]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/string.cpp
fingers crossed..
[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#if defined(__VISAGECPP__) && __IBMCPP__ >= 400
89// must define this static for VA or else you get multiply defined symbols
90// everywhere
91const unsigned int wxSTRING_MAXLEN = UINT_MAX - 100;
92#endif // Visual Age
93
94// empty C style string: points to 'string data' byte of g_strEmpty
95extern 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
156wxSTD 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
187wxSTD 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
195extern 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
222extern 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>
273wxString::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
290void 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
313wxString::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
324wxString::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
347wxString::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
370void 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
395void 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
410void 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
452void 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)
498void 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
517wxChar *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
528void wxString::UngetWriteBuf()
529{
530 GetStringData()->nDataLength = wxStrlen(m_pchData);
531 GetStringData()->Validate(TRUE);
532}
533
534void 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
551void 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
565wxString& 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
586wxString& wxString::operator=(wxChar ch)
587{
588 AssignCopy(1, &ch);
589 return *this;
590}
591
592// assigns C string
593wxString& 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
602wxString& wxString::operator=(const unsigned char* psz)
603{
604 *this = (const char *)psz;
605 return *this;
606}
607
608#if wxUSE_WCHAR_T
609wxString& 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
624void 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
675wxString 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
686wxString 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
696wxString 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
706wxString 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
718wxString 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
739void 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
751wxString 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
782bool 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
810wxString 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)
822wxString 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
835wxString 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)
847wxString 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)
858wxString 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)
870wxString 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
881size_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
922bool 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
932bool 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
942bool 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
954wxString 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
966wxString& 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
976wxString& 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