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