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