From bd77aaa19f0c658254f4e2a0c069a1bfcf0dbea2 Mon Sep 17 00:00:00 2001 From: Moritz Bunkus Date: Sat, 23 Dec 2023 09:33:04 +0100 Subject: [PATCH 1/2] EbmlString::ReadFully: use automatic memory management/fewer allocations (cherry picked from commit ae9bb2580c3e0a79496e72f79185256670abeb95) --- src/EbmlString.cpp | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/src/EbmlString.cpp b/src/EbmlString.cpp index e1f4597d..66b33383 100644 --- a/src/EbmlString.cpp +++ b/src/EbmlString.cpp @@ -142,24 +142,20 @@ filepos_t EbmlString::ReadData(IOCallback & input, ScopeMode ReadFully) return GetSize(); if (GetSize() == 0) { - Value = ""; - SetValueIsSet(); + Value.clear(); + } else { - auto Buffer = (GetSize() + 1 < std::numeric_limits::max()) ? new (std::nothrow) char[GetSize() + 1] : nullptr; - if (Buffer == nullptr) { - // unable to store the data, skip it - input.setFilePointer(GetSize(), seek_current); - } else { - input.readFully(Buffer, GetSize()); - if (Buffer[GetSize()-1] != '\0') { - Buffer[GetSize()] = '\0'; - } - Value = Buffer; - delete [] Buffer; - SetValueIsSet(); - } + Value.resize(GetSize()); + std::memset(&Value[0], 0, GetSize()); + input.readFully(&Value[0], GetSize()); + + auto PosNull = Value.find('\0'); + if (PosNull != std::string::npos) + Value.resize(PosNull); } + SetValueIsSet(); + return GetSize(); } From 12c0cebbbda310420a935c021014bffc2b179102 Mon Sep 17 00:00:00 2001 From: Moritz Bunkus Date: Fri, 22 Dec 2023 17:50:15 +0100 Subject: [PATCH 2/2] EbmlUnicodeString: use std::string when reading instead of manual memory management (cherry picked from commit 6b83a0f6f6d1ae7fa14a4f96e70914c1a9686ed4) --- src/EbmlUnicodeString.cpp | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/src/EbmlUnicodeString.cpp b/src/EbmlUnicodeString.cpp index 56f74cec..570af177 100644 --- a/src/EbmlUnicodeString.cpp +++ b/src/EbmlUnicodeString.cpp @@ -308,24 +308,16 @@ filepos_t EbmlUnicodeString::ReadData(IOCallback & input, ScopeMode ReadFully) if (GetSize() == 0) { Value = static_cast(0); - SetValueIsSet(); + } else { - auto Buffer = (GetSize() + 1 < std::numeric_limits::max()) ? new (std::nothrow) char[GetSize()+1] : nullptr; - if (Buffer == nullptr) { - // impossible to read, skip it - input.setFilePointer(GetSize(), seek_current); - } else { - input.readFully(Buffer, GetSize()); - if (Buffer[GetSize()-1] != 0) { - Buffer[GetSize()] = 0; - } - - Value.SetUTF8(Buffer); // implicit conversion to std::string - delete [] Buffer; - SetValueIsSet(); - } + std::string Buffer(static_cast(GetSize()), static_cast(0)); + input.readFully(&Buffer[0], GetSize()); + + Value.SetUTF8(Buffer.c_str()); // Let conversion to std::string cut off at the first 0 } + SetValueIsSet(); + return GetSize(); }