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