]> git.saurik.com Git - wxWidgets.git/blob - src/common/string.cpp
correct (working) version of wxString
[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 AllocBuffer(nLen);
287 else if ( pData->IsShared() ) {
288 pData->Unlock(); // memory not freed because shared
289 uint nLen = pData->nDataLength;
290 AllocBuffer(nLen);
291 memcpy(m_pchData, pData->data(), nLen*sizeof(char));
292 }
293 else {
294 nLen += EXTRA_ALLOC;
295
296 wxStringData *p = (wxStringData *)
297 realloc(pData, sizeof(wxStringData) + (nLen + 1)*sizeof(char));
298
299 if ( p == NULL ) {
300 // @@@ what to do on memory error?
301 return;
302 }
303
304 // it's not important if the pointer changed or not (the check for this
305 // is not faster than assigning to m_pchData in all cases)
306 p->nAllocLength = nLen;
307 m_pchData = p->data();
308 }
309 }
310 //else: we've already got enough
311 }
312
313 // shrink to minimal size (releasing extra memory)
314 void wxString::Shrink()
315 {
316 wxStringData *pData = GetStringData();
317 void *p = realloc(pData, sizeof(wxStringData) +
318 (pData->nDataLength + 1)*sizeof(char));
319 wxASSERT( p != NULL ); // can't free memory?
320 wxASSERT( p == pData ); // we're decrementing the size - block shouldn't move!
321 }
322
323 // get the pointer to writable buffer of (at least) nLen bytes
324 char *wxString::GetWriteBuf(uint nLen)
325 {
326 AllocBeforeWrite(nLen);
327
328 wxASSERT( GetStringData()->nRefs == 1 );
329 GetStringData()->Validate(FALSE);
330
331 return m_pchData;
332 }
333
334 // put string back in a reasonable state after GetWriteBuf
335 void wxString::UngetWriteBuf()
336 {
337 GetStringData()->nDataLength = strlen(m_pchData);
338 GetStringData()->Validate(TRUE);
339 }
340
341 // ---------------------------------------------------------------------------
342 // data access
343 // ---------------------------------------------------------------------------
344
345 // all functions are inline in string.h
346
347 // ---------------------------------------------------------------------------
348 // assignment operators
349 // ---------------------------------------------------------------------------
350
351 // helper function: does real copy
352 void wxString::AssignCopy(size_t nSrcLen, const char *pszSrcData)
353 {
354 if ( nSrcLen == 0 ) {
355 Reinit();
356 }
357 else {
358 AllocBeforeWrite(nSrcLen);
359 memcpy(m_pchData, pszSrcData, nSrcLen*sizeof(char));
360 GetStringData()->nDataLength = nSrcLen;
361 m_pchData[nSrcLen] = '\0';
362 }
363 }
364
365 // assigns one string to another
366 wxString& wxString::operator=(const wxString& stringSrc)
367 {
368 wxASSERT( stringSrc.GetStringData()->IsValid() );
369
370 // don't copy string over itself
371 if ( m_pchData != stringSrc.m_pchData ) {
372 if ( stringSrc.GetStringData()->IsEmpty() ) {
373 Reinit();
374 }
375 else {
376 // adjust references
377 GetStringData()->Unlock();
378 m_pchData = stringSrc.m_pchData;
379 GetStringData()->Lock();
380 }
381 }
382
383 return *this;
384 }
385
386 // assigns a single character
387 wxString& wxString::operator=(char ch)
388 {
389 AssignCopy(1, &ch);
390 return *this;
391 }
392
393 // assigns C string
394 wxString& wxString::operator=(const char *psz)
395 {
396 AssignCopy(Strlen(psz), psz);
397 return *this;
398 }
399
400 // same as 'signed char' variant
401 wxString& wxString::operator=(const unsigned char* psz)
402 {
403 *this = (const char *)psz;
404 return *this;
405 }
406
407 wxString& wxString::operator=(const wchar_t *pwz)
408 {
409 wxString str(pwz);
410 *this = str;
411 return *this;
412 }
413
414 // ---------------------------------------------------------------------------
415 // string concatenation
416 // ---------------------------------------------------------------------------
417
418 // add something to this string
419 void wxString::ConcatSelf(int nSrcLen, const char *pszSrcData)
420 {
421 STATISTICS_ADD(SummandLength, nSrcLen);
422
423 // concatenating an empty string is a NOP, but it happens quite rarely,
424 // so we don't waste our time checking for it
425 // if ( nSrcLen > 0 )
426 wxStringData *pData = GetStringData();
427 uint nLen = pData->nDataLength;
428 uint nNewLen = nLen + nSrcLen;
429
430 // alloc new buffer if current is too small
431 if ( pData->IsShared() ) {
432 STATISTICS_ADD(ConcatHit, 0);
433
434 // we have to allocate another buffer
435 wxStringData* pOldData = GetStringData();
436 AllocBuffer(nNewLen);
437 memcpy(m_pchData, pOldData->data(), nLen*sizeof(char));
438 pOldData->Unlock();
439 }
440 else if ( nNewLen > pData->nAllocLength ) {
441 STATISTICS_ADD(ConcatHit, 0);
442
443 // we have to grow the buffer
444 Alloc(nNewLen);
445 }
446 else {
447 STATISTICS_ADD(ConcatHit, 1);
448
449 // the buffer is already big enough
450 }
451
452 // should be enough space
453 wxASSERT( nNewLen <= GetStringData()->nAllocLength );
454
455 // fast concatenation - all is done in our buffer
456 memcpy(m_pchData + nLen, pszSrcData, nSrcLen*sizeof(char));
457
458 m_pchData[nNewLen] = '\0'; // put terminating '\0'
459 GetStringData()->nDataLength = nNewLen; // and fix the length
460 }
461
462 /*
463 * concatenation functions come in 5 flavours:
464 * string + string
465 * char + string and string + char
466 * C str + string and string + C str
467 */
468
469 wxString operator+(const wxString& string1, const wxString& string2)
470 {
471 wxASSERT( string1.GetStringData()->IsValid() );
472 wxASSERT( string2.GetStringData()->IsValid() );
473
474 wxString s = string1;
475 s += string2;
476
477 return s;
478 }
479
480 wxString operator+(const wxString& string, char ch)
481 {
482 wxASSERT( string.GetStringData()->IsValid() );
483
484 wxString s = string;
485 s += ch;
486
487 return s;
488 }
489
490 wxString operator+(char ch, const wxString& string)
491 {
492 wxASSERT( string.GetStringData()->IsValid() );
493
494 wxString s = ch;
495 s += string;
496
497 return s;
498 }
499
500 wxString operator+(const wxString& string, const char *psz)
501 {
502 wxASSERT( string.GetStringData()->IsValid() );
503
504 wxString s;
505 s.Alloc(Strlen(psz) + string.Len());
506 s = string;
507 s += psz;
508
509 return s;
510 }
511
512 wxString operator+(const char *psz, const wxString& string)
513 {
514 wxASSERT( string.GetStringData()->IsValid() );
515
516 wxString s;
517 s.Alloc(Strlen(psz) + string.Len());
518 s = psz;
519 s += string;
520
521 return s;
522 }
523
524 // ===========================================================================
525 // other common string functions
526 // ===========================================================================
527
528 // ---------------------------------------------------------------------------
529 // simple sub-string extraction
530 // ---------------------------------------------------------------------------
531
532 // helper function: clone the data attached to this string
533 void wxString::AllocCopy(wxString& dest, int nCopyLen, int nCopyIndex) const
534 {
535 if ( nCopyLen == 0 ) {
536 dest.Init();
537 }
538 else {
539 dest.AllocBuffer(nCopyLen);
540 memcpy(dest.m_pchData, m_pchData + nCopyIndex, nCopyLen*sizeof(char));
541 }
542 }
543
544 // extract string of length nCount starting at nFirst
545 // default value of nCount is 0 and means "till the end"
546 wxString wxString::Mid(size_t nFirst, size_t nCount) const
547 {
548 // out-of-bounds requests return sensible things
549 if ( nCount == 0 )
550 nCount = GetStringData()->nDataLength - nFirst;
551
552 if ( nFirst + nCount > (size_t)GetStringData()->nDataLength )
553 nCount = GetStringData()->nDataLength - nFirst;
554 if ( nFirst > (size_t)GetStringData()->nDataLength )
555 nCount = 0;
556
557 wxString dest;
558 AllocCopy(dest, nCount, nFirst);
559 return dest;
560 }
561
562 // extract nCount last (rightmost) characters
563 wxString wxString::Right(size_t nCount) const
564 {
565 if ( nCount > (size_t)GetStringData()->nDataLength )
566 nCount = GetStringData()->nDataLength;
567
568 wxString dest;
569 AllocCopy(dest, nCount, GetStringData()->nDataLength - nCount);
570 return dest;
571 }
572
573 // get all characters after the last occurence of ch
574 // (returns the whole string if ch not found)
575 wxString wxString::Right(char ch) const
576 {
577 wxString str;
578 int iPos = Find(ch, TRUE);
579 if ( iPos == NOT_FOUND )
580 str = *this;
581 else
582 str = c_str() + iPos + 1;
583
584 return str;
585 }
586
587 // extract nCount first (leftmost) characters
588 wxString wxString::Left(size_t nCount) const
589 {
590 if ( nCount > (size_t)GetStringData()->nDataLength )
591 nCount = GetStringData()->nDataLength;
592
593 wxString dest;
594 AllocCopy(dest, nCount, 0);
595 return dest;
596 }
597
598 // get all characters before the first occurence of ch
599 // (returns the whole string if ch not found)
600 wxString wxString::Left(char ch) const
601 {
602 wxString str;
603 for ( const char *pc = m_pchData; *pc != '\0' && *pc != ch; pc++ )
604 str += *pc;
605
606 return str;
607 }
608
609 /// get all characters before the last occurence of ch
610 /// (returns empty string if ch not found)
611 wxString wxString::Before(char ch) const
612 {
613 wxString str;
614 int iPos = Find(ch, TRUE);
615 if ( iPos != NOT_FOUND && iPos != 0 )
616 str = wxString(c_str(), iPos);
617
618 return str;
619 }
620
621 /// get all characters after the first occurence of ch
622 /// (returns empty string if ch not found)
623 wxString wxString::After(char ch) const
624 {
625 wxString str;
626 int iPos = Find(ch);
627 if ( iPos != NOT_FOUND )
628 str = c_str() + iPos + 1;
629
630 return str;
631 }
632
633 // replace first (or all) occurences of some substring with another one
634 uint wxString::Replace(const char *szOld, const char *szNew, bool bReplaceAll)
635 {
636 uint uiCount = 0; // count of replacements made
637
638 uint uiOldLen = Strlen(szOld);
639
640 wxString strTemp;
641 const char *pCurrent = m_pchData;
642 const char *pSubstr;
643 while ( *pCurrent != '\0' ) {
644 pSubstr = strstr(pCurrent, szOld);
645 if ( pSubstr == NULL ) {
646 // strTemp is unused if no replacements were made, so avoid the copy
647 if ( uiCount == 0 )
648 return 0;
649
650 strTemp += pCurrent; // copy the rest
651 break; // exit the loop
652 }
653 else {
654 // take chars before match
655 strTemp.ConcatSelf(pSubstr - pCurrent, pCurrent);
656 strTemp += szNew;
657 pCurrent = pSubstr + uiOldLen; // restart after match
658
659 uiCount++;
660
661 // stop now?
662 if ( !bReplaceAll ) {
663 strTemp += pCurrent; // copy the rest
664 break; // exit the loop
665 }
666 }
667 }
668
669 // only done if there were replacements, otherwise would have returned above
670 *this = strTemp;
671
672 return uiCount;
673 }
674
675 bool wxString::IsAscii() const
676 {
677 const char *s = (const char*) *this;
678 while(*s){
679 if(!isascii(*s)) return(FALSE);
680 s++;
681 }
682 return(TRUE);
683 }
684
685 bool wxString::IsWord() const
686 {
687 const char *s = (const char*) *this;
688 while(*s){
689 if(!isalpha(*s)) return(FALSE);
690 s++;
691 }
692 return(TRUE);
693 }
694
695 bool wxString::IsNumber() const
696 {
697 const char *s = (const char*) *this;
698 while(*s){
699 if(!isdigit(*s)) return(FALSE);
700 s++;
701 }
702 return(TRUE);
703 }
704
705 wxString wxString::Strip(stripType w) const
706 {
707 wxString s = *this;
708 if ( w & leading ) s.Trim(FALSE);
709 if ( w & trailing ) s.Trim(TRUE);
710 return s;
711 }
712
713 // ---------------------------------------------------------------------------
714 // case conversion
715 // ---------------------------------------------------------------------------
716
717 wxString& wxString::MakeUpper()
718 {
719 CopyBeforeWrite();
720
721 for ( char *p = m_pchData; *p; p++ )
722 *p = (char)toupper(*p);
723
724 return *this;
725 }
726
727 wxString& wxString::MakeLower()
728 {
729 CopyBeforeWrite();
730
731 for ( char *p = m_pchData; *p; p++ )
732 *p = (char)tolower(*p);
733
734 return *this;
735 }
736
737 // ---------------------------------------------------------------------------
738 // trimming and padding
739 // ---------------------------------------------------------------------------
740
741 // trims spaces (in the sense of isspace) from left or right side
742 wxString& wxString::Trim(bool bFromRight)
743 {
744 CopyBeforeWrite();
745
746 if ( bFromRight )
747 {
748 // find last non-space character
749 char *psz = m_pchData + GetStringData()->nDataLength - 1;
750 while ( isspace(*psz) && (psz >= m_pchData) )
751 psz--;
752
753 // truncate at trailing space start
754 *++psz = '\0';
755 GetStringData()->nDataLength = psz - m_pchData;
756 }
757 else
758 {
759 // find first non-space character
760 const char *psz = m_pchData;
761 while ( isspace(*psz) )
762 psz++;
763
764 // fix up data and length
765 int nDataLength = GetStringData()->nDataLength - (psz - m_pchData);
766 memmove(m_pchData, psz, (nDataLength + 1)*sizeof(char));
767 GetStringData()->nDataLength = nDataLength;
768 }
769
770 return *this;
771 }
772
773 // adds nCount characters chPad to the string from either side
774 wxString& wxString::Pad(size_t nCount, char chPad, bool bFromRight)
775 {
776 wxString s(chPad, nCount);
777
778 if ( bFromRight )
779 *this += s;
780 else
781 {
782 s += *this;
783 *this = s;
784 }
785
786 return *this;
787 }
788
789 // truncate the string
790 wxString& wxString::Truncate(size_t uiLen)
791 {
792 *(m_pchData + uiLen) = '\0';
793 GetStringData()->nDataLength = uiLen;
794
795 return *this;
796 }
797
798 // ---------------------------------------------------------------------------
799 // finding (return NOT_FOUND if not found and index otherwise)
800 // ---------------------------------------------------------------------------
801
802 // find a character
803 int wxString::Find(char ch, bool bFromEnd) const
804 {
805 const char *psz = bFromEnd ? strrchr(m_pchData, ch) : strchr(m_pchData, ch);
806
807 return (psz == NULL) ? NOT_FOUND : psz - m_pchData;
808 }
809
810 // find a sub-string (like strstr)
811 int wxString::Find(const char *pszSub) const
812 {
813 const char *psz = strstr(m_pchData, pszSub);
814
815 return (psz == NULL) ? NOT_FOUND : psz - m_pchData;
816 }
817
818 // ---------------------------------------------------------------------------
819 // formatted output
820 // ---------------------------------------------------------------------------
821 int wxString::Printf(const char *pszFormat, ...)
822 {
823 va_list argptr;
824 va_start(argptr, pszFormat);
825
826 int iLen = PrintfV(pszFormat, argptr);
827
828 va_end(argptr);
829
830 return iLen;
831 }
832
833 int wxString::PrintfV(const char* pszFormat, va_list argptr)
834 {
835 static char s_szScratch[1024];
836
837 int iLen = vsprintf(s_szScratch, pszFormat, argptr);
838 AllocBeforeWrite(iLen);
839 strcpy(m_pchData, s_szScratch);
840
841 return iLen;
842 }
843
844 // ----------------------------------------------------------------------------
845 // misc other operations
846 // ----------------------------------------------------------------------------
847 bool wxString::Matches(const char *pszMask) const
848 {
849 // check char by char
850 const char *pszTxt;
851 for ( pszTxt = c_str(); *pszMask != '\0'; pszMask++, pszTxt++ ) {
852 switch ( *pszMask ) {
853 case '?':
854 if ( *pszTxt == '\0' )
855 return FALSE;
856
857 pszTxt++;
858 pszMask++;
859 break;
860
861 case '*':
862 {
863 // ignore special chars immediately following this one
864 while ( *pszMask == '*' || *pszMask == '?' )
865 pszMask++;
866
867 // if there is nothing more, match
868 if ( *pszMask == '\0' )
869 return TRUE;
870
871 // are there any other metacharacters in the mask?
872 uint uiLenMask;
873 const char *pEndMask = strpbrk(pszMask, "*?");
874
875 if ( pEndMask != NULL ) {
876 // we have to match the string between two metachars
877 uiLenMask = pEndMask - pszMask;
878 }
879 else {
880 // we have to match the remainder of the string
881 uiLenMask = strlen(pszMask);
882 }
883
884 wxString strToMatch(pszMask, uiLenMask);
885 const char* pMatch = strstr(pszTxt, strToMatch);
886 if ( pMatch == NULL )
887 return FALSE;
888
889 // -1 to compensate "++" in the loop
890 pszTxt = pMatch + uiLenMask - 1;
891 pszMask += uiLenMask - 1;
892 }
893 break;
894
895 default:
896 if ( *pszMask != *pszTxt )
897 return FALSE;
898 break;
899 }
900 }
901
902 // match only if nothing left
903 return *pszTxt == '\0';
904 }
905
906 // ---------------------------------------------------------------------------
907 // standard C++ library string functions
908 // ---------------------------------------------------------------------------
909 #ifdef STD_STRING_COMPATIBILITY
910
911 wxString& wxString::insert(size_t nPos, const wxString& str)
912 {
913 wxASSERT( str.GetStringData()->IsValid() );
914 wxASSERT( nPos <= Len() );
915
916 wxString strTmp;
917 char *pc = strTmp.GetWriteBuf(Len() + str.Len());
918 strncpy(pc, c_str(), nPos);
919 strcpy(pc + nPos, str);
920 strcpy(pc + nPos + str.Len(), c_str() + nPos);
921 strTmp.UngetWriteBuf();
922 *this = strTmp;
923
924 return *this;
925 }
926
927 size_t wxString::find(const wxString& str, size_t nStart) const
928 {
929 wxASSERT( str.GetStringData()->IsValid() );
930 wxASSERT( nStart <= Len() );
931
932 const char *p = strstr(c_str() + nStart, str);
933
934 return p == NULL ? npos : p - c_str();
935 }
936
937 // VC++ 1.5 can't cope with the default argument in the header.
938 #if ! (defined(_MSC_VER) && !defined(__WIN32__))
939 size_t wxString::find(const char* sz, size_t nStart, size_t n) const
940 {
941 return find(wxString(sz, n == npos ? 0 : n), nStart);
942 }
943 #endif
944
945 size_t wxString::find(char ch, size_t nStart) const
946 {
947 wxASSERT( nStart <= Len() );
948
949 const char *p = strchr(c_str() + nStart, ch);
950
951 return p == NULL ? npos : p - c_str();
952 }
953
954 size_t wxString::rfind(const wxString& str, size_t nStart) const
955 {
956 wxASSERT( str.GetStringData()->IsValid() );
957 wxASSERT( nStart <= Len() );
958
959 // # could be quicker than that
960 const char *p = c_str() + (nStart == npos ? Len() : nStart);
961 while ( p >= c_str() + str.Len() ) {
962 if ( strncmp(p - str.Len(), str, str.Len()) == 0 )
963 return p - str.Len() - c_str();
964 p--;
965 }
966
967 return npos;
968 }
969
970 // VC++ 1.5 can't cope with the default argument in the header.
971 #if ! (defined(_MSC_VER) && !defined(__WIN32__))
972 size_t wxString::rfind(const char* sz, size_t nStart, size_t n) const
973 {
974 return rfind(wxString(sz, n == npos ? 0 : n), nStart);
975 }
976
977 size_t wxString::rfind(char ch, size_t nStart) const
978 {
979 wxASSERT( nStart <= Len() );
980
981 const char *p = strrchr(c_str() + nStart, ch);
982
983 return p == NULL ? npos : p - c_str();
984 }
985 #endif
986
987 wxString wxString::substr(size_t nStart, size_t nLen) const
988 {
989 // npos means 'take all'
990 if ( nLen == npos )
991 nLen = 0;
992
993 wxASSERT( nStart + nLen <= Len() );
994
995 return wxString(c_str() + nStart, nLen == npos ? 0 : nLen);
996 }
997
998 wxString& wxString::erase(size_t nStart, size_t nLen)
999 {
1000 wxString strTmp(c_str(), nStart);
1001 if ( nLen != npos ) {
1002 wxASSERT( nStart + nLen <= Len() );
1003
1004 strTmp.append(c_str() + nStart + nLen);
1005 }
1006
1007 *this = strTmp;
1008 return *this;
1009 }
1010
1011 wxString& wxString::replace(size_t nStart, size_t nLen, const char *sz)
1012 {
1013 wxASSERT( nStart + nLen <= Strlen(sz) );
1014
1015 wxString strTmp;
1016 if ( nStart != 0 )
1017 strTmp.append(c_str(), nStart);
1018 strTmp += sz;
1019 strTmp.append(c_str() + nStart + nLen);
1020
1021 *this = strTmp;
1022 return *this;
1023 }
1024
1025 wxString& wxString::replace(size_t nStart, size_t nLen, size_t nCount, char ch)
1026 {
1027 return replace(nStart, nLen, wxString(ch, nCount));
1028 }
1029
1030 wxString& wxString::replace(size_t nStart, size_t nLen,
1031 const wxString& str, size_t nStart2, size_t nLen2)
1032 {
1033 return replace(nStart, nLen, str.substr(nStart2, nLen2));
1034 }
1035
1036 wxString& wxString::replace(size_t nStart, size_t nLen,
1037 const char* sz, size_t nCount)
1038 {
1039 return replace(nStart, nLen, wxString(sz, nCount));
1040 }
1041
1042 #endif //std::string compatibility
1043
1044 // ============================================================================
1045 // ArrayString
1046 // ============================================================================
1047
1048 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1049 #define ARRAY_MAXSIZE_INCREMENT 4096
1050 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1051 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1052 #endif
1053
1054 #define STRING(p) ((wxString *)(&(p)))
1055
1056 // ctor
1057 wxArrayString::wxArrayString()
1058 {
1059 m_nSize =
1060 m_nCount = 0;
1061 m_pItems = NULL;
1062 }
1063
1064 // copy ctor
1065 wxArrayString::wxArrayString(const wxArrayString& src)
1066 {
1067 m_nSize = src.m_nSize;
1068 m_nCount = src.m_nCount;
1069
1070 if ( m_nSize != 0 )
1071 m_pItems = new char *[m_nSize];
1072 else
1073 m_pItems = NULL;
1074
1075 if ( m_nCount != 0 )
1076 memcpy(m_pItems, src.m_pItems, m_nCount*sizeof(char *));
1077 }
1078
1079 // copy operator
1080 wxArrayString& wxArrayString::operator=(const wxArrayString& src)
1081 {
1082 DELETEA(m_pItems);
1083
1084 m_nSize = src.m_nSize;
1085 m_nCount = src.m_nCount;
1086
1087 if ( m_nSize != 0 )
1088 m_pItems = new char *[m_nCount];
1089 else
1090 m_pItems = NULL;
1091
1092 if ( m_nCount != 0 )
1093 memcpy(m_pItems, src.m_pItems, m_nCount*sizeof(char *));
1094
1095 return *this;
1096 }
1097
1098 // grow the array
1099 void wxArrayString::Grow()
1100 {
1101 // only do it if no more place
1102 if( m_nCount == m_nSize ) {
1103 if( m_nSize == 0 ) {
1104 // was empty, alloc some memory
1105 m_nSize = ARRAY_DEFAULT_INITIAL_SIZE;
1106 m_pItems = new char *[m_nSize];
1107 }
1108 else {
1109 // add 50% but not too much
1110 size_t nIncrement = m_nSize >> 1;
1111 if ( nIncrement > ARRAY_MAXSIZE_INCREMENT )
1112 nIncrement = ARRAY_MAXSIZE_INCREMENT;
1113 m_nSize += nIncrement;
1114 char **pNew = new char *[m_nSize];
1115
1116 // copy data to new location
1117 memcpy(pNew, m_pItems, m_nCount*sizeof(char *));
1118
1119 // delete old memory (but do not release the strings!)
1120 DELETEA(m_pItems);
1121
1122 m_pItems = pNew;
1123 }
1124 }
1125 }
1126
1127 void wxArrayString::Free()
1128 {
1129 for ( size_t n = 0; n < m_nCount; n++ ) {
1130 STRING(m_pItems[n])->GetStringData()->Unlock();
1131 }
1132 }
1133
1134 // deletes all the strings from the list
1135 void wxArrayString::Empty()
1136 {
1137 Free();
1138
1139 m_nCount = 0;
1140 }
1141
1142 // as Empty, but also frees memory
1143 void wxArrayString::Clear()
1144 {
1145 Free();
1146
1147 m_nSize =
1148 m_nCount = 0;
1149
1150 DELETEA(m_pItems);
1151 m_pItems = NULL;
1152 }
1153
1154 // dtor
1155 wxArrayString::~wxArrayString()
1156 {
1157 Free();
1158
1159 DELETEA(m_pItems);
1160 }
1161
1162 // pre-allocates memory (frees the previous data!)
1163 void wxArrayString::Alloc(size_t nSize)
1164 {
1165 wxASSERT( nSize > 0 );
1166
1167 // only if old buffer was not big enough
1168 if ( nSize > m_nSize ) {
1169 Free();
1170 DELETEA(m_pItems);
1171 m_pItems = new char *[nSize];
1172 m_nSize = nSize;
1173 }
1174
1175 m_nCount = 0;
1176 }
1177
1178 // searches the array for an item (forward or backwards)
1179 int wxArrayString::Index(const char *sz, bool bCase, bool bFromEnd) const
1180 {
1181 if ( bFromEnd ) {
1182 if ( m_nCount > 0 ) {
1183 uint ui = m_nCount;
1184 do {
1185 if ( STRING(m_pItems[--ui])->IsSameAs(sz, bCase) )
1186 return ui;
1187 }
1188 while ( ui != 0 );
1189 }
1190 }
1191 else {
1192 for( uint ui = 0; ui < m_nCount; ui++ ) {
1193 if( STRING(m_pItems[ui])->IsSameAs(sz, bCase) )
1194 return ui;
1195 }
1196 }
1197
1198 return NOT_FOUND;
1199 }
1200
1201 // add item at the end
1202 void wxArrayString::Add(const wxString& str)
1203 {
1204 wxASSERT( str.GetStringData()->IsValid() );
1205
1206 Grow();
1207
1208 // the string data must not be deleted!
1209 str.GetStringData()->Lock();
1210 m_pItems[m_nCount++] = (char *)str.c_str();
1211 }
1212
1213 // add item at the given position
1214 void wxArrayString::Insert(const wxString& str, size_t nIndex)
1215 {
1216 wxASSERT( str.GetStringData()->IsValid() );
1217
1218 wxCHECK_RET( nIndex <= m_nCount, "bad index in wxArrayString::Insert" );
1219
1220 Grow();
1221
1222 memmove(&m_pItems[nIndex + 1], &m_pItems[nIndex],
1223 (m_nCount - nIndex)*sizeof(char *));
1224
1225 str.GetStringData()->Lock();
1226 m_pItems[nIndex] = (char *)str.c_str();
1227
1228 m_nCount++;
1229 }
1230
1231 // removes item from array (by index)
1232 void wxArrayString::Remove(size_t nIndex)
1233 {
1234 wxCHECK_RET( nIndex <= m_nCount, "bad index in wxArrayString::Remove" );
1235
1236 // release our lock
1237 Item(nIndex).GetStringData()->Unlock();
1238
1239 memmove(&m_pItems[nIndex], &m_pItems[nIndex + 1],
1240 (m_nCount - nIndex - 1)*sizeof(char *));
1241 m_nCount--;
1242 }
1243
1244 // removes item from array (by value)
1245 void wxArrayString::Remove(const char *sz)
1246 {
1247 int iIndex = Index(sz);
1248
1249 wxCHECK_RET( iIndex != NOT_FOUND,
1250 "removing inexistent element in wxArrayString::Remove" );
1251
1252 Remove((size_t)iIndex);
1253 }
1254
1255 // sort array elements using passed comparaison function
1256
1257 void wxArrayString::Sort(bool bCase, bool bReverse)
1258 {
1259 //@@@@ TO DO
1260 //qsort(m_pItems, m_nCount, sizeof(char *), fCmp);
1261 }