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