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