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