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