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