]> git.saurik.com Git - wxWidgets.git/blame - src/common/string.cpp
no message
[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__
13#pragma implementation "string.h"
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__
31#pragma hdrstop
32#endif
33
34#ifndef WX_PRECOMP
3c024cc2
VZ
35 #include "wx/defs.h"
36 #include "wx/string.h"
37 #include "wx/intl.h"
c801d85f
KB
38#endif
39
40#include <ctype.h>
41#include <string.h>
42#include <stdlib.h>
43
fb4e5803
VZ
44#ifdef wxUSE_WCSRTOMBS
45 #include <wchar.h> // for wcsrtombs(), see comments where it's used
46#endif // GNU
47
c801d85f
KB
48#ifdef WXSTRING_IS_WXOBJECT
49 IMPLEMENT_DYNAMIC_CLASS(wxString, wxObject)
50#endif //WXSTRING_IS_WXOBJECT
51
3168a13f
VZ
52// allocating extra space for each string consumes more memory but speeds up
53// the concatenation operations (nLen is the current string's length)
77ca46e7
VZ
54// NB: EXTRA_ALLOC must be >= 0!
55#define EXTRA_ALLOC (19 - nLen % 16)
3168a13f 56
c801d85f
KB
57// ---------------------------------------------------------------------------
58// static class variables definition
59// ---------------------------------------------------------------------------
60
61#ifdef STD_STRING_COMPATIBILITY
62 const size_t wxString::npos = STRING_MAXLEN;
63#endif
64
3168a13f
VZ
65// ----------------------------------------------------------------------------
66// static data
67// ----------------------------------------------------------------------------
c801d85f 68
3c024cc2
VZ
69// for an empty string, GetStringData() will return this address: this
70// structure has the same layout as wxStringData and it's data() method will
71// return the empty string (dummy pointer)
72static const struct
73{
74 wxStringData data;
75 char dummy;
76} g_strEmpty = { {-1, 0, 0}, '\0' };
77
c801d85f 78// empty C style string: points to 'string data' byte of g_strEmpty
3c024cc2 79extern const char *g_szNul = &g_strEmpty.dummy;
c801d85f 80
3168a13f 81// ----------------------------------------------------------------------------
c801d85f 82// global functions
3168a13f 83// ----------------------------------------------------------------------------
c801d85f
KB
84
85#ifdef STD_STRING_COMPATIBILITY
86
87// MS Visual C++ version 5.0 provides the new STL headers as well as the old
88// iostream ones.
89//
90// ATTN: you can _not_ use both of these in the same program!
fbc535ff
JS
91#if wxUSE_IOSTREAMH
92#include <iostream.h>
93#define NAMESPACE
94#else
95#include <iostream>
96# ifdef _MSC_VER
97 using namespace std;
98# endif
5f31d862
UU
99// for msvc (bcc50+ also) you don't need these NAMESPACE defines,
100// using namespace std; takes care of that.
fbc535ff
JS
101#define NAMESPACE std::
102#endif
103
104
c801d85f
KB
105NAMESPACE istream& operator>>(NAMESPACE istream& is, wxString& WXUNUSED(str))
106{
107#if 0
108 int w = is.width(0);
109 if ( is.ipfx(0) ) {
110 NAMESPACE streambuf *sb = is.rdbuf();
111 str.erase();
112 while ( true ) {
113 int ch = sb->sbumpc ();
114 if ( ch == EOF ) {
115 is.setstate(NAMESPACE ios::eofbit);
116 break;
117 }
118 else if ( isspace(ch) ) {
119 sb->sungetc();
120 break;
121 }
dd1eaa89 122
c801d85f
KB
123 str += ch;
124 if ( --w == 1 )
125 break;
126 }
127 }
128
129 is.isfx();
130 if ( str.length() == 0 )
131 is.setstate(NAMESPACE ios::failbit);
132#endif
133 return is;
134}
135
136#endif //std::string compatibility
137
3168a13f
VZ
138// ----------------------------------------------------------------------------
139// private classes
140// ----------------------------------------------------------------------------
141
142// this small class is used to gather statistics for performance tuning
143//#define WXSTRING_STATISTICS
144#ifdef WXSTRING_STATISTICS
145 class Averager
146 {
147 public:
148 Averager(const char *sz) { m_sz = sz; m_nTotal = m_nCount = 0; }
2c3b684c 149 ~Averager()
3168a13f
VZ
150 { printf("wxString: average %s = %f\n", m_sz, ((float)m_nTotal)/m_nCount); }
151
c86f1403 152 void Add(size_t n) { m_nTotal += n; m_nCount++; }
3168a13f
VZ
153
154 private:
c86f1403 155 size_t m_nCount, m_nTotal;
3168a13f
VZ
156 const char *m_sz;
157 } g_averageLength("allocation size"),
158 g_averageSummandLength("summand length"),
159 g_averageConcatHit("hit probability in concat"),
160 g_averageInitialLength("initial string length");
161
162 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
163#else
164 #define STATISTICS_ADD(av, val)
165#endif // WXSTRING_STATISTICS
166
c801d85f
KB
167// ===========================================================================
168// wxString class core
169// ===========================================================================
170
171// ---------------------------------------------------------------------------
172// construction
173// ---------------------------------------------------------------------------
174
c801d85f
KB
175// constructs string of <nLength> copies of character <ch>
176wxString::wxString(char ch, size_t nLength)
177{
178 Init();
179
180 if ( nLength > 0 ) {
181 AllocBuffer(nLength);
f1da2f03 182
c801d85f
KB
183 wxASSERT( sizeof(char) == 1 ); // can't use memset if not
184
185 memset(m_pchData, ch, nLength);
186 }
187}
188
189// takes nLength elements of psz starting at nPos
190void wxString::InitWith(const char *psz, size_t nPos, size_t nLength)
191{
192 Init();
193
194 wxASSERT( nPos <= Strlen(psz) );
195
196 if ( nLength == STRING_MAXLEN )
197 nLength = Strlen(psz + nPos);
198
3168a13f
VZ
199 STATISTICS_ADD(InitialLength, nLength);
200
c801d85f
KB
201 if ( nLength > 0 ) {
202 // trailing '\0' is written in AllocBuffer()
203 AllocBuffer(nLength);
204 memcpy(m_pchData, psz + nPos, nLength*sizeof(char));
205 }
206}
dd1eaa89 207
c801d85f
KB
208// the same as previous constructor, but for compilers using unsigned char
209wxString::wxString(const unsigned char* psz, size_t nLength)
210{
211 InitWith((const char *)psz, 0, nLength);
dd1eaa89
VZ
212}
213
c801d85f
KB
214#ifdef STD_STRING_COMPATIBILITY
215
c801d85f
KB
216// poor man's iterators are "void *" pointers
217wxString::wxString(const void *pStart, const void *pEnd)
218{
dd1eaa89 219 InitWith((const char *)pStart, 0,
c801d85f
KB
220 (const char *)pEnd - (const char *)pStart);
221}
222
223#endif //std::string compatibility
224
225// from wide string
226wxString::wxString(const wchar_t *pwz)
227{
228 // first get necessary size
fb4e5803
VZ
229
230 // NB: GNU libc5 wcstombs() is completely broken, don't use it (it doesn't
231 // honor the 3rd parameter, thus it will happily crash here).
232#ifdef wxUSE_WCSRTOMBS
233 // don't know if it's really needed (or if we can pass NULL), but better safe
234 // than quick
235 mbstate_t mbstate;
236 size_t nLen = wcsrtombs((char *) NULL, &pwz, 0, &mbstate);
237#else // !GNU libc
c67daf87 238 size_t nLen = wcstombs((char *) NULL, pwz, 0);
fb4e5803 239#endif // GNU
c801d85f
KB
240
241 // empty?
242 if ( nLen != 0 ) {
243 AllocBuffer(nLen);
244 wcstombs(m_pchData, pwz, nLen);
245 }
246 else {
247 Init();
248 }
249}
250
251// ---------------------------------------------------------------------------
252// memory allocation
253// ---------------------------------------------------------------------------
254
255// allocates memory needed to store a C string of length nLen
256void wxString::AllocBuffer(size_t nLen)
257{
258 wxASSERT( nLen > 0 ); //
259 wxASSERT( nLen <= INT_MAX-1 ); // max size (enough room for 1 extra)
260
3168a13f
VZ
261 STATISTICS_ADD(Length, nLen);
262
c801d85f
KB
263 // allocate memory:
264 // 1) one extra character for '\0' termination
265 // 2) sizeof(wxStringData) for housekeeping info
3168a13f
VZ
266 wxStringData* pData = (wxStringData*)
267 malloc(sizeof(wxStringData) + (nLen + EXTRA_ALLOC + 1)*sizeof(char));
c801d85f 268 pData->nRefs = 1;
c801d85f 269 pData->nDataLength = nLen;
3168a13f 270 pData->nAllocLength = nLen + EXTRA_ALLOC;
c801d85f 271 m_pchData = pData->data(); // data starts after wxStringData
3168a13f 272 m_pchData[nLen] = '\0';
c801d85f
KB
273}
274
c801d85f
KB
275// must be called before changing this string
276void wxString::CopyBeforeWrite()
277{
278 wxStringData* pData = GetStringData();
279
280 if ( pData->IsShared() ) {
281 pData->Unlock(); // memory not freed because shared
c86f1403 282 size_t nLen = pData->nDataLength;
3168a13f
VZ
283 AllocBuffer(nLen);
284 memcpy(m_pchData, pData->data(), nLen*sizeof(char));
c801d85f
KB
285 }
286
3bbb630a 287 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
c801d85f
KB
288}
289
290// must be called before replacing contents of this string
291void wxString::AllocBeforeWrite(size_t nLen)
292{
293 wxASSERT( nLen != 0 ); // doesn't make any sense
294
295 // must not share string and must have enough space
3168a13f 296 wxStringData* pData = GetStringData();
c801d85f
KB
297 if ( pData->IsShared() || (nLen > pData->nAllocLength) ) {
298 // can't work with old buffer, get new one
299 pData->Unlock();
300 AllocBuffer(nLen);
301 }
302
f1da2f03 303 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
c801d85f
KB
304}
305
dd1eaa89 306// allocate enough memory for nLen characters
c86f1403 307void wxString::Alloc(size_t nLen)
dd1eaa89
VZ
308{
309 wxStringData *pData = GetStringData();
310 if ( pData->nAllocLength <= nLen ) {
9fbd8b8d
VZ
311 if ( pData->IsEmpty() ) {
312 nLen += EXTRA_ALLOC;
313
314 wxStringData* pData = (wxStringData*)
315 malloc(sizeof(wxStringData) + (nLen + 1)*sizeof(char));
316 pData->nRefs = 1;
317 pData->nDataLength = 0;
318 pData->nAllocLength = nLen;
319 m_pchData = pData->data(); // data starts after wxStringData
320 m_pchData[0u] = '\0';
321 }
3168a13f
VZ
322 else if ( pData->IsShared() ) {
323 pData->Unlock(); // memory not freed because shared
c86f1403 324 size_t nOldLen = pData->nDataLength;
3168a13f 325 AllocBuffer(nLen);
9fbd8b8d 326 memcpy(m_pchData, pData->data(), nOldLen*sizeof(char));
3168a13f 327 }
dd1eaa89 328 else {
3168a13f
VZ
329 nLen += EXTRA_ALLOC;
330
dd1eaa89
VZ
331 wxStringData *p = (wxStringData *)
332 realloc(pData, sizeof(wxStringData) + (nLen + 1)*sizeof(char));
3168a13f
VZ
333
334 if ( p == NULL ) {
335 // @@@ what to do on memory error?
336 return;
dd1eaa89 337 }
3168a13f
VZ
338
339 // it's not important if the pointer changed or not (the check for this
340 // is not faster than assigning to m_pchData in all cases)
341 p->nAllocLength = nLen;
342 m_pchData = p->data();
dd1eaa89
VZ
343 }
344 }
345 //else: we've already got enough
346}
347
348// shrink to minimal size (releasing extra memory)
349void wxString::Shrink()
350{
351 wxStringData *pData = GetStringData();
3bbb630a
VZ
352
353 // this variable is unused in release build, so avoid the compiler warning by
354 // just not declaring it
355#ifdef __WXDEBUG__
356 void *p =
357#endif
358 realloc(pData, sizeof(wxStringData) + (pData->nDataLength + 1)*sizeof(char));
359
3168a13f 360 wxASSERT( p != NULL ); // can't free memory?
dd1eaa89
VZ
361 wxASSERT( p == pData ); // we're decrementing the size - block shouldn't move!
362}
363
c801d85f 364// get the pointer to writable buffer of (at least) nLen bytes
c86f1403 365char *wxString::GetWriteBuf(size_t nLen)
c801d85f
KB
366{
367 AllocBeforeWrite(nLen);
097c080b
VZ
368
369 wxASSERT( GetStringData()->nRefs == 1 );
370 GetStringData()->Validate(FALSE);
371
c801d85f
KB
372 return m_pchData;
373}
374
097c080b
VZ
375// put string back in a reasonable state after GetWriteBuf
376void wxString::UngetWriteBuf()
377{
378 GetStringData()->nDataLength = strlen(m_pchData);
379 GetStringData()->Validate(TRUE);
380}
381
c801d85f
KB
382// ---------------------------------------------------------------------------
383// data access
384// ---------------------------------------------------------------------------
385
386// all functions are inline in string.h
387
388// ---------------------------------------------------------------------------
389// assignment operators
390// ---------------------------------------------------------------------------
391
dd1eaa89 392// helper function: does real copy
c801d85f
KB
393void wxString::AssignCopy(size_t nSrcLen, const char *pszSrcData)
394{
395 if ( nSrcLen == 0 ) {
396 Reinit();
397 }
398 else {
399 AllocBeforeWrite(nSrcLen);
400 memcpy(m_pchData, pszSrcData, nSrcLen*sizeof(char));
401 GetStringData()->nDataLength = nSrcLen;
402 m_pchData[nSrcLen] = '\0';
403 }
404}
405
406// assigns one string to another
407wxString& wxString::operator=(const wxString& stringSrc)
408{
097c080b
VZ
409 wxASSERT( stringSrc.GetStringData()->IsValid() );
410
c801d85f
KB
411 // don't copy string over itself
412 if ( m_pchData != stringSrc.m_pchData ) {
413 if ( stringSrc.GetStringData()->IsEmpty() ) {
414 Reinit();
415 }
416 else {
417 // adjust references
418 GetStringData()->Unlock();
419 m_pchData = stringSrc.m_pchData;
420 GetStringData()->Lock();
421 }
422 }
423
424 return *this;
425}
426
427// assigns a single character
428wxString& wxString::operator=(char ch)
429{
430 AssignCopy(1, &ch);
431 return *this;
432}
433
434// assigns C string
435wxString& wxString::operator=(const char *psz)
436{
437 AssignCopy(Strlen(psz), psz);
438 return *this;
439}
440
441// same as 'signed char' variant
442wxString& wxString::operator=(const unsigned char* psz)
443{
444 *this = (const char *)psz;
445 return *this;
446}
447
448wxString& wxString::operator=(const wchar_t *pwz)
449{
450 wxString str(pwz);
451 *this = str;
452 return *this;
453}
454
455// ---------------------------------------------------------------------------
456// string concatenation
457// ---------------------------------------------------------------------------
458
c801d85f
KB
459// add something to this string
460void wxString::ConcatSelf(int nSrcLen, const char *pszSrcData)
461{
3168a13f 462 STATISTICS_ADD(SummandLength, nSrcLen);
c801d85f 463
05488905
VZ
464 // concatenating an empty string is a NOP
465 if ( nSrcLen > 0 ) {
466 wxStringData *pData = GetStringData();
467 size_t nLen = pData->nDataLength;
468 size_t nNewLen = nLen + nSrcLen;
c801d85f 469
05488905
VZ
470 // alloc new buffer if current is too small
471 if ( pData->IsShared() ) {
472 STATISTICS_ADD(ConcatHit, 0);
3168a13f 473
05488905
VZ
474 // we have to allocate another buffer
475 wxStringData* pOldData = GetStringData();
476 AllocBuffer(nNewLen);
477 memcpy(m_pchData, pOldData->data(), nLen*sizeof(char));
478 pOldData->Unlock();
479 }
480 else if ( nNewLen > pData->nAllocLength ) {
481 STATISTICS_ADD(ConcatHit, 0);
3168a13f 482
05488905
VZ
483 // we have to grow the buffer
484 Alloc(nNewLen);
485 }
486 else {
487 STATISTICS_ADD(ConcatHit, 1);
3168a13f 488
05488905
VZ
489 // the buffer is already big enough
490 }
3168a13f 491
05488905
VZ
492 // should be enough space
493 wxASSERT( nNewLen <= GetStringData()->nAllocLength );
3168a13f 494
05488905
VZ
495 // fast concatenation - all is done in our buffer
496 memcpy(m_pchData + nLen, pszSrcData, nSrcLen*sizeof(char));
3168a13f 497
05488905
VZ
498 m_pchData[nNewLen] = '\0'; // put terminating '\0'
499 GetStringData()->nDataLength = nNewLen; // and fix the length
500 }
501 //else: the string to append was empty
c801d85f
KB
502}
503
504/*
c801d85f
KB
505 * concatenation functions come in 5 flavours:
506 * string + string
507 * char + string and string + char
508 * C str + string and string + C str
509 */
510
511wxString operator+(const wxString& string1, const wxString& string2)
512{
097c080b
VZ
513 wxASSERT( string1.GetStringData()->IsValid() );
514 wxASSERT( string2.GetStringData()->IsValid() );
515
3168a13f
VZ
516 wxString s = string1;
517 s += string2;
518
c801d85f
KB
519 return s;
520}
521
3168a13f 522wxString operator+(const wxString& string, char ch)
c801d85f 523{
3168a13f
VZ
524 wxASSERT( string.GetStringData()->IsValid() );
525
526 wxString s = string;
527 s += ch;
097c080b 528
c801d85f
KB
529 return s;
530}
531
532wxString operator+(char ch, const wxString& string)
533{
097c080b
VZ
534 wxASSERT( string.GetStringData()->IsValid() );
535
3168a13f
VZ
536 wxString s = ch;
537 s += string;
538
c801d85f
KB
539 return s;
540}
541
542wxString operator+(const wxString& string, const char *psz)
543{
097c080b
VZ
544 wxASSERT( string.GetStringData()->IsValid() );
545
c801d85f 546 wxString s;
3168a13f
VZ
547 s.Alloc(Strlen(psz) + string.Len());
548 s = string;
549 s += psz;
550
c801d85f
KB
551 return s;
552}
553
554wxString operator+(const char *psz, const wxString& string)
555{
097c080b
VZ
556 wxASSERT( string.GetStringData()->IsValid() );
557
c801d85f 558 wxString s;
3168a13f
VZ
559 s.Alloc(Strlen(psz) + string.Len());
560 s = psz;
561 s += string;
562
c801d85f
KB
563 return s;
564}
565
566// ===========================================================================
567// other common string functions
568// ===========================================================================
569
570// ---------------------------------------------------------------------------
571// simple sub-string extraction
572// ---------------------------------------------------------------------------
573
574// helper function: clone the data attached to this string
575void wxString::AllocCopy(wxString& dest, int nCopyLen, int nCopyIndex) const
576{
3168a13f 577 if ( nCopyLen == 0 ) {
c801d85f
KB
578 dest.Init();
579 }
3168a13f 580 else {
c801d85f
KB
581 dest.AllocBuffer(nCopyLen);
582 memcpy(dest.m_pchData, m_pchData + nCopyIndex, nCopyLen*sizeof(char));
583 }
584}
585
586// extract string of length nCount starting at nFirst
c801d85f
KB
587wxString wxString::Mid(size_t nFirst, size_t nCount) const
588{
30d9011f
VZ
589 wxStringData *pData = GetStringData();
590 size_t nLen = pData->nDataLength;
591
592 // default value of nCount is STRING_MAXLEN and means "till the end"
593 if ( nCount == STRING_MAXLEN )
594 {
595 nCount = nLen - nFirst;
596 }
597
c801d85f 598 // out-of-bounds requests return sensible things
30d9011f
VZ
599 if ( nFirst + nCount > nLen )
600 {
601 nCount = nLen - nFirst;
602 }
c801d85f 603
30d9011f
VZ
604 if ( nFirst > nLen )
605 {
606 // AllocCopy() will return empty string
c801d85f 607 nCount = 0;
30d9011f 608 }
c801d85f
KB
609
610 wxString dest;
611 AllocCopy(dest, nCount, nFirst);
30d9011f 612
c801d85f
KB
613 return dest;
614}
615
616// extract nCount last (rightmost) characters
617wxString wxString::Right(size_t nCount) const
618{
619 if ( nCount > (size_t)GetStringData()->nDataLength )
620 nCount = GetStringData()->nDataLength;
621
622 wxString dest;
623 AllocCopy(dest, nCount, GetStringData()->nDataLength - nCount);
624 return dest;
625}
626
627// get all characters after the last occurence of ch
628// (returns the whole string if ch not found)
629wxString wxString::Right(char ch) const
630{
631 wxString str;
632 int iPos = Find(ch, TRUE);
633 if ( iPos == NOT_FOUND )
634 str = *this;
635 else
c8cfb486 636 str = c_str() + iPos + 1;
c801d85f
KB
637
638 return str;
639}
640
641// extract nCount first (leftmost) characters
642wxString wxString::Left(size_t nCount) const
643{
644 if ( nCount > (size_t)GetStringData()->nDataLength )
645 nCount = GetStringData()->nDataLength;
646
647 wxString dest;
648 AllocCopy(dest, nCount, 0);
649 return dest;
650}
651
652// get all characters before the first occurence of ch
653// (returns the whole string if ch not found)
654wxString wxString::Left(char ch) const
655{
656 wxString str;
657 for ( const char *pc = m_pchData; *pc != '\0' && *pc != ch; pc++ )
658 str += *pc;
659
660 return str;
661}
662
663/// get all characters before the last occurence of ch
664/// (returns empty string if ch not found)
665wxString wxString::Before(char ch) const
666{
667 wxString str;
668 int iPos = Find(ch, TRUE);
669 if ( iPos != NOT_FOUND && iPos != 0 )
d1c9bbf6 670 str = wxString(c_str(), iPos);
c801d85f
KB
671
672 return str;
673}
674
675/// get all characters after the first occurence of ch
676/// (returns empty string if ch not found)
677wxString wxString::After(char ch) const
678{
679 wxString str;
680 int iPos = Find(ch);
681 if ( iPos != NOT_FOUND )
682 str = c_str() + iPos + 1;
683
684 return str;
685}
686
687// replace first (or all) occurences of some substring with another one
c86f1403 688size_t wxString::Replace(const char *szOld, const char *szNew, bool bReplaceAll)
c801d85f 689{
c86f1403 690 size_t uiCount = 0; // count of replacements made
c801d85f 691
c86f1403 692 size_t uiOldLen = Strlen(szOld);
c801d85f
KB
693
694 wxString strTemp;
695 const char *pCurrent = m_pchData;
dd1eaa89 696 const char *pSubstr;
c801d85f
KB
697 while ( *pCurrent != '\0' ) {
698 pSubstr = strstr(pCurrent, szOld);
699 if ( pSubstr == NULL ) {
700 // strTemp is unused if no replacements were made, so avoid the copy
701 if ( uiCount == 0 )
702 return 0;
703
704 strTemp += pCurrent; // copy the rest
705 break; // exit the loop
706 }
707 else {
708 // take chars before match
709 strTemp.ConcatSelf(pSubstr - pCurrent, pCurrent);
710 strTemp += szNew;
711 pCurrent = pSubstr + uiOldLen; // restart after match
712
713 uiCount++;
714
715 // stop now?
716 if ( !bReplaceAll ) {
717 strTemp += pCurrent; // copy the rest
718 break; // exit the loop
719 }
720 }
721 }
722
723 // only done if there were replacements, otherwise would have returned above
724 *this = strTemp;
725
726 return uiCount;
727}
728
729bool wxString::IsAscii() const
730{
731 const char *s = (const char*) *this;
732 while(*s){
733 if(!isascii(*s)) return(FALSE);
734 s++;
735 }
736 return(TRUE);
737}
dd1eaa89 738
c801d85f
KB
739bool wxString::IsWord() const
740{
741 const char *s = (const char*) *this;
742 while(*s){
743 if(!isalpha(*s)) return(FALSE);
744 s++;
745 }
746 return(TRUE);
747}
dd1eaa89 748
c801d85f
KB
749bool wxString::IsNumber() const
750{
751 const char *s = (const char*) *this;
752 while(*s){
753 if(!isdigit(*s)) return(FALSE);
754 s++;
755 }
756 return(TRUE);
757}
758
c801d85f
KB
759wxString wxString::Strip(stripType w) const
760{
761 wxString s = *this;
762 if ( w & leading ) s.Trim(FALSE);
763 if ( w & trailing ) s.Trim(TRUE);
764 return s;
765}
766
c801d85f
KB
767// ---------------------------------------------------------------------------
768// case conversion
769// ---------------------------------------------------------------------------
770
771wxString& wxString::MakeUpper()
772{
773 CopyBeforeWrite();
774
775 for ( char *p = m_pchData; *p; p++ )
776 *p = (char)toupper(*p);
777
778 return *this;
779}
780
781wxString& wxString::MakeLower()
782{
783 CopyBeforeWrite();
dd1eaa89 784
c801d85f
KB
785 for ( char *p = m_pchData; *p; p++ )
786 *p = (char)tolower(*p);
787
788 return *this;
789}
790
791// ---------------------------------------------------------------------------
792// trimming and padding
793// ---------------------------------------------------------------------------
794
795// trims spaces (in the sense of isspace) from left or right side
796wxString& wxString::Trim(bool bFromRight)
797{
2c3b684c
VZ
798 // first check if we're going to modify the string at all
799 if ( !IsEmpty() &&
800 (
801 (bFromRight && isspace(GetChar(Len() - 1))) ||
802 (!bFromRight && isspace(GetChar(0u)))
803 )
804 )
c801d85f 805 {
2c3b684c
VZ
806 // ok, there is at least one space to trim
807 CopyBeforeWrite();
808
809 if ( bFromRight )
810 {
811 // find last non-space character
812 char *psz = m_pchData + GetStringData()->nDataLength - 1;
813 while ( isspace(*psz) && (psz >= m_pchData) )
814 psz--;
815
816 // truncate at trailing space start
817 *++psz = '\0';
818 GetStringData()->nDataLength = psz - m_pchData;
819 }
820 else
821 {
822 // find first non-space character
823 const char *psz = m_pchData;
824 while ( isspace(*psz) )
825 psz++;
826
827 // fix up data and length
828 int nDataLength = GetStringData()->nDataLength - (psz - m_pchData);
829 memmove(m_pchData, psz, (nDataLength + 1)*sizeof(char));
830 GetStringData()->nDataLength = nDataLength;
831 }
c801d85f
KB
832 }
833
834 return *this;
835}
836
837// adds nCount characters chPad to the string from either side
838wxString& wxString::Pad(size_t nCount, char chPad, bool bFromRight)
839{
840 wxString s(chPad, nCount);
841
842 if ( bFromRight )
843 *this += s;
844 else
845 {
846 s += *this;
847 *this = s;
848 }
849
850 return *this;
851}
852
853// truncate the string
854wxString& wxString::Truncate(size_t uiLen)
855{
856 *(m_pchData + uiLen) = '\0';
857 GetStringData()->nDataLength = uiLen;
858
859 return *this;
860}
861
862// ---------------------------------------------------------------------------
863// finding (return NOT_FOUND if not found and index otherwise)
864// ---------------------------------------------------------------------------
865
866// find a character
867int wxString::Find(char ch, bool bFromEnd) const
868{
869 const char *psz = bFromEnd ? strrchr(m_pchData, ch) : strchr(m_pchData, ch);
870
871 return (psz == NULL) ? NOT_FOUND : psz - m_pchData;
872}
873
874// find a sub-string (like strstr)
875int wxString::Find(const char *pszSub) const
876{
877 const char *psz = strstr(m_pchData, pszSub);
878
879 return (psz == NULL) ? NOT_FOUND : psz - m_pchData;
880}
881
882// ---------------------------------------------------------------------------
9efd3367 883// formatted output
c801d85f
KB
884// ---------------------------------------------------------------------------
885int wxString::Printf(const char *pszFormat, ...)
886{
887 va_list argptr;
888 va_start(argptr, pszFormat);
889
890 int iLen = PrintfV(pszFormat, argptr);
891
892 va_end(argptr);
893
894 return iLen;
895}
896
897int wxString::PrintfV(const char* pszFormat, va_list argptr)
898{
9efd3367 899 static char s_szScratch[1024];
c801d85f
KB
900
901 int iLen = vsprintf(s_szScratch, pszFormat, argptr);
902 AllocBeforeWrite(iLen);
903 strcpy(m_pchData, s_szScratch);
904
905 return iLen;
906}
907
097c080b
VZ
908// ----------------------------------------------------------------------------
909// misc other operations
910// ----------------------------------------------------------------------------
911bool wxString::Matches(const char *pszMask) const
912{
913 // check char by char
914 const char *pszTxt;
915 for ( pszTxt = c_str(); *pszMask != '\0'; pszMask++, pszTxt++ ) {
916 switch ( *pszMask ) {
917 case '?':
918 if ( *pszTxt == '\0' )
919 return FALSE;
920
921 pszTxt++;
922 pszMask++;
923 break;
924
925 case '*':
926 {
927 // ignore special chars immediately following this one
928 while ( *pszMask == '*' || *pszMask == '?' )
929 pszMask++;
930
931 // if there is nothing more, match
932 if ( *pszMask == '\0' )
933 return TRUE;
934
935 // are there any other metacharacters in the mask?
c86f1403 936 size_t uiLenMask;
097c080b
VZ
937 const char *pEndMask = strpbrk(pszMask, "*?");
938
939 if ( pEndMask != NULL ) {
940 // we have to match the string between two metachars
941 uiLenMask = pEndMask - pszMask;
942 }
943 else {
944 // we have to match the remainder of the string
945 uiLenMask = strlen(pszMask);
946 }
947
948 wxString strToMatch(pszMask, uiLenMask);
949 const char* pMatch = strstr(pszTxt, strToMatch);
950 if ( pMatch == NULL )
951 return FALSE;
952
953 // -1 to compensate "++" in the loop
954 pszTxt = pMatch + uiLenMask - 1;
955 pszMask += uiLenMask - 1;
956 }
957 break;
958
959 default:
960 if ( *pszMask != *pszTxt )
961 return FALSE;
962 break;
963 }
964 }
965
966 // match only if nothing left
967 return *pszTxt == '\0';
968}
969
c801d85f
KB
970// ---------------------------------------------------------------------------
971// standard C++ library string functions
972// ---------------------------------------------------------------------------
973#ifdef STD_STRING_COMPATIBILITY
974
975wxString& wxString::insert(size_t nPos, const wxString& str)
976{
097c080b 977 wxASSERT( str.GetStringData()->IsValid() );
c801d85f
KB
978 wxASSERT( nPos <= Len() );
979
cb6780ff
VZ
980 if ( !str.IsEmpty() ) {
981 wxString strTmp;
982 char *pc = strTmp.GetWriteBuf(Len() + str.Len());
983 strncpy(pc, c_str(), nPos);
984 strcpy(pc + nPos, str);
985 strcpy(pc + nPos + str.Len(), c_str() + nPos);
986 strTmp.UngetWriteBuf();
987 *this = strTmp;
988 }
dd1eaa89
VZ
989
990 return *this;
c801d85f
KB
991}
992
993size_t wxString::find(const wxString& str, size_t nStart) const
994{
097c080b 995 wxASSERT( str.GetStringData()->IsValid() );
c801d85f
KB
996 wxASSERT( nStart <= Len() );
997
998 const char *p = strstr(c_str() + nStart, str);
dd1eaa89 999
c801d85f
KB
1000 return p == NULL ? npos : p - c_str();
1001}
1002
f0b3249b
JS
1003// VC++ 1.5 can't cope with the default argument in the header.
1004#if ! (defined(_MSC_VER) && !defined(__WIN32__))
c801d85f
KB
1005size_t wxString::find(const char* sz, size_t nStart, size_t n) const
1006{
1007 return find(wxString(sz, n == npos ? 0 : n), nStart);
1008}
f0b3249b 1009#endif
dd1eaa89 1010
c801d85f
KB
1011size_t wxString::find(char ch, size_t nStart) const
1012{
1013 wxASSERT( nStart <= Len() );
1014
1015 const char *p = strchr(c_str() + nStart, ch);
dd1eaa89 1016
c801d85f
KB
1017 return p == NULL ? npos : p - c_str();
1018}
1019
1020size_t wxString::rfind(const wxString& str, size_t nStart) const
1021{
097c080b 1022 wxASSERT( str.GetStringData()->IsValid() );
c801d85f
KB
1023 wxASSERT( nStart <= Len() );
1024
1025 // # could be quicker than that
1026 const char *p = c_str() + (nStart == npos ? Len() : nStart);
1027 while ( p >= c_str() + str.Len() ) {
1028 if ( strncmp(p - str.Len(), str, str.Len()) == 0 )
1029 return p - str.Len() - c_str();
1030 p--;
1031 }
dd1eaa89 1032
c801d85f
KB
1033 return npos;
1034}
dd1eaa89 1035
f0b3249b
JS
1036// VC++ 1.5 can't cope with the default argument in the header.
1037#if ! (defined(_MSC_VER) && !defined(__WIN32__))
c801d85f
KB
1038size_t wxString::rfind(const char* sz, size_t nStart, size_t n) const
1039{
1040 return rfind(wxString(sz, n == npos ? 0 : n), nStart);
1041}
1042
1043size_t wxString::rfind(char ch, size_t nStart) const
1044{
1045 wxASSERT( nStart <= Len() );
1046
1047 const char *p = strrchr(c_str() + nStart, ch);
dd1eaa89 1048
c801d85f
KB
1049 return p == NULL ? npos : p - c_str();
1050}
f0b3249b 1051#endif
c801d85f
KB
1052
1053wxString wxString::substr(size_t nStart, size_t nLen) const
1054{
1055 // npos means 'take all'
1056 if ( nLen == npos )
1057 nLen = 0;
1058
1059 wxASSERT( nStart + nLen <= Len() );
1060
1061 return wxString(c_str() + nStart, nLen == npos ? 0 : nLen);
1062}
1063
1064wxString& wxString::erase(size_t nStart, size_t nLen)
1065{
1066 wxString strTmp(c_str(), nStart);
1067 if ( nLen != npos ) {
1068 wxASSERT( nStart + nLen <= Len() );
1069
1070 strTmp.append(c_str() + nStart + nLen);
1071 }
1072
1073 *this = strTmp;
1074 return *this;
1075}
1076
1077wxString& wxString::replace(size_t nStart, size_t nLen, const char *sz)
1078{
1079 wxASSERT( nStart + nLen <= Strlen(sz) );
1080
1081 wxString strTmp;
1082 if ( nStart != 0 )
1083 strTmp.append(c_str(), nStart);
1084 strTmp += sz;
1085 strTmp.append(c_str() + nStart + nLen);
dd1eaa89 1086
c801d85f
KB
1087 *this = strTmp;
1088 return *this;
1089}
1090
1091wxString& wxString::replace(size_t nStart, size_t nLen, size_t nCount, char ch)
1092{
1093 return replace(nStart, nLen, wxString(ch, nCount));
1094}
1095
dd1eaa89 1096wxString& wxString::replace(size_t nStart, size_t nLen,
097c080b 1097 const wxString& str, size_t nStart2, size_t nLen2)
c801d85f
KB
1098{
1099 return replace(nStart, nLen, str.substr(nStart2, nLen2));
1100}
1101
dd1eaa89 1102wxString& wxString::replace(size_t nStart, size_t nLen,
c801d85f
KB
1103 const char* sz, size_t nCount)
1104{
1105 return replace(nStart, nLen, wxString(sz, nCount));
1106}
1107
1108#endif //std::string compatibility
1109
1110// ============================================================================
1111// ArrayString
1112// ============================================================================
1113
1114// size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1115#define ARRAY_MAXSIZE_INCREMENT 4096
1116#ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1117 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1118#endif
1119
1120#define STRING(p) ((wxString *)(&(p)))
1121
1122// ctor
1123wxArrayString::wxArrayString()
1124{
1125 m_nSize =
1126 m_nCount = 0;
c67daf87 1127 m_pItems = (char **) NULL;
c801d85f
KB
1128}
1129
1130// copy ctor
1131wxArrayString::wxArrayString(const wxArrayString& src)
1132{
3bbb630a
VZ
1133 m_nSize =
1134 m_nCount = 0;
c67daf87 1135 m_pItems = (char **) NULL;
c801d85f 1136
4d14b524 1137 *this = src;
c801d85f
KB
1138}
1139
4d14b524 1140// assignment operator
c801d85f
KB
1141wxArrayString& wxArrayString::operator=(const wxArrayString& src)
1142{
d93f63db
VZ
1143 if ( m_nSize > 0 )
1144 Clear();
c801d85f 1145
4d14b524
VZ
1146 if ( src.m_nCount > ARRAY_DEFAULT_INITIAL_SIZE )
1147 Alloc(src.m_nCount);
c801d85f 1148
4d14b524
VZ
1149 // we can't just copy the pointers here because otherwise we would share
1150 // the strings with another array
c86f1403 1151 for ( size_t n = 0; n < src.m_nCount; n++ )
4d14b524 1152 Add(src[n]);
c801d85f 1153
3bbb630a
VZ
1154 if ( m_nCount != 0 )
1155 memcpy(m_pItems, src.m_pItems, m_nCount*sizeof(char *));
1156
c801d85f
KB
1157 return *this;
1158}
1159
1160// grow the array
1161void wxArrayString::Grow()
1162{
1163 // only do it if no more place
1164 if( m_nCount == m_nSize ) {
1165 if( m_nSize == 0 ) {
1166 // was empty, alloc some memory
1167 m_nSize = ARRAY_DEFAULT_INITIAL_SIZE;
1168 m_pItems = new char *[m_nSize];
1169 }
1170 else {
3bbb630a
VZ
1171 // otherwise when it's called for the first time, nIncrement would be 0
1172 // and the array would never be expanded
1173 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE != 0 );
1174
c801d85f 1175 // add 50% but not too much
3bbb630a 1176 size_t nIncrement = m_nSize < ARRAY_DEFAULT_INITIAL_SIZE
4d14b524 1177 ? ARRAY_DEFAULT_INITIAL_SIZE : m_nSize >> 1;
c801d85f
KB
1178 if ( nIncrement > ARRAY_MAXSIZE_INCREMENT )
1179 nIncrement = ARRAY_MAXSIZE_INCREMENT;
1180 m_nSize += nIncrement;
1181 char **pNew = new char *[m_nSize];
1182
1183 // copy data to new location
1184 memcpy(pNew, m_pItems, m_nCount*sizeof(char *));
1185
1186 // delete old memory (but do not release the strings!)
a3622daa 1187 wxDELETEA(m_pItems);
c801d85f
KB
1188
1189 m_pItems = pNew;
1190 }
1191 }
1192}
1193
1194void wxArrayString::Free()
1195{
1196 for ( size_t n = 0; n < m_nCount; n++ ) {
1197 STRING(m_pItems[n])->GetStringData()->Unlock();
1198 }
1199}
1200
1201// deletes all the strings from the list
1202void wxArrayString::Empty()
1203{
1204 Free();
1205
1206 m_nCount = 0;
1207}
1208
1209// as Empty, but also frees memory
1210void wxArrayString::Clear()
1211{
1212 Free();
1213
dd1eaa89 1214 m_nSize =
c801d85f
KB
1215 m_nCount = 0;
1216
a3622daa 1217 wxDELETEA(m_pItems);
c801d85f
KB
1218}
1219
1220// dtor
1221wxArrayString::~wxArrayString()
1222{
1223 Free();
1224
a3622daa 1225 wxDELETEA(m_pItems);
c801d85f
KB
1226}
1227
1228// pre-allocates memory (frees the previous data!)
1229void wxArrayString::Alloc(size_t nSize)
1230{
1231 wxASSERT( nSize > 0 );
1232
1233 // only if old buffer was not big enough
1234 if ( nSize > m_nSize ) {
1235 Free();
a3622daa 1236 wxDELETEA(m_pItems);
c801d85f
KB
1237 m_pItems = new char *[nSize];
1238 m_nSize = nSize;
1239 }
1240
1241 m_nCount = 0;
1242}
1243
1244// searches the array for an item (forward or backwards)
c801d85f
KB
1245int wxArrayString::Index(const char *sz, bool bCase, bool bFromEnd) const
1246{
1247 if ( bFromEnd ) {
1248 if ( m_nCount > 0 ) {
c86f1403 1249 size_t ui = m_nCount;
c801d85f
KB
1250 do {
1251 if ( STRING(m_pItems[--ui])->IsSameAs(sz, bCase) )
1252 return ui;
1253 }
1254 while ( ui != 0 );
1255 }
1256 }
1257 else {
c86f1403 1258 for( size_t ui = 0; ui < m_nCount; ui++ ) {
c801d85f
KB
1259 if( STRING(m_pItems[ui])->IsSameAs(sz, bCase) )
1260 return ui;
1261 }
1262 }
1263
1264 return NOT_FOUND;
1265}
1266
1267// add item at the end
097c080b 1268void wxArrayString::Add(const wxString& str)
c801d85f 1269{
097c080b
VZ
1270 wxASSERT( str.GetStringData()->IsValid() );
1271
c801d85f
KB
1272 Grow();
1273
1274 // the string data must not be deleted!
097c080b
VZ
1275 str.GetStringData()->Lock();
1276 m_pItems[m_nCount++] = (char *)str.c_str();
c801d85f
KB
1277}
1278
1279// add item at the given position
097c080b 1280void wxArrayString::Insert(const wxString& str, size_t nIndex)
c801d85f 1281{
097c080b
VZ
1282 wxASSERT( str.GetStringData()->IsValid() );
1283
1a5a8367 1284 wxCHECK_RET( nIndex <= m_nCount, ("bad index in wxArrayString::Insert") );
c801d85f
KB
1285
1286 Grow();
1287
dd1eaa89 1288 memmove(&m_pItems[nIndex + 1], &m_pItems[nIndex],
c801d85f
KB
1289 (m_nCount - nIndex)*sizeof(char *));
1290
097c080b
VZ
1291 str.GetStringData()->Lock();
1292 m_pItems[nIndex] = (char *)str.c_str();
c801d85f
KB
1293
1294 m_nCount++;
1295}
1296
1297// removes item from array (by index)
1298void wxArrayString::Remove(size_t nIndex)
1299{
1a5a8367 1300 wxCHECK_RET( nIndex <= m_nCount, _("bad index in wxArrayString::Remove") );
c801d85f
KB
1301
1302 // release our lock
1303 Item(nIndex).GetStringData()->Unlock();
1304
dd1eaa89 1305 memmove(&m_pItems[nIndex], &m_pItems[nIndex + 1],
c801d85f
KB
1306 (m_nCount - nIndex - 1)*sizeof(char *));
1307 m_nCount--;
1308}
1309
1310// removes item from array (by value)
1311void wxArrayString::Remove(const char *sz)
1312{
1313 int iIndex = Index(sz);
1314
9efd3367 1315 wxCHECK_RET( iIndex != NOT_FOUND,
1a5a8367 1316 _("removing inexistent element in wxArrayString::Remove") );
c801d85f 1317
c86f1403 1318 Remove(iIndex);
c801d85f
KB
1319}
1320
1321// sort array elements using passed comparaison function
1322
d355d3fe 1323void wxArrayString::Sort(bool WXUNUSED(bCase), bool WXUNUSED(bReverse) )
c801d85f
KB
1324{
1325 //@@@@ TO DO
1326 //qsort(m_pItems, m_nCount, sizeof(char *), fCmp);
1327}