1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxString class
4 // Author: Vadim Zeitlin, Ryan Norton
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // (c) 2004 Ryan Norton <wxprojects@comcast.net>
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
13 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
14 #pragma implementation "string.h"
19 * 1) all empty strings use g_strEmpty, nRefs = -1 (set in Init())
20 * 2) AllocBuffer() sets nRefs to 1, Lock() increments it by one
21 * 3) Unlock() decrements nRefs and frees memory if it goes to 0
24 // ===========================================================================
25 // headers, declarations, constants
26 // ===========================================================================
28 // For compilers that support precompilation, includes "wx.h".
29 #include "wx/wxprec.h"
37 #include "wx/string.h"
39 #include "wx/thread.h"
50 // allocating extra space for each string consumes more memory but speeds up
51 // the concatenation operations (nLen is the current string's length)
52 // NB: EXTRA_ALLOC must be >= 0!
53 #define EXTRA_ALLOC (19 - nLen % 16)
55 // ---------------------------------------------------------------------------
56 // static class variables definition
57 // ---------------------------------------------------------------------------
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();
316 // now we have enough space, just update the string length
317 pData
->nDataLength
= nLen
;
320 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
325 wxStringBase
& wxStringBase::append(size_t n
, wxChar ch
)
327 size_type len
= length();
329 if ( !Alloc(len
+ n
) || !CopyBeforeWrite() ) {
330 wxFAIL_MSG( _T("out of memory in wxStringBase::append") );
332 GetStringData()->nDataLength
= len
+ n
;
333 m_pchData
[len
+ n
] = '\0';
334 for ( size_t i
= 0; i
< n
; ++i
)
335 m_pchData
[len
+ i
] = ch
;
339 void wxStringBase::resize(size_t nSize
, wxChar ch
)
341 size_t len
= length();
345 erase(begin() + nSize
, end());
347 else if ( nSize
> len
)
349 append(nSize
- len
, ch
);
351 //else: we have exactly the specified length, nothing to do
354 // allocate enough memory for nLen characters
355 bool wxStringBase::Alloc(size_t nLen
)
357 wxStringData
*pData
= GetStringData();
358 if ( pData
->nAllocLength
<= nLen
) {
359 if ( pData
->IsEmpty() ) {
362 wxStringData
* pData
= (wxStringData
*)
363 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
365 if ( pData
== NULL
) {
366 // allocation failure handled by caller
371 pData
->nDataLength
= 0;
372 pData
->nAllocLength
= nLen
;
373 m_pchData
= pData
->data(); // data starts after wxStringData
374 m_pchData
[0u] = wxT('\0');
376 else if ( pData
->IsShared() ) {
377 pData
->Unlock(); // memory not freed because shared
378 size_t nOldLen
= pData
->nDataLength
;
379 if ( !AllocBuffer(nLen
) ) {
380 // allocation failure handled by caller
383 // +1 to copy the terminator, too
384 memcpy(m_pchData
, pData
->data(), (nOldLen
+1)*sizeof(wxChar
));
385 GetStringData()->nDataLength
= nOldLen
;
390 pData
= (wxStringData
*)
391 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
393 if ( pData
== NULL
) {
394 // allocation failure handled by caller
395 // keep previous data since reallocation failed
399 // it's not important if the pointer changed or not (the check for this
400 // is not faster than assigning to m_pchData in all cases)
401 pData
->nAllocLength
= nLen
;
402 m_pchData
= pData
->data();
405 //else: we've already got enough
409 wxStringBase::iterator
wxStringBase::begin()
416 wxStringBase::iterator
wxStringBase::end()
420 return m_pchData
+ length();
423 wxStringBase::iterator
wxStringBase::erase(iterator it
)
425 size_type idx
= it
- begin();
427 return begin() + idx
;
430 wxStringBase
& wxStringBase::erase(size_t nStart
, size_t nLen
)
432 wxASSERT(nStart
<= length());
433 size_t strLen
= length() - nStart
;
434 // delete nLen or up to the end of the string characters
435 nLen
= strLen
< nLen
? strLen
: nLen
;
436 wxString
strTmp(c_str(), nStart
);
437 strTmp
.append(c_str() + nStart
+ nLen
, length() - nStart
- nLen
);
443 wxStringBase
& wxStringBase::insert(size_t nPos
, const wxChar
*sz
, size_t n
)
445 wxASSERT( nPos
<= length() );
447 if ( n
== npos
) n
= wxStrlen(sz
);
448 if ( n
== 0 ) return *this;
450 if ( !Alloc(length() + n
) || !CopyBeforeWrite() ) {
451 wxFAIL_MSG( _T("out of memory in wxStringBase::insert") );
454 memmove(m_pchData
+ nPos
+ n
, m_pchData
+ nPos
,
455 (length() - nPos
) * sizeof(wxChar
));
456 memcpy(m_pchData
+ nPos
, sz
, n
* sizeof(wxChar
));
457 GetStringData()->nDataLength
= length() + n
;
458 m_pchData
[length()] = '\0';
463 void wxStringBase::swap(wxStringBase
& str
)
465 wxChar
* tmp
= str
.m_pchData
;
466 str
.m_pchData
= m_pchData
;
470 size_t wxStringBase::find(const wxStringBase
& str
, size_t nStart
) const
472 wxASSERT( str
.GetStringData()->IsValid() );
473 wxASSERT( nStart
<= length() );
476 const wxChar
* p
= (const wxChar
*)wxTmemchr(c_str() + nStart
,
483 while(p
- c_str() + str
.length() <= length() &&
484 wxTmemcmp(p
, str
.c_str(), str
.length()) )
486 //Previosly passed as the first argument to wxTmemchr,
487 //but C/C++ standard does not specify evaluation order
488 //of arguments to functions -
489 //http://embedded.com/showArticle.jhtml?articleID=9900607
493 p
= (const wxChar
*)wxTmemchr(p
,
495 length() - (p
- c_str()));
501 return (p
- c_str() + str
.length() <= length()) ? p
- c_str() : npos
;
504 size_t wxStringBase::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
506 return find(wxStringBase(sz
, n
), nStart
);
509 size_t wxStringBase::find(wxChar ch
, size_t nStart
) const
511 wxASSERT( nStart
<= length() );
513 const wxChar
*p
= (const wxChar
*)wxTmemchr(c_str() + nStart
, ch
, length() - nStart
);
515 return p
== NULL
? npos
: p
- c_str();
518 size_t wxStringBase::rfind(const wxStringBase
& str
, size_t nStart
) const
520 wxASSERT( str
.GetStringData()->IsValid() );
521 wxASSERT( nStart
== npos
|| nStart
<= length() );
523 if ( length() >= str
.length() )
525 // avoids a corner case later
526 if ( length() == 0 && str
.length() == 0 )
529 // "top" is the point where search starts from
530 size_t top
= length() - str
.length();
532 if ( nStart
== npos
)
533 nStart
= length() - 1;
537 const wxChar
*cursor
= c_str() + top
;
540 if ( wxTmemcmp(cursor
, str
.c_str(),
543 return cursor
- c_str();
545 } while ( cursor
-- > c_str() );
551 size_t wxStringBase::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
553 return rfind(wxStringBase(sz
, n
), nStart
);
556 size_t wxStringBase::rfind(wxChar ch
, size_t nStart
) const
558 if ( nStart
== npos
)
564 wxASSERT( nStart
<= length() );
567 const wxChar
*actual
;
568 for ( actual
= c_str() + ( nStart
== npos
? length() : nStart
+ 1 );
569 actual
> c_str(); --actual
)
571 if ( *(actual
- 1) == ch
)
572 return (actual
- 1) - c_str();
578 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
) const
580 wxASSERT(nStart
<= length());
582 size_t len
= wxStrlen(sz
);
585 for(i
= nStart
; i
< this->length(); ++i
)
587 if (wxTmemchr(sz
, *(c_str() + i
), len
))
591 if(i
== this->length())
597 size_t wxStringBase::find_first_of(const wxChar
* sz
, size_t nStart
,
600 return find_first_of(wxStringBase(sz
, n
), nStart
);
603 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
) const
605 if ( nStart
== npos
)
607 nStart
= length() - 1;
611 wxASSERT_MSG( nStart
<= length(),
612 _T("invalid index in find_last_of()") );
615 size_t len
= wxStrlen(sz
);
617 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
619 if ( wxTmemchr(sz
, *p
, len
) )
626 size_t wxStringBase::find_last_of(const wxChar
* sz
, size_t nStart
,
629 return find_last_of(wxStringBase(sz
, n
), nStart
);
632 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
634 if ( nStart
== npos
)
640 wxASSERT( nStart
<= length() );
643 size_t len
= wxStrlen(sz
);
646 for(i
= nStart
; i
< this->length(); ++i
)
648 if (!wxTmemchr(sz
, *(c_str() + i
), len
))
652 if(i
== this->length())
658 size_t wxStringBase::find_first_not_of(const wxChar
* sz
, size_t nStart
,
661 return find_first_not_of(wxStringBase(sz
, n
), nStart
);
664 size_t wxStringBase::find_first_not_of(wxChar ch
, size_t nStart
) const
666 wxASSERT( nStart
<= length() );
668 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
677 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
679 if ( nStart
== npos
)
681 nStart
= length() - 1;
685 wxASSERT( nStart
<= length() );
688 size_t len
= wxStrlen(sz
);
690 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
692 if ( !wxTmemchr(sz
, *p
,len
) )
699 size_t wxStringBase::find_last_not_of(const wxChar
* sz
, size_t nStart
,
702 return find_last_not_of(wxStringBase(sz
, n
), nStart
);
705 size_t wxStringBase::find_last_not_of(wxChar ch
, size_t nStart
) const
707 if ( nStart
== npos
)
709 nStart
= length() - 1;
713 wxASSERT( nStart
<= length() );
716 for ( const wxChar
*p
= c_str() + nStart
; p
>= c_str(); --p
)
725 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
728 wxASSERT_MSG( nStart
<= length(),
729 _T("index out of bounds in wxStringBase::replace") );
730 size_t strLen
= length() - nStart
;
731 nLen
= strLen
< nLen
? strLen
: nLen
;
734 strTmp
.reserve(length()); // micro optimisation to avoid multiple mem allocs
737 strTmp
.append(c_str(), nStart
);
739 strTmp
.append(c_str() + nStart
+ nLen
);
745 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
746 size_t nCount
, wxChar ch
)
748 return replace(nStart
, nLen
, wxStringBase(nCount
, ch
).c_str());
751 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
752 const wxStringBase
& str
,
753 size_t nStart2
, size_t nLen2
)
755 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
758 wxStringBase
& wxStringBase::replace(size_t nStart
, size_t nLen
,
759 const wxChar
* sz
, size_t nCount
)
761 return replace(nStart
, nLen
, wxStringBase(sz
, nCount
).c_str());
764 wxStringBase
wxStringBase::substr(size_t nStart
, size_t nLen
) const
767 nLen
= length() - nStart
;
768 return wxStringBase(*this, nStart
, nLen
);
771 // assigns one string to another
772 wxStringBase
& wxStringBase::operator=(const wxStringBase
& stringSrc
)
774 wxASSERT( stringSrc
.GetStringData()->IsValid() );
776 // don't copy string over itself
777 if ( m_pchData
!= stringSrc
.m_pchData
) {
778 if ( stringSrc
.GetStringData()->IsEmpty() ) {
783 GetStringData()->Unlock();
784 m_pchData
= stringSrc
.m_pchData
;
785 GetStringData()->Lock();
792 // assigns a single character
793 wxStringBase
& wxStringBase::operator=(wxChar ch
)
795 if ( !AssignCopy(1, &ch
) ) {
796 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(wxChar)") );
802 wxStringBase
& wxStringBase::operator=(const wxChar
*psz
)
804 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
805 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(const wxChar *)") );
810 // helper function: does real copy
811 bool wxStringBase::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
813 if ( nSrcLen
== 0 ) {
817 if ( !AllocBeforeWrite(nSrcLen
) ) {
818 // allocation failure handled by caller
821 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
822 GetStringData()->nDataLength
= nSrcLen
;
823 m_pchData
[nSrcLen
] = wxT('\0');
828 // ---------------------------------------------------------------------------
829 // string concatenation
830 // ---------------------------------------------------------------------------
832 // add something to this string
833 bool wxStringBase::ConcatSelf(size_t nSrcLen
, const wxChar
*pszSrcData
,
836 STATISTICS_ADD(SummandLength
, nSrcLen
);
838 nSrcLen
= nSrcLen
< nMaxLen
? nSrcLen
: nMaxLen
;
840 // concatenating an empty string is a NOP
842 wxStringData
*pData
= GetStringData();
843 size_t nLen
= pData
->nDataLength
;
844 size_t nNewLen
= nLen
+ nSrcLen
;
846 // alloc new buffer if current is too small
847 if ( pData
->IsShared() ) {
848 STATISTICS_ADD(ConcatHit
, 0);
850 // we have to allocate another buffer
851 wxStringData
* pOldData
= GetStringData();
852 if ( !AllocBuffer(nNewLen
) ) {
853 // allocation failure handled by caller
856 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
859 else if ( nNewLen
> pData
->nAllocLength
) {
860 STATISTICS_ADD(ConcatHit
, 0);
863 // we have to grow the buffer
864 if ( capacity() < nNewLen
) {
865 // allocation failure handled by caller
870 STATISTICS_ADD(ConcatHit
, 1);
872 // the buffer is already big enough
875 // should be enough space
876 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
878 // fast concatenation - all is done in our buffer
879 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
881 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
882 GetStringData()->nDataLength
= nNewLen
; // and fix the length
884 //else: the string to append was empty
888 // ---------------------------------------------------------------------------
889 // simple sub-string extraction
890 // ---------------------------------------------------------------------------
892 // helper function: clone the data attached to this string
893 bool wxStringBase::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
895 if ( nCopyLen
== 0 ) {
899 if ( !dest
.AllocBuffer(nCopyLen
) ) {
900 // allocation failure handled by caller
903 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
910 #if !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
913 #define STRINGCLASS wxStringBase
915 #define STRINGCLASS wxString
918 static inline int wxDoCmp(const wxChar
* s1
, size_t l1
,
919 const wxChar
* s2
, size_t l2
)
922 return wxTmemcmp(s1
, s2
, l1
);
925 int ret
= wxTmemcmp(s1
, s2
, l1
);
926 return ret
== 0 ? -1 : ret
;
930 int ret
= wxTmemcmp(s1
, s2
, l2
);
931 return ret
== 0 ? +1 : ret
;
935 int STRINGCLASS::compare(const wxStringBase
& str
) const
937 return ::wxDoCmp(data(), length(), str
.data(), str
.length());
940 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
941 const wxStringBase
& str
) const
943 wxASSERT(nStart
<= length());
944 size_type strLen
= length() - nStart
;
945 nLen
= strLen
< nLen
? strLen
: nLen
;
946 return ::wxDoCmp(data() + nStart
, nLen
, str
.data(), str
.length());
949 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
950 const wxStringBase
& str
,
951 size_t nStart2
, size_t nLen2
) const
953 wxASSERT(nStart
<= length());
954 wxASSERT(nStart2
<= str
.length());
955 size_type strLen
= length() - nStart
,
956 strLen2
= str
.length() - nStart2
;
957 nLen
= strLen
< nLen
? strLen
: nLen
;
958 nLen2
= strLen2
< nLen2
? strLen2
: nLen2
;
959 return ::wxDoCmp(data() + nStart
, nLen
, str
.data() + nStart2
, nLen2
);
962 int STRINGCLASS::compare(const wxChar
* sz
) const
964 size_t nLen
= wxStrlen(sz
);
965 return ::wxDoCmp(data(), length(), sz
, nLen
);
968 int STRINGCLASS::compare(size_t nStart
, size_t nLen
,
969 const wxChar
* sz
, size_t nCount
) const
971 wxASSERT(nStart
<= length());
972 size_type strLen
= length() - nStart
;
973 nLen
= strLen
< nLen
? strLen
: nLen
;
975 nCount
= wxStrlen(sz
);
977 return ::wxDoCmp(data() + nStart
, nLen
, sz
, nCount
);
982 #endif // !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
984 // ===========================================================================
985 // wxString class core
986 // ===========================================================================
988 // ---------------------------------------------------------------------------
989 // construction and conversion
990 // ---------------------------------------------------------------------------
994 // from multibyte string
995 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
997 // if nLength != npos, then we have to make a NULL-terminated copy
998 // of first nLength bytes of psz first because the input buffer to MB2WC
999 // must always be NULL-terminated:
1000 wxCharBuffer
inBuf((const char *)NULL
);
1001 if (nLength
!= npos
)
1003 wxASSERT( psz
!= NULL
);
1004 wxCharBuffer
tmp(nLength
);
1005 memcpy(tmp
.data(), psz
, nLength
);
1006 tmp
.data()[nLength
] = '\0';
1011 // first get the size of the buffer we need
1015 // calculate the needed size ourselves or use the provided one
1016 if (nLength
== npos
)
1023 // nothing to convert
1029 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
1033 wxWCharBuffer theBuffer
= conv
.cMB2WC(psz
, nLen
, &nRealSize
);
1037 assign( theBuffer
.data() , nRealSize
- 1 );
1041 //Convert wxString in Unicode mode to a multi-byte string
1042 const wxCharBuffer
wxString::mb_str(wxMBConv
& conv
) const
1045 return conv
.cWC2MB(c_str(), length(), &dwOutSize
);
1052 wxString::wxString(const wchar_t *pwz
, wxMBConv
& conv
, size_t nLength
)
1054 // if nLength != npos, then we have to make a NULL-terminated copy
1055 // of first nLength chars of psz first because the input buffer to WC2MB
1056 // must always be NULL-terminated:
1057 wxWCharBuffer
inBuf((const wchar_t *)NULL
);
1058 if (nLength
!= npos
)
1060 wxASSERT( pwz
!= NULL
);
1061 wxWCharBuffer
tmp(nLength
);
1062 memcpy(tmp
.data(), pwz
, nLength
* sizeof(wchar_t));
1063 tmp
.data()[nLength
] = '\0';
1068 // first get the size of the buffer we need
1072 // calculate the needed size ourselves or use the provided one
1073 if (nLength
== npos
)
1074 nLen
= wxWcslen(pwz
);
1080 // nothing to convert
1085 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) )
1089 wxCharBuffer theBuffer
= conv
.cWC2MB(pwz
, nLen
, &nRealSize
);
1093 assign( theBuffer
.data() , nRealSize
- 1 );
1097 //Converts this string to a wide character string if unicode
1098 //mode is not enabled and wxUSE_WCHAR_T is enabled
1099 const wxWCharBuffer
wxString::wc_str(wxMBConv
& conv
) const
1102 return conv
.cMB2WC(c_str(), length(), &dwOutSize
);
1105 #endif // wxUSE_WCHAR_T
1107 #endif // Unicode/ANSI
1109 // shrink to minimal size (releasing extra memory)
1110 bool wxString::Shrink()
1112 wxString
tmp(begin(), end());
1114 return tmp
.length() == length();
1118 // get the pointer to writable buffer of (at least) nLen bytes
1119 wxChar
*wxString::GetWriteBuf(size_t nLen
)
1121 if ( !AllocBeforeWrite(nLen
) ) {
1122 // allocation failure handled by caller
1126 wxASSERT( GetStringData()->nRefs
== 1 );
1127 GetStringData()->Validate(false);
1132 // put string back in a reasonable state after GetWriteBuf
1133 void wxString::UngetWriteBuf()
1135 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
1136 GetStringData()->Validate(true);
1139 void wxString::UngetWriteBuf(size_t nLen
)
1141 GetStringData()->nDataLength
= nLen
;
1142 GetStringData()->Validate(true);
1146 // ---------------------------------------------------------------------------
1148 // ---------------------------------------------------------------------------
1150 // all functions are inline in string.h
1152 // ---------------------------------------------------------------------------
1153 // assignment operators
1154 // ---------------------------------------------------------------------------
1158 // same as 'signed char' variant
1159 wxString
& wxString::operator=(const unsigned char* psz
)
1161 *this = (const char *)psz
;
1166 wxString
& wxString::operator=(const wchar_t *pwz
)
1177 * concatenation functions come in 5 flavours:
1179 * char + string and string + char
1180 * C str + string and string + C str
1183 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
1186 wxASSERT( str1
.GetStringData()->IsValid() );
1187 wxASSERT( str2
.GetStringData()->IsValid() );
1196 wxString
operator+(const wxString
& str
, wxChar ch
)
1199 wxASSERT( str
.GetStringData()->IsValid() );
1208 wxString
operator+(wxChar ch
, const wxString
& str
)
1211 wxASSERT( str
.GetStringData()->IsValid() );
1220 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
1223 wxASSERT( str
.GetStringData()->IsValid() );
1227 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
1228 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1236 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
1239 wxASSERT( str
.GetStringData()->IsValid() );
1243 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
1244 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1252 // ===========================================================================
1253 // other common string functions
1254 // ===========================================================================
1256 int wxString::Cmp(const wxString
& s
) const
1261 int wxString::Cmp(const wxChar
* psz
) const
1263 return compare(psz
);
1266 static inline int wxDoCmpNoCase(const wxChar
* s1
, size_t l1
,
1267 const wxChar
* s2
, size_t l2
)
1273 for(i
= 0; i
< l1
; ++i
)
1275 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1278 return i
== l1
? 0 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1282 for(i
= 0; i
< l1
; ++i
)
1284 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1287 return i
== l1
? -1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1291 for(i
= 0; i
< l2
; ++i
)
1293 if(wxTolower(s1
[i
]) != wxTolower(s2
[i
]))
1296 return i
== l2
? 1 : wxTolower(s1
[i
]) < wxTolower(s2
[i
]) ? -1 : 1;
1300 int wxString::CmpNoCase(const wxString
& s
) const
1302 return wxDoCmpNoCase(data(), length(), s
.data(), s
.length());
1305 int wxString::CmpNoCase(const wxChar
* psz
) const
1307 int nLen
= wxStrlen(psz
);
1309 return wxDoCmpNoCase(data(), length(), psz
, nLen
);
1316 #ifndef __SCHAR_MAX__
1317 #define __SCHAR_MAX__ 127
1321 wxString
wxString::FromAscii(const char *ascii
)
1324 return wxEmptyString
;
1326 size_t len
= strlen( ascii
);
1331 wxStringBuffer
buf(res
, len
);
1333 wchar_t *dest
= buf
;
1337 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
1345 wxString
wxString::FromAscii(const char ascii
)
1347 // What do we do with '\0' ?
1350 res
+= (wchar_t)(unsigned char) ascii
;
1355 const wxCharBuffer
wxString::ToAscii() const
1357 // this will allocate enough space for the terminating NUL too
1358 wxCharBuffer
buffer(length());
1361 char *dest
= buffer
.data();
1363 const wchar_t *pwc
= c_str();
1366 *dest
++ = (char)(*pwc
> SCHAR_MAX
? wxT('_') : *pwc
);
1368 // the output string can't have embedded NULs anyhow, so we can safely
1369 // stop at first of them even if we do have any
1379 // extract string of length nCount starting at nFirst
1380 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
1382 size_t nLen
= length();
1384 // default value of nCount is npos and means "till the end"
1385 if ( nCount
== npos
)
1387 nCount
= nLen
- nFirst
;
1390 // out-of-bounds requests return sensible things
1391 if ( nFirst
+ nCount
> nLen
)
1393 nCount
= nLen
- nFirst
;
1396 if ( nFirst
> nLen
)
1398 // AllocCopy() will return empty string
1402 wxString
dest(*this, nFirst
, nCount
);
1403 if ( dest
.length() != nCount
) {
1404 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
1410 // check that the string starts with prefix and return the rest of the string
1411 // in the provided pointer if it is not NULL, otherwise return false
1412 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
1414 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
1416 // first check if the beginning of the string matches the prefix: note
1417 // that we don't have to check that we don't run out of this string as
1418 // when we reach the terminating NUL, either prefix string ends too (and
1419 // then it's ok) or we break out of the loop because there is no match
1420 const wxChar
*p
= c_str();
1423 if ( *prefix
++ != *p
++ )
1432 // put the rest of the string into provided pointer
1439 // extract nCount last (rightmost) characters
1440 wxString
wxString::Right(size_t nCount
) const
1442 if ( nCount
> length() )
1445 wxString
dest(*this, length() - nCount
, nCount
);
1446 if ( dest
.length() != nCount
) {
1447 wxFAIL_MSG( _T("out of memory in wxString::Right") );
1452 // get all characters after the last occurence of ch
1453 // (returns the whole string if ch not found)
1454 wxString
wxString::AfterLast(wxChar ch
) const
1457 int iPos
= Find(ch
, true);
1458 if ( iPos
== wxNOT_FOUND
)
1461 str
= c_str() + iPos
+ 1;
1466 // extract nCount first (leftmost) characters
1467 wxString
wxString::Left(size_t nCount
) const
1469 if ( nCount
> length() )
1472 wxString
dest(*this, 0, nCount
);
1473 if ( dest
.length() != nCount
) {
1474 wxFAIL_MSG( _T("out of memory in wxString::Left") );
1479 // get all characters before the first occurence of ch
1480 // (returns the whole string if ch not found)
1481 wxString
wxString::BeforeFirst(wxChar ch
) const
1483 int iPos
= Find(ch
);
1484 if ( iPos
== wxNOT_FOUND
) iPos
= length();
1485 return wxString(*this, 0, iPos
);
1488 /// get all characters before the last occurence of ch
1489 /// (returns empty string if ch not found)
1490 wxString
wxString::BeforeLast(wxChar ch
) const
1493 int iPos
= Find(ch
, true);
1494 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
1495 str
= wxString(c_str(), iPos
);
1500 /// get all characters after the first occurence of ch
1501 /// (returns empty string if ch not found)
1502 wxString
wxString::AfterFirst(wxChar ch
) const
1505 int iPos
= Find(ch
);
1506 if ( iPos
!= wxNOT_FOUND
)
1507 str
= c_str() + iPos
+ 1;
1512 // replace first (or all) occurences of some substring with another one
1514 wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
1516 // if we tried to replace an empty string we'd enter an infinite loop below
1517 wxCHECK_MSG( szOld
&& *szOld
&& szNew
, 0,
1518 _T("wxString::Replace(): invalid parameter") );
1520 size_t uiCount
= 0; // count of replacements made
1522 size_t uiOldLen
= wxStrlen(szOld
);
1525 const wxChar
*pCurrent
= c_str();
1526 const wxChar
*pSubstr
;
1527 while ( *pCurrent
!= wxT('\0') ) {
1528 pSubstr
= wxStrstr(pCurrent
, szOld
);
1529 if ( pSubstr
== NULL
) {
1530 // strTemp is unused if no replacements were made, so avoid the copy
1534 strTemp
+= pCurrent
; // copy the rest
1535 break; // exit the loop
1538 // take chars before match
1539 size_type len
= strTemp
.length();
1540 strTemp
.append(pCurrent
, pSubstr
- pCurrent
);
1541 if ( strTemp
.length() != (size_t)(len
+ pSubstr
- pCurrent
) ) {
1542 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
1546 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
1551 if ( !bReplaceAll
) {
1552 strTemp
+= pCurrent
; // copy the rest
1553 break; // exit the loop
1558 // only done if there were replacements, otherwise would have returned above
1564 bool wxString::IsAscii() const
1566 const wxChar
*s
= (const wxChar
*) *this;
1568 if(!isascii(*s
)) return(false);
1574 bool wxString::IsWord() const
1576 const wxChar
*s
= (const wxChar
*) *this;
1578 if(!wxIsalpha(*s
)) return(false);
1584 bool wxString::IsNumber() const
1586 const wxChar
*s
= (const wxChar
*) *this;
1588 if ((s
[0] == wxT('-')) || (s
[0] == wxT('+'))) s
++;
1590 if(!wxIsdigit(*s
)) return(false);
1596 wxString
wxString::Strip(stripType w
) const
1599 if ( w
& leading
) s
.Trim(false);
1600 if ( w
& trailing
) s
.Trim(true);
1604 // ---------------------------------------------------------------------------
1606 // ---------------------------------------------------------------------------
1608 wxString
& wxString::MakeUpper()
1610 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1611 *it
= (wxChar
)wxToupper(*it
);
1616 wxString
& wxString::MakeLower()
1618 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1619 *it
= (wxChar
)wxTolower(*it
);
1624 // ---------------------------------------------------------------------------
1625 // trimming and padding
1626 // ---------------------------------------------------------------------------
1628 // some compilers (VC++ 6.0 not to name them) return true for a call to
1629 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1630 // live with this by checking that the character is a 7 bit one - even if this
1631 // may fail to detect some spaces (I don't know if Unicode doesn't have
1632 // space-like symbols somewhere except in the first 128 chars), it is arguably
1633 // still better than trimming away accented letters
1634 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1636 // trims spaces (in the sense of isspace) from left or right side
1637 wxString
& wxString::Trim(bool bFromRight
)
1639 // first check if we're going to modify the string at all
1642 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1643 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1649 // find last non-space character
1650 iterator psz
= begin() + length() - 1;
1651 while ( wxSafeIsspace(*psz
) && (psz
>= begin()) )
1654 // truncate at trailing space start
1660 // find first non-space character
1661 iterator psz
= begin();
1662 while ( wxSafeIsspace(*psz
) )
1665 // fix up data and length
1666 erase(begin(), psz
);
1673 // adds nCount characters chPad to the string from either side
1674 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1676 wxString
s(chPad
, nCount
);
1689 // truncate the string
1690 wxString
& wxString::Truncate(size_t uiLen
)
1692 if ( uiLen
< Len() ) {
1693 erase(begin() + uiLen
, end());
1695 //else: nothing to do, string is already short enough
1700 // ---------------------------------------------------------------------------
1701 // finding (return wxNOT_FOUND if not found and index otherwise)
1702 // ---------------------------------------------------------------------------
1705 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1707 size_type idx
= bFromEnd
? find_last_of(ch
) : find_first_of(ch
);
1709 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1712 // find a sub-string (like strstr)
1713 int wxString::Find(const wxChar
*pszSub
) const
1715 size_type idx
= find(pszSub
);
1717 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1720 // ----------------------------------------------------------------------------
1721 // conversion to numbers
1722 // ----------------------------------------------------------------------------
1724 bool wxString::ToLong(long *val
, int base
) const
1726 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToLong") );
1727 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1729 const wxChar
*start
= c_str();
1731 *val
= wxStrtol(start
, &end
, base
);
1733 // return true only if scan was stopped by the terminating NUL and if the
1734 // string was not empty to start with
1735 return !*end
&& (end
!= start
);
1738 bool wxString::ToULong(unsigned long *val
, int base
) const
1740 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToULong") );
1741 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1743 const wxChar
*start
= c_str();
1745 *val
= wxStrtoul(start
, &end
, base
);
1747 // return true only if scan was stopped by the terminating NUL and if the
1748 // string was not empty to start with
1749 return !*end
&& (end
!= start
);
1752 bool wxString::ToDouble(double *val
) const
1754 wxCHECK_MSG( val
, false, _T("NULL pointer in wxString::ToDouble") );
1756 const wxChar
*start
= c_str();
1758 *val
= wxStrtod(start
, &end
);
1760 // return true only if scan was stopped by the terminating NUL and if the
1761 // string was not empty to start with
1762 return !*end
&& (end
!= start
);
1765 // ---------------------------------------------------------------------------
1767 // ---------------------------------------------------------------------------
1770 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1773 va_start(argptr
, pszFormat
);
1776 s
.PrintfV(pszFormat
, argptr
);
1784 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1787 s
.PrintfV(pszFormat
, argptr
);
1791 int wxString::Printf(const wxChar
*pszFormat
, ...)
1794 va_start(argptr
, pszFormat
);
1796 int iLen
= PrintfV(pszFormat
, argptr
);
1803 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1811 wxStringBuffer
tmp(*this, size
+ 1);
1820 // wxVsnprintf() may modify the original arg pointer, so pass it
1823 wxVaCopy(argptrcopy
, argptr
);
1824 len
= wxVsnprintf(buf
, size
, pszFormat
, argptrcopy
);
1827 // some implementations of vsnprintf() don't NUL terminate
1828 // the string if there is not enough space for it so
1829 // always do it manually
1830 buf
[size
] = _T('\0');
1833 // vsnprintf() may return either -1 (traditional Unix behaviour) or the
1834 // total number of characters which would have been written if the
1835 // buffer were large enough
1836 if ( len
>= 0 && len
<= size
)
1838 // ok, there was enough space
1842 // still not enough, double it again
1846 // we could have overshot
1852 // ----------------------------------------------------------------------------
1853 // misc other operations
1854 // ----------------------------------------------------------------------------
1856 // returns true if the string matches the pattern which may contain '*' and
1857 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1859 bool wxString::Matches(const wxChar
*pszMask
) const
1861 // I disable this code as it doesn't seem to be faster (in fact, it seems
1862 // to be much slower) than the old, hand-written code below and using it
1863 // here requires always linking with libregex even if the user code doesn't
1865 #if 0 // wxUSE_REGEX
1866 // first translate the shell-like mask into a regex
1868 pattern
.reserve(wxStrlen(pszMask
));
1880 pattern
+= _T(".*");
1891 // these characters are special in a RE, quote them
1892 // (however note that we don't quote '[' and ']' to allow
1893 // using them for Unix shell like matching)
1894 pattern
+= _T('\\');
1898 pattern
+= *pszMask
;
1906 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1907 #else // !wxUSE_REGEX
1908 // TODO: this is, of course, awfully inefficient...
1910 // the char currently being checked
1911 const wxChar
*pszTxt
= c_str();
1913 // the last location where '*' matched
1914 const wxChar
*pszLastStarInText
= NULL
;
1915 const wxChar
*pszLastStarInMask
= NULL
;
1918 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1919 switch ( *pszMask
) {
1921 if ( *pszTxt
== wxT('\0') )
1924 // pszTxt and pszMask will be incremented in the loop statement
1930 // remember where we started to be able to backtrack later
1931 pszLastStarInText
= pszTxt
;
1932 pszLastStarInMask
= pszMask
;
1934 // ignore special chars immediately following this one
1935 // (should this be an error?)
1936 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1939 // if there is nothing more, match
1940 if ( *pszMask
== wxT('\0') )
1943 // are there any other metacharacters in the mask?
1945 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1947 if ( pEndMask
!= NULL
) {
1948 // we have to match the string between two metachars
1949 uiLenMask
= pEndMask
- pszMask
;
1952 // we have to match the remainder of the string
1953 uiLenMask
= wxStrlen(pszMask
);
1956 wxString
strToMatch(pszMask
, uiLenMask
);
1957 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1958 if ( pMatch
== NULL
)
1961 // -1 to compensate "++" in the loop
1962 pszTxt
= pMatch
+ uiLenMask
- 1;
1963 pszMask
+= uiLenMask
- 1;
1968 if ( *pszMask
!= *pszTxt
)
1974 // match only if nothing left
1975 if ( *pszTxt
== wxT('\0') )
1978 // if we failed to match, backtrack if we can
1979 if ( pszLastStarInText
) {
1980 pszTxt
= pszLastStarInText
+ 1;
1981 pszMask
= pszLastStarInMask
;
1983 pszLastStarInText
= NULL
;
1985 // don't bother resetting pszLastStarInMask, it's unnecessary
1991 #endif // wxUSE_REGEX/!wxUSE_REGEX
1994 // Count the number of chars
1995 int wxString::Freq(wxChar ch
) const
1999 for (int i
= 0; i
< len
; i
++)
2001 if (GetChar(i
) == ch
)
2007 // convert to upper case, return the copy of the string
2008 wxString
wxString::Upper() const
2009 { wxString
s(*this); return s
.MakeUpper(); }
2011 // convert to lower case, return the copy of the string
2012 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
2014 int wxString::sprintf(const wxChar
*pszFormat
, ...)
2017 va_start(argptr
, pszFormat
);
2018 int iLen
= PrintfV(pszFormat
, argptr
);
2023 // ============================================================================
2025 // ============================================================================
2027 #include "wx/arrstr.h"
2031 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
2032 #define ARRAY_MAXSIZE_INCREMENT 4096
2034 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
2035 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
2038 #define STRING(p) ((wxString *)(&(p)))
2041 void wxArrayString::Init(bool autoSort
)
2045 m_pItems
= (wxChar
**) NULL
;
2046 m_autoSort
= autoSort
;
2050 wxArrayString::wxArrayString(const wxArrayString
& src
)
2052 Init(src
.m_autoSort
);
2057 // assignment operator
2058 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
2065 m_autoSort
= src
.m_autoSort
;
2070 void wxArrayString::Copy(const wxArrayString
& src
)
2072 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
2073 Alloc(src
.m_nCount
);
2075 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
2080 void wxArrayString::Grow(size_t nIncrement
)
2082 // only do it if no more place
2083 if ( (m_nSize
- m_nCount
) < nIncrement
) {
2084 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2085 // be never resized!
2086 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2087 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2090 if ( m_nSize
== 0 ) {
2091 // was empty, alloc some memory
2092 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
2093 if (m_nSize
< nIncrement
)
2094 m_nSize
= nIncrement
;
2095 m_pItems
= new wxChar
*[m_nSize
];
2098 // otherwise when it's called for the first time, nIncrement would be 0
2099 // and the array would never be expanded
2100 // add 50% but not too much
2101 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
2102 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
2103 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
2104 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
2105 if ( nIncrement
< ndefIncrement
)
2106 nIncrement
= ndefIncrement
;
2107 m_nSize
+= nIncrement
;
2108 wxChar
**pNew
= new wxChar
*[m_nSize
];
2110 // copy data to new location
2111 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2113 // delete old memory (but do not release the strings!)
2114 wxDELETEA(m_pItems
);
2121 void wxArrayString::Free()
2123 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
2124 STRING(m_pItems
[n
])->GetStringData()->Unlock();
2128 // deletes all the strings from the list
2129 void wxArrayString::Empty()
2136 // as Empty, but also frees memory
2137 void wxArrayString::Clear()
2144 wxDELETEA(m_pItems
);
2148 wxArrayString::~wxArrayString()
2152 wxDELETEA(m_pItems
);
2155 void wxArrayString::reserve(size_t nSize
)
2160 // pre-allocates memory (frees the previous data!)
2161 void wxArrayString::Alloc(size_t nSize
)
2163 // only if old buffer was not big enough
2164 if ( nSize
> m_nSize
) {
2166 wxDELETEA(m_pItems
);
2167 m_pItems
= new wxChar
*[nSize
];
2174 // minimizes the memory usage by freeing unused memory
2175 void wxArrayString::Shrink()
2177 // only do it if we have some memory to free
2178 if( m_nCount
< m_nSize
) {
2179 // allocates exactly as much memory as we need
2180 wxChar
**pNew
= new wxChar
*[m_nCount
];
2182 // copy data to new location
2183 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2189 #if WXWIN_COMPATIBILITY_2_4
2191 // return a wxString[] as required for some control ctors.
2192 wxString
* wxArrayString::GetStringArray() const
2194 wxString
*array
= 0;
2198 array
= new wxString
[m_nCount
];
2199 for( size_t i
= 0; i
< m_nCount
; i
++ )
2200 array
[i
] = m_pItems
[i
];
2206 void wxArrayString::Remove(size_t nIndex
, size_t nRemove
)
2208 RemoveAt(nIndex
, nRemove
);
2211 #endif // WXWIN_COMPATIBILITY_2_4
2213 // searches the array for an item (forward or backwards)
2214 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2217 // use binary search in the sorted array
2218 wxASSERT_MSG( bCase
&& !bFromEnd
,
2219 wxT("search parameters ignored for auto sorted array") );
2228 res
= wxStrcmp(sz
, m_pItems
[i
]);
2240 // use linear search in unsorted array
2242 if ( m_nCount
> 0 ) {
2243 size_t ui
= m_nCount
;
2245 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2252 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2253 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2262 // add item at the end
2263 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
2266 // insert the string at the correct position to keep the array sorted
2274 res
= str
.Cmp(m_pItems
[i
]);
2285 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2287 Insert(str
, lo
, nInsert
);
2292 wxASSERT( str
.GetStringData()->IsValid() );
2296 for (size_t i
= 0; i
< nInsert
; i
++)
2298 // the string data must not be deleted!
2299 str
.GetStringData()->Lock();
2302 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2304 size_t ret
= m_nCount
;
2305 m_nCount
+= nInsert
;
2310 // add item at the given position
2311 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2313 wxASSERT( str
.GetStringData()->IsValid() );
2315 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2316 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2317 wxT("array size overflow in wxArrayString::Insert") );
2321 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2322 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2324 for (size_t i
= 0; i
< nInsert
; i
++)
2326 str
.GetStringData()->Lock();
2327 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2329 m_nCount
+= nInsert
;
2332 // range insert (STL 23.2.4.3)
2334 wxArrayString::insert(iterator it
, const_iterator first
, const_iterator last
)
2336 const int idx
= it
- begin();
2341 // reset "it" since it can change inside Grow()
2344 while ( first
!= last
)
2346 it
= insert(it
, *first
);
2348 // insert returns an iterator to the last element inserted but we need
2349 // insert the next after this one, that is before the next one
2357 void wxArrayString::SetCount(size_t count
)
2362 while ( m_nCount
< count
)
2363 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2366 // removes item from array (by index)
2367 void wxArrayString::RemoveAt(size_t nIndex
, size_t nRemove
)
2369 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2370 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2371 wxT("removing too many elements in wxArrayString::Remove") );
2374 for (size_t i
= 0; i
< nRemove
; i
++)
2375 Item(nIndex
+ i
).GetStringData()->Unlock();
2377 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2378 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2379 m_nCount
-= nRemove
;
2382 // removes item from array (by value)
2383 void wxArrayString::Remove(const wxChar
*sz
)
2385 int iIndex
= Index(sz
);
2387 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2388 wxT("removing inexistent element in wxArrayString::Remove") );
2393 void wxArrayString::assign(const_iterator first
, const_iterator last
)
2395 reserve(last
- first
);
2396 for(; first
!= last
; ++first
)
2400 // ----------------------------------------------------------------------------
2402 // ----------------------------------------------------------------------------
2404 // we can only sort one array at a time with the quick-sort based
2407 // need a critical section to protect access to gs_compareFunction and
2408 // gs_sortAscending variables
2409 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2411 // call this before the value of the global sort vars is changed/after
2412 // you're finished with them
2413 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2414 gs_critsectStringSort = new wxCriticalSection; \
2415 gs_critsectStringSort->Enter()
2416 #define END_SORT() gs_critsectStringSort->Leave(); \
2417 delete gs_critsectStringSort; \
2418 gs_critsectStringSort = NULL
2420 #define START_SORT()
2422 #endif // wxUSE_THREADS
2424 // function to use for string comparaison
2425 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2427 // if we don't use the compare function, this flag tells us if we sort the
2428 // array in ascending or descending order
2429 static bool gs_sortAscending
= true;
2431 // function which is called by quick sort
2432 extern "C" int wxC_CALLING_CONV
// LINKAGEMODE
2433 wxStringCompareFunction(const void *first
, const void *second
)
2435 wxString
*strFirst
= (wxString
*)first
;
2436 wxString
*strSecond
= (wxString
*)second
;
2438 if ( gs_compareFunction
) {
2439 return gs_compareFunction(*strFirst
, *strSecond
);
2442 // maybe we should use wxStrcoll
2443 int result
= strFirst
->Cmp(*strSecond
);
2445 return gs_sortAscending
? result
: -result
;
2449 // sort array elements using passed comparaison function
2450 void wxArrayString::Sort(CompareFunction compareFunction
)
2454 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2455 gs_compareFunction
= compareFunction
;
2459 // reset it to NULL so that Sort(bool) will work the next time
2460 gs_compareFunction
= NULL
;
2465 typedef int (wxC_CALLING_CONV
* wxStringCompareFn
)(const void *first
, const void *second
);
2467 void wxArrayString::Sort(CompareFunction2 compareFunction
)
2469 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), (wxStringCompareFn
)compareFunction
);
2472 void wxArrayString::Sort(bool reverseOrder
)
2474 Sort(reverseOrder
? wxStringSortDescending
: wxStringSortAscending
);
2477 void wxArrayString::DoSort()
2479 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2481 // just sort the pointers using qsort() - of course it only works because
2482 // wxString() *is* a pointer to its data
2483 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2486 bool wxArrayString::operator==(const wxArrayString
& a
) const
2488 if ( m_nCount
!= a
.m_nCount
)
2491 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2493 if ( Item(n
) != a
[n
] )
2500 #endif // !wxUSE_STL
2502 int wxCMPFUNC_CONV
wxStringSortAscending(wxString
* s1
, wxString
* s2
)
2504 return s1
->Cmp(*s2
);
2507 int wxCMPFUNC_CONV
wxStringSortDescending(wxString
* s1
, wxString
* s2
)
2509 return -s1
->Cmp(*s2
);