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