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"
50 // allocating extra space for each string consumes more memory but speeds up
51 // the concatenation operations (nLen is the current string's length)
52 // NB: EXTRA_ALLOC must be >= 0!
53 #define EXTRA_ALLOC (19 - nLen % 16)
55 // ---------------------------------------------------------------------------
56 // static class variables definition
57 // ---------------------------------------------------------------------------
60 //According to STL _must_ be a -1 size_t
61 const size_t wxStringBase::npos
= (size_t) -1;
64 // ----------------------------------------------------------------------------
66 // ----------------------------------------------------------------------------
70 extern const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= _T("");
74 // for an empty string, GetStringData() will return this address: this
75 // structure has the same layout as wxStringData and it's data() method will
76 // return the empty string (dummy pointer)
81 } g_strEmpty
= { {-1, 0, 0}, wxT('\0') };
83 // empty C style string: points to 'string data' byte of g_strEmpty
84 extern const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= &g_strEmpty
.dummy
;
88 // ----------------------------------------------------------------------------
90 // ----------------------------------------------------------------------------
92 #if wxUSE_STD_IOSTREAM
96 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
106 #endif // wxUSE_STD_IOSTREAM
108 // ----------------------------------------------------------------------------
110 // ----------------------------------------------------------------------------
112 // this small class is used to gather statistics for performance tuning
113 //#define WXSTRING_STATISTICS
114 #ifdef WXSTRING_STATISTICS
118 Averager(const wxChar
*sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
120 { wxPrintf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
122 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
125 size_t m_nCount
, m_nTotal
;
127 } g_averageLength("allocation size"),
128 g_averageSummandLength("summand length"),
129 g_averageConcatHit("hit probability in concat"),
130 g_averageInitialLength("initial string length");
132 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
134 #define STATISTICS_ADD(av, val)
135 #endif // WXSTRING_STATISTICS
139 // ===========================================================================
140 // wxStringData class deallocation
141 // ===========================================================================
143 #if defined(__VISUALC__) && defined(_MT) && !defined(_DLL)
144 # pragma message (__FILE__ ": building with Multithreaded non DLL runtime has a performance impact on wxString!")
145 void wxStringData::Free()
151 // ===========================================================================
153 // ===========================================================================
155 // takes nLength elements of psz starting at nPos
156 void wxStringBase::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
160 // if the length is not given, assume the string to be NUL terminated
161 if ( nLength
== npos
) {
162 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
164 nLength
= wxStrlen(psz
+ nPos
);
167 STATISTICS_ADD(InitialLength
, nLength
);
170 // trailing '\0' is written in AllocBuffer()
171 if ( !AllocBuffer(nLength
) ) {
172 wxFAIL_MSG( _T("out of memory in wxStringBase::InitWith") );
175 wxTmemcpy(m_pchData
, psz
+ nPos
, nLength
);
179 // poor man's iterators are "void *" pointers
180 wxStringBase::wxStringBase(const void *pStart
, const void *pEnd
)
182 if ( pEnd
>= pStart
)
184 InitWith((const wxChar
*)pStart
, 0,
185 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
189 wxFAIL_MSG( _T("pStart is not before pEnd") );
194 wxStringBase::wxStringBase(size_type n
, wxChar ch
)
200 // ---------------------------------------------------------------------------
202 // ---------------------------------------------------------------------------
204 // allocates memory needed to store a C string of length nLen
205 bool wxStringBase::AllocBuffer(size_t nLen
)
207 // allocating 0 sized buffer doesn't make sense, all empty strings should
209 wxASSERT( nLen
> 0 );
211 // make sure that we don't overflow
212 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
213 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
215 STATISTICS_ADD(Length
, nLen
);
218 // 1) one extra character for '\0' termination
219 // 2) sizeof(wxStringData) for housekeeping info
220 wxStringData
* pData
= (wxStringData
*)
221 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
223 if ( pData
== NULL
) {
224 // allocation failures are handled by the caller
229 pData
->nDataLength
= nLen
;
230 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
231 m_pchData
= pData
->data(); // data starts after wxStringData
232 m_pchData
[nLen
] = wxT('\0');
236 // must be called before changing this string
237 bool wxStringBase::CopyBeforeWrite()
239 wxStringData
* pData
= GetStringData();
241 if ( pData
->IsShared() ) {
242 pData
->Unlock(); // memory not freed because shared
243 size_t nLen
= pData
->nDataLength
;
244 if ( !AllocBuffer(nLen
) ) {
245 // allocation failures are handled by the caller
248 wxTmemcpy(m_pchData
, pData
->data(), nLen
);
251 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
256 // must be called before replacing contents of this string
257 bool wxStringBase::AllocBeforeWrite(size_t nLen
)
259 wxASSERT( nLen
!= 0 ); // doesn't make any sense
261 // must not share string and must have enough space
262 wxStringData
* pData
= GetStringData();
263 if ( pData
->IsShared() || pData
->IsEmpty() ) {
264 // can't work with old buffer, get new one
266 if ( !AllocBuffer(nLen
) ) {
267 // allocation failures are handled by the caller
272 if ( nLen
> pData
->nAllocLength
) {
273 // realloc the buffer instead of calling malloc() again, this is more
275 STATISTICS_ADD(Length
, nLen
);
279 pData
= (wxStringData
*)
280 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
282 if ( pData
== NULL
) {
283 // allocation failures are handled by the caller
284 // keep previous data since reallocation failed
288 pData
->nAllocLength
= nLen
;
289 m_pchData
= pData
->data();
293 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
295 // it doesn't really matter what the string length is as it's going to be
296 // overwritten later but, for extra safety, set it to 0 for now as we may
297 // have some junk in m_pchData
298 GetStringData()->nDataLength
= 0;
303 wxStringBase
& wxStringBase::append(size_t n
, wxChar ch
)
305 size_type len
= length();
307 if ( !Alloc(len
+ n
) || !CopyBeforeWrite() ) {
308 wxFAIL_MSG( _T("out of memory in wxStringBase::append") );
310 GetStringData()->nDataLength
= len
+ n
;
311 m_pchData
[len
+ n
] = '\0';
312 for ( size_t i
= 0; i
< n
; ++i
)
313 m_pchData
[len
+ i
] = ch
;
317 void wxStringBase::resize(size_t nSize
, wxChar ch
)
319 size_t len
= length();
323 erase(begin() + nSize
, end());
325 else if ( nSize
> len
)
327 append(nSize
- len
, ch
);
329 //else: we have exactly the specified length, nothing to do
332 // allocate enough memory for nLen characters
333 bool wxStringBase::Alloc(size_t nLen
)
335 wxStringData
*pData
= GetStringData();
336 if ( pData
->nAllocLength
<= nLen
) {
337 if ( pData
->IsEmpty() ) {
340 pData
= (wxStringData
*)
341 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
343 if ( pData
== NULL
) {
344 // allocation failure handled by caller
349 pData
->nDataLength
= 0;
350 pData
->nAllocLength
= nLen
;
351 m_pchData
= pData
->data(); // data starts after wxStringData
352 m_pchData
[0u] = wxT('\0');
354 else if ( pData
->IsShared() ) {
355 pData
->Unlock(); // memory not freed because shared
356 size_t nOldLen
= pData
->nDataLength
;
357 if ( !AllocBuffer(nLen
) ) {
358 // allocation failure handled by caller
361 // +1 to copy the terminator, too
362 memcpy(m_pchData
, pData
->data(), (nOldLen
+1)*sizeof(wxChar
));
363 GetStringData()->nDataLength
= nOldLen
;
368 pData
= (wxStringData
*)
369 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
371 if ( pData
== NULL
) {
372 // allocation failure handled by caller
373 // keep previous data since reallocation failed
377 // it's not important if the pointer changed or not (the check for this
378 // is not faster than assigning to m_pchData in all cases)
379 pData
->nAllocLength
= nLen
;
380 m_pchData
= pData
->data();
383 //else: we've already got enough
387 wxStringBase::iterator
wxStringBase::begin()
394 wxStringBase::iterator
wxStringBase::end()
398 return m_pchData
+ length();
401 wxStringBase::iterator
wxStringBase::erase(iterator it
)
403 size_type idx
= it
- begin();
405 return begin() + idx
;
408 wxStringBase
& wxStringBase::erase(size_t nStart
, size_t nLen
)
410 wxASSERT(nStart
<= length());
411 size_t strLen
= length() - nStart
;
412 // delete nLen or up to the end of the string characters
413 nLen
= strLen
< nLen
? strLen
: nLen
;
414 wxString
strTmp(c_str(), nStart
);
415 strTmp
.append(c_str() + nStart
+ nLen
, length() - nStart
- nLen
);
421 wxStringBase
& wxStringBase::insert(size_t nPos
, const wxChar
*sz
, size_t n
)
423 wxASSERT( nPos
<= length() );
425 if ( n
== npos
) n
= wxStrlen(sz
);
426 if ( n
== 0 ) return *this;
428 if ( !Alloc(length() + n
) || !CopyBeforeWrite() ) {
429 wxFAIL_MSG( _T("out of memory in wxStringBase::insert") );
432 memmove(m_pchData
+ nPos
+ n
, m_pchData
+ nPos
,
433 (length() - nPos
) * sizeof(wxChar
));
434 memcpy(m_pchData
+ nPos
, sz
, n
* sizeof(wxChar
));
435 GetStringData()->nDataLength
= length() + n
;
436 m_pchData
[length()] = '\0';
441 void wxStringBase::swap(wxStringBase
& str
)
443 wxChar
* tmp
= str
.m_pchData
;
444 str
.m_pchData
= m_pchData
;
448 size_t wxStringBase::find(const wxStringBase
& str
, size_t nStart
) const
450 // deal with the special case of empty string first
451 const size_t nLen
= length();
452 const size_t nLenOther
= str
.length();
456 // empty string is a substring of anything
462 // the other string is non empty so can't be our substring
466 wxASSERT( str
.GetStringData()->IsValid() );
467 wxASSERT( nStart
<= nLen
);
469 const wxChar
* const other
= str
.c_str();
472 const wxChar
* p
= (const wxChar
*)wxTmemchr(c_str() + nStart
,
479 while ( p
- c_str() + nLenOther
<= nLen
&& wxTmemcmp(p
, other
, nLenOther
) )
484 p
= (const wxChar
*)wxTmemchr(p
, *other
, nLen
- (p
- c_str()));
490 return p
- c_str() + nLenOther
<= nLen
? p
- c_str() : npos
;
493 size_t wxStringBase::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
495 return find(wxStringBase(sz
, n
), nStart
);
498 size_t wxStringBase::find(wxChar ch
, size_t nStart
) const
500 wxASSERT( nStart
<= length() );
502 const wxChar
*p
= (const wxChar
*)wxTmemchr(c_str() + nStart
, ch
, length() - nStart
);
504 return p
== NULL
? npos
: p
- c_str();
507 size_t wxStringBase::rfind(const wxStringBase
& str
, size_t nStart
) const
509 wxASSERT( str
.GetStringData()->IsValid() );
510 wxASSERT( nStart
== npos
|| nStart
<= length() );
512 if ( length() >= str
.length() )
514 // avoids a corner case later
515 if ( length() == 0 && str
.length() == 0 )
518 // "top" is the point where search starts from
519 size_t top
= length() - str
.length();
521 if ( nStart
== npos
)
522 nStart
= length() - 1;
526 const wxChar
*cursor
= c_str() + top
;
529 if ( wxTmemcmp(cursor
, str
.c_str(),
532 return cursor
- c_str();
534 } while ( cursor
-- > c_str() );
540 size_t wxStringBase::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
542 return rfind(wxStringBase(sz
, n
), nStart
);
545 size_t wxStringBase::rfind(wxChar ch
, size_t nStart
) const
547 if ( nStart
== npos
)
553 wxASSERT( nStart
<= length() );
556 const wxChar
*actual
;
557 for ( actual
= c_str() + ( nStart
== npos
? length() : nStart
+ 1 );
558 actual
> c_str(); --actual
)
560 if ( *(actual
- 1) == ch
)
561 return (actual
- 1) - c_str();
567 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
) const
569 wxASSERT(nStart
<= length());
571 size_t len
= wxStrlen(sz
);
574 for(i
= nStart
; i
< this->length(); ++i
)
576 if (wxTmemchr(sz
, *(c_str() + i
), len
))
580 if(i
== this->length())
586 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
,
589 return find_first_of(wxStringBase(sz
, n
), nStart
);
592 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
) const
594 if ( nStart
== npos
)
596 nStart
= length() - 1;
600 wxASSERT_MSG( nStart
<= length(),
601 _T("invalid index in find_last_of()") );
604 size_t len
= wxStrlen(sz
);
606 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
608 if ( wxTmemchr(sz
, *p
, len
) )
615 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
,
618 return find_last_of(wxStringBase(sz
, n
), nStart
);
621 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
623 if ( nStart
== npos
)
629 wxASSERT( nStart
<= length() );
632 size_t len
= wxStrlen(sz
);
635 for(i
= nStart
; i
< this->length(); ++i
)
637 if (!wxTmemchr(sz
, *(c_str() + i
), len
))
641 if(i
== this->length())
647 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
,
650 return find_first_not_of(wxStringBase(sz
, n
), nStart
);
653 size_t wxStringBase::find_first_not_of(wxChar ch
, size_t nStart
) const
655 wxASSERT( nStart
<= length() );
657 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
666 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
668 if ( nStart
== npos
)
670 nStart
= length() - 1;
674 wxASSERT( nStart
<= length() );
677 size_t len
= wxStrlen(sz
);
679 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
681 if ( !wxTmemchr(sz
, *p
,len
) )
688 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
,
691 return find_last_not_of(wxStringBase(sz
, n
), nStart
);
694 size_t wxStringBase::find_last_not_of(wxChar ch
, size_t nStart
) const
696 if ( nStart
== npos
)
698 nStart
= length() - 1;
702 wxASSERT( nStart
<= length() );
705 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
714 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
717 wxASSERT_MSG( nStart
<= length(),
718 _T("index out of bounds in wxStringBase::replace") );
719 size_t strLen
= length() - nStart
;
720 nLen
= strLen
< nLen
? strLen
: nLen
;
723 strTmp
.reserve(length()); // micro optimisation to avoid multiple mem allocs
725 //This is kind of inefficient, but its pretty good considering...
726 //we don't want to use character access operators here because on STL
727 //it will freeze the reference count of strTmp, which means a deep copy
728 //at the end when swap is called
730 //Also, we can't use append with the full character pointer and must
731 //do it manually because this string can contain null characters
732 for(size_t i1
= 0; i1
< nStart
; ++i1
)
733 strTmp
.append(1, this->c_str()[i1
]);
735 //its safe to do the full version here because
736 //sz must be a normal c string
739 for(size_t i2
= nStart
+ nLen
; i2
< length(); ++i2
)
740 strTmp
.append(1, this->c_str()[i2
]);
746 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
747 size_t nCount
, wxChar ch
)
749 return replace(nStart
, nLen
, wxStringBase(nCount
, ch
).c_str());
752 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
753 const wxStringBase
& str
,
754 size_t nStart2
, size_t nLen2
)
756 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
759 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
760 const wxChar
* sz
, size_t nCount
)
762 return replace(nStart
, nLen
, wxStringBase(sz
, nCount
).c_str());
765 wxStringBase
wxStringBase::substr(size_t nStart
, size_t nLen
) const
768 nLen
= length() - nStart
;
769 return wxStringBase(*this, nStart
, nLen
);
772 // assigns one string to another
773 wxStringBase
& wxStringBase::operator=(const wxStringBase
& stringSrc
)
775 wxASSERT( stringSrc
.GetStringData()->IsValid() );
777 // don't copy string over itself
778 if ( m_pchData
!= stringSrc
.m_pchData
) {
779 if ( stringSrc
.GetStringData()->IsEmpty() ) {
784 GetStringData()->Unlock();
785 m_pchData
= stringSrc
.m_pchData
;
786 GetStringData()->Lock();
793 // assigns a single character
794 wxStringBase
& wxStringBase::operator=(wxChar ch
)
796 if ( !AssignCopy(1, &ch
) ) {
797 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(wxChar)") );
803 wxStringBase
& wxStringBase::operator=(const wxChar
*psz
)
805 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
806 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(const wxChar *)") );
811 // helper function: does real copy
812 bool wxStringBase::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
814 if ( nSrcLen
== 0 ) {
818 if ( !AllocBeforeWrite(nSrcLen
) ) {
819 // allocation failure handled by caller
822 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
823 GetStringData()->nDataLength
= nSrcLen
;
824 m_pchData
[nSrcLen
] = wxT('\0');
829 // ---------------------------------------------------------------------------
830 // string concatenation
831 // ---------------------------------------------------------------------------
833 // add something to this string
834 bool wxStringBase::ConcatSelf(size_t nSrcLen
, const wxChar
*pszSrcData
,
837 STATISTICS_ADD(SummandLength
, nSrcLen
);
839 nSrcLen
= nSrcLen
< nMaxLen
? nSrcLen
: nMaxLen
;
841 // concatenating an empty string is a NOP
843 wxStringData
*pData
= GetStringData();
844 size_t nLen
= pData
->nDataLength
;
845 size_t nNewLen
= nLen
+ nSrcLen
;
847 // alloc new buffer if current is too small
848 if ( pData
->IsShared() ) {
849 STATISTICS_ADD(ConcatHit
, 0);
851 // we have to allocate another buffer
852 wxStringData
* pOldData
= GetStringData();
853 if ( !AllocBuffer(nNewLen
) ) {
854 // allocation failure handled by caller
857 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
860 else if ( nNewLen
> pData
->nAllocLength
) {
861 STATISTICS_ADD(ConcatHit
, 0);
864 // we have to grow the buffer
865 if ( capacity() < nNewLen
) {
866 // allocation failure handled by caller
871 STATISTICS_ADD(ConcatHit
, 1);
873 // the buffer is already big enough
876 // should be enough space
877 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
879 // fast concatenation - all is done in our buffer
880 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
882 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
883 GetStringData()->nDataLength
= nNewLen
; // and fix the length
885 //else: the string to append was empty
889 // ---------------------------------------------------------------------------
890 // simple sub-string extraction
891 // ---------------------------------------------------------------------------
893 // helper function: clone the data attached to this string
894 bool wxStringBase::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
896 if ( nCopyLen
== 0 ) {
900 if ( !dest
.AllocBuffer(nCopyLen
) ) {
901 // allocation failure handled by caller
904 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
911 #if !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
914 #define STRINGCLASS wxStringBase
916 #define STRINGCLASS wxString
919 static inline int wxDoCmp(const wxChar
* s1
, size_t l1
,
920 const wxChar
* s2
, size_t l2
)
923 return wxTmemcmp(s1
, s2
, l1
);
926 int ret
= wxTmemcmp(s1
, s2
, l1
);
927 return ret
== 0 ? -1 : ret
;
931 int ret
= wxTmemcmp(s1
, s2
, l2
);
932 return ret
== 0 ? +1 : ret
;
936 int STRINGCLASS::compare(const wxStringBase
& str
) const
938 return ::wxDoCmp(data(), length(), str
.data(), str
.length());
941 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
942 const wxStringBase
& str
) const
944 wxASSERT(nStart
<= length());
945 size_type strLen
= length() - nStart
;
946 nLen
= strLen
< nLen
? strLen
: nLen
;
947 return ::wxDoCmp(data() + nStart
, nLen
, str
.data(), str
.length());
950 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
951 const wxStringBase
& str
,
952 size_t nStart2
, size_t nLen2
) const
954 wxASSERT(nStart
<= length());
955 wxASSERT(nStart2
<= str
.length());
956 size_type strLen
= length() - nStart
,
957 strLen2
= str
.length() - nStart2
;
958 nLen
= strLen
< nLen
? strLen
: nLen
;
959 nLen2
= strLen2
< nLen2
? strLen2
: nLen2
;
960 return ::wxDoCmp(data() + nStart
, nLen
, str
.data() + nStart2
, nLen2
);
963 int STRINGCLASS::compare(const wxChar
* sz
) const
965 size_t nLen
= wxStrlen(sz
);
966 return ::wxDoCmp(data(), length(), sz
, nLen
);
969 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
970 const wxChar
* sz
, size_t nCount
) const
972 wxASSERT(nStart
<= length());
973 size_type strLen
= length() - nStart
;
974 nLen
= strLen
< nLen
? strLen
: nLen
;
976 nCount
= wxStrlen(sz
);
978 return ::wxDoCmp(data() + nStart
, nLen
, sz
, nCount
);
983 #endif // !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
985 // ===========================================================================
986 // wxString class core
987 // ===========================================================================
989 // ---------------------------------------------------------------------------
990 // construction and conversion
991 // ---------------------------------------------------------------------------
995 // from multibyte string
996 wxString::wxString(const char *psz
, const wxMBConv
& conv
, size_t nLength
)
999 if ( psz
&& nLength
!= 0 )
1001 if ( nLength
== npos
)
1007 wxWCharBuffer wbuf
= conv
.cMB2WC(psz
, nLength
, &nLenWide
);
1010 assign(wbuf
, nLenWide
);
1014 //Convert wxString in Unicode mode to a multi-byte string
1015 const wxCharBuffer
wxString::mb_str(const wxMBConv
& conv
) const
1017 return conv
.cWC2MB(c_str(), length() + 1 /* size, not length */, NULL
);
1025 wxString::wxString(const wchar_t *pwz
, const wxMBConv
& conv
, size_t nLength
)
1028 if ( pwz
&& nLength
!= 0 )
1030 if ( nLength
== npos
)
1036 wxCharBuffer buf
= conv
.cWC2MB(pwz
, nLength
, &nLenMB
);
1039 assign(buf
, nLenMB
);
1043 //Converts this string to a wide character string if unicode
1044 //mode is not enabled and wxUSE_WCHAR_T is enabled
1045 const wxWCharBuffer
wxString::wc_str(const wxMBConv
& conv
) const
1047 return conv
.cMB2WC(c_str(), length() + 1 /* size, not length */, NULL
);
1050 #endif // wxUSE_WCHAR_T
1052 #endif // Unicode/ANSI
1054 // shrink to minimal size (releasing extra memory)
1055 bool wxString::Shrink()
1057 wxString
tmp(begin(), end());
1059 return tmp
.length() == length();
1063 // get the pointer to writable buffer of (at least) nLen bytes
1064 wxChar
*wxString::DoGetWriteBuf(size_t nLen
)
1066 if ( !AllocBeforeWrite(nLen
) ) {
1067 // allocation failure handled by caller
1071 wxASSERT( GetStringData()->nRefs
== 1 );
1072 GetStringData()->Validate(false);
1077 // put string back in a reasonable state after GetWriteBuf
1078 void wxString::DoUngetWriteBuf()
1080 DoUngetWriteBuf(wxStrlen(m_pchData
));
1083 void wxString::DoUngetWriteBuf(size_t nLen
)
1085 wxStringData
* const pData
= GetStringData();
1087 wxASSERT_MSG( nLen
< pData
->nAllocLength
, _T("buffer overrun") );
1089 // the strings we store are always NUL-terminated
1090 pData
->data()[nLen
] = _T('\0');
1091 pData
->nDataLength
= nLen
;
1092 pData
->Validate(true);
1095 // deprecated compatibility code:
1096 #if WXWIN_COMPATIBILITY_2_8
1097 wxChar
*wxString::GetWriteBuf(size_t nLen
)
1099 return DoGetWriteBuf(nLen
);
1102 void wxString::UngetWriteBuf()
1107 void wxString::UngetWriteBuf(size_t nLen
)
1109 DoUngetWriteBuf(nLen
);
1111 #endif // WXWIN_COMPATIBILITY_2_8
1113 #endif // !wxUSE_STL
1116 // ---------------------------------------------------------------------------
1118 // ---------------------------------------------------------------------------
1120 // all functions are inline in string.h
1122 // ---------------------------------------------------------------------------
1123 // assignment operators
1124 // ---------------------------------------------------------------------------
1128 // same as 'signed char' variant
1129 wxString
& wxString::operator=(const unsigned char* psz
)
1131 *this = (const char *)psz
;
1136 wxString
& wxString::operator=(const wchar_t *pwz
)
1147 * concatenation functions come in 5 flavours:
1149 * char + string and string + char
1150 * C str + string and string + C str
1153 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
1156 wxASSERT( str1
.GetStringData()->IsValid() );
1157 wxASSERT( str2
.GetStringData()->IsValid() );
1166 wxString
operator+(const wxString
& str
, wxChar ch
)
1169 wxASSERT( str
.GetStringData()->IsValid() );
1178 wxString
operator+(wxChar ch
, const wxString
& str
)
1181 wxASSERT( str
.GetStringData()->IsValid() );
1190 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
1193 wxASSERT( str
.GetStringData()->IsValid() );
1197 if ( !s
.Alloc(wxStrlen(psz
) + str
.length()) ) {
1198 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1206 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
1209 wxASSERT( str
.GetStringData()->IsValid() );
1213 if ( !s
.Alloc(wxStrlen(psz
) + str
.length()) ) {
1214 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1222 // ===========================================================================
1223 // other common string functions
1224 // ===========================================================================
1226 int wxString::Cmp(const wxString
& s
) const
1231 int wxString::Cmp(const wxChar
* psz
) const
1233 return compare(psz
);
1236 static inline int wxDoCmpNoCase(const wxChar
* s1
, size_t l1
,
1237 const wxChar
* s2
, size_t l2
)
1243 for(i
= 0; i
< l1
; ++i
)
1245 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1248 return i
== l1
? 0 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1252 for(i
= 0; i
< l1
; ++i
)
1254 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1257 return i
== l1
? -1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1261 for(i
= 0; i
< l2
; ++i
)
1263 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1266 return i
== l2
? 1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1270 int wxString::CmpNoCase(const wxString
& s
) const
1272 return wxDoCmpNoCase(data(), length(), s
.data(), s
.length());
1275 int wxString::CmpNoCase(const wxChar
* psz
) const
1277 int nLen
= wxStrlen(psz
);
1279 return wxDoCmpNoCase(data(), length(), psz
, nLen
);
1286 #ifndef __SCHAR_MAX__
1287 #define __SCHAR_MAX__ 127
1291 wxString
wxString::FromAscii(const char *ascii
)
1294 return wxEmptyString
;
1296 size_t len
= strlen( ascii
);
1301 wxStringBuffer
buf(res
, len
);
1303 wchar_t *dest
= buf
;
1307 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
1315 wxString
wxString::FromAscii(const char ascii
)
1317 // What do we do with '\0' ?
1320 res
+= (wchar_t)(unsigned char) ascii
;
1325 const wxCharBuffer
wxString::ToAscii() const
1327 // this will allocate enough space for the terminating NUL too
1328 wxCharBuffer
buffer(length());
1331 char *dest
= buffer
.data();
1333 const wchar_t *pwc
= c_str();
1336 *dest
++ = (char)(*pwc
> SCHAR_MAX
? wxT('_') : *pwc
);
1338 // the output string can't have embedded NULs anyhow, so we can safely
1339 // stop at first of them even if we do have any
1349 // extract string of length nCount starting at nFirst
1350 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
1352 size_t nLen
= length();
1354 // default value of nCount is npos and means "till the end"
1355 if ( nCount
== npos
)
1357 nCount
= nLen
- nFirst
;
1360 // out-of-bounds requests return sensible things
1361 if ( nFirst
+ nCount
> nLen
)
1363 nCount
= nLen
- nFirst
;
1366 if ( nFirst
> nLen
)
1368 // AllocCopy() will return empty string
1369 return wxEmptyString
;
1372 wxString
dest(*this, nFirst
, nCount
);
1373 if ( dest
.length() != nCount
)
1375 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
1381 // check that the string starts with prefix and return the rest of the string
1382 // in the provided pointer if it is not NULL, otherwise return false
1383 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
1385 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
1387 // first check if the beginning of the string matches the prefix: note
1388 // that we don't have to check that we don't run out of this string as
1389 // when we reach the terminating NUL, either prefix string ends too (and
1390 // then it's ok) or we break out of the loop because there is no match
1391 const wxChar
*p
= c_str();
1394 if ( *prefix
++ != *p
++ )
1403 // put the rest of the string into provided pointer
1411 // check that the string ends with suffix and return the rest of it in the
1412 // provided pointer if it is not NULL, otherwise return false
1413 bool wxString::EndsWith(const wxChar
*suffix
, wxString
*rest
) const
1415 wxASSERT_MSG( suffix
, _T("invalid parameter in wxString::EndssWith") );
1417 int start
= length() - wxStrlen(suffix
);
1418 if ( start
< 0 || wxStrcmp(c_str() + start
, suffix
) != 0 )
1423 // put the rest of the string into provided pointer
1424 rest
->assign(*this, 0, start
);
1431 // extract nCount last (rightmost) characters
1432 wxString
wxString::Right(size_t nCount
) const
1434 if ( nCount
> length() )
1437 wxString
dest(*this, length() - nCount
, nCount
);
1438 if ( dest
.length() != nCount
) {
1439 wxFAIL_MSG( _T("out of memory in wxString::Right") );
1444 // get all characters after the last occurence of ch
1445 // (returns the whole string if ch not found)
1446 wxString
wxString::AfterLast(wxChar ch
) const
1449 int iPos
= Find(ch
, true);
1450 if ( iPos
== wxNOT_FOUND
)
1453 str
= c_str() + iPos
+ 1;
1458 // extract nCount first (leftmost) characters
1459 wxString
wxString::Left(size_t nCount
) const
1461 if ( nCount
> length() )
1464 wxString
dest(*this, 0, nCount
);
1465 if ( dest
.length() != nCount
) {
1466 wxFAIL_MSG( _T("out of memory in wxString::Left") );
1471 // get all characters before the first occurence of ch
1472 // (returns the whole string if ch not found)
1473 wxString
wxString::BeforeFirst(wxChar ch
) const
1475 int iPos
= Find(ch
);
1476 if ( iPos
== wxNOT_FOUND
) iPos
= length();
1477 return wxString(*this, 0, iPos
);
1480 /// get all characters before the last occurence of ch
1481 /// (returns empty string if ch not found)
1482 wxString
wxString::BeforeLast(wxChar ch
) const
1485 int iPos
= Find(ch
, true);
1486 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
1487 str
= wxString(c_str(), iPos
);
1492 /// get all characters after the first occurence of ch
1493 /// (returns empty string if ch not found)
1494 wxString
wxString::AfterFirst(wxChar ch
) const
1497 int iPos
= Find(ch
);
1498 if ( iPos
!= wxNOT_FOUND
)
1499 str
= c_str() + iPos
+ 1;
1504 // replace first (or all) occurences of some substring with another one
1505 size_t wxString::Replace(const wxChar
*szOld
,
1506 const wxChar
*szNew
, bool bReplaceAll
)
1508 // if we tried to replace an empty string we'd enter an infinite loop below
1509 wxCHECK_MSG( szOld
&& *szOld
&& szNew
, 0,
1510 _T("wxString::Replace(): invalid parameter") );
1512 size_t uiCount
= 0; // count of replacements made
1514 size_t uiOldLen
= wxStrlen(szOld
);
1515 size_t uiNewLen
= wxStrlen(szNew
);
1519 while ( this->c_str()[dwPos
] != wxT('\0') )
1521 //DO NOT USE STRSTR HERE
1522 //this string can contain embedded null characters,
1523 //so strstr will function incorrectly
1524 dwPos
= find(szOld
, dwPos
);
1525 if ( dwPos
== npos
)
1526 break; // exit the loop
1529 //replace this occurance of the old string with the new one
1530 replace(dwPos
, uiOldLen
, szNew
, uiNewLen
);
1532 //move up pos past the string that was replaced
1535 //increase replace count
1540 break; // exit the loop
1547 bool wxString::IsAscii() const
1549 const wxChar
*s
= (const wxChar
*) *this;
1551 if(!isascii(*s
)) return(false);
1557 bool wxString::IsWord() const
1559 const wxChar
*s
= (const wxChar
*) *this;
1561 if(!wxIsalpha(*s
)) return(false);
1567 bool wxString::IsNumber() const
1569 const wxChar
*s
= (const wxChar
*) *this;
1571 if ((s
[0] == wxT('-')) || (s
[0] == wxT('+'))) s
++;
1573 if(!wxIsdigit(*s
)) return(false);
1579 wxString
wxString::Strip(stripType w
) const
1582 if ( w
& leading
) s
.Trim(false);
1583 if ( w
& trailing
) s
.Trim(true);
1587 // ---------------------------------------------------------------------------
1589 // ---------------------------------------------------------------------------
1591 wxString
& wxString::MakeUpper()
1593 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1594 *it
= (wxChar
)wxToupper(*it
);
1599 wxString
& wxString::MakeLower()
1601 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1602 *it
= (wxChar
)wxTolower(*it
);
1607 // ---------------------------------------------------------------------------
1608 // trimming and padding
1609 // ---------------------------------------------------------------------------
1611 // some compilers (VC++ 6.0 not to name them) return true for a call to
1612 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1613 // live with this by checking that the character is a 7 bit one - even if this
1614 // may fail to detect some spaces (I don't know if Unicode doesn't have
1615 // space-like symbols somewhere except in the first 128 chars), it is arguably
1616 // still better than trimming away accented letters
1617 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1619 // trims spaces (in the sense of isspace) from left or right side
1620 wxString
& wxString::Trim(bool bFromRight
)
1622 // first check if we're going to modify the string at all
1625 (bFromRight
&& wxSafeIsspace(GetChar(length() - 1))) ||
1626 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1632 // find last non-space character
1633 reverse_iterator psz
= rbegin();
1634 while ( (psz
!= rend()) && wxSafeIsspace(*psz
) )
1637 // truncate at trailing space start
1638 erase(psz
.base(), end());
1642 // find first non-space character
1643 iterator psz
= begin();
1644 while ( (psz
!= end()) && wxSafeIsspace(*psz
) )
1647 // fix up data and length
1648 erase(begin(), psz
);
1655 // adds nCount characters chPad to the string from either side
1656 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1658 wxString
s(chPad
, nCount
);
1671 // truncate the string
1672 wxString
& wxString::Truncate(size_t uiLen
)
1674 if ( uiLen
< length() )
1676 erase(begin() + uiLen
, end());
1678 //else: nothing to do, string is already short enough
1683 // ---------------------------------------------------------------------------
1684 // finding (return wxNOT_FOUND if not found and index otherwise)
1685 // ---------------------------------------------------------------------------
1688 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1690 size_type idx
= bFromEnd
? find_last_of(ch
) : find_first_of(ch
);
1692 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1695 // find a sub-string (like strstr)
1696 int wxString::Find(const wxChar
*pszSub
) const
1698 size_type idx
= find(pszSub
);
1700 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1703 // ----------------------------------------------------------------------------
1704 // conversion to numbers
1705 // ----------------------------------------------------------------------------
1707 // the implementation of all the functions below is exactly the same so factor
1710 template <typename T
, typename F
>
1711 bool wxStringToIntType(const wxChar
*start
,
1716 wxCHECK_MSG( val
, false, _T("NULL output pointer") );
1717 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1724 *val
= (*func
)(start
, &end
, base
);
1726 // return true only if scan was stopped by the terminating NUL and if the
1727 // string was not empty to start with and no under/overflow occurred
1728 return !*end
&& (end
!= start
)
1730 && (errno
!= ERANGE
)
1735 bool wxString::ToLong(long *val
, int base
) const
1737 return wxStringToIntType(c_str(), val
, base
, wxStrtol
);
1740 bool wxString::ToULong(unsigned long *val
, int base
) const
1742 return wxStringToIntType(c_str(), val
, base
, wxStrtoul
);
1745 bool wxString::ToLongLong(wxLongLong_t
*val
, int base
) const
1747 #ifdef wxHAS_STRTOLL
1748 return wxStringToIntType(c_str(), val
, base
, wxStrtoll
);
1750 // TODO: implement this ourselves
1754 #endif // wxHAS_STRTOLL
1757 bool wxString::ToULongLong(wxULongLong_t
*val
, int base
) const
1759 #ifdef wxHAS_STRTOLL
1760 return wxStringToIntType(c_str(), val
, base
, wxStrtoull
);
1762 // TODO: implement this ourselves
1769 bool wxString::ToDouble(double *val
) const
1771 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToDouble") );
1777 const wxChar
*start
= c_str();
1779 *val
= wxStrtod(start
, &end
);
1781 // return true only if scan was stopped by the terminating NUL and if the
1782 // string was not empty to start with and no under/overflow occurred
1783 return !*end
&& (end
!= start
)
1785 && (errno
!= ERANGE
)
1790 // ---------------------------------------------------------------------------
1792 // ---------------------------------------------------------------------------
1795 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1798 va_start(argptr
, pszFormat
);
1801 s
.PrintfV(pszFormat
, argptr
);
1809 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1812 s
.PrintfV(pszFormat
, argptr
);
1816 int wxString::Printf(const wxChar
*pszFormat
, ...)
1819 va_start(argptr
, pszFormat
);
1821 int iLen
= PrintfV(pszFormat
, argptr
);
1828 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1834 wxStringBuffer
tmp(*this, size
+ 1);
1843 // wxVsnprintf() may modify the original arg pointer, so pass it
1846 wxVaCopy(argptrcopy
, argptr
);
1847 int len
= wxVsnprintf(buf
, size
, pszFormat
, argptrcopy
);
1850 // some implementations of vsnprintf() don't NUL terminate
1851 // the string if there is not enough space for it so
1852 // always do it manually
1853 buf
[size
] = _T('\0');
1855 // vsnprintf() may return either -1 (traditional Unix behaviour) or the
1856 // total number of characters which would have been written if the
1857 // buffer were large enough (newer standards such as Unix98)
1860 #if wxUSE_WXVSNPRINTF
1861 // we know that our own implementation of wxVsnprintf() returns -1
1862 // only for a format error - thus there's something wrong with
1863 // the user's format string
1865 #else // assume that system version only returns error if not enough space
1866 // still not enough, as we don't know how much we need, double the
1867 // current size of the buffer
1869 #endif // wxUSE_WXVSNPRINTF/!wxUSE_WXVSNPRINTF
1871 else if ( len
>= size
)
1873 #if wxUSE_WXVSNPRINTF
1874 // we know that our own implementation of wxVsnprintf() returns
1875 // size+1 when there's not enough space but that's not the size
1876 // of the required buffer!
1877 size
*= 2; // so we just double the current size of the buffer
1879 // some vsnprintf() implementations NUL-terminate the buffer and
1880 // some don't in len == size case, to be safe always add 1
1884 else // ok, there was enough space
1890 // we could have overshot
1896 // ----------------------------------------------------------------------------
1897 // misc other operations
1898 // ----------------------------------------------------------------------------
1900 // returns true if the string matches the pattern which may contain '*' and
1901 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1903 bool wxString::Matches(const wxChar
*pszMask
) const
1905 // I disable this code as it doesn't seem to be faster (in fact, it seems
1906 // to be much slower) than the old, hand-written code below and using it
1907 // here requires always linking with libregex even if the user code doesn't
1909 #if 0 // wxUSE_REGEX
1910 // first translate the shell-like mask into a regex
1912 pattern
.reserve(wxStrlen(pszMask
));
1924 pattern
+= _T(".*");
1935 // these characters are special in a RE, quote them
1936 // (however note that we don't quote '[' and ']' to allow
1937 // using them for Unix shell like matching)
1938 pattern
+= _T('\\');
1942 pattern
+= *pszMask
;
1950 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1951 #else // !wxUSE_REGEX
1952 // TODO: this is, of course, awfully inefficient...
1954 // the char currently being checked
1955 const wxChar
*pszTxt
= c_str();
1957 // the last location where '*' matched
1958 const wxChar
*pszLastStarInText
= NULL
;
1959 const wxChar
*pszLastStarInMask
= NULL
;
1962 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1963 switch ( *pszMask
) {
1965 if ( *pszTxt
== wxT('\0') )
1968 // pszTxt and pszMask will be incremented in the loop statement
1974 // remember where we started to be able to backtrack later
1975 pszLastStarInText
= pszTxt
;
1976 pszLastStarInMask
= pszMask
;
1978 // ignore special chars immediately following this one
1979 // (should this be an error?)
1980 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1983 // if there is nothing more, match
1984 if ( *pszMask
== wxT('\0') )
1987 // are there any other metacharacters in the mask?
1989 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1991 if ( pEndMask
!= NULL
) {
1992 // we have to match the string between two metachars
1993 uiLenMask
= pEndMask
- pszMask
;
1996 // we have to match the remainder of the string
1997 uiLenMask
= wxStrlen(pszMask
);
2000 wxString
strToMatch(pszMask
, uiLenMask
);
2001 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
2002 if ( pMatch
== NULL
)
2005 // -1 to compensate "++" in the loop
2006 pszTxt
= pMatch
+ uiLenMask
- 1;
2007 pszMask
+= uiLenMask
- 1;
2012 if ( *pszMask
!= *pszTxt
)
2018 // match only if nothing left
2019 if ( *pszTxt
== wxT('\0') )
2022 // if we failed to match, backtrack if we can
2023 if ( pszLastStarInText
) {
2024 pszTxt
= pszLastStarInText
+ 1;
2025 pszMask
= pszLastStarInMask
;
2027 pszLastStarInText
= NULL
;
2029 // don't bother resetting pszLastStarInMask, it's unnecessary
2035 #endif // wxUSE_REGEX/!wxUSE_REGEX
2038 // Count the number of chars
2039 int wxString::Freq(wxChar ch
) const
2043 for (int i
= 0; i
< len
; i
++)
2045 if (GetChar(i
) == ch
)
2051 // convert to upper case, return the copy of the string
2052 wxString
wxString::Upper() const
2053 { wxString
s(*this); return s
.MakeUpper(); }
2055 // convert to lower case, return the copy of the string
2056 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
2058 int wxString::sprintf(const wxChar
*pszFormat
, ...)
2061 va_start(argptr
, pszFormat
);
2062 int iLen
= PrintfV(pszFormat
, argptr
);
2067 // ============================================================================
2069 // ============================================================================
2071 #include "wx/arrstr.h"
2073 wxArrayString::wxArrayString(size_t sz
, const wxChar
** a
)
2078 for (size_t i
=0; i
< sz
; i
++)
2082 wxArrayString::wxArrayString(size_t sz
, const wxString
* a
)
2087 for (size_t i
=0; i
< sz
; i
++)
2093 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
2094 #define ARRAY_MAXSIZE_INCREMENT 4096
2096 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
2097 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
2100 #define STRING(p) ((wxString *)(&(p)))
2103 void wxArrayString::Init(bool autoSort
)
2107 m_pItems
= (const wxChar
**) NULL
;
2108 m_autoSort
= autoSort
;
2112 wxArrayString::wxArrayString(const wxArrayString
& src
)
2114 Init(src
.m_autoSort
);
2119 // assignment operator
2120 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
2127 m_autoSort
= src
.m_autoSort
;
2132 void wxArrayString::Copy(const wxArrayString
& src
)
2134 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
2135 Alloc(src
.m_nCount
);
2137 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
2142 void wxArrayString::Grow(size_t nIncrement
)
2144 // only do it if no more place
2145 if ( (m_nSize
- m_nCount
) < nIncrement
) {
2146 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2147 // be never resized!
2148 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2149 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2152 if ( m_nSize
== 0 ) {
2153 // was empty, alloc some memory
2154 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
2155 if (m_nSize
< nIncrement
)
2156 m_nSize
= nIncrement
;
2157 m_pItems
= new const wxChar
*[m_nSize
];
2160 // otherwise when it's called for the first time, nIncrement would be 0
2161 // and the array would never be expanded
2162 // add 50% but not too much
2163 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
2164 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
2165 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
2166 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
2167 if ( nIncrement
< ndefIncrement
)
2168 nIncrement
= ndefIncrement
;
2169 m_nSize
+= nIncrement
;
2170 const wxChar
**pNew
= new const wxChar
*[m_nSize
];
2172 // copy data to new location
2173 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2175 // delete old memory (but do not release the strings!)
2176 wxDELETEA(m_pItems
);
2183 void wxArrayString::Free()
2185 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
2186 STRING(m_pItems
[n
])->GetStringData()->Unlock();
2190 // deletes all the strings from the list
2191 void wxArrayString::Empty()
2198 // as Empty, but also frees memory
2199 void wxArrayString::Clear()
2206 wxDELETEA(m_pItems
);
2210 wxArrayString::~wxArrayString()
2214 wxDELETEA(m_pItems
);
2217 void wxArrayString::reserve(size_t nSize
)
2222 // pre-allocates memory (frees the previous data!)
2223 void wxArrayString::Alloc(size_t nSize
)
2225 // only if old buffer was not big enough
2226 if ( nSize
> m_nSize
) {
2227 const wxChar
**pNew
= new const wxChar
*[nSize
];
2231 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2239 // minimizes the memory usage by freeing unused memory
2240 void wxArrayString::Shrink()
2242 // only do it if we have some memory to free
2243 if( m_nCount
< m_nSize
) {
2244 // allocates exactly as much memory as we need
2245 const wxChar
**pNew
= new const wxChar
*[m_nCount
];
2247 // copy data to new location
2248 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2254 // searches the array for an item (forward or backwards)
2255 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2258 // use binary search in the sorted array
2259 wxASSERT_MSG( bCase
&& !bFromEnd
,
2260 wxT("search parameters ignored for auto sorted array") );
2269 res
= wxStrcmp(sz
, m_pItems
[i
]);
2281 // use linear search in unsorted array
2283 if ( m_nCount
> 0 ) {
2284 size_t ui
= m_nCount
;
2286 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2293 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2294 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2303 // add item at the end
2304 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
2307 // insert the string at the correct position to keep the array sorted
2315 res
= str
.Cmp(m_pItems
[i
]);
2326 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2328 Insert(str
, lo
, nInsert
);
2333 wxASSERT( str
.GetStringData()->IsValid() );
2337 for (size_t i
= 0; i
< nInsert
; i
++)
2339 // the string data must not be deleted!
2340 str
.GetStringData()->Lock();
2343 m_pItems
[m_nCount
+ i
] = str
.c_str();
2345 size_t ret
= m_nCount
;
2346 m_nCount
+= nInsert
;
2351 // add item at the given position
2352 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2354 wxASSERT( str
.GetStringData()->IsValid() );
2356 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2357 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2358 wxT("array size overflow in wxArrayString::Insert") );
2362 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2363 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2365 for (size_t i
= 0; i
< nInsert
; i
++)
2367 str
.GetStringData()->Lock();
2368 m_pItems
[nIndex
+ i
] = str
.c_str();
2370 m_nCount
+= nInsert
;
2373 // range insert (STL 23.2.4.3)
2375 wxArrayString::insert(iterator it
, const_iterator first
, const_iterator last
)
2377 const int idx
= it
- begin();
2382 // reset "it" since it can change inside Grow()
2385 while ( first
!= last
)
2387 it
= insert(it
, *first
);
2389 // insert returns an iterator to the last element inserted but we need
2390 // insert the next after this one, that is before the next one
2398 void wxArrayString::SetCount(size_t count
)
2403 while ( m_nCount
< count
)
2404 m_pItems
[m_nCount
++] = s
.c_str();
2407 // removes item from array (by index)
2408 void wxArrayString::RemoveAt(size_t nIndex
, size_t nRemove
)
2410 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2411 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2412 wxT("removing too many elements in wxArrayString::Remove") );
2415 for (size_t i
= 0; i
< nRemove
; i
++)
2416 Item(nIndex
+ i
).GetStringData()->Unlock();
2418 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2419 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2420 m_nCount
-= nRemove
;
2423 // removes item from array (by value)
2424 void wxArrayString::Remove(const wxChar
*sz
)
2426 int iIndex
= Index(sz
);
2428 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2429 wxT("removing inexistent element in wxArrayString::Remove") );
2434 void wxArrayString::assign(const_iterator first
, const_iterator last
)
2436 reserve(last
- first
);
2437 for(; first
!= last
; ++first
)
2441 // ----------------------------------------------------------------------------
2443 // ----------------------------------------------------------------------------
2445 // we can only sort one array at a time with the quick-sort based
2448 // need a critical section to protect access to gs_compareFunction and
2449 // gs_sortAscending variables
2450 static wxCriticalSection gs_critsectStringSort
;
2451 #endif // wxUSE_THREADS
2453 // function to use for string comparaison
2454 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2456 // if we don't use the compare function, this flag tells us if we sort the
2457 // array in ascending or descending order
2458 static bool gs_sortAscending
= true;
2460 // function which is called by quick sort
2461 extern "C" int wxC_CALLING_CONV
// LINKAGEMODE
2462 wxStringCompareFunction(const void *first
, const void *second
)
2464 wxString
*strFirst
= (wxString
*)first
;
2465 wxString
*strSecond
= (wxString
*)second
;
2467 if ( gs_compareFunction
) {
2468 return gs_compareFunction(*strFirst
, *strSecond
);
2471 // maybe we should use wxStrcoll
2472 int result
= strFirst
->Cmp(*strSecond
);
2474 return gs_sortAscending
? result
: -result
;
2478 // sort array elements using passed comparaison function
2479 void wxArrayString::Sort(CompareFunction compareFunction
)
2481 wxCRIT_SECT_LOCKER(lockCmpFunc
, gs_critsectStringSort
);
2483 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2484 gs_compareFunction
= compareFunction
;
2488 // reset it to NULL so that Sort(bool) will work the next time
2489 gs_compareFunction
= NULL
;
2494 typedef int (wxC_CALLING_CONV
* wxStringCompareFn
)(const void *first
,
2495 const void *second
);
2498 void wxArrayString::Sort(CompareFunction2 compareFunction
)
2500 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), (wxStringCompareFn
)compareFunction
);
2503 void wxArrayString::Sort(bool reverseOrder
)
2505 Sort(reverseOrder
? wxStringSortDescending
: wxStringSortAscending
);
2508 void wxArrayString::DoSort()
2510 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2512 // just sort the pointers using qsort() - of course it only works because
2513 // wxString() *is* a pointer to its data
2514 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2517 bool wxArrayString::operator==(const wxArrayString
& a
) const
2519 if ( m_nCount
!= a
.m_nCount
)
2522 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2524 if ( Item(n
) != a
[n
] )
2531 #endif // !wxUSE_STL
2533 int wxCMPFUNC_CONV
wxStringSortAscending(wxString
* s1
, wxString
* s2
)
2535 return s1
->Cmp(*s2
);
2538 int wxCMPFUNC_CONV
wxStringSortDescending(wxString
* s1
, wxString
* s2
)
2540 return -s1
->Cmp(*s2
);