]> git.saurik.com Git - wxWidgets.git/blob - src/common/string.cpp
fixed wxBase compilation (what was msgdlg.h doing in wxchar.cpp?)
[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 wxString wxString::FromAscii( char *ascii )
763 {
764 if (!ascii)
765 return wxEmptyString;
766
767 size_t len = strlen( ascii );
768 wxString res;
769 res.AllocBuffer( len );
770 wchar_t *dest = (wchar_t*)(const wchar_t*) res.c_str();
771
772 for (size_t i = 0; i < len+1; i++)
773 dest[i] = (wchar_t) ascii[i];
774
775 return res;
776 }
777
778 const wxCharBuffer wxString::ToAscii() const
779 {
780 if (IsNull())
781 return wxCharBuffer( (const char*)NULL );
782
783 size_t len = Len();
784 wxCharBuffer buffer( len ); // allocates len+1
785
786 char *dest = (char*)(const char*) buffer;
787
788 for (size_t i = 0; i < len+1; i++)
789 {
790 if (m_pchData[i] > 127)
791 dest[i] = '_';
792 else
793 dest[i] = (char) m_pchData[i];
794 }
795
796 return buffer;
797 }
798 #endif
799
800 // ---------------------------------------------------------------------------
801 // simple sub-string extraction
802 // ---------------------------------------------------------------------------
803
804 // helper function: clone the data attached to this string
805 bool wxString::AllocCopy(wxString& dest, int nCopyLen, int nCopyIndex) const
806 {
807 if ( nCopyLen == 0 ) {
808 dest.Init();
809 }
810 else {
811 if ( !dest.AllocBuffer(nCopyLen) ) {
812 // allocation failure handled by caller
813 return FALSE;
814 }
815 memcpy(dest.m_pchData, m_pchData + nCopyIndex, nCopyLen*sizeof(wxChar));
816 }
817 return TRUE;
818 }
819
820 // extract string of length nCount starting at nFirst
821 wxString wxString::Mid(size_t nFirst, size_t nCount) const
822 {
823 wxStringData *pData = GetStringData();
824 size_t nLen = pData->nDataLength;
825
826 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
827 if ( nCount == wxSTRING_MAXLEN )
828 {
829 nCount = nLen - nFirst;
830 }
831
832 // out-of-bounds requests return sensible things
833 if ( nFirst + nCount > nLen )
834 {
835 nCount = nLen - nFirst;
836 }
837
838 if ( nFirst > nLen )
839 {
840 // AllocCopy() will return empty string
841 nCount = 0;
842 }
843
844 wxString dest;
845 if ( !AllocCopy(dest, nCount, nFirst) ) {
846 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
847 }
848
849 return dest;
850 }
851
852 // check that the tring starts with prefix and return the rest of the string
853 // in the provided pointer if it is not NULL, otherwise return FALSE
854 bool wxString::StartsWith(const wxChar *prefix, wxString *rest) const
855 {
856 wxASSERT_MSG( prefix, _T("invalid parameter in wxString::StartsWith") );
857
858 // first check if the beginning of the string matches the prefix: note
859 // that we don't have to check that we don't run out of this string as
860 // when we reach the terminating NUL, either prefix string ends too (and
861 // then it's ok) or we break out of the loop because there is no match
862 const wxChar *p = c_str();
863 while ( *prefix )
864 {
865 if ( *prefix++ != *p++ )
866 {
867 // no match
868 return FALSE;
869 }
870 }
871
872 if ( rest )
873 {
874 // put the rest of the string into provided pointer
875 *rest = p;
876 }
877
878 return TRUE;
879 }
880
881 // extract nCount last (rightmost) characters
882 wxString wxString::Right(size_t nCount) const
883 {
884 if ( nCount > (size_t)GetStringData()->nDataLength )
885 nCount = GetStringData()->nDataLength;
886
887 wxString dest;
888 if ( !AllocCopy(dest, nCount, GetStringData()->nDataLength - nCount) ) {
889 wxFAIL_MSG( _T("out of memory in wxString::Right") );
890 }
891 return dest;
892 }
893
894 // get all characters after the last occurence of ch
895 // (returns the whole string if ch not found)
896 wxString wxString::AfterLast(wxChar ch) const
897 {
898 wxString str;
899 int iPos = Find(ch, TRUE);
900 if ( iPos == wxNOT_FOUND )
901 str = *this;
902 else
903 str = c_str() + iPos + 1;
904
905 return str;
906 }
907
908 // extract nCount first (leftmost) characters
909 wxString wxString::Left(size_t nCount) const
910 {
911 if ( nCount > (size_t)GetStringData()->nDataLength )
912 nCount = GetStringData()->nDataLength;
913
914 wxString dest;
915 if ( !AllocCopy(dest, nCount, 0) ) {
916 wxFAIL_MSG( _T("out of memory in wxString::Left") );
917 }
918 return dest;
919 }
920
921 // get all characters before the first occurence of ch
922 // (returns the whole string if ch not found)
923 wxString wxString::BeforeFirst(wxChar ch) const
924 {
925 wxString str;
926 for ( const wxChar *pc = m_pchData; *pc != wxT('\0') && *pc != ch; pc++ )
927 str += *pc;
928
929 return str;
930 }
931
932 /// get all characters before the last occurence of ch
933 /// (returns empty string if ch not found)
934 wxString wxString::BeforeLast(wxChar ch) const
935 {
936 wxString str;
937 int iPos = Find(ch, TRUE);
938 if ( iPos != wxNOT_FOUND && iPos != 0 )
939 str = wxString(c_str(), iPos);
940
941 return str;
942 }
943
944 /// get all characters after the first occurence of ch
945 /// (returns empty string if ch not found)
946 wxString wxString::AfterFirst(wxChar ch) const
947 {
948 wxString str;
949 int iPos = Find(ch);
950 if ( iPos != wxNOT_FOUND )
951 str = c_str() + iPos + 1;
952
953 return str;
954 }
955
956 // replace first (or all) occurences of some substring with another one
957 size_t wxString::Replace(const wxChar *szOld, const wxChar *szNew, bool bReplaceAll)
958 {
959 size_t uiCount = 0; // count of replacements made
960
961 size_t uiOldLen = wxStrlen(szOld);
962
963 wxString strTemp;
964 const wxChar *pCurrent = m_pchData;
965 const wxChar *pSubstr;
966 while ( *pCurrent != wxT('\0') ) {
967 pSubstr = wxStrstr(pCurrent, szOld);
968 if ( pSubstr == NULL ) {
969 // strTemp is unused if no replacements were made, so avoid the copy
970 if ( uiCount == 0 )
971 return 0;
972
973 strTemp += pCurrent; // copy the rest
974 break; // exit the loop
975 }
976 else {
977 // take chars before match
978 if ( !strTemp.ConcatSelf(pSubstr - pCurrent, pCurrent) ) {
979 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
980 return 0;
981 }
982 strTemp += szNew;
983 pCurrent = pSubstr + uiOldLen; // restart after match
984
985 uiCount++;
986
987 // stop now?
988 if ( !bReplaceAll ) {
989 strTemp += pCurrent; // copy the rest
990 break; // exit the loop
991 }
992 }
993 }
994
995 // only done if there were replacements, otherwise would have returned above
996 *this = strTemp;
997
998 return uiCount;
999 }
1000
1001 bool wxString::IsAscii() const
1002 {
1003 const wxChar *s = (const wxChar*) *this;
1004 while(*s){
1005 if(!isascii(*s)) return(FALSE);
1006 s++;
1007 }
1008 return(TRUE);
1009 }
1010
1011 bool wxString::IsWord() const
1012 {
1013 const wxChar *s = (const wxChar*) *this;
1014 while(*s){
1015 if(!wxIsalpha(*s)) return(FALSE);
1016 s++;
1017 }
1018 return(TRUE);
1019 }
1020
1021 bool wxString::IsNumber() const
1022 {
1023 const wxChar *s = (const wxChar*) *this;
1024 if (wxStrlen(s))
1025 if ((s[0] == '-') || (s[0] == '+')) s++;
1026 while(*s){
1027 if(!wxIsdigit(*s)) return(FALSE);
1028 s++;
1029 }
1030 return(TRUE);
1031 }
1032
1033 wxString wxString::Strip(stripType w) const
1034 {
1035 wxString s = *this;
1036 if ( w & leading ) s.Trim(FALSE);
1037 if ( w & trailing ) s.Trim(TRUE);
1038 return s;
1039 }
1040
1041 // ---------------------------------------------------------------------------
1042 // case conversion
1043 // ---------------------------------------------------------------------------
1044
1045 wxString& wxString::MakeUpper()
1046 {
1047 if ( !CopyBeforeWrite() ) {
1048 wxFAIL_MSG( _T("out of memory in wxString::MakeUpper") );
1049 return *this;
1050 }
1051
1052 for ( wxChar *p = m_pchData; *p; p++ )
1053 *p = (wxChar)wxToupper(*p);
1054
1055 return *this;
1056 }
1057
1058 wxString& wxString::MakeLower()
1059 {
1060 if ( !CopyBeforeWrite() ) {
1061 wxFAIL_MSG( _T("out of memory in wxString::MakeLower") );
1062 return *this;
1063 }
1064
1065 for ( wxChar *p = m_pchData; *p; p++ )
1066 *p = (wxChar)wxTolower(*p);
1067
1068 return *this;
1069 }
1070
1071 // ---------------------------------------------------------------------------
1072 // trimming and padding
1073 // ---------------------------------------------------------------------------
1074
1075 // some compilers (VC++ 6.0 not to name them) return TRUE for a call to
1076 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1077 // live with this by checking that the character is a 7 bit one - even if this
1078 // may fail to detect some spaces (I don't know if Unicode doesn't have
1079 // space-like symbols somewhere except in the first 128 chars), it is arguably
1080 // still better than trimming away accented letters
1081 inline int wxSafeIsspace(wxChar ch) { return (ch < 127) && wxIsspace(ch); }
1082
1083 // trims spaces (in the sense of isspace) from left or right side
1084 wxString& wxString::Trim(bool bFromRight)
1085 {
1086 // first check if we're going to modify the string at all
1087 if ( !IsEmpty() &&
1088 (
1089 (bFromRight && wxSafeIsspace(GetChar(Len() - 1))) ||
1090 (!bFromRight && wxSafeIsspace(GetChar(0u)))
1091 )
1092 )
1093 {
1094 // ok, there is at least one space to trim
1095 if ( !CopyBeforeWrite() ) {
1096 wxFAIL_MSG( _T("out of memory in wxString::Trim") );
1097 return *this;
1098 }
1099
1100 if ( bFromRight )
1101 {
1102 // find last non-space character
1103 wxChar *psz = m_pchData + GetStringData()->nDataLength - 1;
1104 while ( wxSafeIsspace(*psz) && (psz >= m_pchData) )
1105 psz--;
1106
1107 // truncate at trailing space start
1108 *++psz = wxT('\0');
1109 GetStringData()->nDataLength = psz - m_pchData;
1110 }
1111 else
1112 {
1113 // find first non-space character
1114 const wxChar *psz = m_pchData;
1115 while ( wxSafeIsspace(*psz) )
1116 psz++;
1117
1118 // fix up data and length
1119 int nDataLength = GetStringData()->nDataLength - (psz - (const wxChar*) m_pchData);
1120 memmove(m_pchData, psz, (nDataLength + 1)*sizeof(wxChar));
1121 GetStringData()->nDataLength = nDataLength;
1122 }
1123 }
1124
1125 return *this;
1126 }
1127
1128 // adds nCount characters chPad to the string from either side
1129 wxString& wxString::Pad(size_t nCount, wxChar chPad, bool bFromRight)
1130 {
1131 wxString s(chPad, nCount);
1132
1133 if ( bFromRight )
1134 *this += s;
1135 else
1136 {
1137 s += *this;
1138 *this = s;
1139 }
1140
1141 return *this;
1142 }
1143
1144 // truncate the string
1145 wxString& wxString::Truncate(size_t uiLen)
1146 {
1147 if ( uiLen < Len() ) {
1148 if ( !CopyBeforeWrite() ) {
1149 wxFAIL_MSG( _T("out of memory in wxString::Truncate") );
1150 return *this;
1151 }
1152
1153 *(m_pchData + uiLen) = wxT('\0');
1154 GetStringData()->nDataLength = uiLen;
1155 }
1156 //else: nothing to do, string is already short enough
1157
1158 return *this;
1159 }
1160
1161 // ---------------------------------------------------------------------------
1162 // finding (return wxNOT_FOUND if not found and index otherwise)
1163 // ---------------------------------------------------------------------------
1164
1165 // find a character
1166 int wxString::Find(wxChar ch, bool bFromEnd) const
1167 {
1168 const wxChar *psz = bFromEnd ? wxStrrchr(m_pchData, ch) : wxStrchr(m_pchData, ch);
1169
1170 return (psz == NULL) ? wxNOT_FOUND : psz - (const wxChar*) m_pchData;
1171 }
1172
1173 // find a sub-string (like strstr)
1174 int wxString::Find(const wxChar *pszSub) const
1175 {
1176 const wxChar *psz = wxStrstr(m_pchData, pszSub);
1177
1178 return (psz == NULL) ? wxNOT_FOUND : psz - (const wxChar*) m_pchData;
1179 }
1180
1181 // ----------------------------------------------------------------------------
1182 // conversion to numbers
1183 // ----------------------------------------------------------------------------
1184
1185 bool wxString::ToLong(long *val, int base) const
1186 {
1187 wxCHECK_MSG( val, FALSE, _T("NULL pointer in wxString::ToLong") );
1188 wxASSERT_MSG( !base || (base > 1 && base <= 36), _T("invalid base") );
1189
1190 const wxChar *start = c_str();
1191 wxChar *end;
1192 *val = wxStrtol(start, &end, base);
1193
1194 // return TRUE only if scan was stopped by the terminating NUL and if the
1195 // string was not empty to start with
1196 return !*end && (end != start);
1197 }
1198
1199 bool wxString::ToULong(unsigned long *val, int base) const
1200 {
1201 wxCHECK_MSG( val, FALSE, _T("NULL pointer in wxString::ToULong") );
1202 wxASSERT_MSG( !base || (base > 1 && base <= 36), _T("invalid base") );
1203
1204 const wxChar *start = c_str();
1205 wxChar *end;
1206 *val = wxStrtoul(start, &end, base);
1207
1208 // return TRUE only if scan was stopped by the terminating NUL and if the
1209 // string was not empty to start with
1210 return !*end && (end != start);
1211 }
1212
1213 bool wxString::ToDouble(double *val) const
1214 {
1215 wxCHECK_MSG( val, FALSE, _T("NULL pointer in wxString::ToDouble") );
1216
1217 const wxChar *start = c_str();
1218 wxChar *end;
1219 *val = wxStrtod(start, &end);
1220
1221 // return TRUE only if scan was stopped by the terminating NUL and if the
1222 // string was not empty to start with
1223 return !*end && (end != start);
1224 }
1225
1226 // ---------------------------------------------------------------------------
1227 // formatted output
1228 // ---------------------------------------------------------------------------
1229
1230 /* static */
1231 wxString wxString::Format(const wxChar *pszFormat, ...)
1232 {
1233 va_list argptr;
1234 va_start(argptr, pszFormat);
1235
1236 wxString s;
1237 s.PrintfV(pszFormat, argptr);
1238
1239 va_end(argptr);
1240
1241 return s;
1242 }
1243
1244 /* static */
1245 wxString wxString::FormatV(const wxChar *pszFormat, va_list argptr)
1246 {
1247 wxString s;
1248 s.PrintfV(pszFormat, argptr);
1249 return s;
1250 }
1251
1252 int wxString::Printf(const wxChar *pszFormat, ...)
1253 {
1254 va_list argptr;
1255 va_start(argptr, pszFormat);
1256
1257 int iLen = PrintfV(pszFormat, argptr);
1258
1259 va_end(argptr);
1260
1261 return iLen;
1262 }
1263
1264 int wxString::PrintfV(const wxChar* pszFormat, va_list argptr)
1265 {
1266 #if wxUSE_EXPERIMENTAL_PRINTF
1267 // the new implementation
1268
1269 // buffer to avoid dynamic memory allocation each time for small strings
1270 char szScratch[1024];
1271
1272 Reinit();
1273 for (size_t n = 0; pszFormat[n]; n++)
1274 if (pszFormat[n] == wxT('%')) {
1275 static char s_szFlags[256] = "%";
1276 size_t flagofs = 1;
1277 bool adj_left = FALSE, in_prec = FALSE,
1278 prec_dot = FALSE, done = FALSE;
1279 int ilen = 0;
1280 size_t min_width = 0, max_width = wxSTRING_MAXLEN;
1281 do {
1282 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1283 switch (pszFormat[++n]) {
1284 case wxT('\0'):
1285 done = TRUE;
1286 break;
1287 case wxT('%'):
1288 *this += wxT('%');
1289 done = TRUE;
1290 break;
1291 case wxT('#'):
1292 case wxT('0'):
1293 case wxT(' '):
1294 case wxT('+'):
1295 case wxT('\''):
1296 CHECK_PREC
1297 s_szFlags[flagofs++] = pszFormat[n];
1298 break;
1299 case wxT('-'):
1300 CHECK_PREC
1301 adj_left = TRUE;
1302 s_szFlags[flagofs++] = pszFormat[n];
1303 break;
1304 case wxT('.'):
1305 CHECK_PREC
1306 in_prec = TRUE;
1307 prec_dot = FALSE;
1308 max_width = 0;
1309 // dot will be auto-added to s_szFlags if non-negative number follows
1310 break;
1311 case wxT('h'):
1312 ilen = -1;
1313 CHECK_PREC
1314 s_szFlags[flagofs++] = pszFormat[n];
1315 break;
1316 case wxT('l'):
1317 ilen = 1;
1318 CHECK_PREC
1319 s_szFlags[flagofs++] = pszFormat[n];
1320 break;
1321 case wxT('q'):
1322 case wxT('L'):
1323 ilen = 2;
1324 CHECK_PREC
1325 s_szFlags[flagofs++] = pszFormat[n];
1326 break;
1327 case wxT('Z'):
1328 ilen = 3;
1329 CHECK_PREC
1330 s_szFlags[flagofs++] = pszFormat[n];
1331 break;
1332 case wxT('*'):
1333 {
1334 int len = va_arg(argptr, int);
1335 if (in_prec) {
1336 if (len<0) break;
1337 CHECK_PREC
1338 max_width = len;
1339 } else {
1340 if (len<0) {
1341 adj_left = !adj_left;
1342 s_szFlags[flagofs++] = '-';
1343 len = -len;
1344 }
1345 min_width = len;
1346 }
1347 flagofs += ::sprintf(s_szFlags+flagofs,"%d",len);
1348 }
1349 break;
1350 case wxT('1'): case wxT('2'): case wxT('3'):
1351 case wxT('4'): case wxT('5'): case wxT('6'):
1352 case wxT('7'): case wxT('8'): case wxT('9'):
1353 {
1354 int len = 0;
1355 CHECK_PREC
1356 while ((pszFormat[n]>=wxT('0')) && (pszFormat[n]<=wxT('9'))) {
1357 s_szFlags[flagofs++] = pszFormat[n];
1358 len = len*10 + (pszFormat[n] - wxT('0'));
1359 n++;
1360 }
1361 if (in_prec) max_width = len;
1362 else min_width = len;
1363 n--; // the main loop pre-increments n again
1364 }
1365 break;
1366 case wxT('d'):
1367 case wxT('i'):
1368 case wxT('o'):
1369 case wxT('u'):
1370 case wxT('x'):
1371 case wxT('X'):
1372 CHECK_PREC
1373 s_szFlags[flagofs++] = pszFormat[n];
1374 s_szFlags[flagofs] = '\0';
1375 if (ilen == 0 ) {
1376 int val = va_arg(argptr, int);
1377 ::sprintf(szScratch, s_szFlags, val);
1378 }
1379 else if (ilen == -1) {
1380 short int val = va_arg(argptr, short int);
1381 ::sprintf(szScratch, s_szFlags, val);
1382 }
1383 else if (ilen == 1) {
1384 long int val = va_arg(argptr, long int);
1385 ::sprintf(szScratch, s_szFlags, val);
1386 }
1387 else if (ilen == 2) {
1388 #if SIZEOF_LONG_LONG
1389 long long int val = va_arg(argptr, long long int);
1390 ::sprintf(szScratch, s_szFlags, val);
1391 #else
1392 long int val = va_arg(argptr, long int);
1393 ::sprintf(szScratch, s_szFlags, val);
1394 #endif
1395 }
1396 else if (ilen == 3) {
1397 size_t val = va_arg(argptr, size_t);
1398 ::sprintf(szScratch, s_szFlags, val);
1399 }
1400 *this += wxString(szScratch);
1401 done = TRUE;
1402 break;
1403 case wxT('e'):
1404 case wxT('E'):
1405 case wxT('f'):
1406 case wxT('g'):
1407 case wxT('G'):
1408 CHECK_PREC
1409 s_szFlags[flagofs++] = pszFormat[n];
1410 s_szFlags[flagofs] = '\0';
1411 if (ilen == 2) {
1412 long double val = va_arg(argptr, long double);
1413 ::sprintf(szScratch, s_szFlags, val);
1414 } else {
1415 double val = va_arg(argptr, double);
1416 ::sprintf(szScratch, s_szFlags, val);
1417 }
1418 *this += wxString(szScratch);
1419 done = TRUE;
1420 break;
1421 case wxT('p'):
1422 {
1423 void *val = va_arg(argptr, void *);
1424 CHECK_PREC
1425 s_szFlags[flagofs++] = pszFormat[n];
1426 s_szFlags[flagofs] = '\0';
1427 ::sprintf(szScratch, s_szFlags, val);
1428 *this += wxString(szScratch);
1429 done = TRUE;
1430 }
1431 break;
1432 case wxT('c'):
1433 {
1434 wxChar val = va_arg(argptr, int);
1435 // we don't need to honor padding here, do we?
1436 *this += val;
1437 done = TRUE;
1438 }
1439 break;
1440 case wxT('s'):
1441 if (ilen == -1) {
1442 // wx extension: we'll let %hs mean non-Unicode strings
1443 char *val = va_arg(argptr, char *);
1444 #if wxUSE_UNICODE
1445 // ASCII->Unicode constructor handles max_width right
1446 wxString s(val, wxConvLibc, max_width);
1447 #else
1448 size_t len = wxSTRING_MAXLEN;
1449 if (val) {
1450 for (len = 0; val[len] && (len<max_width); len++);
1451 } else val = wxT("(null)");
1452 wxString s(val, len);
1453 #endif
1454 if (s.Len() < min_width)
1455 s.Pad(min_width - s.Len(), wxT(' '), adj_left);
1456 *this += s;
1457 } else {
1458 wxChar *val = va_arg(argptr, wxChar *);
1459 size_t len = wxSTRING_MAXLEN;
1460 if (val) {
1461 for (len = 0; val[len] && (len<max_width); len++);
1462 } else val = wxT("(null)");
1463 wxString s(val, len);
1464 if (s.Len() < min_width)
1465 s.Pad(min_width - s.Len(), wxT(' '), adj_left);
1466 *this += s;
1467 }
1468 done = TRUE;
1469 break;
1470 case wxT('n'):
1471 if (ilen == 0) {
1472 int *val = va_arg(argptr, int *);
1473 *val = Len();
1474 }
1475 else if (ilen == -1) {
1476 short int *val = va_arg(argptr, short int *);
1477 *val = Len();
1478 }
1479 else if (ilen >= 1) {
1480 long int *val = va_arg(argptr, long int *);
1481 *val = Len();
1482 }
1483 done = TRUE;
1484 break;
1485 default:
1486 if (wxIsalpha(pszFormat[n]))
1487 // probably some flag not taken care of here yet
1488 s_szFlags[flagofs++] = pszFormat[n];
1489 else {
1490 // bad format
1491 *this += wxT('%'); // just to pass the glibc tst-printf.c
1492 n--;
1493 done = TRUE;
1494 }
1495 break;
1496 }
1497 #undef CHECK_PREC
1498 } while (!done);
1499 } else *this += pszFormat[n];
1500
1501 #else
1502 // buffer to avoid dynamic memory allocation each time for small strings
1503 char szScratch[1024];
1504
1505 // NB: wxVsnprintf() may return either less than the buffer size or -1 if
1506 // there is not enough place depending on implementation
1507 int iLen = wxVsnprintfA(szScratch, WXSIZEOF(szScratch), (char *)pszFormat, argptr);
1508 if ( iLen != -1 ) {
1509 // the whole string is in szScratch
1510 *this = szScratch;
1511 }
1512 else {
1513 bool outOfMemory = FALSE;
1514 int size = 2*WXSIZEOF(szScratch);
1515 while ( !outOfMemory ) {
1516 char *buf = GetWriteBuf(size);
1517 if ( buf )
1518 iLen = wxVsnprintfA(buf, size, pszFormat, argptr);
1519 else
1520 outOfMemory = TRUE;
1521
1522 UngetWriteBuf();
1523
1524 if ( iLen != -1 ) {
1525 // ok, there was enough space
1526 break;
1527 }
1528
1529 // still not enough, double it again
1530 size *= 2;
1531 }
1532
1533 if ( outOfMemory ) {
1534 // out of memory
1535 return -1;
1536 }
1537 }
1538 #endif // wxUSE_EXPERIMENTAL_PRINTF/!wxUSE_EXPERIMENTAL_PRINTF
1539
1540 return Len();
1541 }
1542
1543 // ----------------------------------------------------------------------------
1544 // misc other operations
1545 // ----------------------------------------------------------------------------
1546
1547 // returns TRUE if the string matches the pattern which may contain '*' and
1548 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1549 // of them)
1550 bool wxString::Matches(const wxChar *pszMask) const
1551 {
1552 // I disable this code as it doesn't seem to be faster (in fact, it seems
1553 // to be much slower) than the old, hand-written code below and using it
1554 // here requires always linking with libregex even if the user code doesn't
1555 // use it
1556 #if 0 // wxUSE_REGEX
1557 // first translate the shell-like mask into a regex
1558 wxString pattern;
1559 pattern.reserve(wxStrlen(pszMask));
1560
1561 pattern += _T('^');
1562 while ( *pszMask )
1563 {
1564 switch ( *pszMask )
1565 {
1566 case _T('?'):
1567 pattern += _T('.');
1568 break;
1569
1570 case _T('*'):
1571 pattern += _T(".*");
1572 break;
1573
1574 case _T('^'):
1575 case _T('.'):
1576 case _T('$'):
1577 case _T('('):
1578 case _T(')'):
1579 case _T('|'):
1580 case _T('+'):
1581 case _T('\\'):
1582 // these characters are special in a RE, quote them
1583 // (however note that we don't quote '[' and ']' to allow
1584 // using them for Unix shell like matching)
1585 pattern += _T('\\');
1586 // fall through
1587
1588 default:
1589 pattern += *pszMask;
1590 }
1591
1592 pszMask++;
1593 }
1594 pattern += _T('$');
1595
1596 // and now use it
1597 return wxRegEx(pattern, wxRE_NOSUB | wxRE_EXTENDED).Matches(c_str());
1598 #else // !wxUSE_REGEX
1599 // TODO: this is, of course, awfully inefficient...
1600
1601 // the char currently being checked
1602 const wxChar *pszTxt = c_str();
1603
1604 // the last location where '*' matched
1605 const wxChar *pszLastStarInText = NULL;
1606 const wxChar *pszLastStarInMask = NULL;
1607
1608 match:
1609 for ( ; *pszMask != wxT('\0'); pszMask++, pszTxt++ ) {
1610 switch ( *pszMask ) {
1611 case wxT('?'):
1612 if ( *pszTxt == wxT('\0') )
1613 return FALSE;
1614
1615 // pszTxt and pszMask will be incremented in the loop statement
1616
1617 break;
1618
1619 case wxT('*'):
1620 {
1621 // remember where we started to be able to backtrack later
1622 pszLastStarInText = pszTxt;
1623 pszLastStarInMask = pszMask;
1624
1625 // ignore special chars immediately following this one
1626 // (should this be an error?)
1627 while ( *pszMask == wxT('*') || *pszMask == wxT('?') )
1628 pszMask++;
1629
1630 // if there is nothing more, match
1631 if ( *pszMask == wxT('\0') )
1632 return TRUE;
1633
1634 // are there any other metacharacters in the mask?
1635 size_t uiLenMask;
1636 const wxChar *pEndMask = wxStrpbrk(pszMask, wxT("*?"));
1637
1638 if ( pEndMask != NULL ) {
1639 // we have to match the string between two metachars
1640 uiLenMask = pEndMask - pszMask;
1641 }
1642 else {
1643 // we have to match the remainder of the string
1644 uiLenMask = wxStrlen(pszMask);
1645 }
1646
1647 wxString strToMatch(pszMask, uiLenMask);
1648 const wxChar* pMatch = wxStrstr(pszTxt, strToMatch);
1649 if ( pMatch == NULL )
1650 return FALSE;
1651
1652 // -1 to compensate "++" in the loop
1653 pszTxt = pMatch + uiLenMask - 1;
1654 pszMask += uiLenMask - 1;
1655 }
1656 break;
1657
1658 default:
1659 if ( *pszMask != *pszTxt )
1660 return FALSE;
1661 break;
1662 }
1663 }
1664
1665 // match only if nothing left
1666 if ( *pszTxt == wxT('\0') )
1667 return TRUE;
1668
1669 // if we failed to match, backtrack if we can
1670 if ( pszLastStarInText ) {
1671 pszTxt = pszLastStarInText + 1;
1672 pszMask = pszLastStarInMask;
1673
1674 pszLastStarInText = NULL;
1675
1676 // don't bother resetting pszLastStarInMask, it's unnecessary
1677
1678 goto match;
1679 }
1680
1681 return FALSE;
1682 #endif // wxUSE_REGEX/!wxUSE_REGEX
1683 }
1684
1685 // Count the number of chars
1686 int wxString::Freq(wxChar ch) const
1687 {
1688 int count = 0;
1689 int len = Len();
1690 for (int i = 0; i < len; i++)
1691 {
1692 if (GetChar(i) == ch)
1693 count ++;
1694 }
1695 return count;
1696 }
1697
1698 // convert to upper case, return the copy of the string
1699 wxString wxString::Upper() const
1700 { wxString s(*this); return s.MakeUpper(); }
1701
1702 // convert to lower case, return the copy of the string
1703 wxString wxString::Lower() const { wxString s(*this); return s.MakeLower(); }
1704
1705 int wxString::sprintf(const wxChar *pszFormat, ...)
1706 {
1707 va_list argptr;
1708 va_start(argptr, pszFormat);
1709 int iLen = PrintfV(pszFormat, argptr);
1710 va_end(argptr);
1711 return iLen;
1712 }
1713
1714 // ---------------------------------------------------------------------------
1715 // standard C++ library string functions
1716 // ---------------------------------------------------------------------------
1717
1718 #ifdef wxSTD_STRING_COMPATIBILITY
1719
1720 void wxString::resize(size_t nSize, wxChar ch)
1721 {
1722 size_t len = length();
1723
1724 if ( nSize < len )
1725 {
1726 Truncate(nSize);
1727 }
1728 else if ( nSize > len )
1729 {
1730 *this += wxString(ch, nSize - len);
1731 }
1732 //else: we have exactly the specified length, nothing to do
1733 }
1734
1735 void wxString::swap(wxString& str)
1736 {
1737 // this is slightly less efficient than fiddling with m_pchData directly,
1738 // but it is still quite efficient as we don't copy the string here because
1739 // ref count always stays positive
1740 wxString tmp = str;
1741 str = *this;
1742 *this = tmp;
1743 }
1744
1745 wxString& wxString::insert(size_t nPos, const wxString& str)
1746 {
1747 wxASSERT( str.GetStringData()->IsValid() );
1748 wxASSERT( nPos <= Len() );
1749
1750 if ( !str.IsEmpty() ) {
1751 wxString strTmp;
1752 wxChar *pc = strTmp.GetWriteBuf(Len() + str.Len());
1753 wxStrncpy(pc, c_str(), nPos);
1754 wxStrcpy(pc + nPos, str);
1755 wxStrcpy(pc + nPos + str.Len(), c_str() + nPos);
1756 strTmp.UngetWriteBuf();
1757 *this = strTmp;
1758 }
1759
1760 return *this;
1761 }
1762
1763 size_t wxString::find(const wxString& str, size_t nStart) const
1764 {
1765 wxASSERT( str.GetStringData()->IsValid() );
1766 wxASSERT( nStart <= Len() );
1767
1768 const wxChar *p = wxStrstr(c_str() + nStart, str);
1769
1770 return p == NULL ? npos : p - c_str();
1771 }
1772
1773 // VC++ 1.5 can't cope with the default argument in the header.
1774 #if !defined(__VISUALC__) || defined(__WIN32__)
1775 size_t wxString::find(const wxChar* sz, size_t nStart, size_t n) const
1776 {
1777 return find(wxString(sz, n), nStart);
1778 }
1779 #endif // VC++ 1.5
1780
1781 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1782 #if !defined(__BORLANDC__)
1783 size_t wxString::find(wxChar ch, size_t nStart) const
1784 {
1785 wxASSERT( nStart <= Len() );
1786
1787 const wxChar *p = wxStrchr(c_str() + nStart, ch);
1788
1789 return p == NULL ? npos : p - c_str();
1790 }
1791 #endif
1792
1793 size_t wxString::rfind(const wxString& str, size_t nStart) const
1794 {
1795 wxASSERT( str.GetStringData()->IsValid() );
1796 wxASSERT( nStart == npos || nStart <= Len() );
1797
1798 // TODO could be made much quicker than that
1799 const wxChar *p = c_str() + (nStart == npos ? Len() : nStart);
1800 while ( p >= c_str() + str.Len() ) {
1801 if ( wxStrncmp(p - str.Len(), str, str.Len()) == 0 )
1802 return p - str.Len() - c_str();
1803 p--;
1804 }
1805
1806 return npos;
1807 }
1808
1809 // VC++ 1.5 can't cope with the default argument in the header.
1810 #if !defined(__VISUALC__) || defined(__WIN32__)
1811 size_t wxString::rfind(const wxChar* sz, size_t nStart, size_t n) const
1812 {
1813 return rfind(wxString(sz, n == npos ? wxSTRING_MAXLEN : n), nStart);
1814 }
1815
1816 size_t wxString::rfind(wxChar ch, size_t nStart) const
1817 {
1818 if ( nStart == npos )
1819 {
1820 nStart = Len();
1821 }
1822 else
1823 {
1824 wxASSERT( nStart <= Len() );
1825 }
1826
1827 const wxChar *p = wxStrrchr(c_str(), ch);
1828
1829 if ( p == NULL )
1830 return npos;
1831
1832 size_t result = p - c_str();
1833 return ( result > nStart ) ? npos : result;
1834 }
1835 #endif // VC++ 1.5
1836
1837 size_t wxString::find_first_of(const wxChar* sz, size_t nStart) const
1838 {
1839 const wxChar *start = c_str() + nStart;
1840 const wxChar *firstOf = wxStrpbrk(start, sz);
1841 if ( firstOf )
1842 return firstOf - c_str();
1843 else
1844 return npos;
1845 }
1846
1847 size_t wxString::find_last_of(const wxChar* sz, size_t nStart) const
1848 {
1849 if ( nStart == npos )
1850 {
1851 nStart = Len();
1852 }
1853 else
1854 {
1855 wxASSERT( nStart <= Len() );
1856 }
1857
1858 for ( const wxChar *p = c_str() + length() - 1; p >= c_str(); p-- )
1859 {
1860 if ( wxStrchr(sz, *p) )
1861 return p - c_str();
1862 }
1863
1864 return npos;
1865 }
1866
1867 size_t wxString::find_first_not_of(const wxChar* sz, size_t nStart) const
1868 {
1869 if ( nStart == npos )
1870 {
1871 nStart = Len();
1872 }
1873 else
1874 {
1875 wxASSERT( nStart <= Len() );
1876 }
1877
1878 size_t nAccept = wxStrspn(c_str() + nStart, sz);
1879 if ( nAccept >= length() - nStart )
1880 return npos;
1881 else
1882 return nAccept;
1883 }
1884
1885 size_t wxString::find_first_not_of(wxChar ch, size_t nStart) const
1886 {
1887 wxASSERT( nStart <= Len() );
1888
1889 for ( const wxChar *p = c_str() + nStart; *p; p++ )
1890 {
1891 if ( *p != ch )
1892 return p - c_str();
1893 }
1894
1895 return npos;
1896 }
1897
1898 size_t wxString::find_last_not_of(const wxChar* sz, size_t nStart) const
1899 {
1900 if ( nStart == npos )
1901 {
1902 nStart = Len();
1903 }
1904 else
1905 {
1906 wxASSERT( nStart <= Len() );
1907 }
1908
1909 for ( const wxChar *p = c_str() + nStart - 1; p >= c_str(); p-- )
1910 {
1911 if ( !wxStrchr(sz, *p) )
1912 return p - c_str();
1913 }
1914
1915 return npos;
1916 }
1917
1918 size_t wxString::find_last_not_of(wxChar ch, size_t nStart) const
1919 {
1920 if ( nStart == npos )
1921 {
1922 nStart = Len();
1923 }
1924 else
1925 {
1926 wxASSERT( nStart <= Len() );
1927 }
1928
1929 for ( const wxChar *p = c_str() + nStart - 1; p >= c_str(); p-- )
1930 {
1931 if ( *p != ch )
1932 return p - c_str();
1933 }
1934
1935 return npos;
1936 }
1937
1938 wxString& wxString::erase(size_t nStart, size_t nLen)
1939 {
1940 wxString strTmp(c_str(), nStart);
1941 if ( nLen != npos ) {
1942 wxASSERT( nStart + nLen <= Len() );
1943
1944 strTmp.append(c_str() + nStart + nLen);
1945 }
1946
1947 *this = strTmp;
1948 return *this;
1949 }
1950
1951 wxString& wxString::replace(size_t nStart, size_t nLen, const wxChar *sz)
1952 {
1953 wxASSERT_MSG( nStart + nLen <= Len(),
1954 _T("index out of bounds in wxString::replace") );
1955
1956 wxString strTmp;
1957 strTmp.Alloc(Len()); // micro optimisation to avoid multiple mem allocs
1958
1959 if ( nStart != 0 )
1960 strTmp.append(c_str(), nStart);
1961 strTmp << sz << c_str() + nStart + nLen;
1962
1963 *this = strTmp;
1964 return *this;
1965 }
1966
1967 wxString& wxString::replace(size_t nStart, size_t nLen, size_t nCount, wxChar ch)
1968 {
1969 return replace(nStart, nLen, wxString(ch, nCount));
1970 }
1971
1972 wxString& wxString::replace(size_t nStart, size_t nLen,
1973 const wxString& str, size_t nStart2, size_t nLen2)
1974 {
1975 return replace(nStart, nLen, str.substr(nStart2, nLen2));
1976 }
1977
1978 wxString& wxString::replace(size_t nStart, size_t nLen,
1979 const wxChar* sz, size_t nCount)
1980 {
1981 return replace(nStart, nLen, wxString(sz, nCount));
1982 }
1983
1984 #endif //std::string compatibility
1985
1986 // ============================================================================
1987 // ArrayString
1988 // ============================================================================
1989
1990 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1991 #define ARRAY_MAXSIZE_INCREMENT 4096
1992
1993 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1994 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1995 #endif
1996
1997 #define STRING(p) ((wxString *)(&(p)))
1998
1999 // ctor
2000 void wxArrayString::Init(bool autoSort)
2001 {
2002 m_nSize =
2003 m_nCount = 0;
2004 m_pItems = (wxChar **) NULL;
2005 m_autoSort = autoSort;
2006 }
2007
2008 // copy ctor
2009 wxArrayString::wxArrayString(const wxArrayString& src)
2010 {
2011 Init(src.m_autoSort);
2012
2013 *this = src;
2014 }
2015
2016 // assignment operator
2017 wxArrayString& wxArrayString::operator=(const wxArrayString& src)
2018 {
2019 if ( m_nSize > 0 )
2020 Clear();
2021
2022 Copy(src);
2023
2024 m_autoSort = src.m_autoSort;
2025
2026 return *this;
2027 }
2028
2029 void wxArrayString::Copy(const wxArrayString& src)
2030 {
2031 if ( src.m_nCount > ARRAY_DEFAULT_INITIAL_SIZE )
2032 Alloc(src.m_nCount);
2033
2034 for ( size_t n = 0; n < src.m_nCount; n++ )
2035 Add(src[n]);
2036 }
2037
2038 // grow the array
2039 void wxArrayString::Grow(size_t nIncrement)
2040 {
2041 // only do it if no more place
2042 if ( m_nCount == m_nSize ) {
2043 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2044 // be never resized!
2045 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2046 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2047 #endif
2048
2049 if ( m_nSize == 0 ) {
2050 // was empty, alloc some memory
2051 m_nSize = ARRAY_DEFAULT_INITIAL_SIZE;
2052 m_pItems = new wxChar *[m_nSize];
2053 }
2054 else {
2055 // otherwise when it's called for the first time, nIncrement would be 0
2056 // and the array would never be expanded
2057 // add 50% but not too much
2058 size_t ndefIncrement = m_nSize < ARRAY_DEFAULT_INITIAL_SIZE
2059 ? ARRAY_DEFAULT_INITIAL_SIZE : m_nSize >> 1;
2060 if ( ndefIncrement > ARRAY_MAXSIZE_INCREMENT )
2061 ndefIncrement = ARRAY_MAXSIZE_INCREMENT;
2062 if ( nIncrement < ndefIncrement )
2063 nIncrement = ndefIncrement;
2064 m_nSize += nIncrement;
2065 wxChar **pNew = new wxChar *[m_nSize];
2066
2067 // copy data to new location
2068 memcpy(pNew, m_pItems, m_nCount*sizeof(wxChar *));
2069
2070 // delete old memory (but do not release the strings!)
2071 wxDELETEA(m_pItems);
2072
2073 m_pItems = pNew;
2074 }
2075 }
2076 }
2077
2078 void wxArrayString::Free()
2079 {
2080 for ( size_t n = 0; n < m_nCount; n++ ) {
2081 STRING(m_pItems[n])->GetStringData()->Unlock();
2082 }
2083 }
2084
2085 // deletes all the strings from the list
2086 void wxArrayString::Empty()
2087 {
2088 Free();
2089
2090 m_nCount = 0;
2091 }
2092
2093 // as Empty, but also frees memory
2094 void wxArrayString::Clear()
2095 {
2096 Free();
2097
2098 m_nSize =
2099 m_nCount = 0;
2100
2101 wxDELETEA(m_pItems);
2102 }
2103
2104 // dtor
2105 wxArrayString::~wxArrayString()
2106 {
2107 Free();
2108
2109 wxDELETEA(m_pItems);
2110 }
2111
2112 // pre-allocates memory (frees the previous data!)
2113 void wxArrayString::Alloc(size_t nSize)
2114 {
2115 // only if old buffer was not big enough
2116 if ( nSize > m_nSize ) {
2117 Free();
2118 wxDELETEA(m_pItems);
2119 m_pItems = new wxChar *[nSize];
2120 m_nSize = nSize;
2121 }
2122
2123 m_nCount = 0;
2124 }
2125
2126 // minimizes the memory usage by freeing unused memory
2127 void wxArrayString::Shrink()
2128 {
2129 // only do it if we have some memory to free
2130 if( m_nCount < m_nSize ) {
2131 // allocates exactly as much memory as we need
2132 wxChar **pNew = new wxChar *[m_nCount];
2133
2134 // copy data to new location
2135 memcpy(pNew, m_pItems, m_nCount*sizeof(wxChar *));
2136 delete [] m_pItems;
2137 m_pItems = pNew;
2138 }
2139 }
2140
2141 // return a wxString[] as required for some control ctors.
2142 wxString* wxArrayString::GetStringArray() const
2143 {
2144 wxString *array = 0;
2145
2146 if( m_nCount > 0 )
2147 {
2148 array = new wxString[m_nCount];
2149 for( size_t i = 0; i < m_nCount; i++ )
2150 array[i] = m_pItems[i];
2151 }
2152
2153 return array;
2154 }
2155
2156 // searches the array for an item (forward or backwards)
2157 int wxArrayString::Index(const wxChar *sz, bool bCase, bool bFromEnd) const
2158 {
2159 if ( m_autoSort ) {
2160 // use binary search in the sorted array
2161 wxASSERT_MSG( bCase && !bFromEnd,
2162 wxT("search parameters ignored for auto sorted array") );
2163
2164 size_t i,
2165 lo = 0,
2166 hi = m_nCount;
2167 int res;
2168 while ( lo < hi ) {
2169 i = (lo + hi)/2;
2170
2171 res = wxStrcmp(sz, m_pItems[i]);
2172 if ( res < 0 )
2173 hi = i;
2174 else if ( res > 0 )
2175 lo = i + 1;
2176 else
2177 return i;
2178 }
2179
2180 return wxNOT_FOUND;
2181 }
2182 else {
2183 // use linear search in unsorted array
2184 if ( bFromEnd ) {
2185 if ( m_nCount > 0 ) {
2186 size_t ui = m_nCount;
2187 do {
2188 if ( STRING(m_pItems[--ui])->IsSameAs(sz, bCase) )
2189 return ui;
2190 }
2191 while ( ui != 0 );
2192 }
2193 }
2194 else {
2195 for( size_t ui = 0; ui < m_nCount; ui++ ) {
2196 if( STRING(m_pItems[ui])->IsSameAs(sz, bCase) )
2197 return ui;
2198 }
2199 }
2200 }
2201
2202 return wxNOT_FOUND;
2203 }
2204
2205 // add item at the end
2206 size_t wxArrayString::Add(const wxString& str, size_t nInsert)
2207 {
2208 if ( m_autoSort ) {
2209 // insert the string at the correct position to keep the array sorted
2210 size_t i,
2211 lo = 0,
2212 hi = m_nCount;
2213 int res;
2214 while ( lo < hi ) {
2215 i = (lo + hi)/2;
2216
2217 res = wxStrcmp(str, m_pItems[i]);
2218 if ( res < 0 )
2219 hi = i;
2220 else if ( res > 0 )
2221 lo = i + 1;
2222 else {
2223 lo = hi = i;
2224 break;
2225 }
2226 }
2227
2228 wxASSERT_MSG( lo == hi, wxT("binary search broken") );
2229
2230 Insert(str, lo, nInsert);
2231
2232 return (size_t)lo;
2233 }
2234 else {
2235 wxASSERT( str.GetStringData()->IsValid() );
2236
2237 Grow(nInsert);
2238
2239 for (size_t i = 0; i < nInsert; i++)
2240 {
2241 // the string data must not be deleted!
2242 str.GetStringData()->Lock();
2243
2244 // just append
2245 m_pItems[m_nCount + i] = (wxChar *)str.c_str(); // const_cast
2246 }
2247 size_t ret = m_nCount;
2248 m_nCount += nInsert;
2249 return ret;
2250 }
2251 }
2252
2253 // add item at the given position
2254 void wxArrayString::Insert(const wxString& str, size_t nIndex, size_t nInsert)
2255 {
2256 wxASSERT( str.GetStringData()->IsValid() );
2257
2258 wxCHECK_RET( nIndex <= m_nCount, wxT("bad index in wxArrayString::Insert") );
2259 wxCHECK_RET( m_nCount <= m_nCount + nInsert,
2260 wxT("array size overflow in wxArrayString::Insert") );
2261
2262 Grow(nInsert);
2263
2264 memmove(&m_pItems[nIndex + nInsert], &m_pItems[nIndex],
2265 (m_nCount - nIndex)*sizeof(wxChar *));
2266
2267 for (size_t i = 0; i < nInsert; i++)
2268 {
2269 str.GetStringData()->Lock();
2270 m_pItems[nIndex + i] = (wxChar *)str.c_str();
2271 }
2272 m_nCount += nInsert;
2273 }
2274
2275 // expand the array
2276 void wxArrayString::SetCount(size_t count)
2277 {
2278 Alloc(count);
2279
2280 wxString s;
2281 while ( m_nCount < count )
2282 m_pItems[m_nCount++] = (wxChar *)s.c_str();
2283 }
2284
2285 // removes item from array (by index)
2286 void wxArrayString::Remove(size_t nIndex, size_t nRemove)
2287 {
2288 wxCHECK_RET( nIndex < m_nCount, wxT("bad index in wxArrayString::Remove") );
2289 wxCHECK_RET( nIndex + nRemove <= m_nCount,
2290 wxT("removing too many elements in wxArrayString::Remove") );
2291
2292 // release our lock
2293 for (size_t i = 0; i < nRemove; i++)
2294 Item(nIndex + i).GetStringData()->Unlock();
2295
2296 memmove(&m_pItems[nIndex], &m_pItems[nIndex + nRemove],
2297 (m_nCount - nIndex - nRemove)*sizeof(wxChar *));
2298 m_nCount -= nRemove;
2299 }
2300
2301 // removes item from array (by value)
2302 void wxArrayString::Remove(const wxChar *sz)
2303 {
2304 int iIndex = Index(sz);
2305
2306 wxCHECK_RET( iIndex != wxNOT_FOUND,
2307 wxT("removing inexistent element in wxArrayString::Remove") );
2308
2309 Remove(iIndex);
2310 }
2311
2312 // ----------------------------------------------------------------------------
2313 // sorting
2314 // ----------------------------------------------------------------------------
2315
2316 // we can only sort one array at a time with the quick-sort based
2317 // implementation
2318 #if wxUSE_THREADS
2319 // need a critical section to protect access to gs_compareFunction and
2320 // gs_sortAscending variables
2321 static wxCriticalSection *gs_critsectStringSort = NULL;
2322
2323 // call this before the value of the global sort vars is changed/after
2324 // you're finished with them
2325 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2326 gs_critsectStringSort = new wxCriticalSection; \
2327 gs_critsectStringSort->Enter()
2328 #define END_SORT() gs_critsectStringSort->Leave(); \
2329 delete gs_critsectStringSort; \
2330 gs_critsectStringSort = NULL
2331 #else // !threads
2332 #define START_SORT()
2333 #define END_SORT()
2334 #endif // wxUSE_THREADS
2335
2336 // function to use for string comparaison
2337 static wxArrayString::CompareFunction gs_compareFunction = NULL;
2338
2339 // if we don't use the compare function, this flag tells us if we sort the
2340 // array in ascending or descending order
2341 static bool gs_sortAscending = TRUE;
2342
2343 // function which is called by quick sort
2344 extern "C" int LINKAGEMODE
2345 wxStringCompareFunction(const void *first, const void *second)
2346 {
2347 wxString *strFirst = (wxString *)first;
2348 wxString *strSecond = (wxString *)second;
2349
2350 if ( gs_compareFunction ) {
2351 return gs_compareFunction(*strFirst, *strSecond);
2352 }
2353 else {
2354 // maybe we should use wxStrcoll
2355 int result = wxStrcmp(strFirst->c_str(), strSecond->c_str());
2356
2357 return gs_sortAscending ? result : -result;
2358 }
2359 }
2360
2361 // sort array elements using passed comparaison function
2362 void wxArrayString::Sort(CompareFunction compareFunction)
2363 {
2364 START_SORT();
2365
2366 wxASSERT( !gs_compareFunction ); // must have been reset to NULL
2367 gs_compareFunction = compareFunction;
2368
2369 DoSort();
2370
2371 // reset it to NULL so that Sort(bool) will work the next time
2372 gs_compareFunction = NULL;
2373
2374 END_SORT();
2375 }
2376
2377 void wxArrayString::Sort(bool reverseOrder)
2378 {
2379 START_SORT();
2380
2381 wxASSERT( !gs_compareFunction ); // must have been reset to NULL
2382 gs_sortAscending = !reverseOrder;
2383
2384 DoSort();
2385
2386 END_SORT();
2387 }
2388
2389 void wxArrayString::DoSort()
2390 {
2391 wxCHECK_RET( !m_autoSort, wxT("can't use this method with sorted arrays") );
2392
2393 // just sort the pointers using qsort() - of course it only works because
2394 // wxString() *is* a pointer to its data
2395 qsort(m_pItems, m_nCount, sizeof(wxChar *), wxStringCompareFunction);
2396 }
2397
2398 bool wxArrayString::operator==(const wxArrayString& a) const
2399 {
2400 if ( m_nCount != a.m_nCount )
2401 return FALSE;
2402
2403 for ( size_t n = 0; n < m_nCount; n++ )
2404 {
2405 if ( Item(n) != a[n] )
2406 return FALSE;
2407 }
2408
2409 return TRUE;
2410 }
2411