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 #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 a provide 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
267 if ( conv
.MB2WC(m_pchData
, psz
, nLen
+ 1) != (size_t)-1 )
273 //else: the conversion failed -- leave the string empty (what else?)
283 wxString::wxString(const wchar_t *pwz
, wxMBConv
& conv
, size_t nLength
)
285 // first get the size of the buffer we need
289 // calculate the needed size ourselves or use a provide one
290 nLen
= nLength
== wxSTRING_MAXLEN
? conv
.WC2MB(NULL
, pwz
, 0) : nLength
;
294 // nothing to convert
299 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
301 if ( !AllocBuffer(nLen
) )
303 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
307 // WC2MB wants the buffer size, not the string length
308 if ( conv
.WC2MB(m_pchData
, pwz
, nLen
+ 1) != (size_t)-1 )
313 //else: the conversion failed -- leave the string empty (what else?)
318 #endif // wxUSE_WCHAR_T
320 #endif // Unicode/ANSI
322 // ---------------------------------------------------------------------------
324 // ---------------------------------------------------------------------------
326 // allocates memory needed to store a C string of length nLen
327 bool wxString::AllocBuffer(size_t nLen
)
329 // allocating 0 sized buffer doesn't make sense, all empty strings should
331 wxASSERT( nLen
> 0 );
333 // make sure that we don't overflow
334 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
335 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
337 STATISTICS_ADD(Length
, nLen
);
340 // 1) one extra character for '\0' termination
341 // 2) sizeof(wxStringData) for housekeeping info
342 wxStringData
* pData
= (wxStringData
*)
343 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
345 if ( pData
== NULL
) {
346 // allocation failures are handled by the caller
351 pData
->nDataLength
= nLen
;
352 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
353 m_pchData
= pData
->data(); // data starts after wxStringData
354 m_pchData
[nLen
] = wxT('\0');
358 // must be called before changing this string
359 bool wxString::CopyBeforeWrite()
361 wxStringData
* pData
= GetStringData();
363 if ( pData
->IsShared() ) {
364 pData
->Unlock(); // memory not freed because shared
365 size_t nLen
= pData
->nDataLength
;
366 if ( !AllocBuffer(nLen
) ) {
367 // allocation failures are handled by the caller
370 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
373 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
378 // must be called before replacing contents of this string
379 bool wxString::AllocBeforeWrite(size_t nLen
)
381 wxASSERT( nLen
!= 0 ); // doesn't make any sense
383 // must not share string and must have enough space
384 wxStringData
* pData
= GetStringData();
385 if ( pData
->IsShared() || pData
->IsEmpty() ) {
386 // can't work with old buffer, get new one
388 if ( !AllocBuffer(nLen
) ) {
389 // allocation failures are handled by the caller
394 if ( nLen
> pData
->nAllocLength
) {
395 // realloc the buffer instead of calling malloc() again, this is more
397 STATISTICS_ADD(Length
, nLen
);
401 pData
= (wxStringData
*)
402 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
404 if ( pData
== NULL
) {
405 // allocation failures are handled by the caller
406 // keep previous data since reallocation failed
410 pData
->nAllocLength
= nLen
;
411 m_pchData
= pData
->data();
414 // now we have enough space, just update the string length
415 pData
->nDataLength
= nLen
;
418 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
423 // allocate enough memory for nLen characters
424 bool wxString::Alloc(size_t nLen
)
426 wxStringData
*pData
= GetStringData();
427 if ( pData
->nAllocLength
<= nLen
) {
428 if ( pData
->IsEmpty() ) {
431 wxStringData
* pData
= (wxStringData
*)
432 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
434 if ( pData
== NULL
) {
435 // allocation failure handled by caller
440 pData
->nDataLength
= 0;
441 pData
->nAllocLength
= nLen
;
442 m_pchData
= pData
->data(); // data starts after wxStringData
443 m_pchData
[0u] = wxT('\0');
445 else if ( pData
->IsShared() ) {
446 pData
->Unlock(); // memory not freed because shared
447 size_t nOldLen
= pData
->nDataLength
;
448 if ( !AllocBuffer(nLen
) ) {
449 // allocation failure handled by caller
452 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
457 pData
= (wxStringData
*)
458 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
460 if ( pData
== NULL
) {
461 // allocation failure handled by caller
462 // keep previous data since reallocation failed
466 // it's not important if the pointer changed or not (the check for this
467 // is not faster than assigning to m_pchData in all cases)
468 pData
->nAllocLength
= nLen
;
469 m_pchData
= pData
->data();
472 //else: we've already got enough
476 // shrink to minimal size (releasing extra memory)
477 bool wxString::Shrink()
479 wxStringData
*pData
= GetStringData();
481 size_t nLen
= pData
->nDataLength
;
482 void *p
= realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
485 wxFAIL_MSG( _T("out of memory reallocating wxString data") );
486 // keep previous data since reallocation failed
492 // contrary to what one might believe, some realloc() implementation do
493 // move the memory block even when its size is reduced
494 pData
= (wxStringData
*)p
;
496 m_pchData
= pData
->data();
499 pData
->nAllocLength
= nLen
;
504 // get the pointer to writable buffer of (at least) nLen bytes
505 wxChar
*wxString::GetWriteBuf(size_t nLen
)
507 if ( !AllocBeforeWrite(nLen
) ) {
508 // allocation failure handled by caller
512 wxASSERT( GetStringData()->nRefs
== 1 );
513 GetStringData()->Validate(FALSE
);
518 // put string back in a reasonable state after GetWriteBuf
519 void wxString::UngetWriteBuf()
521 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
522 GetStringData()->Validate(TRUE
);
525 void wxString::UngetWriteBuf(size_t nLen
)
527 GetStringData()->nDataLength
= nLen
;
528 GetStringData()->Validate(TRUE
);
531 // ---------------------------------------------------------------------------
533 // ---------------------------------------------------------------------------
535 // all functions are inline in string.h
537 // ---------------------------------------------------------------------------
538 // assignment operators
539 // ---------------------------------------------------------------------------
541 // helper function: does real copy
542 bool wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
544 if ( nSrcLen
== 0 ) {
548 if ( !AllocBeforeWrite(nSrcLen
) ) {
549 // allocation failure handled by caller
552 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
553 GetStringData()->nDataLength
= nSrcLen
;
554 m_pchData
[nSrcLen
] = wxT('\0');
559 // assigns one string to another
560 wxString
& wxString::operator=(const wxString
& stringSrc
)
562 wxASSERT( stringSrc
.GetStringData()->IsValid() );
564 // don't copy string over itself
565 if ( m_pchData
!= stringSrc
.m_pchData
) {
566 if ( stringSrc
.GetStringData()->IsEmpty() ) {
571 GetStringData()->Unlock();
572 m_pchData
= stringSrc
.m_pchData
;
573 GetStringData()->Lock();
580 // assigns a single character
581 wxString
& wxString::operator=(wxChar ch
)
583 if ( !AssignCopy(1, &ch
) ) {
584 wxFAIL_MSG( _T("out of memory in wxString::operator=(wxChar)") );
591 wxString
& wxString::operator=(const wxChar
*psz
)
593 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
594 wxFAIL_MSG( _T("out of memory in wxString::operator=(const wxChar *)") );
601 // same as 'signed char' variant
602 wxString
& wxString::operator=(const unsigned char* psz
)
604 *this = (const char *)psz
;
609 wxString
& wxString::operator=(const wchar_t *pwz
)
619 // ---------------------------------------------------------------------------
620 // string concatenation
621 // ---------------------------------------------------------------------------
623 // add something to this string
624 bool wxString::ConcatSelf(size_t nSrcLen
, const wxChar
*pszSrcData
)
626 STATISTICS_ADD(SummandLength
, nSrcLen
);
628 // concatenating an empty string is a NOP
630 wxStringData
*pData
= GetStringData();
631 size_t nLen
= pData
->nDataLength
;
632 size_t nNewLen
= nLen
+ nSrcLen
;
634 // alloc new buffer if current is too small
635 if ( pData
->IsShared() ) {
636 STATISTICS_ADD(ConcatHit
, 0);
638 // we have to allocate another buffer
639 wxStringData
* pOldData
= GetStringData();
640 if ( !AllocBuffer(nNewLen
) ) {
641 // allocation failure handled by caller
644 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
647 else if ( nNewLen
> pData
->nAllocLength
) {
648 STATISTICS_ADD(ConcatHit
, 0);
650 // we have to grow the buffer
651 if ( !Alloc(nNewLen
) ) {
652 // allocation failure handled by caller
657 STATISTICS_ADD(ConcatHit
, 1);
659 // the buffer is already big enough
662 // should be enough space
663 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
665 // fast concatenation - all is done in our buffer
666 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
668 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
669 GetStringData()->nDataLength
= nNewLen
; // and fix the length
671 //else: the string to append was empty
676 * concatenation functions come in 5 flavours:
678 * char + string and string + char
679 * C str + string and string + C str
682 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
684 wxASSERT( str1
.GetStringData()->IsValid() );
685 wxASSERT( str2
.GetStringData()->IsValid() );
693 wxString
operator+(const wxString
& str
, wxChar ch
)
695 wxASSERT( str
.GetStringData()->IsValid() );
703 wxString
operator+(wxChar ch
, const wxString
& str
)
705 wxASSERT( str
.GetStringData()->IsValid() );
713 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
715 wxASSERT( str
.GetStringData()->IsValid() );
718 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
719 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
727 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
729 wxASSERT( str
.GetStringData()->IsValid() );
732 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
733 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
741 // ===========================================================================
742 // other common string functions
743 // ===========================================================================
747 wxString
wxString::FromAscii(const char *ascii
)
750 return wxEmptyString
;
752 size_t len
= strlen( ascii
);
757 wxStringBuffer
buf(res
, len
);
763 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
771 wxString
wxString::FromAscii(const char ascii
)
773 // What do we do with '\0' ?
776 res
+= (wchar_t)(unsigned char) ascii
;
781 const wxCharBuffer
wxString::ToAscii() const
783 // this will allocate enough space for the terminating NUL too
784 wxCharBuffer
buffer(length());
786 signed char *dest
= (signed char *)buffer
.data();
788 const wchar_t *pwc
= c_str();
791 *dest
++ = *pwc
> SCHAR_MAX
? '_' : *pwc
;
793 // the output string can't have embedded NULs anyhow, so we can safely
794 // stop at first of them even if we do have any
804 // ---------------------------------------------------------------------------
805 // simple sub-string extraction
806 // ---------------------------------------------------------------------------
808 // helper function: clone the data attached to this string
809 bool wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
811 if ( nCopyLen
== 0 ) {
815 if ( !dest
.AllocBuffer(nCopyLen
) ) {
816 // allocation failure handled by caller
819 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
824 // extract string of length nCount starting at nFirst
825 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
827 wxStringData
*pData
= GetStringData();
828 size_t nLen
= pData
->nDataLength
;
830 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
831 if ( nCount
== wxSTRING_MAXLEN
)
833 nCount
= nLen
- nFirst
;
836 // out-of-bounds requests return sensible things
837 if ( nFirst
+ nCount
> nLen
)
839 nCount
= nLen
- nFirst
;
844 // AllocCopy() will return empty string
849 if ( !AllocCopy(dest
, nCount
, nFirst
) ) {
850 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
856 // check that the tring starts with prefix and return the rest of the string
857 // in the provided pointer if it is not NULL, otherwise return FALSE
858 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
860 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
862 // first check if the beginning of the string matches the prefix: note
863 // that we don't have to check that we don't run out of this string as
864 // when we reach the terminating NUL, either prefix string ends too (and
865 // then it's ok) or we break out of the loop because there is no match
866 const wxChar
*p
= c_str();
869 if ( *prefix
++ != *p
++ )
878 // put the rest of the string into provided pointer
885 // extract nCount last (rightmost) characters
886 wxString
wxString::Right(size_t nCount
) const
888 if ( nCount
> (size_t)GetStringData()->nDataLength
)
889 nCount
= GetStringData()->nDataLength
;
892 if ( !AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
) ) {
893 wxFAIL_MSG( _T("out of memory in wxString::Right") );
898 // get all characters after the last occurence of ch
899 // (returns the whole string if ch not found)
900 wxString
wxString::AfterLast(wxChar ch
) const
903 int iPos
= Find(ch
, TRUE
);
904 if ( iPos
== wxNOT_FOUND
)
907 str
= c_str() + iPos
+ 1;
912 // extract nCount first (leftmost) characters
913 wxString
wxString::Left(size_t nCount
) const
915 if ( nCount
> (size_t)GetStringData()->nDataLength
)
916 nCount
= GetStringData()->nDataLength
;
919 if ( !AllocCopy(dest
, nCount
, 0) ) {
920 wxFAIL_MSG( _T("out of memory in wxString::Left") );
925 // get all characters before the first occurence of ch
926 // (returns the whole string if ch not found)
927 wxString
wxString::BeforeFirst(wxChar ch
) const
930 for ( const wxChar
*pc
= m_pchData
; *pc
!= wxT('\0') && *pc
!= ch
; pc
++ )
936 /// get all characters before the last occurence of ch
937 /// (returns empty string if ch not found)
938 wxString
wxString::BeforeLast(wxChar ch
) const
941 int iPos
= Find(ch
, TRUE
);
942 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
943 str
= wxString(c_str(), iPos
);
948 /// get all characters after the first occurence of ch
949 /// (returns empty string if ch not found)
950 wxString
wxString::AfterFirst(wxChar ch
) const
954 if ( iPos
!= wxNOT_FOUND
)
955 str
= c_str() + iPos
+ 1;
960 // replace first (or all) occurences of some substring with another one
962 wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
964 // if we tried to replace an empty string we'd enter an infinite loop below
965 wxCHECK_MSG( szOld
&& *szOld
&& szNew
, 0,
966 _T("wxString::Replace(): invalid parameter") );
968 size_t uiCount
= 0; // count of replacements made
970 size_t uiOldLen
= wxStrlen(szOld
);
973 const wxChar
*pCurrent
= m_pchData
;
974 const wxChar
*pSubstr
;
975 while ( *pCurrent
!= wxT('\0') ) {
976 pSubstr
= wxStrstr(pCurrent
, szOld
);
977 if ( pSubstr
== NULL
) {
978 // strTemp is unused if no replacements were made, so avoid the copy
982 strTemp
+= pCurrent
; // copy the rest
983 break; // exit the loop
986 // take chars before match
987 if ( !strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
) ) {
988 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
992 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
997 if ( !bReplaceAll
) {
998 strTemp
+= pCurrent
; // copy the rest
999 break; // exit the loop
1004 // only done if there were replacements, otherwise would have returned above
1010 bool wxString::IsAscii() const
1012 const wxChar
*s
= (const wxChar
*) *this;
1014 if(!isascii(*s
)) return(FALSE
);
1020 bool wxString::IsWord() const
1022 const wxChar
*s
= (const wxChar
*) *this;
1024 if(!wxIsalpha(*s
)) return(FALSE
);
1030 bool wxString::IsNumber() const
1032 const wxChar
*s
= (const wxChar
*) *this;
1034 if ((s
[0] == '-') || (s
[0] == '+')) s
++;
1036 if(!wxIsdigit(*s
)) return(FALSE
);
1042 wxString
wxString::Strip(stripType w
) const
1045 if ( w
& leading
) s
.Trim(FALSE
);
1046 if ( w
& trailing
) s
.Trim(TRUE
);
1050 // ---------------------------------------------------------------------------
1052 // ---------------------------------------------------------------------------
1054 wxString
& wxString::MakeUpper()
1056 if ( !CopyBeforeWrite() ) {
1057 wxFAIL_MSG( _T("out of memory in wxString::MakeUpper") );
1061 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1062 *p
= (wxChar
)wxToupper(*p
);
1067 wxString
& wxString::MakeLower()
1069 if ( !CopyBeforeWrite() ) {
1070 wxFAIL_MSG( _T("out of memory in wxString::MakeLower") );
1074 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1075 *p
= (wxChar
)wxTolower(*p
);
1080 // ---------------------------------------------------------------------------
1081 // trimming and padding
1082 // ---------------------------------------------------------------------------
1084 // some compilers (VC++ 6.0 not to name them) return TRUE for a call to
1085 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1086 // live with this by checking that the character is a 7 bit one - even if this
1087 // may fail to detect some spaces (I don't know if Unicode doesn't have
1088 // space-like symbols somewhere except in the first 128 chars), it is arguably
1089 // still better than trimming away accented letters
1090 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1092 // trims spaces (in the sense of isspace) from left or right side
1093 wxString
& wxString::Trim(bool bFromRight
)
1095 // first check if we're going to modify the string at all
1098 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1099 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1103 // ok, there is at least one space to trim
1104 if ( !CopyBeforeWrite() ) {
1105 wxFAIL_MSG( _T("out of memory in wxString::Trim") );
1111 // find last non-space character
1112 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
1113 while ( wxSafeIsspace(*psz
) && (psz
>= m_pchData
) )
1116 // truncate at trailing space start
1118 GetStringData()->nDataLength
= psz
- m_pchData
;
1122 // find first non-space character
1123 const wxChar
*psz
= m_pchData
;
1124 while ( wxSafeIsspace(*psz
) )
1127 // fix up data and length
1128 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
1129 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
1130 GetStringData()->nDataLength
= nDataLength
;
1137 // adds nCount characters chPad to the string from either side
1138 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1140 wxString
s(chPad
, nCount
);
1153 // truncate the string
1154 wxString
& wxString::Truncate(size_t uiLen
)
1156 if ( uiLen
< Len() ) {
1157 if ( !CopyBeforeWrite() ) {
1158 wxFAIL_MSG( _T("out of memory in wxString::Truncate") );
1162 *(m_pchData
+ uiLen
) = wxT('\0');
1163 GetStringData()->nDataLength
= uiLen
;
1165 //else: nothing to do, string is already short enough
1170 // ---------------------------------------------------------------------------
1171 // finding (return wxNOT_FOUND if not found and index otherwise)
1172 // ---------------------------------------------------------------------------
1175 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1177 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
1179 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1182 // find a sub-string (like strstr)
1183 int wxString::Find(const wxChar
*pszSub
) const
1185 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
1187 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1190 // ----------------------------------------------------------------------------
1191 // conversion to numbers
1192 // ----------------------------------------------------------------------------
1194 bool wxString::ToLong(long *val
, int base
) const
1196 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToLong") );
1197 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1199 const wxChar
*start
= c_str();
1201 *val
= wxStrtol(start
, &end
, base
);
1203 // return TRUE only if scan was stopped by the terminating NUL and if the
1204 // string was not empty to start with
1205 return !*end
&& (end
!= start
);
1208 bool wxString::ToULong(unsigned long *val
, int base
) const
1210 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToULong") );
1211 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1213 const wxChar
*start
= c_str();
1215 *val
= wxStrtoul(start
, &end
, base
);
1217 // return TRUE only if scan was stopped by the terminating NUL and if the
1218 // string was not empty to start with
1219 return !*end
&& (end
!= start
);
1222 bool wxString::ToDouble(double *val
) const
1224 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToDouble") );
1226 const wxChar
*start
= c_str();
1228 *val
= wxStrtod(start
, &end
);
1230 // return TRUE only if scan was stopped by the terminating NUL and if the
1231 // string was not empty to start with
1232 return !*end
&& (end
!= start
);
1235 // ---------------------------------------------------------------------------
1237 // ---------------------------------------------------------------------------
1240 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1243 va_start(argptr
, pszFormat
);
1246 s
.PrintfV(pszFormat
, argptr
);
1254 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1257 s
.PrintfV(pszFormat
, argptr
);
1261 int wxString::Printf(const wxChar
*pszFormat
, ...)
1264 va_start(argptr
, pszFormat
);
1266 int iLen
= PrintfV(pszFormat
, argptr
);
1273 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1278 wxChar
*buf
= GetWriteBuf(size
+ 1);
1285 int len
= wxVsnprintf(buf
, size
, pszFormat
, argptr
);
1287 // some implementations of vsnprintf() don't NUL terminate the string
1288 // if there is not enough space for it so always do it manually
1289 buf
[size
] = _T('\0');
1295 // ok, there was enough space
1299 // still not enough, double it again
1303 // we could have overshot
1309 // ----------------------------------------------------------------------------
1310 // misc other operations
1311 // ----------------------------------------------------------------------------
1313 // returns TRUE if the string matches the pattern which may contain '*' and
1314 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1316 bool wxString::Matches(const wxChar
*pszMask
) const
1318 // I disable this code as it doesn't seem to be faster (in fact, it seems
1319 // to be much slower) than the old, hand-written code below and using it
1320 // here requires always linking with libregex even if the user code doesn't
1322 #if 0 // wxUSE_REGEX
1323 // first translate the shell-like mask into a regex
1325 pattern
.reserve(wxStrlen(pszMask
));
1337 pattern
+= _T(".*");
1348 // these characters are special in a RE, quote them
1349 // (however note that we don't quote '[' and ']' to allow
1350 // using them for Unix shell like matching)
1351 pattern
+= _T('\\');
1355 pattern
+= *pszMask
;
1363 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1364 #else // !wxUSE_REGEX
1365 // TODO: this is, of course, awfully inefficient...
1367 // the char currently being checked
1368 const wxChar
*pszTxt
= c_str();
1370 // the last location where '*' matched
1371 const wxChar
*pszLastStarInText
= NULL
;
1372 const wxChar
*pszLastStarInMask
= NULL
;
1375 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1376 switch ( *pszMask
) {
1378 if ( *pszTxt
== wxT('\0') )
1381 // pszTxt and pszMask will be incremented in the loop statement
1387 // remember where we started to be able to backtrack later
1388 pszLastStarInText
= pszTxt
;
1389 pszLastStarInMask
= pszMask
;
1391 // ignore special chars immediately following this one
1392 // (should this be an error?)
1393 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1396 // if there is nothing more, match
1397 if ( *pszMask
== wxT('\0') )
1400 // are there any other metacharacters in the mask?
1402 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1404 if ( pEndMask
!= NULL
) {
1405 // we have to match the string between two metachars
1406 uiLenMask
= pEndMask
- pszMask
;
1409 // we have to match the remainder of the string
1410 uiLenMask
= wxStrlen(pszMask
);
1413 wxString
strToMatch(pszMask
, uiLenMask
);
1414 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1415 if ( pMatch
== NULL
)
1418 // -1 to compensate "++" in the loop
1419 pszTxt
= pMatch
+ uiLenMask
- 1;
1420 pszMask
+= uiLenMask
- 1;
1425 if ( *pszMask
!= *pszTxt
)
1431 // match only if nothing left
1432 if ( *pszTxt
== wxT('\0') )
1435 // if we failed to match, backtrack if we can
1436 if ( pszLastStarInText
) {
1437 pszTxt
= pszLastStarInText
+ 1;
1438 pszMask
= pszLastStarInMask
;
1440 pszLastStarInText
= NULL
;
1442 // don't bother resetting pszLastStarInMask, it's unnecessary
1448 #endif // wxUSE_REGEX/!wxUSE_REGEX
1451 // Count the number of chars
1452 int wxString::Freq(wxChar ch
) const
1456 for (int i
= 0; i
< len
; i
++)
1458 if (GetChar(i
) == ch
)
1464 // convert to upper case, return the copy of the string
1465 wxString
wxString::Upper() const
1466 { wxString
s(*this); return s
.MakeUpper(); }
1468 // convert to lower case, return the copy of the string
1469 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1471 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1474 va_start(argptr
, pszFormat
);
1475 int iLen
= PrintfV(pszFormat
, argptr
);
1480 // ---------------------------------------------------------------------------
1481 // standard C++ library string functions
1482 // ---------------------------------------------------------------------------
1484 #ifdef wxSTD_STRING_COMPATIBILITY
1486 void wxString::resize(size_t nSize
, wxChar ch
)
1488 size_t len
= length();
1494 else if ( nSize
> len
)
1496 *this += wxString(ch
, nSize
- len
);
1498 //else: we have exactly the specified length, nothing to do
1501 void wxString::swap(wxString
& str
)
1503 // this is slightly less efficient than fiddling with m_pchData directly,
1504 // but it is still quite efficient as we don't copy the string here because
1505 // ref count always stays positive
1511 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1513 wxASSERT( str
.GetStringData()->IsValid() );
1514 wxASSERT( nPos
<= Len() );
1516 if ( !str
.IsEmpty() ) {
1518 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1519 wxStrncpy(pc
, c_str(), nPos
);
1520 wxStrcpy(pc
+ nPos
, str
);
1521 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1522 strTmp
.UngetWriteBuf();
1529 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1531 wxASSERT( str
.GetStringData()->IsValid() );
1532 wxASSERT( nStart
<= Len() );
1534 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1536 return p
== NULL
? npos
: p
- c_str();
1539 // VC++ 1.5 can't cope with the default argument in the header.
1540 #if !defined(__VISUALC__) || defined(__WIN32__)
1541 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1543 return find(wxString(sz
, n
), nStart
);
1547 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1548 #if !defined(__BORLANDC__)
1549 size_t wxString::find(wxChar ch
, size_t nStart
) const
1551 wxASSERT( nStart
<= Len() );
1553 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1555 return p
== NULL
? npos
: p
- c_str();
1559 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1561 wxASSERT( str
.GetStringData()->IsValid() );
1562 wxASSERT( nStart
== npos
|| nStart
<= Len() );
1564 // TODO could be made much quicker than that
1565 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1566 while ( p
>= c_str() + str
.Len() ) {
1567 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1568 return p
- str
.Len() - c_str();
1575 // VC++ 1.5 can't cope with the default argument in the header.
1576 #if !defined(__VISUALC__) || defined(__WIN32__)
1577 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1579 return rfind(wxString(sz
, n
== npos
? wxSTRING_MAXLEN
: n
), nStart
);
1582 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1584 if ( nStart
== npos
)
1590 wxASSERT( nStart
<= Len() );
1593 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1598 size_t result
= p
- c_str();
1599 return ( result
> nStart
) ? npos
: result
;
1603 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1605 const wxChar
*start
= c_str() + nStart
;
1606 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1608 return firstOf
- c_str();
1613 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1615 if ( nStart
== npos
)
1621 wxASSERT( nStart
<= Len() );
1624 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1626 if ( wxStrchr(sz
, *p
) )
1633 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1635 if ( nStart
== npos
)
1641 wxASSERT( nStart
<= Len() );
1644 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1645 if ( nAccept
>= length() - nStart
)
1651 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1653 wxASSERT( nStart
<= Len() );
1655 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1664 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1666 if ( nStart
== npos
)
1672 wxASSERT( nStart
<= Len() );
1675 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1677 if ( !wxStrchr(sz
, *p
) )
1684 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1686 if ( nStart
== npos
)
1692 wxASSERT( nStart
<= Len() );
1695 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1704 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1706 wxString
strTmp(c_str(), nStart
);
1707 if ( nLen
!= npos
) {
1708 wxASSERT( nStart
+ nLen
<= Len() );
1710 strTmp
.append(c_str() + nStart
+ nLen
);
1717 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1719 wxASSERT_MSG( nStart
+ nLen
<= Len(),
1720 _T("index out of bounds in wxString::replace") );
1723 strTmp
.Alloc(Len()); // micro optimisation to avoid multiple mem allocs
1726 strTmp
.append(c_str(), nStart
);
1727 strTmp
<< sz
<< c_str() + nStart
+ nLen
;
1733 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1735 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1738 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1739 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1741 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1744 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1745 const wxChar
* sz
, size_t nCount
)
1747 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1750 #endif //std::string compatibility
1752 // ============================================================================
1754 // ============================================================================
1756 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1757 #define ARRAY_MAXSIZE_INCREMENT 4096
1759 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1760 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1763 #define STRING(p) ((wxString *)(&(p)))
1766 void wxArrayString::Init(bool autoSort
)
1770 m_pItems
= (wxChar
**) NULL
;
1771 m_autoSort
= autoSort
;
1775 wxArrayString::wxArrayString(const wxArrayString
& src
)
1777 Init(src
.m_autoSort
);
1782 // assignment operator
1783 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1790 m_autoSort
= src
.m_autoSort
;
1795 void wxArrayString::Copy(const wxArrayString
& src
)
1797 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1798 Alloc(src
.m_nCount
);
1800 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1805 void wxArrayString::Grow(size_t nIncrement
)
1807 // only do it if no more place
1808 if ( (m_nSize
- m_nCount
) < nIncrement
) {
1809 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
1810 // be never resized!
1811 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
1812 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
1815 if ( m_nSize
== 0 ) {
1816 // was empty, alloc some memory
1817 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1818 if (m_nSize
< nIncrement
)
1819 m_nSize
= nIncrement
;
1820 m_pItems
= new wxChar
*[m_nSize
];
1823 // otherwise when it's called for the first time, nIncrement would be 0
1824 // and the array would never be expanded
1825 // add 50% but not too much
1826 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1827 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1828 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1829 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1830 if ( nIncrement
< ndefIncrement
)
1831 nIncrement
= ndefIncrement
;
1832 m_nSize
+= nIncrement
;
1833 wxChar
**pNew
= new wxChar
*[m_nSize
];
1835 // copy data to new location
1836 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1838 // delete old memory (but do not release the strings!)
1839 wxDELETEA(m_pItems
);
1846 void wxArrayString::Free()
1848 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1849 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1853 // deletes all the strings from the list
1854 void wxArrayString::Empty()
1861 // as Empty, but also frees memory
1862 void wxArrayString::Clear()
1869 wxDELETEA(m_pItems
);
1873 wxArrayString::~wxArrayString()
1877 wxDELETEA(m_pItems
);
1880 // pre-allocates memory (frees the previous data!)
1881 void wxArrayString::Alloc(size_t nSize
)
1883 // only if old buffer was not big enough
1884 if ( nSize
> m_nSize
) {
1886 wxDELETEA(m_pItems
);
1887 m_pItems
= new wxChar
*[nSize
];
1894 // minimizes the memory usage by freeing unused memory
1895 void wxArrayString::Shrink()
1897 // only do it if we have some memory to free
1898 if( m_nCount
< m_nSize
) {
1899 // allocates exactly as much memory as we need
1900 wxChar
**pNew
= new wxChar
*[m_nCount
];
1902 // copy data to new location
1903 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1909 // return a wxString[] as required for some control ctors.
1910 wxString
* wxArrayString::GetStringArray() const
1912 wxString
*array
= 0;
1916 array
= new wxString
[m_nCount
];
1917 for( size_t i
= 0; i
< m_nCount
; i
++ )
1918 array
[i
] = m_pItems
[i
];
1924 // searches the array for an item (forward or backwards)
1925 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
1928 // use binary search in the sorted array
1929 wxASSERT_MSG( bCase
&& !bFromEnd
,
1930 wxT("search parameters ignored for auto sorted array") );
1939 res
= wxStrcmp(sz
, m_pItems
[i
]);
1951 // use linear search in unsorted array
1953 if ( m_nCount
> 0 ) {
1954 size_t ui
= m_nCount
;
1956 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1963 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1964 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1973 // add item at the end
1974 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
1977 // insert the string at the correct position to keep the array sorted
1985 res
= wxStrcmp(str
, m_pItems
[i
]);
1996 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
1998 Insert(str
, lo
, nInsert
);
2003 wxASSERT( str
.GetStringData()->IsValid() );
2007 for (size_t i
= 0; i
< nInsert
; i
++)
2009 // the string data must not be deleted!
2010 str
.GetStringData()->Lock();
2013 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2015 size_t ret
= m_nCount
;
2016 m_nCount
+= nInsert
;
2021 // add item at the given position
2022 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2024 wxASSERT( str
.GetStringData()->IsValid() );
2026 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2027 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2028 wxT("array size overflow in wxArrayString::Insert") );
2032 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2033 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2035 for (size_t i
= 0; i
< nInsert
; i
++)
2037 str
.GetStringData()->Lock();
2038 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2040 m_nCount
+= nInsert
;
2044 void wxArrayString::SetCount(size_t count
)
2049 while ( m_nCount
< count
)
2050 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2053 // removes item from array (by index)
2054 void wxArrayString::Remove(size_t nIndex
, size_t nRemove
)
2056 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2057 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2058 wxT("removing too many elements in wxArrayString::Remove") );
2061 for (size_t i
= 0; i
< nRemove
; i
++)
2062 Item(nIndex
+ i
).GetStringData()->Unlock();
2064 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2065 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2066 m_nCount
-= nRemove
;
2069 // removes item from array (by value)
2070 void wxArrayString::Remove(const wxChar
*sz
)
2072 int iIndex
= Index(sz
);
2074 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2075 wxT("removing inexistent element in wxArrayString::Remove") );
2080 // ----------------------------------------------------------------------------
2082 // ----------------------------------------------------------------------------
2084 // we can only sort one array at a time with the quick-sort based
2087 // need a critical section to protect access to gs_compareFunction and
2088 // gs_sortAscending variables
2089 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2091 // call this before the value of the global sort vars is changed/after
2092 // you're finished with them
2093 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2094 gs_critsectStringSort = new wxCriticalSection; \
2095 gs_critsectStringSort->Enter()
2096 #define END_SORT() gs_critsectStringSort->Leave(); \
2097 delete gs_critsectStringSort; \
2098 gs_critsectStringSort = NULL
2100 #define START_SORT()
2102 #endif // wxUSE_THREADS
2104 // function to use for string comparaison
2105 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2107 // if we don't use the compare function, this flag tells us if we sort the
2108 // array in ascending or descending order
2109 static bool gs_sortAscending
= TRUE
;
2111 // function which is called by quick sort
2112 extern "C" int wxC_CALLING_CONV
// LINKAGEMODE
2113 wxStringCompareFunction(const void *first
, const void *second
)
2115 wxString
*strFirst
= (wxString
*)first
;
2116 wxString
*strSecond
= (wxString
*)second
;
2118 if ( gs_compareFunction
) {
2119 return gs_compareFunction(*strFirst
, *strSecond
);
2122 // maybe we should use wxStrcoll
2123 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
2125 return gs_sortAscending
? result
: -result
;
2129 // sort array elements using passed comparaison function
2130 void wxArrayString::Sort(CompareFunction compareFunction
)
2134 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2135 gs_compareFunction
= compareFunction
;
2139 // reset it to NULL so that Sort(bool) will work the next time
2140 gs_compareFunction
= NULL
;
2145 void wxArrayString::Sort(bool reverseOrder
)
2149 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2150 gs_sortAscending
= !reverseOrder
;
2157 void wxArrayString::DoSort()
2159 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2161 // just sort the pointers using qsort() - of course it only works because
2162 // wxString() *is* a pointer to its data
2163 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2166 bool wxArrayString::operator==(const wxArrayString
& a
) const
2168 if ( m_nCount
!= a
.m_nCount
)
2171 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2173 if ( Item(n
) != a
[n
] )