1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/string.cpp
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 /////////////////////////////////////////////////////////////////////////////
15 * 1) all empty strings use g_strEmpty, nRefs = -1 (set in Init())
16 * 2) AllocBuffer() sets nRefs to 1, Lock() increments it by one
17 * 3) Unlock() decrements nRefs and frees memory if it goes to 0
20 // ===========================================================================
21 // headers, declarations, constants
22 // ===========================================================================
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
32 #include "wx/string.h"
34 #include "wx/thread.h"
45 // allocating extra space for each string consumes more memory but speeds up
46 // the concatenation operations (nLen is the current string's length)
47 // NB: EXTRA_ALLOC must be >= 0!
48 #define EXTRA_ALLOC (19 - nLen % 16)
50 // ---------------------------------------------------------------------------
51 // static class variables definition
52 // ---------------------------------------------------------------------------
55 //According to STL _must_ be a -1 size_t
56 const size_t wxStringBase::npos
= (size_t) -1;
59 // ----------------------------------------------------------------------------
61 // ----------------------------------------------------------------------------
65 extern const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= _T("");
69 // for an empty string, GetStringData() will return this address: this
70 // structure has the same layout as wxStringData and it's data() method will
71 // return the empty string (dummy pointer)
76 } g_strEmpty
= { {-1, 0, 0}, wxT('\0') };
78 // empty C style string: points to 'string data' byte of g_strEmpty
79 extern const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= &g_strEmpty
.dummy
;
83 // ----------------------------------------------------------------------------
85 // ----------------------------------------------------------------------------
87 #if wxUSE_STD_IOSTREAM
91 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
101 #endif // wxUSE_STD_IOSTREAM
103 // ----------------------------------------------------------------------------
105 // ----------------------------------------------------------------------------
107 // this small class is used to gather statistics for performance tuning
108 //#define WXSTRING_STATISTICS
109 #ifdef WXSTRING_STATISTICS
113 Averager(const wxChar
*sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
115 { wxPrintf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
117 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
120 size_t m_nCount
, m_nTotal
;
122 } g_averageLength("allocation size"),
123 g_averageSummandLength("summand length"),
124 g_averageConcatHit("hit probability in concat"),
125 g_averageInitialLength("initial string length");
127 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
129 #define STATISTICS_ADD(av, val)
130 #endif // WXSTRING_STATISTICS
134 // ===========================================================================
135 // wxStringData class deallocation
136 // ===========================================================================
138 #if defined(__VISUALC__) && defined(_MT) && !defined(_DLL)
139 # pragma message (__FILE__ ": building with Multithreaded non DLL runtime has a performance impact on wxString!")
140 void wxStringData::Free()
146 // ===========================================================================
148 // ===========================================================================
150 // takes nLength elements of psz starting at nPos
151 void wxStringBase::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
155 // if the length is not given, assume the string to be NUL terminated
156 if ( nLength
== npos
) {
157 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
159 nLength
= wxStrlen(psz
+ nPos
);
162 STATISTICS_ADD(InitialLength
, nLength
);
165 // trailing '\0' is written in AllocBuffer()
166 if ( !AllocBuffer(nLength
) ) {
167 wxFAIL_MSG( _T("out of memory in wxStringBase::InitWith") );
170 wxTmemcpy(m_pchData
, psz
+ nPos
, nLength
);
174 // poor man's iterators are "void *" pointers
175 wxStringBase::wxStringBase(const void *pStart
, const void *pEnd
)
177 if ( pEnd
>= pStart
)
179 InitWith((const wxChar
*)pStart
, 0,
180 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
184 wxFAIL_MSG( _T("pStart is not before pEnd") );
189 wxStringBase::wxStringBase(size_type n
, wxChar ch
)
195 // ---------------------------------------------------------------------------
197 // ---------------------------------------------------------------------------
199 // allocates memory needed to store a C string of length nLen
200 bool wxStringBase::AllocBuffer(size_t nLen
)
202 // allocating 0 sized buffer doesn't make sense, all empty strings should
204 wxASSERT( nLen
> 0 );
206 // make sure that we don't overflow
207 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
208 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
210 STATISTICS_ADD(Length
, nLen
);
213 // 1) one extra character for '\0' termination
214 // 2) sizeof(wxStringData) for housekeeping info
215 wxStringData
* pData
= (wxStringData
*)
216 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
218 if ( pData
== NULL
) {
219 // allocation failures are handled by the caller
224 pData
->nDataLength
= nLen
;
225 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
226 m_pchData
= pData
->data(); // data starts after wxStringData
227 m_pchData
[nLen
] = wxT('\0');
231 // must be called before changing this string
232 bool wxStringBase::CopyBeforeWrite()
234 wxStringData
* pData
= GetStringData();
236 if ( pData
->IsShared() ) {
237 pData
->Unlock(); // memory not freed because shared
238 size_t nLen
= pData
->nDataLength
;
239 if ( !AllocBuffer(nLen
) ) {
240 // allocation failures are handled by the caller
243 wxTmemcpy(m_pchData
, pData
->data(), nLen
);
246 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
251 // must be called before replacing contents of this string
252 bool wxStringBase::AllocBeforeWrite(size_t nLen
)
254 wxASSERT( nLen
!= 0 ); // doesn't make any sense
256 // must not share string and must have enough space
257 wxStringData
* pData
= GetStringData();
258 if ( pData
->IsShared() || pData
->IsEmpty() ) {
259 // can't work with old buffer, get new one
261 if ( !AllocBuffer(nLen
) ) {
262 // allocation failures are handled by the caller
267 if ( nLen
> pData
->nAllocLength
) {
268 // realloc the buffer instead of calling malloc() again, this is more
270 STATISTICS_ADD(Length
, nLen
);
274 pData
= (wxStringData
*)
275 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
277 if ( pData
== NULL
) {
278 // allocation failures are handled by the caller
279 // keep previous data since reallocation failed
283 pData
->nAllocLength
= nLen
;
284 m_pchData
= pData
->data();
288 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
290 // it doesn't really matter what the string length is as it's going to be
291 // overwritten later but, for extra safety, set it to 0 for now as we may
292 // have some junk in m_pchData
293 GetStringData()->nDataLength
= 0;
298 wxStringBase
& wxStringBase::append(size_t n
, wxChar ch
)
300 size_type len
= length();
302 if ( !Alloc(len
+ n
) || !CopyBeforeWrite() ) {
303 wxFAIL_MSG( _T("out of memory in wxStringBase::append") );
305 GetStringData()->nDataLength
= len
+ n
;
306 m_pchData
[len
+ n
] = '\0';
307 for ( size_t i
= 0; i
< n
; ++i
)
308 m_pchData
[len
+ i
] = ch
;
312 void wxStringBase::resize(size_t nSize
, wxChar ch
)
314 size_t len
= length();
318 erase(begin() + nSize
, end());
320 else if ( nSize
> len
)
322 append(nSize
- len
, ch
);
324 //else: we have exactly the specified length, nothing to do
327 // allocate enough memory for nLen characters
328 bool wxStringBase::Alloc(size_t nLen
)
330 wxStringData
*pData
= GetStringData();
331 if ( pData
->nAllocLength
<= nLen
) {
332 if ( pData
->IsEmpty() ) {
335 pData
= (wxStringData
*)
336 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
338 if ( pData
== NULL
) {
339 // allocation failure handled by caller
344 pData
->nDataLength
= 0;
345 pData
->nAllocLength
= nLen
;
346 m_pchData
= pData
->data(); // data starts after wxStringData
347 m_pchData
[0u] = wxT('\0');
349 else if ( pData
->IsShared() ) {
350 pData
->Unlock(); // memory not freed because shared
351 size_t nOldLen
= pData
->nDataLength
;
352 if ( !AllocBuffer(nLen
) ) {
353 // allocation failure handled by caller
356 // +1 to copy the terminator, too
357 memcpy(m_pchData
, pData
->data(), (nOldLen
+1)*sizeof(wxChar
));
358 GetStringData()->nDataLength
= nOldLen
;
363 pData
= (wxStringData
*)
364 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
366 if ( pData
== NULL
) {
367 // allocation failure handled by caller
368 // keep previous data since reallocation failed
372 // it's not important if the pointer changed or not (the check for this
373 // is not faster than assigning to m_pchData in all cases)
374 pData
->nAllocLength
= nLen
;
375 m_pchData
= pData
->data();
378 //else: we've already got enough
382 wxStringBase::iterator
wxStringBase::begin()
389 wxStringBase::iterator
wxStringBase::end()
393 return m_pchData
+ length();
396 wxStringBase::iterator
wxStringBase::erase(iterator it
)
398 size_type idx
= it
- begin();
400 return begin() + idx
;
403 wxStringBase
& wxStringBase::erase(size_t nStart
, size_t nLen
)
405 wxASSERT(nStart
<= length());
406 size_t strLen
= length() - nStart
;
407 // delete nLen or up to the end of the string characters
408 nLen
= strLen
< nLen
? strLen
: nLen
;
409 wxString
strTmp(c_str(), nStart
);
410 strTmp
.append(c_str() + nStart
+ nLen
, length() - nStart
- nLen
);
416 wxStringBase
& wxStringBase::insert(size_t nPos
, const wxChar
*sz
, size_t n
)
418 wxASSERT( nPos
<= length() );
420 if ( n
== npos
) n
= wxStrlen(sz
);
421 if ( n
== 0 ) return *this;
423 if ( !Alloc(length() + n
) || !CopyBeforeWrite() ) {
424 wxFAIL_MSG( _T("out of memory in wxStringBase::insert") );
427 memmove(m_pchData
+ nPos
+ n
, m_pchData
+ nPos
,
428 (length() - nPos
) * sizeof(wxChar
));
429 memcpy(m_pchData
+ nPos
, sz
, n
* sizeof(wxChar
));
430 GetStringData()->nDataLength
= length() + n
;
431 m_pchData
[length()] = '\0';
436 void wxStringBase::swap(wxStringBase
& str
)
438 wxChar
* tmp
= str
.m_pchData
;
439 str
.m_pchData
= m_pchData
;
443 size_t wxStringBase::find(const wxStringBase
& str
, size_t nStart
) const
445 // deal with the special case of empty string first
446 const size_t nLen
= length();
447 const size_t nLenOther
= str
.length();
451 // empty string is a substring of anything
457 // the other string is non empty so can't be our substring
461 wxASSERT( str
.GetStringData()->IsValid() );
462 wxASSERT( nStart
<= nLen
);
464 const wxChar
* const other
= str
.c_str();
467 const wxChar
* p
= (const wxChar
*)wxTmemchr(c_str() + nStart
,
474 while ( p
- c_str() + nLenOther
<= nLen
&& wxTmemcmp(p
, other
, nLenOther
) )
479 p
= (const wxChar
*)wxTmemchr(p
, *other
, nLen
- (p
- c_str()));
485 return p
- c_str() + nLenOther
<= nLen
? p
- c_str() : npos
;
488 size_t wxStringBase::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
490 return find(wxStringBase(sz
, n
), nStart
);
493 size_t wxStringBase::find(wxChar ch
, size_t nStart
) const
495 wxASSERT( nStart
<= length() );
497 const wxChar
*p
= (const wxChar
*)wxTmemchr(c_str() + nStart
, ch
, length() - nStart
);
499 return p
== NULL
? npos
: p
- c_str();
502 size_t wxStringBase::rfind(const wxStringBase
& str
, size_t nStart
) const
504 wxASSERT( str
.GetStringData()->IsValid() );
505 wxASSERT( nStart
== npos
|| nStart
<= length() );
507 if ( length() >= str
.length() )
509 // avoids a corner case later
510 if ( length() == 0 && str
.length() == 0 )
513 // "top" is the point where search starts from
514 size_t top
= length() - str
.length();
516 if ( nStart
== npos
)
517 nStart
= length() - 1;
521 const wxChar
*cursor
= c_str() + top
;
524 if ( wxTmemcmp(cursor
, str
.c_str(),
527 return cursor
- c_str();
529 } while ( cursor
-- > c_str() );
535 size_t wxStringBase::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
537 return rfind(wxStringBase(sz
, n
), nStart
);
540 size_t wxStringBase::rfind(wxChar ch
, size_t nStart
) const
542 if ( nStart
== npos
)
548 wxASSERT( nStart
<= length() );
551 const wxChar
*actual
;
552 for ( actual
= c_str() + ( nStart
== npos
? length() : nStart
+ 1 );
553 actual
> c_str(); --actual
)
555 if ( *(actual
- 1) == ch
)
556 return (actual
- 1) - c_str();
562 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
) const
564 wxASSERT(nStart
<= length());
566 size_t len
= wxStrlen(sz
);
569 for(i
= nStart
; i
< this->length(); ++i
)
571 if (wxTmemchr(sz
, *(c_str() + i
), len
))
575 if(i
== this->length())
581 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
,
584 return find_first_of(wxStringBase(sz
, n
), nStart
);
587 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
) const
589 if ( nStart
== npos
)
591 nStart
= length() - 1;
595 wxASSERT_MSG( nStart
<= length(),
596 _T("invalid index in find_last_of()") );
599 size_t len
= wxStrlen(sz
);
601 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
603 if ( wxTmemchr(sz
, *p
, len
) )
610 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
,
613 return find_last_of(wxStringBase(sz
, n
), nStart
);
616 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
618 if ( nStart
== npos
)
624 wxASSERT( nStart
<= length() );
627 size_t len
= wxStrlen(sz
);
630 for(i
= nStart
; i
< this->length(); ++i
)
632 if (!wxTmemchr(sz
, *(c_str() + i
), len
))
636 if(i
== this->length())
642 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
,
645 return find_first_not_of(wxStringBase(sz
, n
), nStart
);
648 size_t wxStringBase::find_first_not_of(wxChar ch
, size_t nStart
) const
650 wxASSERT( nStart
<= length() );
652 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
661 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
663 if ( nStart
== npos
)
665 nStart
= length() - 1;
669 wxASSERT( nStart
<= length() );
672 size_t len
= wxStrlen(sz
);
674 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
676 if ( !wxTmemchr(sz
, *p
,len
) )
683 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
,
686 return find_last_not_of(wxStringBase(sz
, n
), nStart
);
689 size_t wxStringBase::find_last_not_of(wxChar ch
, size_t nStart
) const
691 if ( nStart
== npos
)
693 nStart
= length() - 1;
697 wxASSERT( nStart
<= length() );
700 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
709 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
712 wxASSERT_MSG( nStart
<= length(),
713 _T("index out of bounds in wxStringBase::replace") );
714 size_t strLen
= length() - nStart
;
715 nLen
= strLen
< nLen
? strLen
: nLen
;
718 strTmp
.reserve(length()); // micro optimisation to avoid multiple mem allocs
720 //This is kind of inefficient, but its pretty good considering...
721 //we don't want to use character access operators here because on STL
722 //it will freeze the reference count of strTmp, which means a deep copy
723 //at the end when swap is called
725 //Also, we can't use append with the full character pointer and must
726 //do it manually because this string can contain null characters
727 for(size_t i1
= 0; i1
< nStart
; ++i1
)
728 strTmp
.append(1, this->c_str()[i1
]);
730 //its safe to do the full version here because
731 //sz must be a normal c string
734 for(size_t i2
= nStart
+ nLen
; i2
< length(); ++i2
)
735 strTmp
.append(1, this->c_str()[i2
]);
741 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
742 size_t nCount
, wxChar ch
)
744 return replace(nStart
, nLen
, wxStringBase(nCount
, ch
).c_str());
747 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
748 const wxStringBase
& str
,
749 size_t nStart2
, size_t nLen2
)
751 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
754 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
755 const wxChar
* sz
, size_t nCount
)
757 return replace(nStart
, nLen
, wxStringBase(sz
, nCount
).c_str());
760 wxStringBase
wxStringBase::substr(size_t nStart
, size_t nLen
) const
763 nLen
= length() - nStart
;
764 return wxStringBase(*this, nStart
, nLen
);
767 // assigns one string to another
768 wxStringBase
& wxStringBase::operator=(const wxStringBase
& stringSrc
)
770 wxASSERT( stringSrc
.GetStringData()->IsValid() );
772 // don't copy string over itself
773 if ( m_pchData
!= stringSrc
.m_pchData
) {
774 if ( stringSrc
.GetStringData()->IsEmpty() ) {
779 GetStringData()->Unlock();
780 m_pchData
= stringSrc
.m_pchData
;
781 GetStringData()->Lock();
788 // assigns a single character
789 wxStringBase
& wxStringBase::operator=(wxChar ch
)
791 if ( !AssignCopy(1, &ch
) ) {
792 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(wxChar)") );
798 wxStringBase
& wxStringBase::operator=(const wxChar
*psz
)
800 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
801 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(const wxChar *)") );
806 // helper function: does real copy
807 bool wxStringBase::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
809 if ( nSrcLen
== 0 ) {
813 if ( !AllocBeforeWrite(nSrcLen
) ) {
814 // allocation failure handled by caller
817 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
818 GetStringData()->nDataLength
= nSrcLen
;
819 m_pchData
[nSrcLen
] = wxT('\0');
824 // ---------------------------------------------------------------------------
825 // string concatenation
826 // ---------------------------------------------------------------------------
828 // add something to this string
829 bool wxStringBase::ConcatSelf(size_t nSrcLen
, const wxChar
*pszSrcData
,
832 STATISTICS_ADD(SummandLength
, nSrcLen
);
834 nSrcLen
= nSrcLen
< nMaxLen
? nSrcLen
: nMaxLen
;
836 // concatenating an empty string is a NOP
838 wxStringData
*pData
= GetStringData();
839 size_t nLen
= pData
->nDataLength
;
840 size_t nNewLen
= nLen
+ nSrcLen
;
842 // alloc new buffer if current is too small
843 if ( pData
->IsShared() ) {
844 STATISTICS_ADD(ConcatHit
, 0);
846 // we have to allocate another buffer
847 wxStringData
* pOldData
= GetStringData();
848 if ( !AllocBuffer(nNewLen
) ) {
849 // allocation failure handled by caller
852 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
855 else if ( nNewLen
> pData
->nAllocLength
) {
856 STATISTICS_ADD(ConcatHit
, 0);
859 // we have to grow the buffer
860 if ( capacity() < nNewLen
) {
861 // allocation failure handled by caller
866 STATISTICS_ADD(ConcatHit
, 1);
868 // the buffer is already big enough
871 // should be enough space
872 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
874 // fast concatenation - all is done in our buffer
875 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
877 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
878 GetStringData()->nDataLength
= nNewLen
; // and fix the length
880 //else: the string to append was empty
884 // ---------------------------------------------------------------------------
885 // simple sub-string extraction
886 // ---------------------------------------------------------------------------
888 // helper function: clone the data attached to this string
889 bool wxStringBase::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
891 if ( nCopyLen
== 0 ) {
895 if ( !dest
.AllocBuffer(nCopyLen
) ) {
896 // allocation failure handled by caller
899 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
906 #if !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
909 #define STRINGCLASS wxStringBase
911 #define STRINGCLASS wxString
914 static inline int wxDoCmp(const wxChar
* s1
, size_t l1
,
915 const wxChar
* s2
, size_t l2
)
918 return wxTmemcmp(s1
, s2
, l1
);
921 int ret
= wxTmemcmp(s1
, s2
, l1
);
922 return ret
== 0 ? -1 : ret
;
926 int ret
= wxTmemcmp(s1
, s2
, l2
);
927 return ret
== 0 ? +1 : ret
;
931 int STRINGCLASS::compare(const wxStringBase
& str
) const
933 return ::wxDoCmp(data(), length(), str
.data(), str
.length());
936 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
937 const wxStringBase
& str
) const
939 wxASSERT(nStart
<= length());
940 size_type strLen
= length() - nStart
;
941 nLen
= strLen
< nLen
? strLen
: nLen
;
942 return ::wxDoCmp(data() + nStart
, nLen
, str
.data(), str
.length());
945 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
946 const wxStringBase
& str
,
947 size_t nStart2
, size_t nLen2
) const
949 wxASSERT(nStart
<= length());
950 wxASSERT(nStart2
<= str
.length());
951 size_type strLen
= length() - nStart
,
952 strLen2
= str
.length() - nStart2
;
953 nLen
= strLen
< nLen
? strLen
: nLen
;
954 nLen2
= strLen2
< nLen2
? strLen2
: nLen2
;
955 return ::wxDoCmp(data() + nStart
, nLen
, str
.data() + nStart2
, nLen2
);
958 int STRINGCLASS::compare(const wxChar
* sz
) const
960 size_t nLen
= wxStrlen(sz
);
961 return ::wxDoCmp(data(), length(), sz
, nLen
);
964 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
965 const wxChar
* sz
, size_t nCount
) const
967 wxASSERT(nStart
<= length());
968 size_type strLen
= length() - nStart
;
969 nLen
= strLen
< nLen
? strLen
: nLen
;
971 nCount
= wxStrlen(sz
);
973 return ::wxDoCmp(data() + nStart
, nLen
, sz
, nCount
);
978 #endif // !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
980 // ===========================================================================
981 // wxString class core
982 // ===========================================================================
984 // ---------------------------------------------------------------------------
985 // construction and conversion
986 // ---------------------------------------------------------------------------
990 // from multibyte string
991 wxString::wxString(const char *psz
, const wxMBConv
& conv
, size_t nLength
)
994 if ( psz
&& nLength
!= 0 )
996 if ( nLength
== npos
)
1002 wxWCharBuffer wbuf
= conv
.cMB2WC(psz
, nLength
, &nLenWide
);
1005 assign(wbuf
, nLenWide
);
1009 //Convert wxString in Unicode mode to a multi-byte string
1010 const wxCharBuffer
wxString::mb_str(const wxMBConv
& conv
) const
1012 return conv
.cWC2MB(c_str(), length() + 1 /* size, not length */, NULL
);
1020 wxString::wxString(const wchar_t *pwz
, const wxMBConv
& conv
, size_t nLength
)
1023 if ( pwz
&& nLength
!= 0 )
1025 if ( nLength
== npos
)
1031 wxCharBuffer buf
= conv
.cWC2MB(pwz
, nLength
, &nLenMB
);
1034 assign(buf
, nLenMB
);
1038 //Converts this string to a wide character string if unicode
1039 //mode is not enabled and wxUSE_WCHAR_T is enabled
1040 const wxWCharBuffer
wxString::wc_str(const wxMBConv
& conv
) const
1042 return conv
.cMB2WC(c_str(), length() + 1 /* size, not length */, NULL
);
1045 #endif // wxUSE_WCHAR_T
1047 #endif // Unicode/ANSI
1049 // shrink to minimal size (releasing extra memory)
1050 bool wxString::Shrink()
1052 wxString
tmp(begin(), end());
1054 return tmp
.length() == length();
1058 // get the pointer to writable buffer of (at least) nLen bytes
1059 wxChar
*wxString::GetWriteBuf(size_t nLen
)
1061 if ( !AllocBeforeWrite(nLen
) ) {
1062 // allocation failure handled by caller
1066 wxASSERT( GetStringData()->nRefs
== 1 );
1067 GetStringData()->Validate(false);
1072 // put string back in a reasonable state after GetWriteBuf
1073 void wxString::UngetWriteBuf()
1075 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
1076 GetStringData()->Validate(true);
1079 void wxString::UngetWriteBuf(size_t nLen
)
1081 GetStringData()->nDataLength
= nLen
;
1082 GetStringData()->Validate(true);
1086 // ---------------------------------------------------------------------------
1088 // ---------------------------------------------------------------------------
1090 // all functions are inline in string.h
1092 // ---------------------------------------------------------------------------
1093 // assignment operators
1094 // ---------------------------------------------------------------------------
1098 // same as 'signed char' variant
1099 wxString
& wxString::operator=(const unsigned char* psz
)
1101 *this = (const char *)psz
;
1106 wxString
& wxString::operator=(const wchar_t *pwz
)
1117 * concatenation functions come in 5 flavours:
1119 * char + string and string + char
1120 * C str + string and string + C str
1123 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
1126 wxASSERT( str1
.GetStringData()->IsValid() );
1127 wxASSERT( str2
.GetStringData()->IsValid() );
1136 wxString
operator+(const wxString
& str
, wxChar ch
)
1139 wxASSERT( str
.GetStringData()->IsValid() );
1148 wxString
operator+(wxChar ch
, const wxString
& str
)
1151 wxASSERT( str
.GetStringData()->IsValid() );
1160 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
1163 wxASSERT( str
.GetStringData()->IsValid() );
1167 if ( !s
.Alloc(wxStrlen(psz
) + str
.length()) ) {
1168 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1176 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
1179 wxASSERT( str
.GetStringData()->IsValid() );
1183 if ( !s
.Alloc(wxStrlen(psz
) + str
.length()) ) {
1184 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1192 // ===========================================================================
1193 // other common string functions
1194 // ===========================================================================
1196 int wxString::Cmp(const wxString
& s
) const
1201 int wxString::Cmp(const wxChar
* psz
) const
1203 return compare(psz
);
1206 static inline int wxDoCmpNoCase(const wxChar
* s1
, size_t l1
,
1207 const wxChar
* s2
, size_t l2
)
1213 for(i
= 0; i
< l1
; ++i
)
1215 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1218 return i
== l1
? 0 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1222 for(i
= 0; i
< l1
; ++i
)
1224 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1227 return i
== l1
? -1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1231 for(i
= 0; i
< l2
; ++i
)
1233 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1236 return i
== l2
? 1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1240 int wxString::CmpNoCase(const wxString
& s
) const
1242 return wxDoCmpNoCase(data(), length(), s
.data(), s
.length());
1245 int wxString::CmpNoCase(const wxChar
* psz
) const
1247 int nLen
= wxStrlen(psz
);
1249 return wxDoCmpNoCase(data(), length(), psz
, nLen
);
1256 #ifndef __SCHAR_MAX__
1257 #define __SCHAR_MAX__ 127
1261 wxString
wxString::FromAscii(const char *ascii
)
1264 return wxEmptyString
;
1266 size_t len
= strlen( ascii
);
1271 wxStringBuffer
buf(res
, len
);
1273 wchar_t *dest
= buf
;
1277 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
1285 wxString
wxString::FromAscii(const char ascii
)
1287 // What do we do with '\0' ?
1290 res
+= (wchar_t)(unsigned char) ascii
;
1295 const wxCharBuffer
wxString::ToAscii() const
1297 // this will allocate enough space for the terminating NUL too
1298 wxCharBuffer
buffer(length());
1301 char *dest
= buffer
.data();
1303 const wchar_t *pwc
= c_str();
1306 *dest
++ = (char)(*pwc
> SCHAR_MAX
? wxT('_') : *pwc
);
1308 // the output string can't have embedded NULs anyhow, so we can safely
1309 // stop at first of them even if we do have any
1319 // extract string of length nCount starting at nFirst
1320 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
1322 size_t nLen
= length();
1324 // default value of nCount is npos and means "till the end"
1325 if ( nCount
== npos
)
1327 nCount
= nLen
- nFirst
;
1330 // out-of-bounds requests return sensible things
1331 if ( nFirst
+ nCount
> nLen
)
1333 nCount
= nLen
- nFirst
;
1336 if ( nFirst
> nLen
)
1338 // AllocCopy() will return empty string
1339 return wxEmptyString
;
1342 wxString
dest(*this, nFirst
, nCount
);
1343 if ( dest
.length() != nCount
)
1345 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
1351 // check that the string starts with prefix and return the rest of the string
1352 // in the provided pointer if it is not NULL, otherwise return false
1353 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
1355 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
1357 // first check if the beginning of the string matches the prefix: note
1358 // that we don't have to check that we don't run out of this string as
1359 // when we reach the terminating NUL, either prefix string ends too (and
1360 // then it's ok) or we break out of the loop because there is no match
1361 const wxChar
*p
= c_str();
1364 if ( *prefix
++ != *p
++ )
1373 // put the rest of the string into provided pointer
1381 // check that the string ends with suffix and return the rest of it in the
1382 // provided pointer if it is not NULL, otherwise return false
1383 bool wxString::EndsWith(const wxChar
*suffix
, wxString
*rest
) const
1385 wxASSERT_MSG( suffix
, _T("invalid parameter in wxString::EndssWith") );
1387 int start
= length() - wxStrlen(suffix
);
1388 if ( start
< 0 || wxStrcmp(c_str() + start
, suffix
) != 0 )
1393 // put the rest of the string into provided pointer
1394 rest
->assign(*this, 0, start
);
1401 // extract nCount last (rightmost) characters
1402 wxString
wxString::Right(size_t nCount
) const
1404 if ( nCount
> length() )
1407 wxString
dest(*this, length() - nCount
, nCount
);
1408 if ( dest
.length() != nCount
) {
1409 wxFAIL_MSG( _T("out of memory in wxString::Right") );
1414 // get all characters after the last occurence of ch
1415 // (returns the whole string if ch not found)
1416 wxString
wxString::AfterLast(wxChar ch
) const
1419 int iPos
= Find(ch
, true);
1420 if ( iPos
== wxNOT_FOUND
)
1423 str
= c_str() + iPos
+ 1;
1428 // extract nCount first (leftmost) characters
1429 wxString
wxString::Left(size_t nCount
) const
1431 if ( nCount
> length() )
1434 wxString
dest(*this, 0, nCount
);
1435 if ( dest
.length() != nCount
) {
1436 wxFAIL_MSG( _T("out of memory in wxString::Left") );
1441 // get all characters before the first occurence of ch
1442 // (returns the whole string if ch not found)
1443 wxString
wxString::BeforeFirst(wxChar ch
) const
1445 int iPos
= Find(ch
);
1446 if ( iPos
== wxNOT_FOUND
) iPos
= length();
1447 return wxString(*this, 0, iPos
);
1450 /// get all characters before the last occurence of ch
1451 /// (returns empty string if ch not found)
1452 wxString
wxString::BeforeLast(wxChar ch
) const
1455 int iPos
= Find(ch
, true);
1456 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
1457 str
= wxString(c_str(), iPos
);
1462 /// get all characters after the first occurence of ch
1463 /// (returns empty string if ch not found)
1464 wxString
wxString::AfterFirst(wxChar ch
) const
1467 int iPos
= Find(ch
);
1468 if ( iPos
!= wxNOT_FOUND
)
1469 str
= c_str() + iPos
+ 1;
1474 // replace first (or all) occurences of some substring with another one
1475 size_t wxString::Replace(const wxChar
*szOld
,
1476 const wxChar
*szNew
, bool bReplaceAll
)
1478 // if we tried to replace an empty string we'd enter an infinite loop below
1479 wxCHECK_MSG( szOld
&& *szOld
&& szNew
, 0,
1480 _T("wxString::Replace(): invalid parameter") );
1482 size_t uiCount
= 0; // count of replacements made
1484 size_t uiOldLen
= wxStrlen(szOld
);
1485 size_t uiNewLen
= wxStrlen(szNew
);
1489 while ( this->c_str()[dwPos
] != wxT('\0') )
1491 //DO NOT USE STRSTR HERE
1492 //this string can contain embedded null characters,
1493 //so strstr will function incorrectly
1494 dwPos
= find(szOld
, dwPos
);
1495 if ( dwPos
== npos
)
1496 break; // exit the loop
1499 //replace this occurance of the old string with the new one
1500 replace(dwPos
, uiOldLen
, szNew
, uiNewLen
);
1502 //move up pos past the string that was replaced
1505 //increase replace count
1510 break; // exit the loop
1517 bool wxString::IsAscii() const
1519 const wxChar
*s
= (const wxChar
*) *this;
1521 if(!isascii(*s
)) return(false);
1527 bool wxString::IsWord() const
1529 const wxChar
*s
= (const wxChar
*) *this;
1531 if(!wxIsalpha(*s
)) return(false);
1537 bool wxString::IsNumber() const
1539 const wxChar
*s
= (const wxChar
*) *this;
1541 if ((s
[0] == wxT('-')) || (s
[0] == wxT('+'))) s
++;
1543 if(!wxIsdigit(*s
)) return(false);
1549 wxString
wxString::Strip(stripType w
) const
1552 if ( w
& leading
) s
.Trim(false);
1553 if ( w
& trailing
) s
.Trim(true);
1557 // ---------------------------------------------------------------------------
1559 // ---------------------------------------------------------------------------
1561 wxString
& wxString::MakeUpper()
1563 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1564 *it
= (wxChar
)wxToupper(*it
);
1569 wxString
& wxString::MakeLower()
1571 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1572 *it
= (wxChar
)wxTolower(*it
);
1577 // ---------------------------------------------------------------------------
1578 // trimming and padding
1579 // ---------------------------------------------------------------------------
1581 // some compilers (VC++ 6.0 not to name them) return true for a call to
1582 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1583 // live with this by checking that the character is a 7 bit one - even if this
1584 // may fail to detect some spaces (I don't know if Unicode doesn't have
1585 // space-like symbols somewhere except in the first 128 chars), it is arguably
1586 // still better than trimming away accented letters
1587 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1589 // trims spaces (in the sense of isspace) from left or right side
1590 wxString
& wxString::Trim(bool bFromRight
)
1592 // first check if we're going to modify the string at all
1595 (bFromRight
&& wxSafeIsspace(GetChar(length() - 1))) ||
1596 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1602 // find last non-space character
1603 reverse_iterator psz
= rbegin();
1604 while ( (psz
!= rend()) && wxSafeIsspace(*psz
) )
1607 // truncate at trailing space start
1608 erase(psz
.base(), end());
1612 // find first non-space character
1613 iterator psz
= begin();
1614 while ( (psz
!= end()) && wxSafeIsspace(*psz
) )
1617 // fix up data and length
1618 erase(begin(), psz
);
1625 // adds nCount characters chPad to the string from either side
1626 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1628 wxString
s(chPad
, nCount
);
1641 // truncate the string
1642 wxString
& wxString::Truncate(size_t uiLen
)
1644 if ( uiLen
< length() )
1646 erase(begin() + uiLen
, end());
1648 //else: nothing to do, string is already short enough
1653 // ---------------------------------------------------------------------------
1654 // finding (return wxNOT_FOUND if not found and index otherwise)
1655 // ---------------------------------------------------------------------------
1658 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1660 size_type idx
= bFromEnd
? find_last_of(ch
) : find_first_of(ch
);
1662 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1665 // find a sub-string (like strstr)
1666 int wxString::Find(const wxChar
*pszSub
) const
1668 size_type idx
= find(pszSub
);
1670 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1673 // ----------------------------------------------------------------------------
1674 // conversion to numbers
1675 // ----------------------------------------------------------------------------
1677 bool wxString::ToLong(long *val
, int base
) const
1679 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToLong") );
1680 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1682 const wxChar
*start
= c_str();
1684 *val
= wxStrtol(start
, &end
, base
);
1686 // return true only if scan was stopped by the terminating NUL and if the
1687 // string was not empty to start with
1688 return !*end
&& (end
!= start
);
1691 bool wxString::ToULong(unsigned long *val
, int base
) const
1693 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToULong") );
1694 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1696 const wxChar
*start
= c_str();
1698 *val
= wxStrtoul(start
, &end
, base
);
1700 // return true only if scan was stopped by the terminating NUL and if the
1701 // string was not empty to start with
1702 return !*end
&& (end
!= start
);
1705 bool wxString::ToDouble(double *val
) const
1707 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToDouble") );
1709 const wxChar
*start
= c_str();
1711 *val
= wxStrtod(start
, &end
);
1713 // return true only if scan was stopped by the terminating NUL and if the
1714 // string was not empty to start with
1715 return !*end
&& (end
!= start
);
1718 // ---------------------------------------------------------------------------
1720 // ---------------------------------------------------------------------------
1723 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1726 va_start(argptr
, pszFormat
);
1729 s
.PrintfV(pszFormat
, argptr
);
1737 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1740 s
.PrintfV(pszFormat
, argptr
);
1744 int wxString::Printf(const wxChar
*pszFormat
, ...)
1747 va_start(argptr
, pszFormat
);
1749 int iLen
= PrintfV(pszFormat
, argptr
);
1756 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1762 wxStringBuffer
tmp(*this, size
+ 1);
1771 // wxVsnprintf() may modify the original arg pointer, so pass it
1774 wxVaCopy(argptrcopy
, argptr
);
1775 int len
= wxVsnprintf(buf
, size
, pszFormat
, argptrcopy
);
1778 // some implementations of vsnprintf() don't NUL terminate
1779 // the string if there is not enough space for it so
1780 // always do it manually
1781 buf
[size
] = _T('\0');
1783 // vsnprintf() may return either -1 (traditional Unix behaviour) or the
1784 // total number of characters which would have been written if the
1785 // buffer were large enough (newer standards such as Unix98)
1788 // still not enough, as we don't know how much we need, double the
1789 // current size of the buffer
1792 else if ( len
> size
)
1796 else // ok, there was enough space
1802 // we could have overshot
1808 // ----------------------------------------------------------------------------
1809 // misc other operations
1810 // ----------------------------------------------------------------------------
1812 // returns true if the string matches the pattern which may contain '*' and
1813 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1815 bool wxString::Matches(const wxChar
*pszMask
) const
1817 // I disable this code as it doesn't seem to be faster (in fact, it seems
1818 // to be much slower) than the old, hand-written code below and using it
1819 // here requires always linking with libregex even if the user code doesn't
1821 #if 0 // wxUSE_REGEX
1822 // first translate the shell-like mask into a regex
1824 pattern
.reserve(wxStrlen(pszMask
));
1836 pattern
+= _T(".*");
1847 // these characters are special in a RE, quote them
1848 // (however note that we don't quote '[' and ']' to allow
1849 // using them for Unix shell like matching)
1850 pattern
+= _T('\\');
1854 pattern
+= *pszMask
;
1862 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1863 #else // !wxUSE_REGEX
1864 // TODO: this is, of course, awfully inefficient...
1866 // the char currently being checked
1867 const wxChar
*pszTxt
= c_str();
1869 // the last location where '*' matched
1870 const wxChar
*pszLastStarInText
= NULL
;
1871 const wxChar
*pszLastStarInMask
= NULL
;
1874 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1875 switch ( *pszMask
) {
1877 if ( *pszTxt
== wxT('\0') )
1880 // pszTxt and pszMask will be incremented in the loop statement
1886 // remember where we started to be able to backtrack later
1887 pszLastStarInText
= pszTxt
;
1888 pszLastStarInMask
= pszMask
;
1890 // ignore special chars immediately following this one
1891 // (should this be an error?)
1892 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1895 // if there is nothing more, match
1896 if ( *pszMask
== wxT('\0') )
1899 // are there any other metacharacters in the mask?
1901 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1903 if ( pEndMask
!= NULL
) {
1904 // we have to match the string between two metachars
1905 uiLenMask
= pEndMask
- pszMask
;
1908 // we have to match the remainder of the string
1909 uiLenMask
= wxStrlen(pszMask
);
1912 wxString
strToMatch(pszMask
, uiLenMask
);
1913 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1914 if ( pMatch
== NULL
)
1917 // -1 to compensate "++" in the loop
1918 pszTxt
= pMatch
+ uiLenMask
- 1;
1919 pszMask
+= uiLenMask
- 1;
1924 if ( *pszMask
!= *pszTxt
)
1930 // match only if nothing left
1931 if ( *pszTxt
== wxT('\0') )
1934 // if we failed to match, backtrack if we can
1935 if ( pszLastStarInText
) {
1936 pszTxt
= pszLastStarInText
+ 1;
1937 pszMask
= pszLastStarInMask
;
1939 pszLastStarInText
= NULL
;
1941 // don't bother resetting pszLastStarInMask, it's unnecessary
1947 #endif // wxUSE_REGEX/!wxUSE_REGEX
1950 // Count the number of chars
1951 int wxString::Freq(wxChar ch
) const
1955 for (int i
= 0; i
< len
; i
++)
1957 if (GetChar(i
) == ch
)
1963 // convert to upper case, return the copy of the string
1964 wxString
wxString::Upper() const
1965 { wxString
s(*this); return s
.MakeUpper(); }
1967 // convert to lower case, return the copy of the string
1968 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1970 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1973 va_start(argptr
, pszFormat
);
1974 int iLen
= PrintfV(pszFormat
, argptr
);
1979 // ============================================================================
1981 // ============================================================================
1983 #include "wx/arrstr.h"
1985 wxArrayString::wxArrayString(size_t sz
, const wxChar
** a
)
1990 for (size_t i
=0; i
< sz
; i
++)
1994 wxArrayString::wxArrayString(size_t sz
, const wxString
* a
)
1999 for (size_t i
=0; i
< sz
; i
++)
2005 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
2006 #define ARRAY_MAXSIZE_INCREMENT 4096
2008 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
2009 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
2012 #define STRING(p) ((wxString *)(&(p)))
2015 void wxArrayString::Init(bool autoSort
)
2019 m_pItems
= (wxChar
**) NULL
;
2020 m_autoSort
= autoSort
;
2024 wxArrayString::wxArrayString(const wxArrayString
& src
)
2026 Init(src
.m_autoSort
);
2031 // assignment operator
2032 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
2039 m_autoSort
= src
.m_autoSort
;
2044 void wxArrayString::Copy(const wxArrayString
& src
)
2046 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
2047 Alloc(src
.m_nCount
);
2049 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
2054 void wxArrayString::Grow(size_t nIncrement
)
2056 // only do it if no more place
2057 if ( (m_nSize
- m_nCount
) < nIncrement
) {
2058 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2059 // be never resized!
2060 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2061 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2064 if ( m_nSize
== 0 ) {
2065 // was empty, alloc some memory
2066 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
2067 if (m_nSize
< nIncrement
)
2068 m_nSize
= nIncrement
;
2069 m_pItems
= new wxChar
*[m_nSize
];
2072 // otherwise when it's called for the first time, nIncrement would be 0
2073 // and the array would never be expanded
2074 // add 50% but not too much
2075 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
2076 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
2077 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
2078 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
2079 if ( nIncrement
< ndefIncrement
)
2080 nIncrement
= ndefIncrement
;
2081 m_nSize
+= nIncrement
;
2082 wxChar
**pNew
= new wxChar
*[m_nSize
];
2084 // copy data to new location
2085 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2087 // delete old memory (but do not release the strings!)
2088 wxDELETEA(m_pItems
);
2095 void wxArrayString::Free()
2097 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
2098 STRING(m_pItems
[n
])->GetStringData()->Unlock();
2102 // deletes all the strings from the list
2103 void wxArrayString::Empty()
2110 // as Empty, but also frees memory
2111 void wxArrayString::Clear()
2118 wxDELETEA(m_pItems
);
2122 wxArrayString::~wxArrayString()
2126 wxDELETEA(m_pItems
);
2129 void wxArrayString::reserve(size_t nSize
)
2134 // pre-allocates memory (frees the previous data!)
2135 void wxArrayString::Alloc(size_t nSize
)
2137 // only if old buffer was not big enough
2138 if ( nSize
> m_nSize
) {
2140 wxDELETEA(m_pItems
);
2141 m_pItems
= new wxChar
*[nSize
];
2148 // minimizes the memory usage by freeing unused memory
2149 void wxArrayString::Shrink()
2151 // only do it if we have some memory to free
2152 if( m_nCount
< m_nSize
) {
2153 // allocates exactly as much memory as we need
2154 wxChar
**pNew
= new wxChar
*[m_nCount
];
2156 // copy data to new location
2157 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2163 #if WXWIN_COMPATIBILITY_2_4
2165 // return a wxString[] as required for some control ctors.
2166 wxString
* wxArrayString::GetStringArray() const
2168 wxString
*array
= 0;
2172 array
= new wxString
[m_nCount
];
2173 for( size_t i
= 0; i
< m_nCount
; i
++ )
2174 array
[i
] = m_pItems
[i
];
2180 void wxArrayString::Remove(size_t nIndex
, size_t nRemove
)
2182 RemoveAt(nIndex
, nRemove
);
2185 #endif // WXWIN_COMPATIBILITY_2_4
2187 // searches the array for an item (forward or backwards)
2188 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2191 // use binary search in the sorted array
2192 wxASSERT_MSG( bCase
&& !bFromEnd
,
2193 wxT("search parameters ignored for auto sorted array") );
2202 res
= wxStrcmp(sz
, m_pItems
[i
]);
2214 // use linear search in unsorted array
2216 if ( m_nCount
> 0 ) {
2217 size_t ui
= m_nCount
;
2219 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2226 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2227 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2236 // add item at the end
2237 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
2240 // insert the string at the correct position to keep the array sorted
2248 res
= str
.Cmp(m_pItems
[i
]);
2259 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2261 Insert(str
, lo
, nInsert
);
2266 wxASSERT( str
.GetStringData()->IsValid() );
2270 for (size_t i
= 0; i
< nInsert
; i
++)
2272 // the string data must not be deleted!
2273 str
.GetStringData()->Lock();
2276 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2278 size_t ret
= m_nCount
;
2279 m_nCount
+= nInsert
;
2284 // add item at the given position
2285 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2287 wxASSERT( str
.GetStringData()->IsValid() );
2289 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2290 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2291 wxT("array size overflow in wxArrayString::Insert") );
2295 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2296 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2298 for (size_t i
= 0; i
< nInsert
; i
++)
2300 str
.GetStringData()->Lock();
2301 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2303 m_nCount
+= nInsert
;
2306 // range insert (STL 23.2.4.3)
2308 wxArrayString::insert(iterator it
, const_iterator first
, const_iterator last
)
2310 const int idx
= it
- begin();
2315 // reset "it" since it can change inside Grow()
2318 while ( first
!= last
)
2320 it
= insert(it
, *first
);
2322 // insert returns an iterator to the last element inserted but we need
2323 // insert the next after this one, that is before the next one
2331 void wxArrayString::SetCount(size_t count
)
2336 while ( m_nCount
< count
)
2337 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2340 // removes item from array (by index)
2341 void wxArrayString::RemoveAt(size_t nIndex
, size_t nRemove
)
2343 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2344 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2345 wxT("removing too many elements in wxArrayString::Remove") );
2348 for (size_t i
= 0; i
< nRemove
; i
++)
2349 Item(nIndex
+ i
).GetStringData()->Unlock();
2351 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2352 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2353 m_nCount
-= nRemove
;
2356 // removes item from array (by value)
2357 void wxArrayString::Remove(const wxChar
*sz
)
2359 int iIndex
= Index(sz
);
2361 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2362 wxT("removing inexistent element in wxArrayString::Remove") );
2367 void wxArrayString::assign(const_iterator first
, const_iterator last
)
2369 reserve(last
- first
);
2370 for(; first
!= last
; ++first
)
2374 // ----------------------------------------------------------------------------
2376 // ----------------------------------------------------------------------------
2378 // we can only sort one array at a time with the quick-sort based
2381 // need a critical section to protect access to gs_compareFunction and
2382 // gs_sortAscending variables
2383 static wxCriticalSection gs_critsectStringSort
;
2384 #endif // wxUSE_THREADS
2386 // function to use for string comparaison
2387 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2389 // if we don't use the compare function, this flag tells us if we sort the
2390 // array in ascending or descending order
2391 static bool gs_sortAscending
= true;
2393 // function which is called by quick sort
2394 extern "C" int wxC_CALLING_CONV
// LINKAGEMODE
2395 wxStringCompareFunction(const void *first
, const void *second
)
2397 wxString
*strFirst
= (wxString
*)first
;
2398 wxString
*strSecond
= (wxString
*)second
;
2400 if ( gs_compareFunction
) {
2401 return gs_compareFunction(*strFirst
, *strSecond
);
2404 // maybe we should use wxStrcoll
2405 int result
= strFirst
->Cmp(*strSecond
);
2407 return gs_sortAscending
? result
: -result
;
2411 // sort array elements using passed comparaison function
2412 void wxArrayString::Sort(CompareFunction compareFunction
)
2414 wxCRIT_SECT_LOCKER(lockCmpFunc
, gs_critsectStringSort
);
2416 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2417 gs_compareFunction
= compareFunction
;
2421 // reset it to NULL so that Sort(bool) will work the next time
2422 gs_compareFunction
= NULL
;
2427 typedef int (wxC_CALLING_CONV
* wxStringCompareFn
)(const void *first
,
2428 const void *second
);
2431 void wxArrayString::Sort(CompareFunction2 compareFunction
)
2433 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), (wxStringCompareFn
)compareFunction
);
2436 void wxArrayString::Sort(bool reverseOrder
)
2438 Sort(reverseOrder
? wxStringSortDescending
: wxStringSortAscending
);
2441 void wxArrayString::DoSort()
2443 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2445 // just sort the pointers using qsort() - of course it only works because
2446 // wxString() *is* a pointer to its data
2447 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2450 bool wxArrayString::operator==(const wxArrayString
& a
) const
2452 if ( m_nCount
!= a
.m_nCount
)
2455 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2457 if ( Item(n
) != a
[n
] )
2464 #endif // !wxUSE_STL
2466 int wxCMPFUNC_CONV
wxStringSortAscending(wxString
* s1
, wxString
* s2
)
2468 return s1
->Cmp(*s2
);
2471 int wxCMPFUNC_CONV
wxStringSortDescending(wxString
* s1
, wxString
* s2
)
2473 return -s1
->Cmp(*s2
);