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