1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxString class
4 // Author: Vadim Zeitlin, Ryan Norton
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // (c) 2004 Ryan Norton <wxprojects@comcast.net>
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
13 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
14 #pragma implementation "string.h"
19 * 1) all empty strings use g_strEmpty, nRefs = -1 (set in Init())
20 * 2) AllocBuffer() sets nRefs to 1, Lock() increments it by one
21 * 3) Unlock() decrements nRefs and frees memory if it goes to 0
24 // ===========================================================================
25 // headers, declarations, constants
26 // ===========================================================================
28 // For compilers that support precompilation, includes "wx.h".
29 #include "wx/wxprec.h"
37 #include "wx/string.h"
39 #include "wx/thread.h"
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 // ---------------------------------------------------------------------------
59 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
60 // must define this static for VA or else you get multiply defined symbols
62 const unsigned int wxSTRING_MAXLEN
= UINT_MAX
- 100;
66 const size_t wxStringBase::npos
= wxSTRING_MAXLEN
;
69 // ----------------------------------------------------------------------------
71 // ----------------------------------------------------------------------------
75 extern const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= _T("");
79 // for an empty string, GetStringData() will return this address: this
80 // structure has the same layout as wxStringData and it's data() method will
81 // return the empty string (dummy pointer)
86 } g_strEmpty
= { {-1, 0, 0}, wxT('\0') };
88 // empty C style string: points to 'string data' byte of g_strEmpty
89 extern const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= &g_strEmpty
.dummy
;
93 // ----------------------------------------------------------------------------
95 // ----------------------------------------------------------------------------
97 #if wxUSE_STD_IOSTREAM
99 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
102 // ATTN: you can _not_ use both of these in the same program!
106 wxSTD istream
& operator>>(wxSTD istream
& is
, wxString
& WXUNUSED(str
))
111 streambuf
*sb
= is
.rdbuf();
114 int ch
= sb
->sbumpc ();
116 is
.setstate(ios::eofbit
);
119 else if ( isspace(ch
) ) {
131 if ( str
.length() == 0 )
132 is
.setstate(ios::failbit
);
137 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
143 #endif // wxUSE_STD_IOSTREAM
145 // ----------------------------------------------------------------------------
147 // ----------------------------------------------------------------------------
149 // this small class is used to gather statistics for performance tuning
150 //#define WXSTRING_STATISTICS
151 #ifdef WXSTRING_STATISTICS
155 Averager(const wxChar
*sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
157 { wxPrintf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
159 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
162 size_t m_nCount
, m_nTotal
;
164 } g_averageLength("allocation size"),
165 g_averageSummandLength("summand length"),
166 g_averageConcatHit("hit probability in concat"),
167 g_averageInitialLength("initial string length");
169 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
171 #define STATISTICS_ADD(av, val)
172 #endif // WXSTRING_STATISTICS
176 // ===========================================================================
177 // wxStringData class deallocation
178 // ===========================================================================
180 #if defined(__VISUALC__) && defined(_MT) && !defined(_DLL)
181 # pragma message (__FILE__ ": building with Multithreaded non DLL runtime has a performance impact on wxString!")
182 void wxStringData::Free()
188 // ===========================================================================
190 // ===========================================================================
192 // takes nLength elements of psz starting at nPos
193 void wxStringBase::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
197 // if the length is not given, assume the string to be NUL terminated
198 if ( nLength
== npos
) {
199 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
201 nLength
= wxStrlen(psz
+ nPos
);
204 STATISTICS_ADD(InitialLength
, nLength
);
207 // trailing '\0' is written in AllocBuffer()
208 if ( !AllocBuffer(nLength
) ) {
209 wxFAIL_MSG( _T("out of memory in wxStringBase::InitWith") );
212 wxMemcpy(m_pchData
, psz
+ nPos
, nLength
);
216 // poor man's iterators are "void *" pointers
217 wxStringBase::wxStringBase(const void *pStart
, const void *pEnd
)
219 InitWith((const wxChar
*)pStart
, 0,
220 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
223 wxStringBase::wxStringBase(size_type n
, wxChar ch
)
229 // ---------------------------------------------------------------------------
231 // ---------------------------------------------------------------------------
233 // allocates memory needed to store a C string of length nLen
234 bool wxStringBase::AllocBuffer(size_t nLen
)
236 // allocating 0 sized buffer doesn't make sense, all empty strings should
238 wxASSERT( nLen
> 0 );
240 // make sure that we don't overflow
241 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
242 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
244 STATISTICS_ADD(Length
, nLen
);
247 // 1) one extra character for '\0' termination
248 // 2) sizeof(wxStringData) for housekeeping info
249 wxStringData
* pData
= (wxStringData
*)
250 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
252 if ( pData
== NULL
) {
253 // allocation failures are handled by the caller
258 pData
->nDataLength
= nLen
;
259 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
260 m_pchData
= pData
->data(); // data starts after wxStringData
261 m_pchData
[nLen
] = wxT('\0');
265 // must be called before changing this string
266 bool wxStringBase::CopyBeforeWrite()
268 wxStringData
* pData
= GetStringData();
270 if ( pData
->IsShared() ) {
271 pData
->Unlock(); // memory not freed because shared
272 size_t nLen
= pData
->nDataLength
;
273 if ( !AllocBuffer(nLen
) ) {
274 // allocation failures are handled by the caller
277 wxMemcpy(m_pchData
, pData
->data(), nLen
);
280 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
285 // must be called before replacing contents of this string
286 bool wxStringBase::AllocBeforeWrite(size_t nLen
)
288 wxASSERT( nLen
!= 0 ); // doesn't make any sense
290 // must not share string and must have enough space
291 wxStringData
* pData
= GetStringData();
292 if ( pData
->IsShared() || pData
->IsEmpty() ) {
293 // can't work with old buffer, get new one
295 if ( !AllocBuffer(nLen
) ) {
296 // allocation failures are handled by the caller
301 if ( nLen
> pData
->nAllocLength
) {
302 // realloc the buffer instead of calling malloc() again, this is more
304 STATISTICS_ADD(Length
, nLen
);
308 pData
= (wxStringData
*)
309 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
311 if ( pData
== NULL
) {
312 // allocation failures are handled by the caller
313 // keep previous data since reallocation failed
317 pData
->nAllocLength
= nLen
;
318 m_pchData
= pData
->data();
321 // now we have enough space, just update the string length
322 pData
->nDataLength
= nLen
;
325 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
330 wxStringBase
& wxStringBase::append(size_t n
, wxChar ch
)
332 size_type len
= length();
334 if ( !CopyBeforeWrite() || !Alloc(len
+ n
) ) {
335 wxFAIL_MSG( _T("out of memory in wxStringBase::append") );
337 GetStringData()->nDataLength
= len
+ n
;
338 m_pchData
[len
+ n
] = '\0';
339 for ( size_t i
= 0; i
< n
; ++i
)
340 m_pchData
[len
+ i
] = ch
;
344 void wxStringBase::resize(size_t nSize
, wxChar ch
)
346 size_t len
= length();
350 erase(begin() + nSize
, end());
352 else if ( nSize
> len
)
354 append(nSize
- len
, ch
);
356 //else: we have exactly the specified length, nothing to do
359 // allocate enough memory for nLen characters
360 bool wxStringBase::Alloc(size_t nLen
)
362 wxStringData
*pData
= GetStringData();
363 if ( pData
->nAllocLength
<= nLen
) {
364 if ( pData
->IsEmpty() ) {
367 wxStringData
* pData
= (wxStringData
*)
368 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
370 if ( pData
== NULL
) {
371 // allocation failure handled by caller
376 pData
->nDataLength
= 0;
377 pData
->nAllocLength
= nLen
;
378 m_pchData
= pData
->data(); // data starts after wxStringData
379 m_pchData
[0u] = wxT('\0');
381 else if ( pData
->IsShared() ) {
382 pData
->Unlock(); // memory not freed because shared
383 size_t nOldLen
= pData
->nDataLength
;
384 if ( !AllocBuffer(nLen
) ) {
385 // allocation failure handled by caller
388 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
393 pData
= (wxStringData
*)
394 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
396 if ( pData
== NULL
) {
397 // allocation failure handled by caller
398 // keep previous data since reallocation failed
402 // it's not important if the pointer changed or not (the check for this
403 // is not faster than assigning to m_pchData in all cases)
404 pData
->nAllocLength
= nLen
;
405 m_pchData
= pData
->data();
408 //else: we've already got enough
412 wxStringBase::iterator
wxStringBase::begin()
419 wxStringBase::iterator
wxStringBase::end()
423 return m_pchData
+ length();
426 wxStringBase::iterator
wxStringBase::erase(iterator it
)
428 size_type idx
= it
- begin();
430 return begin() + idx
;
433 wxStringBase
& wxStringBase::erase(size_t nStart
, size_t nLen
)
435 wxASSERT(nStart
<= length());
436 size_t strLen
= length() - nStart
;
437 // delete nLen or up to the end of the string characters
438 nLen
= strLen
< nLen
? strLen
: nLen
;
439 wxString
strTmp(c_str(), nStart
);
440 strTmp
.append(c_str() + nStart
+ nLen
, length() - nStart
- nLen
);
446 wxStringBase
& wxStringBase::insert(size_t nPos
, const wxChar
*sz
, size_t n
)
448 wxASSERT( nPos
<= length() );
450 if ( n
== npos
) n
= wxStrlen(sz
);
451 if ( n
== 0 ) return *this;
453 if ( !CopyBeforeWrite() || !Alloc(length() + n
) ) {
454 wxFAIL_MSG( _T("out of memory in wxStringBase::insert") );
457 memmove(m_pchData
+ nPos
+ n
, m_pchData
+ nPos
,
458 (length() - nPos
) * sizeof(wxChar
));
459 memcpy(m_pchData
+ nPos
, sz
, n
* sizeof(wxChar
));
460 GetStringData()->nDataLength
= length() + n
;
461 m_pchData
[length()] = '\0';
466 void wxStringBase::swap(wxStringBase
& str
)
468 wxChar
* tmp
= str
.m_pchData
;
469 str
.m_pchData
= m_pchData
;
473 size_t wxStringBase::find(const wxStringBase
& str
, size_t nStart
) const
475 wxASSERT( str
.GetStringData()->IsValid() );
476 wxASSERT( nStart
<= length() );
479 const wxChar
* p
= (const wxChar
*)wxMemchr(c_str() + nStart
,
486 while(p
- c_str() + str
.length() <= length() &&
487 wxMemcmp(p
, str
.c_str(), str
.length()) )
490 p
= (const wxChar
*)wxMemchr(++p
,
492 length() - (p
- c_str()));
498 return (p
- c_str() + str
.length() <= length()) ? p
- c_str() : npos
;
501 size_t wxStringBase::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
503 return find(wxStringBase(sz
, n
), nStart
);
506 size_t wxStringBase::find(wxChar ch
, size_t nStart
) const
508 wxASSERT( nStart
<= length() );
510 const wxChar
*p
= (const wxChar
*)wxMemchr(c_str() + nStart
, ch
, length() - nStart
);
512 return p
== NULL
? npos
: p
- c_str();
515 size_t wxStringBase::rfind(const wxStringBase
& str
, size_t nStart
) const
517 wxASSERT( str
.GetStringData()->IsValid() );
518 wxASSERT( nStart
== npos
|| nStart
<= length() );
520 if ( length() >= str
.length() )
522 // avoids a corner case later
523 if ( length() == 0 && str
.length() == 0 )
526 // "top" is the point where search starts from
527 size_t top
= length() - str
.length();
529 if ( nStart
== npos
)
530 nStart
= length() - 1;
534 const wxChar
*cursor
= c_str() + top
;
537 if ( wxMemcmp(cursor
, str
.c_str(),
540 return cursor
- c_str();
542 } while ( cursor
-- > c_str() );
548 size_t wxStringBase::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
550 return rfind(wxStringBase(sz
, n
), nStart
);
553 size_t wxStringBase::rfind(wxChar ch
, size_t nStart
) const
555 if ( nStart
== npos
)
561 wxASSERT( nStart
<= length() );
564 const wxChar
*actual
;
565 for ( actual
= c_str() + ( nStart
== npos
? length() : nStart
+ 1 );
566 actual
> c_str(); --actual
)
568 if ( *(actual
- 1) == ch
)
569 return (actual
- 1) - c_str();
575 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
) const
577 wxASSERT(nStart
<= length());
579 size_t len
= wxStrlen(sz
);
582 for(i
= nStart
; i
< this->length(); ++i
)
584 if (wxMemchr(sz
, *(c_str() + i
), len
))
588 if(i
== this->length())
594 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
,
597 return find_first_of(wxStringBase(sz
, n
), nStart
);
600 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
) const
602 if ( nStart
== npos
)
604 nStart
= length() - 1;
608 wxASSERT_MSG( nStart
<= length(),
609 _T("invalid index in find_last_of()") );
612 size_t len
= wxStrlen(sz
);
614 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
616 if ( wxMemchr(sz
, *p
, len
) )
623 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
,
626 return find_last_of(wxStringBase(sz
, n
), nStart
);
629 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
631 if ( nStart
== npos
)
637 wxASSERT( nStart
<= length() );
640 size_t len
= wxStrlen(sz
);
643 for(i
= nStart
; i
< this->length(); ++i
)
645 if (!wxMemchr(sz
, *(c_str() + i
), len
))
649 if(i
== this->length())
655 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
,
658 return find_first_not_of(wxStringBase(sz
, n
), nStart
);
661 size_t wxStringBase::find_first_not_of(wxChar ch
, size_t nStart
) const
663 wxASSERT( nStart
<= length() );
665 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
674 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
676 if ( nStart
== npos
)
678 nStart
= length() - 1;
682 wxASSERT( nStart
<= length() );
685 size_t len
= wxStrlen(sz
);
687 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
689 if ( !wxMemchr(sz
, *p
,len
) )
696 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
,
699 return find_last_not_of(wxStringBase(sz
, n
), nStart
);
702 size_t wxStringBase::find_last_not_of(wxChar ch
, size_t nStart
) const
704 if ( nStart
== npos
)
706 nStart
= length() - 1;
710 wxASSERT( nStart
<= length() );
713 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
722 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
725 wxASSERT_MSG( nStart
<= length(),
726 _T("index out of bounds in wxStringBase::replace") );
727 size_t strLen
= length() - nStart
;
728 nLen
= strLen
< nLen
? strLen
: nLen
;
731 strTmp
.reserve(length()); // micro optimisation to avoid multiple mem allocs
734 strTmp
.append(c_str(), nStart
);
736 strTmp
.append(c_str() + nStart
+ nLen
);
742 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
743 size_t nCount
, wxChar ch
)
745 return replace(nStart
, nLen
, wxStringBase(nCount
, ch
).c_str());
748 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
749 const wxStringBase
& str
,
750 size_t nStart2
, size_t nLen2
)
752 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
755 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
756 const wxChar
* sz
, size_t nCount
)
758 return replace(nStart
, nLen
, wxStringBase(sz
, nCount
).c_str());
761 wxStringBase
wxStringBase::substr(size_t nStart
, size_t nLen
) const
764 nLen
= length() - nStart
;
765 return wxStringBase(*this, nStart
, nLen
);
768 // assigns one string to another
769 wxStringBase
& wxStringBase::operator=(const wxStringBase
& stringSrc
)
771 wxASSERT( stringSrc
.GetStringData()->IsValid() );
773 // don't copy string over itself
774 if ( m_pchData
!= stringSrc
.m_pchData
) {
775 if ( stringSrc
.GetStringData()->IsEmpty() ) {
780 GetStringData()->Unlock();
781 m_pchData
= stringSrc
.m_pchData
;
782 GetStringData()->Lock();
789 // assigns a single character
790 wxStringBase
& wxStringBase::operator=(wxChar ch
)
792 if ( !AssignCopy(1, &ch
) ) {
793 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(wxChar)") );
799 wxStringBase
& wxStringBase::operator=(const wxChar
*psz
)
801 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
802 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(const wxChar *)") );
807 // helper function: does real copy
808 bool wxStringBase::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
810 if ( nSrcLen
== 0 ) {
814 if ( !AllocBeforeWrite(nSrcLen
) ) {
815 // allocation failure handled by caller
818 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
819 GetStringData()->nDataLength
= nSrcLen
;
820 m_pchData
[nSrcLen
] = wxT('\0');
825 // ---------------------------------------------------------------------------
826 // string concatenation
827 // ---------------------------------------------------------------------------
829 // add something to this string
830 bool wxStringBase::ConcatSelf(size_t nSrcLen
, const wxChar
*pszSrcData
,
833 STATISTICS_ADD(SummandLength
, nSrcLen
);
835 nSrcLen
= nSrcLen
< nMaxLen
? nSrcLen
: nMaxLen
;
837 // concatenating an empty string is a NOP
839 wxStringData
*pData
= GetStringData();
840 size_t nLen
= pData
->nDataLength
;
841 size_t nNewLen
= nLen
+ nSrcLen
;
843 // alloc new buffer if current is too small
844 if ( pData
->IsShared() ) {
845 STATISTICS_ADD(ConcatHit
, 0);
847 // we have to allocate another buffer
848 wxStringData
* pOldData
= GetStringData();
849 if ( !AllocBuffer(nNewLen
) ) {
850 // allocation failure handled by caller
853 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
856 else if ( nNewLen
> pData
->nAllocLength
) {
857 STATISTICS_ADD(ConcatHit
, 0);
860 // we have to grow the buffer
861 if ( capacity() < nNewLen
) {
862 // allocation failure handled by caller
867 STATISTICS_ADD(ConcatHit
, 1);
869 // the buffer is already big enough
872 // should be enough space
873 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
875 // fast concatenation - all is done in our buffer
876 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
878 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
879 GetStringData()->nDataLength
= nNewLen
; // and fix the length
881 //else: the string to append was empty
885 // ---------------------------------------------------------------------------
886 // simple sub-string extraction
887 // ---------------------------------------------------------------------------
889 // helper function: clone the data attached to this string
890 bool wxStringBase::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
892 if ( nCopyLen
== 0 ) {
896 if ( !dest
.AllocBuffer(nCopyLen
) ) {
897 // allocation failure handled by caller
900 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
907 #if !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
910 #define STRINGCLASS wxStringBase
912 #define STRINGCLASS wxString
915 static inline int wxDoCmp(const wxChar
* s1
, size_t l1
,
916 const wxChar
* s2
, size_t l2
)
919 return wxMemcmp(s1
, s2
, l1
);
922 int ret
= wxMemcmp(s1
, s2
, l1
);
923 return ret
== 0 ? -1 : ret
;
927 int ret
= wxMemcmp(s1
, s2
, l2
);
928 return ret
== 0 ? +1 : ret
;
931 wxFAIL
; // must never get there
932 return 0; // quiet compilers
935 int STRINGCLASS::compare(const wxStringBase
& str
) const
937 return ::wxDoCmp(data(), length(), str
.data(), str
.length());
940 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
941 const wxStringBase
& str
) const
943 wxASSERT(nStart
<= length());
944 size_type strLen
= length() - nStart
;
945 nLen
= strLen
< nLen
? strLen
: nLen
;
946 return ::wxDoCmp(data() + nStart
, nLen
, str
.data(), str
.length());
949 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
950 const wxStringBase
& str
,
951 size_t nStart2
, size_t nLen2
) const
953 wxASSERT(nStart
<= length());
954 wxASSERT(nStart2
<= str
.length());
955 size_type strLen
= length() - nStart
,
956 strLen2
= str
.length() - nStart2
;
957 nLen
= strLen
< nLen
? strLen
: nLen
;
958 nLen2
= strLen2
< nLen2
? strLen2
: nLen2
;
959 return ::wxDoCmp(data() + nStart
, nLen
, str
.data() + nStart2
, nLen2
);
962 int STRINGCLASS::compare(const wxChar
* sz
) const
964 size_t nLen
= wxStrlen(sz
);
965 return ::wxDoCmp(data(), length(), sz
, nLen
);
968 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
969 const wxChar
* sz
, size_t nCount
) const
971 wxASSERT(nStart
<= length());
972 size_type strLen
= length() - nStart
;
973 nLen
= strLen
< nLen
? strLen
: nLen
;
975 nCount
= wxStrlen(sz
);
977 return ::wxDoCmp(data() + nStart
, nLen
, sz
, nCount
);
982 #endif // !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
984 // ===========================================================================
985 // wxString class core
986 // ===========================================================================
988 // ---------------------------------------------------------------------------
989 // construction and conversion
990 // ---------------------------------------------------------------------------
994 // from multibyte string
995 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
997 // if nLength != npos, then we have to make a NULL-terminated copy
998 // of first nLength bytes of psz first because the input buffer to MB2WC
999 // must always be NULL-terminated:
1000 wxCharBuffer
inBuf((const char *)NULL
);
1001 if (nLength
!= npos
)
1003 wxASSERT( psz
!= NULL
);
1004 wxCharBuffer
tmp(nLength
);
1005 memcpy(tmp
.data(), psz
, nLength
);
1006 tmp
.data()[nLength
] = '\0';
1011 // first get the size of the buffer we need
1015 // calculate the needed size ourselves or use the provided one
1016 if (nLength
== npos
)
1023 // nothing to convert
1029 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
1031 //Get length of converted string
1032 size_t dwConvLen
= conv
.MB2WC(NULL
, psz
, 0, nLen
);
1034 //if valid, do the conversion
1035 if (dwConvLen
!= (size_t) -1)
1037 //Get internal buffer
1038 wxStringBufferLength
internalBuffer(*this, dwConvLen
+ 1);
1040 //Do the actual conversion & Set the length of the buffer
1041 internalBuffer
.SetLength(
1042 conv
.MB2WC(internalBuffer
, psz
, dwConvLen
+ 1, nLen
)
1048 //Convert wxString in Unicode mode to a multi-byte string
1049 const wxCharBuffer
wxString::mb_str(wxMBConv
& conv
) const
1051 //Get length of converted string
1052 size_t dwConvLen
= conv
.WC2MB(NULL
, (*this).c_str(), 0, length());
1054 //if valid, do the conversion
1055 if (dwConvLen
!= (size_t) -1)
1057 //Create good buffer
1058 wxCharBuffer
buffer(dwConvLen
+ 1);
1060 //Do the actual conversion
1061 conv
.WC2MB(buffer
.data(), (*this).c_str(), dwConvLen
+ 1, length());
1066 //create bogus buffer
1067 wxCharBuffer
buffer(1);
1068 buffer
.data()[0u] = 0;
1076 wxString::wxString(const wchar_t *pwz
, wxMBConv
& conv
, size_t nLength
)
1078 // if nLength != npos, then we have to make a NULL-terminated copy
1079 // of first nLength chars of psz first because the input buffer to WC2MB
1080 // must always be NULL-terminated:
1081 wxWCharBuffer
inBuf((const wchar_t *)NULL
);
1082 if (nLength
!= npos
)
1084 wxASSERT( pwz
!= NULL
);
1085 wxWCharBuffer
tmp(nLength
);
1086 memcpy(tmp
.data(), pwz
, nLength
* sizeof(wchar_t));
1087 tmp
.data()[nLength
] = '\0';
1092 // first get the size of the buffer we need
1096 // calculate the needed size ourselves or use the provided one
1097 if (nLength
== npos
)
1098 nLen
= wxWcslen(pwz
);
1104 // nothing to convert
1109 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
1111 //Get length of converted string
1112 size_t dwConvLen
= conv
.WC2MB(NULL
, pwz
, 0, nLen
);
1114 //if valid, do the conversion
1115 if (dwConvLen
!= (size_t) -1)
1117 //Get internal buffer
1118 wxStringBufferLength
internalBuffer(*this, dwConvLen
+ 1);
1120 //Do the actual conversion & Set the length of the buffer
1121 internalBuffer
.SetLength(
1122 conv
.WC2MB(internalBuffer
, pwz
, dwConvLen
+ 1, nLen
)
1128 //Converts this string to a wide character string if unicode
1129 //mode is not enabled and wxUSE_WCHAR_T is enabled
1130 const wxWCharBuffer
wxString::wc_str(wxMBConv
& conv
) const
1132 //Get length of converted string
1133 size_t dwConvLen
= conv
.MB2WC(NULL
, (*this).c_str(), 0, length());
1135 //if valid, do the conversion
1136 if (dwConvLen
!= (size_t) -1)
1138 //Create good buffer
1139 wxWCharBuffer
buffer(dwConvLen
+ 1);
1141 //Do the actual conversion
1142 conv
.MB2WC(buffer
.data(), (*this).c_str(), dwConvLen
+ 1, length());
1147 //create bogus buffer
1148 wxWCharBuffer
buffer(1);
1149 buffer
.data()[0u] = 0;
1153 #endif // wxUSE_WCHAR_T
1155 #endif // Unicode/ANSI
1157 // shrink to minimal size (releasing extra memory)
1158 bool wxString::Shrink()
1160 wxString
tmp(begin(), end());
1162 return tmp
.length() == length();
1166 // get the pointer to writable buffer of (at least) nLen bytes
1167 wxChar
*wxString::GetWriteBuf(size_t nLen
)
1169 if ( !AllocBeforeWrite(nLen
) ) {
1170 // allocation failure handled by caller
1174 wxASSERT( GetStringData()->nRefs
== 1 );
1175 GetStringData()->Validate(false);
1180 // put string back in a reasonable state after GetWriteBuf
1181 void wxString::UngetWriteBuf()
1183 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
1184 GetStringData()->Validate(true);
1187 void wxString::UngetWriteBuf(size_t nLen
)
1189 GetStringData()->nDataLength
= nLen
;
1190 GetStringData()->Validate(true);
1194 // ---------------------------------------------------------------------------
1196 // ---------------------------------------------------------------------------
1198 // all functions are inline in string.h
1200 // ---------------------------------------------------------------------------
1201 // assignment operators
1202 // ---------------------------------------------------------------------------
1206 // same as 'signed char' variant
1207 wxString
& wxString::operator=(const unsigned char* psz
)
1209 *this = (const char *)psz
;
1214 wxString
& wxString::operator=(const wchar_t *pwz
)
1225 * concatenation functions come in 5 flavours:
1227 * char + string and string + char
1228 * C str + string and string + C str
1231 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
1234 wxASSERT( str1
.GetStringData()->IsValid() );
1235 wxASSERT( str2
.GetStringData()->IsValid() );
1244 wxString
operator+(const wxString
& str
, wxChar ch
)
1247 wxASSERT( str
.GetStringData()->IsValid() );
1256 wxString
operator+(wxChar ch
, const wxString
& str
)
1259 wxASSERT( str
.GetStringData()->IsValid() );
1268 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
1271 wxASSERT( str
.GetStringData()->IsValid() );
1275 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
1276 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1284 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
1287 wxASSERT( str
.GetStringData()->IsValid() );
1291 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
1292 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1300 // ===========================================================================
1301 // other common string functions
1302 // ===========================================================================
1304 int wxString::Cmp(const wxString
& s
) const
1309 int wxString::Cmp(const wxChar
* psz
) const
1311 return compare(psz
);
1314 static inline int wxDoCmpNoCase(const wxChar
* s1
, size_t l1
,
1315 const wxChar
* s2
, size_t l2
)
1321 for(i
= 0; i
< l1
; ++i
)
1323 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1326 return i
== l1
? 0 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1330 for(i
= 0; i
< l1
; ++i
)
1332 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1335 return i
== l1
? -1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1339 for(i
= 0; i
< l2
; ++i
)
1341 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1344 return i
== l2
? 1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1347 wxFAIL
; // must never get there
1348 return 0; // quiet compilers
1351 int wxString::CmpNoCase(const wxString
& s
) const
1353 return wxDoCmpNoCase(data(), length(), s
.data(), s
.length());
1356 int wxString::CmpNoCase(const wxChar
* psz
) const
1358 int nLen
= wxStrlen(psz
);
1360 return wxDoCmpNoCase(data(), length(), psz
, nLen
);
1367 #ifndef __SCHAR_MAX__
1368 #define __SCHAR_MAX__ 127
1372 wxString
wxString::FromAscii(const char *ascii
)
1375 return wxEmptyString
;
1377 size_t len
= strlen( ascii
);
1382 wxStringBuffer
buf(res
, len
);
1384 wchar_t *dest
= buf
;
1388 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
1396 wxString
wxString::FromAscii(const char ascii
)
1398 // What do we do with '\0' ?
1401 res
+= (wchar_t)(unsigned char) ascii
;
1406 const wxCharBuffer
wxString::ToAscii() const
1408 // this will allocate enough space for the terminating NUL too
1409 wxCharBuffer
buffer(length());
1412 char *dest
= buffer
.data();
1414 const wchar_t *pwc
= c_str();
1417 *dest
++ = (char)(*pwc
> SCHAR_MAX
? wxT('_') : *pwc
);
1419 // the output string can't have embedded NULs anyhow, so we can safely
1420 // stop at first of them even if we do have any
1430 // extract string of length nCount starting at nFirst
1431 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
1433 size_t nLen
= length();
1435 // default value of nCount is npos and means "till the end"
1436 if ( nCount
== npos
)
1438 nCount
= nLen
- nFirst
;
1441 // out-of-bounds requests return sensible things
1442 if ( nFirst
+ nCount
> nLen
)
1444 nCount
= nLen
- nFirst
;
1447 if ( nFirst
> nLen
)
1449 // AllocCopy() will return empty string
1453 wxString
dest(*this, nFirst
, nCount
);
1454 if ( dest
.length() != nCount
) {
1455 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
1461 // check that the string starts with prefix and return the rest of the string
1462 // in the provided pointer if it is not NULL, otherwise return false
1463 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
1465 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
1467 // first check if the beginning of the string matches the prefix: note
1468 // that we don't have to check that we don't run out of this string as
1469 // when we reach the terminating NUL, either prefix string ends too (and
1470 // then it's ok) or we break out of the loop because there is no match
1471 const wxChar
*p
= c_str();
1474 if ( *prefix
++ != *p
++ )
1483 // put the rest of the string into provided pointer
1490 // extract nCount last (rightmost) characters
1491 wxString
wxString::Right(size_t nCount
) const
1493 if ( nCount
> length() )
1496 wxString
dest(*this, length() - nCount
, nCount
);
1497 if ( dest
.length() != nCount
) {
1498 wxFAIL_MSG( _T("out of memory in wxString::Right") );
1503 // get all characters after the last occurence of ch
1504 // (returns the whole string if ch not found)
1505 wxString
wxString::AfterLast(wxChar ch
) const
1508 int iPos
= Find(ch
, true);
1509 if ( iPos
== wxNOT_FOUND
)
1512 str
= c_str() + iPos
+ 1;
1517 // extract nCount first (leftmost) characters
1518 wxString
wxString::Left(size_t nCount
) const
1520 if ( nCount
> length() )
1523 wxString
dest(*this, 0, nCount
);
1524 if ( dest
.length() != nCount
) {
1525 wxFAIL_MSG( _T("out of memory in wxString::Left") );
1530 // get all characters before the first occurence of ch
1531 // (returns the whole string if ch not found)
1532 wxString
wxString::BeforeFirst(wxChar ch
) const
1534 int iPos
= Find(ch
);
1535 if ( iPos
== wxNOT_FOUND
) iPos
= length();
1536 return wxString(*this, 0, iPos
);
1539 /// get all characters before the last occurence of ch
1540 /// (returns empty string if ch not found)
1541 wxString
wxString::BeforeLast(wxChar ch
) const
1544 int iPos
= Find(ch
, true);
1545 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
1546 str
= wxString(c_str(), iPos
);
1551 /// get all characters after the first occurence of ch
1552 /// (returns empty string if ch not found)
1553 wxString
wxString::AfterFirst(wxChar ch
) const
1556 int iPos
= Find(ch
);
1557 if ( iPos
!= wxNOT_FOUND
)
1558 str
= c_str() + iPos
+ 1;
1563 // replace first (or all) occurences of some substring with another one
1565 wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
1567 // if we tried to replace an empty string we'd enter an infinite loop below
1568 wxCHECK_MSG( szOld
&& *szOld
&& szNew
, 0,
1569 _T("wxString::Replace(): invalid parameter") );
1571 size_t uiCount
= 0; // count of replacements made
1573 size_t uiOldLen
= wxStrlen(szOld
);
1576 const wxChar
*pCurrent
= c_str();
1577 const wxChar
*pSubstr
;
1578 while ( *pCurrent
!= wxT('\0') ) {
1579 pSubstr
= wxStrstr(pCurrent
, szOld
);
1580 if ( pSubstr
== NULL
) {
1581 // strTemp is unused if no replacements were made, so avoid the copy
1585 strTemp
+= pCurrent
; // copy the rest
1586 break; // exit the loop
1589 // take chars before match
1590 size_type len
= strTemp
.length();
1591 strTemp
.append(pCurrent
, pSubstr
- pCurrent
);
1592 if ( strTemp
.length() != (size_t)(len
+ pSubstr
- pCurrent
) ) {
1593 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
1597 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
1602 if ( !bReplaceAll
) {
1603 strTemp
+= pCurrent
; // copy the rest
1604 break; // exit the loop
1609 // only done if there were replacements, otherwise would have returned above
1615 bool wxString::IsAscii() const
1617 const wxChar
*s
= (const wxChar
*) *this;
1619 if(!isascii(*s
)) return(false);
1625 bool wxString::IsWord() const
1627 const wxChar
*s
= (const wxChar
*) *this;
1629 if(!wxIsalpha(*s
)) return(false);
1635 bool wxString::IsNumber() const
1637 const wxChar
*s
= (const wxChar
*) *this;
1639 if ((s
[0] == wxT('-')) || (s
[0] == wxT('+'))) s
++;
1641 if(!wxIsdigit(*s
)) return(false);
1647 wxString
wxString::Strip(stripType w
) const
1650 if ( w
& leading
) s
.Trim(false);
1651 if ( w
& trailing
) s
.Trim(true);
1655 // ---------------------------------------------------------------------------
1657 // ---------------------------------------------------------------------------
1659 wxString
& wxString::MakeUpper()
1661 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1662 *it
= (wxChar
)wxToupper(*it
);
1667 wxString
& wxString::MakeLower()
1669 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1670 *it
= (wxChar
)wxTolower(*it
);
1675 // ---------------------------------------------------------------------------
1676 // trimming and padding
1677 // ---------------------------------------------------------------------------
1679 // some compilers (VC++ 6.0 not to name them) return true for a call to
1680 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1681 // live with this by checking that the character is a 7 bit one - even if this
1682 // may fail to detect some spaces (I don't know if Unicode doesn't have
1683 // space-like symbols somewhere except in the first 128 chars), it is arguably
1684 // still better than trimming away accented letters
1685 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1687 // trims spaces (in the sense of isspace) from left or right side
1688 wxString
& wxString::Trim(bool bFromRight
)
1690 // first check if we're going to modify the string at all
1693 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1694 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1700 // find last non-space character
1701 iterator psz
= begin() + length() - 1;
1702 while ( wxSafeIsspace(*psz
) && (psz
>= begin()) )
1705 // truncate at trailing space start
1711 // find first non-space character
1712 iterator psz
= begin();
1713 while ( wxSafeIsspace(*psz
) )
1716 // fix up data and length
1717 erase(begin(), psz
);
1724 // adds nCount characters chPad to the string from either side
1725 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1727 wxString
s(chPad
, nCount
);
1740 // truncate the string
1741 wxString
& wxString::Truncate(size_t uiLen
)
1743 if ( uiLen
< Len() ) {
1744 erase(begin() + uiLen
, end());
1746 //else: nothing to do, string is already short enough
1751 // ---------------------------------------------------------------------------
1752 // finding (return wxNOT_FOUND if not found and index otherwise)
1753 // ---------------------------------------------------------------------------
1756 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1758 size_type idx
= bFromEnd
? find_last_of(ch
) : find_first_of(ch
);
1760 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1763 // find a sub-string (like strstr)
1764 int wxString::Find(const wxChar
*pszSub
) const
1766 size_type idx
= find(pszSub
);
1768 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1771 // ----------------------------------------------------------------------------
1772 // conversion to numbers
1773 // ----------------------------------------------------------------------------
1775 bool wxString::ToLong(long *val
, int base
) const
1777 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToLong") );
1778 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1780 const wxChar
*start
= c_str();
1782 *val
= wxStrtol(start
, &end
, base
);
1784 // return true only if scan was stopped by the terminating NUL and if the
1785 // string was not empty to start with
1786 return !*end
&& (end
!= start
);
1789 bool wxString::ToULong(unsigned long *val
, int base
) const
1791 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToULong") );
1792 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1794 const wxChar
*start
= c_str();
1796 *val
= wxStrtoul(start
, &end
, base
);
1798 // return true only if scan was stopped by the terminating NUL and if the
1799 // string was not empty to start with
1800 return !*end
&& (end
!= start
);
1803 bool wxString::ToDouble(double *val
) const
1805 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToDouble") );
1807 const wxChar
*start
= c_str();
1809 *val
= wxStrtod(start
, &end
);
1811 // return true only if scan was stopped by the terminating NUL and if the
1812 // string was not empty to start with
1813 return !*end
&& (end
!= start
);
1816 // ---------------------------------------------------------------------------
1818 // ---------------------------------------------------------------------------
1821 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1824 va_start(argptr
, pszFormat
);
1827 s
.PrintfV(pszFormat
, argptr
);
1835 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1838 s
.PrintfV(pszFormat
, argptr
);
1842 int wxString::Printf(const wxChar
*pszFormat
, ...)
1845 va_start(argptr
, pszFormat
);
1847 int iLen
= PrintfV(pszFormat
, argptr
);
1854 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1862 wxStringBuffer
tmp(*this, size
+ 1);
1871 // wxVsnprintf() may modify the original arg pointer, so pass it
1874 wxVaCopy(argptrcopy
, argptr
);
1875 len
= wxVsnprintf(buf
, size
, pszFormat
, argptrcopy
);
1878 // some implementations of vsnprintf() don't NUL terminate
1879 // the string if there is not enough space for it so
1880 // always do it manually
1881 buf
[size
] = _T('\0');
1884 // vsnprintf() may return either -1 (traditional Unix behaviour) or the
1885 // total number of characters which would have been written if the
1886 // buffer were large enough
1887 if ( len
>= 0 && len
<= size
)
1889 // ok, there was enough space
1893 // still not enough, double it again
1897 // we could have overshot
1903 // ----------------------------------------------------------------------------
1904 // misc other operations
1905 // ----------------------------------------------------------------------------
1907 // returns true if the string matches the pattern which may contain '*' and
1908 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1910 bool wxString::Matches(const wxChar
*pszMask
) const
1912 // I disable this code as it doesn't seem to be faster (in fact, it seems
1913 // to be much slower) than the old, hand-written code below and using it
1914 // here requires always linking with libregex even if the user code doesn't
1916 #if 0 // wxUSE_REGEX
1917 // first translate the shell-like mask into a regex
1919 pattern
.reserve(wxStrlen(pszMask
));
1931 pattern
+= _T(".*");
1942 // these characters are special in a RE, quote them
1943 // (however note that we don't quote '[' and ']' to allow
1944 // using them for Unix shell like matching)
1945 pattern
+= _T('\\');
1949 pattern
+= *pszMask
;
1957 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1958 #else // !wxUSE_REGEX
1959 // TODO: this is, of course, awfully inefficient...
1961 // the char currently being checked
1962 const wxChar
*pszTxt
= c_str();
1964 // the last location where '*' matched
1965 const wxChar
*pszLastStarInText
= NULL
;
1966 const wxChar
*pszLastStarInMask
= NULL
;
1969 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1970 switch ( *pszMask
) {
1972 if ( *pszTxt
== wxT('\0') )
1975 // pszTxt and pszMask will be incremented in the loop statement
1981 // remember where we started to be able to backtrack later
1982 pszLastStarInText
= pszTxt
;
1983 pszLastStarInMask
= pszMask
;
1985 // ignore special chars immediately following this one
1986 // (should this be an error?)
1987 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1990 // if there is nothing more, match
1991 if ( *pszMask
== wxT('\0') )
1994 // are there any other metacharacters in the mask?
1996 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1998 if ( pEndMask
!= NULL
) {
1999 // we have to match the string between two metachars
2000 uiLenMask
= pEndMask
- pszMask
;
2003 // we have to match the remainder of the string
2004 uiLenMask
= wxStrlen(pszMask
);
2007 wxString
strToMatch(pszMask
, uiLenMask
);
2008 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
2009 if ( pMatch
== NULL
)
2012 // -1 to compensate "++" in the loop
2013 pszTxt
= pMatch
+ uiLenMask
- 1;
2014 pszMask
+= uiLenMask
- 1;
2019 if ( *pszMask
!= *pszTxt
)
2025 // match only if nothing left
2026 if ( *pszTxt
== wxT('\0') )
2029 // if we failed to match, backtrack if we can
2030 if ( pszLastStarInText
) {
2031 pszTxt
= pszLastStarInText
+ 1;
2032 pszMask
= pszLastStarInMask
;
2034 pszLastStarInText
= NULL
;
2036 // don't bother resetting pszLastStarInMask, it's unnecessary
2042 #endif // wxUSE_REGEX/!wxUSE_REGEX
2045 // Count the number of chars
2046 int wxString::Freq(wxChar ch
) const
2050 for (int i
= 0; i
< len
; i
++)
2052 if (GetChar(i
) == ch
)
2058 // convert to upper case, return the copy of the string
2059 wxString
wxString::Upper() const
2060 { wxString
s(*this); return s
.MakeUpper(); }
2062 // convert to lower case, return the copy of the string
2063 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
2065 int wxString::sprintf(const wxChar
*pszFormat
, ...)
2068 va_start(argptr
, pszFormat
);
2069 int iLen
= PrintfV(pszFormat
, argptr
);
2074 // ============================================================================
2076 // ============================================================================
2078 #include "wx/arrstr.h"
2082 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
2083 #define ARRAY_MAXSIZE_INCREMENT 4096
2085 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
2086 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
2089 #define STRING(p) ((wxString *)(&(p)))
2092 void wxArrayString::Init(bool autoSort
)
2096 m_pItems
= (wxChar
**) NULL
;
2097 m_autoSort
= autoSort
;
2101 wxArrayString::wxArrayString(const wxArrayString
& src
)
2103 Init(src
.m_autoSort
);
2108 // assignment operator
2109 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
2116 m_autoSort
= src
.m_autoSort
;
2121 void wxArrayString::Copy(const wxArrayString
& src
)
2123 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
2124 Alloc(src
.m_nCount
);
2126 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
2131 void wxArrayString::Grow(size_t nIncrement
)
2133 // only do it if no more place
2134 if ( (m_nSize
- m_nCount
) < nIncrement
) {
2135 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2136 // be never resized!
2137 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2138 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2141 if ( m_nSize
== 0 ) {
2142 // was empty, alloc some memory
2143 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
2144 if (m_nSize
< nIncrement
)
2145 m_nSize
= nIncrement
;
2146 m_pItems
= new wxChar
*[m_nSize
];
2149 // otherwise when it's called for the first time, nIncrement would be 0
2150 // and the array would never be expanded
2151 // add 50% but not too much
2152 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
2153 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
2154 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
2155 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
2156 if ( nIncrement
< ndefIncrement
)
2157 nIncrement
= ndefIncrement
;
2158 m_nSize
+= nIncrement
;
2159 wxChar
**pNew
= new wxChar
*[m_nSize
];
2161 // copy data to new location
2162 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2164 // delete old memory (but do not release the strings!)
2165 wxDELETEA(m_pItems
);
2172 void wxArrayString::Free()
2174 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
2175 STRING(m_pItems
[n
])->GetStringData()->Unlock();
2179 // deletes all the strings from the list
2180 void wxArrayString::Empty()
2187 // as Empty, but also frees memory
2188 void wxArrayString::Clear()
2195 wxDELETEA(m_pItems
);
2199 wxArrayString::~wxArrayString()
2203 wxDELETEA(m_pItems
);
2206 void wxArrayString::reserve(size_t nSize
)
2211 // pre-allocates memory (frees the previous data!)
2212 void wxArrayString::Alloc(size_t nSize
)
2214 // only if old buffer was not big enough
2215 if ( nSize
> m_nSize
) {
2217 wxDELETEA(m_pItems
);
2218 m_pItems
= new wxChar
*[nSize
];
2225 // minimizes the memory usage by freeing unused memory
2226 void wxArrayString::Shrink()
2228 // only do it if we have some memory to free
2229 if( m_nCount
< m_nSize
) {
2230 // allocates exactly as much memory as we need
2231 wxChar
**pNew
= new wxChar
*[m_nCount
];
2233 // copy data to new location
2234 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2240 #if WXWIN_COMPATIBILITY_2_4
2242 // return a wxString[] as required for some control ctors.
2243 wxString
* wxArrayString::GetStringArray() const
2245 wxString
*array
= 0;
2249 array
= new wxString
[m_nCount
];
2250 for( size_t i
= 0; i
< m_nCount
; i
++ )
2251 array
[i
] = m_pItems
[i
];
2257 #endif // WXWIN_COMPATIBILITY_2_4
2259 // searches the array for an item (forward or backwards)
2260 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2263 // use binary search in the sorted array
2264 wxASSERT_MSG( bCase
&& !bFromEnd
,
2265 wxT("search parameters ignored for auto sorted array") );
2274 res
= wxStrcmp(sz
, m_pItems
[i
]);
2286 // use linear search in unsorted array
2288 if ( m_nCount
> 0 ) {
2289 size_t ui
= m_nCount
;
2291 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2298 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2299 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2308 // add item at the end
2309 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
2312 // insert the string at the correct position to keep the array sorted
2320 res
= str
.Cmp(m_pItems
[i
]);
2331 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2333 Insert(str
, lo
, nInsert
);
2338 wxASSERT( str
.GetStringData()->IsValid() );
2342 for (size_t i
= 0; i
< nInsert
; i
++)
2344 // the string data must not be deleted!
2345 str
.GetStringData()->Lock();
2348 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2350 size_t ret
= m_nCount
;
2351 m_nCount
+= nInsert
;
2356 // add item at the given position
2357 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2359 wxASSERT( str
.GetStringData()->IsValid() );
2361 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2362 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2363 wxT("array size overflow in wxArrayString::Insert") );
2367 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2368 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2370 for (size_t i
= 0; i
< nInsert
; i
++)
2372 str
.GetStringData()->Lock();
2373 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2375 m_nCount
+= nInsert
;
2378 // range insert (STL 23.2.4.3)
2380 wxArrayString::insert(iterator it
, const_iterator first
, const_iterator last
)
2382 const int idx
= it
- begin();
2387 // reset "it" since it can change inside Grow()
2390 while ( first
!= last
)
2392 it
= insert(it
, *first
);
2394 // insert returns an iterator to the last element inserted but we need
2395 // insert the next after this one, that is before the next one
2403 void wxArrayString::SetCount(size_t count
)
2408 while ( m_nCount
< count
)
2409 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2412 // removes item from array (by index)
2413 void wxArrayString::RemoveAt(size_t nIndex
, size_t nRemove
)
2415 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2416 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2417 wxT("removing too many elements in wxArrayString::Remove") );
2420 for (size_t i
= 0; i
< nRemove
; i
++)
2421 Item(nIndex
+ i
).GetStringData()->Unlock();
2423 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2424 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2425 m_nCount
-= nRemove
;
2428 // removes item from array (by value)
2429 void wxArrayString::Remove(const wxChar
*sz
)
2431 int iIndex
= Index(sz
);
2433 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2434 wxT("removing inexistent element in wxArrayString::Remove") );
2439 void wxArrayString::assign(const_iterator first
, const_iterator last
)
2441 reserve(last
- first
);
2442 for(; first
!= last
; ++first
)
2446 // ----------------------------------------------------------------------------
2448 // ----------------------------------------------------------------------------
2450 // we can only sort one array at a time with the quick-sort based
2453 // need a critical section to protect access to gs_compareFunction and
2454 // gs_sortAscending variables
2455 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2457 // call this before the value of the global sort vars is changed/after
2458 // you're finished with them
2459 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2460 gs_critsectStringSort = new wxCriticalSection; \
2461 gs_critsectStringSort->Enter()
2462 #define END_SORT() gs_critsectStringSort->Leave(); \
2463 delete gs_critsectStringSort; \
2464 gs_critsectStringSort = NULL
2466 #define START_SORT()
2468 #endif // wxUSE_THREADS
2470 // function to use for string comparaison
2471 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2473 // if we don't use the compare function, this flag tells us if we sort the
2474 // array in ascending or descending order
2475 static bool gs_sortAscending
= true;
2477 // function which is called by quick sort
2478 extern "C" int wxC_CALLING_CONV
// LINKAGEMODE
2479 wxStringCompareFunction(const void *first
, const void *second
)
2481 wxString
*strFirst
= (wxString
*)first
;
2482 wxString
*strSecond
= (wxString
*)second
;
2484 if ( gs_compareFunction
) {
2485 return gs_compareFunction(*strFirst
, *strSecond
);
2488 // maybe we should use wxStrcoll
2489 int result
= strFirst
->Cmp(*strSecond
);
2491 return gs_sortAscending
? result
: -result
;
2495 // sort array elements using passed comparaison function
2496 void wxArrayString::Sort(CompareFunction compareFunction
)
2500 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2501 gs_compareFunction
= compareFunction
;
2505 // reset it to NULL so that Sort(bool) will work the next time
2506 gs_compareFunction
= NULL
;
2511 typedef int (wxC_CALLING_CONV
* wxStringCompareFn
)(const void *first
, const void *second
);
2513 void wxArrayString::Sort(CompareFunction2 compareFunction
)
2515 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), (wxStringCompareFn
)compareFunction
);
2518 void wxArrayString::Sort(bool reverseOrder
)
2520 Sort(reverseOrder
? wxStringSortDescending
: wxStringSortAscending
);
2523 void wxArrayString::DoSort()
2525 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2527 // just sort the pointers using qsort() - of course it only works because
2528 // wxString() *is* a pointer to its data
2529 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2532 bool wxArrayString::operator==(const wxArrayString
& a
) const
2534 if ( m_nCount
!= a
.m_nCount
)
2537 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2539 if ( Item(n
) != a
[n
] )
2546 #endif // !wxUSE_STL
2548 int wxCMPFUNC_CONV
wxStringSortAscending(wxString
* s1
, wxString
* s2
)
2550 return s1
->Cmp(*s2
);
2553 int wxCMPFUNC_CONV
wxStringSortDescending(wxString
* s1
, wxString
* s2
)
2555 return -s1
->Cmp(*s2
);