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