1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxString class
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "string.h"
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
23 // ===========================================================================
24 // headers, declarations, constants
25 // ===========================================================================
27 // For compilers that support precompilation, includes "wx.h".
28 #include "wx/wxprec.h"
36 #include "wx/string.h"
49 #include <wchar.h> // for wcsrtombs(), see comments where it's used
52 #ifdef WXSTRING_IS_WXOBJECT
53 IMPLEMENT_DYNAMIC_CLASS(wxString
, wxObject
)
54 #endif //WXSTRING_IS_WXOBJECT
56 // allocating extra space for each string consumes more memory but speeds up
57 // the concatenation operations (nLen is the current string's length)
58 // NB: EXTRA_ALLOC must be >= 0!
59 #define EXTRA_ALLOC (19 - nLen % 16)
61 // ---------------------------------------------------------------------------
62 // static class variables definition
63 // ---------------------------------------------------------------------------
65 #ifdef wxSTD_STRING_COMPATIBILITY
66 const size_t wxString::npos
= wxSTRING_MAXLEN
;
67 #endif // wxSTD_STRING_COMPATIBILITY
69 // ----------------------------------------------------------------------------
71 // ----------------------------------------------------------------------------
73 // for an empty string, GetStringData() will return this address: this
74 // structure has the same layout as wxStringData and it's data() method will
75 // return the empty string (dummy pointer)
80 } g_strEmpty
= { {-1, 0, 0}, '\0' };
82 // empty C style string: points to 'string data' byte of g_strEmpty
83 extern const char WXDLLEXPORT
*g_szNul
= &g_strEmpty
.dummy
;
85 // ----------------------------------------------------------------------------
86 // conditional compilation
87 // ----------------------------------------------------------------------------
89 // we want to find out if the current platform supports vsnprintf()-like
90 // function: for Unix this is done with configure, for Windows we test the
91 // compiler explicitly.
94 #define wxVsprintf _vsnprintf
98 #define wxVsprintf vsnprintf
100 #endif // Windows/!Windows
103 // in this case we'll use vsprintf() (which is ANSI and thus should be
104 // always available), but it's unsafe because it doesn't check for buffer
105 // size - so give a warning
106 #define wxVsprintf(buffer,len,format,argptr) vsprintf(buffer,format, argptr)
107 #if defined(__VISUALC__)
108 #pragma message("Using sprintf() because no snprintf()-like function defined")
109 #elif defined(__GNUG__)
110 #warning "Using sprintf() because no snprintf()-like function defined"
111 #elif defined(__MWERKS__)
112 #warning "Using sprintf() because no snprintf()-like function defined"
113 #elif defined(__WATCOMC__)
115 #elif defined(__BORLANDC__)
117 #elif defined(__SUNCC__)
118 // nothing -- I don't know about "#warning" for Sun's CC
119 #elif defined(__DECCXX)
122 // change this to some analogue of '#warning' for your compiler
123 #error "Using sprintf() because no snprintf()-like function defined"
126 #endif // no vsnprintf
128 // ----------------------------------------------------------------------------
130 // ----------------------------------------------------------------------------
132 #ifdef wxSTD_STRING_COMPATIBILITY
134 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
137 // ATTN: you can _not_ use both of these in the same program!
139 istream
& operator>>(istream
& is
, wxString
& WXUNUSED(str
))
144 streambuf
*sb
= is
.rdbuf();
147 int ch
= sb
->sbumpc ();
149 is
.setstate(ios::eofbit
);
152 else if ( isspace(ch
) ) {
164 if ( str
.length() == 0 )
165 is
.setstate(ios::failbit
);
170 #endif //std::string compatibility
172 // ----------------------------------------------------------------------------
174 // ----------------------------------------------------------------------------
176 // this small class is used to gather statistics for performance tuning
177 //#define WXSTRING_STATISTICS
178 #ifdef WXSTRING_STATISTICS
182 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
184 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
186 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
189 size_t m_nCount
, m_nTotal
;
191 } g_averageLength("allocation size"),
192 g_averageSummandLength("summand length"),
193 g_averageConcatHit("hit probability in concat"),
194 g_averageInitialLength("initial string length");
196 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
198 #define STATISTICS_ADD(av, val)
199 #endif // WXSTRING_STATISTICS
201 // ===========================================================================
202 // wxString class core
203 // ===========================================================================
205 // ---------------------------------------------------------------------------
207 // ---------------------------------------------------------------------------
209 // constructs string of <nLength> copies of character <ch>
210 wxString::wxString(char ch
, size_t nLength
)
215 AllocBuffer(nLength
);
217 wxASSERT( sizeof(char) == 1 ); // can't use memset if not
219 memset(m_pchData
, ch
, nLength
);
223 // takes nLength elements of psz starting at nPos
224 void wxString::InitWith(const char *psz
, size_t nPos
, size_t nLength
)
228 wxASSERT( nPos
<= Strlen(psz
) );
230 if ( nLength
== wxSTRING_MAXLEN
)
231 nLength
= Strlen(psz
+ nPos
);
233 STATISTICS_ADD(InitialLength
, nLength
);
236 // trailing '\0' is written in AllocBuffer()
237 AllocBuffer(nLength
);
238 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(char));
242 // the same as previous constructor, but for compilers using unsigned char
243 wxString::wxString(const unsigned char* psz
, size_t nLength
)
245 InitWith((const char *)psz
, 0, nLength
);
248 #ifdef wxSTD_STRING_COMPATIBILITY
250 // poor man's iterators are "void *" pointers
251 wxString::wxString(const void *pStart
, const void *pEnd
)
253 InitWith((const char *)pStart
, 0,
254 (const char *)pEnd
- (const char *)pStart
);
257 #endif //std::string compatibility
260 wxString::wxString(const wchar_t *pwz
)
262 // first get necessary size
264 // NB: GNU libc5 wcstombs() is completely broken, don't use it (it doesn't
265 // honor the 3rd parameter, thus it will happily crash here).
267 // don't know if it's really needed (or if we can pass NULL), but better safe
270 size_t nLen
= wcsrtombs((char *) NULL
, &pwz
, 0, &mbstate
);
272 size_t nLen
= wcstombs((char *) NULL
, pwz
, 0);
278 wcstombs(m_pchData
, pwz
, nLen
);
285 // ---------------------------------------------------------------------------
287 // ---------------------------------------------------------------------------
289 // allocates memory needed to store a C string of length nLen
290 void wxString::AllocBuffer(size_t nLen
)
292 wxASSERT( nLen
> 0 ); //
293 wxASSERT( nLen
<= INT_MAX
-1 ); // max size (enough room for 1 extra)
295 STATISTICS_ADD(Length
, nLen
);
298 // 1) one extra character for '\0' termination
299 // 2) sizeof(wxStringData) for housekeeping info
300 wxStringData
* pData
= (wxStringData
*)
301 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(char));
303 pData
->nDataLength
= nLen
;
304 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
305 m_pchData
= pData
->data(); // data starts after wxStringData
306 m_pchData
[nLen
] = '\0';
309 // must be called before changing this string
310 void wxString::CopyBeforeWrite()
312 wxStringData
* pData
= GetStringData();
314 if ( pData
->IsShared() ) {
315 pData
->Unlock(); // memory not freed because shared
316 size_t nLen
= pData
->nDataLength
;
318 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(char));
321 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
324 // must be called before replacing contents of this string
325 void wxString::AllocBeforeWrite(size_t nLen
)
327 wxASSERT( nLen
!= 0 ); // doesn't make any sense
329 // must not share string and must have enough space
330 wxStringData
* pData
= GetStringData();
331 if ( pData
->IsShared() || (nLen
> pData
->nAllocLength
) ) {
332 // can't work with old buffer, get new one
337 // update the string length
338 pData
->nDataLength
= nLen
;
341 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
344 // allocate enough memory for nLen characters
345 void wxString::Alloc(size_t nLen
)
347 wxStringData
*pData
= GetStringData();
348 if ( pData
->nAllocLength
<= nLen
) {
349 if ( pData
->IsEmpty() ) {
352 wxStringData
* pData
= (wxStringData
*)
353 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(char));
355 pData
->nDataLength
= 0;
356 pData
->nAllocLength
= nLen
;
357 m_pchData
= pData
->data(); // data starts after wxStringData
358 m_pchData
[0u] = '\0';
360 else if ( pData
->IsShared() ) {
361 pData
->Unlock(); // memory not freed because shared
362 size_t nOldLen
= pData
->nDataLength
;
364 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(char));
369 wxStringData
*p
= (wxStringData
*)
370 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(char));
373 // @@@ what to do on memory error?
377 // it's not important if the pointer changed or not (the check for this
378 // is not faster than assigning to m_pchData in all cases)
379 p
->nAllocLength
= nLen
;
380 m_pchData
= p
->data();
383 //else: we've already got enough
386 // shrink to minimal size (releasing extra memory)
387 void wxString::Shrink()
389 wxStringData
*pData
= GetStringData();
391 // this variable is unused in release build, so avoid the compiler warning by
392 // just not declaring it
396 realloc(pData
, sizeof(wxStringData
) + (pData
->nDataLength
+ 1)*sizeof(char));
398 wxASSERT( p
!= NULL
); // can't free memory?
399 wxASSERT( p
== pData
); // we're decrementing the size - block shouldn't move!
402 // get the pointer to writable buffer of (at least) nLen bytes
403 char *wxString::GetWriteBuf(size_t nLen
)
405 AllocBeforeWrite(nLen
);
407 wxASSERT( GetStringData()->nRefs
== 1 );
408 GetStringData()->Validate(FALSE
);
413 // put string back in a reasonable state after GetWriteBuf
414 void wxString::UngetWriteBuf()
416 GetStringData()->nDataLength
= strlen(m_pchData
);
417 GetStringData()->Validate(TRUE
);
420 // ---------------------------------------------------------------------------
422 // ---------------------------------------------------------------------------
424 // all functions are inline in string.h
426 // ---------------------------------------------------------------------------
427 // assignment operators
428 // ---------------------------------------------------------------------------
430 // helper function: does real copy
431 void wxString::AssignCopy(size_t nSrcLen
, const char *pszSrcData
)
433 if ( nSrcLen
== 0 ) {
437 AllocBeforeWrite(nSrcLen
);
438 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(char));
439 GetStringData()->nDataLength
= nSrcLen
;
440 m_pchData
[nSrcLen
] = '\0';
444 // assigns one string to another
445 wxString
& wxString::operator=(const wxString
& stringSrc
)
447 wxASSERT( stringSrc
.GetStringData()->IsValid() );
449 // don't copy string over itself
450 if ( m_pchData
!= stringSrc
.m_pchData
) {
451 if ( stringSrc
.GetStringData()->IsEmpty() ) {
456 GetStringData()->Unlock();
457 m_pchData
= stringSrc
.m_pchData
;
458 GetStringData()->Lock();
465 // assigns a single character
466 wxString
& wxString::operator=(char ch
)
473 wxString
& wxString::operator=(const char *psz
)
475 AssignCopy(Strlen(psz
), psz
);
479 // same as 'signed char' variant
480 wxString
& wxString::operator=(const unsigned char* psz
)
482 *this = (const char *)psz
;
486 wxString
& wxString::operator=(const wchar_t *pwz
)
493 // ---------------------------------------------------------------------------
494 // string concatenation
495 // ---------------------------------------------------------------------------
497 // add something to this string
498 void wxString::ConcatSelf(int nSrcLen
, const char *pszSrcData
)
500 STATISTICS_ADD(SummandLength
, nSrcLen
);
502 // concatenating an empty string is a NOP
504 wxStringData
*pData
= GetStringData();
505 size_t nLen
= pData
->nDataLength
;
506 size_t nNewLen
= nLen
+ nSrcLen
;
508 // alloc new buffer if current is too small
509 if ( pData
->IsShared() ) {
510 STATISTICS_ADD(ConcatHit
, 0);
512 // we have to allocate another buffer
513 wxStringData
* pOldData
= GetStringData();
514 AllocBuffer(nNewLen
);
515 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(char));
518 else if ( nNewLen
> pData
->nAllocLength
) {
519 STATISTICS_ADD(ConcatHit
, 0);
521 // we have to grow the buffer
525 STATISTICS_ADD(ConcatHit
, 1);
527 // the buffer is already big enough
530 // should be enough space
531 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
533 // fast concatenation - all is done in our buffer
534 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(char));
536 m_pchData
[nNewLen
] = '\0'; // put terminating '\0'
537 GetStringData()->nDataLength
= nNewLen
; // and fix the length
539 //else: the string to append was empty
543 * concatenation functions come in 5 flavours:
545 * char + string and string + char
546 * C str + string and string + C str
549 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
551 wxASSERT( string1
.GetStringData()->IsValid() );
552 wxASSERT( string2
.GetStringData()->IsValid() );
554 wxString s
= string1
;
560 wxString
operator+(const wxString
& string
, char ch
)
562 wxASSERT( string
.GetStringData()->IsValid() );
570 wxString
operator+(char ch
, const wxString
& string
)
572 wxASSERT( string
.GetStringData()->IsValid() );
580 wxString
operator+(const wxString
& string
, const char *psz
)
582 wxASSERT( string
.GetStringData()->IsValid() );
585 s
.Alloc(Strlen(psz
) + string
.Len());
592 wxString
operator+(const char *psz
, const wxString
& string
)
594 wxASSERT( string
.GetStringData()->IsValid() );
597 s
.Alloc(Strlen(psz
) + string
.Len());
604 // ===========================================================================
605 // other common string functions
606 // ===========================================================================
608 // ---------------------------------------------------------------------------
609 // simple sub-string extraction
610 // ---------------------------------------------------------------------------
612 // helper function: clone the data attached to this string
613 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
615 if ( nCopyLen
== 0 ) {
619 dest
.AllocBuffer(nCopyLen
);
620 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(char));
624 // extract string of length nCount starting at nFirst
625 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
627 wxStringData
*pData
= GetStringData();
628 size_t nLen
= pData
->nDataLength
;
630 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
631 if ( nCount
== wxSTRING_MAXLEN
)
633 nCount
= nLen
- nFirst
;
636 // out-of-bounds requests return sensible things
637 if ( nFirst
+ nCount
> nLen
)
639 nCount
= nLen
- nFirst
;
644 // AllocCopy() will return empty string
649 AllocCopy(dest
, nCount
, nFirst
);
654 // extract nCount last (rightmost) characters
655 wxString
wxString::Right(size_t nCount
) const
657 if ( nCount
> (size_t)GetStringData()->nDataLength
)
658 nCount
= GetStringData()->nDataLength
;
661 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
665 // get all characters after the last occurence of ch
666 // (returns the whole string if ch not found)
667 wxString
wxString::AfterLast(char ch
) const
670 int iPos
= Find(ch
, TRUE
);
671 if ( iPos
== wxNOT_FOUND
)
674 str
= c_str() + iPos
+ 1;
679 // extract nCount first (leftmost) characters
680 wxString
wxString::Left(size_t nCount
) const
682 if ( nCount
> (size_t)GetStringData()->nDataLength
)
683 nCount
= GetStringData()->nDataLength
;
686 AllocCopy(dest
, nCount
, 0);
690 // get all characters before the first occurence of ch
691 // (returns the whole string if ch not found)
692 wxString
wxString::BeforeFirst(char ch
) const
695 for ( const char *pc
= m_pchData
; *pc
!= '\0' && *pc
!= ch
; pc
++ )
701 /// get all characters before the last occurence of ch
702 /// (returns empty string if ch not found)
703 wxString
wxString::BeforeLast(char ch
) const
706 int iPos
= Find(ch
, TRUE
);
707 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
708 str
= wxString(c_str(), iPos
);
713 /// get all characters after the first occurence of ch
714 /// (returns empty string if ch not found)
715 wxString
wxString::AfterFirst(char ch
) const
719 if ( iPos
!= wxNOT_FOUND
)
720 str
= c_str() + iPos
+ 1;
725 // replace first (or all) occurences of some substring with another one
726 size_t wxString::Replace(const char *szOld
, const char *szNew
, bool bReplaceAll
)
728 size_t uiCount
= 0; // count of replacements made
730 size_t uiOldLen
= Strlen(szOld
);
733 const char *pCurrent
= m_pchData
;
735 while ( *pCurrent
!= '\0' ) {
736 pSubstr
= strstr(pCurrent
, szOld
);
737 if ( pSubstr
== NULL
) {
738 // strTemp is unused if no replacements were made, so avoid the copy
742 strTemp
+= pCurrent
; // copy the rest
743 break; // exit the loop
746 // take chars before match
747 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
749 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
754 if ( !bReplaceAll
) {
755 strTemp
+= pCurrent
; // copy the rest
756 break; // exit the loop
761 // only done if there were replacements, otherwise would have returned above
767 bool wxString::IsAscii() const
769 const char *s
= (const char*) *this;
771 if(!isascii(*s
)) return(FALSE
);
777 bool wxString::IsWord() const
779 const char *s
= (const char*) *this;
781 if(!isalpha(*s
)) return(FALSE
);
787 bool wxString::IsNumber() const
789 const char *s
= (const char*) *this;
791 if(!isdigit(*s
)) return(FALSE
);
797 wxString
wxString::Strip(stripType w
) const
800 if ( w
& leading
) s
.Trim(FALSE
);
801 if ( w
& trailing
) s
.Trim(TRUE
);
805 // ---------------------------------------------------------------------------
807 // ---------------------------------------------------------------------------
809 wxString
& wxString::MakeUpper()
813 for ( char *p
= m_pchData
; *p
; p
++ )
814 *p
= (char)toupper(*p
);
819 wxString
& wxString::MakeLower()
823 for ( char *p
= m_pchData
; *p
; p
++ )
824 *p
= (char)tolower(*p
);
829 // ---------------------------------------------------------------------------
830 // trimming and padding
831 // ---------------------------------------------------------------------------
833 // trims spaces (in the sense of isspace) from left or right side
834 wxString
& wxString::Trim(bool bFromRight
)
836 // first check if we're going to modify the string at all
839 (bFromRight
&& isspace(GetChar(Len() - 1))) ||
840 (!bFromRight
&& isspace(GetChar(0u)))
844 // ok, there is at least one space to trim
849 // find last non-space character
850 char *psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
851 while ( isspace(*psz
) && (psz
>= m_pchData
) )
854 // truncate at trailing space start
856 GetStringData()->nDataLength
= psz
- m_pchData
;
860 // find first non-space character
861 const char *psz
= m_pchData
;
862 while ( isspace(*psz
) )
865 // fix up data and length
866 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const char*) m_pchData
);
867 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(char));
868 GetStringData()->nDataLength
= nDataLength
;
875 // adds nCount characters chPad to the string from either side
876 wxString
& wxString::Pad(size_t nCount
, char chPad
, bool bFromRight
)
878 wxString
s(chPad
, nCount
);
891 // truncate the string
892 wxString
& wxString::Truncate(size_t uiLen
)
894 if ( uiLen
< Len() ) {
897 *(m_pchData
+ uiLen
) = '\0';
898 GetStringData()->nDataLength
= uiLen
;
900 //else: nothing to do, string is already short enough
905 // ---------------------------------------------------------------------------
906 // finding (return wxNOT_FOUND if not found and index otherwise)
907 // ---------------------------------------------------------------------------
910 int wxString::Find(char ch
, bool bFromEnd
) const
912 const char *psz
= bFromEnd
? strrchr(m_pchData
, ch
) : strchr(m_pchData
, ch
);
914 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const char*) m_pchData
;
917 // find a sub-string (like strstr)
918 int wxString::Find(const char *pszSub
) const
920 const char *psz
= strstr(m_pchData
, pszSub
);
922 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const char*) m_pchData
;
925 // ---------------------------------------------------------------------------
926 // stream-like operators
927 // ---------------------------------------------------------------------------
928 wxString
& wxString::operator<<(int i
)
933 return (*this) << res
;
936 wxString
& wxString::operator<<(float f
)
941 return (*this) << res
;
944 wxString
& wxString::operator<<(double d
)
949 return (*this) << res
;
952 // ---------------------------------------------------------------------------
954 // ---------------------------------------------------------------------------
955 int wxString::Printf(const char *pszFormat
, ...)
958 va_start(argptr
, pszFormat
);
960 int iLen
= PrintfV(pszFormat
, argptr
);
967 int wxString::PrintfV(const char* pszFormat
, va_list argptr
)
969 // static buffer to avoid dynamic memory allocation each time
970 static char s_szScratch
[1024];
972 // NB: wxVsprintf() may return either less than the buffer size or -1 if there
973 // is not enough place depending on implementation
974 int iLen
= wxVsprintf(s_szScratch
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
976 if ( iLen
< (int)WXSIZEOF(s_szScratch
) ) {
977 buffer
= s_szScratch
;
980 int size
= WXSIZEOF(s_szScratch
) * 2;
981 buffer
= (char *)malloc(size
);
982 while ( buffer
!= NULL
) {
983 iLen
= wxVsprintf(buffer
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
985 // ok, there was enough space
989 // still not enough, double it again
990 buffer
= (char *)realloc(buffer
, size
*= 2);
999 AllocBeforeWrite(iLen
);
1000 strcpy(m_pchData
, buffer
);
1002 if ( buffer
!= s_szScratch
)
1008 // ----------------------------------------------------------------------------
1009 // misc other operations
1010 // ----------------------------------------------------------------------------
1011 bool wxString::Matches(const char *pszMask
) const
1013 // check char by char
1015 for ( pszTxt
= c_str(); *pszMask
!= '\0'; pszMask
++, pszTxt
++ ) {
1016 switch ( *pszMask
) {
1018 if ( *pszTxt
== '\0' )
1027 // ignore special chars immediately following this one
1028 while ( *pszMask
== '*' || *pszMask
== '?' )
1031 // if there is nothing more, match
1032 if ( *pszMask
== '\0' )
1035 // are there any other metacharacters in the mask?
1037 const char *pEndMask
= strpbrk(pszMask
, "*?");
1039 if ( pEndMask
!= NULL
) {
1040 // we have to match the string between two metachars
1041 uiLenMask
= pEndMask
- pszMask
;
1044 // we have to match the remainder of the string
1045 uiLenMask
= strlen(pszMask
);
1048 wxString
strToMatch(pszMask
, uiLenMask
);
1049 const char* pMatch
= strstr(pszTxt
, strToMatch
);
1050 if ( pMatch
== NULL
)
1053 // -1 to compensate "++" in the loop
1054 pszTxt
= pMatch
+ uiLenMask
- 1;
1055 pszMask
+= uiLenMask
- 1;
1060 if ( *pszMask
!= *pszTxt
)
1066 // match only if nothing left
1067 return *pszTxt
== '\0';
1070 // Count the number of chars
1071 int wxString::Freq(char ch
) const
1075 for (int i
= 0; i
< len
; i
++)
1077 if (GetChar(i
) == ch
)
1083 // convert to upper case, return the copy of the string
1084 wxString
wxString::Upper() const
1085 { wxString
s(*this); return s
.MakeUpper(); }
1087 // convert to lower case, return the copy of the string
1088 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1090 int wxString::sprintf(const char *pszFormat
, ...)
1093 va_start(argptr
, pszFormat
);
1094 int iLen
= PrintfV(pszFormat
, argptr
);
1099 // ---------------------------------------------------------------------------
1100 // standard C++ library string functions
1101 // ---------------------------------------------------------------------------
1102 #ifdef wxSTD_STRING_COMPATIBILITY
1104 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1106 wxASSERT( str
.GetStringData()->IsValid() );
1107 wxASSERT( nPos
<= Len() );
1109 if ( !str
.IsEmpty() ) {
1111 char *pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1112 strncpy(pc
, c_str(), nPos
);
1113 strcpy(pc
+ nPos
, str
);
1114 strcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1115 strTmp
.UngetWriteBuf();
1122 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1124 wxASSERT( str
.GetStringData()->IsValid() );
1125 wxASSERT( nStart
<= Len() );
1127 const char *p
= strstr(c_str() + nStart
, str
);
1129 return p
== NULL
? npos
: p
- c_str();
1132 // VC++ 1.5 can't cope with the default argument in the header.
1133 #if !defined(__VISUALC__) || defined(__WIN32__)
1134 size_t wxString::find(const char* sz
, size_t nStart
, size_t n
) const
1136 return find(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1140 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1141 #if !defined(__BORLANDC__)
1142 size_t wxString::find(char ch
, size_t nStart
) const
1144 wxASSERT( nStart
<= Len() );
1146 const char *p
= strchr(c_str() + nStart
, ch
);
1148 return p
== NULL
? npos
: p
- c_str();
1152 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1154 wxASSERT( str
.GetStringData()->IsValid() );
1155 wxASSERT( nStart
<= Len() );
1157 // # could be quicker than that
1158 const char *p
= c_str() + (nStart
== npos
? Len() : nStart
);
1159 while ( p
>= c_str() + str
.Len() ) {
1160 if ( strncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1161 return p
- str
.Len() - c_str();
1168 // VC++ 1.5 can't cope with the default argument in the header.
1169 #if !defined(__VISUALC__) || defined(__WIN32__)
1170 size_t wxString::rfind(const char* sz
, size_t nStart
, size_t n
) const
1172 return rfind(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1175 size_t wxString::rfind(char ch
, size_t nStart
) const
1177 wxASSERT( nStart
<= Len() );
1179 const char *p
= strrchr(c_str() + nStart
, ch
);
1181 return p
== NULL
? npos
: p
- c_str();
1185 wxString
wxString::substr(size_t nStart
, size_t nLen
) const
1187 // npos means 'take all'
1191 wxASSERT( nStart
+ nLen
<= Len() );
1193 return wxString(c_str() + nStart
, nLen
== npos
? 0 : nLen
);
1196 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1198 wxString
strTmp(c_str(), nStart
);
1199 if ( nLen
!= npos
) {
1200 wxASSERT( nStart
+ nLen
<= Len() );
1202 strTmp
.append(c_str() + nStart
+ nLen
);
1209 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const char *sz
)
1211 wxASSERT( nStart
+ nLen
<= Strlen(sz
) );
1215 strTmp
.append(c_str(), nStart
);
1217 strTmp
.append(c_str() + nStart
+ nLen
);
1223 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, char ch
)
1225 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1228 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1229 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1231 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1234 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1235 const char* sz
, size_t nCount
)
1237 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1240 #endif //std::string compatibility
1242 // ============================================================================
1244 // ============================================================================
1246 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1247 #define ARRAY_MAXSIZE_INCREMENT 4096
1248 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1249 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1252 #define STRING(p) ((wxString *)(&(p)))
1255 wxArrayString::wxArrayString()
1259 m_pItems
= (char **) NULL
;
1263 wxArrayString::wxArrayString(const wxArrayString
& src
)
1267 m_pItems
= (char **) NULL
;
1272 // assignment operator
1273 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1278 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1279 Alloc(src
.m_nCount
);
1281 // we can't just copy the pointers here because otherwise we would share
1282 // the strings with another array
1283 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1286 if ( m_nCount
!= 0 )
1287 memcpy(m_pItems
, src
.m_pItems
, m_nCount
*sizeof(char *));
1293 void wxArrayString::Grow()
1295 // only do it if no more place
1296 if( m_nCount
== m_nSize
) {
1297 if( m_nSize
== 0 ) {
1298 // was empty, alloc some memory
1299 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1300 m_pItems
= new char *[m_nSize
];
1303 // otherwise when it's called for the first time, nIncrement would be 0
1304 // and the array would never be expanded
1305 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE
!= 0 );
1307 // add 50% but not too much
1308 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1309 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1310 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1311 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1312 m_nSize
+= nIncrement
;
1313 char **pNew
= new char *[m_nSize
];
1315 // copy data to new location
1316 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(char *));
1318 // delete old memory (but do not release the strings!)
1319 wxDELETEA(m_pItems
);
1326 void wxArrayString::Free()
1328 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1329 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1333 // deletes all the strings from the list
1334 void wxArrayString::Empty()
1341 // as Empty, but also frees memory
1342 void wxArrayString::Clear()
1349 wxDELETEA(m_pItems
);
1353 wxArrayString::~wxArrayString()
1357 wxDELETEA(m_pItems
);
1360 // pre-allocates memory (frees the previous data!)
1361 void wxArrayString::Alloc(size_t nSize
)
1363 wxASSERT( nSize
> 0 );
1365 // only if old buffer was not big enough
1366 if ( nSize
> m_nSize
) {
1368 wxDELETEA(m_pItems
);
1369 m_pItems
= new char *[nSize
];
1376 // searches the array for an item (forward or backwards)
1377 int wxArrayString::Index(const char *sz
, bool bCase
, bool bFromEnd
) const
1380 if ( m_nCount
> 0 ) {
1381 size_t ui
= m_nCount
;
1383 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1390 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1391 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1399 // add item at the end
1400 void wxArrayString::Add(const wxString
& str
)
1402 wxASSERT( str
.GetStringData()->IsValid() );
1406 // the string data must not be deleted!
1407 str
.GetStringData()->Lock();
1408 m_pItems
[m_nCount
++] = (char *)str
.c_str();
1411 // add item at the given position
1412 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
1414 wxASSERT( str
.GetStringData()->IsValid() );
1416 wxCHECK_RET( nIndex
<= m_nCount
, ("bad index in wxArrayString::Insert") );
1420 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
1421 (m_nCount
- nIndex
)*sizeof(char *));
1423 str
.GetStringData()->Lock();
1424 m_pItems
[nIndex
] = (char *)str
.c_str();
1429 // removes item from array (by index)
1430 void wxArrayString::Remove(size_t nIndex
)
1432 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Remove") );
1435 Item(nIndex
).GetStringData()->Unlock();
1437 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
1438 (m_nCount
- nIndex
- 1)*sizeof(char *));
1442 // removes item from array (by value)
1443 void wxArrayString::Remove(const char *sz
)
1445 int iIndex
= Index(sz
);
1447 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
1448 _("removing inexistent element in wxArrayString::Remove") );
1453 // ----------------------------------------------------------------------------
1455 // ----------------------------------------------------------------------------
1457 // we can only sort one array at a time with the quick-sort based
1460 #include <wx/thread.h>
1462 // need a critical section to protect access to gs_compareFunction and
1463 // gs_sortAscending variables
1464 static wxCriticalSection gs_critsectStringSort
;
1466 // call this before the value of the global sort vars is changed/after
1467 // you're finished with them
1468 #define START_SORT() gs_critsectStringSort.Enter()
1469 #define END_SORT() gs_critsectStringSort.Leave()
1471 #define START_SORT()
1473 #endif // wxUSE_THREADS
1475 // function to use for string comparaison
1476 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
1478 // if we don't use the compare function, this flag tells us if we sort the
1479 // array in ascending or descending order
1480 static bool gs_sortAscending
= TRUE
;
1482 // function which is called by quick sort
1483 static int wxStringCompareFunction(const void *first
, const void *second
)
1485 wxString
*strFirst
= (wxString
*)first
;
1486 wxString
*strSecond
= (wxString
*)second
;
1488 if ( gs_compareFunction
) {
1489 return gs_compareFunction(*strFirst
, *strSecond
);
1492 int result
= strcmp(strFirst
->c_str(), strSecond
->c_str());
1494 return gs_sortAscending
? result
: -result
;
1498 // sort array elements using passed comparaison function
1499 void wxArrayString::Sort(CompareFunction compareFunction
)
1503 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1504 gs_compareFunction
= compareFunction
;
1511 void wxArrayString::Sort(bool reverseOrder
)
1515 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1516 gs_sortAscending
= !reverseOrder
;
1523 void wxArrayString::DoSort()
1525 // just sort the pointers using qsort() - of course it only works because
1526 // wxString() *is* a pointer to its data
1527 qsort(m_pItems
, m_nCount
, sizeof(char *), wxStringCompareFunction
);