]> git.saurik.com Git - wxWidgets.git/blob - src/common/string.cpp
"continue;" restored to prevent the app from going into infinite loop
[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 license
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 #endif
39
40 #include <ctype.h>
41 #include <string.h>
42 #include <stdlib.h>
43
44 #ifdef __SALFORDC__
45 #include <clib.h>
46 #endif
47
48 #if wxUSE_WCSRTOMBS
49 #include <wchar.h> // for wcsrtombs(), see comments where it's used
50 #endif // GNU
51
52 #ifdef WXSTRING_IS_WXOBJECT
53 IMPLEMENT_DYNAMIC_CLASS(wxString, wxObject)
54 #endif //WXSTRING_IS_WXOBJECT
55
56 // allocating extra space for each string consumes more memory but speeds up
57 // the concatenation operations (nLen is the current string's length)
58 // NB: EXTRA_ALLOC must be >= 0!
59 #define EXTRA_ALLOC (19 - nLen % 16)
60
61 // ---------------------------------------------------------------------------
62 // static class variables definition
63 // ---------------------------------------------------------------------------
64
65 #ifdef wxSTD_STRING_COMPATIBILITY
66 const size_t wxString::npos = wxSTRING_MAXLEN;
67 #endif // wxSTD_STRING_COMPATIBILITY
68
69 // ----------------------------------------------------------------------------
70 // static data
71 // ----------------------------------------------------------------------------
72
73 // for an empty string, GetStringData() will return this address: this
74 // structure has the same layout as wxStringData and it's data() method will
75 // return the empty string (dummy pointer)
76 static const struct
77 {
78 wxStringData data;
79 char dummy;
80 } g_strEmpty = { {-1, 0, 0}, '\0' };
81
82 // empty C style string: points to 'string data' byte of g_strEmpty
83 extern const char WXDLLEXPORT *g_szNul = &g_strEmpty.dummy;
84
85 // ----------------------------------------------------------------------------
86 // conditional compilation
87 // ----------------------------------------------------------------------------
88
89 // we want to find out if the current platform supports vsnprintf()-like
90 // function: for Unix this is done with configure, for Windows we test the
91 // compiler explicitly.
92 #ifdef __WXMSW__
93 #ifdef __VISUALC__
94 #define wxVsprintf _vsnprintf
95 #endif
96 #else // !Windows
97 #ifdef HAVE_VSNPRINTF
98 #define wxVsprintf vsnprintf
99 #endif
100 #endif // Windows/!Windows
101
102 #ifndef wxVsprintf
103 // in this case we'll use vsprintf() (which is ANSI and thus should be
104 // always available), but it's unsafe because it doesn't check for buffer
105 // size - so give a warning
106 #define wxVsprintf(buffer,len,format,argptr) vsprintf(buffer,format, argptr)
107 #if defined(__VISUALC__)
108 #pragma message("Using sprintf() because no snprintf()-like function defined")
109 #elif defined(__GNUG__)
110 #warning "Using sprintf() because no snprintf()-like function defined"
111 #elif defined(__MWERKS__)
112 #warning "Using sprintf() because no snprintf()-like function defined"
113 #elif defined(__WATCOMC__)
114 // No warning
115 #elif defined(__BORLANDC__)
116 // No warning
117 #elif defined(__SUNCC__)
118 // nothing -- I don't know about "#warning" for Sun's CC
119 #else
120 // change this to some analogue of '#warning' for your compiler
121 #error "Using sprintf() because no snprintf()-like function defined"
122 #endif //compiler
123
124 #endif // no vsnprintf
125
126 // ----------------------------------------------------------------------------
127 // global functions
128 // ----------------------------------------------------------------------------
129
130 #ifdef wxSTD_STRING_COMPATIBILITY
131
132 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
133 // iostream ones.
134 //
135 // ATTN: you can _not_ use both of these in the same program!
136
137 istream& operator>>(istream& is, wxString& WXUNUSED(str))
138 {
139 #if 0
140 int w = is.width(0);
141 if ( is.ipfx(0) ) {
142 streambuf *sb = is.rdbuf();
143 str.erase();
144 while ( true ) {
145 int ch = sb->sbumpc ();
146 if ( ch == EOF ) {
147 is.setstate(ios::eofbit);
148 break;
149 }
150 else if ( isspace(ch) ) {
151 sb->sungetc();
152 break;
153 }
154
155 str += ch;
156 if ( --w == 1 )
157 break;
158 }
159 }
160
161 is.isfx();
162 if ( str.length() == 0 )
163 is.setstate(ios::failbit);
164 #endif
165 return is;
166 }
167
168 #endif //std::string compatibility
169
170 // ----------------------------------------------------------------------------
171 // private classes
172 // ----------------------------------------------------------------------------
173
174 // this small class is used to gather statistics for performance tuning
175 //#define WXSTRING_STATISTICS
176 #ifdef WXSTRING_STATISTICS
177 class Averager
178 {
179 public:
180 Averager(const char *sz) { m_sz = sz; m_nTotal = m_nCount = 0; }
181 ~Averager()
182 { printf("wxString: average %s = %f\n", m_sz, ((float)m_nTotal)/m_nCount); }
183
184 void Add(size_t n) { m_nTotal += n; m_nCount++; }
185
186 private:
187 size_t m_nCount, m_nTotal;
188 const char *m_sz;
189 } g_averageLength("allocation size"),
190 g_averageSummandLength("summand length"),
191 g_averageConcatHit("hit probability in concat"),
192 g_averageInitialLength("initial string length");
193
194 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
195 #else
196 #define STATISTICS_ADD(av, val)
197 #endif // WXSTRING_STATISTICS
198
199 // ===========================================================================
200 // wxString class core
201 // ===========================================================================
202
203 // ---------------------------------------------------------------------------
204 // construction
205 // ---------------------------------------------------------------------------
206
207 // constructs string of <nLength> copies of character <ch>
208 wxString::wxString(char ch, size_t nLength)
209 {
210 Init();
211
212 if ( nLength > 0 ) {
213 AllocBuffer(nLength);
214
215 wxASSERT( sizeof(char) == 1 ); // can't use memset if not
216
217 memset(m_pchData, ch, nLength);
218 }
219 }
220
221 // takes nLength elements of psz starting at nPos
222 void wxString::InitWith(const char *psz, size_t nPos, size_t nLength)
223 {
224 Init();
225
226 wxASSERT( nPos <= Strlen(psz) );
227
228 if ( nLength == wxSTRING_MAXLEN )
229 nLength = Strlen(psz + nPos);
230
231 STATISTICS_ADD(InitialLength, nLength);
232
233 if ( nLength > 0 ) {
234 // trailing '\0' is written in AllocBuffer()
235 AllocBuffer(nLength);
236 memcpy(m_pchData, psz + nPos, nLength*sizeof(char));
237 }
238 }
239
240 // the same as previous constructor, but for compilers using unsigned char
241 wxString::wxString(const unsigned char* psz, size_t nLength)
242 {
243 InitWith((const char *)psz, 0, nLength);
244 }
245
246 #ifdef wxSTD_STRING_COMPATIBILITY
247
248 // poor man's iterators are "void *" pointers
249 wxString::wxString(const void *pStart, const void *pEnd)
250 {
251 InitWith((const char *)pStart, 0,
252 (const char *)pEnd - (const char *)pStart);
253 }
254
255 #endif //std::string compatibility
256
257 // from wide string
258 wxString::wxString(const wchar_t *pwz)
259 {
260 // first get necessary size
261
262 // NB: GNU libc5 wcstombs() is completely broken, don't use it (it doesn't
263 // honor the 3rd parameter, thus it will happily crash here).
264 #if wxUSE_WCSRTOMBS
265 // don't know if it's really needed (or if we can pass NULL), but better safe
266 // than quick
267 mbstate_t mbstate;
268 size_t nLen = wcsrtombs((char *) NULL, &pwz, 0, &mbstate);
269 #else // !GNU libc
270 size_t nLen = wcstombs((char *) NULL, pwz, 0);
271 #endif // GNU
272
273 // empty?
274 if ( nLen != 0 ) {
275 AllocBuffer(nLen);
276 wcstombs(m_pchData, pwz, nLen);
277 }
278 else {
279 Init();
280 }
281 }
282
283 // ---------------------------------------------------------------------------
284 // memory allocation
285 // ---------------------------------------------------------------------------
286
287 // allocates memory needed to store a C string of length nLen
288 void wxString::AllocBuffer(size_t nLen)
289 {
290 wxASSERT( nLen > 0 ); //
291 wxASSERT( nLen <= INT_MAX-1 ); // max size (enough room for 1 extra)
292
293 STATISTICS_ADD(Length, nLen);
294
295 // allocate memory:
296 // 1) one extra character for '\0' termination
297 // 2) sizeof(wxStringData) for housekeeping info
298 wxStringData* pData = (wxStringData*)
299 malloc(sizeof(wxStringData) + (nLen + EXTRA_ALLOC + 1)*sizeof(char));
300 pData->nRefs = 1;
301 pData->nDataLength = nLen;
302 pData->nAllocLength = nLen + EXTRA_ALLOC;
303 m_pchData = pData->data(); // data starts after wxStringData
304 m_pchData[nLen] = '\0';
305 }
306
307 // must be called before changing this string
308 void wxString::CopyBeforeWrite()
309 {
310 wxStringData* pData = GetStringData();
311
312 if ( pData->IsShared() ) {
313 pData->Unlock(); // memory not freed because shared
314 size_t nLen = pData->nDataLength;
315 AllocBuffer(nLen);
316 memcpy(m_pchData, pData->data(), nLen*sizeof(char));
317 }
318
319 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
320 }
321
322 // must be called before replacing contents of this string
323 void wxString::AllocBeforeWrite(size_t nLen)
324 {
325 wxASSERT( nLen != 0 ); // doesn't make any sense
326
327 // must not share string and must have enough space
328 wxStringData* pData = GetStringData();
329 if ( pData->IsShared() || (nLen > pData->nAllocLength) ) {
330 // can't work with old buffer, get new one
331 pData->Unlock();
332 AllocBuffer(nLen);
333 }
334 else {
335 // update the string length
336 pData->nDataLength = nLen;
337 }
338
339 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
340 }
341
342 // allocate enough memory for nLen characters
343 void wxString::Alloc(size_t nLen)
344 {
345 wxStringData *pData = GetStringData();
346 if ( pData->nAllocLength <= nLen ) {
347 if ( pData->IsEmpty() ) {
348 nLen += EXTRA_ALLOC;
349
350 wxStringData* pData = (wxStringData*)
351 malloc(sizeof(wxStringData) + (nLen + 1)*sizeof(char));
352 pData->nRefs = 1;
353 pData->nDataLength = 0;
354 pData->nAllocLength = nLen;
355 m_pchData = pData->data(); // data starts after wxStringData
356 m_pchData[0u] = '\0';
357 }
358 else if ( pData->IsShared() ) {
359 pData->Unlock(); // memory not freed because shared
360 size_t nOldLen = pData->nDataLength;
361 AllocBuffer(nLen);
362 memcpy(m_pchData, pData->data(), nOldLen*sizeof(char));
363 }
364 else {
365 nLen += EXTRA_ALLOC;
366
367 wxStringData *p = (wxStringData *)
368 realloc(pData, sizeof(wxStringData) + (nLen + 1)*sizeof(char));
369
370 if ( p == NULL ) {
371 // @@@ what to do on memory error?
372 return;
373 }
374
375 // it's not important if the pointer changed or not (the check for this
376 // is not faster than assigning to m_pchData in all cases)
377 p->nAllocLength = nLen;
378 m_pchData = p->data();
379 }
380 }
381 //else: we've already got enough
382 }
383
384 // shrink to minimal size (releasing extra memory)
385 void wxString::Shrink()
386 {
387 wxStringData *pData = GetStringData();
388
389 // this variable is unused in release build, so avoid the compiler warning by
390 // just not declaring it
391 #ifdef __WXDEBUG__
392 void *p =
393 #endif
394 realloc(pData, sizeof(wxStringData) + (pData->nDataLength + 1)*sizeof(char));
395
396 wxASSERT( p != NULL ); // can't free memory?
397 wxASSERT( p == pData ); // we're decrementing the size - block shouldn't move!
398 }
399
400 // get the pointer to writable buffer of (at least) nLen bytes
401 char *wxString::GetWriteBuf(size_t nLen)
402 {
403 AllocBeforeWrite(nLen);
404
405 wxASSERT( GetStringData()->nRefs == 1 );
406 GetStringData()->Validate(FALSE);
407
408 return m_pchData;
409 }
410
411 // put string back in a reasonable state after GetWriteBuf
412 void wxString::UngetWriteBuf()
413 {
414 GetStringData()->nDataLength = strlen(m_pchData);
415 GetStringData()->Validate(TRUE);
416 }
417
418 // ---------------------------------------------------------------------------
419 // data access
420 // ---------------------------------------------------------------------------
421
422 // all functions are inline in string.h
423
424 // ---------------------------------------------------------------------------
425 // assignment operators
426 // ---------------------------------------------------------------------------
427
428 // helper function: does real copy
429 void wxString::AssignCopy(size_t nSrcLen, const char *pszSrcData)
430 {
431 if ( nSrcLen == 0 ) {
432 Reinit();
433 }
434 else {
435 AllocBeforeWrite(nSrcLen);
436 memcpy(m_pchData, pszSrcData, nSrcLen*sizeof(char));
437 GetStringData()->nDataLength = nSrcLen;
438 m_pchData[nSrcLen] = '\0';
439 }
440 }
441
442 // assigns one string to another
443 wxString& wxString::operator=(const wxString& stringSrc)
444 {
445 wxASSERT( stringSrc.GetStringData()->IsValid() );
446
447 // don't copy string over itself
448 if ( m_pchData != stringSrc.m_pchData ) {
449 if ( stringSrc.GetStringData()->IsEmpty() ) {
450 Reinit();
451 }
452 else {
453 // adjust references
454 GetStringData()->Unlock();
455 m_pchData = stringSrc.m_pchData;
456 GetStringData()->Lock();
457 }
458 }
459
460 return *this;
461 }
462
463 // assigns a single character
464 wxString& wxString::operator=(char ch)
465 {
466 AssignCopy(1, &ch);
467 return *this;
468 }
469
470 // assigns C string
471 wxString& wxString::operator=(const char *psz)
472 {
473 AssignCopy(Strlen(psz), psz);
474 return *this;
475 }
476
477 // same as 'signed char' variant
478 wxString& wxString::operator=(const unsigned char* psz)
479 {
480 *this = (const char *)psz;
481 return *this;
482 }
483
484 wxString& wxString::operator=(const wchar_t *pwz)
485 {
486 wxString str(pwz);
487 *this = str;
488 return *this;
489 }
490
491 // ---------------------------------------------------------------------------
492 // string concatenation
493 // ---------------------------------------------------------------------------
494
495 // add something to this string
496 void wxString::ConcatSelf(int nSrcLen, const char *pszSrcData)
497 {
498 STATISTICS_ADD(SummandLength, nSrcLen);
499
500 // concatenating an empty string is a NOP
501 if ( nSrcLen > 0 ) {
502 wxStringData *pData = GetStringData();
503 size_t nLen = pData->nDataLength;
504 size_t nNewLen = nLen + nSrcLen;
505
506 // alloc new buffer if current is too small
507 if ( pData->IsShared() ) {
508 STATISTICS_ADD(ConcatHit, 0);
509
510 // we have to allocate another buffer
511 wxStringData* pOldData = GetStringData();
512 AllocBuffer(nNewLen);
513 memcpy(m_pchData, pOldData->data(), nLen*sizeof(char));
514 pOldData->Unlock();
515 }
516 else if ( nNewLen > pData->nAllocLength ) {
517 STATISTICS_ADD(ConcatHit, 0);
518
519 // we have to grow the buffer
520 Alloc(nNewLen);
521 }
522 else {
523 STATISTICS_ADD(ConcatHit, 1);
524
525 // the buffer is already big enough
526 }
527
528 // should be enough space
529 wxASSERT( nNewLen <= GetStringData()->nAllocLength );
530
531 // fast concatenation - all is done in our buffer
532 memcpy(m_pchData + nLen, pszSrcData, nSrcLen*sizeof(char));
533
534 m_pchData[nNewLen] = '\0'; // put terminating '\0'
535 GetStringData()->nDataLength = nNewLen; // and fix the length
536 }
537 //else: the string to append was empty
538 }
539
540 /*
541 * concatenation functions come in 5 flavours:
542 * string + string
543 * char + string and string + char
544 * C str + string and string + C str
545 */
546
547 wxString operator+(const wxString& string1, const wxString& string2)
548 {
549 wxASSERT( string1.GetStringData()->IsValid() );
550 wxASSERT( string2.GetStringData()->IsValid() );
551
552 wxString s = string1;
553 s += string2;
554
555 return s;
556 }
557
558 wxString operator+(const wxString& string, char ch)
559 {
560 wxASSERT( string.GetStringData()->IsValid() );
561
562 wxString s = string;
563 s += ch;
564
565 return s;
566 }
567
568 wxString operator+(char ch, const wxString& string)
569 {
570 wxASSERT( string.GetStringData()->IsValid() );
571
572 wxString s = ch;
573 s += string;
574
575 return s;
576 }
577
578 wxString operator+(const wxString& string, const char *psz)
579 {
580 wxASSERT( string.GetStringData()->IsValid() );
581
582 wxString s;
583 s.Alloc(Strlen(psz) + string.Len());
584 s = string;
585 s += psz;
586
587 return s;
588 }
589
590 wxString operator+(const char *psz, const wxString& string)
591 {
592 wxASSERT( string.GetStringData()->IsValid() );
593
594 wxString s;
595 s.Alloc(Strlen(psz) + string.Len());
596 s = psz;
597 s += string;
598
599 return s;
600 }
601
602 // ===========================================================================
603 // other common string functions
604 // ===========================================================================
605
606 // ---------------------------------------------------------------------------
607 // simple sub-string extraction
608 // ---------------------------------------------------------------------------
609
610 // helper function: clone the data attached to this string
611 void wxString::AllocCopy(wxString& dest, int nCopyLen, int nCopyIndex) const
612 {
613 if ( nCopyLen == 0 ) {
614 dest.Init();
615 }
616 else {
617 dest.AllocBuffer(nCopyLen);
618 memcpy(dest.m_pchData, m_pchData + nCopyIndex, nCopyLen*sizeof(char));
619 }
620 }
621
622 // extract string of length nCount starting at nFirst
623 wxString wxString::Mid(size_t nFirst, size_t nCount) const
624 {
625 wxStringData *pData = GetStringData();
626 size_t nLen = pData->nDataLength;
627
628 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
629 if ( nCount == wxSTRING_MAXLEN )
630 {
631 nCount = nLen - nFirst;
632 }
633
634 // out-of-bounds requests return sensible things
635 if ( nFirst + nCount > nLen )
636 {
637 nCount = nLen - nFirst;
638 }
639
640 if ( nFirst > nLen )
641 {
642 // AllocCopy() will return empty string
643 nCount = 0;
644 }
645
646 wxString dest;
647 AllocCopy(dest, nCount, nFirst);
648
649 return dest;
650 }
651
652 // extract nCount last (rightmost) characters
653 wxString wxString::Right(size_t nCount) const
654 {
655 if ( nCount > (size_t)GetStringData()->nDataLength )
656 nCount = GetStringData()->nDataLength;
657
658 wxString dest;
659 AllocCopy(dest, nCount, GetStringData()->nDataLength - nCount);
660 return dest;
661 }
662
663 // get all characters after the last occurence of ch
664 // (returns the whole string if ch not found)
665 wxString wxString::AfterLast(char ch) const
666 {
667 wxString str;
668 int iPos = Find(ch, TRUE);
669 if ( iPos == wxNOT_FOUND )
670 str = *this;
671 else
672 str = c_str() + iPos + 1;
673
674 return str;
675 }
676
677 // extract nCount first (leftmost) characters
678 wxString wxString::Left(size_t nCount) const
679 {
680 if ( nCount > (size_t)GetStringData()->nDataLength )
681 nCount = GetStringData()->nDataLength;
682
683 wxString dest;
684 AllocCopy(dest, nCount, 0);
685 return dest;
686 }
687
688 // get all characters before the first occurence of ch
689 // (returns the whole string if ch not found)
690 wxString wxString::BeforeFirst(char ch) const
691 {
692 wxString str;
693 for ( const char *pc = m_pchData; *pc != '\0' && *pc != ch; pc++ )
694 str += *pc;
695
696 return str;
697 }
698
699 /// get all characters before the last occurence of ch
700 /// (returns empty string if ch not found)
701 wxString wxString::BeforeLast(char ch) const
702 {
703 wxString str;
704 int iPos = Find(ch, TRUE);
705 if ( iPos != wxNOT_FOUND && iPos != 0 )
706 str = wxString(c_str(), iPos);
707
708 return str;
709 }
710
711 /// get all characters after the first occurence of ch
712 /// (returns empty string if ch not found)
713 wxString wxString::AfterFirst(char ch) const
714 {
715 wxString str;
716 int iPos = Find(ch);
717 if ( iPos != wxNOT_FOUND )
718 str = c_str() + iPos + 1;
719
720 return str;
721 }
722
723 // replace first (or all) occurences of some substring with another one
724 size_t wxString::Replace(const char *szOld, const char *szNew, bool bReplaceAll)
725 {
726 size_t uiCount = 0; // count of replacements made
727
728 size_t uiOldLen = Strlen(szOld);
729
730 wxString strTemp;
731 const char *pCurrent = m_pchData;
732 const char *pSubstr;
733 while ( *pCurrent != '\0' ) {
734 pSubstr = strstr(pCurrent, szOld);
735 if ( pSubstr == NULL ) {
736 // strTemp is unused if no replacements were made, so avoid the copy
737 if ( uiCount == 0 )
738 return 0;
739
740 strTemp += pCurrent; // copy the rest
741 break; // exit the loop
742 }
743 else {
744 // take chars before match
745 strTemp.ConcatSelf(pSubstr - pCurrent, pCurrent);
746 strTemp += szNew;
747 pCurrent = pSubstr + uiOldLen; // restart after match
748
749 uiCount++;
750
751 // stop now?
752 if ( !bReplaceAll ) {
753 strTemp += pCurrent; // copy the rest
754 break; // exit the loop
755 }
756 }
757 }
758
759 // only done if there were replacements, otherwise would have returned above
760 *this = strTemp;
761
762 return uiCount;
763 }
764
765 bool wxString::IsAscii() const
766 {
767 const char *s = (const char*) *this;
768 while(*s){
769 if(!isascii(*s)) return(FALSE);
770 s++;
771 }
772 return(TRUE);
773 }
774
775 bool wxString::IsWord() const
776 {
777 const char *s = (const char*) *this;
778 while(*s){
779 if(!isalpha(*s)) return(FALSE);
780 s++;
781 }
782 return(TRUE);
783 }
784
785 bool wxString::IsNumber() const
786 {
787 const char *s = (const char*) *this;
788 while(*s){
789 if(!isdigit(*s)) return(FALSE);
790 s++;
791 }
792 return(TRUE);
793 }
794
795 wxString wxString::Strip(stripType w) const
796 {
797 wxString s = *this;
798 if ( w & leading ) s.Trim(FALSE);
799 if ( w & trailing ) s.Trim(TRUE);
800 return s;
801 }
802
803 // ---------------------------------------------------------------------------
804 // case conversion
805 // ---------------------------------------------------------------------------
806
807 wxString& wxString::MakeUpper()
808 {
809 CopyBeforeWrite();
810
811 for ( char *p = m_pchData; *p; p++ )
812 *p = (char)toupper(*p);
813
814 return *this;
815 }
816
817 wxString& wxString::MakeLower()
818 {
819 CopyBeforeWrite();
820
821 for ( char *p = m_pchData; *p; p++ )
822 *p = (char)tolower(*p);
823
824 return *this;
825 }
826
827 // ---------------------------------------------------------------------------
828 // trimming and padding
829 // ---------------------------------------------------------------------------
830
831 // trims spaces (in the sense of isspace) from left or right side
832 wxString& wxString::Trim(bool bFromRight)
833 {
834 // first check if we're going to modify the string at all
835 if ( !IsEmpty() &&
836 (
837 (bFromRight && isspace(GetChar(Len() - 1))) ||
838 (!bFromRight && isspace(GetChar(0u)))
839 )
840 )
841 {
842 // ok, there is at least one space to trim
843 CopyBeforeWrite();
844
845 if ( bFromRight )
846 {
847 // find last non-space character
848 char *psz = m_pchData + GetStringData()->nDataLength - 1;
849 while ( isspace(*psz) && (psz >= m_pchData) )
850 psz--;
851
852 // truncate at trailing space start
853 *++psz = '\0';
854 GetStringData()->nDataLength = psz - m_pchData;
855 }
856 else
857 {
858 // find first non-space character
859 const char *psz = m_pchData;
860 while ( isspace(*psz) )
861 psz++;
862
863 // fix up data and length
864 int nDataLength = GetStringData()->nDataLength - (psz - (const char*) m_pchData);
865 memmove(m_pchData, psz, (nDataLength + 1)*sizeof(char));
866 GetStringData()->nDataLength = nDataLength;
867 }
868 }
869
870 return *this;
871 }
872
873 // adds nCount characters chPad to the string from either side
874 wxString& wxString::Pad(size_t nCount, char chPad, bool bFromRight)
875 {
876 wxString s(chPad, nCount);
877
878 if ( bFromRight )
879 *this += s;
880 else
881 {
882 s += *this;
883 *this = s;
884 }
885
886 return *this;
887 }
888
889 // truncate the string
890 wxString& wxString::Truncate(size_t uiLen)
891 {
892 if ( uiLen < Len() ) {
893 CopyBeforeWrite();
894
895 *(m_pchData + uiLen) = '\0';
896 GetStringData()->nDataLength = uiLen;
897 }
898 //else: nothing to do, string is already short enough
899
900 return *this;
901 }
902
903 // ---------------------------------------------------------------------------
904 // finding (return wxNOT_FOUND if not found and index otherwise)
905 // ---------------------------------------------------------------------------
906
907 // find a character
908 int wxString::Find(char ch, bool bFromEnd) const
909 {
910 const char *psz = bFromEnd ? strrchr(m_pchData, ch) : strchr(m_pchData, ch);
911
912 return (psz == NULL) ? wxNOT_FOUND : psz - (const char*) m_pchData;
913 }
914
915 // find a sub-string (like strstr)
916 int wxString::Find(const char *pszSub) const
917 {
918 const char *psz = strstr(m_pchData, pszSub);
919
920 return (psz == NULL) ? wxNOT_FOUND : psz - (const char*) m_pchData;
921 }
922
923 // ---------------------------------------------------------------------------
924 // stream-like operators
925 // ---------------------------------------------------------------------------
926 wxString& wxString::operator<<(int i)
927 {
928 wxString res;
929 res.Printf("%d", i);
930
931 return (*this) << res;
932 }
933
934 wxString& wxString::operator<<(float f)
935 {
936 wxString res;
937 res.Printf("%f", f);
938
939 return (*this) << res;
940 }
941
942 wxString& wxString::operator<<(double d)
943 {
944 wxString res;
945 res.Printf("%g", d);
946
947 return (*this) << res;
948 }
949
950 // ---------------------------------------------------------------------------
951 // formatted output
952 // ---------------------------------------------------------------------------
953 int wxString::Printf(const char *pszFormat, ...)
954 {
955 va_list argptr;
956 va_start(argptr, pszFormat);
957
958 int iLen = PrintfV(pszFormat, argptr);
959
960 va_end(argptr);
961
962 return iLen;
963 }
964
965 int wxString::PrintfV(const char* pszFormat, va_list argptr)
966 {
967 // static buffer to avoid dynamic memory allocation each time
968 static char s_szScratch[1024];
969
970 // NB: wxVsprintf() may return either less than the buffer size or -1 if there
971 // is not enough place depending on implementation
972 int iLen = wxVsprintf(s_szScratch, WXSIZEOF(s_szScratch), pszFormat, argptr);
973 char *buffer;
974 if ( iLen < (int)WXSIZEOF(s_szScratch) ) {
975 buffer = s_szScratch;
976 }
977 else {
978 int size = WXSIZEOF(s_szScratch) * 2;
979 buffer = (char *)malloc(size);
980 while ( buffer != NULL ) {
981 iLen = wxVsprintf(buffer, WXSIZEOF(s_szScratch), pszFormat, argptr);
982 if ( iLen < size ) {
983 // ok, there was enough space
984 break;
985 }
986
987 // still not enough, double it again
988 buffer = (char *)realloc(buffer, size *= 2);
989 }
990
991 if ( !buffer ) {
992 // out of memory
993 return -1;
994 }
995 }
996
997 AllocBeforeWrite(iLen);
998 strcpy(m_pchData, buffer);
999
1000 if ( buffer != s_szScratch )
1001 free(buffer);
1002
1003 return iLen;
1004 }
1005
1006 // ----------------------------------------------------------------------------
1007 // misc other operations
1008 // ----------------------------------------------------------------------------
1009 bool wxString::Matches(const char *pszMask) const
1010 {
1011 // check char by char
1012 const char *pszTxt;
1013 for ( pszTxt = c_str(); *pszMask != '\0'; pszMask++, pszTxt++ ) {
1014 switch ( *pszMask ) {
1015 case '?':
1016 if ( *pszTxt == '\0' )
1017 return FALSE;
1018
1019 pszTxt++;
1020 pszMask++;
1021 break;
1022
1023 case '*':
1024 {
1025 // ignore special chars immediately following this one
1026 while ( *pszMask == '*' || *pszMask == '?' )
1027 pszMask++;
1028
1029 // if there is nothing more, match
1030 if ( *pszMask == '\0' )
1031 return TRUE;
1032
1033 // are there any other metacharacters in the mask?
1034 size_t uiLenMask;
1035 const char *pEndMask = strpbrk(pszMask, "*?");
1036
1037 if ( pEndMask != NULL ) {
1038 // we have to match the string between two metachars
1039 uiLenMask = pEndMask - pszMask;
1040 }
1041 else {
1042 // we have to match the remainder of the string
1043 uiLenMask = strlen(pszMask);
1044 }
1045
1046 wxString strToMatch(pszMask, uiLenMask);
1047 const char* pMatch = strstr(pszTxt, strToMatch);
1048 if ( pMatch == NULL )
1049 return FALSE;
1050
1051 // -1 to compensate "++" in the loop
1052 pszTxt = pMatch + uiLenMask - 1;
1053 pszMask += uiLenMask - 1;
1054 }
1055 break;
1056
1057 default:
1058 if ( *pszMask != *pszTxt )
1059 return FALSE;
1060 break;
1061 }
1062 }
1063
1064 // match only if nothing left
1065 return *pszTxt == '\0';
1066 }
1067
1068 // Count the number of chars
1069 int wxString::Freq(char ch) const
1070 {
1071 int count = 0;
1072 int len = Len();
1073 for (int i = 0; i < len; i++)
1074 {
1075 if (GetChar(i) == ch)
1076 count ++;
1077 }
1078 return count;
1079 }
1080
1081 // convert to upper case, return the copy of the string
1082 wxString wxString::Upper() const
1083 { wxString s(*this); return s.MakeUpper(); }
1084
1085 // convert to lower case, return the copy of the string
1086 wxString wxString::Lower() const { wxString s(*this); return s.MakeLower(); }
1087
1088 int wxString::sprintf(const char *pszFormat, ...)
1089 {
1090 va_list argptr;
1091 va_start(argptr, pszFormat);
1092 int iLen = PrintfV(pszFormat, argptr);
1093 va_end(argptr);
1094 return iLen;
1095 }
1096
1097 // ---------------------------------------------------------------------------
1098 // standard C++ library string functions
1099 // ---------------------------------------------------------------------------
1100 #ifdef wxSTD_STRING_COMPATIBILITY
1101
1102 wxString& wxString::insert(size_t nPos, const wxString& str)
1103 {
1104 wxASSERT( str.GetStringData()->IsValid() );
1105 wxASSERT( nPos <= Len() );
1106
1107 if ( !str.IsEmpty() ) {
1108 wxString strTmp;
1109 char *pc = strTmp.GetWriteBuf(Len() + str.Len());
1110 strncpy(pc, c_str(), nPos);
1111 strcpy(pc + nPos, str);
1112 strcpy(pc + nPos + str.Len(), c_str() + nPos);
1113 strTmp.UngetWriteBuf();
1114 *this = strTmp;
1115 }
1116
1117 return *this;
1118 }
1119
1120 size_t wxString::find(const wxString& str, size_t nStart) const
1121 {
1122 wxASSERT( str.GetStringData()->IsValid() );
1123 wxASSERT( nStart <= Len() );
1124
1125 const char *p = strstr(c_str() + nStart, str);
1126
1127 return p == NULL ? npos : p - c_str();
1128 }
1129
1130 // VC++ 1.5 can't cope with the default argument in the header.
1131 #if !defined(__VISUALC__) || defined(__WIN32__)
1132 size_t wxString::find(const char* sz, size_t nStart, size_t n) const
1133 {
1134 return find(wxString(sz, n == npos ? 0 : n), nStart);
1135 }
1136 #endif // VC++ 1.5
1137
1138 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1139 #if !defined(__BORLANDC__)
1140 size_t wxString::find(char ch, size_t nStart) const
1141 {
1142 wxASSERT( nStart <= Len() );
1143
1144 const char *p = strchr(c_str() + nStart, ch);
1145
1146 return p == NULL ? npos : p - c_str();
1147 }
1148 #endif
1149
1150 size_t wxString::rfind(const wxString& str, size_t nStart) const
1151 {
1152 wxASSERT( str.GetStringData()->IsValid() );
1153 wxASSERT( nStart <= Len() );
1154
1155 // # could be quicker than that
1156 const char *p = c_str() + (nStart == npos ? Len() : nStart);
1157 while ( p >= c_str() + str.Len() ) {
1158 if ( strncmp(p - str.Len(), str, str.Len()) == 0 )
1159 return p - str.Len() - c_str();
1160 p--;
1161 }
1162
1163 return npos;
1164 }
1165
1166 // VC++ 1.5 can't cope with the default argument in the header.
1167 #if !defined(__VISUALC__) || defined(__WIN32__)
1168 size_t wxString::rfind(const char* sz, size_t nStart, size_t n) const
1169 {
1170 return rfind(wxString(sz, n == npos ? 0 : n), nStart);
1171 }
1172
1173 size_t wxString::rfind(char ch, size_t nStart) const
1174 {
1175 wxASSERT( nStart <= Len() );
1176
1177 const char *p = strrchr(c_str() + nStart, ch);
1178
1179 return p == NULL ? npos : p - c_str();
1180 }
1181 #endif // VC++ 1.5
1182
1183 wxString wxString::substr(size_t nStart, size_t nLen) const
1184 {
1185 // npos means 'take all'
1186 if ( nLen == npos )
1187 nLen = 0;
1188
1189 wxASSERT( nStart + nLen <= Len() );
1190
1191 return wxString(c_str() + nStart, nLen == npos ? 0 : nLen);
1192 }
1193
1194 wxString& wxString::erase(size_t nStart, size_t nLen)
1195 {
1196 wxString strTmp(c_str(), nStart);
1197 if ( nLen != npos ) {
1198 wxASSERT( nStart + nLen <= Len() );
1199
1200 strTmp.append(c_str() + nStart + nLen);
1201 }
1202
1203 *this = strTmp;
1204 return *this;
1205 }
1206
1207 wxString& wxString::replace(size_t nStart, size_t nLen, const char *sz)
1208 {
1209 wxASSERT( nStart + nLen <= Strlen(sz) );
1210
1211 wxString strTmp;
1212 if ( nStart != 0 )
1213 strTmp.append(c_str(), nStart);
1214 strTmp += sz;
1215 strTmp.append(c_str() + nStart + nLen);
1216
1217 *this = strTmp;
1218 return *this;
1219 }
1220
1221 wxString& wxString::replace(size_t nStart, size_t nLen, size_t nCount, char ch)
1222 {
1223 return replace(nStart, nLen, wxString(ch, nCount));
1224 }
1225
1226 wxString& wxString::replace(size_t nStart, size_t nLen,
1227 const wxString& str, size_t nStart2, size_t nLen2)
1228 {
1229 return replace(nStart, nLen, str.substr(nStart2, nLen2));
1230 }
1231
1232 wxString& wxString::replace(size_t nStart, size_t nLen,
1233 const char* sz, size_t nCount)
1234 {
1235 return replace(nStart, nLen, wxString(sz, nCount));
1236 }
1237
1238 #endif //std::string compatibility
1239
1240 // ============================================================================
1241 // ArrayString
1242 // ============================================================================
1243
1244 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1245 #define ARRAY_MAXSIZE_INCREMENT 4096
1246 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1247 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1248 #endif
1249
1250 #define STRING(p) ((wxString *)(&(p)))
1251
1252 // ctor
1253 wxArrayString::wxArrayString()
1254 {
1255 m_nSize =
1256 m_nCount = 0;
1257 m_pItems = (char **) NULL;
1258 }
1259
1260 // copy ctor
1261 wxArrayString::wxArrayString(const wxArrayString& src)
1262 {
1263 m_nSize =
1264 m_nCount = 0;
1265 m_pItems = (char **) NULL;
1266
1267 *this = src;
1268 }
1269
1270 // assignment operator
1271 wxArrayString& wxArrayString::operator=(const wxArrayString& src)
1272 {
1273 if ( m_nSize > 0 )
1274 Clear();
1275
1276 if ( src.m_nCount > ARRAY_DEFAULT_INITIAL_SIZE )
1277 Alloc(src.m_nCount);
1278
1279 // we can't just copy the pointers here because otherwise we would share
1280 // the strings with another array
1281 for ( size_t n = 0; n < src.m_nCount; n++ )
1282 Add(src[n]);
1283
1284 if ( m_nCount != 0 )
1285 memcpy(m_pItems, src.m_pItems, m_nCount*sizeof(char *));
1286
1287 return *this;
1288 }
1289
1290 // grow the array
1291 void wxArrayString::Grow()
1292 {
1293 // only do it if no more place
1294 if( m_nCount == m_nSize ) {
1295 if( m_nSize == 0 ) {
1296 // was empty, alloc some memory
1297 m_nSize = ARRAY_DEFAULT_INITIAL_SIZE;
1298 m_pItems = new char *[m_nSize];
1299 }
1300 else {
1301 // otherwise when it's called for the first time, nIncrement would be 0
1302 // and the array would never be expanded
1303 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE != 0 );
1304
1305 // add 50% but not too much
1306 size_t nIncrement = m_nSize < ARRAY_DEFAULT_INITIAL_SIZE
1307 ? ARRAY_DEFAULT_INITIAL_SIZE : m_nSize >> 1;
1308 if ( nIncrement > ARRAY_MAXSIZE_INCREMENT )
1309 nIncrement = ARRAY_MAXSIZE_INCREMENT;
1310 m_nSize += nIncrement;
1311 char **pNew = new char *[m_nSize];
1312
1313 // copy data to new location
1314 memcpy(pNew, m_pItems, m_nCount*sizeof(char *));
1315
1316 // delete old memory (but do not release the strings!)
1317 wxDELETEA(m_pItems);
1318
1319 m_pItems = pNew;
1320 }
1321 }
1322 }
1323
1324 void wxArrayString::Free()
1325 {
1326 for ( size_t n = 0; n < m_nCount; n++ ) {
1327 STRING(m_pItems[n])->GetStringData()->Unlock();
1328 }
1329 }
1330
1331 // deletes all the strings from the list
1332 void wxArrayString::Empty()
1333 {
1334 Free();
1335
1336 m_nCount = 0;
1337 }
1338
1339 // as Empty, but also frees memory
1340 void wxArrayString::Clear()
1341 {
1342 Free();
1343
1344 m_nSize =
1345 m_nCount = 0;
1346
1347 wxDELETEA(m_pItems);
1348 }
1349
1350 // dtor
1351 wxArrayString::~wxArrayString()
1352 {
1353 Free();
1354
1355 wxDELETEA(m_pItems);
1356 }
1357
1358 // pre-allocates memory (frees the previous data!)
1359 void wxArrayString::Alloc(size_t nSize)
1360 {
1361 wxASSERT( nSize > 0 );
1362
1363 // only if old buffer was not big enough
1364 if ( nSize > m_nSize ) {
1365 Free();
1366 wxDELETEA(m_pItems);
1367 m_pItems = new char *[nSize];
1368 m_nSize = nSize;
1369 }
1370
1371 m_nCount = 0;
1372 }
1373
1374 // searches the array for an item (forward or backwards)
1375 int wxArrayString::Index(const char *sz, bool bCase, bool bFromEnd) const
1376 {
1377 if ( bFromEnd ) {
1378 if ( m_nCount > 0 ) {
1379 size_t ui = m_nCount;
1380 do {
1381 if ( STRING(m_pItems[--ui])->IsSameAs(sz, bCase) )
1382 return ui;
1383 }
1384 while ( ui != 0 );
1385 }
1386 }
1387 else {
1388 for( size_t ui = 0; ui < m_nCount; ui++ ) {
1389 if( STRING(m_pItems[ui])->IsSameAs(sz, bCase) )
1390 return ui;
1391 }
1392 }
1393
1394 return wxNOT_FOUND;
1395 }
1396
1397 // add item at the end
1398 void wxArrayString::Add(const wxString& str)
1399 {
1400 wxASSERT( str.GetStringData()->IsValid() );
1401
1402 Grow();
1403
1404 // the string data must not be deleted!
1405 str.GetStringData()->Lock();
1406 m_pItems[m_nCount++] = (char *)str.c_str();
1407 }
1408
1409 // add item at the given position
1410 void wxArrayString::Insert(const wxString& str, size_t nIndex)
1411 {
1412 wxASSERT( str.GetStringData()->IsValid() );
1413
1414 wxCHECK_RET( nIndex <= m_nCount, ("bad index in wxArrayString::Insert") );
1415
1416 Grow();
1417
1418 memmove(&m_pItems[nIndex + 1], &m_pItems[nIndex],
1419 (m_nCount - nIndex)*sizeof(char *));
1420
1421 str.GetStringData()->Lock();
1422 m_pItems[nIndex] = (char *)str.c_str();
1423
1424 m_nCount++;
1425 }
1426
1427 // removes item from array (by index)
1428 void wxArrayString::Remove(size_t nIndex)
1429 {
1430 wxCHECK_RET( nIndex <= m_nCount, _("bad index in wxArrayString::Remove") );
1431
1432 // release our lock
1433 Item(nIndex).GetStringData()->Unlock();
1434
1435 memmove(&m_pItems[nIndex], &m_pItems[nIndex + 1],
1436 (m_nCount - nIndex - 1)*sizeof(char *));
1437 m_nCount--;
1438 }
1439
1440 // removes item from array (by value)
1441 void wxArrayString::Remove(const char *sz)
1442 {
1443 int iIndex = Index(sz);
1444
1445 wxCHECK_RET( iIndex != wxNOT_FOUND,
1446 _("removing inexistent element in wxArrayString::Remove") );
1447
1448 Remove(iIndex);
1449 }
1450
1451 // ----------------------------------------------------------------------------
1452 // sorting
1453 // ----------------------------------------------------------------------------
1454
1455 // we can only sort one array at a time with the quick-sort based
1456 // implementation
1457 #if wxUSE_THREADS
1458 #include <wx/thread.h>
1459
1460 // need a critical section to protect access to gs_compareFunction and
1461 // gs_sortAscending variables
1462 static wxCriticalSection gs_critsectStringSort;
1463
1464 // call this before the value of the global sort vars is changed/after
1465 // you're finished with them
1466 #define START_SORT() gs_critsectStringSort.Enter()
1467 #define END_SORT() gs_critsectStringSort.Leave()
1468 #else // !threads
1469 #define START_SORT()
1470 #define END_SORT()
1471 #endif // wxUSE_THREADS
1472
1473 // function to use for string comparaison
1474 static wxArrayString::CompareFunction gs_compareFunction = NULL;
1475
1476 // if we don't use the compare function, this flag tells us if we sort the
1477 // array in ascending or descending order
1478 static bool gs_sortAscending = TRUE;
1479
1480 // function which is called by quick sort
1481 static int wxStringCompareFunction(const void *first, const void *second)
1482 {
1483 wxString *strFirst = (wxString *)first;
1484 wxString *strSecond = (wxString *)second;
1485
1486 if ( gs_compareFunction )
1487 return gs_compareFunction(*strFirst, *strSecond);
1488 else {
1489 int result = strcmp(strFirst->c_str(), strSecond->c_str());
1490
1491 return gs_sortAscending ? result : -result;
1492 }
1493 }
1494
1495 // sort array elements using passed comparaison function
1496 void wxArrayString::Sort(CompareFunction compareFunction)
1497 {
1498 START_SORT();
1499
1500 wxASSERT( !gs_compareFunction ); // must have been reset to NULL
1501 gs_compareFunction = compareFunction;
1502
1503 DoSort();
1504
1505 END_SORT();
1506 }
1507
1508 void wxArrayString::Sort(bool reverseOrder)
1509 {
1510 START_SORT();
1511
1512 wxASSERT( !gs_compareFunction ); // must have been reset to NULL
1513 gs_sortAscending = !reverseOrder;
1514
1515 DoSort();
1516
1517 END_SORT();
1518 }
1519
1520 void wxArrayString::DoSort()
1521 {
1522 // just sort the pointers using qsort() - of course it only works because
1523 // wxString() *is* a pointer to its data
1524 qsort(m_pItems, m_nCount, sizeof(char *), wxStringCompareFunction);
1525 }