]> git.saurik.com Git - wxWidgets.git/blob - src/common/string.cpp
4c61c07ee80bc07b85b74f06627259d54e5b8858
[wxWidgets.git] / src / common / string.cpp
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>
9 // Licence: wxWindows licence
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
35 #include "wx/defs.h"
36 #include "wx/string.h"
37 #include "wx/intl.h"
38 #include "wx/thread.h"
39 #endif
40
41 #include <ctype.h>
42 #include <string.h>
43 #include <stdlib.h>
44
45 #ifdef __SALFORDC__
46 #include <clib.h>
47 #endif
48
49 // allocating extra space for each string consumes more memory but speeds up
50 // the concatenation operations (nLen is the current string's length)
51 // NB: EXTRA_ALLOC must be >= 0!
52 #define EXTRA_ALLOC (19 - nLen % 16)
53
54 // ---------------------------------------------------------------------------
55 // static class variables definition
56 // ---------------------------------------------------------------------------
57
58 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
59 // must define this static for VA or else you get multiply defined symbols
60 // everywhere
61 const unsigned int wxSTRING_MAXLEN = UINT_MAX - 100;
62 #endif // Visual Age
63
64 #ifdef wxSTD_STRING_COMPATIBILITY
65 const size_t wxString::npos = wxSTRING_MAXLEN;
66 #endif // wxSTD_STRING_COMPATIBILITY
67
68 // ----------------------------------------------------------------------------
69 // static data
70 // ----------------------------------------------------------------------------
71
72 // for an empty string, GetStringData() will return this address: this
73 // structure has the same layout as wxStringData and it's data() method will
74 // return the empty string (dummy pointer)
75 static const struct
76 {
77 wxStringData data;
78 wxChar dummy;
79 } g_strEmpty = { {-1, 0, 0}, wxT('\0') };
80
81 // empty C style string: points to 'string data' byte of g_strEmpty
82 extern const wxChar WXDLLIMPEXP_BASE *wxEmptyString = &g_strEmpty.dummy;
83
84 // ----------------------------------------------------------------------------
85 // global functions
86 // ----------------------------------------------------------------------------
87
88 #if defined(wxSTD_STRING_COMPATIBILITY) && wxUSE_STD_IOSTREAM
89
90 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
91 // iostream ones.
92 //
93 // ATTN: you can _not_ use both of these in the same program!
94
95 wxSTD istream& operator>>(wxSTD istream& is, wxString& WXUNUSED(str))
96 {
97 #if 0
98 int w = is.width(0);
99 if ( is.ipfx(0) ) {
100 streambuf *sb = is.rdbuf();
101 str.erase();
102 while ( true ) {
103 int ch = sb->sbumpc ();
104 if ( ch == EOF ) {
105 is.setstate(ios::eofbit);
106 break;
107 }
108 else if ( isspace(ch) ) {
109 sb->sungetc();
110 break;
111 }
112
113 str += ch;
114 if ( --w == 1 )
115 break;
116 }
117 }
118
119 is.isfx();
120 if ( str.length() == 0 )
121 is.setstate(ios::failbit);
122 #endif
123 return is;
124 }
125
126 wxSTD ostream& operator<<(wxSTD ostream& os, const wxString& str)
127 {
128 os << str.c_str();
129 return os;
130 }
131
132 #endif //std::string compatibility
133
134 // ----------------------------------------------------------------------------
135 // private classes
136 // ----------------------------------------------------------------------------
137
138 // this small class is used to gather statistics for performance tuning
139 //#define WXSTRING_STATISTICS
140 #ifdef WXSTRING_STATISTICS
141 class Averager
142 {
143 public:
144 Averager(const wxChar *sz) { m_sz = sz; m_nTotal = m_nCount = 0; }
145 ~Averager()
146 { wxPrintf("wxString: average %s = %f\n", m_sz, ((float)m_nTotal)/m_nCount); }
147
148 void Add(size_t n) { m_nTotal += n; m_nCount++; }
149
150 private:
151 size_t m_nCount, m_nTotal;
152 const wxChar *m_sz;
153 } g_averageLength("allocation size"),
154 g_averageSummandLength("summand length"),
155 g_averageConcatHit("hit probability in concat"),
156 g_averageInitialLength("initial string length");
157
158 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
159 #else
160 #define STATISTICS_ADD(av, val)
161 #endif // WXSTRING_STATISTICS
162
163 // ===========================================================================
164 // wxStringData class deallocation
165 // ===========================================================================
166
167 #if defined(__VISUALC__) && defined(_MT) && !defined(_DLL)
168 # pragma message (__FILE__ ": building with Multithreaded non DLL runtime has a performance impact on wxString!")
169 void wxStringData::Free()
170 {
171 free(this);
172 }
173 #endif
174
175 // ===========================================================================
176 // wxString class core
177 // ===========================================================================
178
179 // ---------------------------------------------------------------------------
180 // construction
181 // ---------------------------------------------------------------------------
182
183 // constructs string of <nLength> copies of character <ch>
184 wxString::wxString(wxChar ch, size_t nLength)
185 {
186 Init();
187
188 if ( nLength > 0 ) {
189 if ( !AllocBuffer(nLength) ) {
190 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
191 return;
192 }
193
194 #if wxUSE_UNICODE
195 // memset only works on chars
196 for ( size_t n = 0; n < nLength; n++ )
197 m_pchData[n] = ch;
198 #else
199 memset(m_pchData, ch, nLength);
200 #endif
201 }
202 }
203
204 // takes nLength elements of psz starting at nPos
205 void wxString::InitWith(const wxChar *psz, size_t nPos, size_t nLength)
206 {
207 Init();
208
209 // if the length is not given, assume the string to be NUL terminated
210 if ( nLength == wxSTRING_MAXLEN ) {
211 wxASSERT_MSG( nPos <= wxStrlen(psz), _T("index out of bounds") );
212
213 nLength = wxStrlen(psz + nPos);
214 }
215
216 STATISTICS_ADD(InitialLength, nLength);
217
218 if ( nLength > 0 ) {
219 // trailing '\0' is written in AllocBuffer()
220 if ( !AllocBuffer(nLength) ) {
221 wxFAIL_MSG( _T("out of memory in wxString::InitWith") );
222 return;
223 }
224 memcpy(m_pchData, psz + nPos, nLength*sizeof(wxChar));
225 }
226 }
227
228 #ifdef wxSTD_STRING_COMPATIBILITY
229
230 // poor man's iterators are "void *" pointers
231 wxString::wxString(const void *pStart, const void *pEnd)
232 {
233 InitWith((const wxChar *)pStart, 0,
234 (const wxChar *)pEnd - (const wxChar *)pStart);
235 }
236
237 #endif //std::string compatibility
238
239 #if wxUSE_UNICODE
240
241 // from multibyte string
242 wxString::wxString(const char *psz, wxMBConv& conv, size_t nLength)
243 {
244 // first get the size of the buffer we need
245 size_t nLen;
246 if ( psz )
247 {
248 // calculate the needed size ourselves or use a provide one
249 nLen = nLength == wxSTRING_MAXLEN ? conv.MB2WC(NULL, psz, 0) : nLength;
250 }
251 else
252 {
253 // nothing to convert
254 nLen = 0;
255 }
256
257 // anything to do?
258 if ( (nLen != 0) && (nLen != (size_t)-1) )
259 {
260 if ( !AllocBuffer(nLen) )
261 {
262 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
263 }
264 else
265 {
266 // MB2WC wants the buffer size, not the string length
267 if ( conv.MB2WC(m_pchData, psz, nLen + 1) != (size_t)-1 )
268 {
269 // initialized ok
270 m_pchData[nLen] = 0;
271 return;
272 }
273 //else: the conversion failed -- leave the string empty (what else?)
274 }
275 }
276
277 Init();
278 }
279
280 #else // ANSI
281
282 #if wxUSE_WCHAR_T
283 // from wide string
284 wxString::wxString(const wchar_t *pwz, wxMBConv& conv, size_t nLength)
285 {
286 // first get the size of the buffer we need
287 size_t nLen;
288 if ( pwz )
289 {
290 // calculate the needed size ourselves or use a provide one
291 nLen = nLength == wxSTRING_MAXLEN ? conv.WC2MB(NULL, pwz, 0) : nLength;
292 }
293 else
294 {
295 // nothing to convert
296 nLen = 0;
297 }
298
299 // anything to do?
300 if ( (nLen != 0) && (nLen != (size_t)-1) )
301 {
302 if ( !AllocBuffer(nLen) )
303 {
304 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
305 }
306 else
307 {
308 // WC2MB wants the buffer size, not the string length
309 if ( conv.WC2MB(m_pchData, pwz, nLen + 1) != (size_t)-1 )
310 {
311 // initialized ok
312 return;
313 }
314 //else: the conversion failed -- leave the string empty (what else?)
315 }
316 }
317
318 Init();
319 }
320 #endif // wxUSE_WCHAR_T
321
322 #endif // Unicode/ANSI
323
324 // ---------------------------------------------------------------------------
325 // memory allocation
326 // ---------------------------------------------------------------------------
327
328 // allocates memory needed to store a C string of length nLen
329 bool wxString::AllocBuffer(size_t nLen)
330 {
331 // allocating 0 sized buffer doesn't make sense, all empty strings should
332 // reuse g_strEmpty
333 wxASSERT( nLen > 0 );
334
335 // make sure that we don't overflow
336 wxASSERT( nLen < (INT_MAX / sizeof(wxChar)) -
337 (sizeof(wxStringData) + EXTRA_ALLOC + 1) );
338
339 STATISTICS_ADD(Length, nLen);
340
341 // allocate memory:
342 // 1) one extra character for '\0' termination
343 // 2) sizeof(wxStringData) for housekeeping info
344 wxStringData* pData = (wxStringData*)
345 malloc(sizeof(wxStringData) + (nLen + EXTRA_ALLOC + 1)*sizeof(wxChar));
346
347 if ( pData == NULL ) {
348 // allocation failures are handled by the caller
349 return FALSE;
350 }
351
352 pData->nRefs = 1;
353 pData->nDataLength = nLen;
354 pData->nAllocLength = nLen + EXTRA_ALLOC;
355 m_pchData = pData->data(); // data starts after wxStringData
356 m_pchData[nLen] = wxT('\0');
357 return TRUE;
358 }
359
360 // must be called before changing this string
361 bool wxString::CopyBeforeWrite()
362 {
363 wxStringData* pData = GetStringData();
364
365 if ( pData->IsShared() ) {
366 pData->Unlock(); // memory not freed because shared
367 size_t nLen = pData->nDataLength;
368 if ( !AllocBuffer(nLen) ) {
369 // allocation failures are handled by the caller
370 return FALSE;
371 }
372 memcpy(m_pchData, pData->data(), nLen*sizeof(wxChar));
373 }
374
375 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
376
377 return TRUE;
378 }
379
380 // must be called before replacing contents of this string
381 bool wxString::AllocBeforeWrite(size_t nLen)
382 {
383 wxASSERT( nLen != 0 ); // doesn't make any sense
384
385 // must not share string and must have enough space
386 wxStringData* pData = GetStringData();
387 if ( pData->IsShared() || pData->IsEmpty() ) {
388 // can't work with old buffer, get new one
389 pData->Unlock();
390 if ( !AllocBuffer(nLen) ) {
391 // allocation failures are handled by the caller
392 return FALSE;
393 }
394 }
395 else {
396 if ( nLen > pData->nAllocLength ) {
397 // realloc the buffer instead of calling malloc() again, this is more
398 // efficient
399 STATISTICS_ADD(Length, nLen);
400
401 nLen += EXTRA_ALLOC;
402
403 pData = (wxStringData*)
404 realloc(pData, sizeof(wxStringData) + (nLen + 1)*sizeof(wxChar));
405
406 if ( pData == NULL ) {
407 // allocation failures are handled by the caller
408 // keep previous data since reallocation failed
409 return FALSE;
410 }
411
412 pData->nAllocLength = nLen;
413 m_pchData = pData->data();
414 }
415
416 // now we have enough space, just update the string length
417 pData->nDataLength = nLen;
418 }
419
420 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
421
422 return TRUE;
423 }
424
425 // allocate enough memory for nLen characters
426 bool wxString::Alloc(size_t nLen)
427 {
428 wxStringData *pData = GetStringData();
429 if ( pData->nAllocLength <= nLen ) {
430 if ( pData->IsEmpty() ) {
431 nLen += EXTRA_ALLOC;
432
433 wxStringData* pData = (wxStringData*)
434 malloc(sizeof(wxStringData) + (nLen + 1)*sizeof(wxChar));
435
436 if ( pData == NULL ) {
437 // allocation failure handled by caller
438 return FALSE;
439 }
440
441 pData->nRefs = 1;
442 pData->nDataLength = 0;
443 pData->nAllocLength = nLen;
444 m_pchData = pData->data(); // data starts after wxStringData
445 m_pchData[0u] = wxT('\0');
446 }
447 else if ( pData->IsShared() ) {
448 pData->Unlock(); // memory not freed because shared
449 size_t nOldLen = pData->nDataLength;
450 if ( !AllocBuffer(nLen) ) {
451 // allocation failure handled by caller
452 return FALSE;
453 }
454 memcpy(m_pchData, pData->data(), nOldLen*sizeof(wxChar));
455 }
456 else {
457 nLen += EXTRA_ALLOC;
458
459 pData = (wxStringData *)
460 realloc(pData, sizeof(wxStringData) + (nLen + 1)*sizeof(wxChar));
461
462 if ( pData == NULL ) {
463 // allocation failure handled by caller
464 // keep previous data since reallocation failed
465 return FALSE;
466 }
467
468 // it's not important if the pointer changed or not (the check for this
469 // is not faster than assigning to m_pchData in all cases)
470 pData->nAllocLength = nLen;
471 m_pchData = pData->data();
472 }
473 }
474 //else: we've already got enough
475 return TRUE;
476 }
477
478 // shrink to minimal size (releasing extra memory)
479 bool wxString::Shrink()
480 {
481 wxStringData *pData = GetStringData();
482
483 size_t nLen = pData->nDataLength;
484 void *p = realloc(pData, sizeof(wxStringData) + (nLen + 1)*sizeof(wxChar));
485
486 if ( p == NULL) {
487 wxFAIL_MSG( _T("out of memory reallocating wxString data") );
488 // keep previous data since reallocation failed
489 return FALSE;
490 }
491
492 if ( p != pData )
493 {
494 // contrary to what one might believe, some realloc() implementation do
495 // move the memory block even when its size is reduced
496 pData = (wxStringData *)p;
497
498 m_pchData = pData->data();
499 }
500
501 pData->nAllocLength = nLen;
502
503 return TRUE;
504 }
505
506 // get the pointer to writable buffer of (at least) nLen bytes
507 wxChar *wxString::GetWriteBuf(size_t nLen)
508 {
509 if ( !AllocBeforeWrite(nLen) ) {
510 // allocation failure handled by caller
511 return NULL;
512 }
513
514 wxASSERT( GetStringData()->nRefs == 1 );
515 GetStringData()->Validate(FALSE);
516
517 return m_pchData;
518 }
519
520 // put string back in a reasonable state after GetWriteBuf
521 void wxString::UngetWriteBuf()
522 {
523 GetStringData()->nDataLength = wxStrlen(m_pchData);
524 GetStringData()->Validate(TRUE);
525 }
526
527 void wxString::UngetWriteBuf(size_t nLen)
528 {
529 GetStringData()->nDataLength = nLen;
530 GetStringData()->Validate(TRUE);
531 }
532
533 // ---------------------------------------------------------------------------
534 // data access
535 // ---------------------------------------------------------------------------
536
537 // all functions are inline in string.h
538
539 // ---------------------------------------------------------------------------
540 // assignment operators
541 // ---------------------------------------------------------------------------
542
543 // helper function: does real copy
544 bool wxString::AssignCopy(size_t nSrcLen, const wxChar *pszSrcData)
545 {
546 if ( nSrcLen == 0 ) {
547 Reinit();
548 }
549 else {
550 if ( !AllocBeforeWrite(nSrcLen) ) {
551 // allocation failure handled by caller
552 return FALSE;
553 }
554 memcpy(m_pchData, pszSrcData, nSrcLen*sizeof(wxChar));
555 GetStringData()->nDataLength = nSrcLen;
556 m_pchData[nSrcLen] = wxT('\0');
557 }
558 return TRUE;
559 }
560
561 // assigns one string to another
562 wxString& wxString::operator=(const wxString& stringSrc)
563 {
564 wxASSERT( stringSrc.GetStringData()->IsValid() );
565
566 // don't copy string over itself
567 if ( m_pchData != stringSrc.m_pchData ) {
568 if ( stringSrc.GetStringData()->IsEmpty() ) {
569 Reinit();
570 }
571 else {
572 // adjust references
573 GetStringData()->Unlock();
574 m_pchData = stringSrc.m_pchData;
575 GetStringData()->Lock();
576 }
577 }
578
579 return *this;
580 }
581
582 // assigns a single character
583 wxString& wxString::operator=(wxChar ch)
584 {
585 if ( !AssignCopy(1, &ch) ) {
586 wxFAIL_MSG( _T("out of memory in wxString::operator=(wxChar)") );
587 }
588 return *this;
589 }
590
591
592 // assigns C string
593 wxString& wxString::operator=(const wxChar *psz)
594 {
595 if ( !AssignCopy(wxStrlen(psz), psz) ) {
596 wxFAIL_MSG( _T("out of memory in wxString::operator=(const wxChar *)") );
597 }
598 return *this;
599 }
600
601 #if !wxUSE_UNICODE
602
603 // same as 'signed char' variant
604 wxString& wxString::operator=(const unsigned char* psz)
605 {
606 *this = (const char *)psz;
607 return *this;
608 }
609
610 #if wxUSE_WCHAR_T
611 wxString& wxString::operator=(const wchar_t *pwz)
612 {
613 wxString str(pwz);
614 *this = str;
615 return *this;
616 }
617 #endif
618
619 #endif
620
621 // ---------------------------------------------------------------------------
622 // string concatenation
623 // ---------------------------------------------------------------------------
624
625 // add something to this string
626 bool wxString::ConcatSelf(size_t nSrcLen, const wxChar *pszSrcData)
627 {
628 STATISTICS_ADD(SummandLength, nSrcLen);
629
630 // concatenating an empty string is a NOP
631 if ( nSrcLen > 0 ) {
632 wxStringData *pData = GetStringData();
633 size_t nLen = pData->nDataLength;
634 size_t nNewLen = nLen + nSrcLen;
635
636 // alloc new buffer if current is too small
637 if ( pData->IsShared() ) {
638 STATISTICS_ADD(ConcatHit, 0);
639
640 // we have to allocate another buffer
641 wxStringData* pOldData = GetStringData();
642 if ( !AllocBuffer(nNewLen) ) {
643 // allocation failure handled by caller
644 return FALSE;
645 }
646 memcpy(m_pchData, pOldData->data(), nLen*sizeof(wxChar));
647 pOldData->Unlock();
648 }
649 else if ( nNewLen > pData->nAllocLength ) {
650 STATISTICS_ADD(ConcatHit, 0);
651
652 // we have to grow the buffer
653 if ( !Alloc(nNewLen) ) {
654 // allocation failure handled by caller
655 return FALSE;
656 }
657 }
658 else {
659 STATISTICS_ADD(ConcatHit, 1);
660
661 // the buffer is already big enough
662 }
663
664 // should be enough space
665 wxASSERT( nNewLen <= GetStringData()->nAllocLength );
666
667 // fast concatenation - all is done in our buffer
668 memcpy(m_pchData + nLen, pszSrcData, nSrcLen*sizeof(wxChar));
669
670 m_pchData[nNewLen] = wxT('\0'); // put terminating '\0'
671 GetStringData()->nDataLength = nNewLen; // and fix the length
672 }
673 //else: the string to append was empty
674 return TRUE;
675 }
676
677 /*
678 * concatenation functions come in 5 flavours:
679 * string + string
680 * char + string and string + char
681 * C str + string and string + C str
682 */
683
684 wxString operator+(const wxString& str1, const wxString& str2)
685 {
686 wxASSERT( str1.GetStringData()->IsValid() );
687 wxASSERT( str2.GetStringData()->IsValid() );
688
689 wxString s = str1;
690 s += str2;
691
692 return s;
693 }
694
695 wxString operator+(const wxString& str, wxChar ch)
696 {
697 wxASSERT( str.GetStringData()->IsValid() );
698
699 wxString s = str;
700 s += ch;
701
702 return s;
703 }
704
705 wxString operator+(wxChar ch, const wxString& str)
706 {
707 wxASSERT( str.GetStringData()->IsValid() );
708
709 wxString s = ch;
710 s += str;
711
712 return s;
713 }
714
715 wxString operator+(const wxString& str, const wxChar *psz)
716 {
717 wxASSERT( str.GetStringData()->IsValid() );
718
719 wxString s;
720 if ( !s.Alloc(wxStrlen(psz) + str.Len()) ) {
721 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
722 }
723 s = str;
724 s += psz;
725
726 return s;
727 }
728
729 wxString operator+(const wxChar *psz, const wxString& str)
730 {
731 wxASSERT( str.GetStringData()->IsValid() );
732
733 wxString s;
734 if ( !s.Alloc(wxStrlen(psz) + str.Len()) ) {
735 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
736 }
737 s = psz;
738 s += str;
739
740 return s;
741 }
742
743 // ===========================================================================
744 // other common string functions
745 // ===========================================================================
746
747 #if wxUSE_UNICODE
748
749 wxString wxString::FromAscii(const char *ascii)
750 {
751 if (!ascii)
752 return wxEmptyString;
753
754 size_t len = strlen( ascii );
755 wxString res;
756
757 if ( len )
758 {
759 wxStringBuffer buf(res, len);
760
761 wchar_t *dest = buf;
762
763 for ( ;; )
764 {
765 if ( (*dest++ = (wchar_t)(unsigned char)*ascii++) == L'\0' )
766 break;
767 }
768 }
769
770 return res;
771 }
772
773 wxString wxString::FromAscii(const char ascii)
774 {
775 // What do we do with '\0' ?
776
777 wxString res;
778 res += (wchar_t)(unsigned char) ascii;
779
780 return res;
781 }
782
783 const wxCharBuffer wxString::ToAscii() const
784 {
785 // this will allocate enough space for the terminating NUL too
786 wxCharBuffer buffer(length());
787
788 signed char *dest = (signed char *)buffer.data();
789
790 const wchar_t *pwc = c_str();
791 for ( ;; )
792 {
793 *dest++ = *pwc > SCHAR_MAX ? '_' : *pwc;
794
795 // the output string can't have embedded NULs anyhow, so we can safely
796 // stop at first of them even if we do have any
797 if ( !*pwc++ )
798 break;
799 }
800
801 return buffer;
802 }
803
804 #endif // Unicode
805
806 // ---------------------------------------------------------------------------
807 // simple sub-string extraction
808 // ---------------------------------------------------------------------------
809
810 // helper function: clone the data attached to this string
811 bool wxString::AllocCopy(wxString& dest, int nCopyLen, int nCopyIndex) const
812 {
813 if ( nCopyLen == 0 ) {
814 dest.Init();
815 }
816 else {
817 if ( !dest.AllocBuffer(nCopyLen) ) {
818 // allocation failure handled by caller
819 return FALSE;
820 }
821 memcpy(dest.m_pchData, m_pchData + nCopyIndex, nCopyLen*sizeof(wxChar));
822 }
823 return TRUE;
824 }
825
826 // extract string of length nCount starting at nFirst
827 wxString wxString::Mid(size_t nFirst, size_t nCount) const
828 {
829 wxStringData *pData = GetStringData();
830 size_t nLen = pData->nDataLength;
831
832 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
833 if ( nCount == wxSTRING_MAXLEN )
834 {
835 nCount = nLen - nFirst;
836 }
837
838 // out-of-bounds requests return sensible things
839 if ( nFirst + nCount > nLen )
840 {
841 nCount = nLen - nFirst;
842 }
843
844 if ( nFirst > nLen )
845 {
846 // AllocCopy() will return empty string
847 nCount = 0;
848 }
849
850 wxString dest;
851 if ( !AllocCopy(dest, nCount, nFirst) ) {
852 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
853 }
854
855 return dest;
856 }
857
858 // check that the tring starts with prefix and return the rest of the string
859 // in the provided pointer if it is not NULL, otherwise return FALSE
860 bool wxString::StartsWith(const wxChar *prefix, wxString *rest) const
861 {
862 wxASSERT_MSG( prefix, _T("invalid parameter in wxString::StartsWith") );
863
864 // first check if the beginning of the string matches the prefix: note
865 // that we don't have to check that we don't run out of this string as
866 // when we reach the terminating NUL, either prefix string ends too (and
867 // then it's ok) or we break out of the loop because there is no match
868 const wxChar *p = c_str();
869 while ( *prefix )
870 {
871 if ( *prefix++ != *p++ )
872 {
873 // no match
874 return FALSE;
875 }
876 }
877
878 if ( rest )
879 {
880 // put the rest of the string into provided pointer
881 *rest = p;
882 }
883
884 return TRUE;
885 }
886
887 // extract nCount last (rightmost) characters
888 wxString wxString::Right(size_t nCount) const
889 {
890 if ( nCount > (size_t)GetStringData()->nDataLength )
891 nCount = GetStringData()->nDataLength;
892
893 wxString dest;
894 if ( !AllocCopy(dest, nCount, GetStringData()->nDataLength - nCount) ) {
895 wxFAIL_MSG( _T("out of memory in wxString::Right") );
896 }
897 return dest;
898 }
899
900 // get all characters after the last occurence of ch
901 // (returns the whole string if ch not found)
902 wxString wxString::AfterLast(wxChar ch) const
903 {
904 wxString str;
905 int iPos = Find(ch, TRUE);
906 if ( iPos == wxNOT_FOUND )
907 str = *this;
908 else
909 str = c_str() + iPos + 1;
910
911 return str;
912 }
913
914 // extract nCount first (leftmost) characters
915 wxString wxString::Left(size_t nCount) const
916 {
917 if ( nCount > (size_t)GetStringData()->nDataLength )
918 nCount = GetStringData()->nDataLength;
919
920 wxString dest;
921 if ( !AllocCopy(dest, nCount, 0) ) {
922 wxFAIL_MSG( _T("out of memory in wxString::Left") );
923 }
924 return dest;
925 }
926
927 // get all characters before the first occurence of ch
928 // (returns the whole string if ch not found)
929 wxString wxString::BeforeFirst(wxChar ch) const
930 {
931 wxString str;
932 for ( const wxChar *pc = m_pchData; *pc != wxT('\0') && *pc != ch; pc++ )
933 str += *pc;
934
935 return str;
936 }
937
938 /// get all characters before the last occurence of ch
939 /// (returns empty string if ch not found)
940 wxString wxString::BeforeLast(wxChar ch) const
941 {
942 wxString str;
943 int iPos = Find(ch, TRUE);
944 if ( iPos != wxNOT_FOUND && iPos != 0 )
945 str = wxString(c_str(), iPos);
946
947 return str;
948 }
949
950 /// get all characters after the first occurence of ch
951 /// (returns empty string if ch not found)
952 wxString wxString::AfterFirst(wxChar ch) const
953 {
954 wxString str;
955 int iPos = Find(ch);
956 if ( iPos != wxNOT_FOUND )
957 str = c_str() + iPos + 1;
958
959 return str;
960 }
961
962 // replace first (or all) occurences of some substring with another one
963 size_t
964 wxString::Replace(const wxChar *szOld, const wxChar *szNew, bool bReplaceAll)
965 {
966 // if we tried to replace an empty string we'd enter an infinite loop below
967 wxCHECK_MSG( szOld && *szOld && szNew, 0,
968 _T("wxString::Replace(): invalid parameter") );
969
970 size_t uiCount = 0; // count of replacements made
971
972 size_t uiOldLen = wxStrlen(szOld);
973
974 wxString strTemp;
975 const wxChar *pCurrent = m_pchData;
976 const wxChar *pSubstr;
977 while ( *pCurrent != wxT('\0') ) {
978 pSubstr = wxStrstr(pCurrent, szOld);
979 if ( pSubstr == NULL ) {
980 // strTemp is unused if no replacements were made, so avoid the copy
981 if ( uiCount == 0 )
982 return 0;
983
984 strTemp += pCurrent; // copy the rest
985 break; // exit the loop
986 }
987 else {
988 // take chars before match
989 if ( !strTemp.ConcatSelf(pSubstr - pCurrent, pCurrent) ) {
990 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
991 return 0;
992 }
993 strTemp += szNew;
994 pCurrent = pSubstr + uiOldLen; // restart after match
995
996 uiCount++;
997
998 // stop now?
999 if ( !bReplaceAll ) {
1000 strTemp += pCurrent; // copy the rest
1001 break; // exit the loop
1002 }
1003 }
1004 }
1005
1006 // only done if there were replacements, otherwise would have returned above
1007 *this = strTemp;
1008
1009 return uiCount;
1010 }
1011
1012 bool wxString::IsAscii() const
1013 {
1014 const wxChar *s = (const wxChar*) *this;
1015 while(*s){
1016 if(!isascii(*s)) return(FALSE);
1017 s++;
1018 }
1019 return(TRUE);
1020 }
1021
1022 bool wxString::IsWord() const
1023 {
1024 const wxChar *s = (const wxChar*) *this;
1025 while(*s){
1026 if(!wxIsalpha(*s)) return(FALSE);
1027 s++;
1028 }
1029 return(TRUE);
1030 }
1031
1032 bool wxString::IsNumber() const
1033 {
1034 const wxChar *s = (const wxChar*) *this;
1035 if (wxStrlen(s))
1036 if ((s[0] == '-') || (s[0] == '+')) s++;
1037 while(*s){
1038 if(!wxIsdigit(*s)) return(FALSE);
1039 s++;
1040 }
1041 return(TRUE);
1042 }
1043
1044 wxString wxString::Strip(stripType w) const
1045 {
1046 wxString s = *this;
1047 if ( w & leading ) s.Trim(FALSE);
1048 if ( w & trailing ) s.Trim(TRUE);
1049 return s;
1050 }
1051
1052 // ---------------------------------------------------------------------------
1053 // case conversion
1054 // ---------------------------------------------------------------------------
1055
1056 wxString& wxString::MakeUpper()
1057 {
1058 if ( !CopyBeforeWrite() ) {
1059 wxFAIL_MSG( _T("out of memory in wxString::MakeUpper") );
1060 return *this;
1061 }
1062
1063 for ( wxChar *p = m_pchData; *p; p++ )
1064 *p = (wxChar)wxToupper(*p);
1065
1066 return *this;
1067 }
1068
1069 wxString& wxString::MakeLower()
1070 {
1071 if ( !CopyBeforeWrite() ) {
1072 wxFAIL_MSG( _T("out of memory in wxString::MakeLower") );
1073 return *this;
1074 }
1075
1076 for ( wxChar *p = m_pchData; *p; p++ )
1077 *p = (wxChar)wxTolower(*p);
1078
1079 return *this;
1080 }
1081
1082 // ---------------------------------------------------------------------------
1083 // trimming and padding
1084 // ---------------------------------------------------------------------------
1085
1086 // some compilers (VC++ 6.0 not to name them) return TRUE for a call to
1087 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1088 // live with this by checking that the character is a 7 bit one - even if this
1089 // may fail to detect some spaces (I don't know if Unicode doesn't have
1090 // space-like symbols somewhere except in the first 128 chars), it is arguably
1091 // still better than trimming away accented letters
1092 inline int wxSafeIsspace(wxChar ch) { return (ch < 127) && wxIsspace(ch); }
1093
1094 // trims spaces (in the sense of isspace) from left or right side
1095 wxString& wxString::Trim(bool bFromRight)
1096 {
1097 // first check if we're going to modify the string at all
1098 if ( !IsEmpty() &&
1099 (
1100 (bFromRight && wxSafeIsspace(GetChar(Len() - 1))) ||
1101 (!bFromRight && wxSafeIsspace(GetChar(0u)))
1102 )
1103 )
1104 {
1105 // ok, there is at least one space to trim
1106 if ( !CopyBeforeWrite() ) {
1107 wxFAIL_MSG( _T("out of memory in wxString::Trim") );
1108 return *this;
1109 }
1110
1111 if ( bFromRight )
1112 {
1113 // find last non-space character
1114 wxChar *psz = m_pchData + GetStringData()->nDataLength - 1;
1115 while ( wxSafeIsspace(*psz) && (psz >= m_pchData) )
1116 psz--;
1117
1118 // truncate at trailing space start
1119 *++psz = wxT('\0');
1120 GetStringData()->nDataLength = psz - m_pchData;
1121 }
1122 else
1123 {
1124 // find first non-space character
1125 const wxChar *psz = m_pchData;
1126 while ( wxSafeIsspace(*psz) )
1127 psz++;
1128
1129 // fix up data and length
1130 int nDataLength = GetStringData()->nDataLength - (psz - (const wxChar*) m_pchData);
1131 memmove(m_pchData, psz, (nDataLength + 1)*sizeof(wxChar));
1132 GetStringData()->nDataLength = nDataLength;
1133 }
1134 }
1135
1136 return *this;
1137 }
1138
1139 // adds nCount characters chPad to the string from either side
1140 wxString& wxString::Pad(size_t nCount, wxChar chPad, bool bFromRight)
1141 {
1142 wxString s(chPad, nCount);
1143
1144 if ( bFromRight )
1145 *this += s;
1146 else
1147 {
1148 s += *this;
1149 *this = s;
1150 }
1151
1152 return *this;
1153 }
1154
1155 // truncate the string
1156 wxString& wxString::Truncate(size_t uiLen)
1157 {
1158 if ( uiLen < Len() ) {
1159 if ( !CopyBeforeWrite() ) {
1160 wxFAIL_MSG( _T("out of memory in wxString::Truncate") );
1161 return *this;
1162 }
1163
1164 *(m_pchData + uiLen) = wxT('\0');
1165 GetStringData()->nDataLength = uiLen;
1166 }
1167 //else: nothing to do, string is already short enough
1168
1169 return *this;
1170 }
1171
1172 // ---------------------------------------------------------------------------
1173 // finding (return wxNOT_FOUND if not found and index otherwise)
1174 // ---------------------------------------------------------------------------
1175
1176 // find a character
1177 int wxString::Find(wxChar ch, bool bFromEnd) const
1178 {
1179 const wxChar *psz = bFromEnd ? wxStrrchr(m_pchData, ch) : wxStrchr(m_pchData, ch);
1180
1181 return (psz == NULL) ? wxNOT_FOUND : psz - (const wxChar*) m_pchData;
1182 }
1183
1184 // find a sub-string (like strstr)
1185 int wxString::Find(const wxChar *pszSub) const
1186 {
1187 const wxChar *psz = wxStrstr(m_pchData, pszSub);
1188
1189 return (psz == NULL) ? wxNOT_FOUND : psz - (const wxChar*) m_pchData;
1190 }
1191
1192 // ----------------------------------------------------------------------------
1193 // conversion to numbers
1194 // ----------------------------------------------------------------------------
1195
1196 bool wxString::ToLong(long *val, int base) const
1197 {
1198 wxCHECK_MSG( val, FALSE, _T("NULL pointer in wxString::ToLong") );
1199 wxASSERT_MSG( !base || (base > 1 && base <= 36), _T("invalid base") );
1200
1201 const wxChar *start = c_str();
1202 wxChar *end;
1203 *val = wxStrtol(start, &end, base);
1204
1205 // return TRUE only if scan was stopped by the terminating NUL and if the
1206 // string was not empty to start with
1207 return !*end && (end != start);
1208 }
1209
1210 bool wxString::ToULong(unsigned long *val, int base) const
1211 {
1212 wxCHECK_MSG( val, FALSE, _T("NULL pointer in wxString::ToULong") );
1213 wxASSERT_MSG( !base || (base > 1 && base <= 36), _T("invalid base") );
1214
1215 const wxChar *start = c_str();
1216 wxChar *end;
1217 *val = wxStrtoul(start, &end, base);
1218
1219 // return TRUE only if scan was stopped by the terminating NUL and if the
1220 // string was not empty to start with
1221 return !*end && (end != start);
1222 }
1223
1224 bool wxString::ToDouble(double *val) const
1225 {
1226 wxCHECK_MSG( val, FALSE, _T("NULL pointer in wxString::ToDouble") );
1227
1228 const wxChar *start = c_str();
1229 wxChar *end;
1230 *val = wxStrtod(start, &end);
1231
1232 // return TRUE only if scan was stopped by the terminating NUL and if the
1233 // string was not empty to start with
1234 return !*end && (end != start);
1235 }
1236
1237 // ---------------------------------------------------------------------------
1238 // formatted output
1239 // ---------------------------------------------------------------------------
1240
1241 /* static */
1242 wxString wxString::Format(const wxChar *pszFormat, ...)
1243 {
1244 va_list argptr;
1245 va_start(argptr, pszFormat);
1246
1247 wxString s;
1248 s.PrintfV(pszFormat, argptr);
1249
1250 va_end(argptr);
1251
1252 return s;
1253 }
1254
1255 /* static */
1256 wxString wxString::FormatV(const wxChar *pszFormat, va_list argptr)
1257 {
1258 wxString s;
1259 s.PrintfV(pszFormat, argptr);
1260 return s;
1261 }
1262
1263 int wxString::Printf(const wxChar *pszFormat, ...)
1264 {
1265 va_list argptr;
1266 va_start(argptr, pszFormat);
1267
1268 int iLen = PrintfV(pszFormat, argptr);
1269
1270 va_end(argptr);
1271
1272 return iLen;
1273 }
1274
1275 int wxString::PrintfV(const wxChar* pszFormat, va_list argptr)
1276 {
1277 int size = 1024;
1278 for ( ;; )
1279 {
1280 wxChar *buf = GetWriteBuf(size + 1);
1281 if ( !buf )
1282 {
1283 // out of memory
1284 return -1;
1285 }
1286
1287 int len = wxVsnprintf(buf, size, pszFormat, argptr);
1288
1289 // some implementations of vsnprintf() don't NUL terminate the string
1290 // if there is not enough space for it so always do it manually
1291 buf[size] = _T('\0');
1292
1293 UngetWriteBuf();
1294
1295 if ( len >= 0 )
1296 {
1297 // ok, there was enough space
1298 break;
1299 }
1300
1301 // still not enough, double it again
1302 size *= 2;
1303 }
1304
1305 // we could have overshot
1306 Shrink();
1307
1308 return Len();
1309 }
1310
1311 // ----------------------------------------------------------------------------
1312 // misc other operations
1313 // ----------------------------------------------------------------------------
1314
1315 // returns TRUE if the string matches the pattern which may contain '*' and
1316 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1317 // of them)
1318 bool wxString::Matches(const wxChar *pszMask) const
1319 {
1320 // I disable this code as it doesn't seem to be faster (in fact, it seems
1321 // to be much slower) than the old, hand-written code below and using it
1322 // here requires always linking with libregex even if the user code doesn't
1323 // use it
1324 #if 0 // wxUSE_REGEX
1325 // first translate the shell-like mask into a regex
1326 wxString pattern;
1327 pattern.reserve(wxStrlen(pszMask));
1328
1329 pattern += _T('^');
1330 while ( *pszMask )
1331 {
1332 switch ( *pszMask )
1333 {
1334 case _T('?'):
1335 pattern += _T('.');
1336 break;
1337
1338 case _T('*'):
1339 pattern += _T(".*");
1340 break;
1341
1342 case _T('^'):
1343 case _T('.'):
1344 case _T('$'):
1345 case _T('('):
1346 case _T(')'):
1347 case _T('|'):
1348 case _T('+'):
1349 case _T('\\'):
1350 // these characters are special in a RE, quote them
1351 // (however note that we don't quote '[' and ']' to allow
1352 // using them for Unix shell like matching)
1353 pattern += _T('\\');
1354 // fall through
1355
1356 default:
1357 pattern += *pszMask;
1358 }
1359
1360 pszMask++;
1361 }
1362 pattern += _T('$');
1363
1364 // and now use it
1365 return wxRegEx(pattern, wxRE_NOSUB | wxRE_EXTENDED).Matches(c_str());
1366 #else // !wxUSE_REGEX
1367 // TODO: this is, of course, awfully inefficient...
1368
1369 // the char currently being checked
1370 const wxChar *pszTxt = c_str();
1371
1372 // the last location where '*' matched
1373 const wxChar *pszLastStarInText = NULL;
1374 const wxChar *pszLastStarInMask = NULL;
1375
1376 match:
1377 for ( ; *pszMask != wxT('\0'); pszMask++, pszTxt++ ) {
1378 switch ( *pszMask ) {
1379 case wxT('?'):
1380 if ( *pszTxt == wxT('\0') )
1381 return FALSE;
1382
1383 // pszTxt and pszMask will be incremented in the loop statement
1384
1385 break;
1386
1387 case wxT('*'):
1388 {
1389 // remember where we started to be able to backtrack later
1390 pszLastStarInText = pszTxt;
1391 pszLastStarInMask = pszMask;
1392
1393 // ignore special chars immediately following this one
1394 // (should this be an error?)
1395 while ( *pszMask == wxT('*') || *pszMask == wxT('?') )
1396 pszMask++;
1397
1398 // if there is nothing more, match
1399 if ( *pszMask == wxT('\0') )
1400 return TRUE;
1401
1402 // are there any other metacharacters in the mask?
1403 size_t uiLenMask;
1404 const wxChar *pEndMask = wxStrpbrk(pszMask, wxT("*?"));
1405
1406 if ( pEndMask != NULL ) {
1407 // we have to match the string between two metachars
1408 uiLenMask = pEndMask - pszMask;
1409 }
1410 else {
1411 // we have to match the remainder of the string
1412 uiLenMask = wxStrlen(pszMask);
1413 }
1414
1415 wxString strToMatch(pszMask, uiLenMask);
1416 const wxChar* pMatch = wxStrstr(pszTxt, strToMatch);
1417 if ( pMatch == NULL )
1418 return FALSE;
1419
1420 // -1 to compensate "++" in the loop
1421 pszTxt = pMatch + uiLenMask - 1;
1422 pszMask += uiLenMask - 1;
1423 }
1424 break;
1425
1426 default:
1427 if ( *pszMask != *pszTxt )
1428 return FALSE;
1429 break;
1430 }
1431 }
1432
1433 // match only if nothing left
1434 if ( *pszTxt == wxT('\0') )
1435 return TRUE;
1436
1437 // if we failed to match, backtrack if we can
1438 if ( pszLastStarInText ) {
1439 pszTxt = pszLastStarInText + 1;
1440 pszMask = pszLastStarInMask;
1441
1442 pszLastStarInText = NULL;
1443
1444 // don't bother resetting pszLastStarInMask, it's unnecessary
1445
1446 goto match;
1447 }
1448
1449 return FALSE;
1450 #endif // wxUSE_REGEX/!wxUSE_REGEX
1451 }
1452
1453 // Count the number of chars
1454 int wxString::Freq(wxChar ch) const
1455 {
1456 int count = 0;
1457 int len = Len();
1458 for (int i = 0; i < len; i++)
1459 {
1460 if (GetChar(i) == ch)
1461 count ++;
1462 }
1463 return count;
1464 }
1465
1466 // convert to upper case, return the copy of the string
1467 wxString wxString::Upper() const
1468 { wxString s(*this); return s.MakeUpper(); }
1469
1470 // convert to lower case, return the copy of the string
1471 wxString wxString::Lower() const { wxString s(*this); return s.MakeLower(); }
1472
1473 int wxString::sprintf(const wxChar *pszFormat, ...)
1474 {
1475 va_list argptr;
1476 va_start(argptr, pszFormat);
1477 int iLen = PrintfV(pszFormat, argptr);
1478 va_end(argptr);
1479 return iLen;
1480 }
1481
1482 // ---------------------------------------------------------------------------
1483 // standard C++ library string functions
1484 // ---------------------------------------------------------------------------
1485
1486 #ifdef wxSTD_STRING_COMPATIBILITY
1487
1488 void wxString::resize(size_t nSize, wxChar ch)
1489 {
1490 size_t len = length();
1491
1492 if ( nSize < len )
1493 {
1494 Truncate(nSize);
1495 }
1496 else if ( nSize > len )
1497 {
1498 *this += wxString(ch, nSize - len);
1499 }
1500 //else: we have exactly the specified length, nothing to do
1501 }
1502
1503 void wxString::swap(wxString& str)
1504 {
1505 // this is slightly less efficient than fiddling with m_pchData directly,
1506 // but it is still quite efficient as we don't copy the string here because
1507 // ref count always stays positive
1508 wxString tmp = str;
1509 str = *this;
1510 *this = tmp;
1511 }
1512
1513 wxString& wxString::insert(size_t nPos, const wxString& str)
1514 {
1515 wxASSERT( str.GetStringData()->IsValid() );
1516 wxASSERT( nPos <= Len() );
1517
1518 if ( !str.IsEmpty() ) {
1519 wxString strTmp;
1520 wxChar *pc = strTmp.GetWriteBuf(Len() + str.Len());
1521 wxStrncpy(pc, c_str(), nPos);
1522 wxStrcpy(pc + nPos, str);
1523 wxStrcpy(pc + nPos + str.Len(), c_str() + nPos);
1524 strTmp.UngetWriteBuf();
1525 *this = strTmp;
1526 }
1527
1528 return *this;
1529 }
1530
1531 size_t wxString::find(const wxString& str, size_t nStart) const
1532 {
1533 wxASSERT( str.GetStringData()->IsValid() );
1534 wxASSERT( nStart <= Len() );
1535
1536 const wxChar *p = wxStrstr(c_str() + nStart, str);
1537
1538 return p == NULL ? npos : p - c_str();
1539 }
1540
1541 // VC++ 1.5 can't cope with the default argument in the header.
1542 #if !defined(__VISUALC__) || defined(__WIN32__)
1543 size_t wxString::find(const wxChar* sz, size_t nStart, size_t n) const
1544 {
1545 return find(wxString(sz, n), nStart);
1546 }
1547 #endif // VC++ 1.5
1548
1549 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1550 #if !defined(__BORLANDC__)
1551 size_t wxString::find(wxChar ch, size_t nStart) const
1552 {
1553 wxASSERT( nStart <= Len() );
1554
1555 const wxChar *p = wxStrchr(c_str() + nStart, ch);
1556
1557 return p == NULL ? npos : p - c_str();
1558 }
1559 #endif
1560
1561 size_t wxString::rfind(const wxString& str, size_t nStart) const
1562 {
1563 wxASSERT( str.GetStringData()->IsValid() );
1564 wxASSERT( nStart == npos || nStart <= Len() );
1565
1566 // TODO could be made much quicker than that
1567 const wxChar *p = c_str() + (nStart == npos ? Len() : nStart);
1568 while ( p >= c_str() + str.Len() ) {
1569 if ( wxStrncmp(p - str.Len(), str, str.Len()) == 0 )
1570 return p - str.Len() - c_str();
1571 p--;
1572 }
1573
1574 return npos;
1575 }
1576
1577 // VC++ 1.5 can't cope with the default argument in the header.
1578 #if !defined(__VISUALC__) || defined(__WIN32__)
1579 size_t wxString::rfind(const wxChar* sz, size_t nStart, size_t n) const
1580 {
1581 return rfind(wxString(sz, n == npos ? wxSTRING_MAXLEN : n), nStart);
1582 }
1583
1584 size_t wxString::rfind(wxChar ch, size_t nStart) const
1585 {
1586 if ( nStart == npos )
1587 {
1588 nStart = Len();
1589 }
1590 else
1591 {
1592 wxASSERT( nStart <= Len() );
1593 }
1594
1595 const wxChar *p = wxStrrchr(c_str(), ch);
1596
1597 if ( p == NULL )
1598 return npos;
1599
1600 size_t result = p - c_str();
1601 return ( result > nStart ) ? npos : result;
1602 }
1603 #endif // VC++ 1.5
1604
1605 size_t wxString::find_first_of(const wxChar* sz, size_t nStart) const
1606 {
1607 const wxChar *start = c_str() + nStart;
1608 const wxChar *firstOf = wxStrpbrk(start, sz);
1609 if ( firstOf )
1610 return firstOf - c_str();
1611 else
1612 return npos;
1613 }
1614
1615 size_t wxString::find_last_of(const wxChar* sz, size_t nStart) const
1616 {
1617 if ( nStart == npos )
1618 {
1619 nStart = Len();
1620 }
1621 else
1622 {
1623 wxASSERT( nStart <= Len() );
1624 }
1625
1626 for ( const wxChar *p = c_str() + length() - 1; p >= c_str(); p-- )
1627 {
1628 if ( wxStrchr(sz, *p) )
1629 return p - c_str();
1630 }
1631
1632 return npos;
1633 }
1634
1635 size_t wxString::find_first_not_of(const wxChar* sz, size_t nStart) const
1636 {
1637 if ( nStart == npos )
1638 {
1639 nStart = Len();
1640 }
1641 else
1642 {
1643 wxASSERT( nStart <= Len() );
1644 }
1645
1646 size_t nAccept = wxStrspn(c_str() + nStart, sz);
1647 if ( nAccept >= length() - nStart )
1648 return npos;
1649 else
1650 return nAccept;
1651 }
1652
1653 size_t wxString::find_first_not_of(wxChar ch, size_t nStart) const
1654 {
1655 wxASSERT( nStart <= Len() );
1656
1657 for ( const wxChar *p = c_str() + nStart; *p; p++ )
1658 {
1659 if ( *p != ch )
1660 return p - c_str();
1661 }
1662
1663 return npos;
1664 }
1665
1666 size_t wxString::find_last_not_of(const wxChar* sz, size_t nStart) const
1667 {
1668 if ( nStart == npos )
1669 {
1670 nStart = Len();
1671 }
1672 else
1673 {
1674 wxASSERT( nStart <= Len() );
1675 }
1676
1677 for ( const wxChar *p = c_str() + nStart - 1; p >= c_str(); p-- )
1678 {
1679 if ( !wxStrchr(sz, *p) )
1680 return p - c_str();
1681 }
1682
1683 return npos;
1684 }
1685
1686 size_t wxString::find_last_not_of(wxChar ch, size_t nStart) const
1687 {
1688 if ( nStart == npos )
1689 {
1690 nStart = Len();
1691 }
1692 else
1693 {
1694 wxASSERT( nStart <= Len() );
1695 }
1696
1697 for ( const wxChar *p = c_str() + nStart - 1; p >= c_str(); p-- )
1698 {
1699 if ( *p != ch )
1700 return p - c_str();
1701 }
1702
1703 return npos;
1704 }
1705
1706 wxString& wxString::erase(size_t nStart, size_t nLen)
1707 {
1708 wxString strTmp(c_str(), nStart);
1709 if ( nLen != npos ) {
1710 wxASSERT( nStart + nLen <= Len() );
1711
1712 strTmp.append(c_str() + nStart + nLen);
1713 }
1714
1715 *this = strTmp;
1716 return *this;
1717 }
1718
1719 wxString& wxString::replace(size_t nStart, size_t nLen, const wxChar *sz)
1720 {
1721 wxASSERT_MSG( nStart + nLen <= Len(),
1722 _T("index out of bounds in wxString::replace") );
1723
1724 wxString strTmp;
1725 strTmp.Alloc(Len()); // micro optimisation to avoid multiple mem allocs
1726
1727 if ( nStart != 0 )
1728 strTmp.append(c_str(), nStart);
1729 strTmp << sz << c_str() + nStart + nLen;
1730
1731 *this = strTmp;
1732 return *this;
1733 }
1734
1735 wxString& wxString::replace(size_t nStart, size_t nLen, size_t nCount, wxChar ch)
1736 {
1737 return replace(nStart, nLen, wxString(ch, nCount));
1738 }
1739
1740 wxString& wxString::replace(size_t nStart, size_t nLen,
1741 const wxString& str, size_t nStart2, size_t nLen2)
1742 {
1743 return replace(nStart, nLen, str.substr(nStart2, nLen2));
1744 }
1745
1746 wxString& wxString::replace(size_t nStart, size_t nLen,
1747 const wxChar* sz, size_t nCount)
1748 {
1749 return replace(nStart, nLen, wxString(sz, nCount));
1750 }
1751
1752 #endif //std::string compatibility
1753
1754 // ============================================================================
1755 // ArrayString
1756 // ============================================================================
1757
1758 #if !wxUSE_STL
1759
1760 #include "wx/arrstr.h"
1761
1762 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1763 #define ARRAY_MAXSIZE_INCREMENT 4096
1764
1765 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1766 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1767 #endif
1768
1769 #define STRING(p) ((wxString *)(&(p)))
1770
1771 // ctor
1772 void wxArrayString::Init(bool autoSort)
1773 {
1774 m_nSize =
1775 m_nCount = 0;
1776 m_pItems = (wxChar **) NULL;
1777 m_autoSort = autoSort;
1778 }
1779
1780 // copy ctor
1781 wxArrayString::wxArrayString(const wxArrayString& src)
1782 {
1783 Init(src.m_autoSort);
1784
1785 *this = src;
1786 }
1787
1788 // assignment operator
1789 wxArrayString& wxArrayString::operator=(const wxArrayString& src)
1790 {
1791 if ( m_nSize > 0 )
1792 Clear();
1793
1794 Copy(src);
1795
1796 m_autoSort = src.m_autoSort;
1797
1798 return *this;
1799 }
1800
1801 void wxArrayString::Copy(const wxArrayString& src)
1802 {
1803 if ( src.m_nCount > ARRAY_DEFAULT_INITIAL_SIZE )
1804 Alloc(src.m_nCount);
1805
1806 for ( size_t n = 0; n < src.m_nCount; n++ )
1807 Add(src[n]);
1808 }
1809
1810 // grow the array
1811 void wxArrayString::Grow(size_t nIncrement)
1812 {
1813 // only do it if no more place
1814 if ( (m_nSize - m_nCount) < nIncrement ) {
1815 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
1816 // be never resized!
1817 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
1818 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
1819 #endif
1820
1821 if ( m_nSize == 0 ) {
1822 // was empty, alloc some memory
1823 m_nSize = ARRAY_DEFAULT_INITIAL_SIZE;
1824 if (m_nSize < nIncrement)
1825 m_nSize = nIncrement;
1826 m_pItems = new wxChar *[m_nSize];
1827 }
1828 else {
1829 // otherwise when it's called for the first time, nIncrement would be 0
1830 // and the array would never be expanded
1831 // add 50% but not too much
1832 size_t ndefIncrement = m_nSize < ARRAY_DEFAULT_INITIAL_SIZE
1833 ? ARRAY_DEFAULT_INITIAL_SIZE : m_nSize >> 1;
1834 if ( ndefIncrement > ARRAY_MAXSIZE_INCREMENT )
1835 ndefIncrement = ARRAY_MAXSIZE_INCREMENT;
1836 if ( nIncrement < ndefIncrement )
1837 nIncrement = ndefIncrement;
1838 m_nSize += nIncrement;
1839 wxChar **pNew = new wxChar *[m_nSize];
1840
1841 // copy data to new location
1842 memcpy(pNew, m_pItems, m_nCount*sizeof(wxChar *));
1843
1844 // delete old memory (but do not release the strings!)
1845 wxDELETEA(m_pItems);
1846
1847 m_pItems = pNew;
1848 }
1849 }
1850 }
1851
1852 void wxArrayString::Free()
1853 {
1854 for ( size_t n = 0; n < m_nCount; n++ ) {
1855 STRING(m_pItems[n])->GetStringData()->Unlock();
1856 }
1857 }
1858
1859 // deletes all the strings from the list
1860 void wxArrayString::Empty()
1861 {
1862 Free();
1863
1864 m_nCount = 0;
1865 }
1866
1867 // as Empty, but also frees memory
1868 void wxArrayString::Clear()
1869 {
1870 Free();
1871
1872 m_nSize =
1873 m_nCount = 0;
1874
1875 wxDELETEA(m_pItems);
1876 }
1877
1878 // dtor
1879 wxArrayString::~wxArrayString()
1880 {
1881 Free();
1882
1883 wxDELETEA(m_pItems);
1884 }
1885
1886 // pre-allocates memory (frees the previous data!)
1887 void wxArrayString::Alloc(size_t nSize)
1888 {
1889 // only if old buffer was not big enough
1890 if ( nSize > m_nSize ) {
1891 Free();
1892 wxDELETEA(m_pItems);
1893 m_pItems = new wxChar *[nSize];
1894 m_nSize = nSize;
1895 }
1896
1897 m_nCount = 0;
1898 }
1899
1900 // minimizes the memory usage by freeing unused memory
1901 void wxArrayString::Shrink()
1902 {
1903 // only do it if we have some memory to free
1904 if( m_nCount < m_nSize ) {
1905 // allocates exactly as much memory as we need
1906 wxChar **pNew = new wxChar *[m_nCount];
1907
1908 // copy data to new location
1909 memcpy(pNew, m_pItems, m_nCount*sizeof(wxChar *));
1910 delete [] m_pItems;
1911 m_pItems = pNew;
1912 }
1913 }
1914
1915 #if WXWIN_COMPATIBILITY_2_4
1916
1917 // return a wxString[] as required for some control ctors.
1918 wxString* wxArrayString::GetStringArray() const
1919 {
1920 wxString *array = 0;
1921
1922 if( m_nCount > 0 )
1923 {
1924 array = new wxString[m_nCount];
1925 for( size_t i = 0; i < m_nCount; i++ )
1926 array[i] = m_pItems[i];
1927 }
1928
1929 return array;
1930 }
1931
1932 #endif // WXWIN_COMPATIBILITY_2_4
1933
1934 // searches the array for an item (forward or backwards)
1935 int wxArrayString::Index(const wxChar *sz, bool bCase, bool bFromEnd) const
1936 {
1937 if ( m_autoSort ) {
1938 // use binary search in the sorted array
1939 wxASSERT_MSG( bCase && !bFromEnd,
1940 wxT("search parameters ignored for auto sorted array") );
1941
1942 size_t i,
1943 lo = 0,
1944 hi = m_nCount;
1945 int res;
1946 while ( lo < hi ) {
1947 i = (lo + hi)/2;
1948
1949 res = wxStrcmp(sz, m_pItems[i]);
1950 if ( res < 0 )
1951 hi = i;
1952 else if ( res > 0 )
1953 lo = i + 1;
1954 else
1955 return i;
1956 }
1957
1958 return wxNOT_FOUND;
1959 }
1960 else {
1961 // use linear search in unsorted array
1962 if ( bFromEnd ) {
1963 if ( m_nCount > 0 ) {
1964 size_t ui = m_nCount;
1965 do {
1966 if ( STRING(m_pItems[--ui])->IsSameAs(sz, bCase) )
1967 return ui;
1968 }
1969 while ( ui != 0 );
1970 }
1971 }
1972 else {
1973 for( size_t ui = 0; ui < m_nCount; ui++ ) {
1974 if( STRING(m_pItems[ui])->IsSameAs(sz, bCase) )
1975 return ui;
1976 }
1977 }
1978 }
1979
1980 return wxNOT_FOUND;
1981 }
1982
1983 // add item at the end
1984 size_t wxArrayString::Add(const wxString& str, size_t nInsert)
1985 {
1986 if ( m_autoSort ) {
1987 // insert the string at the correct position to keep the array sorted
1988 size_t i,
1989 lo = 0,
1990 hi = m_nCount;
1991 int res;
1992 while ( lo < hi ) {
1993 i = (lo + hi)/2;
1994
1995 res = wxStrcmp(str, m_pItems[i]);
1996 if ( res < 0 )
1997 hi = i;
1998 else if ( res > 0 )
1999 lo = i + 1;
2000 else {
2001 lo = hi = i;
2002 break;
2003 }
2004 }
2005
2006 wxASSERT_MSG( lo == hi, wxT("binary search broken") );
2007
2008 Insert(str, lo, nInsert);
2009
2010 return (size_t)lo;
2011 }
2012 else {
2013 wxASSERT( str.GetStringData()->IsValid() );
2014
2015 Grow(nInsert);
2016
2017 for (size_t i = 0; i < nInsert; i++)
2018 {
2019 // the string data must not be deleted!
2020 str.GetStringData()->Lock();
2021
2022 // just append
2023 m_pItems[m_nCount + i] = (wxChar *)str.c_str(); // const_cast
2024 }
2025 size_t ret = m_nCount;
2026 m_nCount += nInsert;
2027 return ret;
2028 }
2029 }
2030
2031 // add item at the given position
2032 void wxArrayString::Insert(const wxString& str, size_t nIndex, size_t nInsert)
2033 {
2034 wxASSERT( str.GetStringData()->IsValid() );
2035
2036 wxCHECK_RET( nIndex <= m_nCount, wxT("bad index in wxArrayString::Insert") );
2037 wxCHECK_RET( m_nCount <= m_nCount + nInsert,
2038 wxT("array size overflow in wxArrayString::Insert") );
2039
2040 Grow(nInsert);
2041
2042 memmove(&m_pItems[nIndex + nInsert], &m_pItems[nIndex],
2043 (m_nCount - nIndex)*sizeof(wxChar *));
2044
2045 for (size_t i = 0; i < nInsert; i++)
2046 {
2047 str.GetStringData()->Lock();
2048 m_pItems[nIndex + i] = (wxChar *)str.c_str();
2049 }
2050 m_nCount += nInsert;
2051 }
2052
2053 // expand the array
2054 void wxArrayString::SetCount(size_t count)
2055 {
2056 Alloc(count);
2057
2058 wxString s;
2059 while ( m_nCount < count )
2060 m_pItems[m_nCount++] = (wxChar *)s.c_str();
2061 }
2062
2063 // removes item from array (by index)
2064 void wxArrayString::RemoveAt(size_t nIndex, size_t nRemove)
2065 {
2066 wxCHECK_RET( nIndex < m_nCount, wxT("bad index in wxArrayString::Remove") );
2067 wxCHECK_RET( nIndex + nRemove <= m_nCount,
2068 wxT("removing too many elements in wxArrayString::Remove") );
2069
2070 // release our lock
2071 for (size_t i = 0; i < nRemove; i++)
2072 Item(nIndex + i).GetStringData()->Unlock();
2073
2074 memmove(&m_pItems[nIndex], &m_pItems[nIndex + nRemove],
2075 (m_nCount - nIndex - nRemove)*sizeof(wxChar *));
2076 m_nCount -= nRemove;
2077 }
2078
2079 // removes item from array (by value)
2080 void wxArrayString::Remove(const wxChar *sz)
2081 {
2082 int iIndex = Index(sz);
2083
2084 wxCHECK_RET( iIndex != wxNOT_FOUND,
2085 wxT("removing inexistent element in wxArrayString::Remove") );
2086
2087 RemoveAt(iIndex);
2088 }
2089
2090 // ----------------------------------------------------------------------------
2091 // sorting
2092 // ----------------------------------------------------------------------------
2093
2094 // we can only sort one array at a time with the quick-sort based
2095 // implementation
2096 #if wxUSE_THREADS
2097 // need a critical section to protect access to gs_compareFunction and
2098 // gs_sortAscending variables
2099 static wxCriticalSection *gs_critsectStringSort = NULL;
2100
2101 // call this before the value of the global sort vars is changed/after
2102 // you're finished with them
2103 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2104 gs_critsectStringSort = new wxCriticalSection; \
2105 gs_critsectStringSort->Enter()
2106 #define END_SORT() gs_critsectStringSort->Leave(); \
2107 delete gs_critsectStringSort; \
2108 gs_critsectStringSort = NULL
2109 #else // !threads
2110 #define START_SORT()
2111 #define END_SORT()
2112 #endif // wxUSE_THREADS
2113
2114 // function to use for string comparaison
2115 static wxArrayString::CompareFunction gs_compareFunction = NULL;
2116
2117 // if we don't use the compare function, this flag tells us if we sort the
2118 // array in ascending or descending order
2119 static bool gs_sortAscending = TRUE;
2120
2121 // function which is called by quick sort
2122 extern "C" int wxC_CALLING_CONV // LINKAGEMODE
2123 wxStringCompareFunction(const void *first, const void *second)
2124 {
2125 wxString *strFirst = (wxString *)first;
2126 wxString *strSecond = (wxString *)second;
2127
2128 if ( gs_compareFunction ) {
2129 return gs_compareFunction(*strFirst, *strSecond);
2130 }
2131 else {
2132 // maybe we should use wxStrcoll
2133 int result = wxStrcmp(strFirst->c_str(), strSecond->c_str());
2134
2135 return gs_sortAscending ? result : -result;
2136 }
2137 }
2138
2139 // sort array elements using passed comparaison function
2140 void wxArrayString::Sort(CompareFunction compareFunction)
2141 {
2142 START_SORT();
2143
2144 wxASSERT( !gs_compareFunction ); // must have been reset to NULL
2145 gs_compareFunction = compareFunction;
2146
2147 DoSort();
2148
2149 // reset it to NULL so that Sort(bool) will work the next time
2150 gs_compareFunction = NULL;
2151
2152 END_SORT();
2153 }
2154
2155 typedef int (wxC_CALLING_CONV * wxStringCompareFn)(const void *first, const void *second);
2156
2157 void wxArrayString::Sort(CompareFunction2 compareFunction)
2158 {
2159 qsort(m_pItems, m_nCount, sizeof(wxChar *), (wxStringCompareFn)compareFunction);
2160 }
2161
2162 void wxArrayString::Sort(bool reverseOrder)
2163 {
2164 Sort(reverseOrder ? wxStringSortDescending : wxStringSortAscending);
2165 }
2166
2167 void wxArrayString::DoSort()
2168 {
2169 wxCHECK_RET( !m_autoSort, wxT("can't use this method with sorted arrays") );
2170
2171 // just sort the pointers using qsort() - of course it only works because
2172 // wxString() *is* a pointer to its data
2173 qsort(m_pItems, m_nCount, sizeof(wxChar *), wxStringCompareFunction);
2174 }
2175
2176 bool wxArrayString::operator==(const wxArrayString& a) const
2177 {
2178 if ( m_nCount != a.m_nCount )
2179 return FALSE;
2180
2181 for ( size_t n = 0; n < m_nCount; n++ )
2182 {
2183 if ( Item(n) != a[n] )
2184 return FALSE;
2185 }
2186
2187 return TRUE;
2188 }
2189
2190 #endif // !wxUSE_STL
2191
2192 int wxStringSortAscending(wxString* s1, wxString* s2)
2193 {
2194 return wxStrcmp(s1->c_str(), s2->c_str());
2195 }
2196
2197 int wxStringSortDescending(wxString* s1, wxString* s2)
2198 {
2199 return -wxStrcmp(s1->c_str(), s2->c_str());
2200 }