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
120 // change this to some analogue of '#warning' for your compiler
121 #error "Using sprintf() because no snprintf()-like function defined"
124 #endif // no vsnprintf
126 // ----------------------------------------------------------------------------
128 // ----------------------------------------------------------------------------
130 #ifdef wxSTD_STRING_COMPATIBILITY
132 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
135 // ATTN: you can _not_ use both of these in the same program!
137 istream
& operator>>(istream
& is
, wxString
& WXUNUSED(str
))
142 streambuf
*sb
= is
.rdbuf();
145 int ch
= sb
->sbumpc ();
147 is
.setstate(ios::eofbit
);
150 else if ( isspace(ch
) ) {
162 if ( str
.length() == 0 )
163 is
.setstate(ios::failbit
);
168 #endif //std::string compatibility
170 // ----------------------------------------------------------------------------
172 // ----------------------------------------------------------------------------
174 // this small class is used to gather statistics for performance tuning
175 //#define WXSTRING_STATISTICS
176 #ifdef WXSTRING_STATISTICS
180 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
182 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
184 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
187 size_t m_nCount
, m_nTotal
;
189 } g_averageLength("allocation size"),
190 g_averageSummandLength("summand length"),
191 g_averageConcatHit("hit probability in concat"),
192 g_averageInitialLength("initial string length");
194 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
196 #define STATISTICS_ADD(av, val)
197 #endif // WXSTRING_STATISTICS
199 // ===========================================================================
200 // wxString class core
201 // ===========================================================================
203 // ---------------------------------------------------------------------------
205 // ---------------------------------------------------------------------------
207 // constructs string of <nLength> copies of character <ch>
208 wxString::wxString(char ch
, size_t nLength
)
213 AllocBuffer(nLength
);
215 wxASSERT( sizeof(char) == 1 ); // can't use memset if not
217 memset(m_pchData
, ch
, nLength
);
221 // takes nLength elements of psz starting at nPos
222 void wxString::InitWith(const char *psz
, size_t nPos
, size_t nLength
)
226 wxASSERT( nPos
<= Strlen(psz
) );
228 if ( nLength
== wxSTRING_MAXLEN
)
229 nLength
= Strlen(psz
+ nPos
);
231 STATISTICS_ADD(InitialLength
, nLength
);
234 // trailing '\0' is written in AllocBuffer()
235 AllocBuffer(nLength
);
236 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(char));
240 // the same as previous constructor, but for compilers using unsigned char
241 wxString::wxString(const unsigned char* psz
, size_t nLength
)
243 InitWith((const char *)psz
, 0, nLength
);
246 #ifdef wxSTD_STRING_COMPATIBILITY
248 // poor man's iterators are "void *" pointers
249 wxString::wxString(const void *pStart
, const void *pEnd
)
251 InitWith((const char *)pStart
, 0,
252 (const char *)pEnd
- (const char *)pStart
);
255 #endif //std::string compatibility
258 wxString::wxString(const wchar_t *pwz
)
260 // first get necessary size
262 // NB: GNU libc5 wcstombs() is completely broken, don't use it (it doesn't
263 // honor the 3rd parameter, thus it will happily crash here).
265 // don't know if it's really needed (or if we can pass NULL), but better safe
268 size_t nLen
= wcsrtombs((char *) NULL
, &pwz
, 0, &mbstate
);
270 size_t nLen
= wcstombs((char *) NULL
, pwz
, 0);
276 wcstombs(m_pchData
, pwz
, nLen
);
283 // ---------------------------------------------------------------------------
285 // ---------------------------------------------------------------------------
287 // allocates memory needed to store a C string of length nLen
288 void wxString::AllocBuffer(size_t nLen
)
290 wxASSERT( nLen
> 0 ); //
291 wxASSERT( nLen
<= INT_MAX
-1 ); // max size (enough room for 1 extra)
293 STATISTICS_ADD(Length
, nLen
);
296 // 1) one extra character for '\0' termination
297 // 2) sizeof(wxStringData) for housekeeping info
298 wxStringData
* pData
= (wxStringData
*)
299 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(char));
301 pData
->nDataLength
= nLen
;
302 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
303 m_pchData
= pData
->data(); // data starts after wxStringData
304 m_pchData
[nLen
] = '\0';
307 // must be called before changing this string
308 void wxString::CopyBeforeWrite()
310 wxStringData
* pData
= GetStringData();
312 if ( pData
->IsShared() ) {
313 pData
->Unlock(); // memory not freed because shared
314 size_t nLen
= pData
->nDataLength
;
316 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(char));
319 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
322 // must be called before replacing contents of this string
323 void wxString::AllocBeforeWrite(size_t nLen
)
325 wxASSERT( nLen
!= 0 ); // doesn't make any sense
327 // must not share string and must have enough space
328 wxStringData
* pData
= GetStringData();
329 if ( pData
->IsShared() || (nLen
> pData
->nAllocLength
) ) {
330 // can't work with old buffer, get new one
335 // update the string length
336 pData
->nDataLength
= nLen
;
339 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
342 // allocate enough memory for nLen characters
343 void wxString::Alloc(size_t nLen
)
345 wxStringData
*pData
= GetStringData();
346 if ( pData
->nAllocLength
<= nLen
) {
347 if ( pData
->IsEmpty() ) {
350 wxStringData
* pData
= (wxStringData
*)
351 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(char));
353 pData
->nDataLength
= 0;
354 pData
->nAllocLength
= nLen
;
355 m_pchData
= pData
->data(); // data starts after wxStringData
356 m_pchData
[0u] = '\0';
358 else if ( pData
->IsShared() ) {
359 pData
->Unlock(); // memory not freed because shared
360 size_t nOldLen
= pData
->nDataLength
;
362 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(char));
367 wxStringData
*p
= (wxStringData
*)
368 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(char));
371 // @@@ what to do on memory error?
375 // it's not important if the pointer changed or not (the check for this
376 // is not faster than assigning to m_pchData in all cases)
377 p
->nAllocLength
= nLen
;
378 m_pchData
= p
->data();
381 //else: we've already got enough
384 // shrink to minimal size (releasing extra memory)
385 void wxString::Shrink()
387 wxStringData
*pData
= GetStringData();
389 // this variable is unused in release build, so avoid the compiler warning by
390 // just not declaring it
394 realloc(pData
, sizeof(wxStringData
) + (pData
->nDataLength
+ 1)*sizeof(char));
396 wxASSERT( p
!= NULL
); // can't free memory?
397 wxASSERT( p
== pData
); // we're decrementing the size - block shouldn't move!
400 // get the pointer to writable buffer of (at least) nLen bytes
401 char *wxString::GetWriteBuf(size_t nLen
)
403 AllocBeforeWrite(nLen
);
405 wxASSERT( GetStringData()->nRefs
== 1 );
406 GetStringData()->Validate(FALSE
);
411 // put string back in a reasonable state after GetWriteBuf
412 void wxString::UngetWriteBuf()
414 GetStringData()->nDataLength
= strlen(m_pchData
);
415 GetStringData()->Validate(TRUE
);
418 // ---------------------------------------------------------------------------
420 // ---------------------------------------------------------------------------
422 // all functions are inline in string.h
424 // ---------------------------------------------------------------------------
425 // assignment operators
426 // ---------------------------------------------------------------------------
428 // helper function: does real copy
429 void wxString::AssignCopy(size_t nSrcLen
, const char *pszSrcData
)
431 if ( nSrcLen
== 0 ) {
435 AllocBeforeWrite(nSrcLen
);
436 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(char));
437 GetStringData()->nDataLength
= nSrcLen
;
438 m_pchData
[nSrcLen
] = '\0';
442 // assigns one string to another
443 wxString
& wxString::operator=(const wxString
& stringSrc
)
445 wxASSERT( stringSrc
.GetStringData()->IsValid() );
447 // don't copy string over itself
448 if ( m_pchData
!= stringSrc
.m_pchData
) {
449 if ( stringSrc
.GetStringData()->IsEmpty() ) {
454 GetStringData()->Unlock();
455 m_pchData
= stringSrc
.m_pchData
;
456 GetStringData()->Lock();
463 // assigns a single character
464 wxString
& wxString::operator=(char ch
)
471 wxString
& wxString::operator=(const char *psz
)
473 AssignCopy(Strlen(psz
), psz
);
477 // same as 'signed char' variant
478 wxString
& wxString::operator=(const unsigned char* psz
)
480 *this = (const char *)psz
;
484 wxString
& wxString::operator=(const wchar_t *pwz
)
491 // ---------------------------------------------------------------------------
492 // string concatenation
493 // ---------------------------------------------------------------------------
495 // add something to this string
496 void wxString::ConcatSelf(int nSrcLen
, const char *pszSrcData
)
498 STATISTICS_ADD(SummandLength
, nSrcLen
);
500 // concatenating an empty string is a NOP
502 wxStringData
*pData
= GetStringData();
503 size_t nLen
= pData
->nDataLength
;
504 size_t nNewLen
= nLen
+ nSrcLen
;
506 // alloc new buffer if current is too small
507 if ( pData
->IsShared() ) {
508 STATISTICS_ADD(ConcatHit
, 0);
510 // we have to allocate another buffer
511 wxStringData
* pOldData
= GetStringData();
512 AllocBuffer(nNewLen
);
513 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(char));
516 else if ( nNewLen
> pData
->nAllocLength
) {
517 STATISTICS_ADD(ConcatHit
, 0);
519 // we have to grow the buffer
523 STATISTICS_ADD(ConcatHit
, 1);
525 // the buffer is already big enough
528 // should be enough space
529 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
531 // fast concatenation - all is done in our buffer
532 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(char));
534 m_pchData
[nNewLen
] = '\0'; // put terminating '\0'
535 GetStringData()->nDataLength
= nNewLen
; // and fix the length
537 //else: the string to append was empty
541 * concatenation functions come in 5 flavours:
543 * char + string and string + char
544 * C str + string and string + C str
547 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
549 wxASSERT( string1
.GetStringData()->IsValid() );
550 wxASSERT( string2
.GetStringData()->IsValid() );
552 wxString s
= string1
;
558 wxString
operator+(const wxString
& string
, char ch
)
560 wxASSERT( string
.GetStringData()->IsValid() );
568 wxString
operator+(char ch
, const wxString
& string
)
570 wxASSERT( string
.GetStringData()->IsValid() );
578 wxString
operator+(const wxString
& string
, const char *psz
)
580 wxASSERT( string
.GetStringData()->IsValid() );
583 s
.Alloc(Strlen(psz
) + string
.Len());
590 wxString
operator+(const char *psz
, const wxString
& string
)
592 wxASSERT( string
.GetStringData()->IsValid() );
595 s
.Alloc(Strlen(psz
) + string
.Len());
602 // ===========================================================================
603 // other common string functions
604 // ===========================================================================
606 // ---------------------------------------------------------------------------
607 // simple sub-string extraction
608 // ---------------------------------------------------------------------------
610 // helper function: clone the data attached to this string
611 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
613 if ( nCopyLen
== 0 ) {
617 dest
.AllocBuffer(nCopyLen
);
618 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(char));
622 // extract string of length nCount starting at nFirst
623 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
625 wxStringData
*pData
= GetStringData();
626 size_t nLen
= pData
->nDataLength
;
628 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
629 if ( nCount
== wxSTRING_MAXLEN
)
631 nCount
= nLen
- nFirst
;
634 // out-of-bounds requests return sensible things
635 if ( nFirst
+ nCount
> nLen
)
637 nCount
= nLen
- nFirst
;
642 // AllocCopy() will return empty string
647 AllocCopy(dest
, nCount
, nFirst
);
652 // extract nCount last (rightmost) characters
653 wxString
wxString::Right(size_t nCount
) const
655 if ( nCount
> (size_t)GetStringData()->nDataLength
)
656 nCount
= GetStringData()->nDataLength
;
659 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
663 // get all characters after the last occurence of ch
664 // (returns the whole string if ch not found)
665 wxString
wxString::AfterLast(char ch
) const
668 int iPos
= Find(ch
, TRUE
);
669 if ( iPos
== wxNOT_FOUND
)
672 str
= c_str() + iPos
+ 1;
677 // extract nCount first (leftmost) characters
678 wxString
wxString::Left(size_t nCount
) const
680 if ( nCount
> (size_t)GetStringData()->nDataLength
)
681 nCount
= GetStringData()->nDataLength
;
684 AllocCopy(dest
, nCount
, 0);
688 // get all characters before the first occurence of ch
689 // (returns the whole string if ch not found)
690 wxString
wxString::BeforeFirst(char ch
) const
693 for ( const char *pc
= m_pchData
; *pc
!= '\0' && *pc
!= ch
; pc
++ )
699 /// get all characters before the last occurence of ch
700 /// (returns empty string if ch not found)
701 wxString
wxString::BeforeLast(char ch
) const
704 int iPos
= Find(ch
, TRUE
);
705 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
706 str
= wxString(c_str(), iPos
);
711 /// get all characters after the first occurence of ch
712 /// (returns empty string if ch not found)
713 wxString
wxString::AfterFirst(char ch
) const
717 if ( iPos
!= wxNOT_FOUND
)
718 str
= c_str() + iPos
+ 1;
723 // replace first (or all) occurences of some substring with another one
724 size_t wxString::Replace(const char *szOld
, const char *szNew
, bool bReplaceAll
)
726 size_t uiCount
= 0; // count of replacements made
728 size_t uiOldLen
= Strlen(szOld
);
731 const char *pCurrent
= m_pchData
;
733 while ( *pCurrent
!= '\0' ) {
734 pSubstr
= strstr(pCurrent
, szOld
);
735 if ( pSubstr
== NULL
) {
736 // strTemp is unused if no replacements were made, so avoid the copy
740 strTemp
+= pCurrent
; // copy the rest
741 break; // exit the loop
744 // take chars before match
745 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
747 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
752 if ( !bReplaceAll
) {
753 strTemp
+= pCurrent
; // copy the rest
754 break; // exit the loop
759 // only done if there were replacements, otherwise would have returned above
765 bool wxString::IsAscii() const
767 const char *s
= (const char*) *this;
769 if(!isascii(*s
)) return(FALSE
);
775 bool wxString::IsWord() const
777 const char *s
= (const char*) *this;
779 if(!isalpha(*s
)) return(FALSE
);
785 bool wxString::IsNumber() const
787 const char *s
= (const char*) *this;
789 if(!isdigit(*s
)) return(FALSE
);
795 wxString
wxString::Strip(stripType w
) const
798 if ( w
& leading
) s
.Trim(FALSE
);
799 if ( w
& trailing
) s
.Trim(TRUE
);
803 // ---------------------------------------------------------------------------
805 // ---------------------------------------------------------------------------
807 wxString
& wxString::MakeUpper()
811 for ( char *p
= m_pchData
; *p
; p
++ )
812 *p
= (char)toupper(*p
);
817 wxString
& wxString::MakeLower()
821 for ( char *p
= m_pchData
; *p
; p
++ )
822 *p
= (char)tolower(*p
);
827 // ---------------------------------------------------------------------------
828 // trimming and padding
829 // ---------------------------------------------------------------------------
831 // trims spaces (in the sense of isspace) from left or right side
832 wxString
& wxString::Trim(bool bFromRight
)
834 // first check if we're going to modify the string at all
837 (bFromRight
&& isspace(GetChar(Len() - 1))) ||
838 (!bFromRight
&& isspace(GetChar(0u)))
842 // ok, there is at least one space to trim
847 // find last non-space character
848 char *psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
849 while ( isspace(*psz
) && (psz
>= m_pchData
) )
852 // truncate at trailing space start
854 GetStringData()->nDataLength
= psz
- m_pchData
;
858 // find first non-space character
859 const char *psz
= m_pchData
;
860 while ( isspace(*psz
) )
863 // fix up data and length
864 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const char*) m_pchData
);
865 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(char));
866 GetStringData()->nDataLength
= nDataLength
;
873 // adds nCount characters chPad to the string from either side
874 wxString
& wxString::Pad(size_t nCount
, char chPad
, bool bFromRight
)
876 wxString
s(chPad
, nCount
);
889 // truncate the string
890 wxString
& wxString::Truncate(size_t uiLen
)
892 if ( uiLen
< Len() ) {
895 *(m_pchData
+ uiLen
) = '\0';
896 GetStringData()->nDataLength
= uiLen
;
898 //else: nothing to do, string is already short enough
903 // ---------------------------------------------------------------------------
904 // finding (return wxNOT_FOUND if not found and index otherwise)
905 // ---------------------------------------------------------------------------
908 int wxString::Find(char ch
, bool bFromEnd
) const
910 const char *psz
= bFromEnd
? strrchr(m_pchData
, ch
) : strchr(m_pchData
, ch
);
912 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const char*) m_pchData
;
915 // find a sub-string (like strstr)
916 int wxString::Find(const char *pszSub
) const
918 const char *psz
= strstr(m_pchData
, pszSub
);
920 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const char*) m_pchData
;
923 // ---------------------------------------------------------------------------
924 // stream-like operators
925 // ---------------------------------------------------------------------------
926 wxString
& wxString::operator<<(int i
)
931 return (*this) << res
;
934 wxString
& wxString::operator<<(float f
)
939 return (*this) << res
;
942 wxString
& wxString::operator<<(double d
)
947 return (*this) << res
;
950 // ---------------------------------------------------------------------------
952 // ---------------------------------------------------------------------------
953 int wxString::Printf(const char *pszFormat
, ...)
956 va_start(argptr
, pszFormat
);
958 int iLen
= PrintfV(pszFormat
, argptr
);
965 int wxString::PrintfV(const char* pszFormat
, va_list argptr
)
967 // static buffer to avoid dynamic memory allocation each time
968 static char s_szScratch
[1024];
970 // NB: wxVsprintf() may return either less than the buffer size or -1 if there
971 // is not enough place depending on implementation
972 int iLen
= wxVsprintf(s_szScratch
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
974 if ( iLen
< (int)WXSIZEOF(s_szScratch
) ) {
975 buffer
= s_szScratch
;
978 int size
= WXSIZEOF(s_szScratch
) * 2;
979 buffer
= (char *)malloc(size
);
980 while ( buffer
!= NULL
) {
981 iLen
= wxVsprintf(buffer
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
983 // ok, there was enough space
987 // still not enough, double it again
988 buffer
= (char *)realloc(buffer
, size
*= 2);
997 AllocBeforeWrite(iLen
);
998 strcpy(m_pchData
, buffer
);
1000 if ( buffer
!= s_szScratch
)
1006 // ----------------------------------------------------------------------------
1007 // misc other operations
1008 // ----------------------------------------------------------------------------
1009 bool wxString::Matches(const char *pszMask
) const
1011 // check char by char
1013 for ( pszTxt
= c_str(); *pszMask
!= '\0'; pszMask
++, pszTxt
++ ) {
1014 switch ( *pszMask
) {
1016 if ( *pszTxt
== '\0' )
1025 // ignore special chars immediately following this one
1026 while ( *pszMask
== '*' || *pszMask
== '?' )
1029 // if there is nothing more, match
1030 if ( *pszMask
== '\0' )
1033 // are there any other metacharacters in the mask?
1035 const char *pEndMask
= strpbrk(pszMask
, "*?");
1037 if ( pEndMask
!= NULL
) {
1038 // we have to match the string between two metachars
1039 uiLenMask
= pEndMask
- pszMask
;
1042 // we have to match the remainder of the string
1043 uiLenMask
= strlen(pszMask
);
1046 wxString
strToMatch(pszMask
, uiLenMask
);
1047 const char* pMatch
= strstr(pszTxt
, strToMatch
);
1048 if ( pMatch
== NULL
)
1051 // -1 to compensate "++" in the loop
1052 pszTxt
= pMatch
+ uiLenMask
- 1;
1053 pszMask
+= uiLenMask
- 1;
1058 if ( *pszMask
!= *pszTxt
)
1064 // match only if nothing left
1065 return *pszTxt
== '\0';
1068 // Count the number of chars
1069 int wxString::Freq(char ch
) const
1073 for (int i
= 0; i
< len
; i
++)
1075 if (GetChar(i
) == ch
)
1081 // convert to upper case, return the copy of the string
1082 wxString
wxString::Upper() const
1083 { wxString
s(*this); return s
.MakeUpper(); }
1085 // convert to lower case, return the copy of the string
1086 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1088 int wxString::sprintf(const char *pszFormat
, ...)
1091 va_start(argptr
, pszFormat
);
1092 int iLen
= PrintfV(pszFormat
, argptr
);
1097 // ---------------------------------------------------------------------------
1098 // standard C++ library string functions
1099 // ---------------------------------------------------------------------------
1100 #ifdef wxSTD_STRING_COMPATIBILITY
1102 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1104 wxASSERT( str
.GetStringData()->IsValid() );
1105 wxASSERT( nPos
<= Len() );
1107 if ( !str
.IsEmpty() ) {
1109 char *pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1110 strncpy(pc
, c_str(), nPos
);
1111 strcpy(pc
+ nPos
, str
);
1112 strcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1113 strTmp
.UngetWriteBuf();
1120 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1122 wxASSERT( str
.GetStringData()->IsValid() );
1123 wxASSERT( nStart
<= Len() );
1125 const char *p
= strstr(c_str() + nStart
, str
);
1127 return p
== NULL
? npos
: p
- c_str();
1130 // VC++ 1.5 can't cope with the default argument in the header.
1131 #if !defined(__VISUALC__) || defined(__WIN32__)
1132 size_t wxString::find(const char* sz
, size_t nStart
, size_t n
) const
1134 return find(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1138 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1139 #if !defined(__BORLANDC__)
1140 size_t wxString::find(char ch
, size_t nStart
) const
1142 wxASSERT( nStart
<= Len() );
1144 const char *p
= strchr(c_str() + nStart
, ch
);
1146 return p
== NULL
? npos
: p
- c_str();
1150 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1152 wxASSERT( str
.GetStringData()->IsValid() );
1153 wxASSERT( nStart
<= Len() );
1155 // # could be quicker than that
1156 const char *p
= c_str() + (nStart
== npos
? Len() : nStart
);
1157 while ( p
>= c_str() + str
.Len() ) {
1158 if ( strncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1159 return p
- str
.Len() - c_str();
1166 // VC++ 1.5 can't cope with the default argument in the header.
1167 #if !defined(__VISUALC__) || defined(__WIN32__)
1168 size_t wxString::rfind(const char* sz
, size_t nStart
, size_t n
) const
1170 return rfind(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1173 size_t wxString::rfind(char ch
, size_t nStart
) const
1175 wxASSERT( nStart
<= Len() );
1177 const char *p
= strrchr(c_str() + nStart
, ch
);
1179 return p
== NULL
? npos
: p
- c_str();
1183 wxString
wxString::substr(size_t nStart
, size_t nLen
) const
1185 // npos means 'take all'
1189 wxASSERT( nStart
+ nLen
<= Len() );
1191 return wxString(c_str() + nStart
, nLen
== npos
? 0 : nLen
);
1194 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1196 wxString
strTmp(c_str(), nStart
);
1197 if ( nLen
!= npos
) {
1198 wxASSERT( nStart
+ nLen
<= Len() );
1200 strTmp
.append(c_str() + nStart
+ nLen
);
1207 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const char *sz
)
1209 wxASSERT( nStart
+ nLen
<= Strlen(sz
) );
1213 strTmp
.append(c_str(), nStart
);
1215 strTmp
.append(c_str() + nStart
+ nLen
);
1221 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, char ch
)
1223 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1226 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1227 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1229 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1232 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1233 const char* sz
, size_t nCount
)
1235 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1238 #endif //std::string compatibility
1240 // ============================================================================
1242 // ============================================================================
1244 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1245 #define ARRAY_MAXSIZE_INCREMENT 4096
1246 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1247 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1250 #define STRING(p) ((wxString *)(&(p)))
1253 wxArrayString::wxArrayString()
1257 m_pItems
= (char **) NULL
;
1261 wxArrayString::wxArrayString(const wxArrayString
& src
)
1265 m_pItems
= (char **) NULL
;
1270 // assignment operator
1271 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1276 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1277 Alloc(src
.m_nCount
);
1279 // we can't just copy the pointers here because otherwise we would share
1280 // the strings with another array
1281 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1284 if ( m_nCount
!= 0 )
1285 memcpy(m_pItems
, src
.m_pItems
, m_nCount
*sizeof(char *));
1291 void wxArrayString::Grow()
1293 // only do it if no more place
1294 if( m_nCount
== m_nSize
) {
1295 if( m_nSize
== 0 ) {
1296 // was empty, alloc some memory
1297 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1298 m_pItems
= new char *[m_nSize
];
1301 // otherwise when it's called for the first time, nIncrement would be 0
1302 // and the array would never be expanded
1303 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE
!= 0 );
1305 // add 50% but not too much
1306 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1307 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1308 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1309 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1310 m_nSize
+= nIncrement
;
1311 char **pNew
= new char *[m_nSize
];
1313 // copy data to new location
1314 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(char *));
1316 // delete old memory (but do not release the strings!)
1317 wxDELETEA(m_pItems
);
1324 void wxArrayString::Free()
1326 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1327 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1331 // deletes all the strings from the list
1332 void wxArrayString::Empty()
1339 // as Empty, but also frees memory
1340 void wxArrayString::Clear()
1347 wxDELETEA(m_pItems
);
1351 wxArrayString::~wxArrayString()
1355 wxDELETEA(m_pItems
);
1358 // pre-allocates memory (frees the previous data!)
1359 void wxArrayString::Alloc(size_t nSize
)
1361 wxASSERT( nSize
> 0 );
1363 // only if old buffer was not big enough
1364 if ( nSize
> m_nSize
) {
1366 wxDELETEA(m_pItems
);
1367 m_pItems
= new char *[nSize
];
1374 // searches the array for an item (forward or backwards)
1375 int wxArrayString::Index(const char *sz
, bool bCase
, bool bFromEnd
) const
1378 if ( m_nCount
> 0 ) {
1379 size_t ui
= m_nCount
;
1381 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1388 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1389 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1397 // add item at the end
1398 void wxArrayString::Add(const wxString
& str
)
1400 wxASSERT( str
.GetStringData()->IsValid() );
1404 // the string data must not be deleted!
1405 str
.GetStringData()->Lock();
1406 m_pItems
[m_nCount
++] = (char *)str
.c_str();
1409 // add item at the given position
1410 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
1412 wxASSERT( str
.GetStringData()->IsValid() );
1414 wxCHECK_RET( nIndex
<= m_nCount
, ("bad index in wxArrayString::Insert") );
1418 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
1419 (m_nCount
- nIndex
)*sizeof(char *));
1421 str
.GetStringData()->Lock();
1422 m_pItems
[nIndex
] = (char *)str
.c_str();
1427 // removes item from array (by index)
1428 void wxArrayString::Remove(size_t nIndex
)
1430 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Remove") );
1433 Item(nIndex
).GetStringData()->Unlock();
1435 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
1436 (m_nCount
- nIndex
- 1)*sizeof(char *));
1440 // removes item from array (by value)
1441 void wxArrayString::Remove(const char *sz
)
1443 int iIndex
= Index(sz
);
1445 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
1446 _("removing inexistent element in wxArrayString::Remove") );
1451 // ----------------------------------------------------------------------------
1453 // ----------------------------------------------------------------------------
1455 // we can only sort one array at a time with the quick-sort based
1458 #include <wx/thread.h>
1460 // need a critical section to protect access to gs_compareFunction and
1461 // gs_sortAscending variables
1462 static wxCriticalSection gs_critsectStringSort
;
1464 // call this before the value of the global sort vars is changed/after
1465 // you're finished with them
1466 #define START_SORT() gs_critsectStringSort.Enter()
1467 #define END_SORT() gs_critsectStringSort.Leave()
1469 #define START_SORT()
1471 #endif // wxUSE_THREADS
1473 // function to use for string comparaison
1474 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
1476 // if we don't use the compare function, this flag tells us if we sort the
1477 // array in ascending or descending order
1478 static bool gs_sortAscending
= TRUE
;
1480 // function which is called by quick sort
1481 static int wxStringCompareFunction(const void *first
, const void *second
)
1483 wxString
*strFirst
= (wxString
*)first
;
1484 wxString
*strSecond
= (wxString
*)second
;
1486 if ( gs_compareFunction
)
1487 return gs_compareFunction(*strFirst
, *strSecond
);
1489 int result
= strcmp(strFirst
->c_str(), strSecond
->c_str());
1491 return gs_sortAscending
? result
: -result
;
1495 // sort array elements using passed comparaison function
1496 void wxArrayString::Sort(CompareFunction compareFunction
)
1500 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1501 gs_compareFunction
= compareFunction
;
1508 void wxArrayString::Sort(bool reverseOrder
)
1512 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1513 gs_sortAscending
= !reverseOrder
;
1520 void wxArrayString::DoSort()
1522 // just sort the pointers using qsort() - of course it only works because
1523 // wxString() *is* a pointer to its data
1524 qsort(m_pItems
, m_nCount
, sizeof(char *), wxStringCompareFunction
);