1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxString class
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "string.h"
18 * 1) all empty strings use g_strEmpty, nRefs = -1 (set in Init())
19 * 2) AllocBuffer() sets nRefs to 1, Lock() increments it by one
20 * 3) Unlock() decrements nRefs and frees memory if it goes to 0
23 // ===========================================================================
24 // headers, declarations, constants
25 // ===========================================================================
27 // For compilers that support precompilation, includes "wx.h".
28 #include "wx/wxprec.h"
36 #include "wx/string.h"
38 #include "wx/thread.h"
50 #undef wxUSE_EXPERIMENTAL_PRINTF
52 #define wxUSE_EXPERIMENTAL_PRINTF 1
56 // allocating extra space for each string consumes more memory but speeds up
57 // the concatenation operations (nLen is the current string's length)
58 // NB: EXTRA_ALLOC must be >= 0!
59 #define EXTRA_ALLOC (19 - nLen % 16)
61 // ---------------------------------------------------------------------------
62 // static class variables definition
63 // ---------------------------------------------------------------------------
65 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
66 // must define this static for VA or else you get multiply defined symbols
68 const unsigned int wxSTRING_MAXLEN
= UINT_MAX
- 100;
71 #ifdef wxSTD_STRING_COMPATIBILITY
72 const size_t wxString::npos
= wxSTRING_MAXLEN
;
73 #endif // wxSTD_STRING_COMPATIBILITY
75 // ----------------------------------------------------------------------------
77 // ----------------------------------------------------------------------------
79 // for an empty string, GetStringData() will return this address: this
80 // structure has the same layout as wxStringData and it's data() method will
81 // return the empty string (dummy pointer)
86 } g_strEmpty
= { {-1, 0, 0}, wxT('\0') };
88 // empty C style string: points to 'string data' byte of g_strEmpty
89 extern const wxChar WXDLLEXPORT
*wxEmptyString
= &g_strEmpty
.dummy
;
91 // ----------------------------------------------------------------------------
92 // conditional compilation
93 // ----------------------------------------------------------------------------
95 #if !defined(__WXSW__) && wxUSE_UNICODE
96 #ifdef wxUSE_EXPERIMENTAL_PRINTF
97 #undef wxUSE_EXPERIMENTAL_PRINTF
99 #define wxUSE_EXPERIMENTAL_PRINTF 1
102 // we want to find out if the current platform supports vsnprintf()-like
103 // function: for Unix this is done with configure, for Windows we test the
104 // compiler explicitly.
106 // FIXME currently, this is only for ANSI (!Unicode) strings, so we call this
107 // function wxVsnprintfA (A for ANSI), should also find one for Unicode
108 // strings in Unicode build
110 #if defined(__VISUALC__) || (defined(__MINGW32__) && wxUSE_NORLANDER_HEADERS)
111 #define wxVsnprintfA _vsnprintf
113 #elif defined(__WXMAC__)
114 #define wxVsnprintfA vsnprintf
116 #ifdef HAVE_VSNPRINTF
117 #define wxVsnprintfA vsnprintf
119 #endif // Windows/!Windows
122 // in this case we'll use vsprintf() (which is ANSI and thus should be
123 // always available), but it's unsafe because it doesn't check for buffer
124 // size - so give a warning
125 #define wxVsnprintfA(buf, len, format, arg) vsprintf(buf, format, arg)
127 #if defined(__VISUALC__)
128 #pragma message("Using sprintf() because no snprintf()-like function defined")
129 #elif defined(__GNUG__)
130 #warning "Using sprintf() because no snprintf()-like function defined"
132 #endif // no vsnprintf
135 // AIX has vsnprintf, but there's no prototype in the system headers.
136 extern "C" int vsnprintf(char* str
, size_t n
, const char* format
, va_list ap
);
139 // ----------------------------------------------------------------------------
141 // ----------------------------------------------------------------------------
143 #if defined(wxSTD_STRING_COMPATIBILITY) && wxUSE_STD_IOSTREAM
145 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
148 // ATTN: you can _not_ use both of these in the same program!
150 wxSTD istream
& operator>>(wxSTD istream
& is
, wxString
& WXUNUSED(str
))
155 streambuf
*sb
= is
.rdbuf();
158 int ch
= sb
->sbumpc ();
160 is
.setstate(ios::eofbit
);
163 else if ( isspace(ch
) ) {
175 if ( str
.length() == 0 )
176 is
.setstate(ios::failbit
);
181 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
187 #endif //std::string compatibility
189 // ----------------------------------------------------------------------------
191 // ----------------------------------------------------------------------------
193 // this small class is used to gather statistics for performance tuning
194 //#define WXSTRING_STATISTICS
195 #ifdef WXSTRING_STATISTICS
199 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
201 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
203 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
206 size_t m_nCount
, m_nTotal
;
208 } g_averageLength("allocation size"),
209 g_averageSummandLength("summand length"),
210 g_averageConcatHit("hit probability in concat"),
211 g_averageInitialLength("initial string length");
213 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
215 #define STATISTICS_ADD(av, val)
216 #endif // WXSTRING_STATISTICS
218 // ===========================================================================
219 // wxString class core
220 // ===========================================================================
222 // ---------------------------------------------------------------------------
224 // ---------------------------------------------------------------------------
226 // constructs string of <nLength> copies of character <ch>
227 wxString::wxString(wxChar ch
, size_t nLength
)
232 if ( !AllocBuffer(nLength
) ) {
233 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
238 // memset only works on char
239 for (size_t n
=0; n
<nLength
; n
++) m_pchData
[n
] = ch
;
241 memset(m_pchData
, ch
, nLength
);
246 // takes nLength elements of psz starting at nPos
247 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
251 // if the length is not given, assume the string to be NUL terminated
252 if ( nLength
== wxSTRING_MAXLEN
) {
253 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
255 nLength
= wxStrlen(psz
+ nPos
);
258 STATISTICS_ADD(InitialLength
, nLength
);
261 // trailing '\0' is written in AllocBuffer()
262 if ( !AllocBuffer(nLength
) ) {
263 wxFAIL_MSG( _T("out of memory in wxString::InitWith") );
266 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
270 #ifdef wxSTD_STRING_COMPATIBILITY
272 // poor man's iterators are "void *" pointers
273 wxString::wxString(const void *pStart
, const void *pEnd
)
275 InitWith((const wxChar
*)pStart
, 0,
276 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
279 #endif //std::string compatibility
283 // from multibyte string
284 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
286 // first get necessary size
287 size_t nLen
= psz
? conv
.MB2WC((wchar_t *) NULL
, psz
, 0) : 0;
289 // nLength is number of *Unicode* characters here!
290 if ((nLen
!= (size_t)-1) && (nLen
> nLength
))
294 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
295 if ( !AllocBuffer(nLen
) ) {
296 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
299 conv
.MB2WC(m_pchData
, psz
, nLen
);
310 wxString::wxString(const wchar_t *pwz
, wxMBConv
& conv
, size_t nLength
)
312 // first get necessary size
316 if (nLength
== wxSTRING_MAXLEN
)
317 nLen
= conv
.WC2MB((char *) NULL
, pwz
, 0);
323 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
324 if ( !AllocBuffer(nLen
) ) {
325 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
328 conv
.WC2MB(m_pchData
, pwz
, nLen
);
334 #endif // wxUSE_WCHAR_T
336 #endif // Unicode/ANSI
338 // ---------------------------------------------------------------------------
340 // ---------------------------------------------------------------------------
342 // allocates memory needed to store a C string of length nLen
343 bool wxString::AllocBuffer(size_t nLen
)
345 // allocating 0 sized buffer doesn't make sense, all empty strings should
347 wxASSERT( nLen
> 0 );
349 // make sure that we don't overflow
350 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
351 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
353 STATISTICS_ADD(Length
, nLen
);
356 // 1) one extra character for '\0' termination
357 // 2) sizeof(wxStringData) for housekeeping info
358 wxStringData
* pData
= (wxStringData
*)
359 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
361 if ( pData
== NULL
) {
362 // allocation failures are handled by the caller
367 pData
->nDataLength
= nLen
;
368 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
369 m_pchData
= pData
->data(); // data starts after wxStringData
370 m_pchData
[nLen
] = wxT('\0');
374 // must be called before changing this string
375 bool wxString::CopyBeforeWrite()
377 wxStringData
* pData
= GetStringData();
379 if ( pData
->IsShared() ) {
380 pData
->Unlock(); // memory not freed because shared
381 size_t nLen
= pData
->nDataLength
;
382 if ( !AllocBuffer(nLen
) ) {
383 // allocation failures are handled by the caller
386 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
389 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
394 // must be called before replacing contents of this string
395 bool wxString::AllocBeforeWrite(size_t nLen
)
397 wxASSERT( nLen
!= 0 ); // doesn't make any sense
399 // must not share string and must have enough space
400 wxStringData
* pData
= GetStringData();
401 if ( pData
->IsShared() || pData
->IsEmpty() ) {
402 // can't work with old buffer, get new one
404 if ( !AllocBuffer(nLen
) ) {
405 // allocation failures are handled by the caller
410 if ( nLen
> pData
->nAllocLength
) {
411 // realloc the buffer instead of calling malloc() again, this is more
413 STATISTICS_ADD(Length
, nLen
);
417 pData
= (wxStringData
*)
418 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
420 if ( pData
== NULL
) {
421 // allocation failures are handled by the caller
422 // keep previous data since reallocation failed
426 pData
->nAllocLength
= nLen
;
427 m_pchData
= pData
->data();
430 // now we have enough space, just update the string length
431 pData
->nDataLength
= nLen
;
434 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
439 // allocate enough memory for nLen characters
440 bool wxString::Alloc(size_t nLen
)
442 wxStringData
*pData
= GetStringData();
443 if ( pData
->nAllocLength
<= nLen
) {
444 if ( pData
->IsEmpty() ) {
447 wxStringData
* pData
= (wxStringData
*)
448 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
450 if ( pData
== NULL
) {
451 // allocation failure handled by caller
456 pData
->nDataLength
= 0;
457 pData
->nAllocLength
= nLen
;
458 m_pchData
= pData
->data(); // data starts after wxStringData
459 m_pchData
[0u] = wxT('\0');
461 else if ( pData
->IsShared() ) {
462 pData
->Unlock(); // memory not freed because shared
463 size_t nOldLen
= pData
->nDataLength
;
464 if ( !AllocBuffer(nLen
) ) {
465 // allocation failure handled by caller
468 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
473 pData
= (wxStringData
*)
474 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
476 if ( pData
== NULL
) {
477 // allocation failure handled by caller
478 // keep previous data since reallocation failed
482 // it's not important if the pointer changed or not (the check for this
483 // is not faster than assigning to m_pchData in all cases)
484 pData
->nAllocLength
= nLen
;
485 m_pchData
= pData
->data();
488 //else: we've already got enough
492 // shrink to minimal size (releasing extra memory)
493 bool wxString::Shrink()
495 wxStringData
*pData
= GetStringData();
497 size_t nLen
= pData
->nDataLength
;
498 void *p
= realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
501 wxFAIL_MSG( _T("out of memory reallocating wxString data") );
502 // keep previous data since reallocation failed
508 // contrary to what one might believe, some realloc() implementation do
509 // move the memory block even when its size is reduced
510 pData
= (wxStringData
*)p
;
512 m_pchData
= pData
->data();
515 pData
->nAllocLength
= nLen
;
520 // get the pointer to writable buffer of (at least) nLen bytes
521 wxChar
*wxString::GetWriteBuf(size_t nLen
)
523 if ( !AllocBeforeWrite(nLen
) ) {
524 // allocation failure handled by caller
528 wxASSERT( GetStringData()->nRefs
== 1 );
529 GetStringData()->Validate(FALSE
);
534 // put string back in a reasonable state after GetWriteBuf
535 void wxString::UngetWriteBuf()
537 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
538 GetStringData()->Validate(TRUE
);
541 void wxString::UngetWriteBuf(size_t nLen
)
543 GetStringData()->nDataLength
= nLen
;
544 GetStringData()->Validate(TRUE
);
547 // ---------------------------------------------------------------------------
549 // ---------------------------------------------------------------------------
551 // all functions are inline in string.h
553 // ---------------------------------------------------------------------------
554 // assignment operators
555 // ---------------------------------------------------------------------------
557 // helper function: does real copy
558 bool wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
560 if ( nSrcLen
== 0 ) {
564 if ( !AllocBeforeWrite(nSrcLen
) ) {
565 // allocation failure handled by caller
568 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
569 GetStringData()->nDataLength
= nSrcLen
;
570 m_pchData
[nSrcLen
] = wxT('\0');
575 // assigns one string to another
576 wxString
& wxString::operator=(const wxString
& stringSrc
)
578 wxASSERT( stringSrc
.GetStringData()->IsValid() );
580 // don't copy string over itself
581 if ( m_pchData
!= stringSrc
.m_pchData
) {
582 if ( stringSrc
.GetStringData()->IsEmpty() ) {
587 GetStringData()->Unlock();
588 m_pchData
= stringSrc
.m_pchData
;
589 GetStringData()->Lock();
596 // assigns a single character
597 wxString
& wxString::operator=(wxChar ch
)
599 if ( !AssignCopy(1, &ch
) ) {
600 wxFAIL_MSG( _T("out of memory in wxString::operator=(wxChar)") );
607 wxString
& wxString::operator=(const wxChar
*psz
)
609 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
610 wxFAIL_MSG( _T("out of memory in wxString::operator=(const wxChar *)") );
617 // same as 'signed char' variant
618 wxString
& wxString::operator=(const unsigned char* psz
)
620 *this = (const char *)psz
;
625 wxString
& wxString::operator=(const wchar_t *pwz
)
635 // ---------------------------------------------------------------------------
636 // string concatenation
637 // ---------------------------------------------------------------------------
639 // add something to this string
640 bool wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
642 STATISTICS_ADD(SummandLength
, nSrcLen
);
644 // concatenating an empty string is a NOP
646 wxStringData
*pData
= GetStringData();
647 size_t nLen
= pData
->nDataLength
;
648 size_t nNewLen
= nLen
+ nSrcLen
;
650 // alloc new buffer if current is too small
651 if ( pData
->IsShared() ) {
652 STATISTICS_ADD(ConcatHit
, 0);
654 // we have to allocate another buffer
655 wxStringData
* pOldData
= GetStringData();
656 if ( !AllocBuffer(nNewLen
) ) {
657 // allocation failure handled by caller
660 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
663 else if ( nNewLen
> pData
->nAllocLength
) {
664 STATISTICS_ADD(ConcatHit
, 0);
666 // we have to grow the buffer
667 if ( !Alloc(nNewLen
) ) {
668 // allocation failure handled by caller
673 STATISTICS_ADD(ConcatHit
, 1);
675 // the buffer is already big enough
678 // should be enough space
679 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
681 // fast concatenation - all is done in our buffer
682 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
684 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
685 GetStringData()->nDataLength
= nNewLen
; // and fix the length
687 //else: the string to append was empty
692 * concatenation functions come in 5 flavours:
694 * char + string and string + char
695 * C str + string and string + C str
698 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
700 wxASSERT( str1
.GetStringData()->IsValid() );
701 wxASSERT( str2
.GetStringData()->IsValid() );
709 wxString
operator+(const wxString
& str
, wxChar ch
)
711 wxASSERT( str
.GetStringData()->IsValid() );
719 wxString
operator+(wxChar ch
, const wxString
& str
)
721 wxASSERT( str
.GetStringData()->IsValid() );
729 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
731 wxASSERT( str
.GetStringData()->IsValid() );
734 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
735 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
743 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
745 wxASSERT( str
.GetStringData()->IsValid() );
748 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
749 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
757 // ===========================================================================
758 // other common string functions
759 // ===========================================================================
763 wxString
wxString::FromAscii(const char *ascii
)
766 return wxEmptyString
;
768 size_t len
= strlen( ascii
);
773 wxStringBuffer
buf(res
, len
);
779 if ( (*dest
++ = (wchar_t)(unsigned char)*ascii
++) == L
'\0' )
787 const wxCharBuffer
wxString::ToAscii() const
789 // this will allocate enough space for the terminating NUL too
790 wxCharBuffer
buffer(length());
792 signed char *dest
= (signed char *)buffer
.data();
794 const wchar_t *pwc
= c_str();
797 *dest
++ = *pwc
> SCHAR_MAX
? '_' : *pwc
;
799 // the output string can't have embedded NULs anyhow, so we can safely
800 // stop at first of them even if we do have any
810 // ---------------------------------------------------------------------------
811 // simple sub-string extraction
812 // ---------------------------------------------------------------------------
814 // helper function: clone the data attached to this string
815 bool wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
817 if ( nCopyLen
== 0 ) {
821 if ( !dest
.AllocBuffer(nCopyLen
) ) {
822 // allocation failure handled by caller
825 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
830 // extract string of length nCount starting at nFirst
831 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
833 wxStringData
*pData
= GetStringData();
834 size_t nLen
= pData
->nDataLength
;
836 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
837 if ( nCount
== wxSTRING_MAXLEN
)
839 nCount
= nLen
- nFirst
;
842 // out-of-bounds requests return sensible things
843 if ( nFirst
+ nCount
> nLen
)
845 nCount
= nLen
- nFirst
;
850 // AllocCopy() will return empty string
855 if ( !AllocCopy(dest
, nCount
, nFirst
) ) {
856 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
862 // check that the tring starts with prefix and return the rest of the string
863 // in the provided pointer if it is not NULL, otherwise return FALSE
864 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
866 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
868 // first check if the beginning of the string matches the prefix: note
869 // that we don't have to check that we don't run out of this string as
870 // when we reach the terminating NUL, either prefix string ends too (and
871 // then it's ok) or we break out of the loop because there is no match
872 const wxChar
*p
= c_str();
875 if ( *prefix
++ != *p
++ )
884 // put the rest of the string into provided pointer
891 // extract nCount last (rightmost) characters
892 wxString
wxString::Right(size_t nCount
) const
894 if ( nCount
> (size_t)GetStringData()->nDataLength
)
895 nCount
= GetStringData()->nDataLength
;
898 if ( !AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
) ) {
899 wxFAIL_MSG( _T("out of memory in wxString::Right") );
904 // get all characters after the last occurence of ch
905 // (returns the whole string if ch not found)
906 wxString
wxString::AfterLast(wxChar ch
) const
909 int iPos
= Find(ch
, TRUE
);
910 if ( iPos
== wxNOT_FOUND
)
913 str
= c_str() + iPos
+ 1;
918 // extract nCount first (leftmost) characters
919 wxString
wxString::Left(size_t nCount
) const
921 if ( nCount
> (size_t)GetStringData()->nDataLength
)
922 nCount
= GetStringData()->nDataLength
;
925 if ( !AllocCopy(dest
, nCount
, 0) ) {
926 wxFAIL_MSG( _T("out of memory in wxString::Left") );
931 // get all characters before the first occurence of ch
932 // (returns the whole string if ch not found)
933 wxString
wxString::BeforeFirst(wxChar ch
) const
936 for ( const wxChar
*pc
= m_pchData
; *pc
!= wxT('\0') && *pc
!= ch
; pc
++ )
942 /// get all characters before the last occurence of ch
943 /// (returns empty string if ch not found)
944 wxString
wxString::BeforeLast(wxChar ch
) const
947 int iPos
= Find(ch
, TRUE
);
948 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
949 str
= wxString(c_str(), iPos
);
954 /// get all characters after the first occurence of ch
955 /// (returns empty string if ch not found)
956 wxString
wxString::AfterFirst(wxChar ch
) const
960 if ( iPos
!= wxNOT_FOUND
)
961 str
= c_str() + iPos
+ 1;
966 // replace first (or all) occurences of some substring with another one
967 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
969 size_t uiCount
= 0; // count of replacements made
971 size_t uiOldLen
= wxStrlen(szOld
);
974 const wxChar
*pCurrent
= m_pchData
;
975 const wxChar
*pSubstr
;
976 while ( *pCurrent
!= wxT('\0') ) {
977 pSubstr
= wxStrstr(pCurrent
, szOld
);
978 if ( pSubstr
== NULL
) {
979 // strTemp is unused if no replacements were made, so avoid the copy
983 strTemp
+= pCurrent
; // copy the rest
984 break; // exit the loop
987 // take chars before match
988 if ( !strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
) ) {
989 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
993 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
998 if ( !bReplaceAll
) {
999 strTemp
+= pCurrent
; // copy the rest
1000 break; // exit the loop
1005 // only done if there were replacements, otherwise would have returned above
1011 bool wxString::IsAscii() const
1013 const wxChar
*s
= (const wxChar
*) *this;
1015 if(!isascii(*s
)) return(FALSE
);
1021 bool wxString::IsWord() const
1023 const wxChar
*s
= (const wxChar
*) *this;
1025 if(!wxIsalpha(*s
)) return(FALSE
);
1031 bool wxString::IsNumber() const
1033 const wxChar
*s
= (const wxChar
*) *this;
1035 if ((s
[0] == '-') || (s
[0] == '+')) s
++;
1037 if(!wxIsdigit(*s
)) return(FALSE
);
1043 wxString
wxString::Strip(stripType w
) const
1046 if ( w
& leading
) s
.Trim(FALSE
);
1047 if ( w
& trailing
) s
.Trim(TRUE
);
1051 // ---------------------------------------------------------------------------
1053 // ---------------------------------------------------------------------------
1055 wxString
& wxString::MakeUpper()
1057 if ( !CopyBeforeWrite() ) {
1058 wxFAIL_MSG( _T("out of memory in wxString::MakeUpper") );
1062 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1063 *p
= (wxChar
)wxToupper(*p
);
1068 wxString
& wxString::MakeLower()
1070 if ( !CopyBeforeWrite() ) {
1071 wxFAIL_MSG( _T("out of memory in wxString::MakeLower") );
1075 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1076 *p
= (wxChar
)wxTolower(*p
);
1081 // ---------------------------------------------------------------------------
1082 // trimming and padding
1083 // ---------------------------------------------------------------------------
1085 // some compilers (VC++ 6.0 not to name them) return TRUE for a call to
1086 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1087 // live with this by checking that the character is a 7 bit one - even if this
1088 // may fail to detect some spaces (I don't know if Unicode doesn't have
1089 // space-like symbols somewhere except in the first 128 chars), it is arguably
1090 // still better than trimming away accented letters
1091 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1093 // trims spaces (in the sense of isspace) from left or right side
1094 wxString
& wxString::Trim(bool bFromRight
)
1096 // first check if we're going to modify the string at all
1099 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1100 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1104 // ok, there is at least one space to trim
1105 if ( !CopyBeforeWrite() ) {
1106 wxFAIL_MSG( _T("out of memory in wxString::Trim") );
1112 // find last non-space character
1113 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
1114 while ( wxSafeIsspace(*psz
) && (psz
>= m_pchData
) )
1117 // truncate at trailing space start
1119 GetStringData()->nDataLength
= psz
- m_pchData
;
1123 // find first non-space character
1124 const wxChar
*psz
= m_pchData
;
1125 while ( wxSafeIsspace(*psz
) )
1128 // fix up data and length
1129 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
1130 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
1131 GetStringData()->nDataLength
= nDataLength
;
1138 // adds nCount characters chPad to the string from either side
1139 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1141 wxString
s(chPad
, nCount
);
1154 // truncate the string
1155 wxString
& wxString::Truncate(size_t uiLen
)
1157 if ( uiLen
< Len() ) {
1158 if ( !CopyBeforeWrite() ) {
1159 wxFAIL_MSG( _T("out of memory in wxString::Truncate") );
1163 *(m_pchData
+ uiLen
) = wxT('\0');
1164 GetStringData()->nDataLength
= uiLen
;
1166 //else: nothing to do, string is already short enough
1171 // ---------------------------------------------------------------------------
1172 // finding (return wxNOT_FOUND if not found and index otherwise)
1173 // ---------------------------------------------------------------------------
1176 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1178 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
1180 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1183 // find a sub-string (like strstr)
1184 int wxString::Find(const wxChar
*pszSub
) const
1186 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
1188 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1191 // ----------------------------------------------------------------------------
1192 // conversion to numbers
1193 // ----------------------------------------------------------------------------
1195 bool wxString::ToLong(long *val
, int base
) const
1197 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToLong") );
1198 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1200 const wxChar
*start
= c_str();
1202 *val
= wxStrtol(start
, &end
, base
);
1204 // return TRUE only if scan was stopped by the terminating NUL and if the
1205 // string was not empty to start with
1206 return !*end
&& (end
!= start
);
1209 bool wxString::ToULong(unsigned long *val
, int base
) const
1211 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToULong") );
1212 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1214 const wxChar
*start
= c_str();
1216 *val
= wxStrtoul(start
, &end
, base
);
1218 // return TRUE only if scan was stopped by the terminating NUL and if the
1219 // string was not empty to start with
1220 return !*end
&& (end
!= start
);
1223 bool wxString::ToDouble(double *val
) const
1225 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToDouble") );
1227 const wxChar
*start
= c_str();
1229 *val
= wxStrtod(start
, &end
);
1231 // return TRUE only if scan was stopped by the terminating NUL and if the
1232 // string was not empty to start with
1233 return !*end
&& (end
!= start
);
1236 // ---------------------------------------------------------------------------
1238 // ---------------------------------------------------------------------------
1241 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1244 va_start(argptr
, pszFormat
);
1247 s
.PrintfV(pszFormat
, argptr
);
1255 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1258 s
.PrintfV(pszFormat
, argptr
);
1262 int wxString::Printf(const wxChar
*pszFormat
, ...)
1265 va_start(argptr
, pszFormat
);
1267 int iLen
= PrintfV(pszFormat
, argptr
);
1274 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1276 #if wxUSE_EXPERIMENTAL_PRINTF
1277 // the new implementation
1279 // buffer to avoid dynamic memory allocation each time for small strings
1280 char szScratch
[1024];
1283 for (size_t n
= 0; pszFormat
[n
]; n
++)
1284 if (pszFormat
[n
] == wxT('%')) {
1285 static char s_szFlags
[256] = "%";
1287 bool adj_left
= FALSE
, in_prec
= FALSE
,
1288 prec_dot
= FALSE
, done
= FALSE
;
1290 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1292 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1293 switch (pszFormat
[++n
]) {
1307 s_szFlags
[flagofs
++] = pszFormat
[n
];
1312 s_szFlags
[flagofs
++] = pszFormat
[n
];
1319 // dot will be auto-added to s_szFlags if non-negative number follows
1324 s_szFlags
[flagofs
++] = pszFormat
[n
];
1329 s_szFlags
[flagofs
++] = pszFormat
[n
];
1335 s_szFlags
[flagofs
++] = pszFormat
[n
];
1340 s_szFlags
[flagofs
++] = pszFormat
[n
];
1344 int len
= va_arg(argptr
, int);
1351 adj_left
= !adj_left
;
1352 s_szFlags
[flagofs
++] = '-';
1357 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1360 case wxT('1'): case wxT('2'): case wxT('3'):
1361 case wxT('4'): case wxT('5'): case wxT('6'):
1362 case wxT('7'): case wxT('8'): case wxT('9'):
1366 while ((pszFormat
[n
]>=wxT('0')) && (pszFormat
[n
]<=wxT('9'))) {
1367 s_szFlags
[flagofs
++] = pszFormat
[n
];
1368 len
= len
*10 + (pszFormat
[n
] - wxT('0'));
1371 if (in_prec
) max_width
= len
;
1372 else min_width
= len
;
1373 n
--; // the main loop pre-increments n again
1383 s_szFlags
[flagofs
++] = pszFormat
[n
];
1384 s_szFlags
[flagofs
] = '\0';
1386 int val
= va_arg(argptr
, int);
1387 ::sprintf(szScratch
, s_szFlags
, val
);
1389 else if (ilen
== -1) {
1390 short int val
= va_arg(argptr
, short int);
1391 ::sprintf(szScratch
, s_szFlags
, val
);
1393 else if (ilen
== 1) {
1394 long int val
= va_arg(argptr
, long int);
1395 ::sprintf(szScratch
, s_szFlags
, val
);
1397 else if (ilen
== 2) {
1398 #if SIZEOF_LONG_LONG
1399 long long int val
= va_arg(argptr
, long long int);
1400 ::sprintf(szScratch
, s_szFlags
, val
);
1402 long int val
= va_arg(argptr
, long int);
1403 ::sprintf(szScratch
, s_szFlags
, val
);
1406 else if (ilen
== 3) {
1407 size_t val
= va_arg(argptr
, size_t);
1408 ::sprintf(szScratch
, s_szFlags
, val
);
1410 *this += wxString(szScratch
);
1419 s_szFlags
[flagofs
++] = pszFormat
[n
];
1420 s_szFlags
[flagofs
] = '\0';
1422 long double val
= va_arg(argptr
, long double);
1423 ::sprintf(szScratch
, s_szFlags
, val
);
1425 double val
= va_arg(argptr
, double);
1426 ::sprintf(szScratch
, s_szFlags
, val
);
1428 *this += wxString(szScratch
);
1433 void *val
= va_arg(argptr
, void *);
1435 s_szFlags
[flagofs
++] = pszFormat
[n
];
1436 s_szFlags
[flagofs
] = '\0';
1437 ::sprintf(szScratch
, s_szFlags
, val
);
1438 *this += wxString(szScratch
);
1444 wxChar val
= va_arg(argptr
, int);
1445 // we don't need to honor padding here, do we?
1452 // wx extension: we'll let %hs mean non-Unicode strings
1453 char *val
= va_arg(argptr
, char *);
1455 // ASCII->Unicode constructor handles max_width right
1456 wxString
s(val
, wxConvLibc
, max_width
);
1458 size_t len
= wxSTRING_MAXLEN
;
1460 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1461 } else val
= wxT("(null)");
1462 wxString
s(val
, len
);
1464 if (s
.Len() < min_width
)
1465 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1468 wxChar
*val
= va_arg(argptr
, wxChar
*);
1469 size_t len
= wxSTRING_MAXLEN
;
1471 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1472 } else val
= wxT("(null)");
1473 wxString
s(val
, len
);
1474 if (s
.Len() < min_width
)
1475 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1482 int *val
= va_arg(argptr
, int *);
1485 else if (ilen
== -1) {
1486 short int *val
= va_arg(argptr
, short int *);
1489 else if (ilen
>= 1) {
1490 long int *val
= va_arg(argptr
, long int *);
1496 if (wxIsalpha(pszFormat
[n
]))
1497 // probably some flag not taken care of here yet
1498 s_szFlags
[flagofs
++] = pszFormat
[n
];
1501 *this += wxT('%'); // just to pass the glibc tst-printf.c
1509 } else *this += pszFormat
[n
];
1512 // buffer to avoid dynamic memory allocation each time for small strings
1513 char szScratch
[1024];
1515 // NB: wxVsnprintf() may return either less than the buffer size or -1 if
1516 // there is not enough place depending on implementation
1517 int iLen
= wxVsnprintfA(szScratch
, WXSIZEOF(szScratch
), (char *)pszFormat
, argptr
);
1519 // the whole string is in szScratch
1523 bool outOfMemory
= FALSE
;
1524 int size
= 2*WXSIZEOF(szScratch
);
1525 while ( !outOfMemory
) {
1526 char *buf
= GetWriteBuf(size
);
1528 iLen
= wxVsnprintfA(buf
, size
, pszFormat
, argptr
);
1535 // ok, there was enough space
1539 // still not enough, double it again
1543 if ( outOfMemory
) {
1548 #endif // wxUSE_EXPERIMENTAL_PRINTF/!wxUSE_EXPERIMENTAL_PRINTF
1553 // ----------------------------------------------------------------------------
1554 // misc other operations
1555 // ----------------------------------------------------------------------------
1557 // returns TRUE if the string matches the pattern which may contain '*' and
1558 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1560 bool wxString::Matches(const wxChar
*pszMask
) const
1562 // I disable this code as it doesn't seem to be faster (in fact, it seems
1563 // to be much slower) than the old, hand-written code below and using it
1564 // here requires always linking with libregex even if the user code doesn't
1566 #if 0 // wxUSE_REGEX
1567 // first translate the shell-like mask into a regex
1569 pattern
.reserve(wxStrlen(pszMask
));
1581 pattern
+= _T(".*");
1592 // these characters are special in a RE, quote them
1593 // (however note that we don't quote '[' and ']' to allow
1594 // using them for Unix shell like matching)
1595 pattern
+= _T('\\');
1599 pattern
+= *pszMask
;
1607 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1608 #else // !wxUSE_REGEX
1609 // TODO: this is, of course, awfully inefficient...
1611 // the char currently being checked
1612 const wxChar
*pszTxt
= c_str();
1614 // the last location where '*' matched
1615 const wxChar
*pszLastStarInText
= NULL
;
1616 const wxChar
*pszLastStarInMask
= NULL
;
1619 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1620 switch ( *pszMask
) {
1622 if ( *pszTxt
== wxT('\0') )
1625 // pszTxt and pszMask will be incremented in the loop statement
1631 // remember where we started to be able to backtrack later
1632 pszLastStarInText
= pszTxt
;
1633 pszLastStarInMask
= pszMask
;
1635 // ignore special chars immediately following this one
1636 // (should this be an error?)
1637 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1640 // if there is nothing more, match
1641 if ( *pszMask
== wxT('\0') )
1644 // are there any other metacharacters in the mask?
1646 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1648 if ( pEndMask
!= NULL
) {
1649 // we have to match the string between two metachars
1650 uiLenMask
= pEndMask
- pszMask
;
1653 // we have to match the remainder of the string
1654 uiLenMask
= wxStrlen(pszMask
);
1657 wxString
strToMatch(pszMask
, uiLenMask
);
1658 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1659 if ( pMatch
== NULL
)
1662 // -1 to compensate "++" in the loop
1663 pszTxt
= pMatch
+ uiLenMask
- 1;
1664 pszMask
+= uiLenMask
- 1;
1669 if ( *pszMask
!= *pszTxt
)
1675 // match only if nothing left
1676 if ( *pszTxt
== wxT('\0') )
1679 // if we failed to match, backtrack if we can
1680 if ( pszLastStarInText
) {
1681 pszTxt
= pszLastStarInText
+ 1;
1682 pszMask
= pszLastStarInMask
;
1684 pszLastStarInText
= NULL
;
1686 // don't bother resetting pszLastStarInMask, it's unnecessary
1692 #endif // wxUSE_REGEX/!wxUSE_REGEX
1695 // Count the number of chars
1696 int wxString::Freq(wxChar ch
) const
1700 for (int i
= 0; i
< len
; i
++)
1702 if (GetChar(i
) == ch
)
1708 // convert to upper case, return the copy of the string
1709 wxString
wxString::Upper() const
1710 { wxString
s(*this); return s
.MakeUpper(); }
1712 // convert to lower case, return the copy of the string
1713 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1715 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1718 va_start(argptr
, pszFormat
);
1719 int iLen
= PrintfV(pszFormat
, argptr
);
1724 // ---------------------------------------------------------------------------
1725 // standard C++ library string functions
1726 // ---------------------------------------------------------------------------
1728 #ifdef wxSTD_STRING_COMPATIBILITY
1730 void wxString::resize(size_t nSize
, wxChar ch
)
1732 size_t len
= length();
1738 else if ( nSize
> len
)
1740 *this += wxString(ch
, nSize
- len
);
1742 //else: we have exactly the specified length, nothing to do
1745 void wxString::swap(wxString
& str
)
1747 // this is slightly less efficient than fiddling with m_pchData directly,
1748 // but it is still quite efficient as we don't copy the string here because
1749 // ref count always stays positive
1755 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1757 wxASSERT( str
.GetStringData()->IsValid() );
1758 wxASSERT( nPos
<= Len() );
1760 if ( !str
.IsEmpty() ) {
1762 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1763 wxStrncpy(pc
, c_str(), nPos
);
1764 wxStrcpy(pc
+ nPos
, str
);
1765 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1766 strTmp
.UngetWriteBuf();
1773 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1775 wxASSERT( str
.GetStringData()->IsValid() );
1776 wxASSERT( nStart
<= Len() );
1778 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1780 return p
== NULL
? npos
: p
- c_str();
1783 // VC++ 1.5 can't cope with the default argument in the header.
1784 #if !defined(__VISUALC__) || defined(__WIN32__)
1785 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1787 return find(wxString(sz
, n
), nStart
);
1791 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1792 #if !defined(__BORLANDC__)
1793 size_t wxString::find(wxChar ch
, size_t nStart
) const
1795 wxASSERT( nStart
<= Len() );
1797 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1799 return p
== NULL
? npos
: p
- c_str();
1803 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1805 wxASSERT( str
.GetStringData()->IsValid() );
1806 wxASSERT( nStart
== npos
|| nStart
<= Len() );
1808 // TODO could be made much quicker than that
1809 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1810 while ( p
>= c_str() + str
.Len() ) {
1811 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1812 return p
- str
.Len() - c_str();
1819 // VC++ 1.5 can't cope with the default argument in the header.
1820 #if !defined(__VISUALC__) || defined(__WIN32__)
1821 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1823 return rfind(wxString(sz
, n
== npos
? wxSTRING_MAXLEN
: n
), nStart
);
1826 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1828 if ( nStart
== npos
)
1834 wxASSERT( nStart
<= Len() );
1837 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1842 size_t result
= p
- c_str();
1843 return ( result
> nStart
) ? npos
: result
;
1847 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1849 const wxChar
*start
= c_str() + nStart
;
1850 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1852 return firstOf
- c_str();
1857 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1859 if ( nStart
== npos
)
1865 wxASSERT( nStart
<= Len() );
1868 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1870 if ( wxStrchr(sz
, *p
) )
1877 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1879 if ( nStart
== npos
)
1885 wxASSERT( nStart
<= Len() );
1888 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1889 if ( nAccept
>= length() - nStart
)
1895 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1897 wxASSERT( nStart
<= Len() );
1899 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1908 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1910 if ( nStart
== npos
)
1916 wxASSERT( nStart
<= Len() );
1919 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1921 if ( !wxStrchr(sz
, *p
) )
1928 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1930 if ( nStart
== npos
)
1936 wxASSERT( nStart
<= Len() );
1939 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1948 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1950 wxString
strTmp(c_str(), nStart
);
1951 if ( nLen
!= npos
) {
1952 wxASSERT( nStart
+ nLen
<= Len() );
1954 strTmp
.append(c_str() + nStart
+ nLen
);
1961 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1963 wxASSERT_MSG( nStart
+ nLen
<= Len(),
1964 _T("index out of bounds in wxString::replace") );
1967 strTmp
.Alloc(Len()); // micro optimisation to avoid multiple mem allocs
1970 strTmp
.append(c_str(), nStart
);
1971 strTmp
<< sz
<< c_str() + nStart
+ nLen
;
1977 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1979 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1982 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1983 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1985 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1988 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1989 const wxChar
* sz
, size_t nCount
)
1991 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1994 #endif //std::string compatibility
1996 // ============================================================================
1998 // ============================================================================
2000 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
2001 #define ARRAY_MAXSIZE_INCREMENT 4096
2003 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
2004 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
2007 #define STRING(p) ((wxString *)(&(p)))
2010 void wxArrayString::Init(bool autoSort
)
2014 m_pItems
= (wxChar
**) NULL
;
2015 m_autoSort
= autoSort
;
2019 wxArrayString::wxArrayString(const wxArrayString
& src
)
2021 Init(src
.m_autoSort
);
2026 // assignment operator
2027 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
2034 m_autoSort
= src
.m_autoSort
;
2039 void wxArrayString::Copy(const wxArrayString
& src
)
2041 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
2042 Alloc(src
.m_nCount
);
2044 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
2049 void wxArrayString::Grow(size_t nIncrement
)
2051 // only do it if no more place
2052 if ( m_nCount
== m_nSize
) {
2053 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2054 // be never resized!
2055 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2056 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2059 if ( m_nSize
== 0 ) {
2060 // was empty, alloc some memory
2061 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
2062 m_pItems
= new wxChar
*[m_nSize
];
2065 // otherwise when it's called for the first time, nIncrement would be 0
2066 // and the array would never be expanded
2067 // add 50% but not too much
2068 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
2069 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
2070 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
2071 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
2072 if ( nIncrement
< ndefIncrement
)
2073 nIncrement
= ndefIncrement
;
2074 m_nSize
+= nIncrement
;
2075 wxChar
**pNew
= new wxChar
*[m_nSize
];
2077 // copy data to new location
2078 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2080 // delete old memory (but do not release the strings!)
2081 wxDELETEA(m_pItems
);
2088 void wxArrayString::Free()
2090 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
2091 STRING(m_pItems
[n
])->GetStringData()->Unlock();
2095 // deletes all the strings from the list
2096 void wxArrayString::Empty()
2103 // as Empty, but also frees memory
2104 void wxArrayString::Clear()
2111 wxDELETEA(m_pItems
);
2115 wxArrayString::~wxArrayString()
2119 wxDELETEA(m_pItems
);
2122 // pre-allocates memory (frees the previous data!)
2123 void wxArrayString::Alloc(size_t nSize
)
2125 // only if old buffer was not big enough
2126 if ( nSize
> m_nSize
) {
2128 wxDELETEA(m_pItems
);
2129 m_pItems
= new wxChar
*[nSize
];
2136 // minimizes the memory usage by freeing unused memory
2137 void wxArrayString::Shrink()
2139 // only do it if we have some memory to free
2140 if( m_nCount
< m_nSize
) {
2141 // allocates exactly as much memory as we need
2142 wxChar
**pNew
= new wxChar
*[m_nCount
];
2144 // copy data to new location
2145 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2151 // return a wxString[] as required for some control ctors.
2152 wxString
* wxArrayString::GetStringArray() const
2154 wxString
*array
= 0;
2158 array
= new wxString
[m_nCount
];
2159 for( size_t i
= 0; i
< m_nCount
; i
++ )
2160 array
[i
] = m_pItems
[i
];
2166 // searches the array for an item (forward or backwards)
2167 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2170 // use binary search in the sorted array
2171 wxASSERT_MSG( bCase
&& !bFromEnd
,
2172 wxT("search parameters ignored for auto sorted array") );
2181 res
= wxStrcmp(sz
, m_pItems
[i
]);
2193 // use linear search in unsorted array
2195 if ( m_nCount
> 0 ) {
2196 size_t ui
= m_nCount
;
2198 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2205 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2206 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2215 // add item at the end
2216 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
2219 // insert the string at the correct position to keep the array sorted
2227 res
= wxStrcmp(str
, m_pItems
[i
]);
2238 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2240 Insert(str
, lo
, nInsert
);
2245 wxASSERT( str
.GetStringData()->IsValid() );
2249 for (size_t i
= 0; i
< nInsert
; i
++)
2251 // the string data must not be deleted!
2252 str
.GetStringData()->Lock();
2255 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2257 size_t ret
= m_nCount
;
2258 m_nCount
+= nInsert
;
2263 // add item at the given position
2264 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2266 wxASSERT( str
.GetStringData()->IsValid() );
2268 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2269 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2270 wxT("array size overflow in wxArrayString::Insert") );
2274 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2275 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2277 for (size_t i
= 0; i
< nInsert
; i
++)
2279 str
.GetStringData()->Lock();
2280 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2282 m_nCount
+= nInsert
;
2286 void wxArrayString::SetCount(size_t count
)
2291 while ( m_nCount
< count
)
2292 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2295 // removes item from array (by index)
2296 void wxArrayString::Remove(size_t nIndex
, size_t nRemove
)
2298 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2299 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2300 wxT("removing too many elements in wxArrayString::Remove") );
2303 for (size_t i
= 0; i
< nRemove
; i
++)
2304 Item(nIndex
+ i
).GetStringData()->Unlock();
2306 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2307 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2308 m_nCount
-= nRemove
;
2311 // removes item from array (by value)
2312 void wxArrayString::Remove(const wxChar
*sz
)
2314 int iIndex
= Index(sz
);
2316 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2317 wxT("removing inexistent element in wxArrayString::Remove") );
2322 // ----------------------------------------------------------------------------
2324 // ----------------------------------------------------------------------------
2326 // we can only sort one array at a time with the quick-sort based
2329 // need a critical section to protect access to gs_compareFunction and
2330 // gs_sortAscending variables
2331 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2333 // call this before the value of the global sort vars is changed/after
2334 // you're finished with them
2335 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2336 gs_critsectStringSort = new wxCriticalSection; \
2337 gs_critsectStringSort->Enter()
2338 #define END_SORT() gs_critsectStringSort->Leave(); \
2339 delete gs_critsectStringSort; \
2340 gs_critsectStringSort = NULL
2342 #define START_SORT()
2344 #endif // wxUSE_THREADS
2346 // function to use for string comparaison
2347 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2349 // if we don't use the compare function, this flag tells us if we sort the
2350 // array in ascending or descending order
2351 static bool gs_sortAscending
= TRUE
;
2353 // function which is called by quick sort
2354 extern "C" int LINKAGEMODE
2355 wxStringCompareFunction(const void *first
, const void *second
)
2357 wxString
*strFirst
= (wxString
*)first
;
2358 wxString
*strSecond
= (wxString
*)second
;
2360 if ( gs_compareFunction
) {
2361 return gs_compareFunction(*strFirst
, *strSecond
);
2364 // maybe we should use wxStrcoll
2365 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
2367 return gs_sortAscending
? result
: -result
;
2371 // sort array elements using passed comparaison function
2372 void wxArrayString::Sort(CompareFunction compareFunction
)
2376 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2377 gs_compareFunction
= compareFunction
;
2381 // reset it to NULL so that Sort(bool) will work the next time
2382 gs_compareFunction
= NULL
;
2387 void wxArrayString::Sort(bool reverseOrder
)
2391 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2392 gs_sortAscending
= !reverseOrder
;
2399 void wxArrayString::DoSort()
2401 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2403 // just sort the pointers using qsort() - of course it only works because
2404 // wxString() *is* a pointer to its data
2405 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2408 bool wxArrayString::operator==(const wxArrayString
& a
) const
2410 if ( m_nCount
!= a
.m_nCount
)
2413 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2415 if ( Item(n
) != a
[n
] )