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"
38 #include "wx/thread.h"
52 // allocating extra space for each string consumes more memory but speeds up
53 // the concatenation operations (nLen is the current string's length)
54 // NB: EXTRA_ALLOC must be >= 0!
55 #define EXTRA_ALLOC (19 - nLen % 16)
57 // ---------------------------------------------------------------------------
58 // static class variables definition
59 // ---------------------------------------------------------------------------
61 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
62 // must define this static for VA or else you get multiply defined symbols
64 const unsigned int wxSTRING_MAXLEN
= UINT_MAX
- 100;
67 #ifdef wxSTD_STRING_COMPATIBILITY
68 const size_t wxString::npos
= wxSTRING_MAXLEN
;
69 #endif // wxSTD_STRING_COMPATIBILITY
71 // ----------------------------------------------------------------------------
73 // ----------------------------------------------------------------------------
75 // for an empty string, GetStringData() will return this address: this
76 // structure has the same layout as wxStringData and it's data() method will
77 // return the empty string (dummy pointer)
82 } g_strEmpty
= { {-1, 0, 0}, wxT('\0') };
84 // empty C style string: points to 'string data' byte of g_strEmpty
85 extern const wxChar WXDLLEXPORT
*wxEmptyString
= &g_strEmpty
.dummy
;
87 // ----------------------------------------------------------------------------
89 // ----------------------------------------------------------------------------
91 #if defined(wxSTD_STRING_COMPATIBILITY) && wxUSE_STD_IOSTREAM
93 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
96 // ATTN: you can _not_ use both of these in the same program!
98 wxSTD istream
& operator>>(wxSTD istream
& is
, wxString
& WXUNUSED(str
))
103 streambuf
*sb
= is
.rdbuf();
106 int ch
= sb
->sbumpc ();
108 is
.setstate(ios::eofbit
);
111 else if ( isspace(ch
) ) {
123 if ( str
.length() == 0 )
124 is
.setstate(ios::failbit
);
129 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
135 #endif //std::string compatibility
137 // ----------------------------------------------------------------------------
139 // ----------------------------------------------------------------------------
141 // this small class is used to gather statistics for performance tuning
142 //#define WXSTRING_STATISTICS
143 #ifdef WXSTRING_STATISTICS
147 Averager(const wxChar
*sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
149 { wxPrintf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
151 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
154 size_t m_nCount
, m_nTotal
;
156 } g_averageLength("allocation size"),
157 g_averageSummandLength("summand length"),
158 g_averageConcatHit("hit probability in concat"),
159 g_averageInitialLength("initial string length");
161 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
163 #define STATISTICS_ADD(av, val)
164 #endif // WXSTRING_STATISTICS
166 // ===========================================================================
167 // wxString class core
168 // ===========================================================================
170 // ---------------------------------------------------------------------------
172 // ---------------------------------------------------------------------------
174 // constructs string of <nLength> copies of character <ch>
175 wxString::wxString(wxChar ch
, size_t nLength
)
180 if ( !AllocBuffer(nLength
) ) {
181 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
186 // memset only works on chars
187 for ( size_t n
= 0; n
< nLength
; n
++ )
190 memset(m_pchData
, ch
, nLength
);
195 // takes nLength elements of psz starting at nPos
196 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
200 // if the length is not given, assume the string to be NUL terminated
201 if ( nLength
== wxSTRING_MAXLEN
) {
202 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
204 nLength
= wxStrlen(psz
+ nPos
);
207 STATISTICS_ADD(InitialLength
, nLength
);
210 // trailing '\0' is written in AllocBuffer()
211 if ( !AllocBuffer(nLength
) ) {
212 wxFAIL_MSG( _T("out of memory in wxString::InitWith") );
215 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
219 #ifdef wxSTD_STRING_COMPATIBILITY
221 // poor man's iterators are "void *" pointers
222 wxString::wxString(const void *pStart
, const void *pEnd
)
224 InitWith((const wxChar
*)pStart
, 0,
225 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
228 #endif //std::string compatibility
232 // from multibyte string
233 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
235 // first get the size of the buffer we need
239 // calculate the needed size ourselves or use a provide one
240 nLen
= nLength
== wxSTRING_MAXLEN
? conv
.MB2WC(NULL
, psz
, 0) : nLength
;
244 // nothing to convert
249 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
251 if ( !AllocBuffer(nLen
) )
253 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
257 // MB2WC wants the buffer size, not the string length
258 if ( conv
.MB2WC(m_pchData
, psz
, nLen
+ 1) != (size_t)-1 )
263 //else: the conversion failed -- leave the string empty (what else?)
273 wxString::wxString(const wchar_t *pwz
, wxMBConv
& conv
, size_t nLength
)
275 // first get the size of the buffer we need
279 // calculate the needed size ourselves or use a provide one
280 nLen
= nLength
== wxSTRING_MAXLEN
? conv
.WC2MB(NULL
, pwz
, 0) : nLength
;
284 // nothing to convert
289 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
291 if ( !AllocBuffer(nLen
) )
293 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
297 // WC2MB wants the buffer size, not the string length
298 if ( conv
.WC2MB(m_pchData
, pwz
, nLen
+ 1) != (size_t)-1 )
303 //else: the conversion failed -- leave the string empty (what else?)
308 #endif // wxUSE_WCHAR_T
310 #endif // Unicode/ANSI
312 // ---------------------------------------------------------------------------
314 // ---------------------------------------------------------------------------
316 // allocates memory needed to store a C string of length nLen
317 bool wxString::AllocBuffer(size_t nLen
)
319 // allocating 0 sized buffer doesn't make sense, all empty strings should
321 wxASSERT( nLen
> 0 );
323 // make sure that we don't overflow
324 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
325 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
327 STATISTICS_ADD(Length
, nLen
);
330 // 1) one extra character for '\0' termination
331 // 2) sizeof(wxStringData) for housekeeping info
332 wxStringData
* pData
= (wxStringData
*)
333 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
335 if ( pData
== NULL
) {
336 // allocation failures are handled by the caller
341 pData
->nDataLength
= nLen
;
342 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
343 m_pchData
= pData
->data(); // data starts after wxStringData
344 m_pchData
[nLen
] = wxT('\0');
348 // must be called before changing this string
349 bool wxString::CopyBeforeWrite()
351 wxStringData
* pData
= GetStringData();
353 if ( pData
->IsShared() ) {
354 pData
->Unlock(); // memory not freed because shared
355 size_t nLen
= pData
->nDataLength
;
356 if ( !AllocBuffer(nLen
) ) {
357 // allocation failures are handled by the caller
360 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
363 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
368 // must be called before replacing contents of this string
369 bool wxString::AllocBeforeWrite(size_t nLen
)
371 wxASSERT( nLen
!= 0 ); // doesn't make any sense
373 // must not share string and must have enough space
374 wxStringData
* pData
= GetStringData();
375 if ( pData
->IsShared() || pData
->IsEmpty() ) {
376 // can't work with old buffer, get new one
378 if ( !AllocBuffer(nLen
) ) {
379 // allocation failures are handled by the caller
384 if ( nLen
> pData
->nAllocLength
) {
385 // realloc the buffer instead of calling malloc() again, this is more
387 STATISTICS_ADD(Length
, nLen
);
391 pData
= (wxStringData
*)
392 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
394 if ( pData
== NULL
) {
395 // allocation failures are handled by the caller
396 // keep previous data since reallocation failed
400 pData
->nAllocLength
= nLen
;
401 m_pchData
= pData
->data();
404 // now we have enough space, just update the string length
405 pData
->nDataLength
= nLen
;
408 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
413 // allocate enough memory for nLen characters
414 bool wxString::Alloc(size_t nLen
)
416 wxStringData
*pData
= GetStringData();
417 if ( pData
->nAllocLength
<= nLen
) {
418 if ( pData
->IsEmpty() ) {
421 wxStringData
* pData
= (wxStringData
*)
422 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
424 if ( pData
== NULL
) {
425 // allocation failure handled by caller
430 pData
->nDataLength
= 0;
431 pData
->nAllocLength
= nLen
;
432 m_pchData
= pData
->data(); // data starts after wxStringData
433 m_pchData
[0u] = wxT('\0');
435 else if ( pData
->IsShared() ) {
436 pData
->Unlock(); // memory not freed because shared
437 size_t nOldLen
= pData
->nDataLength
;
438 if ( !AllocBuffer(nLen
) ) {
439 // allocation failure handled by caller
442 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
447 pData
= (wxStringData
*)
448 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
450 if ( pData
== NULL
) {
451 // allocation failure handled by caller
452 // keep previous data since reallocation failed
456 // it's not important if the pointer changed or not (the check for this
457 // is not faster than assigning to m_pchData in all cases)
458 pData
->nAllocLength
= nLen
;
459 m_pchData
= pData
->data();
462 //else: we've already got enough
466 // shrink to minimal size (releasing extra memory)
467 bool wxString::Shrink()
469 wxStringData
*pData
= GetStringData();
471 size_t nLen
= pData
->nDataLength
;
472 void *p
= realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
475 wxFAIL_MSG( _T("out of memory reallocating wxString data") );
476 // keep previous data since reallocation failed
482 // contrary to what one might believe, some realloc() implementation do
483 // move the memory block even when its size is reduced
484 pData
= (wxStringData
*)p
;
486 m_pchData
= pData
->data();
489 pData
->nAllocLength
= nLen
;
494 // get the pointer to writable buffer of (at least) nLen bytes
495 wxChar
*wxString::GetWriteBuf(size_t nLen
)
497 if ( !AllocBeforeWrite(nLen
) ) {
498 // allocation failure handled by caller
502 wxASSERT( GetStringData()->nRefs
== 1 );
503 GetStringData()->Validate(FALSE
);
508 // put string back in a reasonable state after GetWriteBuf
509 void wxString::UngetWriteBuf()
511 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
512 GetStringData()->Validate(TRUE
);
515 void wxString::UngetWriteBuf(size_t nLen
)
517 GetStringData()->nDataLength
= nLen
;
518 GetStringData()->Validate(TRUE
);
521 // ---------------------------------------------------------------------------
523 // ---------------------------------------------------------------------------
525 // all functions are inline in string.h
527 // ---------------------------------------------------------------------------
528 // assignment operators
529 // ---------------------------------------------------------------------------
531 // helper function: does real copy
532 bool wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
534 if ( nSrcLen
== 0 ) {
538 if ( !AllocBeforeWrite(nSrcLen
) ) {
539 // allocation failure handled by caller
542 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
543 GetStringData()->nDataLength
= nSrcLen
;
544 m_pchData
[nSrcLen
] = wxT('\0');
549 // assigns one string to another
550 wxString
& wxString::operator=(const wxString
& stringSrc
)
552 wxASSERT( stringSrc
.GetStringData()->IsValid() );
554 // don't copy string over itself
555 if ( m_pchData
!= stringSrc
.m_pchData
) {
556 if ( stringSrc
.GetStringData()->IsEmpty() ) {
561 GetStringData()->Unlock();
562 m_pchData
= stringSrc
.m_pchData
;
563 GetStringData()->Lock();
570 // assigns a single character
571 wxString
& wxString::operator=(wxChar ch
)
573 if ( !AssignCopy(1, &ch
) ) {
574 wxFAIL_MSG( _T("out of memory in wxString::operator=(wxChar)") );
581 wxString
& wxString::operator=(const wxChar
*psz
)
583 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
584 wxFAIL_MSG( _T("out of memory in wxString::operator=(const wxChar *)") );
591 // same as 'signed char' variant
592 wxString
& wxString::operator=(const unsigned char* psz
)
594 *this = (const char *)psz
;
599 wxString
& wxString::operator=(const wchar_t *pwz
)
609 // ---------------------------------------------------------------------------
610 // string concatenation
611 // ---------------------------------------------------------------------------
613 // add something to this string
614 bool wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
616 STATISTICS_ADD(SummandLength
, nSrcLen
);
618 // concatenating an empty string is a NOP
620 wxStringData
*pData
= GetStringData();
621 size_t nLen
= pData
->nDataLength
;
622 size_t nNewLen
= nLen
+ nSrcLen
;
624 // alloc new buffer if current is too small
625 if ( pData
->IsShared() ) {
626 STATISTICS_ADD(ConcatHit
, 0);
628 // we have to allocate another buffer
629 wxStringData
* pOldData
= GetStringData();
630 if ( !AllocBuffer(nNewLen
) ) {
631 // allocation failure handled by caller
634 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
637 else if ( nNewLen
> pData
->nAllocLength
) {
638 STATISTICS_ADD(ConcatHit
, 0);
640 // we have to grow the buffer
641 if ( !Alloc(nNewLen
) ) {
642 // allocation failure handled by caller
647 STATISTICS_ADD(ConcatHit
, 1);
649 // the buffer is already big enough
652 // should be enough space
653 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
655 // fast concatenation - all is done in our buffer
656 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
658 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
659 GetStringData()->nDataLength
= nNewLen
; // and fix the length
661 //else: the string to append was empty
666 * concatenation functions come in 5 flavours:
668 * char + string and string + char
669 * C str + string and string + C str
672 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
674 wxASSERT( str1
.GetStringData()->IsValid() );
675 wxASSERT( str2
.GetStringData()->IsValid() );
683 wxString
operator+(const wxString
& str
, wxChar ch
)
685 wxASSERT( str
.GetStringData()->IsValid() );
693 wxString
operator+(wxChar ch
, const wxString
& str
)
695 wxASSERT( str
.GetStringData()->IsValid() );
703 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
705 wxASSERT( str
.GetStringData()->IsValid() );
708 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
709 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
717 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
719 wxASSERT( str
.GetStringData()->IsValid() );
722 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
723 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
731 // ===========================================================================
732 // other common string functions
733 // ===========================================================================
737 wxString
wxString::FromAscii(const char *ascii
)
740 return wxEmptyString
;
742 size_t len
= strlen( ascii
);
747 wxStringBuffer
buf(res
, len
);
753 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
761 wxString
wxString::FromAscii(const char ascii
)
763 // What do we do with '\0' ?
766 res
+= (wchar_t)(unsigned char) ascii
;
771 const wxCharBuffer
wxString::ToAscii() const
773 // this will allocate enough space for the terminating NUL too
774 wxCharBuffer
buffer(length());
776 signed char *dest
= (signed char *)buffer
.data();
778 const wchar_t *pwc
= c_str();
781 *dest
++ = *pwc
> SCHAR_MAX
? '_' : *pwc
;
783 // the output string can't have embedded NULs anyhow, so we can safely
784 // stop at first of them even if we do have any
794 // ---------------------------------------------------------------------------
795 // simple sub-string extraction
796 // ---------------------------------------------------------------------------
798 // helper function: clone the data attached to this string
799 bool wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
801 if ( nCopyLen
== 0 ) {
805 if ( !dest
.AllocBuffer(nCopyLen
) ) {
806 // allocation failure handled by caller
809 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
814 // extract string of length nCount starting at nFirst
815 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
817 wxStringData
*pData
= GetStringData();
818 size_t nLen
= pData
->nDataLength
;
820 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
821 if ( nCount
== wxSTRING_MAXLEN
)
823 nCount
= nLen
- nFirst
;
826 // out-of-bounds requests return sensible things
827 if ( nFirst
+ nCount
> nLen
)
829 nCount
= nLen
- nFirst
;
834 // AllocCopy() will return empty string
839 if ( !AllocCopy(dest
, nCount
, nFirst
) ) {
840 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
846 // check that the tring starts with prefix and return the rest of the string
847 // in the provided pointer if it is not NULL, otherwise return FALSE
848 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
850 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
852 // first check if the beginning of the string matches the prefix: note
853 // that we don't have to check that we don't run out of this string as
854 // when we reach the terminating NUL, either prefix string ends too (and
855 // then it's ok) or we break out of the loop because there is no match
856 const wxChar
*p
= c_str();
859 if ( *prefix
++ != *p
++ )
868 // put the rest of the string into provided pointer
875 // extract nCount last (rightmost) characters
876 wxString
wxString::Right(size_t nCount
) const
878 if ( nCount
> (size_t)GetStringData()->nDataLength
)
879 nCount
= GetStringData()->nDataLength
;
882 if ( !AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
) ) {
883 wxFAIL_MSG( _T("out of memory in wxString::Right") );
888 // get all characters after the last occurence of ch
889 // (returns the whole string if ch not found)
890 wxString
wxString::AfterLast(wxChar ch
) const
893 int iPos
= Find(ch
, TRUE
);
894 if ( iPos
== wxNOT_FOUND
)
897 str
= c_str() + iPos
+ 1;
902 // extract nCount first (leftmost) characters
903 wxString
wxString::Left(size_t nCount
) const
905 if ( nCount
> (size_t)GetStringData()->nDataLength
)
906 nCount
= GetStringData()->nDataLength
;
909 if ( !AllocCopy(dest
, nCount
, 0) ) {
910 wxFAIL_MSG( _T("out of memory in wxString::Left") );
915 // get all characters before the first occurence of ch
916 // (returns the whole string if ch not found)
917 wxString
wxString::BeforeFirst(wxChar ch
) const
920 for ( const wxChar
*pc
= m_pchData
; *pc
!= wxT('\0') && *pc
!= ch
; pc
++ )
926 /// get all characters before the last occurence of ch
927 /// (returns empty string if ch not found)
928 wxString
wxString::BeforeLast(wxChar ch
) const
931 int iPos
= Find(ch
, TRUE
);
932 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
933 str
= wxString(c_str(), iPos
);
938 /// get all characters after the first occurence of ch
939 /// (returns empty string if ch not found)
940 wxString
wxString::AfterFirst(wxChar ch
) const
944 if ( iPos
!= wxNOT_FOUND
)
945 str
= c_str() + iPos
+ 1;
950 // replace first (or all) occurences of some substring with another one
951 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
953 size_t uiCount
= 0; // count of replacements made
955 size_t uiOldLen
= wxStrlen(szOld
);
958 const wxChar
*pCurrent
= m_pchData
;
959 const wxChar
*pSubstr
;
960 while ( *pCurrent
!= wxT('\0') ) {
961 pSubstr
= wxStrstr(pCurrent
, szOld
);
962 if ( pSubstr
== NULL
) {
963 // strTemp is unused if no replacements were made, so avoid the copy
967 strTemp
+= pCurrent
; // copy the rest
968 break; // exit the loop
971 // take chars before match
972 if ( !strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
) ) {
973 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
977 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
982 if ( !bReplaceAll
) {
983 strTemp
+= pCurrent
; // copy the rest
984 break; // exit the loop
989 // only done if there were replacements, otherwise would have returned above
995 bool wxString::IsAscii() const
997 const wxChar
*s
= (const wxChar
*) *this;
999 if(!isascii(*s
)) return(FALSE
);
1005 bool wxString::IsWord() const
1007 const wxChar
*s
= (const wxChar
*) *this;
1009 if(!wxIsalpha(*s
)) return(FALSE
);
1015 bool wxString::IsNumber() const
1017 const wxChar
*s
= (const wxChar
*) *this;
1019 if ((s
[0] == '-') || (s
[0] == '+')) s
++;
1021 if(!wxIsdigit(*s
)) return(FALSE
);
1027 wxString
wxString::Strip(stripType w
) const
1030 if ( w
& leading
) s
.Trim(FALSE
);
1031 if ( w
& trailing
) s
.Trim(TRUE
);
1035 // ---------------------------------------------------------------------------
1037 // ---------------------------------------------------------------------------
1039 wxString
& wxString::MakeUpper()
1041 if ( !CopyBeforeWrite() ) {
1042 wxFAIL_MSG( _T("out of memory in wxString::MakeUpper") );
1046 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1047 *p
= (wxChar
)wxToupper(*p
);
1052 wxString
& wxString::MakeLower()
1054 if ( !CopyBeforeWrite() ) {
1055 wxFAIL_MSG( _T("out of memory in wxString::MakeLower") );
1059 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1060 *p
= (wxChar
)wxTolower(*p
);
1065 // ---------------------------------------------------------------------------
1066 // trimming and padding
1067 // ---------------------------------------------------------------------------
1069 // some compilers (VC++ 6.0 not to name them) return TRUE for a call to
1070 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1071 // live with this by checking that the character is a 7 bit one - even if this
1072 // may fail to detect some spaces (I don't know if Unicode doesn't have
1073 // space-like symbols somewhere except in the first 128 chars), it is arguably
1074 // still better than trimming away accented letters
1075 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1077 // trims spaces (in the sense of isspace) from left or right side
1078 wxString
& wxString::Trim(bool bFromRight
)
1080 // first check if we're going to modify the string at all
1083 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1084 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1088 // ok, there is at least one space to trim
1089 if ( !CopyBeforeWrite() ) {
1090 wxFAIL_MSG( _T("out of memory in wxString::Trim") );
1096 // find last non-space character
1097 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
1098 while ( wxSafeIsspace(*psz
) && (psz
>= m_pchData
) )
1101 // truncate at trailing space start
1103 GetStringData()->nDataLength
= psz
- m_pchData
;
1107 // find first non-space character
1108 const wxChar
*psz
= m_pchData
;
1109 while ( wxSafeIsspace(*psz
) )
1112 // fix up data and length
1113 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
1114 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
1115 GetStringData()->nDataLength
= nDataLength
;
1122 // adds nCount characters chPad to the string from either side
1123 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1125 wxString
s(chPad
, nCount
);
1138 // truncate the string
1139 wxString
& wxString::Truncate(size_t uiLen
)
1141 if ( uiLen
< Len() ) {
1142 if ( !CopyBeforeWrite() ) {
1143 wxFAIL_MSG( _T("out of memory in wxString::Truncate") );
1147 *(m_pchData
+ uiLen
) = wxT('\0');
1148 GetStringData()->nDataLength
= uiLen
;
1150 //else: nothing to do, string is already short enough
1155 // ---------------------------------------------------------------------------
1156 // finding (return wxNOT_FOUND if not found and index otherwise)
1157 // ---------------------------------------------------------------------------
1160 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1162 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
1164 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1167 // find a sub-string (like strstr)
1168 int wxString::Find(const wxChar
*pszSub
) const
1170 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
1172 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1175 // ----------------------------------------------------------------------------
1176 // conversion to numbers
1177 // ----------------------------------------------------------------------------
1179 bool wxString::ToLong(long *val
, int base
) const
1181 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToLong") );
1182 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1184 const wxChar
*start
= c_str();
1186 *val
= wxStrtol(start
, &end
, base
);
1188 // return TRUE only if scan was stopped by the terminating NUL and if the
1189 // string was not empty to start with
1190 return !*end
&& (end
!= start
);
1193 bool wxString::ToULong(unsigned long *val
, int base
) const
1195 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToULong") );
1196 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1198 const wxChar
*start
= c_str();
1200 *val
= wxStrtoul(start
, &end
, base
);
1202 // return TRUE only if scan was stopped by the terminating NUL and if the
1203 // string was not empty to start with
1204 return !*end
&& (end
!= start
);
1207 bool wxString::ToDouble(double *val
) const
1209 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToDouble") );
1211 const wxChar
*start
= c_str();
1213 *val
= wxStrtod(start
, &end
);
1215 // return TRUE only if scan was stopped by the terminating NUL and if the
1216 // string was not empty to start with
1217 return !*end
&& (end
!= start
);
1220 // ---------------------------------------------------------------------------
1222 // ---------------------------------------------------------------------------
1225 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1228 va_start(argptr
, pszFormat
);
1231 s
.PrintfV(pszFormat
, argptr
);
1239 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1242 s
.PrintfV(pszFormat
, argptr
);
1246 int wxString::Printf(const wxChar
*pszFormat
, ...)
1249 va_start(argptr
, pszFormat
);
1251 int iLen
= PrintfV(pszFormat
, argptr
);
1258 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1263 wxChar
*buf
= GetWriteBuf(size
+ 1);
1270 int len
= wxVsnprintf(buf
, size
, pszFormat
, argptr
);
1272 // some implementations of vsnprintf() don't NUL terminate the string
1273 // if there is not enough space for it so always do it manually
1274 buf
[size
] = _T('\0');
1280 // ok, there was enough space
1284 // still not enough, double it again
1288 // we could have overshot
1294 // ----------------------------------------------------------------------------
1295 // misc other operations
1296 // ----------------------------------------------------------------------------
1298 // returns TRUE if the string matches the pattern which may contain '*' and
1299 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1301 bool wxString::Matches(const wxChar
*pszMask
) const
1303 // I disable this code as it doesn't seem to be faster (in fact, it seems
1304 // to be much slower) than the old, hand-written code below and using it
1305 // here requires always linking with libregex even if the user code doesn't
1307 #if 0 // wxUSE_REGEX
1308 // first translate the shell-like mask into a regex
1310 pattern
.reserve(wxStrlen(pszMask
));
1322 pattern
+= _T(".*");
1333 // these characters are special in a RE, quote them
1334 // (however note that we don't quote '[' and ']' to allow
1335 // using them for Unix shell like matching)
1336 pattern
+= _T('\\');
1340 pattern
+= *pszMask
;
1348 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1349 #else // !wxUSE_REGEX
1350 // TODO: this is, of course, awfully inefficient...
1352 // the char currently being checked
1353 const wxChar
*pszTxt
= c_str();
1355 // the last location where '*' matched
1356 const wxChar
*pszLastStarInText
= NULL
;
1357 const wxChar
*pszLastStarInMask
= NULL
;
1360 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1361 switch ( *pszMask
) {
1363 if ( *pszTxt
== wxT('\0') )
1366 // pszTxt and pszMask will be incremented in the loop statement
1372 // remember where we started to be able to backtrack later
1373 pszLastStarInText
= pszTxt
;
1374 pszLastStarInMask
= pszMask
;
1376 // ignore special chars immediately following this one
1377 // (should this be an error?)
1378 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1381 // if there is nothing more, match
1382 if ( *pszMask
== wxT('\0') )
1385 // are there any other metacharacters in the mask?
1387 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1389 if ( pEndMask
!= NULL
) {
1390 // we have to match the string between two metachars
1391 uiLenMask
= pEndMask
- pszMask
;
1394 // we have to match the remainder of the string
1395 uiLenMask
= wxStrlen(pszMask
);
1398 wxString
strToMatch(pszMask
, uiLenMask
);
1399 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1400 if ( pMatch
== NULL
)
1403 // -1 to compensate "++" in the loop
1404 pszTxt
= pMatch
+ uiLenMask
- 1;
1405 pszMask
+= uiLenMask
- 1;
1410 if ( *pszMask
!= *pszTxt
)
1416 // match only if nothing left
1417 if ( *pszTxt
== wxT('\0') )
1420 // if we failed to match, backtrack if we can
1421 if ( pszLastStarInText
) {
1422 pszTxt
= pszLastStarInText
+ 1;
1423 pszMask
= pszLastStarInMask
;
1425 pszLastStarInText
= NULL
;
1427 // don't bother resetting pszLastStarInMask, it's unnecessary
1433 #endif // wxUSE_REGEX/!wxUSE_REGEX
1436 // Count the number of chars
1437 int wxString::Freq(wxChar ch
) const
1441 for (int i
= 0; i
< len
; i
++)
1443 if (GetChar(i
) == ch
)
1449 // convert to upper case, return the copy of the string
1450 wxString
wxString::Upper() const
1451 { wxString
s(*this); return s
.MakeUpper(); }
1453 // convert to lower case, return the copy of the string
1454 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1456 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1459 va_start(argptr
, pszFormat
);
1460 int iLen
= PrintfV(pszFormat
, argptr
);
1465 // ---------------------------------------------------------------------------
1466 // standard C++ library string functions
1467 // ---------------------------------------------------------------------------
1469 #ifdef wxSTD_STRING_COMPATIBILITY
1471 void wxString::resize(size_t nSize
, wxChar ch
)
1473 size_t len
= length();
1479 else if ( nSize
> len
)
1481 *this += wxString(ch
, nSize
- len
);
1483 //else: we have exactly the specified length, nothing to do
1486 void wxString::swap(wxString
& str
)
1488 // this is slightly less efficient than fiddling with m_pchData directly,
1489 // but it is still quite efficient as we don't copy the string here because
1490 // ref count always stays positive
1496 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1498 wxASSERT( str
.GetStringData()->IsValid() );
1499 wxASSERT( nPos
<= Len() );
1501 if ( !str
.IsEmpty() ) {
1503 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1504 wxStrncpy(pc
, c_str(), nPos
);
1505 wxStrcpy(pc
+ nPos
, str
);
1506 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1507 strTmp
.UngetWriteBuf();
1514 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1516 wxASSERT( str
.GetStringData()->IsValid() );
1517 wxASSERT( nStart
<= Len() );
1519 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1521 return p
== NULL
? npos
: p
- c_str();
1524 // VC++ 1.5 can't cope with the default argument in the header.
1525 #if !defined(__VISUALC__) || defined(__WIN32__)
1526 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1528 return find(wxString(sz
, n
), nStart
);
1532 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1533 #if !defined(__BORLANDC__)
1534 size_t wxString::find(wxChar ch
, size_t nStart
) const
1536 wxASSERT( nStart
<= Len() );
1538 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1540 return p
== NULL
? npos
: p
- c_str();
1544 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1546 wxASSERT( str
.GetStringData()->IsValid() );
1547 wxASSERT( nStart
== npos
|| nStart
<= Len() );
1549 // TODO could be made much quicker than that
1550 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1551 while ( p
>= c_str() + str
.Len() ) {
1552 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1553 return p
- str
.Len() - c_str();
1560 // VC++ 1.5 can't cope with the default argument in the header.
1561 #if !defined(__VISUALC__) || defined(__WIN32__)
1562 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1564 return rfind(wxString(sz
, n
== npos
? wxSTRING_MAXLEN
: n
), nStart
);
1567 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1569 if ( nStart
== npos
)
1575 wxASSERT( nStart
<= Len() );
1578 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1583 size_t result
= p
- c_str();
1584 return ( result
> nStart
) ? npos
: result
;
1588 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1590 const wxChar
*start
= c_str() + nStart
;
1591 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1593 return firstOf
- c_str();
1598 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1600 if ( nStart
== npos
)
1606 wxASSERT( nStart
<= Len() );
1609 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1611 if ( wxStrchr(sz
, *p
) )
1618 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1620 if ( nStart
== npos
)
1626 wxASSERT( nStart
<= Len() );
1629 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1630 if ( nAccept
>= length() - nStart
)
1636 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1638 wxASSERT( nStart
<= Len() );
1640 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1649 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1651 if ( nStart
== npos
)
1657 wxASSERT( nStart
<= Len() );
1660 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1662 if ( !wxStrchr(sz
, *p
) )
1669 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1671 if ( nStart
== npos
)
1677 wxASSERT( nStart
<= Len() );
1680 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1689 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1691 wxString
strTmp(c_str(), nStart
);
1692 if ( nLen
!= npos
) {
1693 wxASSERT( nStart
+ nLen
<= Len() );
1695 strTmp
.append(c_str() + nStart
+ nLen
);
1702 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1704 wxASSERT_MSG( nStart
+ nLen
<= Len(),
1705 _T("index out of bounds in wxString::replace") );
1708 strTmp
.Alloc(Len()); // micro optimisation to avoid multiple mem allocs
1711 strTmp
.append(c_str(), nStart
);
1712 strTmp
<< sz
<< c_str() + nStart
+ nLen
;
1718 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1720 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1723 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1724 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1726 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1729 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1730 const wxChar
* sz
, size_t nCount
)
1732 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1735 #endif //std::string compatibility
1737 // ============================================================================
1739 // ============================================================================
1741 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1742 #define ARRAY_MAXSIZE_INCREMENT 4096
1744 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1745 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1748 #define STRING(p) ((wxString *)(&(p)))
1751 void wxArrayString::Init(bool autoSort
)
1755 m_pItems
= (wxChar
**) NULL
;
1756 m_autoSort
= autoSort
;
1760 wxArrayString::wxArrayString(const wxArrayString
& src
)
1762 Init(src
.m_autoSort
);
1767 // assignment operator
1768 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1775 m_autoSort
= src
.m_autoSort
;
1780 void wxArrayString::Copy(const wxArrayString
& src
)
1782 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1783 Alloc(src
.m_nCount
);
1785 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1790 void wxArrayString::Grow(size_t nIncrement
)
1792 // only do it if no more place
1793 if ( (m_nSize
- m_nCount
) < nIncrement
) {
1794 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
1795 // be never resized!
1796 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
1797 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
1800 if ( m_nSize
== 0 ) {
1801 // was empty, alloc some memory
1802 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1803 if (m_nSize
< nIncrement
)
1804 m_nSize
= nIncrement
;
1805 m_pItems
= new wxChar
*[m_nSize
];
1808 // otherwise when it's called for the first time, nIncrement would be 0
1809 // and the array would never be expanded
1810 // add 50% but not too much
1811 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1812 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1813 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1814 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1815 if ( nIncrement
< ndefIncrement
)
1816 nIncrement
= ndefIncrement
;
1817 m_nSize
+= nIncrement
;
1818 wxChar
**pNew
= new wxChar
*[m_nSize
];
1820 // copy data to new location
1821 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1823 // delete old memory (but do not release the strings!)
1824 wxDELETEA(m_pItems
);
1831 void wxArrayString::Free()
1833 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1834 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1838 // deletes all the strings from the list
1839 void wxArrayString::Empty()
1846 // as Empty, but also frees memory
1847 void wxArrayString::Clear()
1854 wxDELETEA(m_pItems
);
1858 wxArrayString::~wxArrayString()
1862 wxDELETEA(m_pItems
);
1865 // pre-allocates memory (frees the previous data!)
1866 void wxArrayString::Alloc(size_t nSize
)
1868 // only if old buffer was not big enough
1869 if ( nSize
> m_nSize
) {
1871 wxDELETEA(m_pItems
);
1872 m_pItems
= new wxChar
*[nSize
];
1879 // minimizes the memory usage by freeing unused memory
1880 void wxArrayString::Shrink()
1882 // only do it if we have some memory to free
1883 if( m_nCount
< m_nSize
) {
1884 // allocates exactly as much memory as we need
1885 wxChar
**pNew
= new wxChar
*[m_nCount
];
1887 // copy data to new location
1888 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1894 // return a wxString[] as required for some control ctors.
1895 wxString
* wxArrayString::GetStringArray() const
1897 wxString
*array
= 0;
1901 array
= new wxString
[m_nCount
];
1902 for( size_t i
= 0; i
< m_nCount
; i
++ )
1903 array
[i
] = m_pItems
[i
];
1909 // searches the array for an item (forward or backwards)
1910 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
1913 // use binary search in the sorted array
1914 wxASSERT_MSG( bCase
&& !bFromEnd
,
1915 wxT("search parameters ignored for auto sorted array") );
1924 res
= wxStrcmp(sz
, m_pItems
[i
]);
1936 // use linear search in unsorted array
1938 if ( m_nCount
> 0 ) {
1939 size_t ui
= m_nCount
;
1941 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1948 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1949 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1958 // add item at the end
1959 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
1962 // insert the string at the correct position to keep the array sorted
1970 res
= wxStrcmp(str
, m_pItems
[i
]);
1981 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
1983 Insert(str
, lo
, nInsert
);
1988 wxASSERT( str
.GetStringData()->IsValid() );
1992 for (size_t i
= 0; i
< nInsert
; i
++)
1994 // the string data must not be deleted!
1995 str
.GetStringData()->Lock();
1998 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2000 size_t ret
= m_nCount
;
2001 m_nCount
+= nInsert
;
2006 // add item at the given position
2007 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2009 wxASSERT( str
.GetStringData()->IsValid() );
2011 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2012 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2013 wxT("array size overflow in wxArrayString::Insert") );
2017 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2018 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2020 for (size_t i
= 0; i
< nInsert
; i
++)
2022 str
.GetStringData()->Lock();
2023 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2025 m_nCount
+= nInsert
;
2029 void wxArrayString::SetCount(size_t count
)
2034 while ( m_nCount
< count
)
2035 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2038 // removes item from array (by index)
2039 void wxArrayString::Remove(size_t nIndex
, size_t nRemove
)
2041 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2042 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2043 wxT("removing too many elements in wxArrayString::Remove") );
2046 for (size_t i
= 0; i
< nRemove
; i
++)
2047 Item(nIndex
+ i
).GetStringData()->Unlock();
2049 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2050 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2051 m_nCount
-= nRemove
;
2054 // removes item from array (by value)
2055 void wxArrayString::Remove(const wxChar
*sz
)
2057 int iIndex
= Index(sz
);
2059 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2060 wxT("removing inexistent element in wxArrayString::Remove") );
2065 // ----------------------------------------------------------------------------
2067 // ----------------------------------------------------------------------------
2069 // we can only sort one array at a time with the quick-sort based
2072 // need a critical section to protect access to gs_compareFunction and
2073 // gs_sortAscending variables
2074 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2076 // call this before the value of the global sort vars is changed/after
2077 // you're finished with them
2078 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2079 gs_critsectStringSort = new wxCriticalSection; \
2080 gs_critsectStringSort->Enter()
2081 #define END_SORT() gs_critsectStringSort->Leave(); \
2082 delete gs_critsectStringSort; \
2083 gs_critsectStringSort = NULL
2085 #define START_SORT()
2087 #endif // wxUSE_THREADS
2089 // function to use for string comparaison
2090 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2092 // if we don't use the compare function, this flag tells us if we sort the
2093 // array in ascending or descending order
2094 static bool gs_sortAscending
= TRUE
;
2096 // function which is called by quick sort
2097 extern "C" int wxC_CALLING_CONV
// LINKAGEMODE
2098 wxStringCompareFunction(const void *first
, const void *second
)
2100 wxString
*strFirst
= (wxString
*)first
;
2101 wxString
*strSecond
= (wxString
*)second
;
2103 if ( gs_compareFunction
) {
2104 return gs_compareFunction(*strFirst
, *strSecond
);
2107 // maybe we should use wxStrcoll
2108 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
2110 return gs_sortAscending
? result
: -result
;
2114 // sort array elements using passed comparaison function
2115 void wxArrayString::Sort(CompareFunction compareFunction
)
2119 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2120 gs_compareFunction
= compareFunction
;
2124 // reset it to NULL so that Sort(bool) will work the next time
2125 gs_compareFunction
= NULL
;
2130 void wxArrayString::Sort(bool reverseOrder
)
2134 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2135 gs_sortAscending
= !reverseOrder
;
2142 void wxArrayString::DoSort()
2144 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2146 // just sort the pointers using qsort() - of course it only works because
2147 // wxString() *is* a pointer to its data
2148 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2151 bool wxArrayString::operator==(const wxArrayString
& a
) const
2153 if ( m_nCount
!= a
.m_nCount
)
2156 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2158 if ( Item(n
) != a
[n
] )