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