1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxString class
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows licence
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"
49 // allocating extra space for each string consumes more memory but speeds up
50 // the concatenation operations (nLen is the current string's length)
51 // NB: EXTRA_ALLOC must be >= 0!
52 #define EXTRA_ALLOC (19 - nLen % 16)
54 // ---------------------------------------------------------------------------
55 // static class variables definition
56 // ---------------------------------------------------------------------------
58 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
59 // must define this static for VA or else you get multiply defined symbols
61 const unsigned int wxSTRING_MAXLEN
= UINT_MAX
- 100;
64 #ifdef wxSTD_STRING_COMPATIBILITY
65 const size_t wxString::npos
= wxSTRING_MAXLEN
;
66 #endif // wxSTD_STRING_COMPATIBILITY
68 // ----------------------------------------------------------------------------
70 // ----------------------------------------------------------------------------
72 // for an empty string, GetStringData() will return this address: this
73 // structure has the same layout as wxStringData and it's data() method will
74 // return the empty string (dummy pointer)
79 } g_strEmpty
= { {-1, 0, 0}, wxT('\0') };
81 // empty C style string: points to 'string data' byte of g_strEmpty
82 extern const wxChar WXDLLEXPORT
*wxEmptyString
= &g_strEmpty
.dummy
;
84 // ----------------------------------------------------------------------------
86 // ----------------------------------------------------------------------------
88 #if defined(wxSTD_STRING_COMPATIBILITY) && wxUSE_STD_IOSTREAM
90 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
93 // ATTN: you can _not_ use both of these in the same program!
95 wxSTD istream
& operator>>(wxSTD istream
& is
, wxString
& WXUNUSED(str
))
100 streambuf
*sb
= is
.rdbuf();
103 int ch
= sb
->sbumpc ();
105 is
.setstate(ios::eofbit
);
108 else if ( isspace(ch
) ) {
120 if ( str
.length() == 0 )
121 is
.setstate(ios::failbit
);
126 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
132 #endif //std::string compatibility
134 // ----------------------------------------------------------------------------
136 // ----------------------------------------------------------------------------
138 // this small class is used to gather statistics for performance tuning
139 //#define WXSTRING_STATISTICS
140 #ifdef WXSTRING_STATISTICS
144 Averager(const wxChar
*sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
146 { wxPrintf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
148 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
151 size_t m_nCount
, m_nTotal
;
153 } g_averageLength("allocation size"),
154 g_averageSummandLength("summand length"),
155 g_averageConcatHit("hit probability in concat"),
156 g_averageInitialLength("initial string length");
158 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
160 #define STATISTICS_ADD(av, val)
161 #endif // WXSTRING_STATISTICS
163 // ===========================================================================
164 // wxStringData class deallocation
165 // ===========================================================================
167 void wxStringData::Free()
172 // ===========================================================================
173 // wxString class core
174 // ===========================================================================
176 // ---------------------------------------------------------------------------
178 // ---------------------------------------------------------------------------
180 // constructs string of <nLength> copies of character <ch>
181 wxString::wxString(wxChar ch
, size_t nLength
)
186 if ( !AllocBuffer(nLength
) ) {
187 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
192 // memset only works on chars
193 for ( size_t n
= 0; n
< nLength
; n
++ )
196 memset(m_pchData
, ch
, nLength
);
201 // takes nLength elements of psz starting at nPos
202 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
206 // if the length is not given, assume the string to be NUL terminated
207 if ( nLength
== wxSTRING_MAXLEN
) {
208 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
210 nLength
= wxStrlen(psz
+ nPos
);
213 STATISTICS_ADD(InitialLength
, nLength
);
216 // trailing '\0' is written in AllocBuffer()
217 if ( !AllocBuffer(nLength
) ) {
218 wxFAIL_MSG( _T("out of memory in wxString::InitWith") );
221 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
225 #ifdef wxSTD_STRING_COMPATIBILITY
227 // poor man's iterators are "void *" pointers
228 wxString::wxString(const void *pStart
, const void *pEnd
)
230 InitWith((const wxChar
*)pStart
, 0,
231 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
234 #endif //std::string compatibility
238 // from multibyte string
239 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
241 // first get the size of the buffer we need
245 // calculate the needed size ourselves or use a provide one
246 nLen
= nLength
== wxSTRING_MAXLEN
? conv
.MB2WC(NULL
, psz
, 0) : nLength
;
250 // nothing to convert
255 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
257 if ( !AllocBuffer(nLen
) )
259 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
263 // MB2WC wants the buffer size, not the string length
264 if ( conv
.MB2WC(m_pchData
, psz
, nLen
+ 1) != (size_t)-1 )
269 //else: the conversion failed -- leave the string empty (what else?)
279 wxString::wxString(const wchar_t *pwz
, wxMBConv
& conv
, size_t nLength
)
281 // first get the size of the buffer we need
285 // calculate the needed size ourselves or use a provide one
286 nLen
= nLength
== wxSTRING_MAXLEN
? conv
.WC2MB(NULL
, pwz
, 0) : nLength
;
290 // nothing to convert
295 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
297 if ( !AllocBuffer(nLen
) )
299 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
303 // WC2MB wants the buffer size, not the string length
304 if ( conv
.WC2MB(m_pchData
, pwz
, nLen
+ 1) != (size_t)-1 )
309 //else: the conversion failed -- leave the string empty (what else?)
314 #endif // wxUSE_WCHAR_T
316 #endif // Unicode/ANSI
318 // ---------------------------------------------------------------------------
320 // ---------------------------------------------------------------------------
322 // allocates memory needed to store a C string of length nLen
323 bool wxString::AllocBuffer(size_t nLen
)
325 // allocating 0 sized buffer doesn't make sense, all empty strings should
327 wxASSERT( nLen
> 0 );
329 // make sure that we don't overflow
330 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
331 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
333 STATISTICS_ADD(Length
, nLen
);
336 // 1) one extra character for '\0' termination
337 // 2) sizeof(wxStringData) for housekeeping info
338 wxStringData
* pData
= (wxStringData
*)
339 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
341 if ( pData
== NULL
) {
342 // allocation failures are handled by the caller
347 pData
->nDataLength
= nLen
;
348 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
349 m_pchData
= pData
->data(); // data starts after wxStringData
350 m_pchData
[nLen
] = wxT('\0');
354 // must be called before changing this string
355 bool wxString::CopyBeforeWrite()
357 wxStringData
* pData
= GetStringData();
359 if ( pData
->IsShared() ) {
360 pData
->Unlock(); // memory not freed because shared
361 size_t nLen
= pData
->nDataLength
;
362 if ( !AllocBuffer(nLen
) ) {
363 // allocation failures are handled by the caller
366 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
369 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
374 // must be called before replacing contents of this string
375 bool wxString::AllocBeforeWrite(size_t nLen
)
377 wxASSERT( nLen
!= 0 ); // doesn't make any sense
379 // must not share string and must have enough space
380 wxStringData
* pData
= GetStringData();
381 if ( pData
->IsShared() || pData
->IsEmpty() ) {
382 // can't work with old buffer, get new one
384 if ( !AllocBuffer(nLen
) ) {
385 // allocation failures are handled by the caller
390 if ( nLen
> pData
->nAllocLength
) {
391 // realloc the buffer instead of calling malloc() again, this is more
393 STATISTICS_ADD(Length
, nLen
);
397 pData
= (wxStringData
*)
398 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
400 if ( pData
== NULL
) {
401 // allocation failures are handled by the caller
402 // keep previous data since reallocation failed
406 pData
->nAllocLength
= nLen
;
407 m_pchData
= pData
->data();
410 // now we have enough space, just update the string length
411 pData
->nDataLength
= nLen
;
414 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
419 // allocate enough memory for nLen characters
420 bool wxString::Alloc(size_t nLen
)
422 wxStringData
*pData
= GetStringData();
423 if ( pData
->nAllocLength
<= nLen
) {
424 if ( pData
->IsEmpty() ) {
427 wxStringData
* pData
= (wxStringData
*)
428 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
430 if ( pData
== NULL
) {
431 // allocation failure handled by caller
436 pData
->nDataLength
= 0;
437 pData
->nAllocLength
= nLen
;
438 m_pchData
= pData
->data(); // data starts after wxStringData
439 m_pchData
[0u] = wxT('\0');
441 else if ( pData
->IsShared() ) {
442 pData
->Unlock(); // memory not freed because shared
443 size_t nOldLen
= pData
->nDataLength
;
444 if ( !AllocBuffer(nLen
) ) {
445 // allocation failure handled by caller
448 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
453 pData
= (wxStringData
*)
454 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
456 if ( pData
== NULL
) {
457 // allocation failure handled by caller
458 // keep previous data since reallocation failed
462 // it's not important if the pointer changed or not (the check for this
463 // is not faster than assigning to m_pchData in all cases)
464 pData
->nAllocLength
= nLen
;
465 m_pchData
= pData
->data();
468 //else: we've already got enough
472 // shrink to minimal size (releasing extra memory)
473 bool wxString::Shrink()
475 wxStringData
*pData
= GetStringData();
477 size_t nLen
= pData
->nDataLength
;
478 void *p
= realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
481 wxFAIL_MSG( _T("out of memory reallocating wxString data") );
482 // keep previous data since reallocation failed
488 // contrary to what one might believe, some realloc() implementation do
489 // move the memory block even when its size is reduced
490 pData
= (wxStringData
*)p
;
492 m_pchData
= pData
->data();
495 pData
->nAllocLength
= nLen
;
500 // get the pointer to writable buffer of (at least) nLen bytes
501 wxChar
*wxString::GetWriteBuf(size_t nLen
)
503 if ( !AllocBeforeWrite(nLen
) ) {
504 // allocation failure handled by caller
508 wxASSERT( GetStringData()->nRefs
== 1 );
509 GetStringData()->Validate(FALSE
);
514 // put string back in a reasonable state after GetWriteBuf
515 void wxString::UngetWriteBuf()
517 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
518 GetStringData()->Validate(TRUE
);
521 void wxString::UngetWriteBuf(size_t nLen
)
523 GetStringData()->nDataLength
= nLen
;
524 GetStringData()->Validate(TRUE
);
527 // ---------------------------------------------------------------------------
529 // ---------------------------------------------------------------------------
531 // all functions are inline in string.h
533 // ---------------------------------------------------------------------------
534 // assignment operators
535 // ---------------------------------------------------------------------------
537 // helper function: does real copy
538 bool wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
540 if ( nSrcLen
== 0 ) {
544 if ( !AllocBeforeWrite(nSrcLen
) ) {
545 // allocation failure handled by caller
548 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
549 GetStringData()->nDataLength
= nSrcLen
;
550 m_pchData
[nSrcLen
] = wxT('\0');
555 // assigns one string to another
556 wxString
& wxString::operator=(const wxString
& stringSrc
)
558 wxASSERT( stringSrc
.GetStringData()->IsValid() );
560 // don't copy string over itself
561 if ( m_pchData
!= stringSrc
.m_pchData
) {
562 if ( stringSrc
.GetStringData()->IsEmpty() ) {
567 GetStringData()->Unlock();
568 m_pchData
= stringSrc
.m_pchData
;
569 GetStringData()->Lock();
576 // assigns a single character
577 wxString
& wxString::operator=(wxChar ch
)
579 if ( !AssignCopy(1, &ch
) ) {
580 wxFAIL_MSG( _T("out of memory in wxString::operator=(wxChar)") );
587 wxString
& wxString::operator=(const wxChar
*psz
)
589 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
590 wxFAIL_MSG( _T("out of memory in wxString::operator=(const wxChar *)") );
597 // same as 'signed char' variant
598 wxString
& wxString::operator=(const unsigned char* psz
)
600 *this = (const char *)psz
;
605 wxString
& wxString::operator=(const wchar_t *pwz
)
615 // ---------------------------------------------------------------------------
616 // string concatenation
617 // ---------------------------------------------------------------------------
619 // add something to this string
620 bool wxString::ConcatSelf(size_t nSrcLen
, const wxChar
*pszSrcData
)
622 STATISTICS_ADD(SummandLength
, nSrcLen
);
624 // concatenating an empty string is a NOP
626 wxStringData
*pData
= GetStringData();
627 size_t nLen
= pData
->nDataLength
;
628 size_t nNewLen
= nLen
+ nSrcLen
;
630 // alloc new buffer if current is too small
631 if ( pData
->IsShared() ) {
632 STATISTICS_ADD(ConcatHit
, 0);
634 // we have to allocate another buffer
635 wxStringData
* pOldData
= GetStringData();
636 if ( !AllocBuffer(nNewLen
) ) {
637 // allocation failure handled by caller
640 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
643 else if ( nNewLen
> pData
->nAllocLength
) {
644 STATISTICS_ADD(ConcatHit
, 0);
646 // we have to grow the buffer
647 if ( !Alloc(nNewLen
) ) {
648 // allocation failure handled by caller
653 STATISTICS_ADD(ConcatHit
, 1);
655 // the buffer is already big enough
658 // should be enough space
659 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
661 // fast concatenation - all is done in our buffer
662 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
664 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
665 GetStringData()->nDataLength
= nNewLen
; // and fix the length
667 //else: the string to append was empty
672 * concatenation functions come in 5 flavours:
674 * char + string and string + char
675 * C str + string and string + C str
678 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
680 wxASSERT( str1
.GetStringData()->IsValid() );
681 wxASSERT( str2
.GetStringData()->IsValid() );
689 wxString
operator+(const wxString
& str
, wxChar ch
)
691 wxASSERT( str
.GetStringData()->IsValid() );
699 wxString
operator+(wxChar ch
, const wxString
& str
)
701 wxASSERT( str
.GetStringData()->IsValid() );
709 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
711 wxASSERT( str
.GetStringData()->IsValid() );
714 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
715 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
723 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
725 wxASSERT( str
.GetStringData()->IsValid() );
728 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
729 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
737 // ===========================================================================
738 // other common string functions
739 // ===========================================================================
743 wxString
wxString::FromAscii(const char *ascii
)
746 return wxEmptyString
;
748 size_t len
= strlen( ascii
);
753 wxStringBuffer
buf(res
, len
);
759 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
767 wxString
wxString::FromAscii(const char ascii
)
769 // What do we do with '\0' ?
772 res
+= (wchar_t)(unsigned char) ascii
;
777 const wxCharBuffer
wxString::ToAscii() const
779 // this will allocate enough space for the terminating NUL too
780 wxCharBuffer
buffer(length());
782 signed char *dest
= (signed char *)buffer
.data();
784 const wchar_t *pwc
= c_str();
787 *dest
++ = *pwc
> SCHAR_MAX
? '_' : *pwc
;
789 // the output string can't have embedded NULs anyhow, so we can safely
790 // stop at first of them even if we do have any
800 // ---------------------------------------------------------------------------
801 // simple sub-string extraction
802 // ---------------------------------------------------------------------------
804 // helper function: clone the data attached to this string
805 bool wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
807 if ( nCopyLen
== 0 ) {
811 if ( !dest
.AllocBuffer(nCopyLen
) ) {
812 // allocation failure handled by caller
815 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
820 // extract string of length nCount starting at nFirst
821 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
823 wxStringData
*pData
= GetStringData();
824 size_t nLen
= pData
->nDataLength
;
826 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
827 if ( nCount
== wxSTRING_MAXLEN
)
829 nCount
= nLen
- nFirst
;
832 // out-of-bounds requests return sensible things
833 if ( nFirst
+ nCount
> nLen
)
835 nCount
= nLen
- nFirst
;
840 // AllocCopy() will return empty string
845 if ( !AllocCopy(dest
, nCount
, nFirst
) ) {
846 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
852 // check that the tring starts with prefix and return the rest of the string
853 // in the provided pointer if it is not NULL, otherwise return FALSE
854 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
856 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
858 // first check if the beginning of the string matches the prefix: note
859 // that we don't have to check that we don't run out of this string as
860 // when we reach the terminating NUL, either prefix string ends too (and
861 // then it's ok) or we break out of the loop because there is no match
862 const wxChar
*p
= c_str();
865 if ( *prefix
++ != *p
++ )
874 // put the rest of the string into provided pointer
881 // extract nCount last (rightmost) characters
882 wxString
wxString::Right(size_t nCount
) const
884 if ( nCount
> (size_t)GetStringData()->nDataLength
)
885 nCount
= GetStringData()->nDataLength
;
888 if ( !AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
) ) {
889 wxFAIL_MSG( _T("out of memory in wxString::Right") );
894 // get all characters after the last occurence of ch
895 // (returns the whole string if ch not found)
896 wxString
wxString::AfterLast(wxChar ch
) const
899 int iPos
= Find(ch
, TRUE
);
900 if ( iPos
== wxNOT_FOUND
)
903 str
= c_str() + iPos
+ 1;
908 // extract nCount first (leftmost) characters
909 wxString
wxString::Left(size_t nCount
) const
911 if ( nCount
> (size_t)GetStringData()->nDataLength
)
912 nCount
= GetStringData()->nDataLength
;
915 if ( !AllocCopy(dest
, nCount
, 0) ) {
916 wxFAIL_MSG( _T("out of memory in wxString::Left") );
921 // get all characters before the first occurence of ch
922 // (returns the whole string if ch not found)
923 wxString
wxString::BeforeFirst(wxChar ch
) const
926 for ( const wxChar
*pc
= m_pchData
; *pc
!= wxT('\0') && *pc
!= ch
; pc
++ )
932 /// get all characters before the last occurence of ch
933 /// (returns empty string if ch not found)
934 wxString
wxString::BeforeLast(wxChar ch
) const
937 int iPos
= Find(ch
, TRUE
);
938 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
939 str
= wxString(c_str(), iPos
);
944 /// get all characters after the first occurence of ch
945 /// (returns empty string if ch not found)
946 wxString
wxString::AfterFirst(wxChar ch
) const
950 if ( iPos
!= wxNOT_FOUND
)
951 str
= c_str() + iPos
+ 1;
956 // replace first (or all) occurences of some substring with another one
957 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
959 size_t uiCount
= 0; // count of replacements made
961 size_t uiOldLen
= wxStrlen(szOld
);
964 const wxChar
*pCurrent
= m_pchData
;
965 const wxChar
*pSubstr
;
966 while ( *pCurrent
!= wxT('\0') ) {
967 pSubstr
= wxStrstr(pCurrent
, szOld
);
968 if ( pSubstr
== NULL
) {
969 // strTemp is unused if no replacements were made, so avoid the copy
973 strTemp
+= pCurrent
; // copy the rest
974 break; // exit the loop
977 // take chars before match
978 if ( !strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
) ) {
979 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
983 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
988 if ( !bReplaceAll
) {
989 strTemp
+= pCurrent
; // copy the rest
990 break; // exit the loop
995 // only done if there were replacements, otherwise would have returned above
1001 bool wxString::IsAscii() const
1003 const wxChar
*s
= (const wxChar
*) *this;
1005 if(!isascii(*s
)) return(FALSE
);
1011 bool wxString::IsWord() const
1013 const wxChar
*s
= (const wxChar
*) *this;
1015 if(!wxIsalpha(*s
)) return(FALSE
);
1021 bool wxString::IsNumber() const
1023 const wxChar
*s
= (const wxChar
*) *this;
1025 if ((s
[0] == '-') || (s
[0] == '+')) s
++;
1027 if(!wxIsdigit(*s
)) return(FALSE
);
1033 wxString
wxString::Strip(stripType w
) const
1036 if ( w
& leading
) s
.Trim(FALSE
);
1037 if ( w
& trailing
) s
.Trim(TRUE
);
1041 // ---------------------------------------------------------------------------
1043 // ---------------------------------------------------------------------------
1045 wxString
& wxString::MakeUpper()
1047 if ( !CopyBeforeWrite() ) {
1048 wxFAIL_MSG( _T("out of memory in wxString::MakeUpper") );
1052 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1053 *p
= (wxChar
)wxToupper(*p
);
1058 wxString
& wxString::MakeLower()
1060 if ( !CopyBeforeWrite() ) {
1061 wxFAIL_MSG( _T("out of memory in wxString::MakeLower") );
1065 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1066 *p
= (wxChar
)wxTolower(*p
);
1071 // ---------------------------------------------------------------------------
1072 // trimming and padding
1073 // ---------------------------------------------------------------------------
1075 // some compilers (VC++ 6.0 not to name them) return TRUE for a call to
1076 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1077 // live with this by checking that the character is a 7 bit one - even if this
1078 // may fail to detect some spaces (I don't know if Unicode doesn't have
1079 // space-like symbols somewhere except in the first 128 chars), it is arguably
1080 // still better than trimming away accented letters
1081 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1083 // trims spaces (in the sense of isspace) from left or right side
1084 wxString
& wxString::Trim(bool bFromRight
)
1086 // first check if we're going to modify the string at all
1089 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1090 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1094 // ok, there is at least one space to trim
1095 if ( !CopyBeforeWrite() ) {
1096 wxFAIL_MSG( _T("out of memory in wxString::Trim") );
1102 // find last non-space character
1103 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
1104 while ( wxSafeIsspace(*psz
) && (psz
>= m_pchData
) )
1107 // truncate at trailing space start
1109 GetStringData()->nDataLength
= psz
- m_pchData
;
1113 // find first non-space character
1114 const wxChar
*psz
= m_pchData
;
1115 while ( wxSafeIsspace(*psz
) )
1118 // fix up data and length
1119 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
1120 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
1121 GetStringData()->nDataLength
= nDataLength
;
1128 // adds nCount characters chPad to the string from either side
1129 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1131 wxString
s(chPad
, nCount
);
1144 // truncate the string
1145 wxString
& wxString::Truncate(size_t uiLen
)
1147 if ( uiLen
< Len() ) {
1148 if ( !CopyBeforeWrite() ) {
1149 wxFAIL_MSG( _T("out of memory in wxString::Truncate") );
1153 *(m_pchData
+ uiLen
) = wxT('\0');
1154 GetStringData()->nDataLength
= uiLen
;
1156 //else: nothing to do, string is already short enough
1161 // ---------------------------------------------------------------------------
1162 // finding (return wxNOT_FOUND if not found and index otherwise)
1163 // ---------------------------------------------------------------------------
1166 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1168 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
1170 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1173 // find a sub-string (like strstr)
1174 int wxString::Find(const wxChar
*pszSub
) const
1176 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
1178 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1181 // ----------------------------------------------------------------------------
1182 // conversion to numbers
1183 // ----------------------------------------------------------------------------
1185 bool wxString::ToLong(long *val
, int base
) const
1187 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToLong") );
1188 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1190 const wxChar
*start
= c_str();
1192 *val
= wxStrtol(start
, &end
, base
);
1194 // return TRUE only if scan was stopped by the terminating NUL and if the
1195 // string was not empty to start with
1196 return !*end
&& (end
!= start
);
1199 bool wxString::ToULong(unsigned long *val
, int base
) const
1201 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToULong") );
1202 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1204 const wxChar
*start
= c_str();
1206 *val
= wxStrtoul(start
, &end
, base
);
1208 // return TRUE only if scan was stopped by the terminating NUL and if the
1209 // string was not empty to start with
1210 return !*end
&& (end
!= start
);
1213 bool wxString::ToDouble(double *val
) const
1215 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToDouble") );
1217 const wxChar
*start
= c_str();
1219 *val
= wxStrtod(start
, &end
);
1221 // return TRUE only if scan was stopped by the terminating NUL and if the
1222 // string was not empty to start with
1223 return !*end
&& (end
!= start
);
1226 // ---------------------------------------------------------------------------
1228 // ---------------------------------------------------------------------------
1231 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1234 va_start(argptr
, pszFormat
);
1237 s
.PrintfV(pszFormat
, argptr
);
1245 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1248 s
.PrintfV(pszFormat
, argptr
);
1252 int wxString::Printf(const wxChar
*pszFormat
, ...)
1255 va_start(argptr
, pszFormat
);
1257 int iLen
= PrintfV(pszFormat
, argptr
);
1264 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1269 wxChar
*buf
= GetWriteBuf(size
+ 1);
1276 int len
= wxVsnprintf(buf
, size
, pszFormat
, argptr
);
1278 // some implementations of vsnprintf() don't NUL terminate the string
1279 // if there is not enough space for it so always do it manually
1280 buf
[size
] = _T('\0');
1286 // ok, there was enough space
1290 // still not enough, double it again
1294 // we could have overshot
1300 // ----------------------------------------------------------------------------
1301 // misc other operations
1302 // ----------------------------------------------------------------------------
1304 // returns TRUE if the string matches the pattern which may contain '*' and
1305 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1307 bool wxString::Matches(const wxChar
*pszMask
) const
1309 // I disable this code as it doesn't seem to be faster (in fact, it seems
1310 // to be much slower) than the old, hand-written code below and using it
1311 // here requires always linking with libregex even if the user code doesn't
1313 #if 0 // wxUSE_REGEX
1314 // first translate the shell-like mask into a regex
1316 pattern
.reserve(wxStrlen(pszMask
));
1328 pattern
+= _T(".*");
1339 // these characters are special in a RE, quote them
1340 // (however note that we don't quote '[' and ']' to allow
1341 // using them for Unix shell like matching)
1342 pattern
+= _T('\\');
1346 pattern
+= *pszMask
;
1354 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1355 #else // !wxUSE_REGEX
1356 // TODO: this is, of course, awfully inefficient...
1358 // the char currently being checked
1359 const wxChar
*pszTxt
= c_str();
1361 // the last location where '*' matched
1362 const wxChar
*pszLastStarInText
= NULL
;
1363 const wxChar
*pszLastStarInMask
= NULL
;
1366 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1367 switch ( *pszMask
) {
1369 if ( *pszTxt
== wxT('\0') )
1372 // pszTxt and pszMask will be incremented in the loop statement
1378 // remember where we started to be able to backtrack later
1379 pszLastStarInText
= pszTxt
;
1380 pszLastStarInMask
= pszMask
;
1382 // ignore special chars immediately following this one
1383 // (should this be an error?)
1384 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1387 // if there is nothing more, match
1388 if ( *pszMask
== wxT('\0') )
1391 // are there any other metacharacters in the mask?
1393 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1395 if ( pEndMask
!= NULL
) {
1396 // we have to match the string between two metachars
1397 uiLenMask
= pEndMask
- pszMask
;
1400 // we have to match the remainder of the string
1401 uiLenMask
= wxStrlen(pszMask
);
1404 wxString
strToMatch(pszMask
, uiLenMask
);
1405 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1406 if ( pMatch
== NULL
)
1409 // -1 to compensate "++" in the loop
1410 pszTxt
= pMatch
+ uiLenMask
- 1;
1411 pszMask
+= uiLenMask
- 1;
1416 if ( *pszMask
!= *pszTxt
)
1422 // match only if nothing left
1423 if ( *pszTxt
== wxT('\0') )
1426 // if we failed to match, backtrack if we can
1427 if ( pszLastStarInText
) {
1428 pszTxt
= pszLastStarInText
+ 1;
1429 pszMask
= pszLastStarInMask
;
1431 pszLastStarInText
= NULL
;
1433 // don't bother resetting pszLastStarInMask, it's unnecessary
1439 #endif // wxUSE_REGEX/!wxUSE_REGEX
1442 // Count the number of chars
1443 int wxString::Freq(wxChar ch
) const
1447 for (int i
= 0; i
< len
; i
++)
1449 if (GetChar(i
) == ch
)
1455 // convert to upper case, return the copy of the string
1456 wxString
wxString::Upper() const
1457 { wxString
s(*this); return s
.MakeUpper(); }
1459 // convert to lower case, return the copy of the string
1460 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1462 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1465 va_start(argptr
, pszFormat
);
1466 int iLen
= PrintfV(pszFormat
, argptr
);
1471 // ---------------------------------------------------------------------------
1472 // standard C++ library string functions
1473 // ---------------------------------------------------------------------------
1475 #ifdef wxSTD_STRING_COMPATIBILITY
1477 void wxString::resize(size_t nSize
, wxChar ch
)
1479 size_t len
= length();
1485 else if ( nSize
> len
)
1487 *this += wxString(ch
, nSize
- len
);
1489 //else: we have exactly the specified length, nothing to do
1492 void wxString::swap(wxString
& str
)
1494 // this is slightly less efficient than fiddling with m_pchData directly,
1495 // but it is still quite efficient as we don't copy the string here because
1496 // ref count always stays positive
1502 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1504 wxASSERT( str
.GetStringData()->IsValid() );
1505 wxASSERT( nPos
<= Len() );
1507 if ( !str
.IsEmpty() ) {
1509 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1510 wxStrncpy(pc
, c_str(), nPos
);
1511 wxStrcpy(pc
+ nPos
, str
);
1512 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1513 strTmp
.UngetWriteBuf();
1520 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1522 wxASSERT( str
.GetStringData()->IsValid() );
1523 wxASSERT( nStart
<= Len() );
1525 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1527 return p
== NULL
? npos
: p
- c_str();
1530 // VC++ 1.5 can't cope with the default argument in the header.
1531 #if !defined(__VISUALC__) || defined(__WIN32__)
1532 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1534 return find(wxString(sz
, n
), nStart
);
1538 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1539 #if !defined(__BORLANDC__)
1540 size_t wxString::find(wxChar ch
, size_t nStart
) const
1542 wxASSERT( nStart
<= Len() );
1544 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1546 return p
== NULL
? npos
: p
- c_str();
1550 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1552 wxASSERT( str
.GetStringData()->IsValid() );
1553 wxASSERT( nStart
== npos
|| nStart
<= Len() );
1555 // TODO could be made much quicker than that
1556 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1557 while ( p
>= c_str() + str
.Len() ) {
1558 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1559 return p
- str
.Len() - c_str();
1566 // VC++ 1.5 can't cope with the default argument in the header.
1567 #if !defined(__VISUALC__) || defined(__WIN32__)
1568 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1570 return rfind(wxString(sz
, n
== npos
? wxSTRING_MAXLEN
: n
), nStart
);
1573 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1575 if ( nStart
== npos
)
1581 wxASSERT( nStart
<= Len() );
1584 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1589 size_t result
= p
- c_str();
1590 return ( result
> nStart
) ? npos
: result
;
1594 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1596 const wxChar
*start
= c_str() + nStart
;
1597 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1599 return firstOf
- c_str();
1604 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1606 if ( nStart
== npos
)
1612 wxASSERT( nStart
<= Len() );
1615 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1617 if ( wxStrchr(sz
, *p
) )
1624 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1626 if ( nStart
== npos
)
1632 wxASSERT( nStart
<= Len() );
1635 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1636 if ( nAccept
>= length() - nStart
)
1642 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1644 wxASSERT( nStart
<= Len() );
1646 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1655 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1657 if ( nStart
== npos
)
1663 wxASSERT( nStart
<= Len() );
1666 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1668 if ( !wxStrchr(sz
, *p
) )
1675 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1677 if ( nStart
== npos
)
1683 wxASSERT( nStart
<= Len() );
1686 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1695 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1697 wxString
strTmp(c_str(), nStart
);
1698 if ( nLen
!= npos
) {
1699 wxASSERT( nStart
+ nLen
<= Len() );
1701 strTmp
.append(c_str() + nStart
+ nLen
);
1708 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1710 wxASSERT_MSG( nStart
+ nLen
<= Len(),
1711 _T("index out of bounds in wxString::replace") );
1714 strTmp
.Alloc(Len()); // micro optimisation to avoid multiple mem allocs
1717 strTmp
.append(c_str(), nStart
);
1718 strTmp
<< sz
<< c_str() + nStart
+ nLen
;
1724 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1726 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1729 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1730 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1732 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1735 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1736 const wxChar
* sz
, size_t nCount
)
1738 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1741 #endif //std::string compatibility
1743 // ============================================================================
1745 // ============================================================================
1747 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1748 #define ARRAY_MAXSIZE_INCREMENT 4096
1750 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1751 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1754 #define STRING(p) ((wxString *)(&(p)))
1757 void wxArrayString::Init(bool autoSort
)
1761 m_pItems
= (wxChar
**) NULL
;
1762 m_autoSort
= autoSort
;
1766 wxArrayString::wxArrayString(const wxArrayString
& src
)
1768 Init(src
.m_autoSort
);
1773 // assignment operator
1774 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1781 m_autoSort
= src
.m_autoSort
;
1786 void wxArrayString::Copy(const wxArrayString
& src
)
1788 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1789 Alloc(src
.m_nCount
);
1791 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1796 void wxArrayString::Grow(size_t nIncrement
)
1798 // only do it if no more place
1799 if ( (m_nSize
- m_nCount
) < nIncrement
) {
1800 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
1801 // be never resized!
1802 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
1803 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
1806 if ( m_nSize
== 0 ) {
1807 // was empty, alloc some memory
1808 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1809 if (m_nSize
< nIncrement
)
1810 m_nSize
= nIncrement
;
1811 m_pItems
= new wxChar
*[m_nSize
];
1814 // otherwise when it's called for the first time, nIncrement would be 0
1815 // and the array would never be expanded
1816 // add 50% but not too much
1817 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1818 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1819 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1820 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1821 if ( nIncrement
< ndefIncrement
)
1822 nIncrement
= ndefIncrement
;
1823 m_nSize
+= nIncrement
;
1824 wxChar
**pNew
= new wxChar
*[m_nSize
];
1826 // copy data to new location
1827 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1829 // delete old memory (but do not release the strings!)
1830 wxDELETEA(m_pItems
);
1837 void wxArrayString::Free()
1839 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1840 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1844 // deletes all the strings from the list
1845 void wxArrayString::Empty()
1852 // as Empty, but also frees memory
1853 void wxArrayString::Clear()
1860 wxDELETEA(m_pItems
);
1864 wxArrayString::~wxArrayString()
1868 wxDELETEA(m_pItems
);
1871 // pre-allocates memory (frees the previous data!)
1872 void wxArrayString::Alloc(size_t nSize
)
1874 // only if old buffer was not big enough
1875 if ( nSize
> m_nSize
) {
1877 wxDELETEA(m_pItems
);
1878 m_pItems
= new wxChar
*[nSize
];
1885 // minimizes the memory usage by freeing unused memory
1886 void wxArrayString::Shrink()
1888 // only do it if we have some memory to free
1889 if( m_nCount
< m_nSize
) {
1890 // allocates exactly as much memory as we need
1891 wxChar
**pNew
= new wxChar
*[m_nCount
];
1893 // copy data to new location
1894 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1900 // return a wxString[] as required for some control ctors.
1901 wxString
* wxArrayString::GetStringArray() const
1903 wxString
*array
= 0;
1907 array
= new wxString
[m_nCount
];
1908 for( size_t i
= 0; i
< m_nCount
; i
++ )
1909 array
[i
] = m_pItems
[i
];
1915 // searches the array for an item (forward or backwards)
1916 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
1919 // use binary search in the sorted array
1920 wxASSERT_MSG( bCase
&& !bFromEnd
,
1921 wxT("search parameters ignored for auto sorted array") );
1930 res
= wxStrcmp(sz
, m_pItems
[i
]);
1942 // use linear search in unsorted array
1944 if ( m_nCount
> 0 ) {
1945 size_t ui
= m_nCount
;
1947 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1954 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1955 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1964 // add item at the end
1965 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
1968 // insert the string at the correct position to keep the array sorted
1976 res
= wxStrcmp(str
, m_pItems
[i
]);
1987 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
1989 Insert(str
, lo
, nInsert
);
1994 wxASSERT( str
.GetStringData()->IsValid() );
1998 for (size_t i
= 0; i
< nInsert
; i
++)
2000 // the string data must not be deleted!
2001 str
.GetStringData()->Lock();
2004 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2006 size_t ret
= m_nCount
;
2007 m_nCount
+= nInsert
;
2012 // add item at the given position
2013 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2015 wxASSERT( str
.GetStringData()->IsValid() );
2017 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2018 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2019 wxT("array size overflow in wxArrayString::Insert") );
2023 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2024 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2026 for (size_t i
= 0; i
< nInsert
; i
++)
2028 str
.GetStringData()->Lock();
2029 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2031 m_nCount
+= nInsert
;
2035 void wxArrayString::SetCount(size_t count
)
2040 while ( m_nCount
< count
)
2041 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2044 // removes item from array (by index)
2045 void wxArrayString::Remove(size_t nIndex
, size_t nRemove
)
2047 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2048 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2049 wxT("removing too many elements in wxArrayString::Remove") );
2052 for (size_t i
= 0; i
< nRemove
; i
++)
2053 Item(nIndex
+ i
).GetStringData()->Unlock();
2055 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2056 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2057 m_nCount
-= nRemove
;
2060 // removes item from array (by value)
2061 void wxArrayString::Remove(const wxChar
*sz
)
2063 int iIndex
= Index(sz
);
2065 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2066 wxT("removing inexistent element in wxArrayString::Remove") );
2071 // ----------------------------------------------------------------------------
2073 // ----------------------------------------------------------------------------
2075 // we can only sort one array at a time with the quick-sort based
2078 // need a critical section to protect access to gs_compareFunction and
2079 // gs_sortAscending variables
2080 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2082 // call this before the value of the global sort vars is changed/after
2083 // you're finished with them
2084 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2085 gs_critsectStringSort = new wxCriticalSection; \
2086 gs_critsectStringSort->Enter()
2087 #define END_SORT() gs_critsectStringSort->Leave(); \
2088 delete gs_critsectStringSort; \
2089 gs_critsectStringSort = NULL
2091 #define START_SORT()
2093 #endif // wxUSE_THREADS
2095 // function to use for string comparaison
2096 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2098 // if we don't use the compare function, this flag tells us if we sort the
2099 // array in ascending or descending order
2100 static bool gs_sortAscending
= TRUE
;
2102 // function which is called by quick sort
2103 extern "C" int wxC_CALLING_CONV
// LINKAGEMODE
2104 wxStringCompareFunction(const void *first
, const void *second
)
2106 wxString
*strFirst
= (wxString
*)first
;
2107 wxString
*strSecond
= (wxString
*)second
;
2109 if ( gs_compareFunction
) {
2110 return gs_compareFunction(*strFirst
, *strSecond
);
2113 // maybe we should use wxStrcoll
2114 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
2116 return gs_sortAscending
? result
: -result
;
2120 // sort array elements using passed comparaison function
2121 void wxArrayString::Sort(CompareFunction compareFunction
)
2125 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2126 gs_compareFunction
= compareFunction
;
2130 // reset it to NULL so that Sort(bool) will work the next time
2131 gs_compareFunction
= NULL
;
2136 void wxArrayString::Sort(bool reverseOrder
)
2140 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2141 gs_sortAscending
= !reverseOrder
;
2148 void wxArrayString::DoSort()
2150 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2152 // just sort the pointers using qsort() - of course it only works because
2153 // wxString() *is* a pointer to its data
2154 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2157 bool wxArrayString::operator==(const wxArrayString
& a
) const
2159 if ( m_nCount
!= a
.m_nCount
)
2162 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2164 if ( Item(n
) != a
[n
] )