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 /////////////////////////////////////////////////////////////////////////////
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"
33 #include "wx/string.h"
35 #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
94 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
97 // ATTN: you can _not_ use both of these in the same program!
101 wxSTD istream
& operator>>(wxSTD istream
& is
, wxString
& WXUNUSED(str
))
106 streambuf
*sb
= is
.rdbuf();
109 int ch
= sb
->sbumpc ();
111 is
.setstate(ios
::eofbit
);
114 else if ( isspace(ch
) ) {
126 if ( str
.length() == 0 )
127 is
.setstate(ios
::failbit
);
132 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
138 #endif // wxUSE_STD_IOSTREAM
140 // ----------------------------------------------------------------------------
142 // ----------------------------------------------------------------------------
144 // this small class is used to gather statistics for performance tuning
145 //#define WXSTRING_STATISTICS
146 #ifdef WXSTRING_STATISTICS
150 Averager(const wxChar
*sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
152 { wxPrintf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
154 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
157 size_t m_nCount
, m_nTotal
;
159 } g_averageLength("allocation size"),
160 g_averageSummandLength("summand length"),
161 g_averageConcatHit("hit probability in concat"),
162 g_averageInitialLength("initial string length");
164 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
166 #define STATISTICS_ADD(av, val)
167 #endif // WXSTRING_STATISTICS
171 // ===========================================================================
172 // wxStringData class deallocation
173 // ===========================================================================
175 #if defined(__VISUALC__) && defined(_MT) && !defined(_DLL)
176 # pragma message (__FILE__ ": building with Multithreaded non DLL runtime has a performance impact on wxString!")
177 void wxStringData
::Free()
183 // ===========================================================================
185 // ===========================================================================
187 // takes nLength elements of psz starting at nPos
188 void wxStringBase
::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
192 // if the length is not given, assume the string to be NUL terminated
193 if ( nLength
== npos
) {
194 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
196 nLength
= wxStrlen(psz
+ nPos
);
199 STATISTICS_ADD(InitialLength
, nLength
);
202 // trailing '\0' is written in AllocBuffer()
203 if ( !AllocBuffer(nLength
) ) {
204 wxFAIL_MSG( _T("out of memory in wxStringBase::InitWith") );
207 wxTmemcpy(m_pchData
, psz
+ nPos
, nLength
);
211 // poor man's iterators are "void *" pointers
212 wxStringBase
::wxStringBase(const void *pStart
, const void *pEnd
)
214 InitWith((const wxChar
*)pStart
, 0,
215 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
218 wxStringBase
::wxStringBase(size_type n
, wxChar ch
)
224 // ---------------------------------------------------------------------------
226 // ---------------------------------------------------------------------------
228 // allocates memory needed to store a C string of length nLen
229 bool wxStringBase
::AllocBuffer(size_t nLen
)
231 // allocating 0 sized buffer doesn't make sense, all empty strings should
233 wxASSERT( nLen
> 0 );
235 // make sure that we don't overflow
236 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
237 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
239 STATISTICS_ADD(Length
, nLen
);
242 // 1) one extra character for '\0' termination
243 // 2) sizeof(wxStringData) for housekeeping info
244 wxStringData
* pData
= (wxStringData
*)
245 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
247 if ( pData
== NULL
) {
248 // allocation failures are handled by the caller
253 pData
->nDataLength
= nLen
;
254 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
255 m_pchData
= pData
->data(); // data starts after wxStringData
256 m_pchData
[nLen
] = wxT('\0');
260 // must be called before changing this string
261 bool wxStringBase
::CopyBeforeWrite()
263 wxStringData
* pData
= GetStringData();
265 if ( pData
->IsShared() ) {
266 pData
->Unlock(); // memory not freed because shared
267 size_t nLen
= pData
->nDataLength
;
268 if ( !AllocBuffer(nLen
) ) {
269 // allocation failures are handled by the caller
272 wxTmemcpy(m_pchData
, pData
->data(), nLen
);
275 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
280 // must be called before replacing contents of this string
281 bool wxStringBase
::AllocBeforeWrite(size_t nLen
)
283 wxASSERT( nLen
!= 0 ); // doesn't make any sense
285 // must not share string and must have enough space
286 wxStringData
* pData
= GetStringData();
287 if ( pData
->IsShared() || pData
->IsEmpty() ) {
288 // can't work with old buffer, get new one
290 if ( !AllocBuffer(nLen
) ) {
291 // allocation failures are handled by the caller
296 if ( nLen
> pData
->nAllocLength
) {
297 // realloc the buffer instead of calling malloc() again, this is more
299 STATISTICS_ADD(Length
, nLen
);
303 pData
= (wxStringData
*)
304 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
306 if ( pData
== NULL
) {
307 // allocation failures are handled by the caller
308 // keep previous data since reallocation failed
312 pData
->nAllocLength
= nLen
;
313 m_pchData
= pData
->data();
317 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
319 // it doesn't really matter what the string length is as it's going to be
320 // overwritten later but, for extra safety, set it to 0 for now as we may
321 // have some junk in m_pchData
322 GetStringData()->nDataLength
= 0;
327 wxStringBase
& wxStringBase
::append(size_t n
, wxChar ch
)
329 size_type len
= length();
331 if ( !Alloc(len
+ n
) || !CopyBeforeWrite() ) {
332 wxFAIL_MSG( _T("out of memory in wxStringBase::append") );
334 GetStringData()->nDataLength
= len
+ n
;
335 m_pchData
[len
+ n
] = '\0';
336 for ( size_t i
= 0; i
< n
; ++i
)
337 m_pchData
[len
+ i
] = ch
;
341 void wxStringBase
::resize(size_t nSize
, wxChar ch
)
343 size_t len
= length();
347 erase(begin() + nSize
, end());
349 else if ( nSize
> len
)
351 append(nSize
- len
, ch
);
353 //else: we have exactly the specified length, nothing to do
356 // allocate enough memory for nLen characters
357 bool wxStringBase
::Alloc(size_t nLen
)
359 wxStringData
*pData
= GetStringData();
360 if ( pData
->nAllocLength
<= nLen
) {
361 if ( pData
->IsEmpty() ) {
364 wxStringData
* pData
= (wxStringData
*)
365 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
367 if ( pData
== NULL
) {
368 // allocation failure handled by caller
373 pData
->nDataLength
= 0;
374 pData
->nAllocLength
= nLen
;
375 m_pchData
= pData
->data(); // data starts after wxStringData
376 m_pchData
[0u] = wxT('\0');
378 else if ( pData
->IsShared() ) {
379 pData
->Unlock(); // memory not freed because shared
380 size_t nOldLen
= pData
->nDataLength
;
381 if ( !AllocBuffer(nLen
) ) {
382 // allocation failure handled by caller
385 // +1 to copy the terminator, too
386 memcpy(m_pchData
, pData
->data(), (nOldLen
+1)*sizeof(wxChar
));
387 GetStringData()->nDataLength
= nOldLen
;
392 pData
= (wxStringData
*)
393 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
395 if ( pData
== NULL
) {
396 // allocation failure handled by caller
397 // keep previous data since reallocation failed
401 // it's not important if the pointer changed or not (the check for this
402 // is not faster than assigning to m_pchData in all cases)
403 pData
->nAllocLength
= nLen
;
404 m_pchData
= pData
->data();
407 //else: we've already got enough
411 wxStringBase
::iterator wxStringBase
::begin()
418 wxStringBase
::iterator wxStringBase
::end()
422 return m_pchData
+ length();
425 wxStringBase
::iterator wxStringBase
::erase(iterator it
)
427 size_type idx
= it
- begin();
429 return begin() + idx
;
432 wxStringBase
& wxStringBase
::erase(size_t nStart
, size_t nLen
)
434 wxASSERT(nStart
<= length());
435 size_t strLen
= length() - nStart
;
436 // delete nLen or up to the end of the string characters
437 nLen
= strLen
< nLen ? strLen
: nLen
;
438 wxString
strTmp(c_str(), nStart
);
439 strTmp
.append(c_str() + nStart
+ nLen
, length() - nStart
- nLen
);
445 wxStringBase
& wxStringBase
::insert(size_t nPos
, const wxChar
*sz
, size_t n
)
447 wxASSERT( nPos
<= length() );
449 if ( n
== npos
) n
= wxStrlen(sz
);
450 if ( n
== 0 ) return *this;
452 if ( !Alloc(length() + n
) || !CopyBeforeWrite() ) {
453 wxFAIL_MSG( _T("out of memory in wxStringBase::insert") );
456 memmove(m_pchData
+ nPos
+ n
, m_pchData
+ nPos
,
457 (length() - nPos
) * sizeof(wxChar
));
458 memcpy(m_pchData
+ nPos
, sz
, n
* sizeof(wxChar
));
459 GetStringData()->nDataLength
= length() + n
;
460 m_pchData
[length()] = '\0';
465 void wxStringBase
::swap(wxStringBase
& str
)
467 wxChar
* tmp
= str
.m_pchData
;
468 str
.m_pchData
= m_pchData
;
472 size_t wxStringBase
::find(const wxStringBase
& str
, size_t nStart
) const
474 wxASSERT( str
.GetStringData()->IsValid() );
475 wxASSERT( nStart
<= length() );
478 const wxChar
* p
= (const wxChar
*)wxTmemchr(c_str() + nStart
,
485 while(p
- c_str() + str
.length() <= length() &&
486 wxTmemcmp(p
, str
.c_str(), str
.length()) )
488 //Previosly passed as the first argument to wxTmemchr,
489 //but C/C++ standard does not specify evaluation order
490 //of arguments to functions -
491 //http://embedded.com/showArticle.jhtml?articleID=9900607
495 p
= (const wxChar
*)wxTmemchr(p
,
497 length() - (p
- c_str()));
503 return (p
- c_str() + str
.length() <= length()) ? p
- c_str() : npos
;
506 size_t wxStringBase
::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
508 return find(wxStringBase(sz
, n
), nStart
);
511 size_t wxStringBase
::find(wxChar ch
, size_t nStart
) const
513 wxASSERT( nStart
<= length() );
515 const wxChar
*p
= (const wxChar
*)wxTmemchr(c_str() + nStart
, ch
, length() - nStart
);
517 return p
== NULL ? npos
: p
- c_str();
520 size_t wxStringBase
::rfind(const wxStringBase
& str
, size_t nStart
) const
522 wxASSERT( str
.GetStringData()->IsValid() );
523 wxASSERT( nStart
== npos
|| nStart
<= length() );
525 if ( length() >= str
.length() )
527 // avoids a corner case later
528 if ( length() == 0 && str
.length() == 0 )
531 // "top" is the point where search starts from
532 size_t top
= length() - str
.length();
534 if ( nStart
== npos
)
535 nStart
= length() - 1;
539 const wxChar
*cursor
= c_str() + top
;
542 if ( wxTmemcmp(cursor
, str
.c_str(),
545 return cursor
- c_str();
547 } while ( cursor
-- > c_str() );
553 size_t wxStringBase
::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
555 return rfind(wxStringBase(sz
, n
), nStart
);
558 size_t wxStringBase
::rfind(wxChar ch
, size_t nStart
) const
560 if ( nStart
== npos
)
566 wxASSERT( nStart
<= length() );
569 const wxChar
*actual
;
570 for ( actual
= c_str() + ( nStart
== npos ?
length() : nStart
+ 1 );
571 actual
> c_str(); --actual
)
573 if ( *(actual
- 1) == ch
)
574 return (actual
- 1) - c_str();
580 size_t wxStringBase
::find_first_of(const wxChar
* sz
, size_t nStart
) const
582 wxASSERT(nStart
<= length());
584 size_t len
= wxStrlen(sz
);
587 for(i
= nStart
; i
< this->length(); ++i
)
589 if (wxTmemchr(sz
, *(c_str() + i
), len
))
593 if(i
== this->length())
599 size_t wxStringBase
::find_first_of(const wxChar
* sz
, size_t nStart
,
602 return find_first_of(wxStringBase(sz
, n
), nStart
);
605 size_t wxStringBase
::find_last_of(const wxChar
* sz
, size_t nStart
) const
607 if ( nStart
== npos
)
609 nStart
= length() - 1;
613 wxASSERT_MSG( nStart
<= length(),
614 _T("invalid index in find_last_of()") );
617 size_t len
= wxStrlen(sz
);
619 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
621 if ( wxTmemchr(sz
, *p
, len
) )
628 size_t wxStringBase
::find_last_of(const wxChar
* sz
, size_t nStart
,
631 return find_last_of(wxStringBase(sz
, n
), nStart
);
634 size_t wxStringBase
::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
636 if ( nStart
== npos
)
642 wxASSERT( nStart
<= length() );
645 size_t len
= wxStrlen(sz
);
648 for(i
= nStart
; i
< this->length(); ++i
)
650 if (!wxTmemchr(sz
, *(c_str() + i
), len
))
654 if(i
== this->length())
660 size_t wxStringBase
::find_first_not_of(const wxChar
* sz
, size_t nStart
,
663 return find_first_not_of(wxStringBase(sz
, n
), nStart
);
666 size_t wxStringBase
::find_first_not_of(wxChar ch
, size_t nStart
) const
668 wxASSERT( nStart
<= length() );
670 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
679 size_t wxStringBase
::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
681 if ( nStart
== npos
)
683 nStart
= length() - 1;
687 wxASSERT( nStart
<= length() );
690 size_t len
= wxStrlen(sz
);
692 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
694 if ( !wxTmemchr(sz
, *p
,len
) )
701 size_t wxStringBase
::find_last_not_of(const wxChar
* sz
, size_t nStart
,
704 return find_last_not_of(wxStringBase(sz
, n
), nStart
);
707 size_t wxStringBase
::find_last_not_of(wxChar ch
, size_t nStart
) const
709 if ( nStart
== npos
)
711 nStart
= length() - 1;
715 wxASSERT( nStart
<= length() );
718 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
727 wxStringBase
& wxStringBase
::replace(size_t nStart
, size_t nLen
,
730 wxASSERT_MSG( nStart
<= length(),
731 _T("index out of bounds in wxStringBase::replace") );
732 size_t strLen
= length() - nStart
;
733 nLen
= strLen
< nLen ? strLen
: nLen
;
736 strTmp
.reserve(length()); // micro optimisation to avoid multiple mem allocs
738 //This is kind of inefficient, but its pretty good considering...
739 //we don't want to use character access operators here because on STL
740 //it will freeze the reference count of strTmp, which means a deep copy
741 //at the end when swap is called
743 //Also, we can't use append with the full character pointer and must
744 //do it manually because this string can contain null characters
747 for(size_t i1
= 0; i1
< nStart
; ++i1
)
748 strTmp
.append(1, this->c_str()[i1
]);
751 //its safe to do the full version here because
752 //sz must be a normal c string
755 for(size_t i2
= nStart
+ nLen
; i2
< length(); ++i2
)
756 strTmp
.append(1, this->c_str()[i2
]);
762 wxStringBase
& wxStringBase
::replace(size_t nStart
, size_t nLen
,
763 size_t nCount
, wxChar ch
)
765 return replace(nStart
, nLen
, wxStringBase(nCount
, ch
).c_str());
768 wxStringBase
& wxStringBase
::replace(size_t nStart
, size_t nLen
,
769 const wxStringBase
& str
,
770 size_t nStart2
, size_t nLen2
)
772 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
775 wxStringBase
& wxStringBase
::replace(size_t nStart
, size_t nLen
,
776 const wxChar
* sz
, size_t nCount
)
778 return replace(nStart
, nLen
, wxStringBase(sz
, nCount
).c_str());
781 wxStringBase wxStringBase
::substr(size_t nStart
, size_t nLen
) const
784 nLen
= length() - nStart
;
785 return wxStringBase(*this, nStart
, nLen
);
788 // assigns one string to another
789 wxStringBase
& wxStringBase
::operator=(const wxStringBase
& stringSrc
)
791 wxASSERT( stringSrc
.GetStringData()->IsValid() );
793 // don't copy string over itself
794 if ( m_pchData
!= stringSrc
.m_pchData
) {
795 if ( stringSrc
.GetStringData()->IsEmpty() ) {
800 GetStringData()->Unlock();
801 m_pchData
= stringSrc
.m_pchData
;
802 GetStringData()->Lock();
809 // assigns a single character
810 wxStringBase
& wxStringBase
::operator=(wxChar ch
)
812 if ( !AssignCopy(1, &ch
) ) {
813 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(wxChar)") );
819 wxStringBase
& wxStringBase
::operator=(const wxChar
*psz
)
821 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
822 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(const wxChar *)") );
827 // helper function: does real copy
828 bool wxStringBase
::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
830 if ( nSrcLen
== 0 ) {
834 if ( !AllocBeforeWrite(nSrcLen
) ) {
835 // allocation failure handled by caller
838 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
839 GetStringData()->nDataLength
= nSrcLen
;
840 m_pchData
[nSrcLen
] = wxT('\0');
845 // ---------------------------------------------------------------------------
846 // string concatenation
847 // ---------------------------------------------------------------------------
849 // add something to this string
850 bool wxStringBase
::ConcatSelf(size_t nSrcLen
, const wxChar
*pszSrcData
,
853 STATISTICS_ADD(SummandLength
, nSrcLen
);
855 nSrcLen
= nSrcLen
< nMaxLen ? nSrcLen
: nMaxLen
;
857 // concatenating an empty string is a NOP
859 wxStringData
*pData
= GetStringData();
860 size_t nLen
= pData
->nDataLength
;
861 size_t nNewLen
= nLen
+ nSrcLen
;
863 // alloc new buffer if current is too small
864 if ( pData
->IsShared() ) {
865 STATISTICS_ADD(ConcatHit
, 0);
867 // we have to allocate another buffer
868 wxStringData
* pOldData
= GetStringData();
869 if ( !AllocBuffer(nNewLen
) ) {
870 // allocation failure handled by caller
873 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
876 else if ( nNewLen
> pData
->nAllocLength
) {
877 STATISTICS_ADD(ConcatHit
, 0);
880 // we have to grow the buffer
881 if ( capacity() < nNewLen
) {
882 // allocation failure handled by caller
887 STATISTICS_ADD(ConcatHit
, 1);
889 // the buffer is already big enough
892 // should be enough space
893 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
895 // fast concatenation - all is done in our buffer
896 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
898 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
899 GetStringData()->nDataLength
= nNewLen
; // and fix the length
901 //else: the string to append was empty
905 // ---------------------------------------------------------------------------
906 // simple sub-string extraction
907 // ---------------------------------------------------------------------------
909 // helper function: clone the data attached to this string
910 bool wxStringBase
::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
912 if ( nCopyLen
== 0 ) {
916 if ( !dest
.AllocBuffer(nCopyLen
) ) {
917 // allocation failure handled by caller
920 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
927 #if !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
930 #define STRINGCLASS wxStringBase
932 #define STRINGCLASS wxString
935 static inline int wxDoCmp(const wxChar
* s1
, size_t l1
,
936 const wxChar
* s2
, size_t l2
)
939 return wxTmemcmp(s1
, s2
, l1
);
942 int ret
= wxTmemcmp(s1
, s2
, l1
);
943 return ret
== 0 ?
-1 : ret
;
947 int ret
= wxTmemcmp(s1
, s2
, l2
);
948 return ret
== 0 ?
+1 : ret
;
952 int STRINGCLASS
::compare(const wxStringBase
& str
) const
954 return ::wxDoCmp(data(), length(), str
.data(), str
.length());
957 int STRINGCLASS
::compare(size_t nStart
, size_t nLen
,
958 const wxStringBase
& str
) const
960 wxASSERT(nStart
<= length());
961 size_type strLen
= length() - nStart
;
962 nLen
= strLen
< nLen ? strLen
: nLen
;
963 return ::wxDoCmp(data() + nStart
, nLen
, str
.data(), str
.length());
966 int STRINGCLASS
::compare(size_t nStart
, size_t nLen
,
967 const wxStringBase
& str
,
968 size_t nStart2
, size_t nLen2
) const
970 wxASSERT(nStart
<= length());
971 wxASSERT(nStart2
<= str
.length());
972 size_type strLen
= length() - nStart
,
973 strLen2
= str
.length() - nStart2
;
974 nLen
= strLen
< nLen ? strLen
: nLen
;
975 nLen2
= strLen2
< nLen2 ? strLen2
: nLen2
;
976 return ::wxDoCmp(data() + nStart
, nLen
, str
.data() + nStart2
, nLen2
);
979 int STRINGCLASS
::compare(const wxChar
* sz
) const
981 size_t nLen
= wxStrlen(sz
);
982 return ::wxDoCmp(data(), length(), sz
, nLen
);
985 int STRINGCLASS
::compare(size_t nStart
, size_t nLen
,
986 const wxChar
* sz
, size_t nCount
) const
988 wxASSERT(nStart
<= length());
989 size_type strLen
= length() - nStart
;
990 nLen
= strLen
< nLen ? strLen
: nLen
;
992 nCount
= wxStrlen(sz
);
994 return ::wxDoCmp(data() + nStart
, nLen
, sz
, nCount
);
999 #endif // !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
1001 // ===========================================================================
1002 // wxString class core
1003 // ===========================================================================
1005 // ---------------------------------------------------------------------------
1006 // construction and conversion
1007 // ---------------------------------------------------------------------------
1011 // from multibyte string
1012 wxString
::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
1014 // if nLength != npos, then we have to make a NULL-terminated copy
1015 // of first nLength bytes of psz first because the input buffer to MB2WC
1016 // must always be NULL-terminated:
1017 wxCharBuffer
inBuf((const char *)NULL
);
1018 if (nLength
!= npos
)
1020 wxASSERT( psz
!= NULL
);
1021 wxCharBuffer
tmp(nLength
);
1022 memcpy(tmp
.data(), psz
, nLength
);
1023 tmp
.data()[nLength
] = '\0';
1028 // first get the size of the buffer we need
1032 // calculate the needed size ourselves or use the provided one
1033 if (nLength
== npos
)
1040 // nothing to convert
1046 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
1050 wxWCharBuffer theBuffer
= conv
.cMB2WC(psz
, nLen
, &nRealSize
);
1054 assign( theBuffer
.data() , nRealSize
- 1 );
1058 //Convert wxString in Unicode mode to a multi-byte string
1059 const wxCharBuffer wxString
::mb_str(wxMBConv
& conv
) const
1062 return conv
.cWC2MB(c_str(), length(), &dwOutSize
);
1069 wxString
::wxString(const wchar_t *pwz
, wxMBConv
& conv
, size_t nLength
)
1071 // if nLength != npos, then we have to make a NULL-terminated copy
1072 // of first nLength chars of psz first because the input buffer to WC2MB
1073 // must always be NULL-terminated:
1074 wxWCharBuffer
inBuf((const wchar_t *)NULL
);
1075 if (nLength
!= npos
)
1077 wxASSERT( pwz
!= NULL
);
1078 wxWCharBuffer
tmp(nLength
);
1079 memcpy(tmp
.data(), pwz
, nLength
* sizeof(wchar_t));
1080 tmp
.data()[nLength
] = '\0';
1085 // first get the size of the buffer we need
1089 // calculate the needed size ourselves or use the provided one
1090 if (nLength
== npos
)
1091 nLen
= wxWcslen(pwz
);
1097 // nothing to convert
1102 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
1106 wxCharBuffer theBuffer
= conv
.cWC2MB(pwz
, nLen
, &nRealSize
);
1110 assign( theBuffer
.data() , nRealSize
- 1 );
1114 //Converts this string to a wide character string if unicode
1115 //mode is not enabled and wxUSE_WCHAR_T is enabled
1116 const wxWCharBuffer wxString
::wc_str(wxMBConv
& conv
) const
1119 return conv
.cMB2WC(c_str(), length(), &dwOutSize
);
1122 #endif // wxUSE_WCHAR_T
1124 #endif // Unicode/ANSI
1126 // shrink to minimal size (releasing extra memory)
1127 bool wxString
::Shrink()
1129 wxString
tmp(begin(), end());
1131 return tmp
.length() == length();
1135 // get the pointer to writable buffer of (at least) nLen bytes
1136 wxChar
*wxString
::GetWriteBuf(size_t nLen
)
1138 if ( !AllocBeforeWrite(nLen
) ) {
1139 // allocation failure handled by caller
1143 wxASSERT( GetStringData()->nRefs
== 1 );
1144 GetStringData()->Validate(false);
1149 // put string back in a reasonable state after GetWriteBuf
1150 void wxString
::UngetWriteBuf()
1152 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
1153 GetStringData()->Validate(true);
1156 void wxString
::UngetWriteBuf(size_t nLen
)
1158 GetStringData()->nDataLength
= nLen
;
1159 GetStringData()->Validate(true);
1163 // ---------------------------------------------------------------------------
1165 // ---------------------------------------------------------------------------
1167 // all functions are inline in string.h
1169 // ---------------------------------------------------------------------------
1170 // assignment operators
1171 // ---------------------------------------------------------------------------
1175 // same as 'signed char' variant
1176 wxString
& wxString
::operator=(const unsigned char* psz
)
1178 *this = (const char *)psz
;
1183 wxString
& wxString
::operator=(const wchar_t *pwz
)
1194 * concatenation functions come in 5 flavours:
1196 * char + string and string + char
1197 * C str + string and string + C str
1200 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
1203 wxASSERT( str1
.GetStringData()->IsValid() );
1204 wxASSERT( str2
.GetStringData()->IsValid() );
1213 wxString
operator+(const wxString
& str
, wxChar ch
)
1216 wxASSERT( str
.GetStringData()->IsValid() );
1225 wxString
operator+(wxChar ch
, const wxString
& str
)
1228 wxASSERT( str
.GetStringData()->IsValid() );
1237 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
1240 wxASSERT( str
.GetStringData()->IsValid() );
1244 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
1245 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1253 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
1256 wxASSERT( str
.GetStringData()->IsValid() );
1260 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
1261 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1269 // ===========================================================================
1270 // other common string functions
1271 // ===========================================================================
1273 int wxString
::Cmp(const wxString
& s
) const
1278 int wxString
::Cmp(const wxChar
* psz
) const
1280 return compare(psz
);
1283 static inline int wxDoCmpNoCase(const wxChar
* s1
, size_t l1
,
1284 const wxChar
* s2
, size_t l2
)
1290 for(i
= 0; i
< l1
; ++i
)
1292 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1295 return i
== l1 ?
0 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ?
-1 : 1;
1299 for(i
= 0; i
< l1
; ++i
)
1301 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1304 return i
== l1 ?
-1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ?
-1 : 1;
1308 for(i
= 0; i
< l2
; ++i
)
1310 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1313 return i
== l2 ?
1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ?
-1 : 1;
1317 int wxString
::CmpNoCase(const wxString
& s
) const
1319 return wxDoCmpNoCase(data(), length(), s
.data(), s
.length());
1322 int wxString
::CmpNoCase(const wxChar
* psz
) const
1324 int nLen
= wxStrlen(psz
);
1326 return wxDoCmpNoCase(data(), length(), psz
, nLen
);
1333 #ifndef __SCHAR_MAX__
1334 #define __SCHAR_MAX__ 127
1338 wxString wxString
::FromAscii(const char *ascii
)
1341 return wxEmptyString
;
1343 size_t len
= strlen( ascii
);
1348 wxStringBuffer
buf(res
, len
);
1350 wchar_t *dest
= buf
;
1354 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
1362 wxString wxString
::FromAscii(const char ascii
)
1364 // What do we do with '\0' ?
1367 res
+= (wchar_t)(unsigned char) ascii
;
1372 const wxCharBuffer wxString
::ToAscii() const
1374 // this will allocate enough space for the terminating NUL too
1375 wxCharBuffer
buffer(length());
1378 char *dest
= buffer
.data();
1380 const wchar_t *pwc
= c_str();
1383 *dest
++ = (char)(*pwc
> SCHAR_MAX ?
wxT('_') : *pwc
);
1385 // the output string can't have embedded NULs anyhow, so we can safely
1386 // stop at first of them even if we do have any
1396 // extract string of length nCount starting at nFirst
1397 wxString wxString
::Mid(size_t nFirst
, size_t nCount
) const
1399 size_t nLen
= length();
1401 // default value of nCount is npos and means "till the end"
1402 if ( nCount
== npos
)
1404 nCount
= nLen
- nFirst
;
1407 // out-of-bounds requests return sensible things
1408 if ( nFirst
+ nCount
> nLen
)
1410 nCount
= nLen
- nFirst
;
1413 if ( nFirst
> nLen
)
1415 // AllocCopy() will return empty string
1419 wxString
dest(*this, nFirst
, nCount
);
1420 if ( dest
.length() != nCount
) {
1421 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
1427 // check that the string starts with prefix and return the rest of the string
1428 // in the provided pointer if it is not NULL, otherwise return false
1429 bool wxString
::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
1431 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
1433 // first check if the beginning of the string matches the prefix: note
1434 // that we don't have to check that we don't run out of this string as
1435 // when we reach the terminating NUL, either prefix string ends too (and
1436 // then it's ok) or we break out of the loop because there is no match
1437 const wxChar
*p
= c_str();
1440 if ( *prefix
++ != *p
++ )
1449 // put the rest of the string into provided pointer
1456 // extract nCount last (rightmost) characters
1457 wxString wxString
::Right(size_t nCount
) const
1459 if ( nCount
> length() )
1462 wxString
dest(*this, length() - nCount
, nCount
);
1463 if ( dest
.length() != nCount
) {
1464 wxFAIL_MSG( _T("out of memory in wxString::Right") );
1469 // get all characters after the last occurence of ch
1470 // (returns the whole string if ch not found)
1471 wxString wxString
::AfterLast(wxChar ch
) const
1474 int iPos
= Find(ch
, true);
1475 if ( iPos
== wxNOT_FOUND
)
1478 str
= c_str() + iPos
+ 1;
1483 // extract nCount first (leftmost) characters
1484 wxString wxString
::Left(size_t nCount
) const
1486 if ( nCount
> length() )
1489 wxString
dest(*this, 0, nCount
);
1490 if ( dest
.length() != nCount
) {
1491 wxFAIL_MSG( _T("out of memory in wxString::Left") );
1496 // get all characters before the first occurence of ch
1497 // (returns the whole string if ch not found)
1498 wxString wxString
::BeforeFirst(wxChar ch
) const
1500 int iPos
= Find(ch
);
1501 if ( iPos
== wxNOT_FOUND
) iPos
= length();
1502 return wxString(*this, 0, iPos
);
1505 /// get all characters before the last occurence of ch
1506 /// (returns empty string if ch not found)
1507 wxString wxString
::BeforeLast(wxChar ch
) const
1510 int iPos
= Find(ch
, true);
1511 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
1512 str
= wxString(c_str(), iPos
);
1517 /// get all characters after the first occurence of ch
1518 /// (returns empty string if ch not found)
1519 wxString wxString
::AfterFirst(wxChar ch
) const
1522 int iPos
= Find(ch
);
1523 if ( iPos
!= wxNOT_FOUND
)
1524 str
= c_str() + iPos
+ 1;
1529 // replace first (or all) occurences of some substring with another one
1530 size_t wxString
::Replace(const wxChar
*szOld
,
1531 const wxChar
*szNew
, bool bReplaceAll
)
1533 // if we tried to replace an empty string we'd enter an infinite loop below
1534 wxCHECK_MSG( szOld
&& *szOld
&& szNew
, 0,
1535 _T("wxString::Replace(): invalid parameter") );
1537 size_t uiCount
= 0; // count of replacements made
1539 size_t uiOldLen
= wxStrlen(szOld
);
1540 size_t uiNewLen
= wxStrlen(szNew
);
1544 while ( this->c_str()[dwPos
] != wxT('\0') )
1546 //DO NOT USE STRSTR HERE
1547 //this string can contain embedded null characters,
1548 //so strstr will function incorrectly
1549 dwPos
= find(szOld
, dwPos
);
1550 if ( dwPos
== npos
)
1551 break; // exit the loop
1554 //replace this occurance of the old string with the new one
1555 replace(dwPos
, uiOldLen
, szNew
, uiNewLen
);
1557 //move up pos past the old string
1560 //increase replace count
1565 break; // exit the loop
1572 bool wxString
::IsAscii() const
1574 const wxChar
*s
= (const wxChar
*) *this;
1576 if(!isascii(*s
)) return(false);
1582 bool wxString
::IsWord() const
1584 const wxChar
*s
= (const wxChar
*) *this;
1586 if(!wxIsalpha(*s
)) return(false);
1592 bool wxString
::IsNumber() const
1594 const wxChar
*s
= (const wxChar
*) *this;
1596 if ((s
[0] == wxT('-')) || (s
[0] == wxT('+'))) s
++;
1598 if(!wxIsdigit(*s
)) return(false);
1604 wxString wxString
::Strip(stripType w
) const
1607 if ( w
& leading
) s
.Trim(false);
1608 if ( w
& trailing
) s
.Trim(true);
1612 // ---------------------------------------------------------------------------
1614 // ---------------------------------------------------------------------------
1616 wxString
& wxString
::MakeUpper()
1618 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1619 *it
= (wxChar
)wxToupper(*it
);
1624 wxString
& wxString
::MakeLower()
1626 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1627 *it
= (wxChar
)wxTolower(*it
);
1632 // ---------------------------------------------------------------------------
1633 // trimming and padding
1634 // ---------------------------------------------------------------------------
1636 // some compilers (VC++ 6.0 not to name them) return true for a call to
1637 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1638 // live with this by checking that the character is a 7 bit one - even if this
1639 // may fail to detect some spaces (I don't know if Unicode doesn't have
1640 // space-like symbols somewhere except in the first 128 chars), it is arguably
1641 // still better than trimming away accented letters
1642 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1644 // trims spaces (in the sense of isspace) from left or right side
1645 wxString
& wxString
::Trim(bool bFromRight
)
1647 // first check if we're going to modify the string at all
1650 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1651 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1657 // find last non-space character
1658 iterator psz
= begin() + length() - 1;
1659 while ( wxSafeIsspace(*psz
) && (psz
>= begin()) )
1662 // truncate at trailing space start
1668 // find first non-space character
1669 iterator psz
= begin();
1670 while ( wxSafeIsspace(*psz
) )
1673 // fix up data and length
1674 erase(begin(), psz
);
1681 // adds nCount characters chPad to the string from either side
1682 wxString
& wxString
::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1684 wxString
s(chPad
, nCount
);
1697 // truncate the string
1698 wxString
& wxString
::Truncate(size_t uiLen
)
1700 if ( uiLen
< Len() ) {
1701 erase(begin() + uiLen
, end());
1703 //else: nothing to do, string is already short enough
1708 // ---------------------------------------------------------------------------
1709 // finding (return wxNOT_FOUND if not found and index otherwise)
1710 // ---------------------------------------------------------------------------
1713 int wxString
::Find(wxChar ch
, bool bFromEnd
) const
1715 size_type idx
= bFromEnd ?
find_last_of(ch
) : find_first_of(ch
);
1717 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1720 // find a sub-string (like strstr)
1721 int wxString
::Find(const wxChar
*pszSub
) const
1723 size_type idx
= find(pszSub
);
1725 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1728 // ----------------------------------------------------------------------------
1729 // conversion to numbers
1730 // ----------------------------------------------------------------------------
1732 bool wxString
::ToLong(long *val
, int base
) const
1734 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToLong") );
1735 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1737 const wxChar
*start
= c_str();
1739 *val
= wxStrtol(start
, &end
, base
);
1741 // return true only if scan was stopped by the terminating NUL and if the
1742 // string was not empty to start with
1743 return !*end
&& (end
!= start
);
1746 bool wxString
::ToULong(unsigned long *val
, int base
) const
1748 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToULong") );
1749 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1751 const wxChar
*start
= c_str();
1753 *val
= wxStrtoul(start
, &end
, base
);
1755 // return true only if scan was stopped by the terminating NUL and if the
1756 // string was not empty to start with
1757 return !*end
&& (end
!= start
);
1760 bool wxString
::ToDouble(double *val
) const
1762 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToDouble") );
1764 const wxChar
*start
= c_str();
1766 *val
= wxStrtod(start
, &end
);
1768 // return true only if scan was stopped by the terminating NUL and if the
1769 // string was not empty to start with
1770 return !*end
&& (end
!= start
);
1773 // ---------------------------------------------------------------------------
1775 // ---------------------------------------------------------------------------
1778 wxString wxString
::Format(const wxChar
*pszFormat
, ...)
1781 va_start(argptr
, pszFormat
);
1784 s
.PrintfV(pszFormat
, argptr
);
1792 wxString wxString
::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1795 s
.PrintfV(pszFormat
, argptr
);
1799 int wxString
::Printf(const wxChar
*pszFormat
, ...)
1802 va_start(argptr
, pszFormat
);
1804 int iLen
= PrintfV(pszFormat
, argptr
);
1811 int wxString
::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1817 wxStringBuffer
tmp(*this, size
+ 1);
1826 // wxVsnprintf() may modify the original arg pointer, so pass it
1829 wxVaCopy(argptrcopy
, argptr
);
1830 int len
= wxVsnprintf(buf
, size
, pszFormat
, argptrcopy
);
1833 // some implementations of vsnprintf() don't NUL terminate
1834 // the string if there is not enough space for it so
1835 // always do it manually
1836 buf
[size
] = _T('\0');
1838 // vsnprintf() may return either -1 (traditional Unix behaviour) or the
1839 // total number of characters which would have been written if the
1840 // buffer were large enough
1841 // also, it may return an errno may be something like EILSEQ,
1842 // in which case we need to break out
1843 if ( (len
>= 0 && len
<= size
)
1844 // No EOVERFLOW on Windows nor Palm 6.0 nor OpenVMS nor MacOS (not X)
1845 // not OS/2 (not Innotek libc).
1846 #if !defined(__WXMSW__) && !defined(__WXPALMOS__) && !defined( __VMS ) && !(defined(__WXMAC__) && !defined(__WXMAC_OSX__)) && !(defined(__EMX__) && !defined(__INNOTEK_LIBC__))
1847 || errno
!= EOVERFLOW
1851 // ok, there was enough space
1855 // still not enough, double it again
1859 // we could have overshot
1865 // ----------------------------------------------------------------------------
1866 // misc other operations
1867 // ----------------------------------------------------------------------------
1869 // returns true if the string matches the pattern which may contain '*' and
1870 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1872 bool wxString
::Matches(const wxChar
*pszMask
) const
1874 // I disable this code as it doesn't seem to be faster (in fact, it seems
1875 // to be much slower) than the old, hand-written code below and using it
1876 // here requires always linking with libregex even if the user code doesn't
1878 #if 0 // wxUSE_REGEX
1879 // first translate the shell-like mask into a regex
1881 pattern
.reserve(wxStrlen(pszMask
));
1893 pattern
+= _T(".*");
1904 // these characters are special in a RE, quote them
1905 // (however note that we don't quote '[' and ']' to allow
1906 // using them for Unix shell like matching)
1907 pattern
+= _T('\\');
1911 pattern
+= *pszMask
;
1919 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1920 #else // !wxUSE_REGEX
1921 // TODO: this is, of course, awfully inefficient...
1923 // the char currently being checked
1924 const wxChar
*pszTxt
= c_str();
1926 // the last location where '*' matched
1927 const wxChar
*pszLastStarInText
= NULL
;
1928 const wxChar
*pszLastStarInMask
= NULL
;
1931 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1932 switch ( *pszMask
) {
1934 if ( *pszTxt
== wxT('\0') )
1937 // pszTxt and pszMask will be incremented in the loop statement
1943 // remember where we started to be able to backtrack later
1944 pszLastStarInText
= pszTxt
;
1945 pszLastStarInMask
= pszMask
;
1947 // ignore special chars immediately following this one
1948 // (should this be an error?)
1949 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1952 // if there is nothing more, match
1953 if ( *pszMask
== wxT('\0') )
1956 // are there any other metacharacters in the mask?
1958 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1960 if ( pEndMask
!= NULL
) {
1961 // we have to match the string between two metachars
1962 uiLenMask
= pEndMask
- pszMask
;
1965 // we have to match the remainder of the string
1966 uiLenMask
= wxStrlen(pszMask
);
1969 wxString
strToMatch(pszMask
, uiLenMask
);
1970 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1971 if ( pMatch
== NULL
)
1974 // -1 to compensate "++" in the loop
1975 pszTxt
= pMatch
+ uiLenMask
- 1;
1976 pszMask
+= uiLenMask
- 1;
1981 if ( *pszMask
!= *pszTxt
)
1987 // match only if nothing left
1988 if ( *pszTxt
== wxT('\0') )
1991 // if we failed to match, backtrack if we can
1992 if ( pszLastStarInText
) {
1993 pszTxt
= pszLastStarInText
+ 1;
1994 pszMask
= pszLastStarInMask
;
1996 pszLastStarInText
= NULL
;
1998 // don't bother resetting pszLastStarInMask, it's unnecessary
2004 #endif // wxUSE_REGEX/!wxUSE_REGEX
2007 // Count the number of chars
2008 int wxString
::Freq(wxChar ch
) const
2012 for (int i
= 0; i
< len
; i
++)
2014 if (GetChar(i
) == ch
)
2020 // convert to upper case, return the copy of the string
2021 wxString wxString
::Upper() const
2022 { wxString
s(*this); return s
.MakeUpper(); }
2024 // convert to lower case, return the copy of the string
2025 wxString wxString
::Lower() const { wxString
s(*this); return s
.MakeLower(); }
2027 int wxString
::sprintf(const wxChar
*pszFormat
, ...)
2030 va_start(argptr
, pszFormat
);
2031 int iLen
= PrintfV(pszFormat
, argptr
);
2036 // ============================================================================
2038 // ============================================================================
2040 #include "wx/arrstr.h"
2042 wxArrayString
::wxArrayString(size_t sz
, const wxChar
** a
)
2047 for (size_t i
=0; i
< sz
; i
++)
2051 wxArrayString
::wxArrayString(size_t sz
, const wxString
* a
)
2056 for (size_t i
=0; i
< sz
; i
++)
2062 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
2063 #define ARRAY_MAXSIZE_INCREMENT 4096
2065 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
2066 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
2069 #define STRING(p) ((wxString *)(&(p)))
2072 void wxArrayString
::Init(bool autoSort
)
2076 m_pItems
= (wxChar
**) NULL
;
2077 m_autoSort
= autoSort
;
2081 wxArrayString
::wxArrayString(const wxArrayString
& src
)
2083 Init(src
.m_autoSort
);
2088 // assignment operator
2089 wxArrayString
& wxArrayString
::operator=(const wxArrayString
& src
)
2096 m_autoSort
= src
.m_autoSort
;
2101 void wxArrayString
::Copy(const wxArrayString
& src
)
2103 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
2104 Alloc(src
.m_nCount
);
2106 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
2111 void wxArrayString
::Grow(size_t nIncrement
)
2113 // only do it if no more place
2114 if ( (m_nSize
- m_nCount
) < nIncrement
) {
2115 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2116 // be never resized!
2117 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2118 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2121 if ( m_nSize
== 0 ) {
2122 // was empty, alloc some memory
2123 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
2124 if (m_nSize
< nIncrement
)
2125 m_nSize
= nIncrement
;
2126 m_pItems
= new wxChar
*[m_nSize
];
2129 // otherwise when it's called for the first time, nIncrement would be 0
2130 // and the array would never be expanded
2131 // add 50% but not too much
2132 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
2133 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
2134 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
2135 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
2136 if ( nIncrement
< ndefIncrement
)
2137 nIncrement
= ndefIncrement
;
2138 m_nSize
+= nIncrement
;
2139 wxChar
**pNew
= new wxChar
*[m_nSize
];
2141 // copy data to new location
2142 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2144 // delete old memory (but do not release the strings!)
2145 wxDELETEA(m_pItems
);
2152 void wxArrayString
::Free()
2154 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
2155 STRING(m_pItems
[n
])->GetStringData()->Unlock();
2159 // deletes all the strings from the list
2160 void wxArrayString
::Empty()
2167 // as Empty, but also frees memory
2168 void wxArrayString
::Clear()
2175 wxDELETEA(m_pItems
);
2179 wxArrayString
::~wxArrayString()
2183 wxDELETEA(m_pItems
);
2186 void wxArrayString
::reserve(size_t nSize
)
2191 // pre-allocates memory (frees the previous data!)
2192 void wxArrayString
::Alloc(size_t nSize
)
2194 // only if old buffer was not big enough
2195 if ( nSize
> m_nSize
) {
2197 wxDELETEA(m_pItems
);
2198 m_pItems
= new wxChar
*[nSize
];
2205 // minimizes the memory usage by freeing unused memory
2206 void wxArrayString
::Shrink()
2208 // only do it if we have some memory to free
2209 if( m_nCount
< m_nSize
) {
2210 // allocates exactly as much memory as we need
2211 wxChar
**pNew
= new wxChar
*[m_nCount
];
2213 // copy data to new location
2214 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2220 #if WXWIN_COMPATIBILITY_2_4
2222 // return a wxString[] as required for some control ctors.
2223 wxString
* wxArrayString
::GetStringArray() const
2225 wxString
*array
= 0;
2229 array
= new wxString
[m_nCount
];
2230 for( size_t i
= 0; i
< m_nCount
; i
++ )
2231 array
[i
] = m_pItems
[i
];
2237 void wxArrayString
::Remove(size_t nIndex
, size_t nRemove
)
2239 RemoveAt(nIndex
, nRemove
);
2242 #endif // WXWIN_COMPATIBILITY_2_4
2244 // searches the array for an item (forward or backwards)
2245 int wxArrayString
::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2248 // use binary search in the sorted array
2249 wxASSERT_MSG( bCase
&& !bFromEnd
,
2250 wxT("search parameters ignored for auto sorted array") );
2259 res
= wxStrcmp(sz
, m_pItems
[i
]);
2271 // use linear search in unsorted array
2273 if ( m_nCount
> 0 ) {
2274 size_t ui
= m_nCount
;
2276 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2283 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2284 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2293 // add item at the end
2294 size_t wxArrayString
::Add(const wxString
& str
, size_t nInsert
)
2297 // insert the string at the correct position to keep the array sorted
2305 res
= str
.Cmp(m_pItems
[i
]);
2316 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2318 Insert(str
, lo
, nInsert
);
2323 wxASSERT( str
.GetStringData()->IsValid() );
2327 for (size_t i
= 0; i
< nInsert
; i
++)
2329 // the string data must not be deleted!
2330 str
.GetStringData()->Lock();
2333 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2335 size_t ret
= m_nCount
;
2336 m_nCount
+= nInsert
;
2341 // add item at the given position
2342 void wxArrayString
::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2344 wxASSERT( str
.GetStringData()->IsValid() );
2346 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2347 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2348 wxT("array size overflow in wxArrayString::Insert") );
2352 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2353 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2355 for (size_t i
= 0; i
< nInsert
; i
++)
2357 str
.GetStringData()->Lock();
2358 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2360 m_nCount
+= nInsert
;
2363 // range insert (STL 23.2.4.3)
2365 wxArrayString
::insert(iterator it
, const_iterator first
, const_iterator last
)
2367 const int idx
= it
- begin();
2372 // reset "it" since it can change inside Grow()
2375 while ( first
!= last
)
2377 it
= insert(it
, *first
);
2379 // insert returns an iterator to the last element inserted but we need
2380 // insert the next after this one, that is before the next one
2388 void wxArrayString
::SetCount(size_t count
)
2393 while ( m_nCount
< count
)
2394 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2397 // removes item from array (by index)
2398 void wxArrayString
::RemoveAt(size_t nIndex
, size_t nRemove
)
2400 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2401 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2402 wxT("removing too many elements in wxArrayString::Remove") );
2405 for (size_t i
= 0; i
< nRemove
; i
++)
2406 Item(nIndex
+ i
).GetStringData()->Unlock();
2408 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2409 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
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
= NULL
;
2442 // call this before the value of the global sort vars is changed/after
2443 // you're finished with them
2444 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2445 gs_critsectStringSort = new wxCriticalSection; \
2446 gs_critsectStringSort->Enter()
2447 #define END_SORT() gs_critsectStringSort->Leave(); \
2448 delete gs_critsectStringSort; \
2449 gs_critsectStringSort = NULL
2451 #define START_SORT()
2453 #endif // wxUSE_THREADS
2455 // function to use for string comparaison
2456 static wxArrayString
::CompareFunction gs_compareFunction
= NULL
;
2458 // if we don't use the compare function, this flag tells us if we sort the
2459 // array in ascending or descending order
2460 static bool gs_sortAscending
= true;
2462 // function which is called by quick sort
2463 extern "C" int wxC_CALLING_CONV
// LINKAGEMODE
2464 wxStringCompareFunction(const void *first
, const void *second
)
2466 wxString
*strFirst
= (wxString
*)first
;
2467 wxString
*strSecond
= (wxString
*)second
;
2469 if ( gs_compareFunction
) {
2470 return gs_compareFunction(*strFirst
, *strSecond
);
2473 // maybe we should use wxStrcoll
2474 int result
= strFirst
->Cmp(*strSecond
);
2476 return gs_sortAscending ? result
: -result
;
2480 // sort array elements using passed comparaison function
2481 void wxArrayString
::Sort(CompareFunction compareFunction
)
2485 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2486 gs_compareFunction
= compareFunction
;
2490 // reset it to NULL so that Sort(bool) will work the next time
2491 gs_compareFunction
= NULL
;
2496 typedef int (wxC_CALLING_CONV
* wxStringCompareFn
)(const void *first
, const void *second
);
2498 void wxArrayString
::Sort(CompareFunction2 compareFunction
)
2500 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), (wxStringCompareFn
)compareFunction
);
2503 void wxArrayString
::Sort(bool reverseOrder
)
2505 Sort(reverseOrder ? wxStringSortDescending
: wxStringSortAscending
);
2508 void wxArrayString
::DoSort()
2510 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2512 // just sort the pointers using qsort() - of course it only works because
2513 // wxString() *is* a pointer to its data
2514 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2517 bool wxArrayString
::operator==(const wxArrayString
& a
) const
2519 if ( m_nCount
!= a
.m_nCount
)
2522 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2524 if ( Item(n
) != a
[n
] )
2531 #endif // !wxUSE_STL
2533 int wxCMPFUNC_CONV
wxStringSortAscending(wxString
* s1
, wxString
* s2
)
2535 return s1
->Cmp(*s2
);
2538 int wxCMPFUNC_CONV
wxStringSortDescending(wxString
* s1
, wxString
* s2
)
2540 return -s1
->Cmp(*s2
);