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