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