1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxString class
4 // Author: Vadim Zeitlin, Ryan Norton
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // (c) 2004 Ryan Norton <wxprojects@comcast.net>
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
13 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
14 #pragma implementation "string.h"
19 * 1) all empty strings use g_strEmpty, nRefs = -1 (set in Init())
20 * 2) AllocBuffer() sets nRefs to 1, Lock() increments it by one
21 * 3) Unlock() decrements nRefs and frees memory if it goes to 0
24 // ===========================================================================
25 // headers, declarations, constants
26 // ===========================================================================
28 // For compilers that support precompilation, includes "wx.h".
29 #include "wx/wxprec.h"
37 #include "wx/string.h"
39 #include "wx/thread.h"
51 // allocating extra space for each string consumes more memory but speeds up
52 // the concatenation operations (nLen is the current string's length)
53 // NB: EXTRA_ALLOC must be >= 0!
54 #define EXTRA_ALLOC (19 - nLen % 16)
56 // ---------------------------------------------------------------------------
57 // static class variables definition
58 // ---------------------------------------------------------------------------
61 //According to STL _must_ be a -1 size_t
62 const size_t wxStringBase::npos
= (size_t) -1;
65 // ----------------------------------------------------------------------------
67 // ----------------------------------------------------------------------------
71 extern const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= _T("");
75 // for an empty string, GetStringData() will return this address: this
76 // structure has the same layout as wxStringData and it's data() method will
77 // return the empty string (dummy pointer)
82 } g_strEmpty
= { {-1, 0, 0}, wxT('\0') };
84 // empty C style string: points to 'string data' byte of g_strEmpty
85 extern const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= &g_strEmpty
.dummy
;
89 // ----------------------------------------------------------------------------
91 // ----------------------------------------------------------------------------
93 #if wxUSE_STD_IOSTREAM
95 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
98 // ATTN: you can _not_ use both of these in the same program!
102 wxSTD istream
& operator>>(wxSTD istream
& is
, wxString
& WXUNUSED(str
))
107 streambuf
*sb
= is
.rdbuf();
110 int ch
= sb
->sbumpc ();
112 is
.setstate(ios::eofbit
);
115 else if ( isspace(ch
) ) {
127 if ( str
.length() == 0 )
128 is
.setstate(ios::failbit
);
133 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
139 #endif // wxUSE_STD_IOSTREAM
141 // ----------------------------------------------------------------------------
143 // ----------------------------------------------------------------------------
145 // this small class is used to gather statistics for performance tuning
146 //#define WXSTRING_STATISTICS
147 #ifdef WXSTRING_STATISTICS
151 Averager(const wxChar
*sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
153 { wxPrintf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
155 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
158 size_t m_nCount
, m_nTotal
;
160 } g_averageLength("allocation size"),
161 g_averageSummandLength("summand length"),
162 g_averageConcatHit("hit probability in concat"),
163 g_averageInitialLength("initial string length");
165 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
167 #define STATISTICS_ADD(av, val)
168 #endif // WXSTRING_STATISTICS
172 // ===========================================================================
173 // wxStringData class deallocation
174 // ===========================================================================
176 #if defined(__VISUALC__) && defined(_MT) && !defined(_DLL)
177 # pragma message (__FILE__ ": building with Multithreaded non DLL runtime has a performance impact on wxString!")
178 void wxStringData::Free()
184 // ===========================================================================
186 // ===========================================================================
188 // takes nLength elements of psz starting at nPos
189 void wxStringBase::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
193 // if the length is not given, assume the string to be NUL terminated
194 if ( nLength
== npos
) {
195 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
197 nLength
= wxStrlen(psz
+ nPos
);
200 STATISTICS_ADD(InitialLength
, nLength
);
203 // trailing '\0' is written in AllocBuffer()
204 if ( !AllocBuffer(nLength
) ) {
205 wxFAIL_MSG( _T("out of memory in wxStringBase::InitWith") );
208 wxTmemcpy(m_pchData
, psz
+ nPos
, nLength
);
212 // poor man's iterators are "void *" pointers
213 wxStringBase::wxStringBase(const void *pStart
, const void *pEnd
)
215 InitWith((const wxChar
*)pStart
, 0,
216 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
219 wxStringBase::wxStringBase(size_type n
, wxChar ch
)
225 // ---------------------------------------------------------------------------
227 // ---------------------------------------------------------------------------
229 // allocates memory needed to store a C string of length nLen
230 bool wxStringBase::AllocBuffer(size_t nLen
)
232 // allocating 0 sized buffer doesn't make sense, all empty strings should
234 wxASSERT( nLen
> 0 );
236 // make sure that we don't overflow
237 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
238 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
240 STATISTICS_ADD(Length
, nLen
);
243 // 1) one extra character for '\0' termination
244 // 2) sizeof(wxStringData) for housekeeping info
245 wxStringData
* pData
= (wxStringData
*)
246 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
248 if ( pData
== NULL
) {
249 // allocation failures are handled by the caller
254 pData
->nDataLength
= nLen
;
255 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
256 m_pchData
= pData
->data(); // data starts after wxStringData
257 m_pchData
[nLen
] = wxT('\0');
261 // must be called before changing this string
262 bool wxStringBase::CopyBeforeWrite()
264 wxStringData
* pData
= GetStringData();
266 if ( pData
->IsShared() ) {
267 pData
->Unlock(); // memory not freed because shared
268 size_t nLen
= pData
->nDataLength
;
269 if ( !AllocBuffer(nLen
) ) {
270 // allocation failures are handled by the caller
273 wxTmemcpy(m_pchData
, pData
->data(), nLen
);
276 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
281 // must be called before replacing contents of this string
282 bool wxStringBase::AllocBeforeWrite(size_t nLen
)
284 wxASSERT( nLen
!= 0 ); // doesn't make any sense
286 // must not share string and must have enough space
287 wxStringData
* pData
= GetStringData();
288 if ( pData
->IsShared() || pData
->IsEmpty() ) {
289 // can't work with old buffer, get new one
291 if ( !AllocBuffer(nLen
) ) {
292 // allocation failures are handled by the caller
297 if ( nLen
> pData
->nAllocLength
) {
298 // realloc the buffer instead of calling malloc() again, this is more
300 STATISTICS_ADD(Length
, nLen
);
304 pData
= (wxStringData
*)
305 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
307 if ( pData
== NULL
) {
308 // allocation failures are handled by the caller
309 // keep previous data since reallocation failed
313 pData
->nAllocLength
= nLen
;
314 m_pchData
= pData
->data();
318 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
320 // it doesn't really matter what the string length is as it's going to be
321 // overwritten later but, for extra safety, set it to 0 for now as we may
322 // have some junk in m_pchData
323 GetStringData()->nDataLength
= 0;
328 wxStringBase
& wxStringBase::append(size_t n
, wxChar ch
)
330 size_type len
= length();
332 if ( !Alloc(len
+ n
) || !CopyBeforeWrite() ) {
333 wxFAIL_MSG( _T("out of memory in wxStringBase::append") );
335 GetStringData()->nDataLength
= len
+ n
;
336 m_pchData
[len
+ n
] = '\0';
337 for ( size_t i
= 0; i
< n
; ++i
)
338 m_pchData
[len
+ i
] = ch
;
342 void wxStringBase::resize(size_t nSize
, wxChar ch
)
344 size_t len
= length();
348 erase(begin() + nSize
, end());
350 else if ( nSize
> len
)
352 append(nSize
- len
, ch
);
354 //else: we have exactly the specified length, nothing to do
357 // allocate enough memory for nLen characters
358 bool wxStringBase::Alloc(size_t nLen
)
360 wxStringData
*pData
= GetStringData();
361 if ( pData
->nAllocLength
<= nLen
) {
362 if ( pData
->IsEmpty() ) {
365 wxStringData
* pData
= (wxStringData
*)
366 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
368 if ( pData
== NULL
) {
369 // allocation failure handled by caller
374 pData
->nDataLength
= 0;
375 pData
->nAllocLength
= nLen
;
376 m_pchData
= pData
->data(); // data starts after wxStringData
377 m_pchData
[0u] = wxT('\0');
379 else if ( pData
->IsShared() ) {
380 pData
->Unlock(); // memory not freed because shared
381 size_t nOldLen
= pData
->nDataLength
;
382 if ( !AllocBuffer(nLen
) ) {
383 // allocation failure handled by caller
386 // +1 to copy the terminator, too
387 memcpy(m_pchData
, pData
->data(), (nOldLen
+1)*sizeof(wxChar
));
388 GetStringData()->nDataLength
= nOldLen
;
393 pData
= (wxStringData
*)
394 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
396 if ( pData
== NULL
) {
397 // allocation failure handled by caller
398 // keep previous data since reallocation failed
402 // it's not important if the pointer changed or not (the check for this
403 // is not faster than assigning to m_pchData in all cases)
404 pData
->nAllocLength
= nLen
;
405 m_pchData
= pData
->data();
408 //else: we've already got enough
412 wxStringBase::iterator
wxStringBase::begin()
419 wxStringBase::iterator
wxStringBase::end()
423 return m_pchData
+ length();
426 wxStringBase::iterator
wxStringBase::erase(iterator it
)
428 size_type idx
= it
- begin();
430 return begin() + idx
;
433 wxStringBase
& wxStringBase::erase(size_t nStart
, size_t nLen
)
435 wxASSERT(nStart
<= length());
436 size_t strLen
= length() - nStart
;
437 // delete nLen or up to the end of the string characters
438 nLen
= strLen
< nLen
? strLen
: nLen
;
439 wxString
strTmp(c_str(), nStart
);
440 strTmp
.append(c_str() + nStart
+ nLen
, length() - nStart
- nLen
);
446 wxStringBase
& wxStringBase::insert(size_t nPos
, const wxChar
*sz
, size_t n
)
448 wxASSERT( nPos
<= length() );
450 if ( n
== npos
) n
= wxStrlen(sz
);
451 if ( n
== 0 ) return *this;
453 if ( !Alloc(length() + n
) || !CopyBeforeWrite() ) {
454 wxFAIL_MSG( _T("out of memory in wxStringBase::insert") );
457 memmove(m_pchData
+ nPos
+ n
, m_pchData
+ nPos
,
458 (length() - nPos
) * sizeof(wxChar
));
459 memcpy(m_pchData
+ nPos
, sz
, n
* sizeof(wxChar
));
460 GetStringData()->nDataLength
= length() + n
;
461 m_pchData
[length()] = '\0';
466 void wxStringBase::swap(wxStringBase
& str
)
468 wxChar
* tmp
= str
.m_pchData
;
469 str
.m_pchData
= m_pchData
;
473 size_t wxStringBase::find(const wxStringBase
& str
, size_t nStart
) const
475 wxASSERT( str
.GetStringData()->IsValid() );
476 wxASSERT( nStart
<= length() );
479 const wxChar
* p
= (const wxChar
*)wxTmemchr(c_str() + nStart
,
486 while(p
- c_str() + str
.length() <= length() &&
487 wxTmemcmp(p
, str
.c_str(), str
.length()) )
489 //Previosly passed as the first argument to wxTmemchr,
490 //but C/C++ standard does not specify evaluation order
491 //of arguments to functions -
492 //http://embedded.com/showArticle.jhtml?articleID=9900607
496 p
= (const wxChar
*)wxTmemchr(p
,
498 length() - (p
- c_str()));
504 return (p
- c_str() + str
.length() <= length()) ? p
- c_str() : npos
;
507 size_t wxStringBase::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
509 return find(wxStringBase(sz
, n
), nStart
);
512 size_t wxStringBase::find(wxChar ch
, size_t nStart
) const
514 wxASSERT( nStart
<= length() );
516 const wxChar
*p
= (const wxChar
*)wxTmemchr(c_str() + nStart
, ch
, length() - nStart
);
518 return p
== NULL
? npos
: p
- c_str();
521 size_t wxStringBase::rfind(const wxStringBase
& str
, size_t nStart
) const
523 wxASSERT( str
.GetStringData()->IsValid() );
524 wxASSERT( nStart
== npos
|| nStart
<= length() );
526 if ( length() >= str
.length() )
528 // avoids a corner case later
529 if ( length() == 0 && str
.length() == 0 )
532 // "top" is the point where search starts from
533 size_t top
= length() - str
.length();
535 if ( nStart
== npos
)
536 nStart
= length() - 1;
540 const wxChar
*cursor
= c_str() + top
;
543 if ( wxTmemcmp(cursor
, str
.c_str(),
546 return cursor
- c_str();
548 } while ( cursor
-- > c_str() );
554 size_t wxStringBase::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
556 return rfind(wxStringBase(sz
, n
), nStart
);
559 size_t wxStringBase::rfind(wxChar ch
, size_t nStart
) const
561 if ( nStart
== npos
)
567 wxASSERT( nStart
<= length() );
570 const wxChar
*actual
;
571 for ( actual
= c_str() + ( nStart
== npos
? length() : nStart
+ 1 );
572 actual
> c_str(); --actual
)
574 if ( *(actual
- 1) == ch
)
575 return (actual
- 1) - c_str();
581 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
) const
583 wxASSERT(nStart
<= length());
585 size_t len
= wxStrlen(sz
);
588 for(i
= nStart
; i
< this->length(); ++i
)
590 if (wxTmemchr(sz
, *(c_str() + i
), len
))
594 if(i
== this->length())
600 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
,
603 return find_first_of(wxStringBase(sz
, n
), nStart
);
606 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
) const
608 if ( nStart
== npos
)
610 nStart
= length() - 1;
614 wxASSERT_MSG( nStart
<= length(),
615 _T("invalid index in find_last_of()") );
618 size_t len
= wxStrlen(sz
);
620 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
622 if ( wxTmemchr(sz
, *p
, len
) )
629 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
,
632 return find_last_of(wxStringBase(sz
, n
), nStart
);
635 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
637 if ( nStart
== npos
)
643 wxASSERT( nStart
<= length() );
646 size_t len
= wxStrlen(sz
);
649 for(i
= nStart
; i
< this->length(); ++i
)
651 if (!wxTmemchr(sz
, *(c_str() + i
), len
))
655 if(i
== this->length())
661 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
,
664 return find_first_not_of(wxStringBase(sz
, n
), nStart
);
667 size_t wxStringBase::find_first_not_of(wxChar ch
, size_t nStart
) const
669 wxASSERT( nStart
<= length() );
671 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
680 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
682 if ( nStart
== npos
)
684 nStart
= length() - 1;
688 wxASSERT( nStart
<= length() );
691 size_t len
= wxStrlen(sz
);
693 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
695 if ( !wxTmemchr(sz
, *p
,len
) )
702 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
,
705 return find_last_not_of(wxStringBase(sz
, n
), nStart
);
708 size_t wxStringBase::find_last_not_of(wxChar ch
, size_t nStart
) const
710 if ( nStart
== npos
)
712 nStart
= length() - 1;
716 wxASSERT( nStart
<= length() );
719 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
728 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
731 wxASSERT_MSG( nStart
<= length(),
732 _T("index out of bounds in wxStringBase::replace") );
733 size_t strLen
= length() - nStart
;
734 nLen
= strLen
< nLen
? strLen
: nLen
;
737 strTmp
.reserve(length()); // micro optimisation to avoid multiple mem allocs
740 strTmp
.append(c_str(), nStart
);
742 strTmp
.append(c_str() + nStart
+ nLen
);
748 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
749 size_t nCount
, wxChar ch
)
751 return replace(nStart
, nLen
, wxStringBase(nCount
, ch
).c_str());
754 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
755 const wxStringBase
& str
,
756 size_t nStart2
, size_t nLen2
)
758 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
761 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
762 const wxChar
* sz
, size_t nCount
)
764 return replace(nStart
, nLen
, wxStringBase(sz
, nCount
).c_str());
767 wxStringBase
wxStringBase::substr(size_t nStart
, size_t nLen
) const
770 nLen
= length() - nStart
;
771 return wxStringBase(*this, nStart
, nLen
);
774 // assigns one string to another
775 wxStringBase
& wxStringBase::operator=(const wxStringBase
& stringSrc
)
777 wxASSERT( stringSrc
.GetStringData()->IsValid() );
779 // don't copy string over itself
780 if ( m_pchData
!= stringSrc
.m_pchData
) {
781 if ( stringSrc
.GetStringData()->IsEmpty() ) {
786 GetStringData()->Unlock();
787 m_pchData
= stringSrc
.m_pchData
;
788 GetStringData()->Lock();
795 // assigns a single character
796 wxStringBase
& wxStringBase::operator=(wxChar ch
)
798 if ( !AssignCopy(1, &ch
) ) {
799 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(wxChar)") );
805 wxStringBase
& wxStringBase::operator=(const wxChar
*psz
)
807 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
808 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(const wxChar *)") );
813 // helper function: does real copy
814 bool wxStringBase::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
816 if ( nSrcLen
== 0 ) {
820 if ( !AllocBeforeWrite(nSrcLen
) ) {
821 // allocation failure handled by caller
824 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
825 GetStringData()->nDataLength
= nSrcLen
;
826 m_pchData
[nSrcLen
] = wxT('\0');
831 // ---------------------------------------------------------------------------
832 // string concatenation
833 // ---------------------------------------------------------------------------
835 // add something to this string
836 bool wxStringBase::ConcatSelf(size_t nSrcLen
, const wxChar
*pszSrcData
,
839 STATISTICS_ADD(SummandLength
, nSrcLen
);
841 nSrcLen
= nSrcLen
< nMaxLen
? nSrcLen
: nMaxLen
;
843 // concatenating an empty string is a NOP
845 wxStringData
*pData
= GetStringData();
846 size_t nLen
= pData
->nDataLength
;
847 size_t nNewLen
= nLen
+ nSrcLen
;
849 // alloc new buffer if current is too small
850 if ( pData
->IsShared() ) {
851 STATISTICS_ADD(ConcatHit
, 0);
853 // we have to allocate another buffer
854 wxStringData
* pOldData
= GetStringData();
855 if ( !AllocBuffer(nNewLen
) ) {
856 // allocation failure handled by caller
859 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
862 else if ( nNewLen
> pData
->nAllocLength
) {
863 STATISTICS_ADD(ConcatHit
, 0);
866 // we have to grow the buffer
867 if ( capacity() < nNewLen
) {
868 // allocation failure handled by caller
873 STATISTICS_ADD(ConcatHit
, 1);
875 // the buffer is already big enough
878 // should be enough space
879 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
881 // fast concatenation - all is done in our buffer
882 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
884 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
885 GetStringData()->nDataLength
= nNewLen
; // and fix the length
887 //else: the string to append was empty
891 // ---------------------------------------------------------------------------
892 // simple sub-string extraction
893 // ---------------------------------------------------------------------------
895 // helper function: clone the data attached to this string
896 bool wxStringBase::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
898 if ( nCopyLen
== 0 ) {
902 if ( !dest
.AllocBuffer(nCopyLen
) ) {
903 // allocation failure handled by caller
906 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
913 #if !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
916 #define STRINGCLASS wxStringBase
918 #define STRINGCLASS wxString
921 static inline int wxDoCmp(const wxChar
* s1
, size_t l1
,
922 const wxChar
* s2
, size_t l2
)
925 return wxTmemcmp(s1
, s2
, l1
);
928 int ret
= wxTmemcmp(s1
, s2
, l1
);
929 return ret
== 0 ? -1 : ret
;
933 int ret
= wxTmemcmp(s1
, s2
, l2
);
934 return ret
== 0 ? +1 : ret
;
938 int STRINGCLASS::compare(const wxStringBase
& str
) const
940 return ::wxDoCmp(data(), length(), str
.data(), str
.length());
943 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
944 const wxStringBase
& str
) const
946 wxASSERT(nStart
<= length());
947 size_type strLen
= length() - nStart
;
948 nLen
= strLen
< nLen
? strLen
: nLen
;
949 return ::wxDoCmp(data() + nStart
, nLen
, str
.data(), str
.length());
952 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
953 const wxStringBase
& str
,
954 size_t nStart2
, size_t nLen2
) const
956 wxASSERT(nStart
<= length());
957 wxASSERT(nStart2
<= str
.length());
958 size_type strLen
= length() - nStart
,
959 strLen2
= str
.length() - nStart2
;
960 nLen
= strLen
< nLen
? strLen
: nLen
;
961 nLen2
= strLen2
< nLen2
? strLen2
: nLen2
;
962 return ::wxDoCmp(data() + nStart
, nLen
, str
.data() + nStart2
, nLen2
);
965 int STRINGCLASS::compare(const wxChar
* sz
) const
967 size_t nLen
= wxStrlen(sz
);
968 return ::wxDoCmp(data(), length(), sz
, nLen
);
971 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
972 const wxChar
* sz
, size_t nCount
) const
974 wxASSERT(nStart
<= length());
975 size_type strLen
= length() - nStart
;
976 nLen
= strLen
< nLen
? strLen
: nLen
;
978 nCount
= wxStrlen(sz
);
980 return ::wxDoCmp(data() + nStart
, nLen
, sz
, nCount
);
985 #endif // !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
987 // ===========================================================================
988 // wxString class core
989 // ===========================================================================
991 // ---------------------------------------------------------------------------
992 // construction and conversion
993 // ---------------------------------------------------------------------------
997 // from multibyte string
998 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
1000 // if nLength != npos, then we have to make a NULL-terminated copy
1001 // of first nLength bytes of psz first because the input buffer to MB2WC
1002 // must always be NULL-terminated:
1003 wxCharBuffer
inBuf((const char *)NULL
);
1004 if (nLength
!= npos
)
1006 wxASSERT( psz
!= NULL
);
1007 wxCharBuffer
tmp(nLength
);
1008 memcpy(tmp
.data(), psz
, nLength
);
1009 tmp
.data()[nLength
] = '\0';
1014 // first get the size of the buffer we need
1018 // calculate the needed size ourselves or use the provided one
1019 if (nLength
== npos
)
1026 // nothing to convert
1032 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
1036 wxWCharBuffer theBuffer
= conv
.cMB2WC(psz
, nLen
, &nRealSize
);
1040 assign( theBuffer
.data() , nRealSize
- 1 );
1044 //Convert wxString in Unicode mode to a multi-byte string
1045 const wxCharBuffer
wxString::mb_str(wxMBConv
& conv
) const
1048 return conv
.cWC2MB(c_str(), length(), &dwOutSize
);
1055 wxString::wxString(const wchar_t *pwz
, wxMBConv
& conv
, size_t nLength
)
1057 // if nLength != npos, then we have to make a NULL-terminated copy
1058 // of first nLength chars of psz first because the input buffer to WC2MB
1059 // must always be NULL-terminated:
1060 wxWCharBuffer
inBuf((const wchar_t *)NULL
);
1061 if (nLength
!= npos
)
1063 wxASSERT( pwz
!= NULL
);
1064 wxWCharBuffer
tmp(nLength
);
1065 memcpy(tmp
.data(), pwz
, nLength
* sizeof(wchar_t));
1066 tmp
.data()[nLength
] = '\0';
1071 // first get the size of the buffer we need
1075 // calculate the needed size ourselves or use the provided one
1076 if (nLength
== npos
)
1077 nLen
= wxWcslen(pwz
);
1083 // nothing to convert
1088 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
1092 wxCharBuffer theBuffer
= conv
.cWC2MB(pwz
, nLen
, &nRealSize
);
1096 assign( theBuffer
.data() , nRealSize
- 1 );
1100 //Converts this string to a wide character string if unicode
1101 //mode is not enabled and wxUSE_WCHAR_T is enabled
1102 const wxWCharBuffer
wxString::wc_str(wxMBConv
& conv
) const
1105 return conv
.cMB2WC(c_str(), length(), &dwOutSize
);
1108 #endif // wxUSE_WCHAR_T
1110 #endif // Unicode/ANSI
1112 // shrink to minimal size (releasing extra memory)
1113 bool wxString::Shrink()
1115 wxString
tmp(begin(), end());
1117 return tmp
.length() == length();
1121 // get the pointer to writable buffer of (at least) nLen bytes
1122 wxChar
*wxString::GetWriteBuf(size_t nLen
)
1124 if ( !AllocBeforeWrite(nLen
) ) {
1125 // allocation failure handled by caller
1129 wxASSERT( GetStringData()->nRefs
== 1 );
1130 GetStringData()->Validate(false);
1135 // put string back in a reasonable state after GetWriteBuf
1136 void wxString::UngetWriteBuf()
1138 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
1139 GetStringData()->Validate(true);
1142 void wxString::UngetWriteBuf(size_t nLen
)
1144 GetStringData()->nDataLength
= nLen
;
1145 GetStringData()->Validate(true);
1149 // ---------------------------------------------------------------------------
1151 // ---------------------------------------------------------------------------
1153 // all functions are inline in string.h
1155 // ---------------------------------------------------------------------------
1156 // assignment operators
1157 // ---------------------------------------------------------------------------
1161 // same as 'signed char' variant
1162 wxString
& wxString::operator=(const unsigned char* psz
)
1164 *this = (const char *)psz
;
1169 wxString
& wxString::operator=(const wchar_t *pwz
)
1180 * concatenation functions come in 5 flavours:
1182 * char + string and string + char
1183 * C str + string and string + C str
1186 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
1189 wxASSERT( str1
.GetStringData()->IsValid() );
1190 wxASSERT( str2
.GetStringData()->IsValid() );
1199 wxString
operator+(const wxString
& str
, wxChar ch
)
1202 wxASSERT( str
.GetStringData()->IsValid() );
1211 wxString
operator+(wxChar ch
, const wxString
& str
)
1214 wxASSERT( str
.GetStringData()->IsValid() );
1223 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
1226 wxASSERT( str
.GetStringData()->IsValid() );
1230 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
1231 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1239 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
1242 wxASSERT( str
.GetStringData()->IsValid() );
1246 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
1247 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1255 // ===========================================================================
1256 // other common string functions
1257 // ===========================================================================
1259 int wxString::Cmp(const wxString
& s
) const
1264 int wxString::Cmp(const wxChar
* psz
) const
1266 return compare(psz
);
1269 static inline int wxDoCmpNoCase(const wxChar
* s1
, size_t l1
,
1270 const wxChar
* s2
, size_t l2
)
1276 for(i
= 0; i
< l1
; ++i
)
1278 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1281 return i
== l1
? 0 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1285 for(i
= 0; i
< l1
; ++i
)
1287 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1290 return i
== l1
? -1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1294 for(i
= 0; i
< l2
; ++i
)
1296 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1299 return i
== l2
? 1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1303 int wxString::CmpNoCase(const wxString
& s
) const
1305 return wxDoCmpNoCase(data(), length(), s
.data(), s
.length());
1308 int wxString::CmpNoCase(const wxChar
* psz
) const
1310 int nLen
= wxStrlen(psz
);
1312 return wxDoCmpNoCase(data(), length(), psz
, nLen
);
1319 #ifndef __SCHAR_MAX__
1320 #define __SCHAR_MAX__ 127
1324 wxString
wxString::FromAscii(const char *ascii
)
1327 return wxEmptyString
;
1329 size_t len
= strlen( ascii
);
1334 wxStringBuffer
buf(res
, len
);
1336 wchar_t *dest
= buf
;
1340 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
1348 wxString
wxString::FromAscii(const char ascii
)
1350 // What do we do with '\0' ?
1353 res
+= (wchar_t)(unsigned char) ascii
;
1358 const wxCharBuffer
wxString::ToAscii() const
1360 // this will allocate enough space for the terminating NUL too
1361 wxCharBuffer
buffer(length());
1364 char *dest
= buffer
.data();
1366 const wchar_t *pwc
= c_str();
1369 *dest
++ = (char)(*pwc
> SCHAR_MAX
? wxT('_') : *pwc
);
1371 // the output string can't have embedded NULs anyhow, so we can safely
1372 // stop at first of them even if we do have any
1382 // extract string of length nCount starting at nFirst
1383 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
1385 size_t nLen
= length();
1387 // default value of nCount is npos and means "till the end"
1388 if ( nCount
== npos
)
1390 nCount
= nLen
- nFirst
;
1393 // out-of-bounds requests return sensible things
1394 if ( nFirst
+ nCount
> nLen
)
1396 nCount
= nLen
- nFirst
;
1399 if ( nFirst
> nLen
)
1401 // AllocCopy() will return empty string
1405 wxString
dest(*this, nFirst
, nCount
);
1406 if ( dest
.length() != nCount
) {
1407 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
1413 // check that the string starts with prefix and return the rest of the string
1414 // in the provided pointer if it is not NULL, otherwise return false
1415 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
1417 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
1419 // first check if the beginning of the string matches the prefix: note
1420 // that we don't have to check that we don't run out of this string as
1421 // when we reach the terminating NUL, either prefix string ends too (and
1422 // then it's ok) or we break out of the loop because there is no match
1423 const wxChar
*p
= c_str();
1426 if ( *prefix
++ != *p
++ )
1435 // put the rest of the string into provided pointer
1442 // extract nCount last (rightmost) characters
1443 wxString
wxString::Right(size_t nCount
) const
1445 if ( nCount
> length() )
1448 wxString
dest(*this, length() - nCount
, nCount
);
1449 if ( dest
.length() != nCount
) {
1450 wxFAIL_MSG( _T("out of memory in wxString::Right") );
1455 // get all characters after the last occurence of ch
1456 // (returns the whole string if ch not found)
1457 wxString
wxString::AfterLast(wxChar ch
) const
1460 int iPos
= Find(ch
, true);
1461 if ( iPos
== wxNOT_FOUND
)
1464 str
= c_str() + iPos
+ 1;
1469 // extract nCount first (leftmost) characters
1470 wxString
wxString::Left(size_t nCount
) const
1472 if ( nCount
> length() )
1475 wxString
dest(*this, 0, nCount
);
1476 if ( dest
.length() != nCount
) {
1477 wxFAIL_MSG( _T("out of memory in wxString::Left") );
1482 // get all characters before the first occurence of ch
1483 // (returns the whole string if ch not found)
1484 wxString
wxString::BeforeFirst(wxChar ch
) const
1486 int iPos
= Find(ch
);
1487 if ( iPos
== wxNOT_FOUND
) iPos
= length();
1488 return wxString(*this, 0, iPos
);
1491 /// get all characters before the last occurence of ch
1492 /// (returns empty string if ch not found)
1493 wxString
wxString::BeforeLast(wxChar ch
) const
1496 int iPos
= Find(ch
, true);
1497 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
1498 str
= wxString(c_str(), iPos
);
1503 /// get all characters after the first occurence of ch
1504 /// (returns empty string if ch not found)
1505 wxString
wxString::AfterFirst(wxChar ch
) const
1508 int iPos
= Find(ch
);
1509 if ( iPos
!= wxNOT_FOUND
)
1510 str
= c_str() + iPos
+ 1;
1515 // replace first (or all) occurences of some substring with another one
1517 wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
1519 // if we tried to replace an empty string we'd enter an infinite loop below
1520 wxCHECK_MSG( szOld
&& *szOld
&& szNew
, 0,
1521 _T("wxString::Replace(): invalid parameter") );
1523 size_t uiCount
= 0; // count of replacements made
1525 size_t uiOldLen
= wxStrlen(szOld
);
1528 const wxChar
*pCurrent
= c_str();
1529 const wxChar
*pSubstr
;
1530 while ( *pCurrent
!= wxT('\0') ) {
1531 pSubstr
= wxStrstr(pCurrent
, szOld
);
1532 if ( pSubstr
== NULL
) {
1533 // strTemp is unused if no replacements were made, so avoid the copy
1537 strTemp
+= pCurrent
; // copy the rest
1538 break; // exit the loop
1541 // take chars before match
1542 size_type len
= strTemp
.length();
1543 strTemp
.append(pCurrent
, pSubstr
- pCurrent
);
1544 if ( strTemp
.length() != (size_t)(len
+ pSubstr
- pCurrent
) ) {
1545 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
1549 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
1554 if ( !bReplaceAll
) {
1555 strTemp
+= pCurrent
; // copy the rest
1556 break; // exit the loop
1561 // only done if there were replacements, otherwise would have returned above
1567 bool wxString::IsAscii() const
1569 const wxChar
*s
= (const wxChar
*) *this;
1571 if(!isascii(*s
)) return(false);
1577 bool wxString::IsWord() const
1579 const wxChar
*s
= (const wxChar
*) *this;
1581 if(!wxIsalpha(*s
)) return(false);
1587 bool wxString::IsNumber() const
1589 const wxChar
*s
= (const wxChar
*) *this;
1591 if ((s
[0] == wxT('-')) || (s
[0] == wxT('+'))) s
++;
1593 if(!wxIsdigit(*s
)) return(false);
1599 wxString
wxString::Strip(stripType w
) const
1602 if ( w
& leading
) s
.Trim(false);
1603 if ( w
& trailing
) s
.Trim(true);
1607 // ---------------------------------------------------------------------------
1609 // ---------------------------------------------------------------------------
1611 wxString
& wxString::MakeUpper()
1613 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1614 *it
= (wxChar
)wxToupper(*it
);
1619 wxString
& wxString::MakeLower()
1621 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1622 *it
= (wxChar
)wxTolower(*it
);
1627 // ---------------------------------------------------------------------------
1628 // trimming and padding
1629 // ---------------------------------------------------------------------------
1631 // some compilers (VC++ 6.0 not to name them) return true for a call to
1632 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1633 // live with this by checking that the character is a 7 bit one - even if this
1634 // may fail to detect some spaces (I don't know if Unicode doesn't have
1635 // space-like symbols somewhere except in the first 128 chars), it is arguably
1636 // still better than trimming away accented letters
1637 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1639 // trims spaces (in the sense of isspace) from left or right side
1640 wxString
& wxString::Trim(bool bFromRight
)
1642 // first check if we're going to modify the string at all
1645 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1646 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1652 // find last non-space character
1653 iterator psz
= begin() + length() - 1;
1654 while ( wxSafeIsspace(*psz
) && (psz
>= begin()) )
1657 // truncate at trailing space start
1663 // find first non-space character
1664 iterator psz
= begin();
1665 while ( wxSafeIsspace(*psz
) )
1668 // fix up data and length
1669 erase(begin(), psz
);
1676 // adds nCount characters chPad to the string from either side
1677 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1679 wxString
s(chPad
, nCount
);
1692 // truncate the string
1693 wxString
& wxString::Truncate(size_t uiLen
)
1695 if ( uiLen
< Len() ) {
1696 erase(begin() + uiLen
, end());
1698 //else: nothing to do, string is already short enough
1703 // ---------------------------------------------------------------------------
1704 // finding (return wxNOT_FOUND if not found and index otherwise)
1705 // ---------------------------------------------------------------------------
1708 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1710 size_type idx
= bFromEnd
? find_last_of(ch
) : find_first_of(ch
);
1712 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1715 // find a sub-string (like strstr)
1716 int wxString::Find(const wxChar
*pszSub
) const
1718 size_type idx
= find(pszSub
);
1720 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1723 // ----------------------------------------------------------------------------
1724 // conversion to numbers
1725 // ----------------------------------------------------------------------------
1727 bool wxString::ToLong(long *val
, int base
) const
1729 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToLong") );
1730 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1732 const wxChar
*start
= c_str();
1734 *val
= wxStrtol(start
, &end
, base
);
1736 // return true only if scan was stopped by the terminating NUL and if the
1737 // string was not empty to start with
1738 return !*end
&& (end
!= start
);
1741 bool wxString::ToULong(unsigned long *val
, int base
) const
1743 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToULong") );
1744 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1746 const wxChar
*start
= c_str();
1748 *val
= wxStrtoul(start
, &end
, base
);
1750 // return true only if scan was stopped by the terminating NUL and if the
1751 // string was not empty to start with
1752 return !*end
&& (end
!= start
);
1755 bool wxString::ToDouble(double *val
) const
1757 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToDouble") );
1759 const wxChar
*start
= c_str();
1761 *val
= wxStrtod(start
, &end
);
1763 // return true only if scan was stopped by the terminating NUL and if the
1764 // string was not empty to start with
1765 return !*end
&& (end
!= start
);
1768 // ---------------------------------------------------------------------------
1770 // ---------------------------------------------------------------------------
1773 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1776 va_start(argptr
, pszFormat
);
1779 s
.PrintfV(pszFormat
, argptr
);
1787 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1790 s
.PrintfV(pszFormat
, argptr
);
1794 int wxString::Printf(const wxChar
*pszFormat
, ...)
1797 va_start(argptr
, pszFormat
);
1799 int iLen
= PrintfV(pszFormat
, argptr
);
1806 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1814 wxStringBuffer
tmp(*this, size
+ 1);
1823 // wxVsnprintf() may modify the original arg pointer, so pass it
1826 wxVaCopy(argptrcopy
, argptr
);
1827 len
= wxVsnprintf(buf
, size
, pszFormat
, argptrcopy
);
1830 // some implementations of vsnprintf() don't NUL terminate
1831 // the string if there is not enough space for it so
1832 // always do it manually
1833 buf
[size
] = _T('\0');
1836 // vsnprintf() may return either -1 (traditional Unix behaviour) or the
1837 // total number of characters which would have been written if the
1838 // buffer were large enough
1839 // also, it may return an errno may be something like EILSEQ,
1840 // in which case we need to break out
1841 if ( (len
>= 0 && len
<= size
) || errno
!= EOVERFLOW
)
1843 // ok, there was enough space
1847 // still not enough, double it again
1851 // we could have overshot
1857 // ----------------------------------------------------------------------------
1858 // misc other operations
1859 // ----------------------------------------------------------------------------
1861 // returns true if the string matches the pattern which may contain '*' and
1862 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1864 bool wxString::Matches(const wxChar
*pszMask
) const
1866 // I disable this code as it doesn't seem to be faster (in fact, it seems
1867 // to be much slower) than the old, hand-written code below and using it
1868 // here requires always linking with libregex even if the user code doesn't
1870 #if 0 // wxUSE_REGEX
1871 // first translate the shell-like mask into a regex
1873 pattern
.reserve(wxStrlen(pszMask
));
1885 pattern
+= _T(".*");
1896 // these characters are special in a RE, quote them
1897 // (however note that we don't quote '[' and ']' to allow
1898 // using them for Unix shell like matching)
1899 pattern
+= _T('\\');
1903 pattern
+= *pszMask
;
1911 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1912 #else // !wxUSE_REGEX
1913 // TODO: this is, of course, awfully inefficient...
1915 // the char currently being checked
1916 const wxChar
*pszTxt
= c_str();
1918 // the last location where '*' matched
1919 const wxChar
*pszLastStarInText
= NULL
;
1920 const wxChar
*pszLastStarInMask
= NULL
;
1923 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1924 switch ( *pszMask
) {
1926 if ( *pszTxt
== wxT('\0') )
1929 // pszTxt and pszMask will be incremented in the loop statement
1935 // remember where we started to be able to backtrack later
1936 pszLastStarInText
= pszTxt
;
1937 pszLastStarInMask
= pszMask
;
1939 // ignore special chars immediately following this one
1940 // (should this be an error?)
1941 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1944 // if there is nothing more, match
1945 if ( *pszMask
== wxT('\0') )
1948 // are there any other metacharacters in the mask?
1950 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1952 if ( pEndMask
!= NULL
) {
1953 // we have to match the string between two metachars
1954 uiLenMask
= pEndMask
- pszMask
;
1957 // we have to match the remainder of the string
1958 uiLenMask
= wxStrlen(pszMask
);
1961 wxString
strToMatch(pszMask
, uiLenMask
);
1962 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1963 if ( pMatch
== NULL
)
1966 // -1 to compensate "++" in the loop
1967 pszTxt
= pMatch
+ uiLenMask
- 1;
1968 pszMask
+= uiLenMask
- 1;
1973 if ( *pszMask
!= *pszTxt
)
1979 // match only if nothing left
1980 if ( *pszTxt
== wxT('\0') )
1983 // if we failed to match, backtrack if we can
1984 if ( pszLastStarInText
) {
1985 pszTxt
= pszLastStarInText
+ 1;
1986 pszMask
= pszLastStarInMask
;
1988 pszLastStarInText
= NULL
;
1990 // don't bother resetting pszLastStarInMask, it's unnecessary
1996 #endif // wxUSE_REGEX/!wxUSE_REGEX
1999 // Count the number of chars
2000 int wxString::Freq(wxChar ch
) const
2004 for (int i
= 0; i
< len
; i
++)
2006 if (GetChar(i
) == ch
)
2012 // convert to upper case, return the copy of the string
2013 wxString
wxString::Upper() const
2014 { wxString
s(*this); return s
.MakeUpper(); }
2016 // convert to lower case, return the copy of the string
2017 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
2019 int wxString::sprintf(const wxChar
*pszFormat
, ...)
2022 va_start(argptr
, pszFormat
);
2023 int iLen
= PrintfV(pszFormat
, argptr
);
2028 // ============================================================================
2030 // ============================================================================
2032 #include "wx/arrstr.h"
2036 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
2037 #define ARRAY_MAXSIZE_INCREMENT 4096
2039 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
2040 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
2043 #define STRING(p) ((wxString *)(&(p)))
2046 void wxArrayString::Init(bool autoSort
)
2050 m_pItems
= (wxChar
**) NULL
;
2051 m_autoSort
= autoSort
;
2055 wxArrayString::wxArrayString(const wxArrayString
& src
)
2057 Init(src
.m_autoSort
);
2062 // assignment operator
2063 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
2070 m_autoSort
= src
.m_autoSort
;
2075 void wxArrayString::Copy(const wxArrayString
& src
)
2077 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
2078 Alloc(src
.m_nCount
);
2080 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
2085 void wxArrayString::Grow(size_t nIncrement
)
2087 // only do it if no more place
2088 if ( (m_nSize
- m_nCount
) < nIncrement
) {
2089 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2090 // be never resized!
2091 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2092 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2095 if ( m_nSize
== 0 ) {
2096 // was empty, alloc some memory
2097 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
2098 if (m_nSize
< nIncrement
)
2099 m_nSize
= nIncrement
;
2100 m_pItems
= new wxChar
*[m_nSize
];
2103 // otherwise when it's called for the first time, nIncrement would be 0
2104 // and the array would never be expanded
2105 // add 50% but not too much
2106 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
2107 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
2108 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
2109 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
2110 if ( nIncrement
< ndefIncrement
)
2111 nIncrement
= ndefIncrement
;
2112 m_nSize
+= nIncrement
;
2113 wxChar
**pNew
= new wxChar
*[m_nSize
];
2115 // copy data to new location
2116 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2118 // delete old memory (but do not release the strings!)
2119 wxDELETEA(m_pItems
);
2126 void wxArrayString::Free()
2128 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
2129 STRING(m_pItems
[n
])->GetStringData()->Unlock();
2133 // deletes all the strings from the list
2134 void wxArrayString::Empty()
2141 // as Empty, but also frees memory
2142 void wxArrayString::Clear()
2149 wxDELETEA(m_pItems
);
2153 wxArrayString::~wxArrayString()
2157 wxDELETEA(m_pItems
);
2160 void wxArrayString::reserve(size_t nSize
)
2165 // pre-allocates memory (frees the previous data!)
2166 void wxArrayString::Alloc(size_t nSize
)
2168 // only if old buffer was not big enough
2169 if ( nSize
> m_nSize
) {
2171 wxDELETEA(m_pItems
);
2172 m_pItems
= new wxChar
*[nSize
];
2179 // minimizes the memory usage by freeing unused memory
2180 void wxArrayString::Shrink()
2182 // only do it if we have some memory to free
2183 if( m_nCount
< m_nSize
) {
2184 // allocates exactly as much memory as we need
2185 wxChar
**pNew
= new wxChar
*[m_nCount
];
2187 // copy data to new location
2188 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2194 #if WXWIN_COMPATIBILITY_2_4
2196 // return a wxString[] as required for some control ctors.
2197 wxString
* wxArrayString::GetStringArray() const
2199 wxString
*array
= 0;
2203 array
= new wxString
[m_nCount
];
2204 for( size_t i
= 0; i
< m_nCount
; i
++ )
2205 array
[i
] = m_pItems
[i
];
2211 void wxArrayString::Remove(size_t nIndex
, size_t nRemove
)
2213 RemoveAt(nIndex
, nRemove
);
2216 #endif // WXWIN_COMPATIBILITY_2_4
2218 // searches the array for an item (forward or backwards)
2219 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2222 // use binary search in the sorted array
2223 wxASSERT_MSG( bCase
&& !bFromEnd
,
2224 wxT("search parameters ignored for auto sorted array") );
2233 res
= wxStrcmp(sz
, m_pItems
[i
]);
2245 // use linear search in unsorted array
2247 if ( m_nCount
> 0 ) {
2248 size_t ui
= m_nCount
;
2250 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2257 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2258 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2267 // add item at the end
2268 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
2271 // insert the string at the correct position to keep the array sorted
2279 res
= str
.Cmp(m_pItems
[i
]);
2290 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2292 Insert(str
, lo
, nInsert
);
2297 wxASSERT( str
.GetStringData()->IsValid() );
2301 for (size_t i
= 0; i
< nInsert
; i
++)
2303 // the string data must not be deleted!
2304 str
.GetStringData()->Lock();
2307 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2309 size_t ret
= m_nCount
;
2310 m_nCount
+= nInsert
;
2315 // add item at the given position
2316 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2318 wxASSERT( str
.GetStringData()->IsValid() );
2320 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2321 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2322 wxT("array size overflow in wxArrayString::Insert") );
2326 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2327 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2329 for (size_t i
= 0; i
< nInsert
; i
++)
2331 str
.GetStringData()->Lock();
2332 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2334 m_nCount
+= nInsert
;
2337 // range insert (STL 23.2.4.3)
2339 wxArrayString::insert(iterator it
, const_iterator first
, const_iterator last
)
2341 const int idx
= it
- begin();
2346 // reset "it" since it can change inside Grow()
2349 while ( first
!= last
)
2351 it
= insert(it
, *first
);
2353 // insert returns an iterator to the last element inserted but we need
2354 // insert the next after this one, that is before the next one
2362 void wxArrayString::SetCount(size_t count
)
2367 while ( m_nCount
< count
)
2368 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2371 // removes item from array (by index)
2372 void wxArrayString::RemoveAt(size_t nIndex
, size_t nRemove
)
2374 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2375 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2376 wxT("removing too many elements in wxArrayString::Remove") );
2379 for (size_t i
= 0; i
< nRemove
; i
++)
2380 Item(nIndex
+ i
).GetStringData()->Unlock();
2382 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2383 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2384 m_nCount
-= nRemove
;
2387 // removes item from array (by value)
2388 void wxArrayString::Remove(const wxChar
*sz
)
2390 int iIndex
= Index(sz
);
2392 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2393 wxT("removing inexistent element in wxArrayString::Remove") );
2398 void wxArrayString::assign(const_iterator first
, const_iterator last
)
2400 reserve(last
- first
);
2401 for(; first
!= last
; ++first
)
2405 // ----------------------------------------------------------------------------
2407 // ----------------------------------------------------------------------------
2409 // we can only sort one array at a time with the quick-sort based
2412 // need a critical section to protect access to gs_compareFunction and
2413 // gs_sortAscending variables
2414 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2416 // call this before the value of the global sort vars is changed/after
2417 // you're finished with them
2418 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2419 gs_critsectStringSort = new wxCriticalSection; \
2420 gs_critsectStringSort->Enter()
2421 #define END_SORT() gs_critsectStringSort->Leave(); \
2422 delete gs_critsectStringSort; \
2423 gs_critsectStringSort = NULL
2425 #define START_SORT()
2427 #endif // wxUSE_THREADS
2429 // function to use for string comparaison
2430 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2432 // if we don't use the compare function, this flag tells us if we sort the
2433 // array in ascending or descending order
2434 static bool gs_sortAscending
= true;
2436 // function which is called by quick sort
2437 extern "C" int wxC_CALLING_CONV
// LINKAGEMODE
2438 wxStringCompareFunction(const void *first
, const void *second
)
2440 wxString
*strFirst
= (wxString
*)first
;
2441 wxString
*strSecond
= (wxString
*)second
;
2443 if ( gs_compareFunction
) {
2444 return gs_compareFunction(*strFirst
, *strSecond
);
2447 // maybe we should use wxStrcoll
2448 int result
= strFirst
->Cmp(*strSecond
);
2450 return gs_sortAscending
? result
: -result
;
2454 // sort array elements using passed comparaison function
2455 void wxArrayString::Sort(CompareFunction compareFunction
)
2459 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2460 gs_compareFunction
= compareFunction
;
2464 // reset it to NULL so that Sort(bool) will work the next time
2465 gs_compareFunction
= NULL
;
2470 typedef int (wxC_CALLING_CONV
* wxStringCompareFn
)(const void *first
, const void *second
);
2472 void wxArrayString::Sort(CompareFunction2 compareFunction
)
2474 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), (wxStringCompareFn
)compareFunction
);
2477 void wxArrayString::Sort(bool reverseOrder
)
2479 Sort(reverseOrder
? wxStringSortDescending
: wxStringSortAscending
);
2482 void wxArrayString::DoSort()
2484 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2486 // just sort the pointers using qsort() - of course it only works because
2487 // wxString() *is* a pointer to its data
2488 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2491 bool wxArrayString::operator==(const wxArrayString
& a
) const
2493 if ( m_nCount
!= a
.m_nCount
)
2496 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2498 if ( Item(n
) != a
[n
] )
2505 #endif // !wxUSE_STL
2507 int wxCMPFUNC_CONV
wxStringSortAscending(wxString
* s1
, wxString
* s2
)
2509 return s1
->Cmp(*s2
);
2512 int wxCMPFUNC_CONV
wxStringSortDescending(wxString
* s1
, wxString
* s2
)
2514 return -s1
->Cmp(*s2
);