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