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