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