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