From b5e35fb31427932c91b4c2b160cdb425d25af37e Mon Sep 17 00:00:00 2001 From: Michael Hansen Date: Fri, 11 Jan 2013 17:59:20 -0800 Subject: [PATCH] Add Truncate() method to plStringStream, which truncates the buffer without reallocating memory --- Sources/Plasma/CoreLib/plString.cpp | 7 +++---- Sources/Plasma/CoreLib/plString.h | 20 ++++++++++++-------- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/Sources/Plasma/CoreLib/plString.cpp b/Sources/Plasma/CoreLib/plString.cpp index cd24209b..5b0be23b 100644 --- a/Sources/Plasma/CoreLib/plString.cpp +++ b/Sources/Plasma/CoreLib/plString.cpp @@ -822,17 +822,16 @@ plString operator+(const char *left, const plString &right) plStringStream &plStringStream::append(const char *data, size_t length) { - size_t bufSize = ICanHasHeap() ? fBufSize : STRING_STACK_SIZE; char *bufp = ICanHasHeap() ? fBuffer : fShort; - if (fLength + length > bufSize) { - size_t bigSize = bufSize; + if (fLength + length > fBufSize) { + size_t bigSize = fBufSize; do { bigSize *= 2; } while (fLength + length > bigSize); char *bigger = new char[bigSize]; - memcpy(bigger, GetRawBuffer(), bufSize); + memcpy(bigger, GetRawBuffer(), fBufSize); if (ICanHasHeap()) delete [] fBuffer; fBuffer = bufp = bigger; diff --git a/Sources/Plasma/CoreLib/plString.h b/Sources/Plasma/CoreLib/plString.h index 4a60b427..199eddbf 100644 --- a/Sources/Plasma/CoreLib/plString.h +++ b/Sources/Plasma/CoreLib/plString.h @@ -594,7 +594,7 @@ public: /** Construct a new empty string stream. The first STRING_STACK_SIZE * bytes are allocated on the stack for further efficiency. */ - plStringStream() : fLength(0) { } + plStringStream() : fBufSize(STRING_STACK_SIZE), fLength(0) { } /** Destructor, frees any allocated heap memory owned by the stream. */ ~plStringStream() { if (ICanHasHeap()) delete [] fBuffer; } @@ -638,19 +638,23 @@ public: size_t GetLength() const { return fLength; } /** Convert the stream's data to a UTF-8 string. */ - plString GetString() { return plString::FromUtf8(GetRawBuffer(), fLength); } + plString GetString() const { return plString::FromUtf8(GetRawBuffer(), fLength); } + + /** Reset the stream's append pointer back to the beginning. + * This does not incur a reallocation of the buffer -- it is left + * with as much space as it had before, making this method more + * useful for re-using string streams in loops. + */ + void Truncate() { fLength = 0; } private: union { - struct { - char *fBuffer; - size_t fBufSize; - }; + char *fBuffer; char fShort[STRING_STACK_SIZE]; }; - size_t fLength; + size_t fBufSize, fLength; - bool ICanHasHeap() const { return fLength > STRING_STACK_SIZE; } + bool ICanHasHeap() const { return fBufSize > STRING_STACK_SIZE; } }; /** \p strlen implementation for UniChar based C-style string buffers. */