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 // ===========================================================================
762 wxString
wxString::FromAscii( char *ascii
)
765 return wxEmptyString
;
767 size_t len
= strlen( ascii
);
769 res
.AllocBuffer( len
);
770 wchar_t *dest
= (wchar_t*)(const wchar_t*) res
.c_str();
772 for (size_t i
= 0; i
< len
+1; i
++)
773 dest
[i
] = (wchar_t) ascii
[i
];
778 const wxCharBuffer
wxString::ToAscii() const
781 return wxCharBuffer( (const char*)NULL
);
784 wxCharBuffer
buffer( len
); // allocates len+1
786 char *dest
= (char*)(const char*) buffer
;
788 for (size_t i
= 0; i
< len
+1; i
++)
790 if (m_pchData
[i
] > 127)
793 dest
[i
] = (char) m_pchData
[i
];
800 // ---------------------------------------------------------------------------
801 // simple sub-string extraction
802 // ---------------------------------------------------------------------------
804 // helper function: clone the data attached to this string
805 bool wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
807 if ( nCopyLen
== 0 ) {
811 if ( !dest
.AllocBuffer(nCopyLen
) ) {
812 // allocation failure handled by caller
815 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
820 // extract string of length nCount starting at nFirst
821 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
823 wxStringData
*pData
= GetStringData();
824 size_t nLen
= pData
->nDataLength
;
826 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
827 if ( nCount
== wxSTRING_MAXLEN
)
829 nCount
= nLen
- nFirst
;
832 // out-of-bounds requests return sensible things
833 if ( nFirst
+ nCount
> nLen
)
835 nCount
= nLen
- nFirst
;
840 // AllocCopy() will return empty string
845 if ( !AllocCopy(dest
, nCount
, nFirst
) ) {
846 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
852 // check that the tring starts with prefix and return the rest of the string
853 // in the provided pointer if it is not NULL, otherwise return FALSE
854 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
856 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
858 // first check if the beginning of the string matches the prefix: note
859 // that we don't have to check that we don't run out of this string as
860 // when we reach the terminating NUL, either prefix string ends too (and
861 // then it's ok) or we break out of the loop because there is no match
862 const wxChar
*p
= c_str();
865 if ( *prefix
++ != *p
++ )
874 // put the rest of the string into provided pointer
881 // extract nCount last (rightmost) characters
882 wxString
wxString::Right(size_t nCount
) const
884 if ( nCount
> (size_t)GetStringData()->nDataLength
)
885 nCount
= GetStringData()->nDataLength
;
888 if ( !AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
) ) {
889 wxFAIL_MSG( _T("out of memory in wxString::Right") );
894 // get all characters after the last occurence of ch
895 // (returns the whole string if ch not found)
896 wxString
wxString::AfterLast(wxChar ch
) const
899 int iPos
= Find(ch
, TRUE
);
900 if ( iPos
== wxNOT_FOUND
)
903 str
= c_str() + iPos
+ 1;
908 // extract nCount first (leftmost) characters
909 wxString
wxString::Left(size_t nCount
) const
911 if ( nCount
> (size_t)GetStringData()->nDataLength
)
912 nCount
= GetStringData()->nDataLength
;
915 if ( !AllocCopy(dest
, nCount
, 0) ) {
916 wxFAIL_MSG( _T("out of memory in wxString::Left") );
921 // get all characters before the first occurence of ch
922 // (returns the whole string if ch not found)
923 wxString
wxString::BeforeFirst(wxChar ch
) const
926 for ( const wxChar
*pc
= m_pchData
; *pc
!= wxT('\0') && *pc
!= ch
; pc
++ )
932 /// get all characters before the last occurence of ch
933 /// (returns empty string if ch not found)
934 wxString
wxString::BeforeLast(wxChar ch
) const
937 int iPos
= Find(ch
, TRUE
);
938 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
939 str
= wxString(c_str(), iPos
);
944 /// get all characters after the first occurence of ch
945 /// (returns empty string if ch not found)
946 wxString
wxString::AfterFirst(wxChar ch
) const
950 if ( iPos
!= wxNOT_FOUND
)
951 str
= c_str() + iPos
+ 1;
956 // replace first (or all) occurences of some substring with another one
957 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
959 size_t uiCount
= 0; // count of replacements made
961 size_t uiOldLen
= wxStrlen(szOld
);
964 const wxChar
*pCurrent
= m_pchData
;
965 const wxChar
*pSubstr
;
966 while ( *pCurrent
!= wxT('\0') ) {
967 pSubstr
= wxStrstr(pCurrent
, szOld
);
968 if ( pSubstr
== NULL
) {
969 // strTemp is unused if no replacements were made, so avoid the copy
973 strTemp
+= pCurrent
; // copy the rest
974 break; // exit the loop
977 // take chars before match
978 if ( !strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
) ) {
979 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
983 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
988 if ( !bReplaceAll
) {
989 strTemp
+= pCurrent
; // copy the rest
990 break; // exit the loop
995 // only done if there were replacements, otherwise would have returned above
1001 bool wxString::IsAscii() const
1003 const wxChar
*s
= (const wxChar
*) *this;
1005 if(!isascii(*s
)) return(FALSE
);
1011 bool wxString::IsWord() const
1013 const wxChar
*s
= (const wxChar
*) *this;
1015 if(!wxIsalpha(*s
)) return(FALSE
);
1021 bool wxString::IsNumber() const
1023 const wxChar
*s
= (const wxChar
*) *this;
1025 if ((s
[0] == '-') || (s
[0] == '+')) s
++;
1027 if(!wxIsdigit(*s
)) return(FALSE
);
1033 wxString
wxString::Strip(stripType w
) const
1036 if ( w
& leading
) s
.Trim(FALSE
);
1037 if ( w
& trailing
) s
.Trim(TRUE
);
1041 // ---------------------------------------------------------------------------
1043 // ---------------------------------------------------------------------------
1045 wxString
& wxString::MakeUpper()
1047 if ( !CopyBeforeWrite() ) {
1048 wxFAIL_MSG( _T("out of memory in wxString::MakeUpper") );
1052 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1053 *p
= (wxChar
)wxToupper(*p
);
1058 wxString
& wxString::MakeLower()
1060 if ( !CopyBeforeWrite() ) {
1061 wxFAIL_MSG( _T("out of memory in wxString::MakeLower") );
1065 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1066 *p
= (wxChar
)wxTolower(*p
);
1071 // ---------------------------------------------------------------------------
1072 // trimming and padding
1073 // ---------------------------------------------------------------------------
1075 // some compilers (VC++ 6.0 not to name them) return TRUE for a call to
1076 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1077 // live with this by checking that the character is a 7 bit one - even if this
1078 // may fail to detect some spaces (I don't know if Unicode doesn't have
1079 // space-like symbols somewhere except in the first 128 chars), it is arguably
1080 // still better than trimming away accented letters
1081 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1083 // trims spaces (in the sense of isspace) from left or right side
1084 wxString
& wxString::Trim(bool bFromRight
)
1086 // first check if we're going to modify the string at all
1089 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1090 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1094 // ok, there is at least one space to trim
1095 if ( !CopyBeforeWrite() ) {
1096 wxFAIL_MSG( _T("out of memory in wxString::Trim") );
1102 // find last non-space character
1103 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
1104 while ( wxSafeIsspace(*psz
) && (psz
>= m_pchData
) )
1107 // truncate at trailing space start
1109 GetStringData()->nDataLength
= psz
- m_pchData
;
1113 // find first non-space character
1114 const wxChar
*psz
= m_pchData
;
1115 while ( wxSafeIsspace(*psz
) )
1118 // fix up data and length
1119 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
1120 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
1121 GetStringData()->nDataLength
= nDataLength
;
1128 // adds nCount characters chPad to the string from either side
1129 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1131 wxString
s(chPad
, nCount
);
1144 // truncate the string
1145 wxString
& wxString::Truncate(size_t uiLen
)
1147 if ( uiLen
< Len() ) {
1148 if ( !CopyBeforeWrite() ) {
1149 wxFAIL_MSG( _T("out of memory in wxString::Truncate") );
1153 *(m_pchData
+ uiLen
) = wxT('\0');
1154 GetStringData()->nDataLength
= uiLen
;
1156 //else: nothing to do, string is already short enough
1161 // ---------------------------------------------------------------------------
1162 // finding (return wxNOT_FOUND if not found and index otherwise)
1163 // ---------------------------------------------------------------------------
1166 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1168 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
1170 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1173 // find a sub-string (like strstr)
1174 int wxString::Find(const wxChar
*pszSub
) const
1176 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
1178 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1181 // ----------------------------------------------------------------------------
1182 // conversion to numbers
1183 // ----------------------------------------------------------------------------
1185 bool wxString::ToLong(long *val
, int base
) const
1187 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToLong") );
1188 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1190 const wxChar
*start
= c_str();
1192 *val
= wxStrtol(start
, &end
, base
);
1194 // return TRUE only if scan was stopped by the terminating NUL and if the
1195 // string was not empty to start with
1196 return !*end
&& (end
!= start
);
1199 bool wxString::ToULong(unsigned long *val
, int base
) const
1201 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToULong") );
1202 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1204 const wxChar
*start
= c_str();
1206 *val
= wxStrtoul(start
, &end
, base
);
1208 // return TRUE only if scan was stopped by the terminating NUL and if the
1209 // string was not empty to start with
1210 return !*end
&& (end
!= start
);
1213 bool wxString::ToDouble(double *val
) const
1215 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToDouble") );
1217 const wxChar
*start
= c_str();
1219 *val
= wxStrtod(start
, &end
);
1221 // return TRUE only if scan was stopped by the terminating NUL and if the
1222 // string was not empty to start with
1223 return !*end
&& (end
!= start
);
1226 // ---------------------------------------------------------------------------
1228 // ---------------------------------------------------------------------------
1231 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1234 va_start(argptr
, pszFormat
);
1237 s
.PrintfV(pszFormat
, argptr
);
1245 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1248 s
.PrintfV(pszFormat
, argptr
);
1252 int wxString::Printf(const wxChar
*pszFormat
, ...)
1255 va_start(argptr
, pszFormat
);
1257 int iLen
= PrintfV(pszFormat
, argptr
);
1264 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1266 #if wxUSE_EXPERIMENTAL_PRINTF
1267 // the new implementation
1269 // buffer to avoid dynamic memory allocation each time for small strings
1270 char szScratch
[1024];
1273 for (size_t n
= 0; pszFormat
[n
]; n
++)
1274 if (pszFormat
[n
] == wxT('%')) {
1275 static char s_szFlags
[256] = "%";
1277 bool adj_left
= FALSE
, in_prec
= FALSE
,
1278 prec_dot
= FALSE
, done
= FALSE
;
1280 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1282 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1283 switch (pszFormat
[++n
]) {
1297 s_szFlags
[flagofs
++] = pszFormat
[n
];
1302 s_szFlags
[flagofs
++] = pszFormat
[n
];
1309 // dot will be auto-added to s_szFlags if non-negative number follows
1314 s_szFlags
[flagofs
++] = pszFormat
[n
];
1319 s_szFlags
[flagofs
++] = pszFormat
[n
];
1325 s_szFlags
[flagofs
++] = pszFormat
[n
];
1330 s_szFlags
[flagofs
++] = pszFormat
[n
];
1334 int len
= va_arg(argptr
, int);
1341 adj_left
= !adj_left
;
1342 s_szFlags
[flagofs
++] = '-';
1347 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1350 case wxT('1'): case wxT('2'): case wxT('3'):
1351 case wxT('4'): case wxT('5'): case wxT('6'):
1352 case wxT('7'): case wxT('8'): case wxT('9'):
1356 while ((pszFormat
[n
]>=wxT('0')) && (pszFormat
[n
]<=wxT('9'))) {
1357 s_szFlags
[flagofs
++] = pszFormat
[n
];
1358 len
= len
*10 + (pszFormat
[n
] - wxT('0'));
1361 if (in_prec
) max_width
= len
;
1362 else min_width
= len
;
1363 n
--; // the main loop pre-increments n again
1373 s_szFlags
[flagofs
++] = pszFormat
[n
];
1374 s_szFlags
[flagofs
] = '\0';
1376 int val
= va_arg(argptr
, int);
1377 ::sprintf(szScratch
, s_szFlags
, val
);
1379 else if (ilen
== -1) {
1380 short int val
= va_arg(argptr
, short int);
1381 ::sprintf(szScratch
, s_szFlags
, val
);
1383 else if (ilen
== 1) {
1384 long int val
= va_arg(argptr
, long int);
1385 ::sprintf(szScratch
, s_szFlags
, val
);
1387 else if (ilen
== 2) {
1388 #if SIZEOF_LONG_LONG
1389 long long int val
= va_arg(argptr
, long long int);
1390 ::sprintf(szScratch
, s_szFlags
, val
);
1392 long int val
= va_arg(argptr
, long int);
1393 ::sprintf(szScratch
, s_szFlags
, val
);
1396 else if (ilen
== 3) {
1397 size_t val
= va_arg(argptr
, size_t);
1398 ::sprintf(szScratch
, s_szFlags
, val
);
1400 *this += wxString(szScratch
);
1409 s_szFlags
[flagofs
++] = pszFormat
[n
];
1410 s_szFlags
[flagofs
] = '\0';
1412 long double val
= va_arg(argptr
, long double);
1413 ::sprintf(szScratch
, s_szFlags
, val
);
1415 double val
= va_arg(argptr
, double);
1416 ::sprintf(szScratch
, s_szFlags
, val
);
1418 *this += wxString(szScratch
);
1423 void *val
= va_arg(argptr
, void *);
1425 s_szFlags
[flagofs
++] = pszFormat
[n
];
1426 s_szFlags
[flagofs
] = '\0';
1427 ::sprintf(szScratch
, s_szFlags
, val
);
1428 *this += wxString(szScratch
);
1434 wxChar val
= va_arg(argptr
, int);
1435 // we don't need to honor padding here, do we?
1442 // wx extension: we'll let %hs mean non-Unicode strings
1443 char *val
= va_arg(argptr
, char *);
1445 // ASCII->Unicode constructor handles max_width right
1446 wxString
s(val
, wxConvLibc
, max_width
);
1448 size_t len
= wxSTRING_MAXLEN
;
1450 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1451 } else val
= wxT("(null)");
1452 wxString
s(val
, len
);
1454 if (s
.Len() < min_width
)
1455 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1458 wxChar
*val
= va_arg(argptr
, wxChar
*);
1459 size_t len
= wxSTRING_MAXLEN
;
1461 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1462 } else val
= wxT("(null)");
1463 wxString
s(val
, len
);
1464 if (s
.Len() < min_width
)
1465 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1472 int *val
= va_arg(argptr
, int *);
1475 else if (ilen
== -1) {
1476 short int *val
= va_arg(argptr
, short int *);
1479 else if (ilen
>= 1) {
1480 long int *val
= va_arg(argptr
, long int *);
1486 if (wxIsalpha(pszFormat
[n
]))
1487 // probably some flag not taken care of here yet
1488 s_szFlags
[flagofs
++] = pszFormat
[n
];
1491 *this += wxT('%'); // just to pass the glibc tst-printf.c
1499 } else *this += pszFormat
[n
];
1502 // buffer to avoid dynamic memory allocation each time for small strings
1503 char szScratch
[1024];
1505 // NB: wxVsnprintf() may return either less than the buffer size or -1 if
1506 // there is not enough place depending on implementation
1507 int iLen
= wxVsnprintfA(szScratch
, WXSIZEOF(szScratch
), (char *)pszFormat
, argptr
);
1509 // the whole string is in szScratch
1513 bool outOfMemory
= FALSE
;
1514 int size
= 2*WXSIZEOF(szScratch
);
1515 while ( !outOfMemory
) {
1516 char *buf
= GetWriteBuf(size
);
1518 iLen
= wxVsnprintfA(buf
, size
, pszFormat
, argptr
);
1525 // ok, there was enough space
1529 // still not enough, double it again
1533 if ( outOfMemory
) {
1538 #endif // wxUSE_EXPERIMENTAL_PRINTF/!wxUSE_EXPERIMENTAL_PRINTF
1543 // ----------------------------------------------------------------------------
1544 // misc other operations
1545 // ----------------------------------------------------------------------------
1547 // returns TRUE if the string matches the pattern which may contain '*' and
1548 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1550 bool wxString::Matches(const wxChar
*pszMask
) const
1552 // I disable this code as it doesn't seem to be faster (in fact, it seems
1553 // to be much slower) than the old, hand-written code below and using it
1554 // here requires always linking with libregex even if the user code doesn't
1556 #if 0 // wxUSE_REGEX
1557 // first translate the shell-like mask into a regex
1559 pattern
.reserve(wxStrlen(pszMask
));
1571 pattern
+= _T(".*");
1582 // these characters are special in a RE, quote them
1583 // (however note that we don't quote '[' and ']' to allow
1584 // using them for Unix shell like matching)
1585 pattern
+= _T('\\');
1589 pattern
+= *pszMask
;
1597 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1598 #else // !wxUSE_REGEX
1599 // TODO: this is, of course, awfully inefficient...
1601 // the char currently being checked
1602 const wxChar
*pszTxt
= c_str();
1604 // the last location where '*' matched
1605 const wxChar
*pszLastStarInText
= NULL
;
1606 const wxChar
*pszLastStarInMask
= NULL
;
1609 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1610 switch ( *pszMask
) {
1612 if ( *pszTxt
== wxT('\0') )
1615 // pszTxt and pszMask will be incremented in the loop statement
1621 // remember where we started to be able to backtrack later
1622 pszLastStarInText
= pszTxt
;
1623 pszLastStarInMask
= pszMask
;
1625 // ignore special chars immediately following this one
1626 // (should this be an error?)
1627 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1630 // if there is nothing more, match
1631 if ( *pszMask
== wxT('\0') )
1634 // are there any other metacharacters in the mask?
1636 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1638 if ( pEndMask
!= NULL
) {
1639 // we have to match the string between two metachars
1640 uiLenMask
= pEndMask
- pszMask
;
1643 // we have to match the remainder of the string
1644 uiLenMask
= wxStrlen(pszMask
);
1647 wxString
strToMatch(pszMask
, uiLenMask
);
1648 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1649 if ( pMatch
== NULL
)
1652 // -1 to compensate "++" in the loop
1653 pszTxt
= pMatch
+ uiLenMask
- 1;
1654 pszMask
+= uiLenMask
- 1;
1659 if ( *pszMask
!= *pszTxt
)
1665 // match only if nothing left
1666 if ( *pszTxt
== wxT('\0') )
1669 // if we failed to match, backtrack if we can
1670 if ( pszLastStarInText
) {
1671 pszTxt
= pszLastStarInText
+ 1;
1672 pszMask
= pszLastStarInMask
;
1674 pszLastStarInText
= NULL
;
1676 // don't bother resetting pszLastStarInMask, it's unnecessary
1682 #endif // wxUSE_REGEX/!wxUSE_REGEX
1685 // Count the number of chars
1686 int wxString::Freq(wxChar ch
) const
1690 for (int i
= 0; i
< len
; i
++)
1692 if (GetChar(i
) == ch
)
1698 // convert to upper case, return the copy of the string
1699 wxString
wxString::Upper() const
1700 { wxString
s(*this); return s
.MakeUpper(); }
1702 // convert to lower case, return the copy of the string
1703 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1705 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1708 va_start(argptr
, pszFormat
);
1709 int iLen
= PrintfV(pszFormat
, argptr
);
1714 // ---------------------------------------------------------------------------
1715 // standard C++ library string functions
1716 // ---------------------------------------------------------------------------
1718 #ifdef wxSTD_STRING_COMPATIBILITY
1720 void wxString::resize(size_t nSize
, wxChar ch
)
1722 size_t len
= length();
1728 else if ( nSize
> len
)
1730 *this += wxString(ch
, nSize
- len
);
1732 //else: we have exactly the specified length, nothing to do
1735 void wxString::swap(wxString
& str
)
1737 // this is slightly less efficient than fiddling with m_pchData directly,
1738 // but it is still quite efficient as we don't copy the string here because
1739 // ref count always stays positive
1745 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1747 wxASSERT( str
.GetStringData()->IsValid() );
1748 wxASSERT( nPos
<= Len() );
1750 if ( !str
.IsEmpty() ) {
1752 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1753 wxStrncpy(pc
, c_str(), nPos
);
1754 wxStrcpy(pc
+ nPos
, str
);
1755 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1756 strTmp
.UngetWriteBuf();
1763 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1765 wxASSERT( str
.GetStringData()->IsValid() );
1766 wxASSERT( nStart
<= Len() );
1768 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1770 return p
== NULL
? npos
: p
- c_str();
1773 // VC++ 1.5 can't cope with the default argument in the header.
1774 #if !defined(__VISUALC__) || defined(__WIN32__)
1775 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1777 return find(wxString(sz
, n
), nStart
);
1781 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1782 #if !defined(__BORLANDC__)
1783 size_t wxString::find(wxChar ch
, size_t nStart
) const
1785 wxASSERT( nStart
<= Len() );
1787 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1789 return p
== NULL
? npos
: p
- c_str();
1793 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1795 wxASSERT( str
.GetStringData()->IsValid() );
1796 wxASSERT( nStart
== npos
|| nStart
<= Len() );
1798 // TODO could be made much quicker than that
1799 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1800 while ( p
>= c_str() + str
.Len() ) {
1801 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1802 return p
- str
.Len() - c_str();
1809 // VC++ 1.5 can't cope with the default argument in the header.
1810 #if !defined(__VISUALC__) || defined(__WIN32__)
1811 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1813 return rfind(wxString(sz
, n
== npos
? wxSTRING_MAXLEN
: n
), nStart
);
1816 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1818 if ( nStart
== npos
)
1824 wxASSERT( nStart
<= Len() );
1827 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1832 size_t result
= p
- c_str();
1833 return ( result
> nStart
) ? npos
: result
;
1837 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1839 const wxChar
*start
= c_str() + nStart
;
1840 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1842 return firstOf
- c_str();
1847 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1849 if ( nStart
== npos
)
1855 wxASSERT( nStart
<= Len() );
1858 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1860 if ( wxStrchr(sz
, *p
) )
1867 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1869 if ( nStart
== npos
)
1875 wxASSERT( nStart
<= Len() );
1878 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1879 if ( nAccept
>= length() - nStart
)
1885 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1887 wxASSERT( nStart
<= Len() );
1889 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1898 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1900 if ( nStart
== npos
)
1906 wxASSERT( nStart
<= Len() );
1909 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1911 if ( !wxStrchr(sz
, *p
) )
1918 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1920 if ( nStart
== npos
)
1926 wxASSERT( nStart
<= Len() );
1929 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1938 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1940 wxString
strTmp(c_str(), nStart
);
1941 if ( nLen
!= npos
) {
1942 wxASSERT( nStart
+ nLen
<= Len() );
1944 strTmp
.append(c_str() + nStart
+ nLen
);
1951 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1953 wxASSERT_MSG( nStart
+ nLen
<= Len(),
1954 _T("index out of bounds in wxString::replace") );
1957 strTmp
.Alloc(Len()); // micro optimisation to avoid multiple mem allocs
1960 strTmp
.append(c_str(), nStart
);
1961 strTmp
<< sz
<< c_str() + nStart
+ nLen
;
1967 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1969 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1972 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1973 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1975 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1978 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1979 const wxChar
* sz
, size_t nCount
)
1981 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1984 #endif //std::string compatibility
1986 // ============================================================================
1988 // ============================================================================
1990 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1991 #define ARRAY_MAXSIZE_INCREMENT 4096
1993 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1994 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1997 #define STRING(p) ((wxString *)(&(p)))
2000 void wxArrayString::Init(bool autoSort
)
2004 m_pItems
= (wxChar
**) NULL
;
2005 m_autoSort
= autoSort
;
2009 wxArrayString::wxArrayString(const wxArrayString
& src
)
2011 Init(src
.m_autoSort
);
2016 // assignment operator
2017 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
2024 m_autoSort
= src
.m_autoSort
;
2029 void wxArrayString::Copy(const wxArrayString
& src
)
2031 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
2032 Alloc(src
.m_nCount
);
2034 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
2039 void wxArrayString::Grow(size_t nIncrement
)
2041 // only do it if no more place
2042 if ( m_nCount
== m_nSize
) {
2043 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2044 // be never resized!
2045 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2046 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2049 if ( m_nSize
== 0 ) {
2050 // was empty, alloc some memory
2051 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
2052 m_pItems
= new wxChar
*[m_nSize
];
2055 // otherwise when it's called for the first time, nIncrement would be 0
2056 // and the array would never be expanded
2057 // add 50% but not too much
2058 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
2059 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
2060 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
2061 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
2062 if ( nIncrement
< ndefIncrement
)
2063 nIncrement
= ndefIncrement
;
2064 m_nSize
+= nIncrement
;
2065 wxChar
**pNew
= new wxChar
*[m_nSize
];
2067 // copy data to new location
2068 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2070 // delete old memory (but do not release the strings!)
2071 wxDELETEA(m_pItems
);
2078 void wxArrayString::Free()
2080 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
2081 STRING(m_pItems
[n
])->GetStringData()->Unlock();
2085 // deletes all the strings from the list
2086 void wxArrayString::Empty()
2093 // as Empty, but also frees memory
2094 void wxArrayString::Clear()
2101 wxDELETEA(m_pItems
);
2105 wxArrayString::~wxArrayString()
2109 wxDELETEA(m_pItems
);
2112 // pre-allocates memory (frees the previous data!)
2113 void wxArrayString::Alloc(size_t nSize
)
2115 // only if old buffer was not big enough
2116 if ( nSize
> m_nSize
) {
2118 wxDELETEA(m_pItems
);
2119 m_pItems
= new wxChar
*[nSize
];
2126 // minimizes the memory usage by freeing unused memory
2127 void wxArrayString::Shrink()
2129 // only do it if we have some memory to free
2130 if( m_nCount
< m_nSize
) {
2131 // allocates exactly as much memory as we need
2132 wxChar
**pNew
= new wxChar
*[m_nCount
];
2134 // copy data to new location
2135 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2141 // return a wxString[] as required for some control ctors.
2142 wxString
* wxArrayString::GetStringArray() const
2144 wxString
*array
= 0;
2148 array
= new wxString
[m_nCount
];
2149 for( size_t i
= 0; i
< m_nCount
; i
++ )
2150 array
[i
] = m_pItems
[i
];
2156 // searches the array for an item (forward or backwards)
2157 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2160 // use binary search in the sorted array
2161 wxASSERT_MSG( bCase
&& !bFromEnd
,
2162 wxT("search parameters ignored for auto sorted array") );
2171 res
= wxStrcmp(sz
, m_pItems
[i
]);
2183 // use linear search in unsorted array
2185 if ( m_nCount
> 0 ) {
2186 size_t ui
= m_nCount
;
2188 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2195 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2196 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2205 // add item at the end
2206 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
2209 // insert the string at the correct position to keep the array sorted
2217 res
= wxStrcmp(str
, m_pItems
[i
]);
2228 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2230 Insert(str
, lo
, nInsert
);
2235 wxASSERT( str
.GetStringData()->IsValid() );
2239 for (size_t i
= 0; i
< nInsert
; i
++)
2241 // the string data must not be deleted!
2242 str
.GetStringData()->Lock();
2245 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2247 size_t ret
= m_nCount
;
2248 m_nCount
+= nInsert
;
2253 // add item at the given position
2254 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2256 wxASSERT( str
.GetStringData()->IsValid() );
2258 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2259 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2260 wxT("array size overflow in wxArrayString::Insert") );
2264 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2265 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2267 for (size_t i
= 0; i
< nInsert
; i
++)
2269 str
.GetStringData()->Lock();
2270 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2272 m_nCount
+= nInsert
;
2276 void wxArrayString::SetCount(size_t count
)
2281 while ( m_nCount
< count
)
2282 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2285 // removes item from array (by index)
2286 void wxArrayString::Remove(size_t nIndex
, size_t nRemove
)
2288 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2289 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2290 wxT("removing too many elements in wxArrayString::Remove") );
2293 for (size_t i
= 0; i
< nRemove
; i
++)
2294 Item(nIndex
+ i
).GetStringData()->Unlock();
2296 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2297 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2298 m_nCount
-= nRemove
;
2301 // removes item from array (by value)
2302 void wxArrayString::Remove(const wxChar
*sz
)
2304 int iIndex
= Index(sz
);
2306 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2307 wxT("removing inexistent element in wxArrayString::Remove") );
2312 // ----------------------------------------------------------------------------
2314 // ----------------------------------------------------------------------------
2316 // we can only sort one array at a time with the quick-sort based
2319 // need a critical section to protect access to gs_compareFunction and
2320 // gs_sortAscending variables
2321 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2323 // call this before the value of the global sort vars is changed/after
2324 // you're finished with them
2325 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2326 gs_critsectStringSort = new wxCriticalSection; \
2327 gs_critsectStringSort->Enter()
2328 #define END_SORT() gs_critsectStringSort->Leave(); \
2329 delete gs_critsectStringSort; \
2330 gs_critsectStringSort = NULL
2332 #define START_SORT()
2334 #endif // wxUSE_THREADS
2336 // function to use for string comparaison
2337 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2339 // if we don't use the compare function, this flag tells us if we sort the
2340 // array in ascending or descending order
2341 static bool gs_sortAscending
= TRUE
;
2343 // function which is called by quick sort
2344 extern "C" int LINKAGEMODE
2345 wxStringCompareFunction(const void *first
, const void *second
)
2347 wxString
*strFirst
= (wxString
*)first
;
2348 wxString
*strSecond
= (wxString
*)second
;
2350 if ( gs_compareFunction
) {
2351 return gs_compareFunction(*strFirst
, *strSecond
);
2354 // maybe we should use wxStrcoll
2355 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
2357 return gs_sortAscending
? result
: -result
;
2361 // sort array elements using passed comparaison function
2362 void wxArrayString::Sort(CompareFunction compareFunction
)
2366 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2367 gs_compareFunction
= compareFunction
;
2371 // reset it to NULL so that Sort(bool) will work the next time
2372 gs_compareFunction
= NULL
;
2377 void wxArrayString::Sort(bool reverseOrder
)
2381 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2382 gs_sortAscending
= !reverseOrder
;
2389 void wxArrayString::DoSort()
2391 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2393 // just sort the pointers using qsort() - of course it only works because
2394 // wxString() *is* a pointer to its data
2395 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2398 bool wxArrayString::operator==(const wxArrayString
& a
) const
2400 if ( m_nCount
!= a
.m_nCount
)
2403 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2405 if ( Item(n
) != a
[n
] )