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