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