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
89 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
92 // ATTN: you can _not_ use both of these in the same program!
96 wxSTD istream
& operator>>(wxSTD istream
& is
, wxString
& WXUNUSED(str
))
101 streambuf
*sb
= is
.rdbuf();
104 int ch
= sb
->sbumpc ();
106 is
.setstate(ios::eofbit
);
109 else if ( isspace(ch
) ) {
121 if ( str
.length() == 0 )
122 is
.setstate(ios::failbit
);
127 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
137 #endif // wxUSE_STD_IOSTREAM
139 // ----------------------------------------------------------------------------
141 // ----------------------------------------------------------------------------
143 // this small class is used to gather statistics for performance tuning
144 //#define WXSTRING_STATISTICS
145 #ifdef WXSTRING_STATISTICS
149 Averager(const wxChar
*sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
151 { wxPrintf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
153 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
156 size_t m_nCount
, m_nTotal
;
158 } g_averageLength("allocation size"),
159 g_averageSummandLength("summand length"),
160 g_averageConcatHit("hit probability in concat"),
161 g_averageInitialLength("initial string length");
163 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
165 #define STATISTICS_ADD(av, val)
166 #endif // WXSTRING_STATISTICS
170 // ===========================================================================
171 // wxStringData class deallocation
172 // ===========================================================================
174 #if defined(__VISUALC__) && defined(_MT) && !defined(_DLL)
175 # pragma message (__FILE__ ": building with Multithreaded non DLL runtime has a performance impact on wxString!")
176 void wxStringData::Free()
182 // ===========================================================================
184 // ===========================================================================
186 // takes nLength elements of psz starting at nPos
187 void wxStringBase::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
191 // if the length is not given, assume the string to be NUL terminated
192 if ( nLength
== npos
) {
193 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
195 nLength
= wxStrlen(psz
+ nPos
);
198 STATISTICS_ADD(InitialLength
, nLength
);
201 // trailing '\0' is written in AllocBuffer()
202 if ( !AllocBuffer(nLength
) ) {
203 wxFAIL_MSG( _T("out of memory in wxStringBase::InitWith") );
206 wxTmemcpy(m_pchData
, psz
+ nPos
, nLength
);
210 // poor man's iterators are "void *" pointers
211 wxStringBase::wxStringBase(const void *pStart
, const void *pEnd
)
213 InitWith((const wxChar
*)pStart
, 0,
214 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
217 wxStringBase::wxStringBase(size_type n
, wxChar ch
)
223 // ---------------------------------------------------------------------------
225 // ---------------------------------------------------------------------------
227 // allocates memory needed to store a C string of length nLen
228 bool wxStringBase::AllocBuffer(size_t nLen
)
230 // allocating 0 sized buffer doesn't make sense, all empty strings should
232 wxASSERT( nLen
> 0 );
234 // make sure that we don't overflow
235 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
236 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
238 STATISTICS_ADD(Length
, nLen
);
241 // 1) one extra character for '\0' termination
242 // 2) sizeof(wxStringData) for housekeeping info
243 wxStringData
* pData
= (wxStringData
*)
244 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
246 if ( pData
== NULL
) {
247 // allocation failures are handled by the caller
252 pData
->nDataLength
= nLen
;
253 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
254 m_pchData
= pData
->data(); // data starts after wxStringData
255 m_pchData
[nLen
] = wxT('\0');
259 // must be called before changing this string
260 bool wxStringBase::CopyBeforeWrite()
262 wxStringData
* pData
= GetStringData();
264 if ( pData
->IsShared() ) {
265 pData
->Unlock(); // memory not freed because shared
266 size_t nLen
= pData
->nDataLength
;
267 if ( !AllocBuffer(nLen
) ) {
268 // allocation failures are handled by the caller
271 wxTmemcpy(m_pchData
, pData
->data(), nLen
);
274 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
279 // must be called before replacing contents of this string
280 bool wxStringBase::AllocBeforeWrite(size_t nLen
)
282 wxASSERT( nLen
!= 0 ); // doesn't make any sense
284 // must not share string and must have enough space
285 wxStringData
* pData
= GetStringData();
286 if ( pData
->IsShared() || pData
->IsEmpty() ) {
287 // can't work with old buffer, get new one
289 if ( !AllocBuffer(nLen
) ) {
290 // allocation failures are handled by the caller
295 if ( nLen
> pData
->nAllocLength
) {
296 // realloc the buffer instead of calling malloc() again, this is more
298 STATISTICS_ADD(Length
, nLen
);
302 pData
= (wxStringData
*)
303 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
305 if ( pData
== NULL
) {
306 // allocation failures are handled by the caller
307 // keep previous data since reallocation failed
311 pData
->nAllocLength
= nLen
;
312 m_pchData
= pData
->data();
316 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
318 // it doesn't really matter what the string length is as it's going to be
319 // overwritten later but, for extra safety, set it to 0 for now as we may
320 // have some junk in m_pchData
321 GetStringData()->nDataLength
= 0;
326 wxStringBase
& wxStringBase::append(size_t n
, wxChar ch
)
328 size_type len
= length();
330 if ( !Alloc(len
+ n
) || !CopyBeforeWrite() ) {
331 wxFAIL_MSG( _T("out of memory in wxStringBase::append") );
333 GetStringData()->nDataLength
= len
+ n
;
334 m_pchData
[len
+ n
] = '\0';
335 for ( size_t i
= 0; i
< n
; ++i
)
336 m_pchData
[len
+ i
] = ch
;
340 void wxStringBase::resize(size_t nSize
, wxChar ch
)
342 size_t len
= length();
346 erase(begin() + nSize
, end());
348 else if ( nSize
> len
)
350 append(nSize
- len
, ch
);
352 //else: we have exactly the specified length, nothing to do
355 // allocate enough memory for nLen characters
356 bool wxStringBase::Alloc(size_t nLen
)
358 wxStringData
*pData
= GetStringData();
359 if ( pData
->nAllocLength
<= nLen
) {
360 if ( pData
->IsEmpty() ) {
363 pData
= (wxStringData
*)
364 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
366 if ( pData
== NULL
) {
367 // allocation failure handled by caller
372 pData
->nDataLength
= 0;
373 pData
->nAllocLength
= nLen
;
374 m_pchData
= pData
->data(); // data starts after wxStringData
375 m_pchData
[0u] = wxT('\0');
377 else if ( pData
->IsShared() ) {
378 pData
->Unlock(); // memory not freed because shared
379 size_t nOldLen
= pData
->nDataLength
;
380 if ( !AllocBuffer(nLen
) ) {
381 // allocation failure handled by caller
384 // +1 to copy the terminator, too
385 memcpy(m_pchData
, pData
->data(), (nOldLen
+1)*sizeof(wxChar
));
386 GetStringData()->nDataLength
= nOldLen
;
391 pData
= (wxStringData
*)
392 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
394 if ( pData
== NULL
) {
395 // allocation failure handled by caller
396 // keep previous data since reallocation failed
400 // it's not important if the pointer changed or not (the check for this
401 // is not faster than assigning to m_pchData in all cases)
402 pData
->nAllocLength
= nLen
;
403 m_pchData
= pData
->data();
406 //else: we've already got enough
410 wxStringBase::iterator
wxStringBase::begin()
417 wxStringBase::iterator
wxStringBase::end()
421 return m_pchData
+ length();
424 wxStringBase::iterator
wxStringBase::erase(iterator it
)
426 size_type idx
= it
- begin();
428 return begin() + idx
;
431 wxStringBase
& wxStringBase::erase(size_t nStart
, size_t nLen
)
433 wxASSERT(nStart
<= length());
434 size_t strLen
= length() - nStart
;
435 // delete nLen or up to the end of the string characters
436 nLen
= strLen
< nLen
? strLen
: nLen
;
437 wxString
strTmp(c_str(), nStart
);
438 strTmp
.append(c_str() + nStart
+ nLen
, length() - nStart
- nLen
);
444 wxStringBase
& wxStringBase::insert(size_t nPos
, const wxChar
*sz
, size_t n
)
446 wxASSERT( nPos
<= length() );
448 if ( n
== npos
) n
= wxStrlen(sz
);
449 if ( n
== 0 ) return *this;
451 if ( !Alloc(length() + n
) || !CopyBeforeWrite() ) {
452 wxFAIL_MSG( _T("out of memory in wxStringBase::insert") );
455 memmove(m_pchData
+ nPos
+ n
, m_pchData
+ nPos
,
456 (length() - nPos
) * sizeof(wxChar
));
457 memcpy(m_pchData
+ nPos
, sz
, n
* sizeof(wxChar
));
458 GetStringData()->nDataLength
= length() + n
;
459 m_pchData
[length()] = '\0';
464 void wxStringBase::swap(wxStringBase
& str
)
466 wxChar
* tmp
= str
.m_pchData
;
467 str
.m_pchData
= m_pchData
;
471 size_t wxStringBase::find(const wxStringBase
& str
, size_t nStart
) const
473 wxASSERT( str
.GetStringData()->IsValid() );
474 wxASSERT( nStart
<= length() );
477 const wxChar
* p
= (const wxChar
*)wxTmemchr(c_str() + nStart
,
484 while(p
- c_str() + str
.length() <= length() &&
485 wxTmemcmp(p
, str
.c_str(), str
.length()) )
487 //Previosly passed as the first argument to wxTmemchr,
488 //but C/C++ standard does not specify evaluation order
489 //of arguments to functions -
490 //http://embedded.com/showArticle.jhtml?articleID=9900607
494 p
= (const wxChar
*)wxTmemchr(p
,
496 length() - (p
- c_str()));
502 return (p
- c_str() + str
.length() <= length()) ? p
- c_str() : npos
;
505 size_t wxStringBase::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
507 return find(wxStringBase(sz
, n
), nStart
);
510 size_t wxStringBase::find(wxChar ch
, size_t nStart
) const
512 wxASSERT( nStart
<= length() );
514 const wxChar
*p
= (const wxChar
*)wxTmemchr(c_str() + nStart
, ch
, length() - nStart
);
516 return p
== NULL
? npos
: p
- c_str();
519 size_t wxStringBase::rfind(const wxStringBase
& str
, size_t nStart
) const
521 wxASSERT( str
.GetStringData()->IsValid() );
522 wxASSERT( nStart
== npos
|| nStart
<= length() );
524 if ( length() >= str
.length() )
526 // avoids a corner case later
527 if ( length() == 0 && str
.length() == 0 )
530 // "top" is the point where search starts from
531 size_t top
= length() - str
.length();
533 if ( nStart
== npos
)
534 nStart
= length() - 1;
538 const wxChar
*cursor
= c_str() + top
;
541 if ( wxTmemcmp(cursor
, str
.c_str(),
544 return cursor
- c_str();
546 } while ( cursor
-- > c_str() );
552 size_t wxStringBase::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
554 return rfind(wxStringBase(sz
, n
), nStart
);
557 size_t wxStringBase::rfind(wxChar ch
, size_t nStart
) const
559 if ( nStart
== npos
)
565 wxASSERT( nStart
<= length() );
568 const wxChar
*actual
;
569 for ( actual
= c_str() + ( nStart
== npos
? length() : nStart
+ 1 );
570 actual
> c_str(); --actual
)
572 if ( *(actual
- 1) == ch
)
573 return (actual
- 1) - c_str();
579 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
) const
581 wxASSERT(nStart
<= length());
583 size_t len
= wxStrlen(sz
);
586 for(i
= nStart
; i
< this->length(); ++i
)
588 if (wxTmemchr(sz
, *(c_str() + i
), len
))
592 if(i
== this->length())
598 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
,
601 return find_first_of(wxStringBase(sz
, n
), nStart
);
604 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
) const
606 if ( nStart
== npos
)
608 nStart
= length() - 1;
612 wxASSERT_MSG( nStart
<= length(),
613 _T("invalid index in find_last_of()") );
616 size_t len
= wxStrlen(sz
);
618 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
620 if ( wxTmemchr(sz
, *p
, len
) )
627 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
,
630 return find_last_of(wxStringBase(sz
, n
), nStart
);
633 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
635 if ( nStart
== npos
)
641 wxASSERT( nStart
<= length() );
644 size_t len
= wxStrlen(sz
);
647 for(i
= nStart
; i
< this->length(); ++i
)
649 if (!wxTmemchr(sz
, *(c_str() + i
), len
))
653 if(i
== this->length())
659 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
,
662 return find_first_not_of(wxStringBase(sz
, n
), nStart
);
665 size_t wxStringBase::find_first_not_of(wxChar ch
, size_t nStart
) const
667 wxASSERT( nStart
<= length() );
669 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
678 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
680 if ( nStart
== npos
)
682 nStart
= length() - 1;
686 wxASSERT( nStart
<= length() );
689 size_t len
= wxStrlen(sz
);
691 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
693 if ( !wxTmemchr(sz
, *p
,len
) )
700 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
,
703 return find_last_not_of(wxStringBase(sz
, n
), nStart
);
706 size_t wxStringBase::find_last_not_of(wxChar ch
, size_t nStart
) const
708 if ( nStart
== npos
)
710 nStart
= length() - 1;
714 wxASSERT( nStart
<= length() );
717 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
726 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
729 wxASSERT_MSG( nStart
<= length(),
730 _T("index out of bounds in wxStringBase::replace") );
731 size_t strLen
= length() - nStart
;
732 nLen
= strLen
< nLen
? strLen
: nLen
;
735 strTmp
.reserve(length()); // micro optimisation to avoid multiple mem allocs
737 //This is kind of inefficient, but its pretty good considering...
738 //we don't want to use character access operators here because on STL
739 //it will freeze the reference count of strTmp, which means a deep copy
740 //at the end when swap is called
742 //Also, we can't use append with the full character pointer and must
743 //do it manually because this string can contain null characters
744 for(size_t i1
= 0; i1
< nStart
; ++i1
)
745 strTmp
.append(1, this->c_str()[i1
]);
747 //its safe to do the full version here because
748 //sz must be a normal c string
751 for(size_t i2
= nStart
+ nLen
; i2
< length(); ++i2
)
752 strTmp
.append(1, this->c_str()[i2
]);
758 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
759 size_t nCount
, wxChar ch
)
761 return replace(nStart
, nLen
, wxStringBase(nCount
, ch
).c_str());
764 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
765 const wxStringBase
& str
,
766 size_t nStart2
, size_t nLen2
)
768 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
771 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
772 const wxChar
* sz
, size_t nCount
)
774 return replace(nStart
, nLen
, wxStringBase(sz
, nCount
).c_str());
777 wxStringBase
wxStringBase::substr(size_t nStart
, size_t nLen
) const
780 nLen
= length() - nStart
;
781 return wxStringBase(*this, nStart
, nLen
);
784 // assigns one string to another
785 wxStringBase
& wxStringBase::operator=(const wxStringBase
& stringSrc
)
787 wxASSERT( stringSrc
.GetStringData()->IsValid() );
789 // don't copy string over itself
790 if ( m_pchData
!= stringSrc
.m_pchData
) {
791 if ( stringSrc
.GetStringData()->IsEmpty() ) {
796 GetStringData()->Unlock();
797 m_pchData
= stringSrc
.m_pchData
;
798 GetStringData()->Lock();
805 // assigns a single character
806 wxStringBase
& wxStringBase::operator=(wxChar ch
)
808 if ( !AssignCopy(1, &ch
) ) {
809 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(wxChar)") );
815 wxStringBase
& wxStringBase::operator=(const wxChar
*psz
)
817 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
818 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(const wxChar *)") );
823 // helper function: does real copy
824 bool wxStringBase::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
826 if ( nSrcLen
== 0 ) {
830 if ( !AllocBeforeWrite(nSrcLen
) ) {
831 // allocation failure handled by caller
834 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
835 GetStringData()->nDataLength
= nSrcLen
;
836 m_pchData
[nSrcLen
] = wxT('\0');
841 // ---------------------------------------------------------------------------
842 // string concatenation
843 // ---------------------------------------------------------------------------
845 // add something to this string
846 bool wxStringBase::ConcatSelf(size_t nSrcLen
, const wxChar
*pszSrcData
,
849 STATISTICS_ADD(SummandLength
, nSrcLen
);
851 nSrcLen
= nSrcLen
< nMaxLen
? nSrcLen
: nMaxLen
;
853 // concatenating an empty string is a NOP
855 wxStringData
*pData
= GetStringData();
856 size_t nLen
= pData
->nDataLength
;
857 size_t nNewLen
= nLen
+ nSrcLen
;
859 // alloc new buffer if current is too small
860 if ( pData
->IsShared() ) {
861 STATISTICS_ADD(ConcatHit
, 0);
863 // we have to allocate another buffer
864 wxStringData
* pOldData
= GetStringData();
865 if ( !AllocBuffer(nNewLen
) ) {
866 // allocation failure handled by caller
869 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
872 else if ( nNewLen
> pData
->nAllocLength
) {
873 STATISTICS_ADD(ConcatHit
, 0);
876 // we have to grow the buffer
877 if ( capacity() < nNewLen
) {
878 // allocation failure handled by caller
883 STATISTICS_ADD(ConcatHit
, 1);
885 // the buffer is already big enough
888 // should be enough space
889 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
891 // fast concatenation - all is done in our buffer
892 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
894 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
895 GetStringData()->nDataLength
= nNewLen
; // and fix the length
897 //else: the string to append was empty
901 // ---------------------------------------------------------------------------
902 // simple sub-string extraction
903 // ---------------------------------------------------------------------------
905 // helper function: clone the data attached to this string
906 bool wxStringBase::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
908 if ( nCopyLen
== 0 ) {
912 if ( !dest
.AllocBuffer(nCopyLen
) ) {
913 // allocation failure handled by caller
916 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
923 #if !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
926 #define STRINGCLASS wxStringBase
928 #define STRINGCLASS wxString
931 static inline int wxDoCmp(const wxChar
* s1
, size_t l1
,
932 const wxChar
* s2
, size_t l2
)
935 return wxTmemcmp(s1
, s2
, l1
);
938 int ret
= wxTmemcmp(s1
, s2
, l1
);
939 return ret
== 0 ? -1 : ret
;
943 int ret
= wxTmemcmp(s1
, s2
, l2
);
944 return ret
== 0 ? +1 : ret
;
948 int STRINGCLASS::compare(const wxStringBase
& str
) const
950 return ::wxDoCmp(data(), length(), str
.data(), str
.length());
953 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
954 const wxStringBase
& str
) const
956 wxASSERT(nStart
<= length());
957 size_type strLen
= length() - nStart
;
958 nLen
= strLen
< nLen
? strLen
: nLen
;
959 return ::wxDoCmp(data() + nStart
, nLen
, str
.data(), str
.length());
962 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
963 const wxStringBase
& str
,
964 size_t nStart2
, size_t nLen2
) const
966 wxASSERT(nStart
<= length());
967 wxASSERT(nStart2
<= str
.length());
968 size_type strLen
= length() - nStart
,
969 strLen2
= str
.length() - nStart2
;
970 nLen
= strLen
< nLen
? strLen
: nLen
;
971 nLen2
= strLen2
< nLen2
? strLen2
: nLen2
;
972 return ::wxDoCmp(data() + nStart
, nLen
, str
.data() + nStart2
, nLen2
);
975 int STRINGCLASS::compare(const wxChar
* sz
) const
977 size_t nLen
= wxStrlen(sz
);
978 return ::wxDoCmp(data(), length(), sz
, nLen
);
981 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
982 const wxChar
* sz
, size_t nCount
) const
984 wxASSERT(nStart
<= length());
985 size_type strLen
= length() - nStart
;
986 nLen
= strLen
< nLen
? strLen
: nLen
;
988 nCount
= wxStrlen(sz
);
990 return ::wxDoCmp(data() + nStart
, nLen
, sz
, nCount
);
995 #endif // !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
997 // ===========================================================================
998 // wxString class core
999 // ===========================================================================
1001 // ---------------------------------------------------------------------------
1002 // construction and conversion
1003 // ---------------------------------------------------------------------------
1007 // from multibyte string
1008 wxString::wxString(const char *psz
, const wxMBConv
& conv
, size_t nLength
)
1011 if ( psz
&& nLength
!= 0 )
1013 if ( nLength
== npos
)
1019 wxWCharBuffer wbuf
= conv
.cMB2WC(psz
, nLength
, &nLenWide
);
1022 assign(wbuf
, nLenWide
);
1026 //Convert wxString in Unicode mode to a multi-byte string
1027 const wxCharBuffer
wxString::mb_str(const wxMBConv
& conv
) const
1029 return conv
.cWC2MB(c_str(), length() + 1 /* size, not length */, NULL
);
1037 wxString::wxString(const wchar_t *pwz
, const wxMBConv
& conv
, size_t nLength
)
1040 if ( pwz
&& nLength
!= 0 )
1042 if ( nLength
== npos
)
1048 wxCharBuffer buf
= conv
.cWC2MB(pwz
, nLength
, &nLenMB
);
1051 assign(buf
, nLenMB
);
1055 //Converts this string to a wide character string if unicode
1056 //mode is not enabled and wxUSE_WCHAR_T is enabled
1057 const wxWCharBuffer
wxString::wc_str(const wxMBConv
& conv
) const
1059 return conv
.cMB2WC(c_str(), length() + 1 /* size, not length */, NULL
);
1062 #endif // wxUSE_WCHAR_T
1064 #endif // Unicode/ANSI
1066 // shrink to minimal size (releasing extra memory)
1067 bool wxString::Shrink()
1069 wxString
tmp(begin(), end());
1071 return tmp
.length() == length();
1075 // get the pointer to writable buffer of (at least) nLen bytes
1076 wxChar
*wxString::GetWriteBuf(size_t nLen
)
1078 if ( !AllocBeforeWrite(nLen
) ) {
1079 // allocation failure handled by caller
1083 wxASSERT( GetStringData()->nRefs
== 1 );
1084 GetStringData()->Validate(false);
1089 // put string back in a reasonable state after GetWriteBuf
1090 void wxString::UngetWriteBuf()
1092 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
1093 GetStringData()->Validate(true);
1096 void wxString::UngetWriteBuf(size_t nLen
)
1098 GetStringData()->nDataLength
= nLen
;
1099 GetStringData()->Validate(true);
1103 // ---------------------------------------------------------------------------
1105 // ---------------------------------------------------------------------------
1107 // all functions are inline in string.h
1109 // ---------------------------------------------------------------------------
1110 // assignment operators
1111 // ---------------------------------------------------------------------------
1115 // same as 'signed char' variant
1116 wxString
& wxString::operator=(const unsigned char* psz
)
1118 *this = (const char *)psz
;
1123 wxString
& wxString::operator=(const wchar_t *pwz
)
1134 * concatenation functions come in 5 flavours:
1136 * char + string and string + char
1137 * C str + string and string + C str
1140 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
1143 wxASSERT( str1
.GetStringData()->IsValid() );
1144 wxASSERT( str2
.GetStringData()->IsValid() );
1153 wxString
operator+(const wxString
& str
, wxChar ch
)
1156 wxASSERT( str
.GetStringData()->IsValid() );
1165 wxString
operator+(wxChar ch
, const wxString
& str
)
1168 wxASSERT( str
.GetStringData()->IsValid() );
1177 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
1180 wxASSERT( str
.GetStringData()->IsValid() );
1184 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
1185 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1193 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
1196 wxASSERT( str
.GetStringData()->IsValid() );
1200 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
1201 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1209 // ===========================================================================
1210 // other common string functions
1211 // ===========================================================================
1213 int wxString::Cmp(const wxString
& s
) const
1218 int wxString::Cmp(const wxChar
* psz
) const
1220 return compare(psz
);
1223 static inline int wxDoCmpNoCase(const wxChar
* s1
, size_t l1
,
1224 const wxChar
* s2
, size_t l2
)
1230 for(i
= 0; i
< l1
; ++i
)
1232 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1235 return i
== l1
? 0 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1239 for(i
= 0; i
< l1
; ++i
)
1241 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1244 return i
== l1
? -1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1248 for(i
= 0; i
< l2
; ++i
)
1250 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1253 return i
== l2
? 1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1257 int wxString::CmpNoCase(const wxString
& s
) const
1259 return wxDoCmpNoCase(data(), length(), s
.data(), s
.length());
1262 int wxString::CmpNoCase(const wxChar
* psz
) const
1264 int nLen
= wxStrlen(psz
);
1266 return wxDoCmpNoCase(data(), length(), psz
, nLen
);
1273 #ifndef __SCHAR_MAX__
1274 #define __SCHAR_MAX__ 127
1278 wxString
wxString::FromAscii(const char *ascii
)
1281 return wxEmptyString
;
1283 size_t len
= strlen( ascii
);
1288 wxStringBuffer
buf(res
, len
);
1290 wchar_t *dest
= buf
;
1294 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
1302 wxString
wxString::FromAscii(const char ascii
)
1304 // What do we do with '\0' ?
1307 res
+= (wchar_t)(unsigned char) ascii
;
1312 const wxCharBuffer
wxString::ToAscii() const
1314 // this will allocate enough space for the terminating NUL too
1315 wxCharBuffer
buffer(length());
1318 char *dest
= buffer
.data();
1320 const wchar_t *pwc
= c_str();
1323 *dest
++ = (char)(*pwc
> SCHAR_MAX
? wxT('_') : *pwc
);
1325 // the output string can't have embedded NULs anyhow, so we can safely
1326 // stop at first of them even if we do have any
1336 // extract string of length nCount starting at nFirst
1337 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
1339 size_t nLen
= length();
1341 // default value of nCount is npos and means "till the end"
1342 if ( nCount
== npos
)
1344 nCount
= nLen
- nFirst
;
1347 // out-of-bounds requests return sensible things
1348 if ( nFirst
+ nCount
> nLen
)
1350 nCount
= nLen
- nFirst
;
1353 if ( nFirst
> nLen
)
1355 // AllocCopy() will return empty string
1356 return wxEmptyString
;
1359 wxString
dest(*this, nFirst
, nCount
);
1360 if ( dest
.length() != nCount
)
1362 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
1368 // check that the string starts with prefix and return the rest of the string
1369 // in the provided pointer if it is not NULL, otherwise return false
1370 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
1372 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
1374 // first check if the beginning of the string matches the prefix: note
1375 // that we don't have to check that we don't run out of this string as
1376 // when we reach the terminating NUL, either prefix string ends too (and
1377 // then it's ok) or we break out of the loop because there is no match
1378 const wxChar
*p
= c_str();
1381 if ( *prefix
++ != *p
++ )
1390 // put the rest of the string into provided pointer
1398 // check that the string ends with suffix and return the rest of it in the
1399 // provided pointer if it is not NULL, otherwise return false
1400 bool wxString::EndsWith(const wxChar
*suffix
, wxString
*rest
) const
1402 wxASSERT_MSG( suffix
, _T("invalid parameter in wxString::EndssWith") );
1404 int start
= length() - wxStrlen(suffix
);
1405 if ( start
< 0 || wxStrcmp(c_str() + start
, suffix
) != 0 )
1410 // put the rest of the string into provided pointer
1411 rest
->assign(*this, 0, start
);
1418 // extract nCount last (rightmost) characters
1419 wxString
wxString::Right(size_t nCount
) const
1421 if ( nCount
> length() )
1424 wxString
dest(*this, length() - nCount
, nCount
);
1425 if ( dest
.length() != nCount
) {
1426 wxFAIL_MSG( _T("out of memory in wxString::Right") );
1431 // get all characters after the last occurence of ch
1432 // (returns the whole string if ch not found)
1433 wxString
wxString::AfterLast(wxChar ch
) const
1436 int iPos
= Find(ch
, true);
1437 if ( iPos
== wxNOT_FOUND
)
1440 str
= c_str() + iPos
+ 1;
1445 // extract nCount first (leftmost) characters
1446 wxString
wxString::Left(size_t nCount
) const
1448 if ( nCount
> length() )
1451 wxString
dest(*this, 0, nCount
);
1452 if ( dest
.length() != nCount
) {
1453 wxFAIL_MSG( _T("out of memory in wxString::Left") );
1458 // get all characters before the first occurence of ch
1459 // (returns the whole string if ch not found)
1460 wxString
wxString::BeforeFirst(wxChar ch
) const
1462 int iPos
= Find(ch
);
1463 if ( iPos
== wxNOT_FOUND
) iPos
= length();
1464 return wxString(*this, 0, iPos
);
1467 /// get all characters before the last occurence of ch
1468 /// (returns empty string if ch not found)
1469 wxString
wxString::BeforeLast(wxChar ch
) const
1472 int iPos
= Find(ch
, true);
1473 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
1474 str
= wxString(c_str(), iPos
);
1479 /// get all characters after the first occurence of ch
1480 /// (returns empty string if ch not found)
1481 wxString
wxString::AfterFirst(wxChar ch
) const
1484 int iPos
= Find(ch
);
1485 if ( iPos
!= wxNOT_FOUND
)
1486 str
= c_str() + iPos
+ 1;
1491 // replace first (or all) occurences of some substring with another one
1492 size_t wxString::Replace(const wxChar
*szOld
,
1493 const wxChar
*szNew
, bool bReplaceAll
)
1495 // if we tried to replace an empty string we'd enter an infinite loop below
1496 wxCHECK_MSG( szOld
&& *szOld
&& szNew
, 0,
1497 _T("wxString::Replace(): invalid parameter") );
1499 size_t uiCount
= 0; // count of replacements made
1501 size_t uiOldLen
= wxStrlen(szOld
);
1502 size_t uiNewLen
= wxStrlen(szNew
);
1506 while ( this->c_str()[dwPos
] != wxT('\0') )
1508 //DO NOT USE STRSTR HERE
1509 //this string can contain embedded null characters,
1510 //so strstr will function incorrectly
1511 dwPos
= find(szOld
, dwPos
);
1512 if ( dwPos
== npos
)
1513 break; // exit the loop
1516 //replace this occurance of the old string with the new one
1517 replace(dwPos
, uiOldLen
, szNew
, uiNewLen
);
1519 //move up pos past the string that was replaced
1522 //increase replace count
1527 break; // exit the loop
1534 bool wxString::IsAscii() const
1536 const wxChar
*s
= (const wxChar
*) *this;
1538 if(!isascii(*s
)) return(false);
1544 bool wxString::IsWord() const
1546 const wxChar
*s
= (const wxChar
*) *this;
1548 if(!wxIsalpha(*s
)) return(false);
1554 bool wxString::IsNumber() const
1556 const wxChar
*s
= (const wxChar
*) *this;
1558 if ((s
[0] == wxT('-')) || (s
[0] == wxT('+'))) s
++;
1560 if(!wxIsdigit(*s
)) return(false);
1566 wxString
wxString::Strip(stripType w
) const
1569 if ( w
& leading
) s
.Trim(false);
1570 if ( w
& trailing
) s
.Trim(true);
1574 // ---------------------------------------------------------------------------
1576 // ---------------------------------------------------------------------------
1578 wxString
& wxString::MakeUpper()
1580 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1581 *it
= (wxChar
)wxToupper(*it
);
1586 wxString
& wxString::MakeLower()
1588 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1589 *it
= (wxChar
)wxTolower(*it
);
1594 // ---------------------------------------------------------------------------
1595 // trimming and padding
1596 // ---------------------------------------------------------------------------
1598 // some compilers (VC++ 6.0 not to name them) return true for a call to
1599 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1600 // live with this by checking that the character is a 7 bit one - even if this
1601 // may fail to detect some spaces (I don't know if Unicode doesn't have
1602 // space-like symbols somewhere except in the first 128 chars), it is arguably
1603 // still better than trimming away accented letters
1604 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1606 // trims spaces (in the sense of isspace) from left or right side
1607 wxString
& wxString::Trim(bool bFromRight
)
1609 // first check if we're going to modify the string at all
1612 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1613 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1619 // find last non-space character
1620 iterator psz
= begin() + length() - 1;
1621 while ( wxSafeIsspace(*psz
) && (psz
>= begin()) )
1624 // truncate at trailing space start
1630 // find first non-space character
1631 iterator psz
= begin();
1632 while ( wxSafeIsspace(*psz
) )
1635 // fix up data and length
1636 erase(begin(), psz
);
1643 // adds nCount characters chPad to the string from either side
1644 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1646 wxString
s(chPad
, nCount
);
1659 // truncate the string
1660 wxString
& wxString::Truncate(size_t uiLen
)
1662 if ( uiLen
< Len() ) {
1663 erase(begin() + uiLen
, end());
1665 //else: nothing to do, string is already short enough
1670 // ---------------------------------------------------------------------------
1671 // finding (return wxNOT_FOUND if not found and index otherwise)
1672 // ---------------------------------------------------------------------------
1675 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1677 size_type idx
= bFromEnd
? find_last_of(ch
) : find_first_of(ch
);
1679 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1682 // find a sub-string (like strstr)
1683 int wxString::Find(const wxChar
*pszSub
) const
1685 size_type idx
= find(pszSub
);
1687 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1690 // ----------------------------------------------------------------------------
1691 // conversion to numbers
1692 // ----------------------------------------------------------------------------
1694 bool wxString::ToLong(long *val
, int base
) const
1696 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToLong") );
1697 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1699 const wxChar
*start
= c_str();
1701 *val
= wxStrtol(start
, &end
, base
);
1703 // return true only if scan was stopped by the terminating NUL and if the
1704 // string was not empty to start with
1705 return !*end
&& (end
!= start
);
1708 bool wxString::ToULong(unsigned long *val
, int base
) const
1710 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToULong") );
1711 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1713 const wxChar
*start
= c_str();
1715 *val
= wxStrtoul(start
, &end
, base
);
1717 // return true only if scan was stopped by the terminating NUL and if the
1718 // string was not empty to start with
1719 return !*end
&& (end
!= start
);
1722 bool wxString::ToDouble(double *val
) const
1724 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToDouble") );
1726 const wxChar
*start
= c_str();
1728 *val
= wxStrtod(start
, &end
);
1730 // return true only if scan was stopped by the terminating NUL and if the
1731 // string was not empty to start with
1732 return !*end
&& (end
!= start
);
1735 // ---------------------------------------------------------------------------
1737 // ---------------------------------------------------------------------------
1740 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1743 va_start(argptr
, pszFormat
);
1746 s
.PrintfV(pszFormat
, argptr
);
1754 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1757 s
.PrintfV(pszFormat
, argptr
);
1761 int wxString::Printf(const wxChar
*pszFormat
, ...)
1764 va_start(argptr
, pszFormat
);
1766 int iLen
= PrintfV(pszFormat
, argptr
);
1773 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1779 wxStringBuffer
tmp(*this, size
+ 1);
1788 // wxVsnprintf() may modify the original arg pointer, so pass it
1791 wxVaCopy(argptrcopy
, argptr
);
1792 int len
= wxVsnprintf(buf
, size
, pszFormat
, argptrcopy
);
1795 // some implementations of vsnprintf() don't NUL terminate
1796 // the string if there is not enough space for it so
1797 // always do it manually
1798 buf
[size
] = _T('\0');
1800 // vsnprintf() may return either -1 (traditional Unix behaviour) or the
1801 // total number of characters which would have been written if the
1802 // buffer were large enough (newer standards such as Unix98)
1805 // still not enough, as we don't know how much we need, double the
1806 // current size of the buffer
1809 else if ( len
> size
)
1813 else // ok, there was enough space
1819 // we could have overshot
1825 // ----------------------------------------------------------------------------
1826 // misc other operations
1827 // ----------------------------------------------------------------------------
1829 // returns true if the string matches the pattern which may contain '*' and
1830 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1832 bool wxString::Matches(const wxChar
*pszMask
) const
1834 // I disable this code as it doesn't seem to be faster (in fact, it seems
1835 // to be much slower) than the old, hand-written code below and using it
1836 // here requires always linking with libregex even if the user code doesn't
1838 #if 0 // wxUSE_REGEX
1839 // first translate the shell-like mask into a regex
1841 pattern
.reserve(wxStrlen(pszMask
));
1853 pattern
+= _T(".*");
1864 // these characters are special in a RE, quote them
1865 // (however note that we don't quote '[' and ']' to allow
1866 // using them for Unix shell like matching)
1867 pattern
+= _T('\\');
1871 pattern
+= *pszMask
;
1879 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1880 #else // !wxUSE_REGEX
1881 // TODO: this is, of course, awfully inefficient...
1883 // the char currently being checked
1884 const wxChar
*pszTxt
= c_str();
1886 // the last location where '*' matched
1887 const wxChar
*pszLastStarInText
= NULL
;
1888 const wxChar
*pszLastStarInMask
= NULL
;
1891 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1892 switch ( *pszMask
) {
1894 if ( *pszTxt
== wxT('\0') )
1897 // pszTxt and pszMask will be incremented in the loop statement
1903 // remember where we started to be able to backtrack later
1904 pszLastStarInText
= pszTxt
;
1905 pszLastStarInMask
= pszMask
;
1907 // ignore special chars immediately following this one
1908 // (should this be an error?)
1909 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1912 // if there is nothing more, match
1913 if ( *pszMask
== wxT('\0') )
1916 // are there any other metacharacters in the mask?
1918 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1920 if ( pEndMask
!= NULL
) {
1921 // we have to match the string between two metachars
1922 uiLenMask
= pEndMask
- pszMask
;
1925 // we have to match the remainder of the string
1926 uiLenMask
= wxStrlen(pszMask
);
1929 wxString
strToMatch(pszMask
, uiLenMask
);
1930 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1931 if ( pMatch
== NULL
)
1934 // -1 to compensate "++" in the loop
1935 pszTxt
= pMatch
+ uiLenMask
- 1;
1936 pszMask
+= uiLenMask
- 1;
1941 if ( *pszMask
!= *pszTxt
)
1947 // match only if nothing left
1948 if ( *pszTxt
== wxT('\0') )
1951 // if we failed to match, backtrack if we can
1952 if ( pszLastStarInText
) {
1953 pszTxt
= pszLastStarInText
+ 1;
1954 pszMask
= pszLastStarInMask
;
1956 pszLastStarInText
= NULL
;
1958 // don't bother resetting pszLastStarInMask, it's unnecessary
1964 #endif // wxUSE_REGEX/!wxUSE_REGEX
1967 // Count the number of chars
1968 int wxString::Freq(wxChar ch
) const
1972 for (int i
= 0; i
< len
; i
++)
1974 if (GetChar(i
) == ch
)
1980 // convert to upper case, return the copy of the string
1981 wxString
wxString::Upper() const
1982 { wxString
s(*this); return s
.MakeUpper(); }
1984 // convert to lower case, return the copy of the string
1985 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1987 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1990 va_start(argptr
, pszFormat
);
1991 int iLen
= PrintfV(pszFormat
, argptr
);
1996 // ============================================================================
1998 // ============================================================================
2000 #include "wx/arrstr.h"
2002 wxArrayString::wxArrayString(size_t sz
, const wxChar
** a
)
2007 for (size_t i
=0; i
< sz
; i
++)
2011 wxArrayString::wxArrayString(size_t sz
, const wxString
* a
)
2016 for (size_t i
=0; i
< sz
; i
++)
2022 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
2023 #define ARRAY_MAXSIZE_INCREMENT 4096
2025 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
2026 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
2029 #define STRING(p) ((wxString *)(&(p)))
2032 void wxArrayString::Init(bool autoSort
)
2036 m_pItems
= (wxChar
**) NULL
;
2037 m_autoSort
= autoSort
;
2041 wxArrayString::wxArrayString(const wxArrayString
& src
)
2043 Init(src
.m_autoSort
);
2048 // assignment operator
2049 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
2056 m_autoSort
= src
.m_autoSort
;
2061 void wxArrayString::Copy(const wxArrayString
& src
)
2063 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
2064 Alloc(src
.m_nCount
);
2066 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
2071 void wxArrayString::Grow(size_t nIncrement
)
2073 // only do it if no more place
2074 if ( (m_nSize
- m_nCount
) < nIncrement
) {
2075 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2076 // be never resized!
2077 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2078 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2081 if ( m_nSize
== 0 ) {
2082 // was empty, alloc some memory
2083 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
2084 if (m_nSize
< nIncrement
)
2085 m_nSize
= nIncrement
;
2086 m_pItems
= new wxChar
*[m_nSize
];
2089 // otherwise when it's called for the first time, nIncrement would be 0
2090 // and the array would never be expanded
2091 // add 50% but not too much
2092 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
2093 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
2094 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
2095 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
2096 if ( nIncrement
< ndefIncrement
)
2097 nIncrement
= ndefIncrement
;
2098 m_nSize
+= nIncrement
;
2099 wxChar
**pNew
= new wxChar
*[m_nSize
];
2101 // copy data to new location
2102 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2104 // delete old memory (but do not release the strings!)
2105 wxDELETEA(m_pItems
);
2112 void wxArrayString::Free()
2114 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
2115 STRING(m_pItems
[n
])->GetStringData()->Unlock();
2119 // deletes all the strings from the list
2120 void wxArrayString::Empty()
2127 // as Empty, but also frees memory
2128 void wxArrayString::Clear()
2135 wxDELETEA(m_pItems
);
2139 wxArrayString::~wxArrayString()
2143 wxDELETEA(m_pItems
);
2146 void wxArrayString::reserve(size_t nSize
)
2151 // pre-allocates memory (frees the previous data!)
2152 void wxArrayString::Alloc(size_t nSize
)
2154 // only if old buffer was not big enough
2155 if ( nSize
> m_nSize
) {
2157 wxDELETEA(m_pItems
);
2158 m_pItems
= new wxChar
*[nSize
];
2165 // minimizes the memory usage by freeing unused memory
2166 void wxArrayString::Shrink()
2168 // only do it if we have some memory to free
2169 if( m_nCount
< m_nSize
) {
2170 // allocates exactly as much memory as we need
2171 wxChar
**pNew
= new wxChar
*[m_nCount
];
2173 // copy data to new location
2174 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2180 #if WXWIN_COMPATIBILITY_2_4
2182 // return a wxString[] as required for some control ctors.
2183 wxString
* wxArrayString::GetStringArray() const
2185 wxString
*array
= 0;
2189 array
= new wxString
[m_nCount
];
2190 for( size_t i
= 0; i
< m_nCount
; i
++ )
2191 array
[i
] = m_pItems
[i
];
2197 void wxArrayString::Remove(size_t nIndex
, size_t nRemove
)
2199 RemoveAt(nIndex
, nRemove
);
2202 #endif // WXWIN_COMPATIBILITY_2_4
2204 // searches the array for an item (forward or backwards)
2205 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2208 // use binary search in the sorted array
2209 wxASSERT_MSG( bCase
&& !bFromEnd
,
2210 wxT("search parameters ignored for auto sorted array") );
2219 res
= wxStrcmp(sz
, m_pItems
[i
]);
2231 // use linear search in unsorted array
2233 if ( m_nCount
> 0 ) {
2234 size_t ui
= m_nCount
;
2236 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2243 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2244 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2253 // add item at the end
2254 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
2257 // insert the string at the correct position to keep the array sorted
2265 res
= str
.Cmp(m_pItems
[i
]);
2276 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2278 Insert(str
, lo
, nInsert
);
2283 wxASSERT( str
.GetStringData()->IsValid() );
2287 for (size_t i
= 0; i
< nInsert
; i
++)
2289 // the string data must not be deleted!
2290 str
.GetStringData()->Lock();
2293 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2295 size_t ret
= m_nCount
;
2296 m_nCount
+= nInsert
;
2301 // add item at the given position
2302 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2304 wxASSERT( str
.GetStringData()->IsValid() );
2306 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2307 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2308 wxT("array size overflow in wxArrayString::Insert") );
2312 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2313 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2315 for (size_t i
= 0; i
< nInsert
; i
++)
2317 str
.GetStringData()->Lock();
2318 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2320 m_nCount
+= nInsert
;
2323 // range insert (STL 23.2.4.3)
2325 wxArrayString::insert(iterator it
, const_iterator first
, const_iterator last
)
2327 const int idx
= it
- begin();
2332 // reset "it" since it can change inside Grow()
2335 while ( first
!= last
)
2337 it
= insert(it
, *first
);
2339 // insert returns an iterator to the last element inserted but we need
2340 // insert the next after this one, that is before the next one
2348 void wxArrayString::SetCount(size_t count
)
2353 while ( m_nCount
< count
)
2354 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2357 // removes item from array (by index)
2358 void wxArrayString::RemoveAt(size_t nIndex
, size_t nRemove
)
2360 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2361 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2362 wxT("removing too many elements in wxArrayString::Remove") );
2365 for (size_t i
= 0; i
< nRemove
; i
++)
2366 Item(nIndex
+ i
).GetStringData()->Unlock();
2368 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2369 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2370 m_nCount
-= nRemove
;
2373 // removes item from array (by value)
2374 void wxArrayString::Remove(const wxChar
*sz
)
2376 int iIndex
= Index(sz
);
2378 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2379 wxT("removing inexistent element in wxArrayString::Remove") );
2384 void wxArrayString::assign(const_iterator first
, const_iterator last
)
2386 reserve(last
- first
);
2387 for(; first
!= last
; ++first
)
2391 // ----------------------------------------------------------------------------
2393 // ----------------------------------------------------------------------------
2395 // we can only sort one array at a time with the quick-sort based
2398 // need a critical section to protect access to gs_compareFunction and
2399 // gs_sortAscending variables
2400 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2402 // call this before the value of the global sort vars is changed/after
2403 // you're finished with them
2404 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2405 gs_critsectStringSort = new wxCriticalSection; \
2406 gs_critsectStringSort->Enter()
2407 #define END_SORT() gs_critsectStringSort->Leave(); \
2408 delete gs_critsectStringSort; \
2409 gs_critsectStringSort = NULL
2411 #define START_SORT()
2413 #endif // wxUSE_THREADS
2415 // function to use for string comparaison
2416 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2418 // if we don't use the compare function, this flag tells us if we sort the
2419 // array in ascending or descending order
2420 static bool gs_sortAscending
= true;
2422 // function which is called by quick sort
2423 extern "C" int wxC_CALLING_CONV
// LINKAGEMODE
2424 wxStringCompareFunction(const void *first
, const void *second
)
2426 wxString
*strFirst
= (wxString
*)first
;
2427 wxString
*strSecond
= (wxString
*)second
;
2429 if ( gs_compareFunction
) {
2430 return gs_compareFunction(*strFirst
, *strSecond
);
2433 // maybe we should use wxStrcoll
2434 int result
= strFirst
->Cmp(*strSecond
);
2436 return gs_sortAscending
? result
: -result
;
2440 // sort array elements using passed comparaison function
2441 void wxArrayString::Sort(CompareFunction compareFunction
)
2445 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2446 gs_compareFunction
= compareFunction
;
2450 // reset it to NULL so that Sort(bool) will work the next time
2451 gs_compareFunction
= NULL
;
2458 typedef int (wxC_CALLING_CONV
* wxStringCompareFn
)(const void *first
,
2459 const void *second
);
2462 void wxArrayString::Sort(CompareFunction2 compareFunction
)
2464 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), (wxStringCompareFn
)compareFunction
);
2467 void wxArrayString::Sort(bool reverseOrder
)
2469 Sort(reverseOrder
? wxStringSortDescending
: wxStringSortAscending
);
2472 void wxArrayString::DoSort()
2474 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2476 // just sort the pointers using qsort() - of course it only works because
2477 // wxString() *is* a pointer to its data
2478 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2481 bool wxArrayString::operator==(const wxArrayString
& a
) const
2483 if ( m_nCount
!= a
.m_nCount
)
2486 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2488 if ( Item(n
) != a
[n
] )
2495 #endif // !wxUSE_STL
2497 int wxCMPFUNC_CONV
wxStringSortAscending(wxString
* s1
, wxString
* s2
)
2499 return s1
->Cmp(*s2
);
2502 int wxCMPFUNC_CONV
wxStringSortDescending(wxString
* s1
, wxString
* s2
)
2504 return -s1
->Cmp(*s2
);