2 // file: SC_StringBuffer.cpp
3 // copyright: 2003 stefan kersten <steve@k-hornz.de>
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License as
8 // published by the Free Software Foundation; either version 2 of the
9 // License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful, but
12 // WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
21 #include "SC_StringBuffer.h"
28 # define vsnprintf _vsnprintf
33 SC_StringBuffer::SC_StringBuffer(size_t initialSize
)
34 : mCapacity(0), mPtr(0), mData(0)
39 SC_StringBuffer::SC_StringBuffer(const SC_StringBuffer
& other
)
40 : mCapacity(0), mPtr(0), mData(0)
42 growBy(other
.getSize());
43 append(other
.getData(), other
.getSize());
46 SC_StringBuffer::~SC_StringBuffer()
51 void SC_StringBuffer::append(const char* src
, size_t size
)
54 size_t remaining
= getRemaining();
55 if (size
> remaining
) {
56 growBy(size
- remaining
);
58 memcpy(mPtr
, src
, size
);
63 void SC_StringBuffer::append(char c
)
65 append(&c
, sizeof(c
));
68 void SC_StringBuffer::append(const char* str
)
70 append(str
, strlen(str
));
73 void SC_StringBuffer::vappendf(const char* fmt
, va_list ap
)
76 size_t remaining
= getRemaining();
78 // Calling vsnprintf may invalidate vargs, so keep a copy
85 // NOTE: This only works since glibc 2.0.6!
86 int size
= vsnprintf(mPtr
, remaining
, fmt
, ap
);
89 // size returned excludes trailing \0
91 if ((size_t)size
> remaining
) {
92 growBy(size
- remaining
);
93 vsnprintf(mPtr
, size
, fmt
, ap2
);
95 mPtr
+= size
-1; // omit trailing \0
101 void SC_StringBuffer::appendf(const char* fmt
, ...)
109 void SC_StringBuffer::growBy(size_t request
)
111 size_t oldSize
= getSize();
112 size_t newCapacity
= mCapacity
+ ((request
+ (size_t)kGrowAlign
) & (size_t)~kGrowMask
);
114 // fprintf(stderr, "%s: mCapacity %u, request %u, newCapacity %u\n",
115 // __PRETTY_FUNCTION__, mCapacity, request, newCapacity);
116 assert((newCapacity
>= (mCapacity
+ request
)) && ((newCapacity
& kGrowMask
) == 0));
118 char* newData
= (char*)realloc(mData
, newCapacity
);
121 mCapacity
= newCapacity
;
122 mPtr
= mData
+ oldSize
;
124 throw std::runtime_error("SC_StringBuffer: memory allocation failure");