]> git.saurik.com Git - wxWidgets.git/blob - src/common/string.cpp
no message
[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 // formatted output
884 // ---------------------------------------------------------------------------
885 int wxString::Printf(const char *pszFormat, ...)
886 {
887 va_list argptr;
888 va_start(argptr, pszFormat);
889
890 int iLen = PrintfV(pszFormat, argptr);
891
892 va_end(argptr);
893
894 return iLen;
895 }
896
897 int wxString::PrintfV(const char* pszFormat, va_list argptr)
898 {
899 static char s_szScratch[1024];
900
901 int iLen = vsprintf(s_szScratch, pszFormat, argptr);
902 AllocBeforeWrite(iLen);
903 strcpy(m_pchData, s_szScratch);
904
905 return iLen;
906 }
907
908 // ----------------------------------------------------------------------------
909 // misc other operations
910 // ----------------------------------------------------------------------------
911 bool wxString::Matches(const char *pszMask) const
912 {
913 // check char by char
914 const char *pszTxt;
915 for ( pszTxt = c_str(); *pszMask != '\0'; pszMask++, pszTxt++ ) {
916 switch ( *pszMask ) {
917 case '?':
918 if ( *pszTxt == '\0' )
919 return FALSE;
920
921 pszTxt++;
922 pszMask++;
923 break;
924
925 case '*':
926 {
927 // ignore special chars immediately following this one
928 while ( *pszMask == '*' || *pszMask == '?' )
929 pszMask++;
930
931 // if there is nothing more, match
932 if ( *pszMask == '\0' )
933 return TRUE;
934
935 // are there any other metacharacters in the mask?
936 size_t uiLenMask;
937 const char *pEndMask = strpbrk(pszMask, "*?");
938
939 if ( pEndMask != NULL ) {
940 // we have to match the string between two metachars
941 uiLenMask = pEndMask - pszMask;
942 }
943 else {
944 // we have to match the remainder of the string
945 uiLenMask = strlen(pszMask);
946 }
947
948 wxString strToMatch(pszMask, uiLenMask);
949 const char* pMatch = strstr(pszTxt, strToMatch);
950 if ( pMatch == NULL )
951 return FALSE;
952
953 // -1 to compensate "++" in the loop
954 pszTxt = pMatch + uiLenMask - 1;
955 pszMask += uiLenMask - 1;
956 }
957 break;
958
959 default:
960 if ( *pszMask != *pszTxt )
961 return FALSE;
962 break;
963 }
964 }
965
966 // match only if nothing left
967 return *pszTxt == '\0';
968 }
969
970 // ---------------------------------------------------------------------------
971 // standard C++ library string functions
972 // ---------------------------------------------------------------------------
973 #ifdef STD_STRING_COMPATIBILITY
974
975 wxString& wxString::insert(size_t nPos, const wxString& str)
976 {
977 wxASSERT( str.GetStringData()->IsValid() );
978 wxASSERT( nPos <= Len() );
979
980 if ( !str.IsEmpty() ) {
981 wxString strTmp;
982 char *pc = strTmp.GetWriteBuf(Len() + str.Len());
983 strncpy(pc, c_str(), nPos);
984 strcpy(pc + nPos, str);
985 strcpy(pc + nPos + str.Len(), c_str() + nPos);
986 strTmp.UngetWriteBuf();
987 *this = strTmp;
988 }
989
990 return *this;
991 }
992
993 size_t wxString::find(const wxString& str, size_t nStart) const
994 {
995 wxASSERT( str.GetStringData()->IsValid() );
996 wxASSERT( nStart <= Len() );
997
998 const char *p = strstr(c_str() + nStart, str);
999
1000 return p == NULL ? npos : p - c_str();
1001 }
1002
1003 // VC++ 1.5 can't cope with the default argument in the header.
1004 #if ! (defined(_MSC_VER) && !defined(__WIN32__))
1005 size_t wxString::find(const char* sz, size_t nStart, size_t n) const
1006 {
1007 return find(wxString(sz, n == npos ? 0 : n), nStart);
1008 }
1009 #endif
1010
1011 size_t wxString::find(char ch, size_t nStart) const
1012 {
1013 wxASSERT( nStart <= Len() );
1014
1015 const char *p = strchr(c_str() + nStart, ch);
1016
1017 return p == NULL ? npos : p - c_str();
1018 }
1019
1020 size_t wxString::rfind(const wxString& str, size_t nStart) const
1021 {
1022 wxASSERT( str.GetStringData()->IsValid() );
1023 wxASSERT( nStart <= Len() );
1024
1025 // # could be quicker than that
1026 const char *p = c_str() + (nStart == npos ? Len() : nStart);
1027 while ( p >= c_str() + str.Len() ) {
1028 if ( strncmp(p - str.Len(), str, str.Len()) == 0 )
1029 return p - str.Len() - c_str();
1030 p--;
1031 }
1032
1033 return npos;
1034 }
1035
1036 // VC++ 1.5 can't cope with the default argument in the header.
1037 #if ! (defined(_MSC_VER) && !defined(__WIN32__))
1038 size_t wxString::rfind(const char* sz, size_t nStart, size_t n) const
1039 {
1040 return rfind(wxString(sz, n == npos ? 0 : n), nStart);
1041 }
1042
1043 size_t wxString::rfind(char ch, size_t nStart) const
1044 {
1045 wxASSERT( nStart <= Len() );
1046
1047 const char *p = strrchr(c_str() + nStart, ch);
1048
1049 return p == NULL ? npos : p - c_str();
1050 }
1051 #endif
1052
1053 wxString wxString::substr(size_t nStart, size_t nLen) const
1054 {
1055 // npos means 'take all'
1056 if ( nLen == npos )
1057 nLen = 0;
1058
1059 wxASSERT( nStart + nLen <= Len() );
1060
1061 return wxString(c_str() + nStart, nLen == npos ? 0 : nLen);
1062 }
1063
1064 wxString& wxString::erase(size_t nStart, size_t nLen)
1065 {
1066 wxString strTmp(c_str(), nStart);
1067 if ( nLen != npos ) {
1068 wxASSERT( nStart + nLen <= Len() );
1069
1070 strTmp.append(c_str() + nStart + nLen);
1071 }
1072
1073 *this = strTmp;
1074 return *this;
1075 }
1076
1077 wxString& wxString::replace(size_t nStart, size_t nLen, const char *sz)
1078 {
1079 wxASSERT( nStart + nLen <= Strlen(sz) );
1080
1081 wxString strTmp;
1082 if ( nStart != 0 )
1083 strTmp.append(c_str(), nStart);
1084 strTmp += sz;
1085 strTmp.append(c_str() + nStart + nLen);
1086
1087 *this = strTmp;
1088 return *this;
1089 }
1090
1091 wxString& wxString::replace(size_t nStart, size_t nLen, size_t nCount, char ch)
1092 {
1093 return replace(nStart, nLen, wxString(ch, nCount));
1094 }
1095
1096 wxString& wxString::replace(size_t nStart, size_t nLen,
1097 const wxString& str, size_t nStart2, size_t nLen2)
1098 {
1099 return replace(nStart, nLen, str.substr(nStart2, nLen2));
1100 }
1101
1102 wxString& wxString::replace(size_t nStart, size_t nLen,
1103 const char* sz, size_t nCount)
1104 {
1105 return replace(nStart, nLen, wxString(sz, nCount));
1106 }
1107
1108 #endif //std::string compatibility
1109
1110 // ============================================================================
1111 // ArrayString
1112 // ============================================================================
1113
1114 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1115 #define ARRAY_MAXSIZE_INCREMENT 4096
1116 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1117 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1118 #endif
1119
1120 #define STRING(p) ((wxString *)(&(p)))
1121
1122 // ctor
1123 wxArrayString::wxArrayString()
1124 {
1125 m_nSize =
1126 m_nCount = 0;
1127 m_pItems = (char **) NULL;
1128 }
1129
1130 // copy ctor
1131 wxArrayString::wxArrayString(const wxArrayString& src)
1132 {
1133 m_nSize =
1134 m_nCount = 0;
1135 m_pItems = (char **) NULL;
1136
1137 *this = src;
1138 }
1139
1140 // assignment operator
1141 wxArrayString& wxArrayString::operator=(const wxArrayString& src)
1142 {
1143 if ( m_nSize > 0 )
1144 Clear();
1145
1146 if ( src.m_nCount > ARRAY_DEFAULT_INITIAL_SIZE )
1147 Alloc(src.m_nCount);
1148
1149 // we can't just copy the pointers here because otherwise we would share
1150 // the strings with another array
1151 for ( size_t n = 0; n < src.m_nCount; n++ )
1152 Add(src[n]);
1153
1154 if ( m_nCount != 0 )
1155 memcpy(m_pItems, src.m_pItems, m_nCount*sizeof(char *));
1156
1157 return *this;
1158 }
1159
1160 // grow the array
1161 void wxArrayString::Grow()
1162 {
1163 // only do it if no more place
1164 if( m_nCount == m_nSize ) {
1165 if( m_nSize == 0 ) {
1166 // was empty, alloc some memory
1167 m_nSize = ARRAY_DEFAULT_INITIAL_SIZE;
1168 m_pItems = new char *[m_nSize];
1169 }
1170 else {
1171 // otherwise when it's called for the first time, nIncrement would be 0
1172 // and the array would never be expanded
1173 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE != 0 );
1174
1175 // add 50% but not too much
1176 size_t nIncrement = m_nSize < ARRAY_DEFAULT_INITIAL_SIZE
1177 ? ARRAY_DEFAULT_INITIAL_SIZE : m_nSize >> 1;
1178 if ( nIncrement > ARRAY_MAXSIZE_INCREMENT )
1179 nIncrement = ARRAY_MAXSIZE_INCREMENT;
1180 m_nSize += nIncrement;
1181 char **pNew = new char *[m_nSize];
1182
1183 // copy data to new location
1184 memcpy(pNew, m_pItems, m_nCount*sizeof(char *));
1185
1186 // delete old memory (but do not release the strings!)
1187 wxDELETEA(m_pItems);
1188
1189 m_pItems = pNew;
1190 }
1191 }
1192 }
1193
1194 void wxArrayString::Free()
1195 {
1196 for ( size_t n = 0; n < m_nCount; n++ ) {
1197 STRING(m_pItems[n])->GetStringData()->Unlock();
1198 }
1199 }
1200
1201 // deletes all the strings from the list
1202 void wxArrayString::Empty()
1203 {
1204 Free();
1205
1206 m_nCount = 0;
1207 }
1208
1209 // as Empty, but also frees memory
1210 void wxArrayString::Clear()
1211 {
1212 Free();
1213
1214 m_nSize =
1215 m_nCount = 0;
1216
1217 wxDELETEA(m_pItems);
1218 }
1219
1220 // dtor
1221 wxArrayString::~wxArrayString()
1222 {
1223 Free();
1224
1225 wxDELETEA(m_pItems);
1226 }
1227
1228 // pre-allocates memory (frees the previous data!)
1229 void wxArrayString::Alloc(size_t nSize)
1230 {
1231 wxASSERT( nSize > 0 );
1232
1233 // only if old buffer was not big enough
1234 if ( nSize > m_nSize ) {
1235 Free();
1236 wxDELETEA(m_pItems);
1237 m_pItems = new char *[nSize];
1238 m_nSize = nSize;
1239 }
1240
1241 m_nCount = 0;
1242 }
1243
1244 // searches the array for an item (forward or backwards)
1245 int wxArrayString::Index(const char *sz, bool bCase, bool bFromEnd) const
1246 {
1247 if ( bFromEnd ) {
1248 if ( m_nCount > 0 ) {
1249 size_t ui = m_nCount;
1250 do {
1251 if ( STRING(m_pItems[--ui])->IsSameAs(sz, bCase) )
1252 return ui;
1253 }
1254 while ( ui != 0 );
1255 }
1256 }
1257 else {
1258 for( size_t ui = 0; ui < m_nCount; ui++ ) {
1259 if( STRING(m_pItems[ui])->IsSameAs(sz, bCase) )
1260 return ui;
1261 }
1262 }
1263
1264 return NOT_FOUND;
1265 }
1266
1267 // add item at the end
1268 void wxArrayString::Add(const wxString& str)
1269 {
1270 wxASSERT( str.GetStringData()->IsValid() );
1271
1272 Grow();
1273
1274 // the string data must not be deleted!
1275 str.GetStringData()->Lock();
1276 m_pItems[m_nCount++] = (char *)str.c_str();
1277 }
1278
1279 // add item at the given position
1280 void wxArrayString::Insert(const wxString& str, size_t nIndex)
1281 {
1282 wxASSERT( str.GetStringData()->IsValid() );
1283
1284 wxCHECK_RET( nIndex <= m_nCount, ("bad index in wxArrayString::Insert") );
1285
1286 Grow();
1287
1288 memmove(&m_pItems[nIndex + 1], &m_pItems[nIndex],
1289 (m_nCount - nIndex)*sizeof(char *));
1290
1291 str.GetStringData()->Lock();
1292 m_pItems[nIndex] = (char *)str.c_str();
1293
1294 m_nCount++;
1295 }
1296
1297 // removes item from array (by index)
1298 void wxArrayString::Remove(size_t nIndex)
1299 {
1300 wxCHECK_RET( nIndex <= m_nCount, _("bad index in wxArrayString::Remove") );
1301
1302 // release our lock
1303 Item(nIndex).GetStringData()->Unlock();
1304
1305 memmove(&m_pItems[nIndex], &m_pItems[nIndex + 1],
1306 (m_nCount - nIndex - 1)*sizeof(char *));
1307 m_nCount--;
1308 }
1309
1310 // removes item from array (by value)
1311 void wxArrayString::Remove(const char *sz)
1312 {
1313 int iIndex = Index(sz);
1314
1315 wxCHECK_RET( iIndex != NOT_FOUND,
1316 _("removing inexistent element in wxArrayString::Remove") );
1317
1318 Remove(iIndex);
1319 }
1320
1321 // sort array elements using passed comparaison function
1322
1323 void wxArrayString::Sort(bool WXUNUSED(bCase), bool WXUNUSED(bReverse) )
1324 {
1325 //@@@@ TO DO
1326 //qsort(m_pItems, m_nCount, sizeof(char *), fCmp);
1327 }