1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxString class
4 // Author: Vadim Zeitlin, Ryan Norton
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // (c) 2004 Ryan Norton <wxprojects@comcast.net>
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
13 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
14 #pragma implementation "string.h"
19 * 1) all empty strings use g_strEmpty, nRefs = -1 (set in Init())
20 * 2) AllocBuffer() sets nRefs to 1, Lock() increments it by one
21 * 3) Unlock() decrements nRefs and frees memory if it goes to 0
24 // ===========================================================================
25 // headers, declarations, constants
26 // ===========================================================================
28 // For compilers that support precompilation, includes "wx.h".
29 #include "wx/wxprec.h"
37 #include "wx/string.h"
39 #include "wx/thread.h"
50 // allocating extra space for each string consumes more memory but speeds up
51 // the concatenation operations (nLen is the current string's length)
52 // NB: EXTRA_ALLOC must be >= 0!
53 #define EXTRA_ALLOC (19 - nLen % 16)
55 // ---------------------------------------------------------------------------
56 // static class variables definition
57 // ---------------------------------------------------------------------------
60 //According to STL _must_ be a -1 size_t
61 const size_t wxStringBase::npos
= (size_t) -1;
64 // ----------------------------------------------------------------------------
66 // ----------------------------------------------------------------------------
70 extern const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= _T("");
74 // for an empty string, GetStringData() will return this address: this
75 // structure has the same layout as wxStringData and it's data() method will
76 // return the empty string (dummy pointer)
81 } g_strEmpty
= { {-1, 0, 0}, wxT('\0') };
83 // empty C style string: points to 'string data' byte of g_strEmpty
84 extern const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= &g_strEmpty
.dummy
;
88 // ----------------------------------------------------------------------------
90 // ----------------------------------------------------------------------------
92 #if wxUSE_STD_IOSTREAM
94 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
97 // ATTN: you can _not_ use both of these in the same program!
101 wxSTD istream
& operator>>(wxSTD istream
& is
, wxString
& WXUNUSED(str
))
106 streambuf
*sb
= is
.rdbuf();
109 int ch
= sb
->sbumpc ();
111 is
.setstate(ios::eofbit
);
114 else if ( isspace(ch
) ) {
126 if ( str
.length() == 0 )
127 is
.setstate(ios::failbit
);
132 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
138 #endif // wxUSE_STD_IOSTREAM
140 // ----------------------------------------------------------------------------
142 // ----------------------------------------------------------------------------
144 // this small class is used to gather statistics for performance tuning
145 //#define WXSTRING_STATISTICS
146 #ifdef WXSTRING_STATISTICS
150 Averager(const wxChar
*sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
152 { wxPrintf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
154 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
157 size_t m_nCount
, m_nTotal
;
159 } g_averageLength("allocation size"),
160 g_averageSummandLength("summand length"),
161 g_averageConcatHit("hit probability in concat"),
162 g_averageInitialLength("initial string length");
164 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
166 #define STATISTICS_ADD(av, val)
167 #endif // WXSTRING_STATISTICS
171 // ===========================================================================
172 // wxStringData class deallocation
173 // ===========================================================================
175 #if defined(__VISUALC__) && defined(_MT) && !defined(_DLL)
176 # pragma message (__FILE__ ": building with Multithreaded non DLL runtime has a performance impact on wxString!")
177 void wxStringData::Free()
183 // ===========================================================================
185 // ===========================================================================
187 // takes nLength elements of psz starting at nPos
188 void wxStringBase::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
192 // if the length is not given, assume the string to be NUL terminated
193 if ( nLength
== npos
) {
194 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
196 nLength
= wxStrlen(psz
+ nPos
);
199 STATISTICS_ADD(InitialLength
, nLength
);
202 // trailing '\0' is written in AllocBuffer()
203 if ( !AllocBuffer(nLength
) ) {
204 wxFAIL_MSG( _T("out of memory in wxStringBase::InitWith") );
207 wxTmemcpy(m_pchData
, psz
+ nPos
, nLength
);
211 // poor man's iterators are "void *" pointers
212 wxStringBase::wxStringBase(const void *pStart
, const void *pEnd
)
214 InitWith((const wxChar
*)pStart
, 0,
215 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
218 wxStringBase::wxStringBase(size_type n
, wxChar ch
)
224 // ---------------------------------------------------------------------------
226 // ---------------------------------------------------------------------------
228 // allocates memory needed to store a C string of length nLen
229 bool wxStringBase::AllocBuffer(size_t nLen
)
231 // allocating 0 sized buffer doesn't make sense, all empty strings should
233 wxASSERT( nLen
> 0 );
235 // make sure that we don't overflow
236 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
237 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
239 STATISTICS_ADD(Length
, nLen
);
242 // 1) one extra character for '\0' termination
243 // 2) sizeof(wxStringData) for housekeeping info
244 wxStringData
* pData
= (wxStringData
*)
245 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
247 if ( pData
== NULL
) {
248 // allocation failures are handled by the caller
253 pData
->nDataLength
= nLen
;
254 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
255 m_pchData
= pData
->data(); // data starts after wxStringData
256 m_pchData
[nLen
] = wxT('\0');
260 // must be called before changing this string
261 bool wxStringBase::CopyBeforeWrite()
263 wxStringData
* pData
= GetStringData();
265 if ( pData
->IsShared() ) {
266 pData
->Unlock(); // memory not freed because shared
267 size_t nLen
= pData
->nDataLength
;
268 if ( !AllocBuffer(nLen
) ) {
269 // allocation failures are handled by the caller
272 wxTmemcpy(m_pchData
, pData
->data(), nLen
);
275 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
280 // must be called before replacing contents of this string
281 bool wxStringBase::AllocBeforeWrite(size_t nLen
)
283 wxASSERT( nLen
!= 0 ); // doesn't make any sense
285 // must not share string and must have enough space
286 wxStringData
* pData
= GetStringData();
287 if ( pData
->IsShared() || pData
->IsEmpty() ) {
288 // can't work with old buffer, get new one
290 if ( !AllocBuffer(nLen
) ) {
291 // allocation failures are handled by the caller
296 if ( nLen
> pData
->nAllocLength
) {
297 // realloc the buffer instead of calling malloc() again, this is more
299 STATISTICS_ADD(Length
, nLen
);
303 pData
= (wxStringData
*)
304 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
306 if ( pData
== NULL
) {
307 // allocation failures are handled by the caller
308 // keep previous data since reallocation failed
312 pData
->nAllocLength
= nLen
;
313 m_pchData
= pData
->data();
316 // now we have enough space, just update the string length
317 pData
->nDataLength
= nLen
;
320 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
325 wxStringBase
& wxStringBase::append(size_t n
, wxChar ch
)
327 size_type len
= length();
329 if ( !CopyBeforeWrite() || !Alloc(len
+ n
) ) {
330 wxFAIL_MSG( _T("out of memory in wxStringBase::append") );
332 GetStringData()->nDataLength
= len
+ n
;
333 m_pchData
[len
+ n
] = '\0';
334 for ( size_t i
= 0; i
< n
; ++i
)
335 m_pchData
[len
+ i
] = ch
;
339 void wxStringBase::resize(size_t nSize
, wxChar ch
)
341 size_t len
= length();
345 erase(begin() + nSize
, end());
347 else if ( nSize
> len
)
349 append(nSize
- len
, ch
);
351 //else: we have exactly the specified length, nothing to do
354 // allocate enough memory for nLen characters
355 bool wxStringBase::Alloc(size_t nLen
)
357 wxStringData
*pData
= GetStringData();
358 if ( pData
->nAllocLength
<= nLen
) {
359 if ( pData
->IsEmpty() ) {
362 wxStringData
* pData
= (wxStringData
*)
363 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
365 if ( pData
== NULL
) {
366 // allocation failure handled by caller
371 pData
->nDataLength
= 0;
372 pData
->nAllocLength
= nLen
;
373 m_pchData
= pData
->data(); // data starts after wxStringData
374 m_pchData
[0u] = wxT('\0');
376 else if ( pData
->IsShared() ) {
377 pData
->Unlock(); // memory not freed because shared
378 size_t nOldLen
= pData
->nDataLength
;
379 if ( !AllocBuffer(nLen
) ) {
380 // allocation failure handled by caller
383 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
388 pData
= (wxStringData
*)
389 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
391 if ( pData
== NULL
) {
392 // allocation failure handled by caller
393 // keep previous data since reallocation failed
397 // it's not important if the pointer changed or not (the check for this
398 // is not faster than assigning to m_pchData in all cases)
399 pData
->nAllocLength
= nLen
;
400 m_pchData
= pData
->data();
403 //else: we've already got enough
407 wxStringBase::iterator
wxStringBase::begin()
414 wxStringBase::iterator
wxStringBase::end()
418 return m_pchData
+ length();
421 wxStringBase::iterator
wxStringBase::erase(iterator it
)
423 size_type idx
= it
- begin();
425 return begin() + idx
;
428 wxStringBase
& wxStringBase::erase(size_t nStart
, size_t nLen
)
430 wxASSERT(nStart
<= length());
431 size_t strLen
= length() - nStart
;
432 // delete nLen or up to the end of the string characters
433 nLen
= strLen
< nLen
? strLen
: nLen
;
434 wxString
strTmp(c_str(), nStart
);
435 strTmp
.append(c_str() + nStart
+ nLen
, length() - nStart
- nLen
);
441 wxStringBase
& wxStringBase::insert(size_t nPos
, const wxChar
*sz
, size_t n
)
443 wxASSERT( nPos
<= length() );
445 if ( n
== npos
) n
= wxStrlen(sz
);
446 if ( n
== 0 ) return *this;
448 if ( !CopyBeforeWrite() || !Alloc(length() + n
) ) {
449 wxFAIL_MSG( _T("out of memory in wxStringBase::insert") );
452 memmove(m_pchData
+ nPos
+ n
, m_pchData
+ nPos
,
453 (length() - nPos
) * sizeof(wxChar
));
454 memcpy(m_pchData
+ nPos
, sz
, n
* sizeof(wxChar
));
455 GetStringData()->nDataLength
= length() + n
;
456 m_pchData
[length()] = '\0';
461 void wxStringBase::swap(wxStringBase
& str
)
463 wxChar
* tmp
= str
.m_pchData
;
464 str
.m_pchData
= m_pchData
;
468 size_t wxStringBase::find(const wxStringBase
& str
, size_t nStart
) const
470 wxASSERT( str
.GetStringData()->IsValid() );
471 wxASSERT( nStart
<= length() );
474 const wxChar
* p
= (const wxChar
*)wxTmemchr(c_str() + nStart
,
481 while(p
- c_str() + str
.length() <= length() &&
482 wxTmemcmp(p
, str
.c_str(), str
.length()) )
485 p
= (const wxChar
*)wxTmemchr(++p
,
487 length() - (p
- c_str()));
493 return (p
- c_str() + str
.length() <= length()) ? p
- c_str() : npos
;
496 size_t wxStringBase::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
498 return find(wxStringBase(sz
, n
), nStart
);
501 size_t wxStringBase::find(wxChar ch
, size_t nStart
) const
503 wxASSERT( nStart
<= length() );
505 const wxChar
*p
= (const wxChar
*)wxTmemchr(c_str() + nStart
, ch
, length() - nStart
);
507 return p
== NULL
? npos
: p
- c_str();
510 size_t wxStringBase::rfind(const wxStringBase
& str
, size_t nStart
) const
512 wxASSERT( str
.GetStringData()->IsValid() );
513 wxASSERT( nStart
== npos
|| nStart
<= length() );
515 if ( length() >= str
.length() )
517 // avoids a corner case later
518 if ( length() == 0 && str
.length() == 0 )
521 // "top" is the point where search starts from
522 size_t top
= length() - str
.length();
524 if ( nStart
== npos
)
525 nStart
= length() - 1;
529 const wxChar
*cursor
= c_str() + top
;
532 if ( wxTmemcmp(cursor
, str
.c_str(),
535 return cursor
- c_str();
537 } while ( cursor
-- > c_str() );
543 size_t wxStringBase::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
545 return rfind(wxStringBase(sz
, n
), nStart
);
548 size_t wxStringBase::rfind(wxChar ch
, size_t nStart
) const
550 if ( nStart
== npos
)
556 wxASSERT( nStart
<= length() );
559 const wxChar
*actual
;
560 for ( actual
= c_str() + ( nStart
== npos
? length() : nStart
+ 1 );
561 actual
> c_str(); --actual
)
563 if ( *(actual
- 1) == ch
)
564 return (actual
- 1) - c_str();
570 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
) const
572 wxASSERT(nStart
<= length());
574 size_t len
= wxStrlen(sz
);
577 for(i
= nStart
; i
< this->length(); ++i
)
579 if (wxTmemchr(sz
, *(c_str() + i
), len
))
583 if(i
== this->length())
589 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
,
592 return find_first_of(wxStringBase(sz
, n
), nStart
);
595 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
) const
597 if ( nStart
== npos
)
599 nStart
= length() - 1;
603 wxASSERT_MSG( nStart
<= length(),
604 _T("invalid index in find_last_of()") );
607 size_t len
= wxStrlen(sz
);
609 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
611 if ( wxTmemchr(sz
, *p
, len
) )
618 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
,
621 return find_last_of(wxStringBase(sz
, n
), nStart
);
624 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
626 if ( nStart
== npos
)
632 wxASSERT( nStart
<= length() );
635 size_t len
= wxStrlen(sz
);
638 for(i
= nStart
; i
< this->length(); ++i
)
640 if (!wxTmemchr(sz
, *(c_str() + i
), len
))
644 if(i
== this->length())
650 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
,
653 return find_first_not_of(wxStringBase(sz
, n
), nStart
);
656 size_t wxStringBase::find_first_not_of(wxChar ch
, size_t nStart
) const
658 wxASSERT( nStart
<= length() );
660 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
669 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
671 if ( nStart
== npos
)
673 nStart
= length() - 1;
677 wxASSERT( nStart
<= length() );
680 size_t len
= wxStrlen(sz
);
682 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
684 if ( !wxTmemchr(sz
, *p
,len
) )
691 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
,
694 return find_last_not_of(wxStringBase(sz
, n
), nStart
);
697 size_t wxStringBase::find_last_not_of(wxChar ch
, size_t nStart
) const
699 if ( nStart
== npos
)
701 nStart
= length() - 1;
705 wxASSERT( nStart
<= length() );
708 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
717 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
720 wxASSERT_MSG( nStart
<= length(),
721 _T("index out of bounds in wxStringBase::replace") );
722 size_t strLen
= length() - nStart
;
723 nLen
= strLen
< nLen
? strLen
: nLen
;
726 strTmp
.reserve(length()); // micro optimisation to avoid multiple mem allocs
729 strTmp
.append(c_str(), nStart
);
731 strTmp
.append(c_str() + nStart
+ nLen
);
737 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
738 size_t nCount
, wxChar ch
)
740 return replace(nStart
, nLen
, wxStringBase(nCount
, ch
).c_str());
743 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
744 const wxStringBase
& str
,
745 size_t nStart2
, size_t nLen2
)
747 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
750 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
751 const wxChar
* sz
, size_t nCount
)
753 return replace(nStart
, nLen
, wxStringBase(sz
, nCount
).c_str());
756 wxStringBase
wxStringBase::substr(size_t nStart
, size_t nLen
) const
759 nLen
= length() - nStart
;
760 return wxStringBase(*this, nStart
, nLen
);
763 // assigns one string to another
764 wxStringBase
& wxStringBase::operator=(const wxStringBase
& stringSrc
)
766 wxASSERT( stringSrc
.GetStringData()->IsValid() );
768 // don't copy string over itself
769 if ( m_pchData
!= stringSrc
.m_pchData
) {
770 if ( stringSrc
.GetStringData()->IsEmpty() ) {
775 GetStringData()->Unlock();
776 m_pchData
= stringSrc
.m_pchData
;
777 GetStringData()->Lock();
784 // assigns a single character
785 wxStringBase
& wxStringBase::operator=(wxChar ch
)
787 if ( !AssignCopy(1, &ch
) ) {
788 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(wxChar)") );
794 wxStringBase
& wxStringBase::operator=(const wxChar
*psz
)
796 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
797 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(const wxChar *)") );
802 // helper function: does real copy
803 bool wxStringBase::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
805 if ( nSrcLen
== 0 ) {
809 if ( !AllocBeforeWrite(nSrcLen
) ) {
810 // allocation failure handled by caller
813 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
814 GetStringData()->nDataLength
= nSrcLen
;
815 m_pchData
[nSrcLen
] = wxT('\0');
820 // ---------------------------------------------------------------------------
821 // string concatenation
822 // ---------------------------------------------------------------------------
824 // add something to this string
825 bool wxStringBase::ConcatSelf(size_t nSrcLen
, const wxChar
*pszSrcData
,
828 STATISTICS_ADD(SummandLength
, nSrcLen
);
830 nSrcLen
= nSrcLen
< nMaxLen
? nSrcLen
: nMaxLen
;
832 // concatenating an empty string is a NOP
834 wxStringData
*pData
= GetStringData();
835 size_t nLen
= pData
->nDataLength
;
836 size_t nNewLen
= nLen
+ nSrcLen
;
838 // alloc new buffer if current is too small
839 if ( pData
->IsShared() ) {
840 STATISTICS_ADD(ConcatHit
, 0);
842 // we have to allocate another buffer
843 wxStringData
* pOldData
= GetStringData();
844 if ( !AllocBuffer(nNewLen
) ) {
845 // allocation failure handled by caller
848 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
851 else if ( nNewLen
> pData
->nAllocLength
) {
852 STATISTICS_ADD(ConcatHit
, 0);
855 // we have to grow the buffer
856 if ( capacity() < nNewLen
) {
857 // allocation failure handled by caller
862 STATISTICS_ADD(ConcatHit
, 1);
864 // the buffer is already big enough
867 // should be enough space
868 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
870 // fast concatenation - all is done in our buffer
871 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
873 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
874 GetStringData()->nDataLength
= nNewLen
; // and fix the length
876 //else: the string to append was empty
880 // ---------------------------------------------------------------------------
881 // simple sub-string extraction
882 // ---------------------------------------------------------------------------
884 // helper function: clone the data attached to this string
885 bool wxStringBase::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
887 if ( nCopyLen
== 0 ) {
891 if ( !dest
.AllocBuffer(nCopyLen
) ) {
892 // allocation failure handled by caller
895 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
902 #if !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
905 #define STRINGCLASS wxStringBase
907 #define STRINGCLASS wxString
910 static inline int wxDoCmp(const wxChar
* s1
, size_t l1
,
911 const wxChar
* s2
, size_t l2
)
914 return wxTmemcmp(s1
, s2
, l1
);
917 int ret
= wxTmemcmp(s1
, s2
, l1
);
918 return ret
== 0 ? -1 : ret
;
922 int ret
= wxTmemcmp(s1
, s2
, l2
);
923 return ret
== 0 ? +1 : ret
;
927 int STRINGCLASS::compare(const wxStringBase
& str
) const
929 return ::wxDoCmp(data(), length(), str
.data(), str
.length());
932 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
933 const wxStringBase
& str
) const
935 wxASSERT(nStart
<= length());
936 size_type strLen
= length() - nStart
;
937 nLen
= strLen
< nLen
? strLen
: nLen
;
938 return ::wxDoCmp(data() + nStart
, nLen
, str
.data(), str
.length());
941 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
942 const wxStringBase
& str
,
943 size_t nStart2
, size_t nLen2
) const
945 wxASSERT(nStart
<= length());
946 wxASSERT(nStart2
<= str
.length());
947 size_type strLen
= length() - nStart
,
948 strLen2
= str
.length() - nStart2
;
949 nLen
= strLen
< nLen
? strLen
: nLen
;
950 nLen2
= strLen2
< nLen2
? strLen2
: nLen2
;
951 return ::wxDoCmp(data() + nStart
, nLen
, str
.data() + nStart2
, nLen2
);
954 int STRINGCLASS::compare(const wxChar
* sz
) const
956 size_t nLen
= wxStrlen(sz
);
957 return ::wxDoCmp(data(), length(), sz
, nLen
);
960 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
961 const wxChar
* sz
, size_t nCount
) const
963 wxASSERT(nStart
<= length());
964 size_type strLen
= length() - nStart
;
965 nLen
= strLen
< nLen
? strLen
: nLen
;
967 nCount
= wxStrlen(sz
);
969 return ::wxDoCmp(data() + nStart
, nLen
, sz
, nCount
);
974 #endif // !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
976 // ===========================================================================
977 // wxString class core
978 // ===========================================================================
980 // ---------------------------------------------------------------------------
981 // construction and conversion
982 // ---------------------------------------------------------------------------
986 // from multibyte string
987 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
989 // if nLength != npos, then we have to make a NULL-terminated copy
990 // of first nLength bytes of psz first because the input buffer to MB2WC
991 // must always be NULL-terminated:
992 wxCharBuffer
inBuf((const char *)NULL
);
995 wxASSERT( psz
!= NULL
);
996 wxCharBuffer
tmp(nLength
);
997 memcpy(tmp
.data(), psz
, nLength
);
998 tmp
.data()[nLength
] = '\0';
1003 // first get the size of the buffer we need
1007 // calculate the needed size ourselves or use the provided one
1008 if (nLength
== npos
)
1015 // nothing to convert
1021 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
1025 wxWCharBuffer theBuffer
= conv
.cMB2WC(psz
, nLen
, &nRealSize
);
1029 assign( theBuffer
.data() , nRealSize
- 1 );
1033 //Convert wxString in Unicode mode to a multi-byte string
1034 const wxCharBuffer
wxString::mb_str(wxMBConv
& conv
) const
1037 return conv
.cWC2MB(c_str(), length(), &dwOutSize
);
1044 wxString::wxString(const wchar_t *pwz
, wxMBConv
& conv
, size_t nLength
)
1046 // if nLength != npos, then we have to make a NULL-terminated copy
1047 // of first nLength chars of psz first because the input buffer to WC2MB
1048 // must always be NULL-terminated:
1049 wxWCharBuffer
inBuf((const wchar_t *)NULL
);
1050 if (nLength
!= npos
)
1052 wxASSERT( pwz
!= NULL
);
1053 wxWCharBuffer
tmp(nLength
);
1054 memcpy(tmp
.data(), pwz
, nLength
* sizeof(wchar_t));
1055 tmp
.data()[nLength
] = '\0';
1060 // first get the size of the buffer we need
1064 // calculate the needed size ourselves or use the provided one
1065 if (nLength
== npos
)
1066 nLen
= wxWcslen(pwz
);
1072 // nothing to convert
1077 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
1081 wxCharBuffer theBuffer
= conv
.cWC2MB(pwz
, nLen
, &nRealSize
);
1085 assign( theBuffer
.data() , nRealSize
- 1 );
1089 //Converts this string to a wide character string if unicode
1090 //mode is not enabled and wxUSE_WCHAR_T is enabled
1091 const wxWCharBuffer
wxString::wc_str(wxMBConv
& conv
) const
1094 return conv
.cMB2WC(c_str(), length(), &dwOutSize
);
1097 #endif // wxUSE_WCHAR_T
1099 #endif // Unicode/ANSI
1101 // shrink to minimal size (releasing extra memory)
1102 bool wxString::Shrink()
1104 wxString
tmp(begin(), end());
1106 return tmp
.length() == length();
1110 // get the pointer to writable buffer of (at least) nLen bytes
1111 wxChar
*wxString::GetWriteBuf(size_t nLen
)
1113 if ( !AllocBeforeWrite(nLen
) ) {
1114 // allocation failure handled by caller
1118 wxASSERT( GetStringData()->nRefs
== 1 );
1119 GetStringData()->Validate(false);
1124 // put string back in a reasonable state after GetWriteBuf
1125 void wxString::UngetWriteBuf()
1127 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
1128 GetStringData()->Validate(true);
1131 void wxString::UngetWriteBuf(size_t nLen
)
1133 GetStringData()->nDataLength
= nLen
;
1134 GetStringData()->Validate(true);
1138 // ---------------------------------------------------------------------------
1140 // ---------------------------------------------------------------------------
1142 // all functions are inline in string.h
1144 // ---------------------------------------------------------------------------
1145 // assignment operators
1146 // ---------------------------------------------------------------------------
1150 // same as 'signed char' variant
1151 wxString
& wxString::operator=(const unsigned char* psz
)
1153 *this = (const char *)psz
;
1158 wxString
& wxString::operator=(const wchar_t *pwz
)
1169 * concatenation functions come in 5 flavours:
1171 * char + string and string + char
1172 * C str + string and string + C str
1175 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
1178 wxASSERT( str1
.GetStringData()->IsValid() );
1179 wxASSERT( str2
.GetStringData()->IsValid() );
1188 wxString
operator+(const wxString
& str
, wxChar ch
)
1191 wxASSERT( str
.GetStringData()->IsValid() );
1200 wxString
operator+(wxChar ch
, const wxString
& str
)
1203 wxASSERT( str
.GetStringData()->IsValid() );
1212 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
1215 wxASSERT( str
.GetStringData()->IsValid() );
1219 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
1220 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1228 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
1231 wxASSERT( str
.GetStringData()->IsValid() );
1235 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
1236 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1244 // ===========================================================================
1245 // other common string functions
1246 // ===========================================================================
1248 int wxString::Cmp(const wxString
& s
) const
1253 int wxString::Cmp(const wxChar
* psz
) const
1255 return compare(psz
);
1258 static inline int wxDoCmpNoCase(const wxChar
* s1
, size_t l1
,
1259 const wxChar
* s2
, size_t l2
)
1265 for(i
= 0; i
< l1
; ++i
)
1267 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1270 return i
== l1
? 0 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1274 for(i
= 0; i
< l1
; ++i
)
1276 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1279 return i
== l1
? -1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1283 for(i
= 0; i
< l2
; ++i
)
1285 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1288 return i
== l2
? 1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1292 int wxString::CmpNoCase(const wxString
& s
) const
1294 return wxDoCmpNoCase(data(), length(), s
.data(), s
.length());
1297 int wxString::CmpNoCase(const wxChar
* psz
) const
1299 int nLen
= wxStrlen(psz
);
1301 return wxDoCmpNoCase(data(), length(), psz
, nLen
);
1308 #ifndef __SCHAR_MAX__
1309 #define __SCHAR_MAX__ 127
1313 wxString
wxString::FromAscii(const char *ascii
)
1316 return wxEmptyString
;
1318 size_t len
= strlen( ascii
);
1323 wxStringBuffer
buf(res
, len
);
1325 wchar_t *dest
= buf
;
1329 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
1337 wxString
wxString::FromAscii(const char ascii
)
1339 // What do we do with '\0' ?
1342 res
+= (wchar_t)(unsigned char) ascii
;
1347 const wxCharBuffer
wxString::ToAscii() const
1349 // this will allocate enough space for the terminating NUL too
1350 wxCharBuffer
buffer(length());
1353 char *dest
= buffer
.data();
1355 const wchar_t *pwc
= c_str();
1358 *dest
++ = (char)(*pwc
> SCHAR_MAX
? wxT('_') : *pwc
);
1360 // the output string can't have embedded NULs anyhow, so we can safely
1361 // stop at first of them even if we do have any
1371 // extract string of length nCount starting at nFirst
1372 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
1374 size_t nLen
= length();
1376 // default value of nCount is npos and means "till the end"
1377 if ( nCount
== npos
)
1379 nCount
= nLen
- nFirst
;
1382 // out-of-bounds requests return sensible things
1383 if ( nFirst
+ nCount
> nLen
)
1385 nCount
= nLen
- nFirst
;
1388 if ( nFirst
> nLen
)
1390 // AllocCopy() will return empty string
1394 wxString
dest(*this, nFirst
, nCount
);
1395 if ( dest
.length() != nCount
) {
1396 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
1402 // check that the string starts with prefix and return the rest of the string
1403 // in the provided pointer if it is not NULL, otherwise return false
1404 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
1406 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
1408 // first check if the beginning of the string matches the prefix: note
1409 // that we don't have to check that we don't run out of this string as
1410 // when we reach the terminating NUL, either prefix string ends too (and
1411 // then it's ok) or we break out of the loop because there is no match
1412 const wxChar
*p
= c_str();
1415 if ( *prefix
++ != *p
++ )
1424 // put the rest of the string into provided pointer
1431 // extract nCount last (rightmost) characters
1432 wxString
wxString::Right(size_t nCount
) const
1434 if ( nCount
> length() )
1437 wxString
dest(*this, length() - nCount
, nCount
);
1438 if ( dest
.length() != nCount
) {
1439 wxFAIL_MSG( _T("out of memory in wxString::Right") );
1444 // get all characters after the last occurence of ch
1445 // (returns the whole string if ch not found)
1446 wxString
wxString::AfterLast(wxChar ch
) const
1449 int iPos
= Find(ch
, true);
1450 if ( iPos
== wxNOT_FOUND
)
1453 str
= c_str() + iPos
+ 1;
1458 // extract nCount first (leftmost) characters
1459 wxString
wxString::Left(size_t nCount
) const
1461 if ( nCount
> length() )
1464 wxString
dest(*this, 0, nCount
);
1465 if ( dest
.length() != nCount
) {
1466 wxFAIL_MSG( _T("out of memory in wxString::Left") );
1471 // get all characters before the first occurence of ch
1472 // (returns the whole string if ch not found)
1473 wxString
wxString::BeforeFirst(wxChar ch
) const
1475 int iPos
= Find(ch
);
1476 if ( iPos
== wxNOT_FOUND
) iPos
= length();
1477 return wxString(*this, 0, iPos
);
1480 /// get all characters before the last occurence of ch
1481 /// (returns empty string if ch not found)
1482 wxString
wxString::BeforeLast(wxChar ch
) const
1485 int iPos
= Find(ch
, true);
1486 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
1487 str
= wxString(c_str(), iPos
);
1492 /// get all characters after the first occurence of ch
1493 /// (returns empty string if ch not found)
1494 wxString
wxString::AfterFirst(wxChar ch
) const
1497 int iPos
= Find(ch
);
1498 if ( iPos
!= wxNOT_FOUND
)
1499 str
= c_str() + iPos
+ 1;
1504 // replace first (or all) occurences of some substring with another one
1506 wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
1508 // if we tried to replace an empty string we'd enter an infinite loop below
1509 wxCHECK_MSG( szOld
&& *szOld
&& szNew
, 0,
1510 _T("wxString::Replace(): invalid parameter") );
1512 size_t uiCount
= 0; // count of replacements made
1514 size_t uiOldLen
= wxStrlen(szOld
);
1517 const wxChar
*pCurrent
= c_str();
1518 const wxChar
*pSubstr
;
1519 while ( *pCurrent
!= wxT('\0') ) {
1520 pSubstr
= wxStrstr(pCurrent
, szOld
);
1521 if ( pSubstr
== NULL
) {
1522 // strTemp is unused if no replacements were made, so avoid the copy
1526 strTemp
+= pCurrent
; // copy the rest
1527 break; // exit the loop
1530 // take chars before match
1531 size_type len
= strTemp
.length();
1532 strTemp
.append(pCurrent
, pSubstr
- pCurrent
);
1533 if ( strTemp
.length() != (size_t)(len
+ pSubstr
- pCurrent
) ) {
1534 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
1538 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
1543 if ( !bReplaceAll
) {
1544 strTemp
+= pCurrent
; // copy the rest
1545 break; // exit the loop
1550 // only done if there were replacements, otherwise would have returned above
1556 bool wxString::IsAscii() const
1558 const wxChar
*s
= (const wxChar
*) *this;
1560 if(!isascii(*s
)) return(false);
1566 bool wxString::IsWord() const
1568 const wxChar
*s
= (const wxChar
*) *this;
1570 if(!wxIsalpha(*s
)) return(false);
1576 bool wxString::IsNumber() const
1578 const wxChar
*s
= (const wxChar
*) *this;
1580 if ((s
[0] == wxT('-')) || (s
[0] == wxT('+'))) s
++;
1582 if(!wxIsdigit(*s
)) return(false);
1588 wxString
wxString::Strip(stripType w
) const
1591 if ( w
& leading
) s
.Trim(false);
1592 if ( w
& trailing
) s
.Trim(true);
1596 // ---------------------------------------------------------------------------
1598 // ---------------------------------------------------------------------------
1600 wxString
& wxString::MakeUpper()
1602 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1603 *it
= (wxChar
)wxToupper(*it
);
1608 wxString
& wxString::MakeLower()
1610 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1611 *it
= (wxChar
)wxTolower(*it
);
1616 // ---------------------------------------------------------------------------
1617 // trimming and padding
1618 // ---------------------------------------------------------------------------
1620 // some compilers (VC++ 6.0 not to name them) return true for a call to
1621 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1622 // live with this by checking that the character is a 7 bit one - even if this
1623 // may fail to detect some spaces (I don't know if Unicode doesn't have
1624 // space-like symbols somewhere except in the first 128 chars), it is arguably
1625 // still better than trimming away accented letters
1626 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1628 // trims spaces (in the sense of isspace) from left or right side
1629 wxString
& wxString::Trim(bool bFromRight
)
1631 // first check if we're going to modify the string at all
1634 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1635 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1641 // find last non-space character
1642 iterator psz
= begin() + length() - 1;
1643 while ( wxSafeIsspace(*psz
) && (psz
>= begin()) )
1646 // truncate at trailing space start
1652 // find first non-space character
1653 iterator psz
= begin();
1654 while ( wxSafeIsspace(*psz
) )
1657 // fix up data and length
1658 erase(begin(), psz
);
1665 // adds nCount characters chPad to the string from either side
1666 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1668 wxString
s(chPad
, nCount
);
1681 // truncate the string
1682 wxString
& wxString::Truncate(size_t uiLen
)
1684 if ( uiLen
< Len() ) {
1685 erase(begin() + uiLen
, end());
1687 //else: nothing to do, string is already short enough
1692 // ---------------------------------------------------------------------------
1693 // finding (return wxNOT_FOUND if not found and index otherwise)
1694 // ---------------------------------------------------------------------------
1697 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1699 size_type idx
= bFromEnd
? find_last_of(ch
) : find_first_of(ch
);
1701 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1704 // find a sub-string (like strstr)
1705 int wxString::Find(const wxChar
*pszSub
) const
1707 size_type idx
= find(pszSub
);
1709 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1712 // ----------------------------------------------------------------------------
1713 // conversion to numbers
1714 // ----------------------------------------------------------------------------
1716 bool wxString::ToLong(long *val
, int base
) const
1718 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToLong") );
1719 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1721 const wxChar
*start
= c_str();
1723 *val
= wxStrtol(start
, &end
, base
);
1725 // return true only if scan was stopped by the terminating NUL and if the
1726 // string was not empty to start with
1727 return !*end
&& (end
!= start
);
1730 bool wxString::ToULong(unsigned long *val
, int base
) const
1732 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToULong") );
1733 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1735 const wxChar
*start
= c_str();
1737 *val
= wxStrtoul(start
, &end
, base
);
1739 // return true only if scan was stopped by the terminating NUL and if the
1740 // string was not empty to start with
1741 return !*end
&& (end
!= start
);
1744 bool wxString::ToDouble(double *val
) const
1746 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToDouble") );
1748 const wxChar
*start
= c_str();
1750 *val
= wxStrtod(start
, &end
);
1752 // return true only if scan was stopped by the terminating NUL and if the
1753 // string was not empty to start with
1754 return !*end
&& (end
!= start
);
1757 // ---------------------------------------------------------------------------
1759 // ---------------------------------------------------------------------------
1762 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1765 va_start(argptr
, pszFormat
);
1768 s
.PrintfV(pszFormat
, argptr
);
1776 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1779 s
.PrintfV(pszFormat
, argptr
);
1783 int wxString::Printf(const wxChar
*pszFormat
, ...)
1786 va_start(argptr
, pszFormat
);
1788 int iLen
= PrintfV(pszFormat
, argptr
);
1795 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1803 wxStringBuffer
tmp(*this, size
+ 1);
1812 // wxVsnprintf() may modify the original arg pointer, so pass it
1815 wxVaCopy(argptrcopy
, argptr
);
1816 len
= wxVsnprintf(buf
, size
, pszFormat
, argptrcopy
);
1819 // some implementations of vsnprintf() don't NUL terminate
1820 // the string if there is not enough space for it so
1821 // always do it manually
1822 buf
[size
] = _T('\0');
1825 // vsnprintf() may return either -1 (traditional Unix behaviour) or the
1826 // total number of characters which would have been written if the
1827 // buffer were large enough
1828 if ( len
>= 0 && len
<= size
)
1830 // ok, there was enough space
1834 // still not enough, double it again
1838 // we could have overshot
1844 // ----------------------------------------------------------------------------
1845 // misc other operations
1846 // ----------------------------------------------------------------------------
1848 // returns true if the string matches the pattern which may contain '*' and
1849 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1851 bool wxString::Matches(const wxChar
*pszMask
) const
1853 // I disable this code as it doesn't seem to be faster (in fact, it seems
1854 // to be much slower) than the old, hand-written code below and using it
1855 // here requires always linking with libregex even if the user code doesn't
1857 #if 0 // wxUSE_REGEX
1858 // first translate the shell-like mask into a regex
1860 pattern
.reserve(wxStrlen(pszMask
));
1872 pattern
+= _T(".*");
1883 // these characters are special in a RE, quote them
1884 // (however note that we don't quote '[' and ']' to allow
1885 // using them for Unix shell like matching)
1886 pattern
+= _T('\\');
1890 pattern
+= *pszMask
;
1898 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1899 #else // !wxUSE_REGEX
1900 // TODO: this is, of course, awfully inefficient...
1902 // the char currently being checked
1903 const wxChar
*pszTxt
= c_str();
1905 // the last location where '*' matched
1906 const wxChar
*pszLastStarInText
= NULL
;
1907 const wxChar
*pszLastStarInMask
= NULL
;
1910 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1911 switch ( *pszMask
) {
1913 if ( *pszTxt
== wxT('\0') )
1916 // pszTxt and pszMask will be incremented in the loop statement
1922 // remember where we started to be able to backtrack later
1923 pszLastStarInText
= pszTxt
;
1924 pszLastStarInMask
= pszMask
;
1926 // ignore special chars immediately following this one
1927 // (should this be an error?)
1928 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1931 // if there is nothing more, match
1932 if ( *pszMask
== wxT('\0') )
1935 // are there any other metacharacters in the mask?
1937 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1939 if ( pEndMask
!= NULL
) {
1940 // we have to match the string between two metachars
1941 uiLenMask
= pEndMask
- pszMask
;
1944 // we have to match the remainder of the string
1945 uiLenMask
= wxStrlen(pszMask
);
1948 wxString
strToMatch(pszMask
, uiLenMask
);
1949 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1950 if ( pMatch
== NULL
)
1953 // -1 to compensate "++" in the loop
1954 pszTxt
= pMatch
+ uiLenMask
- 1;
1955 pszMask
+= uiLenMask
- 1;
1960 if ( *pszMask
!= *pszTxt
)
1966 // match only if nothing left
1967 if ( *pszTxt
== wxT('\0') )
1970 // if we failed to match, backtrack if we can
1971 if ( pszLastStarInText
) {
1972 pszTxt
= pszLastStarInText
+ 1;
1973 pszMask
= pszLastStarInMask
;
1975 pszLastStarInText
= NULL
;
1977 // don't bother resetting pszLastStarInMask, it's unnecessary
1983 #endif // wxUSE_REGEX/!wxUSE_REGEX
1986 // Count the number of chars
1987 int wxString::Freq(wxChar ch
) const
1991 for (int i
= 0; i
< len
; i
++)
1993 if (GetChar(i
) == ch
)
1999 // convert to upper case, return the copy of the string
2000 wxString
wxString::Upper() const
2001 { wxString
s(*this); return s
.MakeUpper(); }
2003 // convert to lower case, return the copy of the string
2004 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
2006 int wxString::sprintf(const wxChar
*pszFormat
, ...)
2009 va_start(argptr
, pszFormat
);
2010 int iLen
= PrintfV(pszFormat
, argptr
);
2015 // ============================================================================
2017 // ============================================================================
2019 #include "wx/arrstr.h"
2023 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
2024 #define ARRAY_MAXSIZE_INCREMENT 4096
2026 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
2027 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
2030 #define STRING(p) ((wxString *)(&(p)))
2033 void wxArrayString::Init(bool autoSort
)
2037 m_pItems
= (wxChar
**) NULL
;
2038 m_autoSort
= autoSort
;
2042 wxArrayString::wxArrayString(const wxArrayString
& src
)
2044 Init(src
.m_autoSort
);
2049 // assignment operator
2050 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
2057 m_autoSort
= src
.m_autoSort
;
2062 void wxArrayString::Copy(const wxArrayString
& src
)
2064 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
2065 Alloc(src
.m_nCount
);
2067 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
2072 void wxArrayString::Grow(size_t nIncrement
)
2074 // only do it if no more place
2075 if ( (m_nSize
- m_nCount
) < nIncrement
) {
2076 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2077 // be never resized!
2078 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2079 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2082 if ( m_nSize
== 0 ) {
2083 // was empty, alloc some memory
2084 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
2085 if (m_nSize
< nIncrement
)
2086 m_nSize
= nIncrement
;
2087 m_pItems
= new wxChar
*[m_nSize
];
2090 // otherwise when it's called for the first time, nIncrement would be 0
2091 // and the array would never be expanded
2092 // add 50% but not too much
2093 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
2094 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
2095 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
2096 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
2097 if ( nIncrement
< ndefIncrement
)
2098 nIncrement
= ndefIncrement
;
2099 m_nSize
+= nIncrement
;
2100 wxChar
**pNew
= new wxChar
*[m_nSize
];
2102 // copy data to new location
2103 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2105 // delete old memory (but do not release the strings!)
2106 wxDELETEA(m_pItems
);
2113 void wxArrayString::Free()
2115 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
2116 STRING(m_pItems
[n
])->GetStringData()->Unlock();
2120 // deletes all the strings from the list
2121 void wxArrayString::Empty()
2128 // as Empty, but also frees memory
2129 void wxArrayString::Clear()
2136 wxDELETEA(m_pItems
);
2140 wxArrayString::~wxArrayString()
2144 wxDELETEA(m_pItems
);
2147 void wxArrayString::reserve(size_t nSize
)
2152 // pre-allocates memory (frees the previous data!)
2153 void wxArrayString::Alloc(size_t nSize
)
2155 // only if old buffer was not big enough
2156 if ( nSize
> m_nSize
) {
2158 wxDELETEA(m_pItems
);
2159 m_pItems
= new wxChar
*[nSize
];
2166 // minimizes the memory usage by freeing unused memory
2167 void wxArrayString::Shrink()
2169 // only do it if we have some memory to free
2170 if( m_nCount
< m_nSize
) {
2171 // allocates exactly as much memory as we need
2172 wxChar
**pNew
= new wxChar
*[m_nCount
];
2174 // copy data to new location
2175 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2181 #if WXWIN_COMPATIBILITY_2_4
2183 // return a wxString[] as required for some control ctors.
2184 wxString
* wxArrayString::GetStringArray() const
2186 wxString
*array
= 0;
2190 array
= new wxString
[m_nCount
];
2191 for( size_t i
= 0; i
< m_nCount
; i
++ )
2192 array
[i
] = m_pItems
[i
];
2198 #endif // WXWIN_COMPATIBILITY_2_4
2200 // searches the array for an item (forward or backwards)
2201 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2204 // use binary search in the sorted array
2205 wxASSERT_MSG( bCase
&& !bFromEnd
,
2206 wxT("search parameters ignored for auto sorted array") );
2215 res
= wxStrcmp(sz
, m_pItems
[i
]);
2227 // use linear search in unsorted array
2229 if ( m_nCount
> 0 ) {
2230 size_t ui
= m_nCount
;
2232 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2239 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2240 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2249 // add item at the end
2250 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
2253 // insert the string at the correct position to keep the array sorted
2261 res
= str
.Cmp(m_pItems
[i
]);
2272 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2274 Insert(str
, lo
, nInsert
);
2279 wxASSERT( str
.GetStringData()->IsValid() );
2283 for (size_t i
= 0; i
< nInsert
; i
++)
2285 // the string data must not be deleted!
2286 str
.GetStringData()->Lock();
2289 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2291 size_t ret
= m_nCount
;
2292 m_nCount
+= nInsert
;
2297 // add item at the given position
2298 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2300 wxASSERT( str
.GetStringData()->IsValid() );
2302 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2303 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2304 wxT("array size overflow in wxArrayString::Insert") );
2308 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2309 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2311 for (size_t i
= 0; i
< nInsert
; i
++)
2313 str
.GetStringData()->Lock();
2314 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2316 m_nCount
+= nInsert
;
2319 // range insert (STL 23.2.4.3)
2321 wxArrayString::insert(iterator it
, const_iterator first
, const_iterator last
)
2323 const int idx
= it
- begin();
2328 // reset "it" since it can change inside Grow()
2331 while ( first
!= last
)
2333 it
= insert(it
, *first
);
2335 // insert returns an iterator to the last element inserted but we need
2336 // insert the next after this one, that is before the next one
2344 void wxArrayString::SetCount(size_t count
)
2349 while ( m_nCount
< count
)
2350 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2353 // removes item from array (by index)
2354 void wxArrayString::RemoveAt(size_t nIndex
, size_t nRemove
)
2356 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2357 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2358 wxT("removing too many elements in wxArrayString::Remove") );
2361 for (size_t i
= 0; i
< nRemove
; i
++)
2362 Item(nIndex
+ i
).GetStringData()->Unlock();
2364 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2365 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2366 m_nCount
-= nRemove
;
2369 // removes item from array (by value)
2370 void wxArrayString::Remove(const wxChar
*sz
)
2372 int iIndex
= Index(sz
);
2374 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2375 wxT("removing inexistent element in wxArrayString::Remove") );
2380 void wxArrayString::assign(const_iterator first
, const_iterator last
)
2382 reserve(last
- first
);
2383 for(; first
!= last
; ++first
)
2387 // ----------------------------------------------------------------------------
2389 // ----------------------------------------------------------------------------
2391 // we can only sort one array at a time with the quick-sort based
2394 // need a critical section to protect access to gs_compareFunction and
2395 // gs_sortAscending variables
2396 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2398 // call this before the value of the global sort vars is changed/after
2399 // you're finished with them
2400 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2401 gs_critsectStringSort = new wxCriticalSection; \
2402 gs_critsectStringSort->Enter()
2403 #define END_SORT() gs_critsectStringSort->Leave(); \
2404 delete gs_critsectStringSort; \
2405 gs_critsectStringSort = NULL
2407 #define START_SORT()
2409 #endif // wxUSE_THREADS
2411 // function to use for string comparaison
2412 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2414 // if we don't use the compare function, this flag tells us if we sort the
2415 // array in ascending or descending order
2416 static bool gs_sortAscending
= true;
2418 // function which is called by quick sort
2419 extern "C" int wxC_CALLING_CONV
// LINKAGEMODE
2420 wxStringCompareFunction(const void *first
, const void *second
)
2422 wxString
*strFirst
= (wxString
*)first
;
2423 wxString
*strSecond
= (wxString
*)second
;
2425 if ( gs_compareFunction
) {
2426 return gs_compareFunction(*strFirst
, *strSecond
);
2429 // maybe we should use wxStrcoll
2430 int result
= strFirst
->Cmp(*strSecond
);
2432 return gs_sortAscending
? result
: -result
;
2436 // sort array elements using passed comparaison function
2437 void wxArrayString::Sort(CompareFunction compareFunction
)
2441 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2442 gs_compareFunction
= compareFunction
;
2446 // reset it to NULL so that Sort(bool) will work the next time
2447 gs_compareFunction
= NULL
;
2452 typedef int (wxC_CALLING_CONV
* wxStringCompareFn
)(const void *first
, const void *second
);
2454 void wxArrayString::Sort(CompareFunction2 compareFunction
)
2456 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), (wxStringCompareFn
)compareFunction
);
2459 void wxArrayString::Sort(bool reverseOrder
)
2461 Sort(reverseOrder
? wxStringSortDescending
: wxStringSortAscending
);
2464 void wxArrayString::DoSort()
2466 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2468 // just sort the pointers using qsort() - of course it only works because
2469 // wxString() *is* a pointer to its data
2470 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2473 bool wxArrayString::operator==(const wxArrayString
& a
) const
2475 if ( m_nCount
!= a
.m_nCount
)
2478 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2480 if ( Item(n
) != a
[n
] )
2487 #endif // !wxUSE_STL
2489 int wxCMPFUNC_CONV
wxStringSortAscending(wxString
* s1
, wxString
* s2
)
2491 return s1
->Cmp(*s2
);
2494 int wxCMPFUNC_CONV
wxStringSortDescending(wxString
* s1
, wxString
* s2
)
2496 return -s1
->Cmp(*s2
);