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