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