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