]> git.saurik.com Git - wxWidgets.git/blame - src/common/string.cpp
another compilation fix
[wxWidgets.git] / src / common / string.cpp
CommitLineData
c801d85f
KB
1/////////////////////////////////////////////////////////////////////////////
2// Name: string.cpp
3// Purpose: wxString class
4// Author: Vadim Zeitlin
5// Modified by:
6// Created: 29/01/98
7// RCS-ID: $Id$
8// Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
dd1eaa89 9// Licence: wxWindows license
c801d85f
KB
10/////////////////////////////////////////////////////////////////////////////
11
12#ifdef __GNUG__
30b21f9a 13 #pragma implementation "string.h"
c801d85f
KB
14#endif
15
16/*
17 * About ref counting:
18 * 1) all empty strings use g_strEmpty, nRefs = -1 (set in Init())
19 * 2) AllocBuffer() sets nRefs to 1, Lock() increments it by one
20 * 3) Unlock() decrements nRefs and frees memory if it goes to 0
21 */
22
23// ===========================================================================
24// headers, declarations, constants
25// ===========================================================================
26
27// For compilers that support precompilation, includes "wx.h".
28#include "wx/wxprec.h"
29
30#ifdef __BORLANDC__
30b21f9a 31 #pragma hdrstop
c801d85f
KB
32#endif
33
34#ifndef WX_PRECOMP
3c024cc2
VZ
35 #include "wx/defs.h"
36 #include "wx/string.h"
37 #include "wx/intl.h"
3096bd2f 38 #include "wx/thread.h"
6b769f3d 39#endif
c801d85f
KB
40
41#include <ctype.h>
42#include <string.h>
43#include <stdlib.h>
44
ce3ed50d 45#ifdef __SALFORDC__
30b21f9a 46 #include <clib.h>
ce3ed50d
JS
47#endif
48
ede25f5b 49#if wxUSE_WCSRTOMBS
fb4e5803
VZ
50 #include <wchar.h> // for wcsrtombs(), see comments where it's used
51#endif // GNU
52
c801d85f
KB
53#ifdef WXSTRING_IS_WXOBJECT
54 IMPLEMENT_DYNAMIC_CLASS(wxString, wxObject)
55#endif //WXSTRING_IS_WXOBJECT
56
ec2ba3aa
OK
57#if wxUSE_UNICODE
58#undef wxUSE_EXPERIMENTAL_PRINTF
59#define wxUSE_EXPERIMENTAL_PRINTF 1
60#endif
61
3168a13f
VZ
62// allocating extra space for each string consumes more memory but speeds up
63// the concatenation operations (nLen is the current string's length)
77ca46e7
VZ
64// NB: EXTRA_ALLOC must be >= 0!
65#define EXTRA_ALLOC (19 - nLen % 16)
3168a13f 66
c801d85f
KB
67// ---------------------------------------------------------------------------
68// static class variables definition
69// ---------------------------------------------------------------------------
70
8de2e39c 71#ifdef wxSTD_STRING_COMPATIBILITY
566b84d2 72 const size_t wxString::npos = wxSTRING_MAXLEN;
8de2e39c 73#endif // wxSTD_STRING_COMPATIBILITY
c801d85f 74
3168a13f
VZ
75// ----------------------------------------------------------------------------
76// static data
77// ----------------------------------------------------------------------------
c801d85f 78
3c024cc2
VZ
79// for an empty string, GetStringData() will return this address: this
80// structure has the same layout as wxStringData and it's data() method will
81// return the empty string (dummy pointer)
82static const struct
83{
84 wxStringData data;
2bb67b80 85 wxChar dummy;
223d09f6 86} g_strEmpty = { {-1, 0, 0}, wxT('\0') };
3c024cc2 87
5d33ed2c 88#if defined(__VISAGECPP__) && __IBMCPP__ >= 400
ed582841
VZ
89// must define this static for VA or else you get multiply defined symbols
90// everywhere
5d33ed2c 91const unsigned int wxSTRING_MAXLEN = UINT_MAX - 100;
ed582841 92#endif // Visual Age
5d33ed2c 93
c801d85f 94// empty C style string: points to 'string data' byte of g_strEmpty
e90c1d2a 95extern const wxChar WXDLLEXPORT *wxEmptyString = &g_strEmpty.dummy;
c801d85f 96
89b892a2
VZ
97// ----------------------------------------------------------------------------
98// conditional compilation
99// ----------------------------------------------------------------------------
100
dcf924a3
RR
101#if !defined(__WXSW__) && wxUSE_UNICODE
102 #ifdef wxUSE_EXPERIMENTAL_PRINTF
103 #undef wxUSE_EXPERIMENTAL_PRINTF
104 #endif
105 #define wxUSE_EXPERIMENTAL_PRINTF 1
106#endif
107
89b892a2
VZ
108// we want to find out if the current platform supports vsnprintf()-like
109// function: for Unix this is done with configure, for Windows we test the
110// compiler explicitly.
378b05f7
VZ
111//
112// FIXME currently, this is only for ANSI (!Unicode) strings, so we call this
113// function wxVsnprintfA (A for ANSI), should also find one for Unicode
114// strings in Unicode build
89b892a2 115#ifdef __WXMSW__
012286eb 116 #if defined(__VISUALC__) || (defined(__MINGW32__) && wxUSE_NORLANDER_HEADERS)
378b05f7 117 #define wxVsnprintfA _vsnprintf
89b892a2 118 #endif
03e11df5
GD
119#elif defined(__WXMAC__)
120 #define wxVsnprintfA vsnprintf
89b892a2
VZ
121#else // !Windows
122 #ifdef HAVE_VSNPRINTF
378b05f7 123 #define wxVsnprintfA vsnprintf
89b892a2
VZ
124 #endif
125#endif // Windows/!Windows
126
378b05f7 127#ifndef wxVsnprintfA
89b892a2
VZ
128 // in this case we'll use vsprintf() (which is ANSI and thus should be
129 // always available), but it's unsafe because it doesn't check for buffer
130 // size - so give a warning
378b05f7 131 #define wxVsnprintfA(buf, len, format, arg) vsprintf(buf, format, arg)
566b84d2 132
57493f9f
VZ
133 #if defined(__VISUALC__)
134 #pragma message("Using sprintf() because no snprintf()-like function defined")
03e11df5 135 #elif defined(__GNUG__)
378b05f7 136 #warning "Using sprintf() because no snprintf()-like function defined"
57493f9f 137 #endif //compiler
3f4a0c5b 138#endif // no vsnprintf
89b892a2 139
227b5cd7
VZ
140#ifdef _AIX
141 // AIX has vsnprintf, but there's no prototype in the system headers.
142 extern "C" int vsnprintf(char* str, size_t n, const char* format, va_list ap);
143#endif
144
3168a13f 145// ----------------------------------------------------------------------------
c801d85f 146// global functions
3168a13f 147// ----------------------------------------------------------------------------
c801d85f 148
a533f5c1 149#if defined(wxSTD_STRING_COMPATIBILITY) && wxUSE_STD_IOSTREAM
c801d85f
KB
150
151// MS Visual C++ version 5.0 provides the new STL headers as well as the old
152// iostream ones.
153//
154// ATTN: you can _not_ use both of these in the same program!
a38b83c3 155
dd107c50 156wxSTD istream& operator>>(wxSTD istream& is, wxString& WXUNUSED(str))
c801d85f
KB
157{
158#if 0
159 int w = is.width(0);
160 if ( is.ipfx(0) ) {
3f4a0c5b 161 streambuf *sb = is.rdbuf();
c801d85f
KB
162 str.erase();
163 while ( true ) {
164 int ch = sb->sbumpc ();
165 if ( ch == EOF ) {
3f4a0c5b 166 is.setstate(ios::eofbit);
c801d85f
KB
167 break;
168 }
169 else if ( isspace(ch) ) {
170 sb->sungetc();
171 break;
172 }
dd1eaa89 173
c801d85f
KB
174 str += ch;
175 if ( --w == 1 )
176 break;
177 }
178 }
179
180 is.isfx();
181 if ( str.length() == 0 )
3f4a0c5b 182 is.setstate(ios::failbit);
c801d85f
KB
183#endif
184 return is;
185}
186
dd107c50 187wxSTD ostream& operator<<(wxSTD ostream& os, const wxString& str)
825ba8f0
SB
188{
189 os << str.c_str();
190 return os;
191}
192
c801d85f
KB
193#endif //std::string compatibility
194
378b05f7
VZ
195extern int WXDLLEXPORT wxVsnprintf(wxChar *buf, size_t len,
196 const wxChar *format, va_list argptr)
197{
198#if wxUSE_UNICODE
199 // FIXME should use wvsnprintf() or whatever if it's available
200 wxString s;
201 int iLen = s.PrintfV(format, argptr);
202 if ( iLen != -1 )
203 {
7f017c64
VZ
204 wxStrncpy(buf, s.c_str(), len);
205 buf[len-1] = wxT('\0');
378b05f7
VZ
206 }
207
208 return iLen;
209#else // ANSI
b568d04f
VZ
210 // vsnprintf() will not terminate the string with '\0' if there is not
211 // enough place, but we want the string to always be NUL terminated
212 int rc = wxVsnprintfA(buf, len - 1, format, argptr);
2f02cb89
VZ
213 if ( rc == -1 )
214 {
215 buf[len] = 0;
216 }
b568d04f
VZ
217
218 return rc;
378b05f7
VZ
219#endif // Unicode/ANSI
220}
221
222extern int WXDLLEXPORT wxSnprintf(wxChar *buf, size_t len,
223 const wxChar *format, ...)
224{
225 va_list argptr;
226 va_start(argptr, format);
227
228 int iLen = wxVsnprintf(buf, len, format, argptr);
229
230 va_end(argptr);
231
232 return iLen;
233}
234
3168a13f
VZ
235// ----------------------------------------------------------------------------
236// private classes
237// ----------------------------------------------------------------------------
238
239// this small class is used to gather statistics for performance tuning
240//#define WXSTRING_STATISTICS
241#ifdef WXSTRING_STATISTICS
242 class Averager
243 {
244 public:
245 Averager(const char *sz) { m_sz = sz; m_nTotal = m_nCount = 0; }
2c3b684c 246 ~Averager()
3168a13f
VZ
247 { printf("wxString: average %s = %f\n", m_sz, ((float)m_nTotal)/m_nCount); }
248
c86f1403 249 void Add(size_t n) { m_nTotal += n; m_nCount++; }
3168a13f
VZ
250
251 private:
c86f1403 252 size_t m_nCount, m_nTotal;
3168a13f
VZ
253 const char *m_sz;
254 } g_averageLength("allocation size"),
255 g_averageSummandLength("summand length"),
256 g_averageConcatHit("hit probability in concat"),
257 g_averageInitialLength("initial string length");
258
259 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
260#else
261 #define STATISTICS_ADD(av, val)
262#endif // WXSTRING_STATISTICS
263
c801d85f
KB
264// ===========================================================================
265// wxString class core
266// ===========================================================================
267
268// ---------------------------------------------------------------------------
269// construction
270// ---------------------------------------------------------------------------
271
c801d85f 272// constructs string of <nLength> copies of character <ch>
2bb67b80 273wxString::wxString(wxChar ch, size_t nLength)
c801d85f
KB
274{
275 Init();
276
277 if ( nLength > 0 ) {
278 AllocBuffer(nLength);
f1da2f03 279
2bb67b80
OK
280#if wxUSE_UNICODE
281 // memset only works on char
282 for (size_t n=0; n<nLength; n++) m_pchData[n] = ch;
283#else
c801d85f 284 memset(m_pchData, ch, nLength);
2bb67b80 285#endif
c801d85f
KB
286 }
287}
288
289// takes nLength elements of psz starting at nPos
2bb67b80 290void wxString::InitWith(const wxChar *psz, size_t nPos, size_t nLength)
c801d85f
KB
291{
292 Init();
293
f6bcfd97
BP
294 // if the length is not given, assume the string to be NUL terminated
295 if ( nLength == wxSTRING_MAXLEN ) {
296 wxASSERT_MSG( nPos <= wxStrlen(psz), _T("index out of bounds") );
c801d85f 297
f6bcfd97
BP
298 nLength = wxStrlen(psz + nPos);
299 }
6c68273f 300
3168a13f
VZ
301 STATISTICS_ADD(InitialLength, nLength);
302
c801d85f
KB
303 if ( nLength > 0 ) {
304 // trailing '\0' is written in AllocBuffer()
305 AllocBuffer(nLength);
2bb67b80 306 memcpy(m_pchData, psz + nPos, nLength*sizeof(wxChar));
c801d85f
KB
307 }
308}
dd1eaa89 309
8de2e39c 310#ifdef wxSTD_STRING_COMPATIBILITY
c801d85f 311
c801d85f
KB
312// poor man's iterators are "void *" pointers
313wxString::wxString(const void *pStart, const void *pEnd)
314{
2bb67b80
OK
315 InitWith((const wxChar *)pStart, 0,
316 (const wxChar *)pEnd - (const wxChar *)pStart);
c801d85f
KB
317}
318
319#endif //std::string compatibility
320
2bb67b80
OK
321#if wxUSE_UNICODE
322
323// from multibyte string
cf2f341a 324wxString::wxString(const char *psz, wxMBConv& conv, size_t nLength)
2bb67b80
OK
325{
326 // first get necessary size
435595e0 327 size_t nLen = psz ? conv.MB2WC((wchar_t *) NULL, psz, 0) : 0;
2bb67b80
OK
328
329 // nLength is number of *Unicode* characters here!
eea4f86a 330 if ((nLen != (size_t)-1) && (nLen > nLength))
2bb67b80
OK
331 nLen = nLength;
332
333 // empty?
eea4f86a 334 if ( (nLen != 0) && (nLen != (size_t)-1) ) {
2bb67b80
OK
335 AllocBuffer(nLen);
336 conv.MB2WC(m_pchData, psz, nLen);
337 }
338 else {
339 Init();
340 }
341}
342
e90c1d2a 343#else // ANSI
2bb67b80 344
0f3e3e0c 345#if wxUSE_WCHAR_T
c801d85f 346// from wide string
f6bcfd97 347wxString::wxString(const wchar_t *pwz, wxMBConv& conv)
c801d85f
KB
348{
349 // first get necessary size
f6bcfd97 350 size_t nLen = pwz ? conv.WC2MB((char *) NULL, pwz, 0) : 0;
c801d85f
KB
351
352 // empty?
eea4f86a 353 if ( (nLen != 0) && (nLen != (size_t)-1) ) {
c801d85f 354 AllocBuffer(nLen);
f6bcfd97 355 conv.WC2MB(m_pchData, pwz, nLen);
c801d85f
KB
356 }
357 else {
358 Init();
359 }
360}
e90c1d2a 361#endif // wxUSE_WCHAR_T
c801d85f 362
e90c1d2a 363#endif // Unicode/ANSI
2bb67b80 364
c801d85f
KB
365// ---------------------------------------------------------------------------
366// memory allocation
367// ---------------------------------------------------------------------------
368
369// allocates memory needed to store a C string of length nLen
370void wxString::AllocBuffer(size_t nLen)
371{
13111b2a
VZ
372 // allocating 0 sized buffer doesn't make sense, all empty strings should
373 // reuse g_strEmpty
374 wxASSERT( nLen > 0 );
375
376 // make sure that we don't overflow
377 wxASSERT( nLen < (INT_MAX / sizeof(wxChar)) -
378 (sizeof(wxStringData) + EXTRA_ALLOC + 1) );
c801d85f 379
3168a13f
VZ
380 STATISTICS_ADD(Length, nLen);
381
c801d85f
KB
382 // allocate memory:
383 // 1) one extra character for '\0' termination
384 // 2) sizeof(wxStringData) for housekeeping info
3168a13f 385 wxStringData* pData = (wxStringData*)
2bb67b80 386 malloc(sizeof(wxStringData) + (nLen + EXTRA_ALLOC + 1)*sizeof(wxChar));
c801d85f 387 pData->nRefs = 1;
c801d85f 388 pData->nDataLength = nLen;
3168a13f 389 pData->nAllocLength = nLen + EXTRA_ALLOC;
c801d85f 390 m_pchData = pData->data(); // data starts after wxStringData
223d09f6 391 m_pchData[nLen] = wxT('\0');
c801d85f
KB
392}
393
c801d85f
KB
394// must be called before changing this string
395void wxString::CopyBeforeWrite()
396{
397 wxStringData* pData = GetStringData();
398
399 if ( pData->IsShared() ) {
400 pData->Unlock(); // memory not freed because shared
c86f1403 401 size_t nLen = pData->nDataLength;
3168a13f 402 AllocBuffer(nLen);
2bb67b80 403 memcpy(m_pchData, pData->data(), nLen*sizeof(wxChar));
c801d85f
KB
404 }
405
3bbb630a 406 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
c801d85f
KB
407}
408
409// must be called before replacing contents of this string
410void wxString::AllocBeforeWrite(size_t nLen)
411{
412 wxASSERT( nLen != 0 ); // doesn't make any sense
413
414 // must not share string and must have enough space
3168a13f 415 wxStringData* pData = GetStringData();
fbf0c83d 416 if ( pData->IsShared() || pData->IsEmpty() ) {
c801d85f
KB
417 // can't work with old buffer, get new one
418 pData->Unlock();
419 AllocBuffer(nLen);
420 }
471aebdd 421 else {
fbf0c83d
VZ
422 if ( nLen > pData->nAllocLength ) {
423 // realloc the buffer instead of calling malloc() again, this is more
424 // efficient
425 STATISTICS_ADD(Length, nLen);
426
427 nLen += EXTRA_ALLOC;
428
429 wxStringData *pDataOld = pData;
430 pData = (wxStringData*)
431 realloc(pData, sizeof(wxStringData) + (nLen + 1)*sizeof(wxChar));
432 if ( !pData ) {
433 // out of memory
434 free(pDataOld);
435
436 // FIXME we're going to crash...
437 return;
438 }
439
440 pData->nAllocLength = nLen;
441 m_pchData = pData->data();
442 }
443
444 // now we have enough space, just update the string length
471aebdd
VZ
445 pData->nDataLength = nLen;
446 }
c801d85f 447
f1da2f03 448 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
c801d85f
KB
449}
450
dd1eaa89 451// allocate enough memory for nLen characters
c86f1403 452void wxString::Alloc(size_t nLen)
dd1eaa89
VZ
453{
454 wxStringData *pData = GetStringData();
455 if ( pData->nAllocLength <= nLen ) {
9fbd8b8d
VZ
456 if ( pData->IsEmpty() ) {
457 nLen += EXTRA_ALLOC;
458
459 wxStringData* pData = (wxStringData*)
2bb67b80 460 malloc(sizeof(wxStringData) + (nLen + 1)*sizeof(wxChar));
9fbd8b8d
VZ
461 pData->nRefs = 1;
462 pData->nDataLength = 0;
463 pData->nAllocLength = nLen;
464 m_pchData = pData->data(); // data starts after wxStringData
223d09f6 465 m_pchData[0u] = wxT('\0');
9fbd8b8d 466 }
3168a13f
VZ
467 else if ( pData->IsShared() ) {
468 pData->Unlock(); // memory not freed because shared
c86f1403 469 size_t nOldLen = pData->nDataLength;
3168a13f 470 AllocBuffer(nLen);
2bb67b80 471 memcpy(m_pchData, pData->data(), nOldLen*sizeof(wxChar));
3168a13f 472 }
dd1eaa89 473 else {
3168a13f
VZ
474 nLen += EXTRA_ALLOC;
475
fbf0c83d 476 wxStringData *pDataOld = pData;
dd1eaa89 477 wxStringData *p = (wxStringData *)
2bb67b80 478 realloc(pData, sizeof(wxStringData) + (nLen + 1)*sizeof(wxChar));
3168a13f
VZ
479
480 if ( p == NULL ) {
fbf0c83d
VZ
481 // don't leak memory
482 free(pDataOld);
483
484 // FIXME what to do on memory error?
3168a13f 485 return;
dd1eaa89 486 }
3168a13f
VZ
487
488 // it's not important if the pointer changed or not (the check for this
489 // is not faster than assigning to m_pchData in all cases)
490 p->nAllocLength = nLen;
491 m_pchData = p->data();
dd1eaa89
VZ
492 }
493 }
494 //else: we've already got enough
495}
496
497// shrink to minimal size (releasing extra memory)
498void wxString::Shrink()
499{
500 wxStringData *pData = GetStringData();
3bbb630a 501
fbf0c83d
VZ
502 // this variable is unused in release build, so avoid the compiler warning
503 // by just not declaring it
3bbb630a
VZ
504#ifdef __WXDEBUG__
505 void *p =
506#endif
2bb67b80 507 realloc(pData, sizeof(wxStringData) + (pData->nDataLength + 1)*sizeof(wxChar));
3bbb630a 508
fbf0c83d
VZ
509 // we rely on a reasonable realloc() implementation here - so far I haven't
510 // seen any which wouldn't behave like this
511
3168a13f 512 wxASSERT( p != NULL ); // can't free memory?
dd1eaa89
VZ
513 wxASSERT( p == pData ); // we're decrementing the size - block shouldn't move!
514}
515
c801d85f 516// get the pointer to writable buffer of (at least) nLen bytes
2bb67b80 517wxChar *wxString::GetWriteBuf(size_t nLen)
c801d85f
KB
518{
519 AllocBeforeWrite(nLen);
097c080b
VZ
520
521 wxASSERT( GetStringData()->nRefs == 1 );
522 GetStringData()->Validate(FALSE);
523
c801d85f
KB
524 return m_pchData;
525}
526
097c080b
VZ
527// put string back in a reasonable state after GetWriteBuf
528void wxString::UngetWriteBuf()
529{
2bb67b80 530 GetStringData()->nDataLength = wxStrlen(m_pchData);
097c080b
VZ
531 GetStringData()->Validate(TRUE);
532}
533
8f06a017
RD
534void wxString::UngetWriteBuf(size_t nLen)
535{
536 GetStringData()->nDataLength = nLen;
537 GetStringData()->Validate(TRUE);
538}
539
c801d85f
KB
540// ---------------------------------------------------------------------------
541// data access
542// ---------------------------------------------------------------------------
543
544// all functions are inline in string.h
545
546// ---------------------------------------------------------------------------
547// assignment operators
548// ---------------------------------------------------------------------------
549
dd1eaa89 550// helper function: does real copy
2bb67b80 551void wxString::AssignCopy(size_t nSrcLen, const wxChar *pszSrcData)
c801d85f
KB
552{
553 if ( nSrcLen == 0 ) {
554 Reinit();
555 }
556 else {
557 AllocBeforeWrite(nSrcLen);
2bb67b80 558 memcpy(m_pchData, pszSrcData, nSrcLen*sizeof(wxChar));
c801d85f 559 GetStringData()->nDataLength = nSrcLen;
223d09f6 560 m_pchData[nSrcLen] = wxT('\0');
c801d85f
KB
561 }
562}
563
564// assigns one string to another
565wxString& wxString::operator=(const wxString& stringSrc)
566{
097c080b
VZ
567 wxASSERT( stringSrc.GetStringData()->IsValid() );
568
c801d85f
KB
569 // don't copy string over itself
570 if ( m_pchData != stringSrc.m_pchData ) {
571 if ( stringSrc.GetStringData()->IsEmpty() ) {
572 Reinit();
573 }
574 else {
575 // adjust references
576 GetStringData()->Unlock();
577 m_pchData = stringSrc.m_pchData;
578 GetStringData()->Lock();
579 }
580 }
581
582 return *this;
583}
584
585// assigns a single character
2bb67b80 586wxString& wxString::operator=(wxChar ch)
c801d85f
KB
587{
588 AssignCopy(1, &ch);
589 return *this;
590}
591
592// assigns C string
2bb67b80 593wxString& wxString::operator=(const wxChar *psz)
c801d85f 594{
2bb67b80 595 AssignCopy(wxStrlen(psz), psz);
c801d85f
KB
596 return *this;
597}
598
2bb67b80
OK
599#if !wxUSE_UNICODE
600
c801d85f
KB
601// same as 'signed char' variant
602wxString& wxString::operator=(const unsigned char* psz)
603{
604 *this = (const char *)psz;
605 return *this;
606}
607
0f3e3e0c 608#if wxUSE_WCHAR_T
c801d85f
KB
609wxString& wxString::operator=(const wchar_t *pwz)
610{
611 wxString str(pwz);
612 *this = str;
613 return *this;
614}
0f3e3e0c 615#endif
c801d85f 616
2bb67b80
OK
617#endif
618
c801d85f
KB
619// ---------------------------------------------------------------------------
620// string concatenation
621// ---------------------------------------------------------------------------
622
c801d85f 623// add something to this string
2bb67b80 624void wxString::ConcatSelf(int nSrcLen, const wxChar *pszSrcData)
c801d85f 625{
3168a13f 626 STATISTICS_ADD(SummandLength, nSrcLen);
c801d85f 627
05488905
VZ
628 // concatenating an empty string is a NOP
629 if ( nSrcLen > 0 ) {
630 wxStringData *pData = GetStringData();
631 size_t nLen = pData->nDataLength;
632 size_t nNewLen = nLen + nSrcLen;
c801d85f 633
05488905
VZ
634 // alloc new buffer if current is too small
635 if ( pData->IsShared() ) {
636 STATISTICS_ADD(ConcatHit, 0);
3168a13f 637
05488905
VZ
638 // we have to allocate another buffer
639 wxStringData* pOldData = GetStringData();
640 AllocBuffer(nNewLen);
2bb67b80 641 memcpy(m_pchData, pOldData->data(), nLen*sizeof(wxChar));
05488905
VZ
642 pOldData->Unlock();
643 }
644 else if ( nNewLen > pData->nAllocLength ) {
645 STATISTICS_ADD(ConcatHit, 0);
3168a13f 646
05488905
VZ
647 // we have to grow the buffer
648 Alloc(nNewLen);
649 }
650 else {
651 STATISTICS_ADD(ConcatHit, 1);
3168a13f 652
05488905
VZ
653 // the buffer is already big enough
654 }
3168a13f 655
05488905
VZ
656 // should be enough space
657 wxASSERT( nNewLen <= GetStringData()->nAllocLength );
3168a13f 658
05488905 659 // fast concatenation - all is done in our buffer
2bb67b80 660 memcpy(m_pchData + nLen, pszSrcData, nSrcLen*sizeof(wxChar));
3168a13f 661
223d09f6 662 m_pchData[nNewLen] = wxT('\0'); // put terminating '\0'
05488905
VZ
663 GetStringData()->nDataLength = nNewLen; // and fix the length
664 }
665 //else: the string to append was empty
c801d85f
KB
666}
667
668/*
c801d85f
KB
669 * concatenation functions come in 5 flavours:
670 * string + string
671 * char + string and string + char
672 * C str + string and string + C str
673 */
674
675wxString operator+(const wxString& string1, const wxString& string2)
676{
097c080b
VZ
677 wxASSERT( string1.GetStringData()->IsValid() );
678 wxASSERT( string2.GetStringData()->IsValid() );
679
3168a13f
VZ
680 wxString s = string1;
681 s += string2;
682
c801d85f
KB
683 return s;
684}
685
2bb67b80 686wxString operator+(const wxString& string, wxChar ch)
c801d85f 687{
3168a13f
VZ
688 wxASSERT( string.GetStringData()->IsValid() );
689
690 wxString s = string;
691 s += ch;
097c080b 692
c801d85f
KB
693 return s;
694}
695
2bb67b80 696wxString operator+(wxChar ch, const wxString& string)
c801d85f 697{
097c080b
VZ
698 wxASSERT( string.GetStringData()->IsValid() );
699
3168a13f
VZ
700 wxString s = ch;
701 s += string;
702
c801d85f
KB
703 return s;
704}
705
2bb67b80 706wxString operator+(const wxString& string, const wxChar *psz)
c801d85f 707{
097c080b
VZ
708 wxASSERT( string.GetStringData()->IsValid() );
709
c801d85f 710 wxString s;
2bb67b80 711 s.Alloc(wxStrlen(psz) + string.Len());
3168a13f
VZ
712 s = string;
713 s += psz;
714
c801d85f
KB
715 return s;
716}
717
2bb67b80 718wxString operator+(const wxChar *psz, const wxString& string)
c801d85f 719{
097c080b
VZ
720 wxASSERT( string.GetStringData()->IsValid() );
721
c801d85f 722 wxString s;
2bb67b80 723 s.Alloc(wxStrlen(psz) + string.Len());
3168a13f
VZ
724 s = psz;
725 s += string;
726
c801d85f
KB
727 return s;
728}
729
730// ===========================================================================
731// other common string functions
732// ===========================================================================
733
734// ---------------------------------------------------------------------------
735// simple sub-string extraction
736// ---------------------------------------------------------------------------
737
738// helper function: clone the data attached to this string
739void wxString::AllocCopy(wxString& dest, int nCopyLen, int nCopyIndex) const
740{
3168a13f 741 if ( nCopyLen == 0 ) {
c801d85f
KB
742 dest.Init();
743 }
3168a13f 744 else {
c801d85f 745 dest.AllocBuffer(nCopyLen);
2bb67b80 746 memcpy(dest.m_pchData, m_pchData + nCopyIndex, nCopyLen*sizeof(wxChar));
c801d85f
KB
747 }
748}
749
750// extract string of length nCount starting at nFirst
c801d85f
KB
751wxString wxString::Mid(size_t nFirst, size_t nCount) const
752{
30d9011f
VZ
753 wxStringData *pData = GetStringData();
754 size_t nLen = pData->nDataLength;
755
566b84d2
VZ
756 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
757 if ( nCount == wxSTRING_MAXLEN )
30d9011f
VZ
758 {
759 nCount = nLen - nFirst;
760 }
761
c801d85f 762 // out-of-bounds requests return sensible things
30d9011f
VZ
763 if ( nFirst + nCount > nLen )
764 {
765 nCount = nLen - nFirst;
766 }
c801d85f 767
30d9011f
VZ
768 if ( nFirst > nLen )
769 {
770 // AllocCopy() will return empty string
c801d85f 771 nCount = 0;
30d9011f 772 }
c801d85f
KB
773
774 wxString dest;
775 AllocCopy(dest, nCount, nFirst);
30d9011f 776
c801d85f
KB
777 return dest;
778}
779
f6bcfd97
BP
780// check that the tring starts with prefix and return the rest of the string
781// in the provided pointer if it is not NULL, otherwise return FALSE
782bool wxString::StartsWith(const wxChar *prefix, wxString *rest) const
783{
784 wxASSERT_MSG( prefix, _T("invalid parameter in wxString::StartsWith") );
785
786 // first check if the beginning of the string matches the prefix: note
787 // that we don't have to check that we don't run out of this string as
788 // when we reach the terminating NUL, either prefix string ends too (and
789 // then it's ok) or we break out of the loop because there is no match
790 const wxChar *p = c_str();
791 while ( *prefix )
792 {
793 if ( *prefix++ != *p++ )
794 {
795 // no match
796 return FALSE;
797 }
798 }
799
800 if ( rest )
801 {
802 // put the rest of the string into provided pointer
803 *rest = p;
804 }
805
806 return TRUE;
807}
808
c801d85f
KB
809// extract nCount last (rightmost) characters
810wxString wxString::Right(size_t nCount) const
811{
812 if ( nCount > (size_t)GetStringData()->nDataLength )
813 nCount = GetStringData()->nDataLength;
814
815 wxString dest;
816 AllocCopy(dest, nCount, GetStringData()->nDataLength - nCount);
817 return dest;
818}
819
820// get all characters after the last occurence of ch
821// (returns the whole string if ch not found)
2bb67b80 822wxString wxString::AfterLast(wxChar ch) const
c801d85f
KB
823{
824 wxString str;
825 int iPos = Find(ch, TRUE);
3c67202d 826 if ( iPos == wxNOT_FOUND )
c801d85f
KB
827 str = *this;
828 else
c8cfb486 829 str = c_str() + iPos + 1;
c801d85f
KB
830
831 return str;
832}
833
834// extract nCount first (leftmost) characters
835wxString wxString::Left(size_t nCount) const
836{
837 if ( nCount > (size_t)GetStringData()->nDataLength )
838 nCount = GetStringData()->nDataLength;
839
840 wxString dest;
841 AllocCopy(dest, nCount, 0);
842 return dest;
843}
844
845// get all characters before the first occurence of ch
846// (returns the whole string if ch not found)
2bb67b80 847wxString wxString::BeforeFirst(wxChar ch) const
c801d85f
KB
848{
849 wxString str;
223d09f6 850 for ( const wxChar *pc = m_pchData; *pc != wxT('\0') && *pc != ch; pc++ )
c801d85f
KB
851 str += *pc;
852
853 return str;
854}
855
856/// get all characters before the last occurence of ch
857/// (returns empty string if ch not found)
2bb67b80 858wxString wxString::BeforeLast(wxChar ch) const
c801d85f
KB
859{
860 wxString str;
861 int iPos = Find(ch, TRUE);
3c67202d 862 if ( iPos != wxNOT_FOUND && iPos != 0 )
d1c9bbf6 863 str = wxString(c_str(), iPos);
c801d85f
KB
864
865 return str;
866}
867
868/// get all characters after the first occurence of ch
869/// (returns empty string if ch not found)
2bb67b80 870wxString wxString::AfterFirst(wxChar ch) const
c801d85f
KB
871{
872 wxString str;
873 int iPos = Find(ch);
3c67202d 874 if ( iPos != wxNOT_FOUND )
c801d85f
KB
875 str = c_str() + iPos + 1;
876
877 return str;
878}
879
880// replace first (or all) occurences of some substring with another one
2bb67b80 881size_t wxString::Replace(const wxChar *szOld, const wxChar *szNew, bool bReplaceAll)
c801d85f 882{
c86f1403 883 size_t uiCount = 0; // count of replacements made
c801d85f 884
2bb67b80 885 size_t uiOldLen = wxStrlen(szOld);
c801d85f
KB
886
887 wxString strTemp;
2bb67b80
OK
888 const wxChar *pCurrent = m_pchData;
889 const wxChar *pSubstr;
223d09f6 890 while ( *pCurrent != wxT('\0') ) {
2bb67b80 891 pSubstr = wxStrstr(pCurrent, szOld);
c801d85f
KB
892 if ( pSubstr == NULL ) {
893 // strTemp is unused if no replacements were made, so avoid the copy
894 if ( uiCount == 0 )
895 return 0;
896
897 strTemp += pCurrent; // copy the rest
898 break; // exit the loop
899 }
900 else {
901 // take chars before match
902 strTemp.ConcatSelf(pSubstr - pCurrent, pCurrent);
903 strTemp += szNew;
904 pCurrent = pSubstr + uiOldLen; // restart after match
905
906 uiCount++;
907
908 // stop now?
909 if ( !bReplaceAll ) {
910 strTemp += pCurrent; // copy the rest
911 break; // exit the loop
912 }
913 }
914 }
915
916 // only done if there were replacements, otherwise would have returned above
917 *this = strTemp;
918
919 return uiCount;
920}
921
922bool wxString::IsAscii() const
923{
2bb67b80 924 const wxChar *s = (const wxChar*) *this;
c801d85f
KB
925 while(*s){
926 if(!isascii(*s)) return(FALSE);
927 s++;
928 }
929 return(TRUE);
930}
dd1eaa89 931
c801d85f
KB
932bool wxString::IsWord() const
933{
2bb67b80 934 const wxChar *s = (const wxChar*) *this;
c801d85f 935 while(*s){
2bb67b80 936 if(!wxIsalpha(*s)) return(FALSE);
c801d85f
KB
937 s++;
938 }
939 return(TRUE);
940}
dd1eaa89 941
c801d85f
KB
942bool wxString::IsNumber() const
943{
2bb67b80 944 const wxChar *s = (const wxChar*) *this;
2f74ed28
GT
945 if (wxStrlen(s))
946 if ((s[0] == '-') || (s[0] == '+')) s++;
c801d85f 947 while(*s){
2bb67b80 948 if(!wxIsdigit(*s)) return(FALSE);
c801d85f
KB
949 s++;
950 }
951 return(TRUE);
952}
953
c801d85f
KB
954wxString wxString::Strip(stripType w) const
955{
956 wxString s = *this;
957 if ( w & leading ) s.Trim(FALSE);
958 if ( w & trailing ) s.Trim(TRUE);
959 return s;
960}
961
c801d85f
KB
962// ---------------------------------------------------------------------------
963// case conversion
964// ---------------------------------------------------------------------------
965
966wxString& wxString::MakeUpper()
967{
968 CopyBeforeWrite();
969
2bb67b80
OK
970 for ( wxChar *p = m_pchData; *p; p++ )
971 *p = (wxChar)wxToupper(*p);
c801d85f
KB
972
973 return *this;
974}
975
976wxString& wxString::MakeLower()
977{
978 CopyBeforeWrite();
dd1eaa89 979
2bb67b80
OK
980 for ( wxChar *p = m_pchData; *p; p++ )
981 *p = (wxChar)wxTolower(*p);
c801d85f
KB
982
983 return *this;
984}
985
986// ---------------------------------------------------------------------------
987// trimming and padding
988// ---------------------------------------------------------------------------
989
576c608d
VZ
990// some compilers (VC++ 6.0 not to name them) return TRUE for a call to
991