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