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