]> git.saurik.com Git - wxWidgets.git/blob - src/common/string.cpp
Fixed windows installer to not need a reboot and therefore not have
[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 #if wxUSE_THREADS
39 #include <wx/thread.h>
40 #endif
41 #endif
42
43 #include <ctype.h>
44 #include <string.h>
45 #include <stdlib.h>
46
47 #ifdef __SALFORDC__
48 #include <clib.h>
49 #endif
50
51 #if wxUSE_WCSRTOMBS
52 #include <wchar.h> // for wcsrtombs(), see comments where it's used
53 #endif // GNU
54
55 #ifdef WXSTRING_IS_WXOBJECT
56 IMPLEMENT_DYNAMIC_CLASS(wxString, wxObject)
57 #endif //WXSTRING_IS_WXOBJECT
58
59 #if wxUSE_UNICODE
60 #undef wxUSE_EXPERIMENTAL_PRINTF
61 #define wxUSE_EXPERIMENTAL_PRINTF 1
62 #endif
63
64 // allocating extra space for each string consumes more memory but speeds up
65 // the concatenation operations (nLen is the current string's length)
66 // NB: EXTRA_ALLOC must be >= 0!
67 #define EXTRA_ALLOC (19 - nLen % 16)
68
69 // ---------------------------------------------------------------------------
70 // static class variables definition
71 // ---------------------------------------------------------------------------
72
73 #ifdef wxSTD_STRING_COMPATIBILITY
74 const size_t wxString::npos = wxSTRING_MAXLEN;
75 #endif // wxSTD_STRING_COMPATIBILITY
76
77 // ----------------------------------------------------------------------------
78 // static data
79 // ----------------------------------------------------------------------------
80
81 // for an empty string, GetStringData() will return this address: this
82 // structure has the same layout as wxStringData and it's data() method will
83 // return the empty string (dummy pointer)
84 static const struct
85 {
86 wxStringData data;
87 wxChar dummy;
88 } g_strEmpty = { {-1, 0, 0}, wxT('\0') };
89
90 // empty C style string: points to 'string data' byte of g_strEmpty
91 extern const wxChar WXDLLEXPORT *wxEmptyString = &g_strEmpty.dummy;
92
93 // ----------------------------------------------------------------------------
94 // conditional compilation
95 // ----------------------------------------------------------------------------
96
97 #if !defined(__WXSW__) && wxUSE_UNICODE
98 #ifdef wxUSE_EXPERIMENTAL_PRINTF
99 #undef wxUSE_EXPERIMENTAL_PRINTF
100 #endif
101 #define wxUSE_EXPERIMENTAL_PRINTF 1
102 #endif
103
104 // we want to find out if the current platform supports vsnprintf()-like
105 // function: for Unix this is done with configure, for Windows we test the
106 // compiler explicitly.
107 #ifdef __WXMSW__
108 #ifdef __VISUALC__
109 #define wxVsnprintf _vsnprintf
110 #endif
111 #else // !Windows
112 #ifdef HAVE_VSNPRINTF
113 #define wxVsnprintf vsnprintf
114 #endif
115 #endif // Windows/!Windows
116
117 #ifndef wxVsnprintf
118 // in this case we'll use vsprintf() (which is ANSI and thus should be
119 // always available), but it's unsafe because it doesn't check for buffer
120 // size - so give a warning
121 #define wxVsnprintf(buffer,len,format,argptr) vsprintf(buffer,format, argptr)
122
123 #if defined(__VISUALC__)
124 #pragma message("Using sprintf() because no snprintf()-like function defined")
125 #elif defined(__GNUG__) && !defined(__UNIX__)
126 #warning "Using sprintf() because no snprintf()-like function defined"
127 #elif defined(__MWERKS__)
128 #warning "Using sprintf() because no snprintf()-like function defined"
129 #endif //compiler
130 #endif // no vsnprintf
131
132 #ifdef _AIX
133 // AIX has vsnprintf, but there's no prototype in the system headers.
134 extern "C" int vsnprintf(char* str, size_t n, const char* format, va_list ap);
135 #endif
136
137 // ----------------------------------------------------------------------------
138 // global functions
139 // ----------------------------------------------------------------------------
140
141 #if defined(wxSTD_STRING_COMPATIBILITY) && wxUSE_STD_IOSTREAM
142
143 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
144 // iostream ones.
145 //
146 // ATTN: you can _not_ use both of these in the same program!
147
148 istream& operator>>(istream& is, wxString& WXUNUSED(str))
149 {
150 #if 0
151 int w = is.width(0);
152 if ( is.ipfx(0) ) {
153 streambuf *sb = is.rdbuf();
154 str.erase();
155 while ( true ) {
156 int ch = sb->sbumpc ();
157 if ( ch == EOF ) {
158 is.setstate(ios::eofbit);
159 break;
160 }
161 else if ( isspace(ch) ) {
162 sb->sungetc();
163 break;
164 }
165
166 str += ch;
167 if ( --w == 1 )
168 break;
169 }
170 }
171
172 is.isfx();
173 if ( str.length() == 0 )
174 is.setstate(ios::failbit);
175 #endif
176 return is;
177 }
178
179 ostream& operator<<(ostream& os, const wxString& str)
180 {
181 os << str.c_str();
182 return os;
183 }
184
185 #endif //std::string compatibility
186
187 // ----------------------------------------------------------------------------
188 // private classes
189 // ----------------------------------------------------------------------------
190
191 // this small class is used to gather statistics for performance tuning
192 //#define WXSTRING_STATISTICS
193 #ifdef WXSTRING_STATISTICS
194 class Averager
195 {
196 public:
197 Averager(const char *sz) { m_sz = sz; m_nTotal = m_nCount = 0; }
198 ~Averager()
199 { printf("wxString: average %s = %f\n", m_sz, ((float)m_nTotal)/m_nCount); }
200
201 void Add(size_t n) { m_nTotal += n; m_nCount++; }
202
203 private:
204 size_t m_nCount, m_nTotal;
205 const char *m_sz;
206 } g_averageLength("allocation size"),
207 g_averageSummandLength("summand length"),
208 g_averageConcatHit("hit probability in concat"),
209 g_averageInitialLength("initial string length");
210
211 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
212 #else
213 #define STATISTICS_ADD(av, val)
214 #endif // WXSTRING_STATISTICS
215
216 // ===========================================================================
217 // wxString class core
218 // ===========================================================================
219
220 // ---------------------------------------------------------------------------
221 // construction
222 // ---------------------------------------------------------------------------
223
224 // constructs string of <nLength> copies of character <ch>
225 wxString::wxString(wxChar ch, size_t nLength)
226 {
227 Init();
228
229 if ( nLength > 0 ) {
230 AllocBuffer(nLength);
231
232 #if wxUSE_UNICODE
233 // memset only works on char
234 for (size_t n=0; n<nLength; n++) m_pchData[n] = ch;
235 #else
236 memset(m_pchData, ch, nLength);
237 #endif
238 }
239 }
240
241 // takes nLength elements of psz starting at nPos
242 void wxString::InitWith(const wxChar *psz, size_t nPos, size_t nLength)
243 {
244 Init();
245
246 wxASSERT( nPos <= wxStrlen(psz) );
247
248 if ( nLength == wxSTRING_MAXLEN )
249 nLength = wxStrlen(psz + nPos);
250
251 STATISTICS_ADD(InitialLength, nLength);
252
253 if ( nLength > 0 ) {
254 // trailing '\0' is written in AllocBuffer()
255 AllocBuffer(nLength);
256 memcpy(m_pchData, psz + nPos, nLength*sizeof(wxChar));
257 }
258 }
259
260 #ifdef wxSTD_STRING_COMPATIBILITY
261
262 // poor man's iterators are "void *" pointers
263 wxString::wxString(const void *pStart, const void *pEnd)
264 {
265 InitWith((const wxChar *)pStart, 0,
266 (const wxChar *)pEnd - (const wxChar *)pStart);
267 }
268
269 #endif //std::string compatibility
270
271 #if wxUSE_UNICODE
272
273 // from multibyte string
274 wxString::wxString(const char *psz, wxMBConv& conv, size_t nLength)
275 {
276 // first get necessary size
277 size_t nLen = psz ? conv.MB2WC((wchar_t *) NULL, psz, 0) : 0;
278
279 // nLength is number of *Unicode* characters here!
280 if ((nLen != (size_t)-1) && (nLen > nLength))
281 nLen = nLength;
282
283 // empty?
284 if ( (nLen != 0) && (nLen != (size_t)-1) ) {
285 AllocBuffer(nLen);
286 conv.MB2WC(m_pchData, psz, nLen);
287 }
288 else {
289 Init();
290 }
291 }
292
293 #else // ANSI
294
295 #if wxUSE_WCHAR_T
296 // from wide string
297 wxString::wxString(const wchar_t *pwz)
298 {
299 // first get necessary size
300 size_t nLen = pwz ? wxWC2MB((char *) NULL, pwz, 0) : 0;
301
302 // empty?
303 if ( (nLen != 0) && (nLen != (size_t)-1) ) {
304 AllocBuffer(nLen);
305 wxWC2MB(m_pchData, pwz, nLen);
306 }
307 else {
308 Init();
309 }
310 }
311 #endif // wxUSE_WCHAR_T
312
313 #endif // Unicode/ANSI
314
315 // ---------------------------------------------------------------------------
316 // memory allocation
317 // ---------------------------------------------------------------------------
318
319 // allocates memory needed to store a C string of length nLen
320 void wxString::AllocBuffer(size_t nLen)
321 {
322 wxASSERT( nLen > 0 ); //
323 wxASSERT( nLen <= INT_MAX-1 ); // max size (enough room for 1 extra)
324
325 STATISTICS_ADD(Length, nLen);
326
327 // allocate memory:
328 // 1) one extra character for '\0' termination
329 // 2) sizeof(wxStringData) for housekeeping info
330 wxStringData* pData = (wxStringData*)
331 malloc(sizeof(wxStringData) + (nLen + EXTRA_ALLOC + 1)*sizeof(wxChar));
332 pData->nRefs = 1;
333 pData->nDataLength = nLen;
334 pData->nAllocLength = nLen + EXTRA_ALLOC;
335 m_pchData = pData->data(); // data starts after wxStringData
336 m_pchData[nLen] = wxT('\0');
337 }
338
339 // must be called before changing this string
340 void wxString::CopyBeforeWrite()
341 {
342 wxStringData* pData = GetStringData();
343
344 if ( pData->IsShared() ) {
345 pData->Unlock(); // memory not freed because shared
346 size_t nLen = pData->nDataLength;
347 AllocBuffer(nLen);
348 memcpy(m_pchData, pData->data(), nLen*sizeof(wxChar));
349 }
350
351 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
352 }
353
354 // must be called before replacing contents of this string
355 void wxString::AllocBeforeWrite(size_t nLen)
356 {
357 wxASSERT( nLen != 0 ); // doesn't make any sense
358
359 // must not share string and must have enough space
360 wxStringData* pData = GetStringData();
361 if ( pData->IsShared() || (nLen > pData->nAllocLength) ) {
362 // can't work with old buffer, get new one
363 pData->Unlock();
364 AllocBuffer(nLen);
365 }
366 else {
367 // update the string length
368 pData->nDataLength = nLen;
369 }
370
371 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
372 }
373
374 // allocate enough memory for nLen characters
375 void wxString::Alloc(size_t nLen)
376 {
377 wxStringData *pData = GetStringData();
378 if ( pData->nAllocLength <= nLen ) {
379 if ( pData->IsEmpty() ) {
380 nLen += EXTRA_ALLOC;
381
382 wxStringData* pData = (wxStringData*)
383 malloc(sizeof(wxStringData) + (nLen + 1)*sizeof(wxChar));
384 pData->nRefs = 1;
385 pData->nDataLength = 0;
386 pData->nAllocLength = nLen;
387 m_pchData = pData->data(); // data starts after wxStringData
388 m_pchData[0u] = wxT('\0');
389 }
390 else if ( pData->IsShared() ) {
391 pData->Unlock(); // memory not freed because shared
392 size_t nOldLen = pData->nDataLength;
393 AllocBuffer(nLen);
394 memcpy(m_pchData, pData->data(), nOldLen*sizeof(wxChar));
395 }
396 else {
397 nLen += EXTRA_ALLOC;
398
399 wxStringData *p = (wxStringData *)
400 realloc(pData, sizeof(wxStringData) + (nLen + 1)*sizeof(wxChar));
401
402 if ( p == NULL ) {
403 // @@@ what to do on memory error?
404 return;
405 }
406
407 // it's not important if the pointer changed or not (the check for this
408 // is not faster than assigning to m_pchData in all cases)
409 p->nAllocLength = nLen;
410 m_pchData = p->data();
411 }
412 }
413 //else: we've already got enough
414 }
415
416 // shrink to minimal size (releasing extra memory)
417 void wxString::Shrink()
418 {
419 wxStringData *pData = GetStringData();
420
421 // this variable is unused in release build, so avoid the compiler warning by
422 // just not declaring it
423 #ifdef __WXDEBUG__
424 void *p =
425 #endif
426 realloc(pData, sizeof(wxStringData) + (pData->nDataLength + 1)*sizeof(wxChar));
427
428 wxASSERT( p != NULL ); // can't free memory?
429 wxASSERT( p == pData ); // we're decrementing the size - block shouldn't move!
430 }
431
432 // get the pointer to writable buffer of (at least) nLen bytes
433 wxChar *wxString::GetWriteBuf(size_t nLen)
434 {
435 AllocBeforeWrite(nLen);
436
437 wxASSERT( GetStringData()->nRefs == 1 );
438 GetStringData()->Validate(FALSE);
439
440 return m_pchData;
441 }
442
443 // put string back in a reasonable state after GetWriteBuf
444 void wxString::UngetWriteBuf()
445 {
446 GetStringData()->nDataLength = wxStrlen(m_pchData);
447 GetStringData()->Validate(TRUE);
448 }
449
450 // ---------------------------------------------------------------------------
451 // data access
452 // ---------------------------------------------------------------------------
453
454 // all functions are inline in string.h
455
456 // ---------------------------------------------------------------------------
457 // assignment operators
458 // ---------------------------------------------------------------------------
459
460 // helper function: does real copy
461 void wxString::AssignCopy(size_t nSrcLen, const wxChar *pszSrcData)
462 {
463 if ( nSrcLen == 0 ) {
464 Reinit();
465 }
466 else {
467 AllocBeforeWrite(nSrcLen);
468 memcpy(m_pchData, pszSrcData, nSrcLen*sizeof(wxChar));
469 GetStringData()->nDataLength = nSrcLen;
470 m_pchData[nSrcLen] = wxT('\0');
471 }
472 }
473
474 // assigns one string to another
475 wxString& wxString::operator=(const wxString& stringSrc)
476 {
477 wxASSERT( stringSrc.GetStringData()->IsValid() );
478
479 // don't copy string over itself
480 if ( m_pchData != stringSrc.m_pchData ) {
481 if ( stringSrc.GetStringData()->IsEmpty() ) {
482 Reinit();
483 }
484 else {
485 // adjust references
486 GetStringData()->Unlock();
487 m_pchData = stringSrc.m_pchData;
488 GetStringData()->Lock();
489 }
490 }
491
492 return *this;
493 }
494
495 // assigns a single character
496 wxString& wxString::operator=(wxChar ch)
497 {
498 AssignCopy(1, &ch);
499 return *this;
500 }
501
502 // assigns C string
503 wxString& wxString::operator=(const wxChar *psz)
504 {
505 AssignCopy(wxStrlen(psz), psz);
506 return *this;
507 }
508
509 #if !wxUSE_UNICODE
510
511 // same as 'signed char' variant
512 wxString& wxString::operator=(const unsigned char* psz)
513 {
514 *this = (const char *)psz;
515 return *this;
516 }
517
518 #if wxUSE_WCHAR_T
519 wxString& wxString::operator=(const wchar_t *pwz)
520 {
521 wxString str(pwz);
522 *this = str;
523 return *this;
524 }
525 #endif
526
527 #endif
528
529 // ---------------------------------------------------------------------------
530 // string concatenation
531 // ---------------------------------------------------------------------------
532
533 // add something to this string
534 void wxString::ConcatSelf(int nSrcLen, const wxChar *pszSrcData)
535 {
536 STATISTICS_ADD(SummandLength, nSrcLen);
537
538 // concatenating an empty string is a NOP
539 if ( nSrcLen > 0 ) {
540 wxStringData *pData = GetStringData();
541 size_t nLen = pData->nDataLength;
542 size_t nNewLen = nLen + nSrcLen;
543
544 // alloc new buffer if current is too small
545 if ( pData->IsShared() ) {
546 STATISTICS_ADD(ConcatHit, 0);
547
548 // we have to allocate another buffer
549 wxStringData* pOldData = GetStringData();
550 AllocBuffer(nNewLen);
551 memcpy(m_pchData, pOldData->data(), nLen*sizeof(wxChar));
552 pOldData->Unlock();
553 }
554 else if ( nNewLen > pData->nAllocLength ) {
555 STATISTICS_ADD(ConcatHit, 0);
556
557 // we have to grow the buffer
558 Alloc(nNewLen);
559 }
560 else {
561 STATISTICS_ADD(ConcatHit, 1);
562
563 // the buffer is already big enough
564 }
565
566 // should be enough space
567 wxASSERT( nNewLen <= GetStringData()->nAllocLength );
568
569 // fast concatenation - all is done in our buffer
570 memcpy(m_pchData + nLen, pszSrcData, nSrcLen*sizeof(wxChar));
571
572 m_pchData[nNewLen] = wxT('\0'); // put terminating '\0'
573 GetStringData()->nDataLength = nNewLen; // and fix the length
574 }
575 //else: the string to append was empty
576 }
577
578 /*
579 * concatenation functions come in 5 flavours:
580 * string + string
581 * char + string and string + char
582 * C str + string and string + C str
583 */
584
585 wxString operator+(const wxString& string1, const wxString& string2)
586 {
587 wxASSERT( string1.GetStringData()->IsValid() );
588 wxASSERT( string2.GetStringData()->IsValid() );
589
590 wxString s = string1;
591 s += string2;
592
593 return s;
594 }
595
596 wxString operator+(const wxString& string, wxChar ch)
597 {
598 wxASSERT( string.GetStringData()->IsValid() );
599
600 wxString s = string;
601 s += ch;
602
603 return s;
604 }
605
606 wxString operator+(wxChar ch, const wxString& string)
607 {
608 wxASSERT( string.GetStringData()->IsValid() );
609
610 wxString s = ch;
611 s += string;
612
613 return s;
614 }
615
616 wxString operator+(const wxString& string, const wxChar *psz)
617 {
618 wxASSERT( string.GetStringData()->IsValid() );
619
620 wxString s;
621 s.Alloc(wxStrlen(psz) + string.Len());
622 s = string;
623 s += psz;
624
625 return s;
626 }
627
628 wxString operator+(const wxChar *psz, const wxString& string)
629 {
630 wxASSERT( string.GetStringData()->IsValid() );
631
632 wxString s;
633 s.Alloc(wxStrlen(psz) + string.Len());
634 s = psz;
635 s += string;
636
637 return s;
638 }
639
640 // ===========================================================================
641 // other common string functions
642 // ===========================================================================
643
644 // ---------------------------------------------------------------------------
645 // simple sub-string extraction
646 // ---------------------------------------------------------------------------
647
648 // helper function: clone the data attached to this string
649 void wxString::AllocCopy(wxString& dest, int nCopyLen, int nCopyIndex) const
650 {
651 if ( nCopyLen == 0 ) {
652 dest.Init();
653 }
654 else {
655 dest.AllocBuffer(nCopyLen);
656 memcpy(dest.m_pchData, m_pchData + nCopyIndex, nCopyLen*sizeof(wxChar));
657 }
658 }
659
660 // extract string of length nCount starting at nFirst
661 wxString wxString::Mid(size_t nFirst, size_t nCount) const
662 {
663 wxStringData *pData = GetStringData();
664 size_t nLen = pData->nDataLength;
665
666 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
667 if ( nCount == wxSTRING_MAXLEN )
668 {
669 nCount = nLen - nFirst;
670 }
671
672 // out-of-bounds requests return sensible things
673 if ( nFirst + nCount > nLen )
674 {
675 nCount = nLen - nFirst;
676 }
677
678 if ( nFirst > nLen )
679 {
680 // AllocCopy() will return empty string
681 nCount = 0;
682 }
683
684 wxString dest;
685 AllocCopy(dest, nCount, nFirst);
686
687 return dest;
688 }
689
690 // extract nCount last (rightmost) characters
691 wxString wxString::Right(size_t nCount) const
692 {
693 if ( nCount > (size_t)GetStringData()->nDataLength )
694 nCount = GetStringData()->nDataLength;
695
696 wxString dest;
697 AllocCopy(dest, nCount, GetStringData()->nDataLength - nCount);
698 return dest;
699 }
700
701 // get all characters after the last occurence of ch
702 // (returns the whole string if ch not found)
703 wxString wxString::AfterLast(wxChar ch) const
704 {
705 wxString str;
706 int iPos = Find(ch, TRUE);
707 if ( iPos == wxNOT_FOUND )
708 str = *this;
709 else
710 str = c_str() + iPos + 1;
711
712 return str;
713 }
714
715 // extract nCount first (leftmost) characters
716 wxString wxString::Left(size_t nCount) const
717 {
718 if ( nCount > (size_t)GetStringData()->nDataLength )
719 nCount = GetStringData()->nDataLength;
720
721 wxString dest;
722 AllocCopy(dest, nCount, 0);
723 return dest;
724 }
725
726 // get all characters before the first occurence of ch
727 // (returns the whole string if ch not found)
728 wxString wxString::BeforeFirst(wxChar ch) const
729 {
730 wxString str;
731 for ( const wxChar *pc = m_pchData; *pc != wxT('\0') && *pc != ch; pc++ )
732 str += *pc;
733
734 return str;
735 }
736
737 /// get all characters before the last occurence of ch
738 /// (returns empty string if ch not found)
739 wxString wxString::BeforeLast(wxChar ch) const
740 {
741 wxString str;
742 int iPos = Find(ch, TRUE);
743 if ( iPos != wxNOT_FOUND && iPos != 0 )
744 str = wxString(c_str(), iPos);
745
746 return str;
747 }
748
749 /// get all characters after the first occurence of ch
750 /// (returns empty string if ch not found)
751 wxString wxString::AfterFirst(wxChar ch) const
752 {
753 wxString str;
754 int iPos = Find(ch);
755 if ( iPos != wxNOT_FOUND )
756 str = c_str() + iPos + 1;
757
758 return str;
759 }
760
761 // replace first (or all) occurences of some substring with another one
762 size_t wxString::Replace(const wxChar *szOld, const wxChar *szNew, bool bReplaceAll)
763 {
764 size_t uiCount = 0; // count of replacements made
765
766 size_t uiOldLen = wxStrlen(szOld);
767
768 wxString strTemp;
769 const wxChar *pCurrent = m_pchData;
770 const wxChar *pSubstr;
771 while ( *pCurrent != wxT('\0') ) {
772 pSubstr = wxStrstr(pCurrent, szOld);
773 if ( pSubstr == NULL ) {
774 // strTemp is unused if no replacements were made, so avoid the copy
775 if ( uiCount == 0 )
776 return 0;
777
778 strTemp += pCurrent; // copy the rest
779 break; // exit the loop
780 }
781 else {
782 // take chars before match
783 strTemp.ConcatSelf(pSubstr - pCurrent, pCurrent);
784 strTemp += szNew;
785 pCurrent = pSubstr + uiOldLen; // restart after match
786
787 uiCount++;
788
789 // stop now?
790 if ( !bReplaceAll ) {
791 strTemp += pCurrent; // copy the rest
792 break; // exit the loop
793 }
794 }
795 }
796
797 // only done if there were replacements, otherwise would have returned above
798 *this = strTemp;
799
800 return uiCount;
801 }
802
803 bool wxString::IsAscii() const
804 {
805 const wxChar *s = (const wxChar*) *this;
806 while(*s){
807 if(!isascii(*s)) return(FALSE);
808 s++;
809 }
810 return(TRUE);
811 }
812
813 bool wxString::IsWord() const
814 {
815 const wxChar *s = (const wxChar*) *this;
816 while(*s){
817 if(!wxIsalpha(*s)) return(FALSE);
818 s++;
819 }
820 return(TRUE);
821 }
822
823 bool wxString::IsNumber() const
824 {
825 const wxChar *s = (const wxChar*) *this;
826 while(*s){
827 if(!wxIsdigit(*s)) return(FALSE);
828 s++;
829 }
830 return(TRUE);
831 }
832
833 wxString wxString::Strip(stripType w) const
834 {
835 wxString s = *this;
836 if ( w & leading ) s.Trim(FALSE);
837 if ( w & trailing ) s.Trim(TRUE);
838 return s;
839 }
840
841 // ---------------------------------------------------------------------------
842 // case conversion
843 // ---------------------------------------------------------------------------
844
845 wxString& wxString::MakeUpper()
846 {
847 CopyBeforeWrite();
848
849 for ( wxChar *p = m_pchData; *p; p++ )
850 *p = (wxChar)wxToupper(*p);
851
852 return *this;
853 }
854
855 wxString& wxString::MakeLower()
856 {
857 CopyBeforeWrite();
858
859 for ( wxChar *p = m_pchData; *p; p++ )
860 *p = (wxChar)wxTolower(*p);
861
862 return *this;
863 }
864
865 // ---------------------------------------------------------------------------
866 // trimming and padding
867 // ---------------------------------------------------------------------------
868
869 // trims spaces (in the sense of isspace) from left or right side
870 wxString& wxString::Trim(bool bFromRight)
871 {
872 // first check if we're going to modify the string at all
873 if ( !IsEmpty() &&
874 (
875 (bFromRight && wxIsspace(GetChar(Len() - 1))) ||
876 (!bFromRight && wxIsspace(GetChar(0u)))
877 )
878 )
879 {
880 // ok, there is at least one space to trim
881 CopyBeforeWrite();
882
883 if ( bFromRight )
884 {
885 // find last non-space character
886 wxChar *psz = m_pchData + GetStringData()->nDataLength - 1;
887 while ( wxIsspace(*psz) && (psz >= m_pchData) )
888 psz--;
889
890 // truncate at trailing space start
891 *++psz = wxT('\0');
892 GetStringData()->nDataLength = psz - m_pchData;
893 }
894 else
895 {
896 // find first non-space character
897 const wxChar *psz = m_pchData;
898 while ( wxIsspace(*psz) )
899 psz++;
900
901 // fix up data and length
902 int nDataLength = GetStringData()->nDataLength - (psz - (const wxChar*) m_pchData);
903 memmove(m_pchData, psz, (nDataLength + 1)*sizeof(wxChar));
904 GetStringData()->nDataLength = nDataLength;
905 }
906 }
907
908 return *this;
909 }
910
911 // adds nCount characters chPad to the string from either side
912 wxString& wxString::Pad(size_t nCount, wxChar chPad, bool bFromRight)
913 {
914 wxString s(chPad, nCount);
915
916 if ( bFromRight )
917 *this += s;
918 else
919 {
920 s += *this;
921 *this = s;
922 }
923
924 return *this;
925 }
926
927 // truncate the string
928 wxString& wxString::Truncate(size_t uiLen)
929 {
930 if ( uiLen < Len() ) {
931 CopyBeforeWrite();
932
933 *(m_pchData + uiLen) = wxT('\0');
934 GetStringData()->nDataLength = uiLen;
935 }
936 //else: nothing to do, string is already short enough
937
938 return *this;
939 }
940
941 // ---------------------------------------------------------------------------
942 // finding (return wxNOT_FOUND if not found and index otherwise)
943 // ---------------------------------------------------------------------------
944
945 // find a character
946 int wxString::Find(wxChar ch, bool bFromEnd) const
947 {
948 const wxChar *psz = bFromEnd ? wxStrrchr(m_pchData, ch) : wxStrchr(m_pchData, ch);
949
950 return (psz == NULL) ? wxNOT_FOUND : psz - (const wxChar*) m_pchData;
951 }
952
953 // find a sub-string (like strstr)
954 int wxString::Find(const wxChar *pszSub) const
955 {
956 const wxChar *psz = wxStrstr(m_pchData, pszSub);
957
958 return (psz == NULL) ? wxNOT_FOUND : psz - (const wxChar*) m_pchData;
959 }
960
961 // ---------------------------------------------------------------------------
962 // stream-like operators
963 // ---------------------------------------------------------------------------
964 wxString& wxString::operator<<(int i)
965 {
966 wxString res;
967 res.Printf(wxT("%d"), i);
968
969 return (*this) << res;
970 }
971
972 wxString& wxString::operator<<(float f)
973 {
974 wxString res;
975 res.Printf(wxT("%f"), f);
976
977 return (*this) << res;
978 }
979
980 wxString& wxString::operator<<(double d)
981 {
982 wxString res;
983 res.Printf(wxT("%g"), d);
984
985 return (*this) << res;
986 }
987
988 // ---------------------------------------------------------------------------
989 // formatted output
990 // ---------------------------------------------------------------------------
991 int wxString::Printf(const wxChar *pszFormat, ...)
992 {
993 va_list argptr;
994 va_start(argptr, pszFormat);
995
996 int iLen = PrintfV(pszFormat, argptr);
997
998 va_end(argptr);
999
1000 return iLen;
1001 }
1002
1003 int wxString::PrintfV(const wxChar* pszFormat, va_list argptr)
1004 {
1005 // static buffer to avoid dynamic memory allocation each time
1006 char s_szScratch[1024]; // using static buffer causes internal compiler err
1007 #if 0
1008 #if wxUSE_THREADS
1009 // protect the static buffer
1010 static wxCriticalSection critsect;
1011 wxCriticalSectionLocker lock(critsect);
1012 #endif
1013 #endif
1014
1015 #if wxUSE_EXPERIMENTAL_PRINTF
1016 // the new implementation
1017
1018 Reinit();
1019 for (size_t n = 0; pszFormat[n]; n++)
1020 if (pszFormat[n] == wxT('%')) {
1021 static char s_szFlags[256] = "%";
1022 size_t flagofs = 1;
1023 bool adj_left = FALSE, in_prec = FALSE,
1024 prec_dot = FALSE, done = FALSE;
1025 int ilen = 0;
1026 size_t min_width = 0, max_width = wxSTRING_MAXLEN;
1027 do {
1028 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1029 switch (pszFormat[++n]) {
1030 case wxT('\0'):
1031 done = TRUE;
1032 break;
1033 case wxT('%'):
1034 *this += wxT('%');
1035 done = TRUE;
1036 break;
1037 case wxT('#'):
1038 case wxT('0'):
1039 case wxT(' '):
1040 case wxT('+'):
1041 case wxT('\''):
1042 CHECK_PREC
1043 s_szFlags[flagofs++] = pszFormat[n];
1044 break;
1045 case wxT('-'):
1046 CHECK_PREC
1047 adj_left = TRUE;
1048 s_szFlags[flagofs++] = pszFormat[n];
1049 break;
1050 case wxT('.'):
1051 CHECK_PREC
1052 in_prec = TRUE;
1053 prec_dot = FALSE;
1054 max_width = 0;
1055 // dot will be auto-added to s_szFlags if non-negative number follows
1056 break;
1057 case wxT('h'):
1058 ilen = -1;
1059 CHECK_PREC
1060 s_szFlags[flagofs++] = pszFormat[n];
1061 break;
1062 case wxT('l'):
1063 ilen = 1;
1064 CHECK_PREC
1065 s_szFlags[flagofs++] = pszFormat[n];
1066 break;
1067 case wxT('q'):
1068 case wxT('L'):
1069 ilen = 2;
1070 CHECK_PREC
1071 s_szFlags[flagofs++] = pszFormat[n];
1072 break;
1073 case wxT('Z'):
1074 ilen = 3;
1075 CHECK_PREC
1076 s_szFlags[flagofs++] = pszFormat[n];
1077 break;
1078 case wxT('*'):
1079 {
1080 int len = va_arg(argptr, int);
1081 if (in_prec) {
1082 if (len<0) break;
1083 CHECK_PREC
1084 max_width = len;
1085 } else {
1086 if (len<0) {
1087 adj_left = !adj_left;
1088 s_szFlags[flagofs++] = '-';
1089 len = -len;
1090 }
1091 min_width = len;
1092 }
1093 flagofs += ::sprintf(s_szFlags+flagofs,"%d",len);
1094 }
1095 break;
1096 case wxT('1'): case wxT('2'): case wxT('3'):
1097 case wxT('4'): case wxT('5'): case wxT('6'):
1098 case wxT('7'): case wxT('8'): case wxT('9'):
1099 {
1100 int len = 0;
1101 CHECK_PREC
1102 while ((pszFormat[n]>=wxT('0')) && (pszFormat[n]<=wxT('9'))) {
1103 s_szFlags[flagofs++] = pszFormat[n];
1104 len = len*10 + (pszFormat[n] - wxT('0'));
1105 n++;
1106 }
1107 if (in_prec) max_width = len;
1108 else min_width = len;
1109 n--; // the main loop pre-increments n again
1110 }
1111 break;
1112 case wxT('d'):
1113 case wxT('i'):
1114 case wxT('o'):
1115 case wxT('u'):
1116 case wxT('x'):
1117 case wxT('X'):
1118 CHECK_PREC
1119 s_szFlags[flagofs++] = pszFormat[n];
1120 s_szFlags[flagofs] = '\0';
1121 if (ilen == 0 ) {
1122 int val = va_arg(argptr, int);
1123 ::sprintf(s_szScratch, s_szFlags, val);
1124 }
1125 else if (ilen == -1) {
1126 short int val = va_arg(argptr, short int);
1127 ::sprintf(s_szScratch, s_szFlags, val);
1128 }
1129 else if (ilen == 1) {
1130 long int val = va_arg(argptr, long int);
1131 ::sprintf(s_szScratch, s_szFlags, val);
1132 }
1133 else if (ilen == 2) {
1134 #if SIZEOF_LONG_LONG
1135 long long int val = va_arg(argptr, long long int);
1136 ::sprintf(s_szScratch, s_szFlags, val);
1137 #else
1138 long int val = va_arg(argptr, long int);
1139 ::sprintf(s_szScratch, s_szFlags, val);
1140 #endif
1141 }
1142 else if (ilen == 3) {
1143 size_t val = va_arg(argptr, size_t);
1144 ::sprintf(s_szScratch, s_szFlags, val);
1145 }
1146 *this += wxString(s_szScratch);
1147 done = TRUE;
1148 break;
1149 case wxT('e'):
1150 case wxT('E'):
1151 case wxT('f'):
1152 case wxT('g'):
1153 case wxT('G'):
1154 CHECK_PREC
1155 s_szFlags[flagofs++] = pszFormat[n];
1156 s_szFlags[flagofs] = '\0';
1157 if (ilen == 2) {
1158 long double val = va_arg(argptr, long double);
1159 ::sprintf(s_szScratch, s_szFlags, val);
1160 } else {
1161 double val = va_arg(argptr, double);
1162 ::sprintf(s_szScratch, s_szFlags, val);
1163 }
1164 *this += wxString(s_szScratch);
1165 done = TRUE;
1166 break;
1167 case wxT('p'):
1168 {
1169 void *val = va_arg(argptr, void *);
1170 CHECK_PREC
1171 s_szFlags[flagofs++] = pszFormat[n];
1172 s_szFlags[flagofs] = '\0';
1173 ::sprintf(s_szScratch, s_szFlags, val);
1174 *this += wxString(s_szScratch);
1175 done = TRUE;
1176 }
1177 break;
1178 case wxT('c'):
1179 {
1180 wxChar val = va_arg(argptr, int);
1181 // we don't need to honor padding here, do we?
1182 *this += val;
1183 done = TRUE;
1184 }
1185 break;
1186 case wxT('s'):
1187 if (ilen == -1) {
1188 // wx extension: we'll let %hs mean non-Unicode strings
1189 char *val = va_arg(argptr, char *);
1190 #if wxUSE_UNICODE
1191 // ASCII->Unicode constructor handles max_width right
1192 wxString s(val, wxConvLibc, max_width);
1193 #else
1194 size_t len = wxSTRING_MAXLEN;
1195 if (val) {
1196 for (len = 0; val[len] && (len<max_width); len++);
1197 } else val = wxT("(null)");
1198 wxString s(val, len);
1199 #endif
1200 if (s.Len() < min_width)
1201 s.Pad(min_width - s.Len(), wxT(' '), adj_left);
1202 *this += s;
1203 } else {
1204 wxChar *val = va_arg(argptr, wxChar *);
1205 size_t len = wxSTRING_MAXLEN;
1206 if (val) {
1207 for (len = 0; val[len] && (len<max_width); len++);
1208 } else val = wxT("(null)");
1209 wxString s(val, len);
1210 if (s.Len() < min_width)
1211 s.Pad(min_width - s.Len(), wxT(' '), adj_left);
1212 *this += s;
1213 }
1214 done = TRUE;
1215 break;
1216 case wxT('n'):
1217 if (ilen == 0) {
1218 int *val = va_arg(argptr, int *);
1219 *val = Len();
1220 }
1221 else if (ilen == -1) {
1222 short int *val = va_arg(argptr, short int *);
1223 *val = Len();
1224 }
1225 else if (ilen >= 1) {
1226 long int *val = va_arg(argptr, long int *);
1227 *val = Len();
1228 }
1229 done = TRUE;
1230 break;
1231 default:
1232 if (wxIsalpha(pszFormat[n]))
1233 // probably some flag not taken care of here yet
1234 s_szFlags[flagofs++] = pszFormat[n];
1235 else {
1236 // bad format
1237 *this += wxT('%'); // just to pass the glibc tst-printf.c
1238 n--;
1239 done = TRUE;
1240 }
1241 break;
1242 }
1243 #undef CHECK_PREC
1244 } while (!done);
1245 } else *this += pszFormat[n];
1246
1247 #else
1248 // NB: wxVsnprintf() may return either less than the buffer size or -1 if there
1249 // is not enough place depending on implementation
1250 int iLen = wxVsnprintf(s_szScratch, WXSIZEOF(s_szScratch), pszFormat, argptr);
1251 char *buffer;
1252 if ( iLen < (int)WXSIZEOF(s_szScratch) ) {
1253 buffer = s_szScratch;
1254 }
1255 else {
1256 int size = WXSIZEOF(s_szScratch) * 2;
1257 buffer = (char *)malloc(size);
1258 while ( buffer != NULL ) {
1259 iLen = wxVsnprintf(buffer, WXSIZEOF(s_szScratch), pszFormat, argptr);
1260 if ( iLen < size ) {
1261 // ok, there was enough space
1262 break;
1263 }
1264
1265 // still not enough, double it again
1266 buffer = (char *)realloc(buffer, size *= 2);
1267 }
1268
1269 if ( !buffer ) {
1270 // out of memory
1271 return -1;
1272 }
1273 }
1274
1275 wxString s(buffer);
1276 *this = s;
1277
1278 if ( buffer != s_szScratch )
1279 free(buffer);
1280 #endif
1281
1282 return Len();
1283 }
1284
1285 // ----------------------------------------------------------------------------
1286 // misc other operations
1287 // ----------------------------------------------------------------------------
1288
1289 // returns TRUE if the string matches the pattern which may contain '*' and
1290 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1291 // of them)
1292 bool wxString::Matches(const wxChar *pszMask) const
1293 {
1294 // check char by char
1295 const wxChar *pszTxt;
1296 for ( pszTxt = c_str(); *pszMask != wxT('\0'); pszMask++, pszTxt++ ) {
1297 switch ( *pszMask ) {
1298 case wxT('?'):
1299 if ( *pszTxt == wxT('\0') )
1300 return FALSE;
1301
1302 // pszText and pszMask will be incremented in the loop statement
1303
1304 break;
1305
1306 case wxT('*'):
1307 {
1308 // ignore special chars immediately following this one
1309 while ( *pszMask == wxT('*') || *pszMask == wxT('?') )
1310 pszMask++;
1311
1312 // if there is nothing more, match
1313 if ( *pszMask == wxT('\0') )
1314 return TRUE;
1315
1316 // are there any other metacharacters in the mask?
1317 size_t uiLenMask;
1318 const wxChar *pEndMask = wxStrpbrk(pszMask, wxT("*?"));
1319
1320 if ( pEndMask != NULL ) {
1321 // we have to match the string between two metachars
1322 uiLenMask = pEndMask - pszMask;
1323 }
1324 else {
1325 // we have to match the remainder of the string
1326 uiLenMask = wxStrlen(pszMask);
1327 }
1328
1329 wxString strToMatch(pszMask, uiLenMask);
1330 const wxChar* pMatch = wxStrstr(pszTxt, strToMatch);
1331 if ( pMatch == NULL )
1332 return FALSE;
1333
1334 // -1 to compensate "++" in the loop
1335 pszTxt = pMatch + uiLenMask - 1;
1336 pszMask += uiLenMask - 1;
1337 }
1338 break;
1339
1340 default:
1341 if ( *pszMask != *pszTxt )
1342 return FALSE;
1343 break;
1344 }
1345 }
1346
1347 // match only if nothing left
1348 return *pszTxt == wxT('\0');
1349 }
1350
1351 // Count the number of chars
1352 int wxString::Freq(wxChar ch) const
1353 {
1354 int count = 0;
1355 int len = Len();
1356 for (int i = 0; i < len; i++)
1357 {
1358 if (GetChar(i) == ch)
1359 count ++;
1360 }
1361 return count;
1362 }
1363
1364 // convert to upper case, return the copy of the string
1365 wxString wxString::Upper() const
1366 { wxString s(*this); return s.MakeUpper(); }
1367
1368 // convert to lower case, return the copy of the string
1369 wxString wxString::Lower() const { wxString s(*this); return s.MakeLower(); }
1370
1371 int wxString::sprintf(const wxChar *pszFormat, ...)
1372 {
1373 va_list argptr;
1374 va_start(argptr, pszFormat);
1375 int iLen = PrintfV(pszFormat, argptr);
1376 va_end(argptr);
1377 return iLen;
1378 }
1379
1380 // ---------------------------------------------------------------------------
1381 // standard C++ library string functions
1382 // ---------------------------------------------------------------------------
1383 #ifdef wxSTD_STRING_COMPATIBILITY
1384
1385 wxString& wxString::insert(size_t nPos, const wxString& str)
1386 {
1387 wxASSERT( str.GetStringData()->IsValid() );
1388 wxASSERT( nPos <= Len() );
1389
1390 if ( !str.IsEmpty() ) {
1391 wxString strTmp;
1392 wxChar *pc = strTmp.GetWriteBuf(Len() + str.Len());
1393 wxStrncpy(pc, c_str(), nPos);
1394 wxStrcpy(pc + nPos, str);
1395 wxStrcpy(pc + nPos + str.Len(), c_str() + nPos);
1396 strTmp.UngetWriteBuf();
1397 *this = strTmp;
1398 }
1399
1400 return *this;
1401 }
1402
1403 size_t wxString::find(const wxString& str, size_t nStart) const
1404 {
1405 wxASSERT( str.GetStringData()->IsValid() );
1406 wxASSERT( nStart <= Len() );
1407
1408 const wxChar *p = wxStrstr(c_str() + nStart, str);
1409
1410 return p == NULL ? npos : p - c_str();
1411 }
1412
1413 // VC++ 1.5 can't cope with the default argument in the header.
1414 #if !defined(__VISUALC__) || defined(__WIN32__)
1415 size_t wxString::find(const wxChar* sz, size_t nStart, size_t n) const
1416 {
1417 return find(wxString(sz, n == npos ? 0 : n), nStart);
1418 }
1419 #endif // VC++ 1.5
1420
1421 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1422 #if !defined(__BORLANDC__)
1423 size_t wxString::find(wxChar ch, size_t nStart) const
1424 {
1425 wxASSERT( nStart <= Len() );
1426
1427 const wxChar *p = wxStrchr(c_str() + nStart, ch);
1428
1429 return p == NULL ? npos : p - c_str();
1430 }
1431 #endif
1432
1433 size_t wxString::rfind(const wxString& str, size_t nStart) const
1434 {
1435 wxASSERT( str.GetStringData()->IsValid() );
1436 wxASSERT( nStart <= Len() );
1437
1438 // TODO could be made much quicker than that
1439 const wxChar *p = c_str() + (nStart == npos ? Len() : nStart);
1440 while ( p >= c_str() + str.Len() ) {
1441 if ( wxStrncmp(p - str.Len(), str, str.Len()) == 0 )
1442 return p - str.Len() - c_str();
1443 p--;
1444 }
1445
1446 return npos;
1447 }
1448
1449 // VC++ 1.5 can't cope with the default argument in the header.
1450 #if !defined(__VISUALC__) || defined(__WIN32__)
1451 size_t wxString::rfind(const wxChar* sz, size_t nStart, size_t n) const
1452 {
1453 return rfind(wxString(sz, n == npos ? 0 : n), nStart);
1454 }
1455
1456 size_t wxString::rfind(wxChar ch, size_t nStart) const
1457 {
1458 if ( nStart == npos )
1459 {
1460 nStart = Len();
1461 }
1462 else
1463 {
1464 wxASSERT( nStart <= Len() );
1465 }
1466
1467 const wxChar *p = wxStrrchr(c_str(), ch);
1468
1469 if ( p == NULL )
1470 return npos;
1471
1472 size_t result = p - c_str();
1473 return ( result > nStart ) ? npos : result;
1474 }
1475 #endif // VC++ 1.5
1476
1477 size_t wxString::find_first_of(const wxChar* sz, size_t nStart) const
1478 {
1479 const wxChar *start = c_str() + nStart;
1480 const wxChar *firstOf = wxStrpbrk(start, sz);
1481 if ( firstOf )
1482 return firstOf - start;
1483 else
1484 return npos;
1485 }
1486
1487 size_t wxString::find_last_of(const wxChar* sz, size_t nStart) const
1488 {
1489 if ( nStart == npos )
1490 {
1491 nStart = Len();
1492 }
1493 else
1494 {
1495 wxASSERT( nStart <= Len() );
1496 }
1497
1498 for ( const wxChar *p = c_str() + length() - 1; p >= c_str(); p-- )
1499 {
1500 if ( wxStrchr(sz, *p) )
1501 return p - c_str();
1502 }
1503
1504 return npos;
1505 }
1506
1507 size_t wxString::find_first_not_of(const wxChar* sz, size_t nStart) const
1508 {
1509 if ( nStart == npos )
1510 {
1511 nStart = Len();
1512 }
1513 else
1514 {
1515 wxASSERT( nStart <= Len() );
1516 }
1517
1518 size_t nAccept = wxStrspn(c_str() + nStart, sz);
1519 if ( nAccept >= length() - nStart )
1520 return npos;
1521 else
1522 return nAccept;
1523 }
1524
1525 size_t wxString::find_first_not_of(wxChar ch, size_t nStart) const
1526 {
1527 wxASSERT( nStart <= Len() );
1528
1529 for ( const wxChar *p = c_str() + nStart; *p; p++ )
1530 {
1531 if ( *p != ch )
1532 return p - c_str();
1533 }
1534
1535 return npos;
1536 }
1537
1538 size_t wxString::find_last_not_of(const wxChar* sz, size_t nStart) const
1539 {
1540 if ( nStart == npos )
1541 {
1542 nStart = Len();
1543 }
1544 else
1545 {
1546 wxASSERT( nStart <= Len() );
1547 }
1548
1549 for ( const wxChar *p = c_str() + nStart - 1; p >= c_str(); p-- )
1550 {
1551 if ( !wxStrchr(sz, *p) )
1552 return p - c_str();
1553 }
1554
1555 return npos;
1556 }
1557
1558 size_t wxString::find_last_not_of(wxChar ch, size_t nStart) const
1559 {
1560 if ( nStart == npos )
1561 {
1562 nStart = Len();
1563 }
1564 else
1565 {
1566 wxASSERT( nStart <= Len() );
1567 }
1568
1569 for ( const wxChar *p = c_str() + nStart - 1; p >= c_str(); p-- )
1570 {
1571 if ( *p != ch )
1572 return p - c_str();
1573 }
1574
1575 return npos;
1576 }
1577
1578 wxString wxString::substr(size_t nStart, size_t nLen) const
1579 {
1580 // npos means 'take all'
1581 if ( nLen == npos )
1582 nLen = 0;
1583
1584 wxASSERT( nStart + nLen <= Len() );
1585
1586 return wxString(c_str() + nStart, nLen == npos ? 0 : nLen);
1587 }
1588
1589 wxString& wxString::erase(size_t nStart, size_t nLen)
1590 {
1591 wxString strTmp(c_str(), nStart);
1592 if ( nLen != npos ) {
1593 wxASSERT( nStart + nLen <= Len() );
1594
1595 strTmp.append(c_str() + nStart + nLen);
1596 }
1597
1598 *this = strTmp;
1599 return *this;
1600 }
1601
1602 wxString& wxString::replace(size_t nStart, size_t nLen, const wxChar *sz)
1603 {
1604 wxASSERT( nStart + nLen <= wxStrlen(sz) );
1605
1606 wxString strTmp;
1607 if ( nStart != 0 )
1608 strTmp.append(c_str(), nStart);
1609 strTmp += sz;
1610 strTmp.append(c_str() + nStart + nLen);
1611
1612 *this = strTmp;
1613 return *this;
1614 }
1615
1616 wxString& wxString::replace(size_t nStart, size_t nLen, size_t nCount, wxChar ch)
1617 {
1618 return replace(nStart, nLen, wxString(ch, nCount));
1619 }
1620
1621 wxString& wxString::replace(size_t nStart, size_t nLen,
1622 const wxString& str, size_t nStart2, size_t nLen2)
1623 {
1624 return replace(nStart, nLen, str.substr(nStart2, nLen2));
1625 }
1626
1627 wxString& wxString::replace(size_t nStart, size_t nLen,
1628 const wxChar* sz, size_t nCount)
1629 {
1630 return replace(nStart, nLen, wxString(sz, nCount));
1631 }
1632
1633 #endif //std::string compatibility
1634
1635 // ============================================================================
1636 // ArrayString
1637 // ============================================================================
1638
1639 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1640 #define ARRAY_MAXSIZE_INCREMENT 4096
1641 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1642 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1643 #endif
1644
1645 #define STRING(p) ((wxString *)(&(p)))
1646
1647 // ctor
1648 wxArrayString::wxArrayString(bool autoSort)
1649 {
1650 m_nSize =
1651 m_nCount = 0;
1652 m_pItems = (wxChar **) NULL;
1653 m_autoSort = autoSort;
1654 }
1655
1656 // copy ctor
1657 wxArrayString::wxArrayString(const wxArrayString& src)
1658 {
1659 m_nSize =
1660 m_nCount = 0;
1661 m_pItems = (wxChar **) NULL;
1662 m_autoSort = src.m_autoSort;
1663
1664 *this = src;
1665 }
1666
1667 // assignment operator
1668 wxArrayString& wxArrayString::operator=(const wxArrayString& src)
1669 {
1670 if ( m_nSize > 0 )
1671 Clear();
1672
1673 Copy(src);
1674
1675 return *this;
1676 }
1677
1678 void wxArrayString::Copy(const wxArrayString& src)
1679 {
1680 if ( src.m_nCount > ARRAY_DEFAULT_INITIAL_SIZE )
1681 Alloc(src.m_nCount);
1682
1683 // we can't just copy the pointers here because otherwise we would share
1684 // the strings with another array because strings are ref counted
1685 #if 0
1686 if ( m_nCount != 0 )
1687 memcpy(m_pItems, src.m_pItems, m_nCount*sizeof(wxChar *));
1688 #endif // 0
1689
1690 for ( size_t n = 0; n < src.m_nCount; n++ )
1691 Add(src[n]);
1692
1693 // if the other array is auto sorted too, we're already sorted, but
1694 // otherwise we should rearrange the items
1695 if ( m_autoSort && !src.m_autoSort )
1696 Sort();
1697 }
1698
1699 // grow the array
1700 void wxArrayString::Grow()
1701 {
1702 // only do it if no more place
1703 if( m_nCount == m_nSize ) {
1704 if( m_nSize == 0 ) {
1705 // was empty, alloc some memory
1706 m_nSize = ARRAY_DEFAULT_INITIAL_SIZE;
1707 m_pItems = new wxChar *[m_nSize];
1708 }
1709 else {
1710 // otherwise when it's called for the first time, nIncrement would be 0
1711 // and the array would never be expanded
1712 #if defined(__VISAGECPP__) && defined(__WXDEBUG__)
1713 int array_size = ARRAY_DEFAULT_INITIAL_SIZE;
1714 wxASSERT( array_size != 0 );
1715 #else
1716 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE != 0 );
1717 #endif
1718
1719 // add 50% but not too much
1720 size_t nIncrement = m_nSize < ARRAY_DEFAULT_INITIAL_SIZE
1721 ? ARRAY_DEFAULT_INITIAL_SIZE : m_nSize >> 1;
1722 if ( nIncrement > ARRAY_MAXSIZE_INCREMENT )
1723 nIncrement = ARRAY_MAXSIZE_INCREMENT;
1724 m_nSize += nIncrement;
1725 wxChar **pNew = new wxChar *[m_nSize];
1726
1727 // copy data to new location
1728 memcpy(pNew, m_pItems, m_nCount*sizeof(wxChar *));
1729
1730 // delete old memory (but do not release the strings!)
1731 wxDELETEA(m_pItems);
1732
1733 m_pItems = pNew;
1734 }
1735 }
1736 }
1737
1738 void wxArrayString::Free()
1739 {
1740 for ( size_t n = 0; n < m_nCount; n++ ) {
1741 STRING(m_pItems[n])->GetStringData()->Unlock();
1742 }
1743 }
1744
1745 // deletes all the strings from the list
1746 void wxArrayString::Empty()
1747 {
1748 Free();
1749
1750 m_nCount = 0;
1751 }
1752
1753 // as Empty, but also frees memory
1754 void wxArrayString::Clear()
1755 {
1756 Free();
1757
1758 m_nSize =
1759 m_nCount = 0;
1760
1761 wxDELETEA(m_pItems);
1762 }
1763
1764 // dtor
1765 wxArrayString::~wxArrayString()
1766 {
1767 Free();
1768
1769 wxDELETEA(m_pItems);
1770 }
1771
1772 // pre-allocates memory (frees the previous data!)
1773 void wxArrayString::Alloc(size_t nSize)
1774 {
1775 wxASSERT( nSize > 0 );
1776
1777 // only if old buffer was not big enough
1778 if ( nSize > m_nSize ) {
1779 Free();
1780 wxDELETEA(m_pItems);
1781 m_pItems = new wxChar *[nSize];
1782 m_nSize = nSize;
1783 }
1784
1785 m_nCount = 0;
1786 }
1787
1788 // minimizes the memory usage by freeing unused memory
1789 void wxArrayString::Shrink()
1790 {
1791 // only do it if we have some memory to free
1792 if( m_nCount < m_nSize ) {
1793 // allocates exactly as much memory as we need
1794 wxChar **pNew = new wxChar *[m_nCount];
1795
1796 // copy data to new location
1797 memcpy(pNew, m_pItems, m_nCount*sizeof(wxChar *));
1798 delete [] m_pItems;
1799 m_pItems = pNew;
1800 }
1801 }
1802
1803 // searches the array for an item (forward or backwards)
1804 int wxArrayString::Index(const wxChar *sz, bool bCase, bool bFromEnd) const
1805 {
1806 if ( m_autoSort ) {
1807 // use binary search in the sorted array
1808 wxASSERT_MSG( bCase && !bFromEnd,
1809 wxT("search parameters ignored for auto sorted array") );
1810
1811 size_t i,
1812 lo = 0,
1813 hi = m_nCount;
1814 int res;
1815 while ( lo < hi ) {
1816 i = (lo + hi)/2;
1817
1818 res = wxStrcmp(sz, m_pItems[i]);
1819 if ( res < 0 )
1820 hi = i;
1821 else if ( res > 0 )
1822 lo = i + 1;
1823 else
1824 return i;
1825 }
1826
1827 return wxNOT_FOUND;
1828 }
1829 else {
1830 // use linear search in unsorted array
1831 if ( bFromEnd ) {
1832 if ( m_nCount > 0 ) {
1833 size_t ui = m_nCount;
1834 do {
1835 if ( STRING(m_pItems[--ui])->IsSameAs(sz, bCase) )
1836 return ui;
1837 }
1838 while ( ui != 0 );
1839 }
1840 }
1841 else {
1842 for( size_t ui = 0; ui < m_nCount; ui++ ) {
1843 if( STRING(m_pItems[ui])->IsSameAs(sz, bCase) )
1844 return ui;
1845 }
1846 }
1847 }
1848
1849 return wxNOT_FOUND;
1850 }
1851
1852 // add item at the end
1853 size_t wxArrayString::Add(const wxString& str)
1854 {
1855 if ( m_autoSort ) {
1856 // insert the string at the correct position to keep the array sorted
1857 size_t i,
1858 lo = 0,
1859 hi = m_nCount;
1860 int res;
1861 while ( lo < hi ) {
1862 i = (lo + hi)/2;
1863
1864 res = wxStrcmp(str, m_pItems[i]);
1865 if ( res < 0 )
1866 hi = i;
1867 else if ( res > 0 )
1868 lo = i + 1;
1869 else {
1870 lo = hi = i;
1871 break;
1872 }
1873 }
1874
1875 wxASSERT_MSG( lo == hi, wxT("binary search broken") );
1876
1877 Insert(str, lo);
1878
1879 return (size_t)lo;
1880 }
1881 else {
1882 wxASSERT( str.GetStringData()->IsValid() );
1883
1884 Grow();
1885
1886 // the string data must not be deleted!
1887 str.GetStringData()->Lock();
1888
1889 // just append
1890 m_pItems[m_nCount] = (wxChar *)str.c_str(); // const_cast
1891
1892 return m_nCount++;
1893 }
1894 }
1895
1896 // add item at the given position
1897 void wxArrayString::Insert(const wxString& str, size_t nIndex)
1898 {
1899 wxASSERT( str.GetStringData()->IsValid() );
1900
1901 wxCHECK_RET( nIndex <= m_nCount, wxT("bad index in wxArrayString::Insert") );
1902
1903 Grow();
1904
1905 memmove(&m_pItems[nIndex + 1], &m_pItems[nIndex],
1906 (m_nCount - nIndex)*sizeof(wxChar *));
1907
1908 str.GetStringData()->Lock();
1909 m_pItems[nIndex] = (wxChar *)str.c_str();
1910
1911 m_nCount++;
1912 }
1913
1914 // removes item from array (by index)
1915 void wxArrayString::Remove(size_t nIndex)
1916 {
1917 wxCHECK_RET( nIndex <= m_nCount, wxT("bad index in wxArrayString::Remove") );
1918
1919 // release our lock
1920 Item(nIndex).GetStringData()->Unlock();
1921
1922 memmove(&m_pItems[nIndex], &m_pItems[nIndex + 1],
1923 (m_nCount - nIndex - 1)*sizeof(wxChar *));
1924 m_nCount--;
1925 }
1926
1927 // removes item from array (by value)
1928 void wxArrayString::Remove(const wxChar *sz)
1929 {
1930 int iIndex = Index(sz);
1931
1932 wxCHECK_RET( iIndex != wxNOT_FOUND,
1933 wxT("removing inexistent element in wxArrayString::Remove") );
1934
1935 Remove(iIndex);
1936 }
1937
1938 // ----------------------------------------------------------------------------
1939 // sorting
1940 // ----------------------------------------------------------------------------
1941
1942 // we can only sort one array at a time with the quick-sort based
1943 // implementation
1944 #if wxUSE_THREADS
1945 // need a critical section to protect access to gs_compareFunction and
1946 // gs_sortAscending variables
1947 static wxCriticalSection *gs_critsectStringSort = NULL;
1948
1949 // call this before the value of the global sort vars is changed/after
1950 // you're finished with them
1951 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
1952 gs_critsectStringSort = new wxCriticalSection; \
1953 gs_critsectStringSort->Enter()
1954 #define END_SORT() gs_critsectStringSort->Leave(); \
1955 delete gs_critsectStringSort; \
1956 gs_critsectStringSort = NULL
1957 #else // !threads
1958 #define START_SORT()
1959 #define END_SORT()
1960 #endif // wxUSE_THREADS
1961
1962 // function to use for string comparaison
1963 static wxArrayString::CompareFunction gs_compareFunction = NULL;
1964
1965 // if we don't use the compare function, this flag tells us if we sort the
1966 // array in ascending or descending order
1967 static bool gs_sortAscending = TRUE;
1968
1969 // function which is called by quick sort
1970 static int LINKAGEMODE wxStringCompareFunction(const void *first, const void *second)
1971 {
1972 wxString *strFirst = (wxString *)first;
1973 wxString *strSecond = (wxString *)second;
1974
1975 if ( gs_compareFunction ) {
1976 return gs_compareFunction(*strFirst, *strSecond);
1977 }
1978 else {
1979 // maybe we should use wxStrcoll
1980 int result = wxStrcmp(strFirst->c_str(), strSecond->c_str());
1981
1982 return gs_sortAscending ? result : -result;
1983 }
1984 }
1985
1986 // sort array elements using passed comparaison function
1987 void wxArrayString::Sort(CompareFunction compareFunction)
1988 {
1989 START_SORT();
1990
1991 wxASSERT( !gs_compareFunction ); // must have been reset to NULL
1992 gs_compareFunction = compareFunction;
1993
1994 DoSort();
1995
1996 END_SORT();
1997 }
1998
1999 void wxArrayString::Sort(bool reverseOrder)
2000 {
2001 START_SORT();
2002
2003 wxASSERT( !gs_compareFunction ); // must have been reset to NULL
2004 gs_sortAscending = !reverseOrder;
2005
2006 DoSort();
2007
2008 END_SORT();
2009 }
2010
2011 void wxArrayString::DoSort()
2012 {
2013 wxCHECK_RET( !m_autoSort, wxT("can't use this method with sorted arrays") );
2014
2015 // just sort the pointers using qsort() - of course it only works because
2016 // wxString() *is* a pointer to its data
2017 qsort(m_pItems, m_nCount, sizeof(wxChar *), wxStringCompareFunction);
2018 }
2019