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