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