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"
54 // allocating extra space for each string consumes more memory but speeds up
55 // the concatenation operations (nLen is the current string's length)
56 // NB: EXTRA_ALLOC must be >= 0!
57 #define EXTRA_ALLOC (19 - nLen % 16)
59 // ---------------------------------------------------------------------------
60 // static class variables definition
61 // ---------------------------------------------------------------------------
64 //According to STL _must_ be a -1 size_t
65 const size_t wxStringBase::npos
= (size_t) -1;
68 // ----------------------------------------------------------------------------
70 // ----------------------------------------------------------------------------
74 extern const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= _T("");
78 // for an empty string, GetStringData() will return this address: this
79 // structure has the same layout as wxStringData and it's data() method will
80 // return the empty string (dummy pointer)
85 } g_strEmpty
= { {-1, 0, 0}, wxT('\0') };
87 // empty C style string: points to 'string data' byte of g_strEmpty
88 extern const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= &g_strEmpty
.dummy
;
92 // ----------------------------------------------------------------------------
94 // ----------------------------------------------------------------------------
96 #if wxUSE_STD_IOSTREAM
98 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
101 // ATTN: you can _not_ use both of these in the same program!
105 wxSTD istream
& operator>>(wxSTD istream
& is
, wxString
& WXUNUSED(str
))
110 streambuf
*sb
= is
.rdbuf();
113 int ch
= sb
->sbumpc ();
115 is
.setstate(ios::eofbit
);
118 else if ( isspace(ch
) ) {
130 if ( str
.length() == 0 )
131 is
.setstate(ios::failbit
);
136 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
142 #endif // wxUSE_STD_IOSTREAM
144 // ----------------------------------------------------------------------------
146 // ----------------------------------------------------------------------------
148 // this small class is used to gather statistics for performance tuning
149 //#define WXSTRING_STATISTICS
150 #ifdef WXSTRING_STATISTICS
154 Averager(const wxChar
*sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
156 { wxPrintf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
158 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
161 size_t m_nCount
, m_nTotal
;
163 } g_averageLength("allocation size"),
164 g_averageSummandLength("summand length"),
165 g_averageConcatHit("hit probability in concat"),
166 g_averageInitialLength("initial string length");
168 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
170 #define STATISTICS_ADD(av, val)
171 #endif // WXSTRING_STATISTICS
175 // ===========================================================================
176 // wxStringData class deallocation
177 // ===========================================================================
179 #if defined(__VISUALC__) && defined(_MT) && !defined(_DLL)
180 # pragma message (__FILE__ ": building with Multithreaded non DLL runtime has a performance impact on wxString!")
181 void wxStringData::Free()
187 // ===========================================================================
189 // ===========================================================================
191 // takes nLength elements of psz starting at nPos
192 void wxStringBase::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
196 // if the length is not given, assume the string to be NUL terminated
197 if ( nLength
== npos
) {
198 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
200 nLength
= wxStrlen(psz
+ nPos
);
203 STATISTICS_ADD(InitialLength
, nLength
);
206 // trailing '\0' is written in AllocBuffer()
207 if ( !AllocBuffer(nLength
) ) {
208 wxFAIL_MSG( _T("out of memory in wxStringBase::InitWith") );
211 wxTmemcpy(m_pchData
, psz
+ nPos
, nLength
);
215 // poor man's iterators are "void *" pointers
216 wxStringBase::wxStringBase(const void *pStart
, const void *pEnd
)
218 InitWith((const wxChar
*)pStart
, 0,
219 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
222 wxStringBase::wxStringBase(size_type n
, wxChar ch
)
228 // ---------------------------------------------------------------------------
230 // ---------------------------------------------------------------------------
232 // allocates memory needed to store a C string of length nLen
233 bool wxStringBase::AllocBuffer(size_t nLen
)
235 // allocating 0 sized buffer doesn't make sense, all empty strings should
237 wxASSERT( nLen
> 0 );
239 // make sure that we don't overflow
240 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
241 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
243 STATISTICS_ADD(Length
, nLen
);
246 // 1) one extra character for '\0' termination
247 // 2) sizeof(wxStringData) for housekeeping info
248 wxStringData
* pData
= (wxStringData
*)
249 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
251 if ( pData
== NULL
) {
252 // allocation failures are handled by the caller
257 pData
->nDataLength
= nLen
;
258 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
259 m_pchData
= pData
->data(); // data starts after wxStringData
260 m_pchData
[nLen
] = wxT('\0');
264 // must be called before changing this string
265 bool wxStringBase::CopyBeforeWrite()
267 wxStringData
* pData
= GetStringData();
269 if ( pData
->IsShared() ) {
270 pData
->Unlock(); // memory not freed because shared
271 size_t nLen
= pData
->nDataLength
;
272 if ( !AllocBuffer(nLen
) ) {
273 // allocation failures are handled by the caller
276 wxTmemcpy(m_pchData
, pData
->data(), nLen
);
279 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
284 // must be called before replacing contents of this string
285 bool wxStringBase::AllocBeforeWrite(size_t nLen
)
287 wxASSERT( nLen
!= 0 ); // doesn't make any sense
289 // must not share string and must have enough space
290 wxStringData
* pData
= GetStringData();
291 if ( pData
->IsShared() || pData
->IsEmpty() ) {
292 // can't work with old buffer, get new one
294 if ( !AllocBuffer(nLen
) ) {
295 // allocation failures are handled by the caller
300 if ( nLen
> pData
->nAllocLength
) {
301 // realloc the buffer instead of calling malloc() again, this is more
303 STATISTICS_ADD(Length
, nLen
);
307 pData
= (wxStringData
*)
308 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
310 if ( pData
== NULL
) {
311 // allocation failures are handled by the caller
312 // keep previous data since reallocation failed
316 pData
->nAllocLength
= nLen
;
317 m_pchData
= pData
->data();
321 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
323 // it doesn't really matter what the string length is as it's going to be
324 // overwritten later but, for extra safety, set it to 0 for now as we may
325 // have some junk in m_pchData
326 GetStringData()->nDataLength
= 0;
331 wxStringBase
& wxStringBase::append(size_t n
, wxChar ch
)
333 size_type len
= length();
335 if ( !Alloc(len
+ n
) || !CopyBeforeWrite() ) {
336 wxFAIL_MSG( _T("out of memory in wxStringBase::append") );
338 GetStringData()->nDataLength
= len
+ n
;
339 m_pchData
[len
+ n
] = '\0';
340 for ( size_t i
= 0; i
< n
; ++i
)
341 m_pchData
[len
+ i
] = ch
;
345 void wxStringBase::resize(size_t nSize
, wxChar ch
)
347 size_t len
= length();
351 erase(begin() + nSize
, end());
353 else if ( nSize
> len
)
355 append(nSize
- len
, ch
);
357 //else: we have exactly the specified length, nothing to do
360 // allocate enough memory for nLen characters
361 bool wxStringBase::Alloc(size_t nLen
)
363 wxStringData
*pData
= GetStringData();
364 if ( pData
->nAllocLength
<= nLen
) {
365 if ( pData
->IsEmpty() ) {
368 wxStringData
* pData
= (wxStringData
*)
369 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
371 if ( pData
== NULL
) {
372 // allocation failure handled by caller
377 pData
->nDataLength
= 0;
378 pData
->nAllocLength
= nLen
;
379 m_pchData
= pData
->data(); // data starts after wxStringData
380 m_pchData
[0u] = wxT('\0');
382 else if ( pData
->IsShared() ) {
383 pData
->Unlock(); // memory not freed because shared
384 size_t nOldLen
= pData
->nDataLength
;
385 if ( !AllocBuffer(nLen
) ) {
386 // allocation failure handled by caller
389 // +1 to copy the terminator, too
390 memcpy(m_pchData
, pData
->data(), (nOldLen
+1)*sizeof(wxChar
));
391 GetStringData()->nDataLength
= nOldLen
;
396 pData
= (wxStringData
*)
397 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
399 if ( pData
== NULL
) {
400 // allocation failure handled by caller
401 // keep previous data since reallocation failed
405 // it's not important if the pointer changed or not (the check for this
406 // is not faster than assigning to m_pchData in all cases)
407 pData
->nAllocLength
= nLen
;
408 m_pchData
= pData
->data();
411 //else: we've already got enough
415 wxStringBase::iterator
wxStringBase::begin()
422 wxStringBase::iterator
wxStringBase::end()
426 return m_pchData
+ length();
429 wxStringBase::iterator
wxStringBase::erase(iterator it
)
431 size_type idx
= it
- begin();
433 return begin() + idx
;
436 wxStringBase
& wxStringBase::erase(size_t nStart
, size_t nLen
)
438 wxASSERT(nStart
<= length());
439 size_t strLen
= length() - nStart
;
440 // delete nLen or up to the end of the string characters
441 nLen
= strLen
< nLen
? strLen
: nLen
;
442 wxString
strTmp(c_str(), nStart
);
443 strTmp
.append(c_str() + nStart
+ nLen
, length() - nStart
- nLen
);
449 wxStringBase
& wxStringBase::insert(size_t nPos
, const wxChar
*sz
, size_t n
)
451 wxASSERT( nPos
<= length() );
453 if ( n
== npos
) n
= wxStrlen(sz
);
454 if ( n
== 0 ) return *this;
456 if ( !Alloc(length() + n
) || !CopyBeforeWrite() ) {
457 wxFAIL_MSG( _T("out of memory in wxStringBase::insert") );
460 memmove(m_pchData
+ nPos
+ n
, m_pchData
+ nPos
,
461 (length() - nPos
) * sizeof(wxChar
));
462 memcpy(m_pchData
+ nPos
, sz
, n
* sizeof(wxChar
));
463 GetStringData()->nDataLength
= length() + n
;
464 m_pchData
[length()] = '\0';
469 void wxStringBase::swap(wxStringBase
& str
)
471 wxChar
* tmp
= str
.m_pchData
;
472 str
.m_pchData
= m_pchData
;
476 size_t wxStringBase::find(const wxStringBase
& str
, size_t nStart
) const
478 wxASSERT( str
.GetStringData()->IsValid() );
479 wxASSERT( nStart
<= length() );
482 const wxChar
* p
= (const wxChar
*)wxTmemchr(c_str() + nStart
,
489 while(p
- c_str() + str
.length() <= length() &&
490 wxTmemcmp(p
, str
.c_str(), str
.length()) )
492 //Previosly passed as the first argument to wxTmemchr,
493 //but C/C++ standard does not specify evaluation order
494 //of arguments to functions -
495 //http://embedded.com/showArticle.jhtml?articleID=9900607
499 p
= (const wxChar
*)wxTmemchr(p
,
501 length() - (p
- c_str()));
507 return (p
- c_str() + str
.length() <= length()) ? p
- c_str() : npos
;
510 size_t wxStringBase::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
512 return find(wxStringBase(sz
, n
), nStart
);
515 size_t wxStringBase::find(wxChar ch
, size_t nStart
) const
517 wxASSERT( nStart
<= length() );
519 const wxChar
*p
= (const wxChar
*)wxTmemchr(c_str() + nStart
, ch
, length() - nStart
);
521 return p
== NULL
? npos
: p
- c_str();
524 size_t wxStringBase::rfind(const wxStringBase
& str
, size_t nStart
) const
526 wxASSERT( str
.GetStringData()->IsValid() );
527 wxASSERT( nStart
== npos
|| nStart
<= length() );
529 if ( length() >= str
.length() )
531 // avoids a corner case later
532 if ( length() == 0 && str
.length() == 0 )
535 // "top" is the point where search starts from
536 size_t top
= length() - str
.length();
538 if ( nStart
== npos
)
539 nStart
= length() - 1;
543 const wxChar
*cursor
= c_str() + top
;
546 if ( wxTmemcmp(cursor
, str
.c_str(),
549 return cursor
- c_str();
551 } while ( cursor
-- > c_str() );
557 size_t wxStringBase::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
559 return rfind(wxStringBase(sz
, n
), nStart
);
562 size_t wxStringBase::rfind(wxChar ch
, size_t nStart
) const
564 if ( nStart
== npos
)
570 wxASSERT( nStart
<= length() );
573 const wxChar
*actual
;
574 for ( actual
= c_str() + ( nStart
== npos
? length() : nStart
+ 1 );
575 actual
> c_str(); --actual
)
577 if ( *(actual
- 1) == ch
)
578 return (actual
- 1) - c_str();
584 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
) const
586 wxASSERT(nStart
<= length());
588 size_t len
= wxStrlen(sz
);
591 for(i
= nStart
; i
< this->length(); ++i
)
593 if (wxTmemchr(sz
, *(c_str() + i
), len
))
597 if(i
== this->length())
603 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
,
606 return find_first_of(wxStringBase(sz
, n
), nStart
);
609 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
) const
611 if ( nStart
== npos
)
613 nStart
= length() - 1;
617 wxASSERT_MSG( nStart
<= length(),
618 _T("invalid index in find_last_of()") );
621 size_t len
= wxStrlen(sz
);
623 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
625 if ( wxTmemchr(sz
, *p
, len
) )
632 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
,
635 return find_last_of(wxStringBase(sz
, n
), nStart
);
638 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
640 if ( nStart
== npos
)
646 wxASSERT( nStart
<= length() );
649 size_t len
= wxStrlen(sz
);
652 for(i
= nStart
; i
< this->length(); ++i
)
654 if (!wxTmemchr(sz
, *(c_str() + i
), len
))
658 if(i
== this->length())
664 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
,
667 return find_first_not_of(wxStringBase(sz
, n
), nStart
);
670 size_t wxStringBase::find_first_not_of(wxChar ch
, size_t nStart
) const
672 wxASSERT( nStart
<= length() );
674 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
683 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
685 if ( nStart
== npos
)
687 nStart
= length() - 1;
691 wxASSERT( nStart
<= length() );
694 size_t len
= wxStrlen(sz
);
696 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
698 if ( !wxTmemchr(sz
, *p
,len
) )
705 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
,
708 return find_last_not_of(wxStringBase(sz
, n
), nStart
);
711 size_t wxStringBase::find_last_not_of(wxChar ch
, size_t nStart
) const
713 if ( nStart
== npos
)
715 nStart
= length() - 1;
719 wxASSERT( nStart
<= length() );
722 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
731 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
734 wxASSERT_MSG( nStart
<= length(),
735 _T("index out of bounds in wxStringBase::replace") );
736 size_t strLen
= length() - nStart
;
737 nLen
= strLen
< nLen
? strLen
: nLen
;
740 strTmp
.reserve(length()); // micro optimisation to avoid multiple mem allocs
743 strTmp
.append(c_str(), nStart
);
745 strTmp
.append(c_str() + nStart
+ nLen
);
751 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
752 size_t nCount
, wxChar ch
)
754 return replace(nStart
, nLen
, wxStringBase(nCount
, ch
).c_str());
757 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
758 const wxStringBase
& str
,
759 size_t nStart2
, size_t nLen2
)
761 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
764 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
765 const wxChar
* sz
, size_t nCount
)
767 return replace(nStart
, nLen
, wxStringBase(sz
, nCount
).c_str());
770 wxStringBase
wxStringBase::substr(size_t nStart
, size_t nLen
) const
773 nLen
= length() - nStart
;
774 return wxStringBase(*this, nStart
, nLen
);
777 // assigns one string to another
778 wxStringBase
& wxStringBase::operator=(const wxStringBase
& stringSrc
)
780 wxASSERT( stringSrc
.GetStringData()->IsValid() );
782 // don't copy string over itself
783 if ( m_pchData
!= stringSrc
.m_pchData
) {
784 if ( stringSrc
.GetStringData()->IsEmpty() ) {
789 GetStringData()->Unlock();
790 m_pchData
= stringSrc
.m_pchData
;
791 GetStringData()->Lock();
798 // assigns a single character
799 wxStringBase
& wxStringBase::operator=(wxChar ch
)
801 if ( !AssignCopy(1, &ch
) ) {
802 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(wxChar)") );
808 wxStringBase
& wxStringBase::operator=(const wxChar
*psz
)
810 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
811 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(const wxChar *)") );
816 // helper function: does real copy
817 bool wxStringBase::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
819 if ( nSrcLen
== 0 ) {
823 if ( !AllocBeforeWrite(nSrcLen
) ) {
824 // allocation failure handled by caller
827 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
828 GetStringData()->nDataLength
= nSrcLen
;
829 m_pchData
[nSrcLen
] = wxT('\0');
834 // ---------------------------------------------------------------------------
835 // string concatenation
836 // ---------------------------------------------------------------------------
838 // add something to this string
839 bool wxStringBase::ConcatSelf(size_t nSrcLen
, const wxChar
*pszSrcData
,
842 STATISTICS_ADD(SummandLength
, nSrcLen
);
844 nSrcLen
= nSrcLen
< nMaxLen
? nSrcLen
: nMaxLen
;
846 // concatenating an empty string is a NOP
848 wxStringData
*pData
= GetStringData();
849 size_t nLen
= pData
->nDataLength
;
850 size_t nNewLen
= nLen
+ nSrcLen
;
852 // alloc new buffer if current is too small
853 if ( pData
->IsShared() ) {
854 STATISTICS_ADD(ConcatHit
, 0);
856 // we have to allocate another buffer
857 wxStringData
* pOldData
= GetStringData();
858 if ( !AllocBuffer(nNewLen
) ) {
859 // allocation failure handled by caller
862 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
865 else if ( nNewLen
> pData
->nAllocLength
) {
866 STATISTICS_ADD(ConcatHit
, 0);
869 // we have to grow the buffer
870 if ( capacity() < nNewLen
) {
871 // allocation failure handled by caller
876 STATISTICS_ADD(ConcatHit
, 1);
878 // the buffer is already big enough
881 // should be enough space
882 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
884 // fast concatenation - all is done in our buffer
885 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
887 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
888 GetStringData()->nDataLength
= nNewLen
; // and fix the length
890 //else: the string to append was empty
894 // ---------------------------------------------------------------------------
895 // simple sub-string extraction
896 // ---------------------------------------------------------------------------
898 // helper function: clone the data attached to this string
899 bool wxStringBase::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
901 if ( nCopyLen
== 0 ) {
905 if ( !dest
.AllocBuffer(nCopyLen
) ) {
906 // allocation failure handled by caller
909 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
916 #if !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
919 #define STRINGCLASS wxStringBase
921 #define STRINGCLASS wxString
924 static inline int wxDoCmp(const wxChar
* s1
, size_t l1
,
925 const wxChar
* s2
, size_t l2
)
928 return wxTmemcmp(s1
, s2
, l1
);
931 int ret
= wxTmemcmp(s1
, s2
, l1
);
932 return ret
== 0 ? -1 : ret
;
936 int ret
= wxTmemcmp(s1
, s2
, l2
);
937 return ret
== 0 ? +1 : ret
;
941 int STRINGCLASS::compare(const wxStringBase
& str
) const
943 return ::wxDoCmp(data(), length(), str
.data(), str
.length());
946 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
947 const wxStringBase
& str
) const
949 wxASSERT(nStart
<= length());
950 size_type strLen
= length() - nStart
;
951 nLen
= strLen
< nLen
? strLen
: nLen
;
952 return ::wxDoCmp(data() + nStart
, nLen
, str
.data(), str
.length());
955 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
956 const wxStringBase
& str
,
957 size_t nStart2
, size_t nLen2
) const
959 wxASSERT(nStart
<= length());
960 wxASSERT(nStart2
<= str
.length());
961 size_type strLen
= length() - nStart
,
962 strLen2
= str
.length() - nStart2
;
963 nLen
= strLen
< nLen
? strLen
: nLen
;
964 nLen2
= strLen2
< nLen2
? strLen2
: nLen2
;
965 return ::wxDoCmp(data() + nStart
, nLen
, str
.data() + nStart2
, nLen2
);
968 int STRINGCLASS::compare(const wxChar
* sz
) const
970 size_t nLen
= wxStrlen(sz
);
971 return ::wxDoCmp(data(), length(), sz
, nLen
);
974 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
975 const wxChar
* sz
, size_t nCount
) const
977 wxASSERT(nStart
<= length());
978 size_type strLen
= length() - nStart
;
979 nLen
= strLen
< nLen
? strLen
: nLen
;
981 nCount
= wxStrlen(sz
);
983 return ::wxDoCmp(data() + nStart
, nLen
, sz
, nCount
);
988 #endif // !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
990 // ===========================================================================
991 // wxString class core
992 // ===========================================================================
994 // ---------------------------------------------------------------------------
995 // construction and conversion
996 // ---------------------------------------------------------------------------
1000 // from multibyte string
1001 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
1003 // if nLength != npos, then we have to make a NULL-terminated copy
1004 // of first nLength bytes of psz first because the input buffer to MB2WC
1005 // must always be NULL-terminated:
1006 wxCharBuffer
inBuf((const char *)NULL
);
1007 if (nLength
!= npos
)
1009 wxASSERT( psz
!= NULL
);
1010 wxCharBuffer
tmp(nLength
);
1011 memcpy(tmp
.data(), psz
, nLength
);
1012 tmp
.data()[nLength
] = '\0';
1017 // first get the size of the buffer we need
1021 // calculate the needed size ourselves or use the provided one
1022 if (nLength
== npos
)
1029 // nothing to convert
1035 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
1039 wxWCharBuffer theBuffer
= conv
.cMB2WC(psz
, nLen
, &nRealSize
);
1043 assign( theBuffer
.data() , nRealSize
- 1 );
1047 //Convert wxString in Unicode mode to a multi-byte string
1048 const wxCharBuffer
wxString::mb_str(wxMBConv
& conv
) const
1051 return conv
.cWC2MB(c_str(), length(), &dwOutSize
);
1058 wxString::wxString(const wchar_t *pwz
, wxMBConv
& conv
, size_t nLength
)
1060 // if nLength != npos, then we have to make a NULL-terminated copy
1061 // of first nLength chars of psz first because the input buffer to WC2MB
1062 // must always be NULL-terminated:
1063 wxWCharBuffer
inBuf((const wchar_t *)NULL
);
1064 if (nLength
!= npos
)
1066 wxASSERT( pwz
!= NULL
);
1067 wxWCharBuffer
tmp(nLength
);
1068 memcpy(tmp
.data(), pwz
, nLength
* sizeof(wchar_t));
1069 tmp
.data()[nLength
] = '\0';
1074 // first get the size of the buffer we need
1078 // calculate the needed size ourselves or use the provided one
1079 if (nLength
== npos
)
1080 nLen
= wxWcslen(pwz
);
1086 // nothing to convert
1091 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
1095 wxCharBuffer theBuffer
= conv
.cWC2MB(pwz
, nLen
, &nRealSize
);
1099 assign( theBuffer
.data() , nRealSize
- 1 );
1103 //Converts this string to a wide character string if unicode
1104 //mode is not enabled and wxUSE_WCHAR_T is enabled
1105 const wxWCharBuffer
wxString::wc_str(wxMBConv
& conv
) const
1108 return conv
.cMB2WC(c_str(), length(), &dwOutSize
);
1111 #endif // wxUSE_WCHAR_T
1113 #endif // Unicode/ANSI
1115 // shrink to minimal size (releasing extra memory)
1116 bool wxString::Shrink()
1118 wxString
tmp(begin(), end());
1120 return tmp
.length() == length();
1124 // get the pointer to writable buffer of (at least) nLen bytes
1125 wxChar
*wxString::GetWriteBuf(size_t nLen
)
1127 if ( !AllocBeforeWrite(nLen
) ) {
1128 // allocation failure handled by caller
1132 wxASSERT( GetStringData()->nRefs
== 1 );
1133 GetStringData()->Validate(false);
1138 // put string back in a reasonable state after GetWriteBuf
1139 void wxString::UngetWriteBuf()
1141 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
1142 GetStringData()->Validate(true);
1145 void wxString::UngetWriteBuf(size_t nLen
)
1147 GetStringData()->nDataLength
= nLen
;
1148 GetStringData()->Validate(true);
1152 // ---------------------------------------------------------------------------
1154 // ---------------------------------------------------------------------------
1156 // all functions are inline in string.h
1158 // ---------------------------------------------------------------------------
1159 // assignment operators
1160 // ---------------------------------------------------------------------------
1164 // same as 'signed char' variant
1165 wxString
& wxString::operator=(const unsigned char* psz
)
1167 *this = (const char *)psz
;
1172 wxString
& wxString::operator=(const wchar_t *pwz
)
1183 * concatenation functions come in 5 flavours:
1185 * char + string and string + char
1186 * C str + string and string + C str
1189 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
1192 wxASSERT( str1
.GetStringData()->IsValid() );
1193 wxASSERT( str2
.GetStringData()->IsValid() );
1202 wxString
operator+(const wxString
& str
, wxChar ch
)
1205 wxASSERT( str
.GetStringData()->IsValid() );
1214 wxString
operator+(wxChar ch
, const wxString
& str
)
1217 wxASSERT( str
.GetStringData()->IsValid() );
1226 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
1229 wxASSERT( str
.GetStringData()->IsValid() );
1233 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
1234 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1242 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
1245 wxASSERT( str
.GetStringData()->IsValid() );
1249 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
1250 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1258 // ===========================================================================
1259 // other common string functions
1260 // ===========================================================================
1262 int wxString::Cmp(const wxString
& s
) const
1267 int wxString::Cmp(const wxChar
* psz
) const
1269 return compare(psz
);
1272 static inline int wxDoCmpNoCase(const wxChar
* s1
, size_t l1
,
1273 const wxChar
* s2
, size_t l2
)
1279 for(i
= 0; i
< l1
; ++i
)
1281 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1284 return i
== l1
? 0 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1288 for(i
= 0; i
< l1
; ++i
)
1290 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1293 return i
== l1
? -1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1297 for(i
= 0; i
< l2
; ++i
)
1299 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1302 return i
== l2
? 1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1306 int wxString::CmpNoCase(const wxString
& s
) const
1308 return wxDoCmpNoCase(data(), length(), s
.data(), s
.length());
1311 int wxString::CmpNoCase(const wxChar
* psz
) const
1313 int nLen
= wxStrlen(psz
);
1315 return wxDoCmpNoCase(data(), length(), psz
, nLen
);
1322 #ifndef __SCHAR_MAX__
1323 #define __SCHAR_MAX__ 127
1327 wxString
wxString::FromAscii(const char *ascii
)
1330 return wxEmptyString
;
1332 size_t len
= strlen( ascii
);
1337 wxStringBuffer
buf(res
, len
);
1339 wchar_t *dest
= buf
;
1343 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
1351 wxString
wxString::FromAscii(const char ascii
)
1353 // What do we do with '\0' ?
1356 res
+= (wchar_t)(unsigned char) ascii
;
1361 const wxCharBuffer
wxString::ToAscii() const
1363 // this will allocate enough space for the terminating NUL too
1364 wxCharBuffer
buffer(length());
1367 char *dest
= buffer
.data();
1369 const wchar_t *pwc
= c_str();
1372 *dest
++ = (char)(*pwc
> SCHAR_MAX
? wxT('_') : *pwc
);
1374 // the output string can't have embedded NULs anyhow, so we can safely
1375 // stop at first of them even if we do have any
1385 // extract string of length nCount starting at nFirst
1386 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
1388 size_t nLen
= length();
1390 // default value of nCount is npos and means "till the end"
1391 if ( nCount
== npos
)
1393 nCount
= nLen
- nFirst
;
1396 // out-of-bounds requests return sensible things
1397 if ( nFirst
+ nCount
> nLen
)
1399 nCount
= nLen
- nFirst
;
1402 if ( nFirst
> nLen
)
1404 // AllocCopy() will return empty string
1408 wxString
dest(*this, nFirst
, nCount
);
1409 if ( dest
.length() != nCount
) {
1410 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
1416 // check that the string starts with prefix and return the rest of the string
1417 // in the provided pointer if it is not NULL, otherwise return false
1418 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
1420 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
1422 // first check if the beginning of the string matches the prefix: note
1423 // that we don't have to check that we don't run out of this string as
1424 // when we reach the terminating NUL, either prefix string ends too (and
1425 // then it's ok) or we break out of the loop because there is no match
1426 const wxChar
*p
= c_str();
1429 if ( *prefix
++ != *p
++ )
1438 // put the rest of the string into provided pointer
1445 // extract nCount last (rightmost) characters
1446 wxString
wxString::Right(size_t nCount
) const
1448 if ( nCount
> length() )
1451 wxString
dest(*this, length() - nCount
, nCount
);
1452 if ( dest
.length() != nCount
) {
1453 wxFAIL_MSG( _T("out of memory in wxString::Right") );
1458 // get all characters after the last occurence of ch
1459 // (returns the whole string if ch not found)
1460 wxString
wxString::AfterLast(wxChar ch
) const
1463 int iPos
= Find(ch
, true);
1464 if ( iPos
== wxNOT_FOUND
)
1467 str
= c_str() + iPos
+ 1;
1472 // extract nCount first (leftmost) characters
1473 wxString
wxString::Left(size_t nCount
) const
1475 if ( nCount
> length() )
1478 wxString
dest(*this, 0, nCount
);
1479 if ( dest
.length() != nCount
) {
1480 wxFAIL_MSG( _T("out of memory in wxString::Left") );
1485 // get all characters before the first occurence of ch
1486 // (returns the whole string if ch not found)
1487 wxString
wxString::BeforeFirst(wxChar ch
) const
1489 int iPos
= Find(ch
);
1490 if ( iPos
== wxNOT_FOUND
) iPos
= length();
1491 return wxString(*this, 0, iPos
);
1494 /// get all characters before the last occurence of ch
1495 /// (returns empty string if ch not found)
1496 wxString
wxString::BeforeLast(wxChar ch
) const
1499 int iPos
= Find(ch
, true);
1500 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
1501 str
= wxString(c_str(), iPos
);
1506 /// get all characters after the first occurence of ch
1507 /// (returns empty string if ch not found)
1508 wxString
wxString::AfterFirst(wxChar ch
) const
1511 int iPos
= Find(ch
);
1512 if ( iPos
!= wxNOT_FOUND
)
1513 str
= c_str() + iPos
+ 1;
1518 // replace first (or all) occurences of some substring with another one
1520 wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
1522 // if we tried to replace an empty string we'd enter an infinite loop below
1523 wxCHECK_MSG( szOld
&& *szOld
&& szNew
, 0,
1524 _T("wxString::Replace(): invalid parameter") );
1526 size_t uiCount
= 0; // count of replacements made
1528 size_t uiOldLen
= wxStrlen(szOld
);
1531 const wxChar
*pCurrent
= c_str();
1532 const wxChar
*pSubstr
;
1533 while ( *pCurrent
!= wxT('\0') ) {
1534 pSubstr
= wxStrstr(pCurrent
, szOld
);
1535 if ( pSubstr
== NULL
) {
1536 // strTemp is unused if no replacements were made, so avoid the copy
1540 strTemp
+= pCurrent
; // copy the rest
1541 break; // exit the loop
1544 // take chars before match
1545 size_type len
= strTemp
.length();
1546 strTemp
.append(pCurrent
, pSubstr
- pCurrent
);
1547 if ( strTemp
.length() != (size_t)(len
+ pSubstr
- pCurrent
) ) {
1548 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
1552 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
1557 if ( !bReplaceAll
) {
1558 strTemp
+= pCurrent
; // copy the rest
1559 break; // exit the loop
1564 // only done if there were replacements, otherwise would have returned above
1570 bool wxString::IsAscii() const
1572 const wxChar
*s
= (const wxChar
*) *this;
1574 if(!isascii(*s
)) return(false);
1580 bool wxString::IsWord() const
1582 const wxChar
*s
= (const wxChar
*) *this;
1584 if(!wxIsalpha(*s
)) return(false);
1590 bool wxString::IsNumber() const
1592 const wxChar
*s
= (const wxChar
*) *this;
1594 if ((s
[0] == wxT('-')) || (s
[0] == wxT('+'))) s
++;
1596 if(!wxIsdigit(*s
)) return(false);
1602 wxString
wxString::Strip(stripType w
) const
1605 if ( w
& leading
) s
.Trim(false);
1606 if ( w
& trailing
) s
.Trim(true);
1610 // ---------------------------------------------------------------------------
1612 // ---------------------------------------------------------------------------
1614 wxString
& wxString::MakeUpper()
1616 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1617 *it
= (wxChar
)wxToupper(*it
);
1622 wxString
& wxString::MakeLower()
1624 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1625 *it
= (wxChar
)wxTolower(*it
);
1630 // ---------------------------------------------------------------------------
1631 // trimming and padding
1632 // ---------------------------------------------------------------------------
1634 // some compilers (VC++ 6.0 not to name them) return true for a call to
1635 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1636 // live with this by checking that the character is a 7 bit one - even if this
1637 // may fail to detect some spaces (I don't know if Unicode doesn't have
1638 // space-like symbols somewhere except in the first 128 chars), it is arguably
1639 // still better than trimming away accented letters
1640 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1642 // trims spaces (in the sense of isspace) from left or right side
1643 wxString
& wxString::Trim(bool bFromRight
)
1645 // first check if we're going to modify the string at all
1648 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1649 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1655 // find last non-space character
1656 iterator psz
= begin() + length() - 1;
1657 while ( wxSafeIsspace(*psz
) && (psz
>= begin()) )
1660 // truncate at trailing space start
1666 // find first non-space character
1667 iterator psz
= begin();
1668 while ( wxSafeIsspace(*psz
) )
1671 // fix up data and length
1672 erase(begin(), psz
);
1679 // adds nCount characters chPad to the string from either side
1680 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1682 wxString
s(chPad
, nCount
);
1695 // truncate the string
1696 wxString
& wxString::Truncate(size_t uiLen
)
1698 if ( uiLen
< Len() ) {
1699 erase(begin() + uiLen
, end());
1701 //else: nothing to do, string is already short enough
1706 // ---------------------------------------------------------------------------
1707 // finding (return wxNOT_FOUND if not found and index otherwise)
1708 // ---------------------------------------------------------------------------
1711 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1713 size_type idx
= bFromEnd
? find_last_of(ch
) : find_first_of(ch
);
1715 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1718 // find a sub-string (like strstr)
1719 int wxString::Find(const wxChar
*pszSub
) const
1721 size_type idx
= find(pszSub
);
1723 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1726 // ----------------------------------------------------------------------------
1727 // conversion to numbers
1728 // ----------------------------------------------------------------------------
1730 bool wxString::ToLong(long *val
, int base
) const
1732 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToLong") );
1733 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1735 const wxChar
*start
= c_str();
1737 *val
= wxStrtol(start
, &end
, base
);
1739 // return true only if scan was stopped by the terminating NUL and if the
1740 // string was not empty to start with
1741 return !*end
&& (end
!= start
);
1744 bool wxString::ToULong(unsigned long *val
, int base
) const
1746 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToULong") );
1747 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1749 const wxChar
*start
= c_str();
1751 *val
= wxStrtoul(start
, &end
, base
);
1753 // return true only if scan was stopped by the terminating NUL and if the
1754 // string was not empty to start with
1755 return !*end
&& (end
!= start
);
1758 bool wxString::ToDouble(double *val
) const
1760 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToDouble") );
1762 const wxChar
*start
= c_str();
1764 *val
= wxStrtod(start
, &end
);
1766 // return true only if scan was stopped by the terminating NUL and if the
1767 // string was not empty to start with
1768 return !*end
&& (end
!= start
);
1771 // ---------------------------------------------------------------------------
1773 // ---------------------------------------------------------------------------
1776 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1779 va_start(argptr
, pszFormat
);
1782 s
.PrintfV(pszFormat
, argptr
);
1790 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1793 s
.PrintfV(pszFormat
, argptr
);
1797 int wxString::Printf(const wxChar
*pszFormat
, ...)
1800 va_start(argptr
, pszFormat
);
1802 int iLen
= PrintfV(pszFormat
, argptr
);
1809 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 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');
1839 // vsnprintf() may return either -1 (traditional Unix behaviour) or the
1840 // total number of characters which would have been written if the
1841 // buffer were large enough
1842 // also, it may return an errno may be something like EILSEQ,
1843 // in which case we need to break out
1844 if ( (len
>= 0 && len
<= size
)
1845 // No EOVERFLOW on Windows nor Palm 6.0
1846 #if !defined(__WXMSW__) && !defined(__WXPALMOS__)
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"
2044 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
2045 #define ARRAY_MAXSIZE_INCREMENT 4096
2047 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
2048 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
2051 #define STRING(p) ((wxString *)(&(p)))
2054 void wxArrayString::Init(bool autoSort
)
2058 m_pItems
= (wxChar
**) NULL
;
2059 m_autoSort
= autoSort
;
2063 wxArrayString::wxArrayString(const wxArrayString
& src
)
2065 Init(src
.m_autoSort
);
2070 // assignment operator
2071 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
2078 m_autoSort
= src
.m_autoSort
;
2083 void wxArrayString::Copy(const wxArrayString
& src
)
2085 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
2086 Alloc(src
.m_nCount
);
2088 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
2093 void wxArrayString::Grow(size_t nIncrement
)
2095 // only do it if no more place
2096 if ( (m_nSize
- m_nCount
) < nIncrement
) {
2097 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2098 // be never resized!
2099 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2100 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2103 if ( m_nSize
== 0 ) {
2104 // was empty, alloc some memory
2105 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
2106 if (m_nSize
< nIncrement
)
2107 m_nSize
= nIncrement
;
2108 m_pItems
= new wxChar
*[m_nSize
];
2111 // otherwise when it's called for the first time, nIncrement would be 0
2112 // and the array would never be expanded
2113 // add 50% but not too much
2114 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
2115 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
2116 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
2117 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
2118 if ( nIncrement
< ndefIncrement
)
2119 nIncrement
= ndefIncrement
;
2120 m_nSize
+= nIncrement
;
2121 wxChar
**pNew
= new wxChar
*[m_nSize
];
2123 // copy data to new location
2124 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2126 // delete old memory (but do not release the strings!)
2127 wxDELETEA(m_pItems
);
2134 void wxArrayString::Free()
2136 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
2137 STRING(m_pItems
[n
])->GetStringData()->Unlock();
2141 // deletes all the strings from the list
2142 void wxArrayString::Empty()
2149 // as Empty, but also frees memory
2150 void wxArrayString::Clear()
2157 wxDELETEA(m_pItems
);
2161 wxArrayString::~wxArrayString()
2165 wxDELETEA(m_pItems
);
2168 void wxArrayString::reserve(size_t nSize
)
2173 // pre-allocates memory (frees the previous data!)
2174 void wxArrayString::Alloc(size_t nSize
)
2176 // only if old buffer was not big enough
2177 if ( nSize
> m_nSize
) {
2179 wxDELETEA(m_pItems
);
2180 m_pItems
= new wxChar
*[nSize
];
2187 // minimizes the memory usage by freeing unused memory
2188 void wxArrayString::Shrink()
2190 // only do it if we have some memory to free
2191 if( m_nCount
< m_nSize
) {
2192 // allocates exactly as much memory as we need
2193 wxChar
**pNew
= new wxChar
*[m_nCount
];
2195 // copy data to new location
2196 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2202 #if WXWIN_COMPATIBILITY_2_4
2204 // return a wxString[] as required for some control ctors.
2205 wxString
* wxArrayString::GetStringArray() const
2207 wxString
*array
= 0;
2211 array
= new wxString
[m_nCount
];
2212 for( size_t i
= 0; i
< m_nCount
; i
++ )
2213 array
[i
] = m_pItems
[i
];
2219 void wxArrayString::Remove(size_t nIndex
, size_t nRemove
)
2221 RemoveAt(nIndex
, nRemove
);
2224 #endif // WXWIN_COMPATIBILITY_2_4
2226 // searches the array for an item (forward or backwards)
2227 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2230 // use binary search in the sorted array
2231 wxASSERT_MSG( bCase
&& !bFromEnd
,
2232 wxT("search parameters ignored for auto sorted array") );
2241 res
= wxStrcmp(sz
, m_pItems
[i
]);
2253 // use linear search in unsorted array
2255 if ( m_nCount
> 0 ) {
2256 size_t ui
= m_nCount
;
2258 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2265 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2266 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2275 // add item at the end
2276 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
2279 // insert the string at the correct position to keep the array sorted
2287 res
= str
.Cmp(m_pItems
[i
]);
2298 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2300 Insert(str
, lo
, nInsert
);
2305 wxASSERT( str
.GetStringData()->IsValid() );
2309 for (size_t i
= 0; i
< nInsert
; i
++)
2311 // the string data must not be deleted!
2312 str
.GetStringData()->Lock();
2315 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2317 size_t ret
= m_nCount
;
2318 m_nCount
+= nInsert
;
2323 // add item at the given position
2324 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2326 wxASSERT( str
.GetStringData()->IsValid() );
2328 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2329 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2330 wxT("array size overflow in wxArrayString::Insert") );
2334 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2335 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2337 for (size_t i
= 0; i
< nInsert
; i
++)
2339 str
.GetStringData()->Lock();
2340 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2342 m_nCount
+= nInsert
;
2345 // range insert (STL 23.2.4.3)
2347 wxArrayString::insert(iterator it
, const_iterator first
, const_iterator last
)
2349 const int idx
= it
- begin();
2354 // reset "it" since it can change inside Grow()
2357 while ( first
!= last
)
2359 it
= insert(it
, *first
);
2361 // insert returns an iterator to the last element inserted but we need
2362 // insert the next after this one, that is before the next one
2370 void wxArrayString::SetCount(size_t count
)
2375 while ( m_nCount
< count
)
2376 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2379 // removes item from array (by index)
2380 void wxArrayString::RemoveAt(size_t nIndex
, size_t nRemove
)
2382 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2383 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2384 wxT("removing too many elements in wxArrayString::Remove") );
2387 for (size_t i
= 0; i
< nRemove
; i
++)
2388 Item(nIndex
+ i
).GetStringData()->Unlock();
2390 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2391 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2392 m_nCount
-= nRemove
;
2395 // removes item from array (by value)
2396 void wxArrayString::Remove(const wxChar
*sz
)
2398 int iIndex
= Index(sz
);
2400 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2401 wxT("removing inexistent element in wxArrayString::Remove") );
2406 void wxArrayString::assign(const_iterator first
, const_iterator last
)
2408 reserve(last
- first
);
2409 for(; first
!= last
; ++first
)
2413 // ----------------------------------------------------------------------------
2415 // ----------------------------------------------------------------------------
2417 // we can only sort one array at a time with the quick-sort based
2420 // need a critical section to protect access to gs_compareFunction and
2421 // gs_sortAscending variables
2422 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2424 // call this before the value of the global sort vars is changed/after
2425 // you're finished with them
2426 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2427 gs_critsectStringSort = new wxCriticalSection; \
2428 gs_critsectStringSort->Enter()
2429 #define END_SORT() gs_critsectStringSort->Leave(); \
2430 delete gs_critsectStringSort; \
2431 gs_critsectStringSort = NULL
2433 #define START_SORT()
2435 #endif // wxUSE_THREADS
2437 // function to use for string comparaison
2438 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2440 // if we don't use the compare function, this flag tells us if we sort the
2441 // array in ascending or descending order
2442 static bool gs_sortAscending
= true;
2444 // function which is called by quick sort
2445 extern "C" int wxC_CALLING_CONV
// LINKAGEMODE
2446 wxStringCompareFunction(const void *first
, const void *second
)
2448 wxString
*strFirst
= (wxString
*)first
;
2449 wxString
*strSecond
= (wxString
*)second
;
2451 if ( gs_compareFunction
) {
2452 return gs_compareFunction(*strFirst
, *strSecond
);
2455 // maybe we should use wxStrcoll
2456 int result
= strFirst
->Cmp(*strSecond
);
2458 return gs_sortAscending
? result
: -result
;
2462 // sort array elements using passed comparaison function
2463 void wxArrayString::Sort(CompareFunction compareFunction
)
2467 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2468 gs_compareFunction
= compareFunction
;
2472 // reset it to NULL so that Sort(bool) will work the next time
2473 gs_compareFunction
= NULL
;
2478 typedef int (wxC_CALLING_CONV
* wxStringCompareFn
)(const void *first
, const void *second
);
2480 void wxArrayString::Sort(CompareFunction2 compareFunction
)
2482 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), (wxStringCompareFn
)compareFunction
);
2485 void wxArrayString::Sort(bool reverseOrder
)
2487 Sort(reverseOrder
? wxStringSortDescending
: wxStringSortAscending
);
2490 void wxArrayString::DoSort()
2492 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2494 // just sort the pointers using qsort() - of course it only works because
2495 // wxString() *is* a pointer to its data
2496 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2499 bool wxArrayString::operator==(const wxArrayString
& a
) const
2501 if ( m_nCount
!= a
.m_nCount
)
2504 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2506 if ( Item(n
) != a
[n
] )
2513 #endif // !wxUSE_STL
2515 int wxCMPFUNC_CONV
wxStringSortAscending(wxString
* s1
, wxString
* s2
)
2517 return s1
->Cmp(*s2
);
2520 int wxCMPFUNC_CONV
wxStringSortDescending(wxString
* s1
, wxString
* s2
)
2522 return -s1
->Cmp(*s2
);