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