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