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 WXDLLIMPEXP_BASE
*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 #if defined(__VISUALC__) && defined(_MT) && !defined(_DLL)
168 # pragma message (__FILE__ ": building with Multithreaded non DLL runtime has a performance impact on wxString!")
169 void wxStringData::Free()
175 // ===========================================================================
176 // wxString class core
177 // ===========================================================================
179 // ---------------------------------------------------------------------------
181 // ---------------------------------------------------------------------------
183 // constructs string of <nLength> copies of character <ch>
184 wxString::wxString(wxChar ch
, size_t nLength
)
189 if ( !AllocBuffer(nLength
) ) {
190 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
195 // memset only works on chars
196 for ( size_t n
= 0; n
< nLength
; n
++ )
199 memset(m_pchData
, ch
, nLength
);
204 // takes nLength elements of psz starting at nPos
205 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
209 // if the length is not given, assume the string to be NUL terminated
210 if ( nLength
== wxSTRING_MAXLEN
) {
211 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
213 nLength
= wxStrlen(psz
+ nPos
);
216 STATISTICS_ADD(InitialLength
, nLength
);
219 // trailing '\0' is written in AllocBuffer()
220 if ( !AllocBuffer(nLength
) ) {
221 wxFAIL_MSG( _T("out of memory in wxString::InitWith") );
224 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
228 #ifdef wxSTD_STRING_COMPATIBILITY
230 // poor man's iterators are "void *" pointers
231 wxString::wxString(const void *pStart
, const void *pEnd
)
233 InitWith((const wxChar
*)pStart
, 0,
234 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
237 #endif //std::string compatibility
241 // from multibyte string
242 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
244 // first get the size of the buffer we need
248 // calculate the needed size ourselves or use the provided one
249 nLen
= nLength
== wxSTRING_MAXLEN
? conv
.MB2WC(NULL
, psz
, 0) : nLength
;
253 // nothing to convert
258 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
260 if ( !AllocBuffer(nLen
) )
262 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
266 // MB2WC wants the buffer size, not the string length hence +1
267 nLen
= conv
.MB2WC(m_pchData
, psz
, nLen
+ 1);
269 if ( nLen
!= (size_t)-1 )
271 // initialized ok, set the real length as nLength specified by
272 // the caller could be greater than the real string length
273 GetStringData()->nDataLength
= nLen
;
277 //else: the conversion failed -- leave the string empty (what else?)
288 wxString::wxString(const wchar_t *pwz
, wxMBConv
& conv
, size_t nLength
)
290 // first get the size of the buffer we need
294 // calculate the needed size ourselves or use the provided one
295 nLen
= nLength
== wxSTRING_MAXLEN
? conv
.WC2MB(NULL
, pwz
, 0) : nLength
;
299 // nothing to convert
304 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
306 if ( !AllocBuffer(nLen
) )
308 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
312 // WC2MB wants the buffer size, not the string length
313 if ( conv
.WC2MB(m_pchData
, pwz
, nLen
+ 1) != (size_t)-1 )
318 //else: the conversion failed -- leave the string empty (what else?)
324 #endif // wxUSE_WCHAR_T
326 #endif // Unicode/ANSI
328 // ---------------------------------------------------------------------------
330 // ---------------------------------------------------------------------------
332 // allocates memory needed to store a C string of length nLen
333 bool wxString::AllocBuffer(size_t nLen
)
335 // allocating 0 sized buffer doesn't make sense, all empty strings should
337 wxASSERT( nLen
> 0 );
339 // make sure that we don't overflow
340 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
341 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
343 STATISTICS_ADD(Length
, nLen
);
346 // 1) one extra character for '\0' termination
347 // 2) sizeof(wxStringData) for housekeeping info
348 wxStringData
* pData
= (wxStringData
*)
349 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
351 if ( pData
== NULL
) {
352 // allocation failures are handled by the caller
357 pData
->nDataLength
= nLen
;
358 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
359 m_pchData
= pData
->data(); // data starts after wxStringData
360 m_pchData
[nLen
] = wxT('\0');
364 // must be called before changing this string
365 bool wxString::CopyBeforeWrite()
367 wxStringData
* pData
= GetStringData();
369 if ( pData
->IsShared() ) {
370 pData
->Unlock(); // memory not freed because shared
371 size_t nLen
= pData
->nDataLength
;
372 if ( !AllocBuffer(nLen
) ) {
373 // allocation failures are handled by the caller
376 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
379 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
384 // must be called before replacing contents of this string
385 bool wxString::AllocBeforeWrite(size_t nLen
)
387 wxASSERT( nLen
!= 0 ); // doesn't make any sense
389 // must not share string and must have enough space
390 wxStringData
* pData
= GetStringData();
391 if ( pData
->IsShared() || pData
->IsEmpty() ) {
392 // can't work with old buffer, get new one
394 if ( !AllocBuffer(nLen
) ) {
395 // allocation failures are handled by the caller
400 if ( nLen
> pData
->nAllocLength
) {
401 // realloc the buffer instead of calling malloc() again, this is more
403 STATISTICS_ADD(Length
, nLen
);
407 pData
= (wxStringData
*)
408 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
410 if ( pData
== NULL
) {
411 // allocation failures are handled by the caller
412 // keep previous data since reallocation failed
416 pData
->nAllocLength
= nLen
;
417 m_pchData
= pData
->data();
420 // now we have enough space, just update the string length
421 pData
->nDataLength
= nLen
;
424 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
429 // allocate enough memory for nLen characters
430 bool wxString::Alloc(size_t nLen
)
432 wxStringData
*pData
= GetStringData();
433 if ( pData
->nAllocLength
<= nLen
) {
434 if ( pData
->IsEmpty() ) {
437 wxStringData
* pData
= (wxStringData
*)
438 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
440 if ( pData
== NULL
) {
441 // allocation failure handled by caller
446 pData
->nDataLength
= 0;
447 pData
->nAllocLength
= nLen
;
448 m_pchData
= pData
->data(); // data starts after wxStringData
449 m_pchData
[0u] = wxT('\0');
451 else if ( pData
->IsShared() ) {
452 pData
->Unlock(); // memory not freed because shared
453 size_t nOldLen
= pData
->nDataLength
;
454 if ( !AllocBuffer(nLen
) ) {
455 // allocation failure handled by caller
458 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
463 pData
= (wxStringData
*)
464 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
466 if ( pData
== NULL
) {
467 // allocation failure handled by caller
468 // keep previous data since reallocation failed
472 // it's not important if the pointer changed or not (the check for this
473 // is not faster than assigning to m_pchData in all cases)
474 pData
->nAllocLength
= nLen
;
475 m_pchData
= pData
->data();
478 //else: we've already got enough
482 // shrink to minimal size (releasing extra memory)
483 bool wxString::Shrink()
485 wxStringData
*pData
= GetStringData();
487 size_t nLen
= pData
->nDataLength
;
488 void *p
= realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
491 wxFAIL_MSG( _T("out of memory reallocating wxString data") );
492 // keep previous data since reallocation failed
498 // contrary to what one might believe, some realloc() implementation do
499 // move the memory block even when its size is reduced
500 pData
= (wxStringData
*)p
;
502 m_pchData
= pData
->data();
505 pData
->nAllocLength
= nLen
;
510 // get the pointer to writable buffer of (at least) nLen bytes
511 wxChar
*wxString::GetWriteBuf(size_t nLen
)
513 if ( !AllocBeforeWrite(nLen
) ) {
514 // allocation failure handled by caller
518 wxASSERT( GetStringData()->nRefs
== 1 );
519 GetStringData()->Validate(FALSE
);
524 // put string back in a reasonable state after GetWriteBuf
525 void wxString::UngetWriteBuf()
527 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
528 GetStringData()->Validate(TRUE
);
531 void wxString::UngetWriteBuf(size_t nLen
)
533 GetStringData()->nDataLength
= nLen
;
534 GetStringData()->Validate(TRUE
);
537 // ---------------------------------------------------------------------------
539 // ---------------------------------------------------------------------------
541 // all functions are inline in string.h
543 // ---------------------------------------------------------------------------
544 // assignment operators
545 // ---------------------------------------------------------------------------
547 // helper function: does real copy
548 bool wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
550 if ( nSrcLen
== 0 ) {
554 if ( !AllocBeforeWrite(nSrcLen
) ) {
555 // allocation failure handled by caller
558 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
559 GetStringData()->nDataLength
= nSrcLen
;
560 m_pchData
[nSrcLen
] = wxT('\0');
565 // assigns one string to another
566 wxString
& wxString::operator=(const wxString
& stringSrc
)
568 wxASSERT( stringSrc
.GetStringData()->IsValid() );
570 // don't copy string over itself
571 if ( m_pchData
!= stringSrc
.m_pchData
) {
572 if ( stringSrc
.GetStringData()->IsEmpty() ) {
577 GetStringData()->Unlock();
578 m_pchData
= stringSrc
.m_pchData
;
579 GetStringData()->Lock();
586 // assigns a single character
587 wxString
& wxString::operator=(wxChar ch
)
589 if ( !AssignCopy(1, &ch
) ) {
590 wxFAIL_MSG( _T("out of memory in wxString::operator=(wxChar)") );
597 wxString
& wxString::operator=(const wxChar
*psz
)
599 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
600 wxFAIL_MSG( _T("out of memory in wxString::operator=(const wxChar *)") );
607 // same as 'signed char' variant
608 wxString
& wxString::operator=(const unsigned char* psz
)
610 *this = (const char *)psz
;
615 wxString
& wxString::operator=(const wchar_t *pwz
)
625 // ---------------------------------------------------------------------------
626 // string concatenation
627 // ---------------------------------------------------------------------------
629 // add something to this string
630 bool wxString::ConcatSelf(size_t nSrcLen
, const wxChar
*pszSrcData
)
632 STATISTICS_ADD(SummandLength
, nSrcLen
);
634 // concatenating an empty string is a NOP
636 wxStringData
*pData
= GetStringData();
637 size_t nLen
= pData
->nDataLength
;
638 size_t nNewLen
= nLen
+ nSrcLen
;
640 // alloc new buffer if current is too small
641 if ( pData
->IsShared() ) {
642 STATISTICS_ADD(ConcatHit
, 0);
644 // we have to allocate another buffer
645 wxStringData
* pOldData
= GetStringData();
646 if ( !AllocBuffer(nNewLen
) ) {
647 // allocation failure handled by caller
650 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
653 else if ( nNewLen
> pData
->nAllocLength
) {
654 STATISTICS_ADD(ConcatHit
, 0);
656 // we have to grow the buffer
657 if ( !Alloc(nNewLen
) ) {
658 // allocation failure handled by caller
663 STATISTICS_ADD(ConcatHit
, 1);
665 // the buffer is already big enough
668 // should be enough space
669 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
671 // fast concatenation - all is done in our buffer
672 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
674 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
675 GetStringData()->nDataLength
= nNewLen
; // and fix the length
677 //else: the string to append was empty
682 * concatenation functions come in 5 flavours:
684 * char + string and string + char
685 * C str + string and string + C str
688 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
690 wxASSERT( str1
.GetStringData()->IsValid() );
691 wxASSERT( str2
.GetStringData()->IsValid() );
699 wxString
operator+(const wxString
& str
, wxChar ch
)
701 wxASSERT( str
.GetStringData()->IsValid() );
709 wxString
operator+(wxChar ch
, const wxString
& str
)
711 wxASSERT( str
.GetStringData()->IsValid() );
719 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
721 wxASSERT( str
.GetStringData()->IsValid() );
724 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
725 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
733 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
735 wxASSERT( str
.GetStringData()->IsValid() );
738 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
739 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
747 // ===========================================================================
748 // other common string functions
749 // ===========================================================================
753 wxString
wxString::FromAscii(const char *ascii
)
756 return wxEmptyString
;
758 size_t len
= strlen( ascii
);
763 wxStringBuffer
buf(res
, len
);
769 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
777 wxString
wxString::FromAscii(const char ascii
)
779 // What do we do with '\0' ?
782 res
+= (wchar_t)(unsigned char) ascii
;
787 const wxCharBuffer
wxString::ToAscii() const
789 // this will allocate enough space for the terminating NUL too
790 wxCharBuffer
buffer(length());
792 signed char *dest
= (signed char *)buffer
.data();
794 const wchar_t *pwc
= c_str();
797 *dest
++ = *pwc
> SCHAR_MAX
? '_' : *pwc
;
799 // the output string can't have embedded NULs anyhow, so we can safely
800 // stop at first of them even if we do have any
810 // ---------------------------------------------------------------------------
811 // simple sub-string extraction
812 // ---------------------------------------------------------------------------
814 // helper function: clone the data attached to this string
815 bool wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
817 if ( nCopyLen
== 0 ) {
821 if ( !dest
.AllocBuffer(nCopyLen
) ) {
822 // allocation failure handled by caller
825 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
830 // extract string of length nCount starting at nFirst
831 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
833 wxStringData
*pData
= GetStringData();
834 size_t nLen
= pData
->nDataLength
;
836 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
837 if ( nCount
== wxSTRING_MAXLEN
)
839 nCount
= nLen
- nFirst
;
842 // out-of-bounds requests return sensible things
843 if ( nFirst
+ nCount
> nLen
)
845 nCount
= nLen
- nFirst
;
850 // AllocCopy() will return empty string
855 if ( !AllocCopy(dest
, nCount
, nFirst
) ) {
856 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
862 // check that the tring starts with prefix and return the rest of the string
863 // in the provided pointer if it is not NULL, otherwise return FALSE
864 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
866 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
868 // first check if the beginning of the string matches the prefix: note
869 // that we don't have to check that we don't run out of this string as
870 // when we reach the terminating NUL, either prefix string ends too (and
871 // then it's ok) or we break out of the loop because there is no match
872 const wxChar
*p
= c_str();
875 if ( *prefix
++ != *p
++ )
884 // put the rest of the string into provided pointer
891 // extract nCount last (rightmost) characters
892 wxString
wxString::Right(size_t nCount
) const
894 if ( nCount
> (size_t)GetStringData()->nDataLength
)
895 nCount
= GetStringData()->nDataLength
;
898 if ( !AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
) ) {
899 wxFAIL_MSG( _T("out of memory in wxString::Right") );
904 // get all characters after the last occurence of ch
905 // (returns the whole string if ch not found)
906 wxString
wxString::AfterLast(wxChar ch
) const
909 int iPos
= Find(ch
, TRUE
);
910 if ( iPos
== wxNOT_FOUND
)
913 str
= c_str() + iPos
+ 1;
918 // extract nCount first (leftmost) characters
919 wxString
wxString::Left(size_t nCount
) const
921 if ( nCount
> (size_t)GetStringData()->nDataLength
)
922 nCount
= GetStringData()->nDataLength
;
925 if ( !AllocCopy(dest
, nCount
, 0) ) {
926 wxFAIL_MSG( _T("out of memory in wxString::Left") );
931 // get all characters before the first occurence of ch
932 // (returns the whole string if ch not found)
933 wxString
wxString::BeforeFirst(wxChar ch
) const
936 for ( const wxChar
*pc
= m_pchData
; *pc
!= wxT('\0') && *pc
!= ch
; pc
++ )
942 /// get all characters before the last occurence of ch
943 /// (returns empty string if ch not found)
944 wxString
wxString::BeforeLast(wxChar ch
) const
947 int iPos
= Find(ch
, TRUE
);
948 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
949 str
= wxString(c_str(), iPos
);
954 /// get all characters after the first occurence of ch
955 /// (returns empty string if ch not found)
956 wxString
wxString::AfterFirst(wxChar ch
) const
960 if ( iPos
!= wxNOT_FOUND
)
961 str
= c_str() + iPos
+ 1;
966 // replace first (or all) occurences of some substring with another one
968 wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
970 // if we tried to replace an empty string we'd enter an infinite loop below
971 wxCHECK_MSG( szOld
&& *szOld
&& szNew
, 0,
972 _T("wxString::Replace(): invalid parameter") );
974 size_t uiCount
= 0; // count of replacements made
976 size_t uiOldLen
= wxStrlen(szOld
);
979 const wxChar
*pCurrent
= m_pchData
;
980 const wxChar
*pSubstr
;
981 while ( *pCurrent
!= wxT('\0') ) {
982 pSubstr
= wxStrstr(pCurrent
, szOld
);
983 if ( pSubstr
== NULL
) {
984 // strTemp is unused if no replacements were made, so avoid the copy
988 strTemp
+= pCurrent
; // copy the rest
989 break; // exit the loop
992 // take chars before match
993 if ( !strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
) ) {
994 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
998 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
1003 if ( !bReplaceAll
) {
1004 strTemp
+= pCurrent
; // copy the rest
1005 break; // exit the loop
1010 // only done if there were replacements, otherwise would have returned above
1017 inline int isascii(wxChar c
) { return (c
>= 0) && (c
<=127); }
1020 bool wxString::IsAscii() const
1022 const wxChar
*s
= (const wxChar
*) *this;
1024 if(!isascii(*s
)) return(FALSE
);
1030 bool wxString::IsWord() const
1032 const wxChar
*s
= (const wxChar
*) *this;
1034 if(!wxIsalpha(*s
)) return(FALSE
);
1040 bool wxString::IsNumber() const
1042 const wxChar
*s
= (const wxChar
*) *this;
1044 if ((s
[0] == '-') || (s
[0] == '+')) s
++;
1046 if(!wxIsdigit(*s
)) return(FALSE
);
1052 wxString
wxString::Strip(stripType w
) const
1055 if ( w
& leading
) s
.Trim(FALSE
);
1056 if ( w
& trailing
) s
.Trim(TRUE
);
1060 // ---------------------------------------------------------------------------
1062 // ---------------------------------------------------------------------------
1064 wxString
& wxString::MakeUpper()
1066 if ( !CopyBeforeWrite() ) {
1067 wxFAIL_MSG( _T("out of memory in wxString::MakeUpper") );
1071 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1072 *p
= (wxChar
)wxToupper(*p
);
1077 wxString
& wxString::MakeLower()
1079 if ( !CopyBeforeWrite() ) {
1080 wxFAIL_MSG( _T("out of memory in wxString::MakeLower") );
1084 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1085 *p
= (wxChar
)wxTolower(*p
);
1090 // ---------------------------------------------------------------------------
1091 // trimming and padding
1092 // ---------------------------------------------------------------------------
1094 // some compilers (VC++ 6.0 not to name them) return TRUE for a call to
1095 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1096 // live with this by checking that the character is a 7 bit one - even if this
1097 // may fail to detect some spaces (I don't know if Unicode doesn't have
1098 // space-like symbols somewhere except in the first 128 chars), it is arguably
1099 // still better than trimming away accented letters
1100 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1102 // trims spaces (in the sense of isspace) from left or right side
1103 wxString
& wxString::Trim(bool bFromRight
)
1105 // first check if we're going to modify the string at all
1108 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1109 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1113 // ok, there is at least one space to trim
1114 if ( !CopyBeforeWrite() ) {
1115 wxFAIL_MSG( _T("out of memory in wxString::Trim") );
1121 // find last non-space character
1122 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
1123 while ( wxSafeIsspace(*psz
) && (psz
>= m_pchData
) )
1126 // truncate at trailing space start
1128 GetStringData()->nDataLength
= psz
- m_pchData
;
1132 // find first non-space character
1133 const wxChar
*psz
= m_pchData
;
1134 while ( wxSafeIsspace(*psz
) )
1137 // fix up data and length
1138 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
1139 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
1140 GetStringData()->nDataLength
= nDataLength
;
1147 // adds nCount characters chPad to the string from either side
1148 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1150 wxString
s(chPad
, nCount
);
1163 // truncate the string
1164 wxString
& wxString::Truncate(size_t uiLen
)
1166 if ( uiLen
< Len() ) {
1167 if ( !CopyBeforeWrite() ) {
1168 wxFAIL_MSG( _T("out of memory in wxString::Truncate") );
1172 *(m_pchData
+ uiLen
) = wxT('\0');
1173 GetStringData()->nDataLength
= uiLen
;
1175 //else: nothing to do, string is already short enough
1180 // ---------------------------------------------------------------------------
1181 // finding (return wxNOT_FOUND if not found and index otherwise)
1182 // ---------------------------------------------------------------------------
1185 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1187 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
1189 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1192 // find a sub-string (like strstr)
1193 int wxString::Find(const wxChar
*pszSub
) const
1195 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
1197 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1200 // ----------------------------------------------------------------------------
1201 // conversion to numbers
1202 // ----------------------------------------------------------------------------
1204 bool wxString::ToLong(long *val
, int base
) const
1206 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToLong") );
1207 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1209 const wxChar
*start
= c_str();
1211 *val
= wxStrtol(start
, &end
, base
);
1213 // return TRUE only if scan was stopped by the terminating NUL and if the
1214 // string was not empty to start with
1215 return !*end
&& (end
!= start
);
1218 bool wxString::ToULong(unsigned long *val
, int base
) const
1220 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToULong") );
1221 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1223 const wxChar
*start
= c_str();
1225 *val
= wxStrtoul(start
, &end
, base
);
1227 // return TRUE only if scan was stopped by the terminating NUL and if the
1228 // string was not empty to start with
1229 return !*end
&& (end
!= start
);
1232 bool wxString::ToDouble(double *val
) const
1234 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToDouble") );
1236 const wxChar
*start
= c_str();
1238 *val
= wxStrtod(start
, &end
);
1240 // return TRUE only if scan was stopped by the terminating NUL and if the
1241 // string was not empty to start with
1242 return !*end
&& (end
!= start
);
1245 // ---------------------------------------------------------------------------
1247 // ---------------------------------------------------------------------------
1250 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1253 va_start(argptr
, pszFormat
);
1256 s
.PrintfV(pszFormat
, argptr
);
1264 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1267 s
.PrintfV(pszFormat
, argptr
);
1271 int wxString::Printf(const wxChar
*pszFormat
, ...)
1274 va_start(argptr
, pszFormat
);
1276 int iLen
= PrintfV(pszFormat
, argptr
);
1283 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1288 wxChar
*buf
= GetWriteBuf(size
+ 1);
1295 int len
= wxVsnprintf(buf
, size
, pszFormat
, argptr
);
1297 // some implementations of vsnprintf() don't NUL terminate the string
1298 // if there is not enough space for it so always do it manually
1299 buf
[size
] = _T('\0');
1305 // ok, there was enough space
1309 // still not enough, double it again
1313 // we could have overshot
1319 // ----------------------------------------------------------------------------
1320 // misc other operations
1321 // ----------------------------------------------------------------------------
1323 // returns TRUE if the string matches the pattern which may contain '*' and
1324 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1326 bool wxString::Matches(const wxChar
*pszMask
) const
1328 // I disable this code as it doesn't seem to be faster (in fact, it seems
1329 // to be much slower) than the old, hand-written code below and using it
1330 // here requires always linking with libregex even if the user code doesn't
1332 #if 0 // wxUSE_REGEX
1333 // first translate the shell-like mask into a regex
1335 pattern
.reserve(wxStrlen(pszMask
));
1347 pattern
+= _T(".*");
1358 // these characters are special in a RE, quote them
1359 // (however note that we don't quote '[' and ']' to allow
1360 // using them for Unix shell like matching)
1361 pattern
+= _T('\\');
1365 pattern
+= *pszMask
;
1373 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1374 #else // !wxUSE_REGEX
1375 // TODO: this is, of course, awfully inefficient...
1377 // the char currently being checked
1378 const wxChar
*pszTxt
= c_str();
1380 // the last location where '*' matched
1381 const wxChar
*pszLastStarInText
= NULL
;
1382 const wxChar
*pszLastStarInMask
= NULL
;
1385 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1386 switch ( *pszMask
) {
1388 if ( *pszTxt
== wxT('\0') )
1391 // pszTxt and pszMask will be incremented in the loop statement
1397 // remember where we started to be able to backtrack later
1398 pszLastStarInText
= pszTxt
;
1399 pszLastStarInMask
= pszMask
;
1401 // ignore special chars immediately following this one
1402 // (should this be an error?)
1403 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1406 // if there is nothing more, match
1407 if ( *pszMask
== wxT('\0') )
1410 // are there any other metacharacters in the mask?
1412 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1414 if ( pEndMask
!= NULL
) {
1415 // we have to match the string between two metachars
1416 uiLenMask
= pEndMask
- pszMask
;
1419 // we have to match the remainder of the string
1420 uiLenMask
= wxStrlen(pszMask
);
1423 wxString
strToMatch(pszMask
, uiLenMask
);
1424 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1425 if ( pMatch
== NULL
)
1428 // -1 to compensate "++" in the loop
1429 pszTxt
= pMatch
+ uiLenMask
- 1;
1430 pszMask
+= uiLenMask
- 1;
1435 if ( *pszMask
!= *pszTxt
)
1441 // match only if nothing left
1442 if ( *pszTxt
== wxT('\0') )
1445 // if we failed to match, backtrack if we can
1446 if ( pszLastStarInText
) {
1447 pszTxt
= pszLastStarInText
+ 1;
1448 pszMask
= pszLastStarInMask
;
1450 pszLastStarInText
= NULL
;
1452 // don't bother resetting pszLastStarInMask, it's unnecessary
1458 #endif // wxUSE_REGEX/!wxUSE_REGEX
1461 // Count the number of chars
1462 int wxString::Freq(wxChar ch
) const
1466 for (int i
= 0; i
< len
; i
++)
1468 if (GetChar(i
) == ch
)
1474 // convert to upper case, return the copy of the string
1475 wxString
wxString::Upper() const
1476 { wxString
s(*this); return s
.MakeUpper(); }
1478 // convert to lower case, return the copy of the string
1479 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1481 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1484 va_start(argptr
, pszFormat
);
1485 int iLen
= PrintfV(pszFormat
, argptr
);
1490 // ---------------------------------------------------------------------------
1491 // standard C++ library string functions
1492 // ---------------------------------------------------------------------------
1494 #ifdef wxSTD_STRING_COMPATIBILITY
1496 void wxString::resize(size_t nSize
, wxChar ch
)
1498 size_t len
= length();
1504 else if ( nSize
> len
)
1506 *this += wxString(ch
, nSize
- len
);
1508 //else: we have exactly the specified length, nothing to do
1511 void wxString::swap(wxString
& str
)
1513 // this is slightly less efficient than fiddling with m_pchData directly,
1514 // but it is still quite efficient as we don't copy the string here because
1515 // ref count always stays positive
1521 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1523 wxASSERT( str
.GetStringData()->IsValid() );
1524 wxASSERT( nPos
<= Len() );
1526 if ( !str
.IsEmpty() ) {
1528 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1529 wxStrncpy(pc
, c_str(), nPos
);
1530 wxStrcpy(pc
+ nPos
, str
);
1531 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1532 strTmp
.UngetWriteBuf();
1539 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1541 wxASSERT( str
.GetStringData()->IsValid() );
1542 wxASSERT( nStart
<= Len() );
1544 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1546 return p
== NULL
? npos
: p
- c_str();
1549 // VC++ 1.5 can't cope with the default argument in the header.
1550 #if !defined(__VISUALC__) || defined(__WIN32__)
1551 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1553 return find(wxString(sz
, n
), nStart
);
1557 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1558 #if !defined(__BORLANDC__)
1559 size_t wxString::find(wxChar ch
, size_t nStart
) const
1561 wxASSERT( nStart
<= Len() );
1563 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1565 return p
== NULL
? npos
: p
- c_str();
1569 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1571 wxASSERT( str
.GetStringData()->IsValid() );
1572 wxASSERT( nStart
== npos
|| nStart
<= Len() );
1574 // TODO could be made much quicker than that
1575 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1576 while ( p
>= c_str() + str
.Len() ) {
1577 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1578 return p
- str
.Len() - c_str();
1585 // VC++ 1.5 can't cope with the default argument in the header.
1586 #if !defined(__VISUALC__) || defined(__WIN32__)
1587 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1589 return rfind(wxString(sz
, n
== npos
? wxSTRING_MAXLEN
: n
), nStart
);
1592 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1594 if ( nStart
== npos
)
1600 wxASSERT( nStart
<= Len() );
1603 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1608 size_t result
= p
- c_str();
1609 return ( result
> nStart
) ? npos
: result
;
1613 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1615 const wxChar
*start
= c_str() + nStart
;
1616 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1618 return firstOf
- c_str();
1623 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1625 if ( nStart
== npos
)
1631 wxASSERT( nStart
<= Len() );
1634 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1636 if ( wxStrchr(sz
, *p
) )
1643 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1645 if ( nStart
== npos
)
1651 wxASSERT( nStart
<= Len() );
1654 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1655 if ( nAccept
>= length() - nStart
)
1661 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1663 wxASSERT( nStart
<= Len() );
1665 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1674 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1676 if ( nStart
== npos
)
1682 wxASSERT( nStart
<= Len() );
1685 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1687 if ( !wxStrchr(sz
, *p
) )
1694 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1696 if ( nStart
== npos
)
1702 wxASSERT( nStart
<= Len() );
1705 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1714 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1716 wxString
strTmp(c_str(), nStart
);
1717 if ( nLen
!= npos
) {
1718 wxASSERT( nStart
+ nLen
<= Len() );
1720 strTmp
.append(c_str() + nStart
+ nLen
);
1727 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1729 wxASSERT_MSG( nStart
+ nLen
<= Len(),
1730 _T("index out of bounds in wxString::replace") );
1733 strTmp
.Alloc(Len()); // micro optimisation to avoid multiple mem allocs
1736 strTmp
.append(c_str(), nStart
);
1737 strTmp
<< sz
<< c_str() + nStart
+ nLen
;
1743 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1745 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1748 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1749 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1751 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1754 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1755 const wxChar
* sz
, size_t nCount
)
1757 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1760 #endif //std::string compatibility
1762 // ============================================================================
1764 // ============================================================================
1766 #include "wx/arrstr.h"
1770 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1771 #define ARRAY_MAXSIZE_INCREMENT 4096
1773 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1774 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1777 #define STRING(p) ((wxString *)(&(p)))
1780 void wxArrayString::Init(bool autoSort
)
1784 m_pItems
= (wxChar
**) NULL
;
1785 m_autoSort
= autoSort
;
1789 wxArrayString::wxArrayString(const wxArrayString
& src
)
1791 Init(src
.m_autoSort
);
1796 // assignment operator
1797 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1804 m_autoSort
= src
.m_autoSort
;
1809 void wxArrayString::Copy(const wxArrayString
& src
)
1811 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1812 Alloc(src
.m_nCount
);
1814 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1819 void wxArrayString::Grow(size_t nIncrement
)
1821 // only do it if no more place
1822 if ( (m_nSize
- m_nCount
) < nIncrement
) {
1823 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
1824 // be never resized!
1825 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
1826 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
1829 if ( m_nSize
== 0 ) {
1830 // was empty, alloc some memory
1831 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1832 if (m_nSize
< nIncrement
)
1833 m_nSize
= nIncrement
;
1834 m_pItems
= new wxChar
*[m_nSize
];
1837 // otherwise when it's called for the first time, nIncrement would be 0
1838 // and the array would never be expanded
1839 // add 50% but not too much
1840 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1841 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1842 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1843 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1844 if ( nIncrement
< ndefIncrement
)
1845 nIncrement
= ndefIncrement
;
1846 m_nSize
+= nIncrement
;
1847 wxChar
**pNew
= new wxChar
*[m_nSize
];
1849 // copy data to new location
1850 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1852 // delete old memory (but do not release the strings!)
1853 wxDELETEA(m_pItems
);
1860 void wxArrayString::Free()
1862 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1863 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1867 // deletes all the strings from the list
1868 void wxArrayString::Empty()
1875 // as Empty, but also frees memory
1876 void wxArrayString::Clear()
1883 wxDELETEA(m_pItems
);
1887 wxArrayString::~wxArrayString()
1891 wxDELETEA(m_pItems
);
1894 // pre-allocates memory (frees the previous data!)
1895 void wxArrayString::Alloc(size_t nSize
)
1897 // only if old buffer was not big enough
1898 if ( nSize
> m_nSize
) {
1900 wxDELETEA(m_pItems
);
1901 m_pItems
= new wxChar
*[nSize
];
1908 // minimizes the memory usage by freeing unused memory
1909 void wxArrayString::Shrink()
1911 // only do it if we have some memory to free
1912 if( m_nCount
< m_nSize
) {
1913 // allocates exactly as much memory as we need
1914 wxChar
**pNew
= new wxChar
*[m_nCount
];
1916 // copy data to new location
1917 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1923 #if WXWIN_COMPATIBILITY_2_4
1925 // return a wxString[] as required for some control ctors.
1926 wxString
* wxArrayString::GetStringArray() const
1928 wxString
*array
= 0;
1932 array
= new wxString
[m_nCount
];
1933 for( size_t i
= 0; i
< m_nCount
; i
++ )
1934 array
[i
] = m_pItems
[i
];
1940 #endif // WXWIN_COMPATIBILITY_2_4
1942 // searches the array for an item (forward or backwards)
1943 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
1946 // use binary search in the sorted array
1947 wxASSERT_MSG( bCase
&& !bFromEnd
,
1948 wxT("search parameters ignored for auto sorted array") );
1957 res
= wxStrcmp(sz
, m_pItems
[i
]);
1969 // use linear search in unsorted array
1971 if ( m_nCount
> 0 ) {
1972 size_t ui
= m_nCount
;
1974 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1981 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1982 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1991 // add item at the end
1992 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
1995 // insert the string at the correct position to keep the array sorted
2003 res
= wxStrcmp(str
, m_pItems
[i
]);
2014 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2016 Insert(str
, lo
, nInsert
);
2021 wxASSERT( str
.GetStringData()->IsValid() );
2025 for (size_t i
= 0; i
< nInsert
; i
++)
2027 // the string data must not be deleted!
2028 str
.GetStringData()->Lock();
2031 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2033 size_t ret
= m_nCount
;
2034 m_nCount
+= nInsert
;
2039 // add item at the given position
2040 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2042 wxASSERT( str
.GetStringData()->IsValid() );
2044 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2045 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2046 wxT("array size overflow in wxArrayString::Insert") );
2050 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2051 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2053 for (size_t i
= 0; i
< nInsert
; i
++)
2055 str
.GetStringData()->Lock();
2056 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2058 m_nCount
+= nInsert
;
2062 void wxArrayString::SetCount(size_t count
)
2067 while ( m_nCount
< count
)
2068 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2071 // removes item from array (by index)
2072 void wxArrayString::RemoveAt(size_t nIndex
, size_t nRemove
)
2074 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2075 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2076 wxT("removing too many elements in wxArrayString::Remove") );
2079 for (size_t i
= 0; i
< nRemove
; i
++)
2080 Item(nIndex
+ i
).GetStringData()->Unlock();
2082 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2083 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2084 m_nCount
-= nRemove
;
2087 // removes item from array (by value)
2088 void wxArrayString::Remove(const wxChar
*sz
)
2090 int iIndex
= Index(sz
);
2092 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2093 wxT("removing inexistent element in wxArrayString::Remove") );
2098 // ----------------------------------------------------------------------------
2100 // ----------------------------------------------------------------------------
2102 // we can only sort one array at a time with the quick-sort based
2105 // need a critical section to protect access to gs_compareFunction and
2106 // gs_sortAscending variables
2107 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2109 // call this before the value of the global sort vars is changed/after
2110 // you're finished with them
2111 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2112 gs_critsectStringSort = new wxCriticalSection; \
2113 gs_critsectStringSort->Enter()
2114 #define END_SORT() gs_critsectStringSort->Leave(); \
2115 delete gs_critsectStringSort; \
2116 gs_critsectStringSort = NULL
2118 #define START_SORT()
2120 #endif // wxUSE_THREADS
2122 // function to use for string comparaison
2123 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2125 // if we don't use the compare function, this flag tells us if we sort the
2126 // array in ascending or descending order
2127 static bool gs_sortAscending
= TRUE
;
2129 // function which is called by quick sort
2130 extern "C" int wxC_CALLING_CONV
// LINKAGEMODE
2131 wxStringCompareFunction(const void *first
, const void *second
)
2133 wxString
*strFirst
= (wxString
*)first
;
2134 wxString
*strSecond
= (wxString
*)second
;
2136 if ( gs_compareFunction
) {
2137 return gs_compareFunction(*strFirst
, *strSecond
);
2140 // maybe we should use wxStrcoll
2141 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
2143 return gs_sortAscending
? result
: -result
;
2147 // sort array elements using passed comparaison function
2148 void wxArrayString::Sort(CompareFunction compareFunction
)
2152 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2153 gs_compareFunction
= compareFunction
;
2157 // reset it to NULL so that Sort(bool) will work the next time
2158 gs_compareFunction
= NULL
;
2163 typedef int (wxC_CALLING_CONV
* wxStringCompareFn
)(const void *first
, const void *second
);
2165 void wxArrayString::Sort(CompareFunction2 compareFunction
)
2167 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), (wxStringCompareFn
)compareFunction
);
2170 void wxArrayString::Sort(bool reverseOrder
)
2172 Sort(reverseOrder
? wxStringSortDescending
: wxStringSortAscending
);
2175 void wxArrayString::DoSort()
2177 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2179 // just sort the pointers using qsort() - of course it only works because
2180 // wxString() *is* a pointer to its data
2181 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2184 bool wxArrayString::operator==(const wxArrayString
& a
) const
2186 if ( m_nCount
!= a
.m_nCount
)
2189 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2191 if ( Item(n
) != a
[n
] )
2198 #endif // !wxUSE_STL
2200 int wxStringSortAscending(wxString
* s1
, wxString
* s2
)
2202 return wxStrcmp(s1
->c_str(), s2
->c_str());
2205 int wxStringSortDescending(wxString
* s1
, wxString
* s2
)
2207 return -wxStrcmp(s1
->c_str(), s2
->c_str());