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