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