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
)
98 return os
<< str
.c_str();
101 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxCStrData
& str
)
103 #if wxUSE_UNICODE && !defined(__BORLANDC__)
104 return os
<< str
.AsWChar();
106 return os
<< str
.AsChar();
110 #endif // wxUSE_STD_IOSTREAM
112 // ----------------------------------------------------------------------------
114 // ----------------------------------------------------------------------------
116 // this small class is used to gather statistics for performance tuning
117 //#define WXSTRING_STATISTICS
118 #ifdef WXSTRING_STATISTICS
122 Averager(const wxChar
*sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
124 { wxPrintf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
126 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
129 size_t m_nCount
, m_nTotal
;
131 } g_averageLength("allocation size"),
132 g_averageSummandLength("summand length"),
133 g_averageConcatHit("hit probability in concat"),
134 g_averageInitialLength("initial string length");
136 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
138 #define STATISTICS_ADD(av, val)
139 #endif // WXSTRING_STATISTICS
143 // ===========================================================================
144 // wxStringData class deallocation
145 // ===========================================================================
147 #if defined(__VISUALC__) && defined(_MT) && !defined(_DLL)
148 # pragma message (__FILE__ ": building with Multithreaded non DLL runtime has a performance impact on wxString!")
149 void wxStringData::Free()
155 // ===========================================================================
157 // ===========================================================================
159 // takes nLength elements of psz starting at nPos
160 void wxStringBase::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
164 // if the length is not given, assume the string to be NUL terminated
165 if ( nLength
== npos
) {
166 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
168 nLength
= wxStrlen(psz
+ nPos
);
171 STATISTICS_ADD(InitialLength
, nLength
);
174 // trailing '\0' is written in AllocBuffer()
175 if ( !AllocBuffer(nLength
) ) {
176 wxFAIL_MSG( _T("out of memory in wxStringBase::InitWith") );
179 wxTmemcpy(m_pchData
, psz
+ nPos
, nLength
);
183 // poor man's iterators are "void *" pointers
184 wxStringBase::wxStringBase(const void *pStart
, const void *pEnd
)
186 if ( pEnd
>= pStart
)
188 InitWith((const wxChar
*)pStart
, 0,
189 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
193 wxFAIL_MSG( _T("pStart is not before pEnd") );
198 wxStringBase::wxStringBase(size_type n
, wxUniChar ch
)
204 // ---------------------------------------------------------------------------
206 // ---------------------------------------------------------------------------
208 // allocates memory needed to store a C string of length nLen
209 bool wxStringBase::AllocBuffer(size_t nLen
)
211 // allocating 0 sized buffer doesn't make sense, all empty strings should
213 wxASSERT( nLen
> 0 );
215 // make sure that we don't overflow
216 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
217 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
219 STATISTICS_ADD(Length
, nLen
);
222 // 1) one extra character for '\0' termination
223 // 2) sizeof(wxStringData) for housekeeping info
224 wxStringData
* pData
= (wxStringData
*)
225 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
227 if ( pData
== NULL
) {
228 // allocation failures are handled by the caller
233 pData
->nDataLength
= nLen
;
234 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
235 m_pchData
= pData
->data(); // data starts after wxStringData
236 m_pchData
[nLen
] = wxT('\0');
240 // must be called before changing this string
241 bool wxStringBase::CopyBeforeWrite()
243 wxStringData
* pData
= GetStringData();
245 if ( pData
->IsShared() ) {
246 pData
->Unlock(); // memory not freed because shared
247 size_t nLen
= pData
->nDataLength
;
248 if ( !AllocBuffer(nLen
) ) {
249 // allocation failures are handled by the caller
252 wxTmemcpy(m_pchData
, pData
->data(), nLen
);
255 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
260 // must be called before replacing contents of this string
261 bool wxStringBase::AllocBeforeWrite(size_t nLen
)
263 wxASSERT( nLen
!= 0 ); // doesn't make any sense
265 // must not share string and must have enough space
266 wxStringData
* pData
= GetStringData();
267 if ( pData
->IsShared() || pData
->IsEmpty() ) {
268 // can't work with old buffer, get new one
270 if ( !AllocBuffer(nLen
) ) {
271 // allocation failures are handled by the caller
276 if ( nLen
> pData
->nAllocLength
) {
277 // realloc the buffer instead of calling malloc() again, this is more
279 STATISTICS_ADD(Length
, nLen
);
283 pData
= (wxStringData
*)
284 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
286 if ( pData
== NULL
) {
287 // allocation failures are handled by the caller
288 // keep previous data since reallocation failed
292 pData
->nAllocLength
= nLen
;
293 m_pchData
= pData
->data();
297 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
299 // it doesn't really matter what the string length is as it's going to be
300 // overwritten later but, for extra safety, set it to 0 for now as we may
301 // have some junk in m_pchData
302 GetStringData()->nDataLength
= 0;
307 wxStringBase
& wxStringBase::append(size_t n
, wxUniChar ch
)
309 size_type len
= length();
311 if ( !Alloc(len
+ n
) || !CopyBeforeWrite() ) {
312 wxFAIL_MSG( _T("out of memory in wxStringBase::append") );
314 GetStringData()->nDataLength
= len
+ n
;
315 m_pchData
[len
+ n
] = '\0';
316 for ( size_t i
= 0; i
< n
; ++i
)
317 m_pchData
[len
+ i
] = ch
;
321 void wxStringBase::resize(size_t nSize
, wxUniChar ch
)
323 size_t len
= length();
327 erase(begin() + nSize
, end());
329 else if ( nSize
> len
)
331 append(nSize
- len
, ch
);
333 //else: we have exactly the specified length, nothing to do
336 // allocate enough memory for nLen characters
337 bool wxStringBase::Alloc(size_t nLen
)
339 wxStringData
*pData
= GetStringData();
340 if ( pData
->nAllocLength
<= nLen
) {
341 if ( pData
->IsEmpty() ) {
344 pData
= (wxStringData
*)
345 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
347 if ( pData
== NULL
) {
348 // allocation failure handled by caller
353 pData
->nDataLength
= 0;
354 pData
->nAllocLength
= nLen
;
355 m_pchData
= pData
->data(); // data starts after wxStringData
356 m_pchData
[0u] = wxT('\0');
358 else if ( pData
->IsShared() ) {
359 pData
->Unlock(); // memory not freed because shared
360 size_t nOldLen
= pData
->nDataLength
;
361 if ( !AllocBuffer(nLen
) ) {
362 // allocation failure handled by caller
365 // +1 to copy the terminator, too
366 memcpy(m_pchData
, pData
->data(), (nOldLen
+1)*sizeof(wxChar
));
367 GetStringData()->nDataLength
= nOldLen
;
372 pData
= (wxStringData
*)
373 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
375 if ( pData
== NULL
) {
376 // allocation failure handled by caller
377 // keep previous data since reallocation failed
381 // it's not important if the pointer changed or not (the check for this
382 // is not faster than assigning to m_pchData in all cases)
383 pData
->nAllocLength
= nLen
;
384 m_pchData
= pData
->data();
387 //else: we've already got enough
391 wxStringBase::iterator
wxStringBase::begin()
398 wxStringBase::iterator
wxStringBase::end()
402 return m_pchData
+ length();
405 wxStringBase::iterator
wxStringBase::erase(iterator it
)
407 size_type idx
= it
- begin();
409 return begin() + idx
;
412 wxStringBase
& wxStringBase::erase(size_t nStart
, size_t nLen
)
414 wxASSERT(nStart
<= length());
415 size_t strLen
= length() - nStart
;
416 // delete nLen or up to the end of the string characters
417 nLen
= strLen
< nLen
? strLen
: nLen
;
418 wxString
strTmp(c_str(), nStart
);
419 strTmp
.append(c_str() + nStart
+ nLen
, length() - nStart
- nLen
);
425 wxStringBase
& wxStringBase::insert(size_t nPos
, const wxChar
*sz
, size_t n
)
427 wxASSERT( nPos
<= length() );
429 if ( n
== npos
) n
= wxStrlen(sz
);
430 if ( n
== 0 ) return *this;
432 if ( !Alloc(length() + n
) || !CopyBeforeWrite() ) {
433 wxFAIL_MSG( _T("out of memory in wxStringBase::insert") );
436 memmove(m_pchData
+ nPos
+ n
, m_pchData
+ nPos
,
437 (length() - nPos
) * sizeof(wxChar
));
438 memcpy(m_pchData
+ nPos
, sz
, n
* sizeof(wxChar
));
439 GetStringData()->nDataLength
= length() + n
;
440 m_pchData
[length()] = '\0';
445 void wxStringBase::swap(wxStringBase
& str
)
447 wxChar
* tmp
= str
.m_pchData
;
448 str
.m_pchData
= m_pchData
;
452 size_t wxStringBase::find(const wxStringBase
& str
, size_t nStart
) const
454 // deal with the special case of empty string first
455 const size_t nLen
= length();
456 const size_t nLenOther
= str
.length();
460 // empty string is a substring of anything
466 // the other string is non empty so can't be our substring
470 wxASSERT( str
.GetStringData()->IsValid() );
471 wxASSERT( nStart
<= nLen
);
473 const wxChar
* const other
= str
.c_str();
476 const wxChar
* p
= (const wxChar
*)wxTmemchr(c_str() + nStart
,
483 while ( p
- c_str() + nLenOther
<= nLen
&& wxTmemcmp(p
, other
, nLenOther
) )
488 p
= (const wxChar
*)wxTmemchr(p
, *other
, nLen
- (p
- c_str()));
494 return p
- c_str() + nLenOther
<= nLen
? p
- c_str() : npos
;
497 size_t wxStringBase::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
499 return find(wxStringBase(sz
, n
), nStart
);
502 size_t wxStringBase::find(wxUniChar ch
, size_t nStart
) const
504 wxASSERT( nStart
<= length() );
506 const wxChar
*p
= (const wxChar
*)wxTmemchr(c_str() + nStart
, ch
, length() - nStart
);
508 return p
== NULL
? npos
: p
- c_str();
511 size_t wxStringBase::rfind(const wxStringBase
& str
, size_t nStart
) const
513 wxASSERT( str
.GetStringData()->IsValid() );
514 wxASSERT( nStart
== npos
|| nStart
<= length() );
516 if ( length() >= str
.length() )
518 // avoids a corner case later
519 if ( length() == 0 && str
.length() == 0 )
522 // "top" is the point where search starts from
523 size_t top
= length() - str
.length();
525 if ( nStart
== npos
)
526 nStart
= length() - 1;
530 const wxChar
*cursor
= c_str() + top
;
533 if ( wxTmemcmp(cursor
, str
.c_str(),
536 return cursor
- c_str();
538 } while ( cursor
-- > c_str() );
544 size_t wxStringBase::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
546 return rfind(wxStringBase(sz
, n
), nStart
);
549 size_t wxStringBase::rfind(wxUniChar ch
, size_t nStart
) const
551 if ( nStart
== npos
)
557 wxASSERT( nStart
<= length() );
560 const wxChar
*actual
;
561 for ( actual
= c_str() + ( nStart
== npos
? length() : nStart
+ 1 );
562 actual
> c_str(); --actual
)
564 if ( *(actual
- 1) == ch
)
565 return (actual
- 1) - c_str();
571 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
) const
573 wxASSERT(nStart
<= length());
575 size_t len
= wxStrlen(sz
);
578 for(i
= nStart
; i
< this->length(); ++i
)
580 if (wxTmemchr(sz
, *(c_str() + i
), len
))
584 if(i
== this->length())
590 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
,
593 return find_first_of(wxStringBase(sz
, n
), nStart
);
596 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
) const
598 if ( nStart
== npos
)
600 nStart
= length() - 1;
604 wxASSERT_MSG( nStart
<= length(),
605 _T("invalid index in find_last_of()") );
608 size_t len
= wxStrlen(sz
);
610 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
612 if ( wxTmemchr(sz
, *p
, len
) )
619 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
,
622 return find_last_of(wxStringBase(sz
, n
), nStart
);
625 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
627 if ( nStart
== npos
)
633 wxASSERT( nStart
<= length() );
636 size_t len
= wxStrlen(sz
);
639 for(i
= nStart
; i
< this->length(); ++i
)
641 if (!wxTmemchr(sz
, *(c_str() + i
), len
))
645 if(i
== this->length())
651 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
,
654 return find_first_not_of(wxStringBase(sz
, n
), nStart
);
657 size_t wxStringBase::find_first_not_of(wxUniChar ch
, size_t nStart
) const
659 wxASSERT( nStart
<= length() );
661 for ( const_iterator p
= begin() + nStart
; (bool)*p
; ++p
) // FIXME-DMARS
670 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
672 if ( nStart
== npos
)
674 nStart
= length() - 1;
678 wxASSERT( nStart
<= length() );
681 size_t len
= wxStrlen(sz
);
683 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
685 if ( !wxTmemchr(sz
, *p
,len
) )
692 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
,
695 return find_last_not_of(wxStringBase(sz
, n
), nStart
);
698 size_t wxStringBase::find_last_not_of(wxUniChar ch
, size_t nStart
) const
700 if ( nStart
== npos
)
702 nStart
= length() - 1;
706 wxASSERT( nStart
<= length() );
709 for ( const_iterator p
= begin() + nStart
; p
!= begin(); --p
)
718 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
721 wxASSERT_MSG( nStart
<= length(),
722 _T("index out of bounds in wxStringBase::replace") );
723 size_t strLen
= length() - nStart
;
724 nLen
= strLen
< nLen
? strLen
: nLen
;
727 strTmp
.reserve(length()); // micro optimisation to avoid multiple mem allocs
729 //This is kind of inefficient, but its pretty good considering...
730 //we don't want to use character access operators here because on STL
731 //it will freeze the reference count of strTmp, which means a deep copy
732 //at the end when swap is called
734 //Also, we can't use append with the full character pointer and must
735 //do it manually because this string can contain null characters
736 for(size_t i1
= 0; i1
< nStart
; ++i1
)
737 strTmp
.append(1, this->c_str()[i1
]);
739 //its safe to do the full version here because
740 //sz must be a normal c string
743 for(size_t i2
= nStart
+ nLen
; i2
< length(); ++i2
)
744 strTmp
.append(1, this->c_str()[i2
]);
750 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
751 size_t nCount
, wxUniChar ch
)
753 return replace(nStart
, nLen
, wxStringBase(nCount
, ch
).c_str());
756 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
757 const wxStringBase
& str
,
758 size_t nStart2
, size_t nLen2
)
760 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
763 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
764 const wxChar
* sz
, size_t nCount
)
766 return replace(nStart
, nLen
, wxStringBase(sz
, nCount
).c_str());
769 wxStringBase
wxStringBase::substr(size_t nStart
, size_t nLen
) const
772 nLen
= length() - nStart
;
773 return wxStringBase(*this, nStart
, nLen
);
776 // assigns one string to another
777 wxStringBase
& wxStringBase::operator=(const wxStringBase
& stringSrc
)
779 wxASSERT( stringSrc
.GetStringData()->IsValid() );
781 // don't copy string over itself
782 if ( m_pchData
!= stringSrc
.m_pchData
) {
783 if ( stringSrc
.GetStringData()->IsEmpty() ) {
788 GetStringData()->Unlock();
789 m_pchData
= stringSrc
.m_pchData
;
790 GetStringData()->Lock();
797 // assigns a single character
798 wxStringBase
& wxStringBase::operator=(wxUniChar ch
)
801 if ( !AssignCopy(1, &c
) ) {
802 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(wxChar)") );
808 wxStringBase
& wxStringBase::operator=(const wxChar
*psz
)
810 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
811 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(const wxChar *)") );
816 // helper function: does real copy
817 bool wxStringBase::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
819 if ( nSrcLen
== 0 ) {
823 if ( !AllocBeforeWrite(nSrcLen
) ) {
824 // allocation failure handled by caller
827 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
828 GetStringData()->nDataLength
= nSrcLen
;
829 m_pchData
[nSrcLen
] = wxT('\0');
834 // ---------------------------------------------------------------------------
835 // string concatenation
836 // ---------------------------------------------------------------------------
838 // add something to this string
839 bool wxStringBase::ConcatSelf(size_t nSrcLen
, const wxChar
*pszSrcData
,
842 STATISTICS_ADD(SummandLength
, nSrcLen
);
844 nSrcLen
= nSrcLen
< nMaxLen
? nSrcLen
: nMaxLen
;
846 // concatenating an empty string is a NOP
848 wxStringData
*pData
= GetStringData();
849 size_t nLen
= pData
->nDataLength
;
850 size_t nNewLen
= nLen
+ nSrcLen
;
852 // alloc new buffer if current is too small
853 if ( pData
->IsShared() ) {
854 STATISTICS_ADD(ConcatHit
, 0);
856 // we have to allocate another buffer
857 wxStringData
* pOldData
= GetStringData();
858 if ( !AllocBuffer(nNewLen
) ) {
859 // allocation failure handled by caller
862 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
865 else if ( nNewLen
> pData
->nAllocLength
) {
866 STATISTICS_ADD(ConcatHit
, 0);
869 // we have to grow the buffer
870 if ( capacity() < nNewLen
) {
871 // allocation failure handled by caller
876 STATISTICS_ADD(ConcatHit
, 1);
878 // the buffer is already big enough
881 // should be enough space
882 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
884 // fast concatenation - all is done in our buffer
885 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
887 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
888 GetStringData()->nDataLength
= nNewLen
; // and fix the length
890 //else: the string to append was empty
894 // ---------------------------------------------------------------------------
895 // simple sub-string extraction
896 // ---------------------------------------------------------------------------
898 // helper function: clone the data attached to this string
899 bool wxStringBase::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
901 if ( nCopyLen
== 0 ) {
905 if ( !dest
.AllocBuffer(nCopyLen
) ) {
906 // allocation failure handled by caller
909 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
916 #if !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
919 #define STRINGCLASS wxStringBase
921 #define STRINGCLASS wxString
924 static inline int wxDoCmp(const wxChar
* s1
, size_t l1
,
925 const wxChar
* s2
, size_t l2
)
928 return wxTmemcmp(s1
, s2
, l1
);
931 int ret
= wxTmemcmp(s1
, s2
, l1
);
932 return ret
== 0 ? -1 : ret
;
936 int ret
= wxTmemcmp(s1
, s2
, l2
);
937 return ret
== 0 ? +1 : ret
;
941 int STRINGCLASS::compare(const wxStringBase
& str
) const
943 return ::wxDoCmp(data(), length(), str
.data(), str
.length());
946 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
947 const wxStringBase
& str
) const
949 wxASSERT(nStart
<= length());
950 size_type strLen
= length() - nStart
;
951 nLen
= strLen
< nLen
? strLen
: nLen
;
952 return ::wxDoCmp(data() + nStart
, nLen
, str
.data(), str
.length());
955 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
956 const wxStringBase
& str
,
957 size_t nStart2
, size_t nLen2
) const
959 wxASSERT(nStart
<= length());
960 wxASSERT(nStart2
<= str
.length());
961 size_type strLen
= length() - nStart
,
962 strLen2
= str
.length() - nStart2
;
963 nLen
= strLen
< nLen
? strLen
: nLen
;
964 nLen2
= strLen2
< nLen2
? strLen2
: nLen2
;
965 return ::wxDoCmp(data() + nStart
, nLen
, str
.data() + nStart2
, nLen2
);
968 int STRINGCLASS::compare(const wxChar
* sz
) const
970 size_t nLen
= wxStrlen(sz
);
971 return ::wxDoCmp(data(), length(), sz
, nLen
);
974 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
975 const wxChar
* sz
, size_t nCount
) const
977 wxASSERT(nStart
<= length());
978 size_type strLen
= length() - nStart
;
979 nLen
= strLen
< nLen
? strLen
: nLen
;
981 nCount
= wxStrlen(sz
);
983 return ::wxDoCmp(data() + nStart
, nLen
, sz
, nCount
);
988 #endif // !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
990 // ===========================================================================
991 // wxString class core
992 // ===========================================================================
994 // ---------------------------------------------------------------------------
995 // construction and conversion
996 // ---------------------------------------------------------------------------
1000 // from multibyte string
1001 wxString::wxString(const char *psz
, const wxMBConv
& conv
, size_t nLength
)
1004 if ( psz
&& nLength
!= 0 )
1006 if ( nLength
== npos
)
1012 wxWCharBuffer wbuf
= conv
.cMB2WC(psz
, nLength
, &nLenWide
);
1015 assign(wbuf
, nLenWide
);
1019 //Convert wxString in Unicode mode to a multi-byte string
1020 const wxCharBuffer
wxString::mb_str(const wxMBConv
& conv
) const
1022 return conv
.cWC2MB(c_str(), length() + 1 /* size, not length */, NULL
);
1030 wxString::wxString(const wchar_t *pwz
, const wxMBConv
& conv
, size_t nLength
)
1033 if ( pwz
&& nLength
!= 0 )
1035 if ( nLength
== npos
)
1041 wxCharBuffer buf
= conv
.cWC2MB(pwz
, nLength
, &nLenMB
);
1044 assign(buf
, nLenMB
);
1048 //Converts this string to a wide character string if unicode
1049 //mode is not enabled and wxUSE_WCHAR_T is enabled
1050 const wxWCharBuffer
wxString::wc_str(const wxMBConv
& conv
) const
1052 return conv
.cMB2WC(c_str(), length() + 1 /* size, not length */, NULL
);
1055 #endif // wxUSE_WCHAR_T
1057 #endif // Unicode/ANSI
1059 // shrink to minimal size (releasing extra memory)
1060 bool wxString::Shrink()
1062 wxString
tmp(begin(), end());
1064 return tmp
.length() == length();
1068 // get the pointer to writable buffer of (at least) nLen bytes
1069 wxChar
*wxString::DoGetWriteBuf(size_t nLen
)
1071 if ( !AllocBeforeWrite(nLen
) ) {
1072 // allocation failure handled by caller
1076 wxASSERT( GetStringData()->nRefs
== 1 );
1077 GetStringData()->Validate(false);
1082 // put string back in a reasonable state after GetWriteBuf
1083 void wxString::DoUngetWriteBuf()
1085 DoUngetWriteBuf(wxStrlen(m_pchData
));
1088 void wxString::DoUngetWriteBuf(size_t nLen
)
1090 wxStringData
* const pData
= GetStringData();
1092 wxASSERT_MSG( nLen
< pData
->nAllocLength
, _T("buffer overrun") );
1094 // the strings we store are always NUL-terminated
1095 pData
->data()[nLen
] = _T('\0');
1096 pData
->nDataLength
= nLen
;
1097 pData
->Validate(true);
1100 // deprecated compatibility code:
1101 #if WXWIN_COMPATIBILITY_2_8
1102 wxChar
*wxString::GetWriteBuf(size_t nLen
)
1104 return DoGetWriteBuf(nLen
);
1107 void wxString::UngetWriteBuf()
1112 void wxString::UngetWriteBuf(size_t nLen
)
1114 DoUngetWriteBuf(nLen
);
1116 #endif // WXWIN_COMPATIBILITY_2_8
1118 #endif // !wxUSE_STL
1121 // ---------------------------------------------------------------------------
1123 // ---------------------------------------------------------------------------
1125 // all functions are inline in string.h
1127 // ---------------------------------------------------------------------------
1128 // assignment operators
1129 // ---------------------------------------------------------------------------
1133 // same as 'signed char' variant
1134 wxString
& wxString::operator=(const unsigned char* psz
)
1136 *this = (const char *)psz
;
1141 wxString
& wxString::operator=(const wchar_t *pwz
)
1152 * concatenation functions come in 5 flavours:
1154 * char + string and string + char
1155 * C str + string and string + C str
1158 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
1161 wxASSERT( str1
.GetStringData()->IsValid() );
1162 wxASSERT( str2
.GetStringData()->IsValid() );
1171 wxString
operator+(const wxString
& str
, wxUniChar ch
)
1174 wxASSERT( str
.GetStringData()->IsValid() );
1183 wxString
operator+(wxUniChar ch
, const wxString
& str
)
1186 wxASSERT( str
.GetStringData()->IsValid() );
1195 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
1198 wxASSERT( str
.GetStringData()->IsValid() );
1202 if ( !s
.Alloc(wxStrlen(psz
) + str
.length()) ) {
1203 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1211 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
1214 wxASSERT( str
.GetStringData()->IsValid() );
1218 if ( !s
.Alloc(wxStrlen(psz
) + str
.length()) ) {
1219 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1227 // ===========================================================================
1228 // other common string functions
1229 // ===========================================================================
1231 int wxString::Cmp(const wxString
& s
) const
1236 int wxString::Cmp(const wxChar
* psz
) const
1238 return compare(psz
);
1241 static inline int wxDoCmpNoCase(const wxChar
* s1
, size_t l1
,
1242 const wxChar
* s2
, size_t l2
)
1248 for(i
= 0; i
< l1
; ++i
)
1250 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1253 return i
== l1
? 0 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1257 for(i
= 0; i
< l1
; ++i
)
1259 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1262 return i
== l1
? -1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1266 for(i
= 0; i
< l2
; ++i
)
1268 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1271 return i
== l2
? 1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1275 int wxString::CmpNoCase(const wxString
& s
) const
1277 return wxDoCmpNoCase(data(), length(), s
.data(), s
.length());
1280 int wxString::CmpNoCase(const wxChar
* psz
) const
1282 int nLen
= wxStrlen(psz
);
1284 return wxDoCmpNoCase(data(), length(), psz
, nLen
);
1291 #ifndef __SCHAR_MAX__
1292 #define __SCHAR_MAX__ 127
1296 wxString
wxString::FromAscii(const char *ascii
)
1299 return wxEmptyString
;
1301 size_t len
= strlen( ascii
);
1306 wxStringBuffer
buf(res
, len
);
1308 wchar_t *dest
= buf
;
1312 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
1320 wxString
wxString::FromAscii(const char ascii
)
1322 // What do we do with '\0' ?
1325 res
+= (wchar_t)(unsigned char) ascii
;
1330 const wxCharBuffer
wxString::ToAscii() const
1332 // this will allocate enough space for the terminating NUL too
1333 wxCharBuffer
buffer(length());
1336 char *dest
= buffer
.data();
1338 const wchar_t *pwc
= c_str();
1341 *dest
++ = (char)(*pwc
> SCHAR_MAX
? wxT('_') : *pwc
);
1343 // the output string can't have embedded NULs anyhow, so we can safely
1344 // stop at first of them even if we do have any
1354 // extract string of length nCount starting at nFirst
1355 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
1357 size_t nLen
= length();
1359 // default value of nCount is npos and means "till the end"
1360 if ( nCount
== npos
)
1362 nCount
= nLen
- nFirst
;
1365 // out-of-bounds requests return sensible things
1366 if ( nFirst
+ nCount
> nLen
)
1368 nCount
= nLen
- nFirst
;
1371 if ( nFirst
> nLen
)
1373 // AllocCopy() will return empty string
1374 return wxEmptyString
;
1377 wxString
dest(*this, nFirst
, nCount
);
1378 if ( dest
.length() != nCount
)
1380 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
1386 // check that the string starts with prefix and return the rest of the string
1387 // in the provided pointer if it is not NULL, otherwise return false
1388 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
1390 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
1392 // first check if the beginning of the string matches the prefix: note
1393 // that we don't have to check that we don't run out of this string as
1394 // when we reach the terminating NUL, either prefix string ends too (and
1395 // then it's ok) or we break out of the loop because there is no match
1396 const wxChar
*p
= c_str();
1399 if ( *prefix
++ != *p
++ )
1408 // put the rest of the string into provided pointer
1416 // check that the string ends with suffix and return the rest of it in the
1417 // provided pointer if it is not NULL, otherwise return false
1418 bool wxString::EndsWith(const wxChar
*suffix
, wxString
*rest
) const
1420 wxASSERT_MSG( suffix
, _T("invalid parameter in wxString::EndssWith") );
1422 int start
= length() - wxStrlen(suffix
);
1423 if ( start
< 0 || wxStrcmp(wx_str() + start
, suffix
) != 0 )
1428 // put the rest of the string into provided pointer
1429 rest
->assign(*this, 0, start
);
1436 // extract nCount last (rightmost) characters
1437 wxString
wxString::Right(size_t nCount
) const
1439 if ( nCount
> length() )
1442 wxString
dest(*this, length() - nCount
, nCount
);
1443 if ( dest
.length() != nCount
) {
1444 wxFAIL_MSG( _T("out of memory in wxString::Right") );
1449 // get all characters after the last occurence of ch
1450 // (returns the whole string if ch not found)
1451 wxString
wxString::AfterLast(wxUniChar ch
) const
1454 int iPos
= Find(ch
, true);
1455 if ( iPos
== wxNOT_FOUND
)
1458 str
= wx_str() + iPos
+ 1;
1463 // extract nCount first (leftmost) characters
1464 wxString
wxString::Left(size_t nCount
) const
1466 if ( nCount
> length() )
1469 wxString
dest(*this, 0, nCount
);
1470 if ( dest
.length() != nCount
) {
1471 wxFAIL_MSG( _T("out of memory in wxString::Left") );
1476 // get all characters before the first occurence of ch
1477 // (returns the whole string if ch not found)
1478 wxString
wxString::BeforeFirst(wxUniChar ch
) const
1480 int iPos
= Find(ch
);
1481 if ( iPos
== wxNOT_FOUND
) iPos
= length();
1482 return wxString(*this, 0, iPos
);
1485 /// get all characters before the last occurence of ch
1486 /// (returns empty string if ch not found)
1487 wxString
wxString::BeforeLast(wxUniChar ch
) const
1490 int iPos
= Find(ch
, true);
1491 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
1492 str
= wxString(c_str(), iPos
);
1497 /// get all characters after the first occurence of ch
1498 /// (returns empty string if ch not found)
1499 wxString
wxString::AfterFirst(wxUniChar ch
) const
1502 int iPos
= Find(ch
);
1503 if ( iPos
!= wxNOT_FOUND
)
1504 str
= wx_str() + iPos
+ 1;
1509 // replace first (or all) occurences of some substring with another one
1510 size_t wxString::Replace(const wxChar
*szOld
,
1511 const wxChar
*szNew
, bool bReplaceAll
)
1513 // if we tried to replace an empty string we'd enter an infinite loop below
1514 wxCHECK_MSG( szOld
&& *szOld
&& szNew
, 0,
1515 _T("wxString::Replace(): invalid parameter") );
1517 size_t uiCount
= 0; // count of replacements made
1519 size_t uiOldLen
= wxStrlen(szOld
);
1520 size_t uiNewLen
= wxStrlen(szNew
);
1524 while ( this->c_str()[dwPos
] != wxT('\0') )
1526 //DO NOT USE STRSTR HERE
1527 //this string can contain embedded null characters,
1528 //so strstr will function incorrectly
1529 dwPos
= find(szOld
, dwPos
);
1530 if ( dwPos
== npos
)
1531 break; // exit the loop
1534 //replace this occurance of the old string with the new one
1535 replace(dwPos
, uiOldLen
, szNew
, uiNewLen
);
1537 //move up pos past the string that was replaced
1540 //increase replace count
1545 break; // exit the loop
1552 bool wxString::IsAscii() const
1554 const wxChar
*s
= (const wxChar
*) *this;
1556 if(!isascii(*s
)) return(false);
1562 bool wxString::IsWord() const
1564 const wxChar
*s
= (const wxChar
*) *this;
1566 if(!wxIsalpha(*s
)) return(false);
1572 bool wxString::IsNumber() const
1574 const wxChar
*s
= (const wxChar
*) *this;
1576 if ((s
[0] == wxT('-')) || (s
[0] == wxT('+'))) s
++;
1578 if(!wxIsdigit(*s
)) return(false);
1584 wxString
wxString::Strip(stripType w
) const
1587 if ( w
& leading
) s
.Trim(false);
1588 if ( w
& trailing
) s
.Trim(true);
1592 // ---------------------------------------------------------------------------
1594 // ---------------------------------------------------------------------------
1596 wxString
& wxString::MakeUpper()
1598 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1599 *it
= (wxChar
)wxToupper(*it
);
1604 wxString
& wxString::MakeLower()
1606 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1607 *it
= (wxChar
)wxTolower(*it
);
1612 // ---------------------------------------------------------------------------
1613 // trimming and padding
1614 // ---------------------------------------------------------------------------
1616 // some compilers (VC++ 6.0 not to name them) return true for a call to
1617 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1618 // live with this by checking that the character is a 7 bit one - even if this
1619 // may fail to detect some spaces (I don't know if Unicode doesn't have
1620 // space-like symbols somewhere except in the first 128 chars), it is arguably
1621 // still better than trimming away accented letters
1622 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1624 // trims spaces (in the sense of isspace) from left or right side
1625 wxString
& wxString::Trim(bool bFromRight
)
1627 // first check if we're going to modify the string at all
1630 (bFromRight
&& wxSafeIsspace(GetChar(length() - 1))) ||
1631 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1637 // find last non-space character
1638 reverse_iterator psz
= rbegin();
1639 while ( (psz
!= rend()) && wxSafeIsspace(*psz
) )
1642 // truncate at trailing space start
1643 erase(psz
.base(), end());
1647 // find first non-space character
1648 iterator psz
= begin();
1649 while ( (psz
!= end()) && wxSafeIsspace(*psz
) )
1652 // fix up data and length
1653 erase(begin(), psz
);
1660 // adds nCount characters chPad to the string from either side
1661 wxString
& wxString::Pad(size_t nCount
, wxUniChar chPad
, bool bFromRight
)
1663 wxString
s(chPad
, nCount
);
1676 // truncate the string
1677 wxString
& wxString::Truncate(size_t uiLen
)
1679 if ( uiLen
< length() )
1681 erase(begin() + uiLen
, end());
1683 //else: nothing to do, string is already short enough
1688 // ---------------------------------------------------------------------------
1689 // finding (return wxNOT_FOUND if not found and index otherwise)
1690 // ---------------------------------------------------------------------------
1693 int wxString::Find(wxUniChar ch
, bool bFromEnd
) const
1695 size_type idx
= bFromEnd
? find_last_of(ch
) : find_first_of(ch
);
1697 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1700 // find a sub-string (like strstr)
1701 int wxString::Find(const wxChar
*pszSub
) const
1703 size_type idx
= find(pszSub
);
1705 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1708 // ----------------------------------------------------------------------------
1709 // conversion to numbers
1710 // ----------------------------------------------------------------------------
1712 // the implementation of all the functions below is exactly the same so factor
1715 template <typename T
, typename F
>
1716 bool wxStringToIntType(const wxChar
*start
,
1721 wxCHECK_MSG( val
, false, _T("NULL output pointer") );
1722 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1729 *val
= (*func
)(start
, &end
, base
);
1731 // return true only if scan was stopped by the terminating NUL and if the
1732 // string was not empty to start with and no under/overflow occurred
1733 return !*end
&& (end
!= start
)
1735 && (errno
!= ERANGE
)
1740 bool wxString::ToLong(long *val
, int base
) const
1742 return wxStringToIntType((const wxChar
*)c_str(), val
, base
, wxStrtol
);
1745 bool wxString::ToULong(unsigned long *val
, int base
) const
1747 return wxStringToIntType((const wxChar
*)c_str(), val
, base
, wxStrtoul
);
1750 bool wxString::ToLongLong(wxLongLong_t
*val
, int base
) const
1752 #ifdef wxHAS_STRTOLL
1753 return wxStringToIntType((const wxChar
*)c_str(), val
, base
, wxStrtoll
);
1755 // TODO: implement this ourselves
1759 #endif // wxHAS_STRTOLL
1762 bool wxString::ToULongLong(wxULongLong_t
*val
, int base
) const
1764 #ifdef wxHAS_STRTOLL
1765 return wxStringToIntType((const wxChar
*)c_str(), val
, base
, wxStrtoull
);
1767 // TODO: implement this ourselves
1774 bool wxString::ToDouble(double *val
) const
1776 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToDouble") );
1782 const wxChar
*start
= c_str();
1784 *val
= wxStrtod(start
, &end
);
1786 // return true only if scan was stopped by the terminating NUL and if the
1787 // string was not empty to start with and no under/overflow occurred
1788 return !*end
&& (end
!= start
)
1790 && (errno
!= ERANGE
)
1795 // ---------------------------------------------------------------------------
1797 // ---------------------------------------------------------------------------
1800 #ifdef wxNEEDS_WXSTRING_PRINTF_MIXIN
1801 wxString
wxStringPrintfMixinBase::DoFormat(const wxChar
*format
, ...)
1803 wxString
wxString::DoFormat(const wxChar
*format
, ...)
1807 va_start(argptr
, format
);
1810 s
.PrintfV(format
, argptr
);
1818 wxString
wxString::FormatV(const wxString
& format
, va_list argptr
)
1821 s
.PrintfV(format
, argptr
);
1825 #ifdef wxNEEDS_WXSTRING_PRINTF_MIXIN
1826 int wxStringPrintfMixinBase::DoPrintf(const wxChar
*format
, ...)
1828 int wxString::DoPrintf(const wxChar
*format
, ...)
1832 va_start(argptr
, format
);
1834 #ifdef wxNEEDS_WXSTRING_PRINTF_MIXIN
1835 // get a pointer to the wxString instance; we have to use dynamic_cast<>
1836 // because it's the only cast that works safely for downcasting when
1837 // multiple inheritance is used:
1838 wxString
*str
= static_cast<wxString
*>(this);
1840 wxString
*str
= this;
1843 int iLen
= str
->PrintfV(format
, argptr
);
1850 int wxString::PrintfV(const wxString
& format
, va_list argptr
)
1856 wxStringBuffer
tmp(*this, size
+ 1);
1865 // wxVsnprintf() may modify the original arg pointer, so pass it
1868 wxVaCopy(argptrcopy
, argptr
);
1869 int len
= wxVsnprintf(buf
, size
, format
, argptrcopy
);
1872 // some implementations of vsnprintf() don't NUL terminate
1873 // the string if there is not enough space for it so
1874 // always do it manually
1875 buf
[size
] = _T('\0');
1877 // vsnprintf() may return either -1 (traditional Unix behaviour) or the
1878 // total number of characters which would have been written if the
1879 // buffer were large enough (newer standards such as Unix98)
1882 #if wxUSE_WXVSNPRINTF
1883 // we know that our own implementation of wxVsnprintf() returns -1
1884 // only for a format error - thus there's something wrong with
1885 // the user's format string
1887 #else // assume that system version only returns error if not enough space
1888 // still not enough, as we don't know how much we need, double the
1889 // current size of the buffer
1891 #endif // wxUSE_WXVSNPRINTF/!wxUSE_WXVSNPRINTF
1893 else if ( len
>= size
)
1895 #if wxUSE_WXVSNPRINTF
1896 // we know that our own implementation of wxVsnprintf() returns
1897 // size+1 when there's not enough space but that's not the size
1898 // of the required buffer!
1899 size
*= 2; // so we just double the current size of the buffer
1901 // some vsnprintf() implementations NUL-terminate the buffer and
1902 // some don't in len == size case, to be safe always add 1
1906 else // ok, there was enough space
1912 // we could have overshot
1918 // ----------------------------------------------------------------------------
1919 // misc other operations
1920 // ----------------------------------------------------------------------------
1922 // returns true if the string matches the pattern which may contain '*' and
1923 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1925 bool wxString::Matches(const wxChar
*pszMask
) const
1927 // I disable this code as it doesn't seem to be faster (in fact, it seems
1928 // to be much slower) than the old, hand-written code below and using it
1929 // here requires always linking with libregex even if the user code doesn't
1931 #if 0 // wxUSE_REGEX
1932 // first translate the shell-like mask into a regex
1934 pattern
.reserve(wxStrlen(pszMask
));
1946 pattern
+= _T(".*");
1957 // these characters are special in a RE, quote them
1958 // (however note that we don't quote '[' and ']' to allow
1959 // using them for Unix shell like matching)
1960 pattern
+= _T('\\');
1964 pattern
+= *pszMask
;
1972 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1973 #else // !wxUSE_REGEX
1974 // TODO: this is, of course, awfully inefficient...
1976 // the char currently being checked
1977 const wxChar
*pszTxt
= c_str();
1979 // the last location where '*' matched
1980 const wxChar
*pszLastStarInText
= NULL
;
1981 const wxChar
*pszLastStarInMask
= NULL
;
1984 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1985 switch ( *pszMask
) {
1987 if ( *pszTxt
== wxT('\0') )
1990 // pszTxt and pszMask will be incremented in the loop statement
1996 // remember where we started to be able to backtrack later
1997 pszLastStarInText
= pszTxt
;
1998 pszLastStarInMask
= pszMask
;
2000 // ignore special chars immediately following this one
2001 // (should this be an error?)
2002 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
2005 // if there is nothing more, match
2006 if ( *pszMask
== wxT('\0') )
2009 // are there any other metacharacters in the mask?
2011 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
2013 if ( pEndMask
!= NULL
) {
2014 // we have to match the string between two metachars
2015 uiLenMask
= pEndMask
- pszMask
;
2018 // we have to match the remainder of the string
2019 uiLenMask
= wxStrlen(pszMask
);
2022 wxString
strToMatch(pszMask
, uiLenMask
);
2023 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
2024 if ( pMatch
== NULL
)
2027 // -1 to compensate "++" in the loop
2028 pszTxt
= pMatch
+ uiLenMask
- 1;
2029 pszMask
+= uiLenMask
- 1;
2034 if ( *pszMask
!= *pszTxt
)
2040 // match only if nothing left
2041 if ( *pszTxt
== wxT('\0') )
2044 // if we failed to match, backtrack if we can
2045 if ( pszLastStarInText
) {
2046 pszTxt
= pszLastStarInText
+ 1;
2047 pszMask
= pszLastStarInMask
;
2049 pszLastStarInText
= NULL
;
2051 // don't bother resetting pszLastStarInMask, it's unnecessary
2057 #endif // wxUSE_REGEX/!wxUSE_REGEX
2060 // Count the number of chars
2061 int wxString::Freq(wxUniChar ch
) const
2065 for (int i
= 0; i
< len
; i
++)
2067 if (GetChar(i
) == ch
)
2073 // convert to upper case, return the copy of the string
2074 wxString
wxString::Upper() const
2075 { wxString
s(*this); return s
.MakeUpper(); }
2077 // convert to lower case, return the copy of the string
2078 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
2080 // ============================================================================
2082 // ============================================================================
2084 #include "wx/arrstr.h"
2086 wxArrayString::wxArrayString(size_t sz
, const wxChar
** a
)
2091 for (size_t i
=0; i
< sz
; i
++)
2095 wxArrayString::wxArrayString(size_t sz
, const wxString
* a
)
2100 for (size_t i
=0; i
< sz
; i
++)
2106 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
2107 #define ARRAY_MAXSIZE_INCREMENT 4096
2109 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
2110 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
2114 void wxArrayString::Init(bool autoSort
)
2119 m_autoSort
= autoSort
;
2123 wxArrayString::wxArrayString(const wxArrayString
& src
)
2125 Init(src
.m_autoSort
);
2130 // assignment operator
2131 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
2138 m_autoSort
= src
.m_autoSort
;
2143 void wxArrayString::Copy(const wxArrayString
& src
)
2145 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
2146 Alloc(src
.m_nCount
);
2148 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
2153 void wxArrayString::Grow(size_t nIncrement
)
2155 // only do it if no more place
2156 if ( (m_nSize
- m_nCount
) < nIncrement
) {
2157 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2158 // be never resized!
2159 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2160 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2163 if ( m_nSize
== 0 ) {
2164 // was empty, alloc some memory
2165 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
2166 if (m_nSize
< nIncrement
)
2167 m_nSize
= nIncrement
;
2168 m_pItems
= new wxString
[m_nSize
];
2171 // otherwise when it's called for the first time, nIncrement would be 0
2172 // and the array would never be expanded
2173 // add 50% but not too much
2174 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
2175 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
2176 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
2177 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
2178 if ( nIncrement
< ndefIncrement
)
2179 nIncrement
= ndefIncrement
;
2180 m_nSize
+= nIncrement
;
2181 wxString
*pNew
= new wxString
[m_nSize
];
2183 // copy data to new location
2184 for ( size_t j
= 0; j
< m_nCount
; j
++ )
2185 pNew
[j
] = m_pItems
[j
];
2187 // delete old memory (but do not release the strings!)
2188 wxDELETEA(m_pItems
);
2195 // deletes all the strings from the list
2196 void wxArrayString::Empty()
2201 // as Empty, but also frees memory
2202 void wxArrayString::Clear()
2207 wxDELETEA(m_pItems
);
2211 wxArrayString::~wxArrayString()
2213 wxDELETEA(m_pItems
);
2216 void wxArrayString::reserve(size_t nSize
)
2221 // pre-allocates memory (frees the previous data!)
2222 void wxArrayString::Alloc(size_t nSize
)
2224 // only if old buffer was not big enough
2225 if ( nSize
> m_nSize
) {
2226 wxString
*pNew
= new wxString
[nSize
];
2230 for ( size_t j
= 0; j
< m_nCount
; j
++ )
2231 pNew
[j
] = m_pItems
[j
];
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 wxString
*pNew
= new wxString
[m_nCount
];
2247 // copy data to new location
2248 for ( size_t j
= 0; j
< m_nCount
; j
++ )
2249 pNew
[j
] = m_pItems
[j
];
2255 // searches the array for an item (forward or backwards)
2256 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2259 // use binary search in the sorted array
2260 wxASSERT_MSG( bCase
&& !bFromEnd
,
2261 wxT("search parameters ignored for auto sorted array") );
2270 res
= wxStrcmp(sz
, m_pItems
[i
]);
2282 // use linear search in unsorted array
2284 if ( m_nCount
> 0 ) {
2285 size_t ui
= m_nCount
;
2287 if ( m_pItems
[--ui
].IsSameAs(sz
, bCase
) )
2294 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2295 if( m_pItems
[ui
].IsSameAs(sz
, bCase
) )
2304 // add item at the end
2305 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
2308 // insert the string at the correct position to keep the array sorted
2316 res
= str
.Cmp(m_pItems
[i
]);
2327 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2329 Insert(str
, lo
, nInsert
);
2336 for (size_t i
= 0; i
< nInsert
; i
++)
2339 m_pItems
[m_nCount
+ i
] = str
;
2341 size_t ret
= m_nCount
;
2342 m_nCount
+= nInsert
;
2347 // add item at the given position
2348 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2350 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2351 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2352 wxT("array size overflow in wxArrayString::Insert") );
2356 for (int j
= m_nCount
- nIndex
- 1; j
>= 0; j
--)
2357 m_pItems
[nIndex
+ nInsert
+ j
] = m_pItems
[nIndex
+ j
];
2359 for (size_t i
= 0; i
< nInsert
; i
++)
2361 m_pItems
[nIndex
+ i
] = str
;
2363 m_nCount
+= nInsert
;
2366 // range insert (STL 23.2.4.3)
2368 wxArrayString::insert(iterator it
, const_iterator first
, const_iterator last
)
2370 const int idx
= it
- begin();
2375 // reset "it" since it can change inside Grow()
2378 while ( first
!= last
)
2380 it
= insert(it
, *first
);
2382 // insert returns an iterator to the last element inserted but we need
2383 // insert the next after this one, that is before the next one
2391 void wxArrayString::SetCount(size_t count
)
2396 while ( m_nCount
< count
)
2397 m_pItems
[m_nCount
++] = s
;
2400 // removes item from array (by index)
2401 void wxArrayString::RemoveAt(size_t nIndex
, size_t nRemove
)
2403 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2404 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2405 wxT("removing too many elements in wxArrayString::Remove") );
2407 for ( size_t j
= 0; j
< m_nCount
- nIndex
-nRemove
; j
++)
2408 m_pItems
[nIndex
+ j
] = m_pItems
[nIndex
+ nRemove
+ j
];
2410 m_nCount
-= nRemove
;
2413 // removes item from array (by value)
2414 void wxArrayString::Remove(const wxChar
*sz
)
2416 int iIndex
= Index(sz
);
2418 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2419 wxT("removing inexistent element in wxArrayString::Remove") );
2424 void wxArrayString::assign(const_iterator first
, const_iterator last
)
2426 reserve(last
- first
);
2427 for(; first
!= last
; ++first
)
2431 // ----------------------------------------------------------------------------
2433 // ----------------------------------------------------------------------------
2435 // we can only sort one array at a time with the quick-sort based
2438 // need a critical section to protect access to gs_compareFunction and
2439 // gs_sortAscending variables
2440 static wxCriticalSection gs_critsectStringSort
;
2441 #endif // wxUSE_THREADS
2443 // function to use for string comparaison
2444 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2446 // if we don't use the compare function, this flag tells us if we sort the
2447 // array in ascending or descending order
2448 static bool gs_sortAscending
= true;
2450 // function which is called by quick sort
2451 extern "C" int wxC_CALLING_CONV
// LINKAGEMODE
2452 wxStringCompareFunction(const void *first
, const void *second
)
2454 wxString
*strFirst
= (wxString
*)first
;
2455 wxString
*strSecond
= (wxString
*)second
;
2457 if ( gs_compareFunction
) {
2458 return gs_compareFunction(*strFirst
, *strSecond
);
2461 // maybe we should use wxStrcoll
2462 int result
= strFirst
->Cmp(*strSecond
);
2464 return gs_sortAscending
? result
: -result
;
2468 // sort array elements using passed comparaison function
2469 void wxArrayString::Sort(CompareFunction compareFunction
)
2471 wxCRIT_SECT_LOCKER(lockCmpFunc
, gs_critsectStringSort
);
2473 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2474 gs_compareFunction
= compareFunction
;
2478 // reset it to NULL so that Sort(bool) will work the next time
2479 gs_compareFunction
= NULL
;
2484 typedef int (wxC_CALLING_CONV
* wxStringCompareFn
)(const void *first
,
2485 const void *second
);
2488 void wxArrayString::Sort(CompareFunction2 compareFunction
)
2490 qsort(m_pItems
, m_nCount
, sizeof(wxString
), (wxStringCompareFn
)compareFunction
);
2493 void wxArrayString::Sort(bool reverseOrder
)
2495 Sort(reverseOrder
? wxStringSortDescending
: wxStringSortAscending
);
2498 void wxArrayString::DoSort()
2500 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2502 qsort(m_pItems
, m_nCount
, sizeof(wxString
), wxStringCompareFunction
);
2505 bool wxArrayString::operator==(const wxArrayString
& a
) const
2507 if ( m_nCount
!= a
.m_nCount
)
2510 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2512 if ( Item(n
) != a
[n
] )
2519 #endif // !wxUSE_STL
2521 int wxCMPFUNC_CONV
wxStringSortAscending(wxString
* s1
, wxString
* s2
)
2523 return s1
->Cmp(*s2
);
2526 int wxCMPFUNC_CONV
wxStringSortDescending(wxString
* s1
, wxString
* s2
)
2528 return -s1
->Cmp(*s2
);