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
51 #define wxUSE_EXPERIMENTAL_PRINTF 1
54 // allocating extra space for each string consumes more memory but speeds up
55 // the concatenation operations (nLen is the current string's length)
56 // NB: EXTRA_ALLOC must be >= 0!
57 #define EXTRA_ALLOC (19 - nLen % 16)
59 // ---------------------------------------------------------------------------
60 // static class variables definition
61 // ---------------------------------------------------------------------------
63 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
64 // must define this static for VA or else you get multiply defined symbols
66 const unsigned int wxSTRING_MAXLEN
= UINT_MAX
- 100;
69 #ifdef wxSTD_STRING_COMPATIBILITY
70 const size_t wxString::npos
= wxSTRING_MAXLEN
;
71 #endif // wxSTD_STRING_COMPATIBILITY
73 // ----------------------------------------------------------------------------
75 // ----------------------------------------------------------------------------
77 // for an empty string, GetStringData() will return this address: this
78 // structure has the same layout as wxStringData and it's data() method will
79 // return the empty string (dummy pointer)
84 } g_strEmpty
= { {-1, 0, 0}, wxT('\0') };
86 // empty C style string: points to 'string data' byte of g_strEmpty
87 extern const wxChar WXDLLEXPORT
*wxEmptyString
= &g_strEmpty
.dummy
;
89 // ----------------------------------------------------------------------------
90 // conditional compilation
91 // ----------------------------------------------------------------------------
93 #if !defined(__WXSW__) && wxUSE_UNICODE
94 #ifdef wxUSE_EXPERIMENTAL_PRINTF
95 #undef wxUSE_EXPERIMENTAL_PRINTF
97 #define wxUSE_EXPERIMENTAL_PRINTF 1
100 // we want to find out if the current platform supports vsnprintf()-like
101 // function: for Unix this is done with configure, for Windows we test the
102 // compiler explicitly.
104 // FIXME currently, this is only for ANSI (!Unicode) strings, so we call this
105 // function wxVsnprintfA (A for ANSI), should also find one for Unicode
106 // strings in Unicode build
108 #if defined(__VISUALC__) || (defined(__MINGW32__) && wxUSE_NORLANDER_HEADERS)
109 #define wxVsnprintfA _vsnprintf
111 #elif defined(__WXMAC__)
112 #define wxVsnprintfA vsnprintf
114 #ifdef HAVE_VSNPRINTF
115 #define wxVsnprintfA vsnprintf
117 #endif // Windows/!Windows
120 // in this case we'll use vsprintf() (which is ANSI and thus should be
121 // always available), but it's unsafe because it doesn't check for buffer
122 // size - so give a warning
123 #define wxVsnprintfA(buf, len, format, arg) vsprintf(buf, format, arg)
125 #if defined(__VISUALC__)
126 #pragma message("Using sprintf() because no snprintf()-like function defined")
127 #elif defined(__GNUG__)
128 #warning "Using sprintf() because no snprintf()-like function defined"
130 #endif // no vsnprintf
133 // AIX has vsnprintf, but there's no prototype in the system headers.
134 extern "C" int vsnprintf(char* str
, size_t n
, const char* format
, va_list ap
);
137 // ----------------------------------------------------------------------------
139 // ----------------------------------------------------------------------------
141 #if defined(wxSTD_STRING_COMPATIBILITY) && wxUSE_STD_IOSTREAM
143 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
146 // ATTN: you can _not_ use both of these in the same program!
148 wxSTD istream
& operator>>(wxSTD istream
& is
, wxString
& WXUNUSED(str
))
153 streambuf
*sb
= is
.rdbuf();
156 int ch
= sb
->sbumpc ();
158 is
.setstate(ios::eofbit
);
161 else if ( isspace(ch
) ) {
173 if ( str
.length() == 0 )
174 is
.setstate(ios::failbit
);
179 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
185 #endif //std::string compatibility
187 extern int WXDLLEXPORT
wxVsnprintf(wxChar
*buf
, size_t len
,
188 const wxChar
*format
, va_list argptr
)
191 // FIXME should use wvsnprintf() or whatever if it's available
193 int iLen
= s
.PrintfV(format
, argptr
);
196 wxStrncpy(buf
, s
.c_str(), len
);
197 buf
[len
-1] = wxT('\0');
202 // vsnprintf() will not terminate the string with '\0' if there is not
203 // enough place, but we want the string to always be NUL terminated
204 int rc
= wxVsnprintfA(buf
, len
- 1, format
, argptr
);
211 #endif // Unicode/ANSI
214 extern int WXDLLEXPORT
wxSnprintf(wxChar
*buf
, size_t len
,
215 const wxChar
*format
, ...)
218 va_start(argptr
, format
);
220 int iLen
= wxVsnprintf(buf
, len
, format
, argptr
);
227 // ----------------------------------------------------------------------------
229 // ----------------------------------------------------------------------------
231 // this small class is used to gather statistics for performance tuning
232 //#define WXSTRING_STATISTICS
233 #ifdef WXSTRING_STATISTICS
237 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
239 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
241 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
244 size_t m_nCount
, m_nTotal
;
246 } g_averageLength("allocation size"),
247 g_averageSummandLength("summand length"),
248 g_averageConcatHit("hit probability in concat"),
249 g_averageInitialLength("initial string length");
251 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
253 #define STATISTICS_ADD(av, val)
254 #endif // WXSTRING_STATISTICS
256 // ===========================================================================
257 // wxString class core
258 // ===========================================================================
260 // ---------------------------------------------------------------------------
262 // ---------------------------------------------------------------------------
264 // constructs string of <nLength> copies of character <ch>
265 wxString::wxString(wxChar ch
, size_t nLength
)
270 if ( !AllocBuffer(nLength
) ) {
271 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
276 // memset only works on char
277 for (size_t n
=0; n
<nLength
; n
++) m_pchData
[n
] = ch
;
279 memset(m_pchData
, ch
, nLength
);
284 // takes nLength elements of psz starting at nPos
285 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
289 // if the length is not given, assume the string to be NUL terminated
290 if ( nLength
== wxSTRING_MAXLEN
) {
291 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
293 nLength
= wxStrlen(psz
+ nPos
);
296 STATISTICS_ADD(InitialLength
, nLength
);
299 // trailing '\0' is written in AllocBuffer()
300 if ( !AllocBuffer(nLength
) ) {
301 wxFAIL_MSG( _T("out of memory in wxString::InitWith") );
304 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
308 #ifdef wxSTD_STRING_COMPATIBILITY
310 // poor man's iterators are "void *" pointers
311 wxString::wxString(const void *pStart
, const void *pEnd
)
313 InitWith((const wxChar
*)pStart
, 0,
314 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
317 #endif //std::string compatibility
321 // from multibyte string
322 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
324 // first get necessary size
325 size_t nLen
= psz
? conv
.MB2WC((wchar_t *) NULL
, psz
, 0) : 0;
327 // nLength is number of *Unicode* characters here!
328 if ((nLen
!= (size_t)-1) && (nLen
> nLength
))
332 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
333 if ( !AllocBuffer(nLen
) ) {
334 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
337 conv
.MB2WC(m_pchData
, psz
, nLen
);
348 wxString::wxString(const wchar_t *pwz
, wxMBConv
& conv
, size_t nLength
)
350 // first get necessary size
354 if (nLength
== wxSTRING_MAXLEN
)
355 nLen
= conv
.WC2MB((char *) NULL
, pwz
, 0);
361 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
362 if ( !AllocBuffer(nLen
) ) {
363 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
366 conv
.WC2MB(m_pchData
, pwz
, nLen
);
372 #endif // wxUSE_WCHAR_T
374 #endif // Unicode/ANSI
376 // ---------------------------------------------------------------------------
378 // ---------------------------------------------------------------------------
380 // allocates memory needed to store a C string of length nLen
381 bool wxString::AllocBuffer(size_t nLen
)
383 // allocating 0 sized buffer doesn't make sense, all empty strings should
385 wxASSERT( nLen
> 0 );
387 // make sure that we don't overflow
388 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
389 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
391 STATISTICS_ADD(Length
, nLen
);
394 // 1) one extra character for '\0' termination
395 // 2) sizeof(wxStringData) for housekeeping info
396 wxStringData
* pData
= (wxStringData
*)
397 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
399 if ( pData
== NULL
) {
400 // allocation failures are handled by the caller
405 pData
->nDataLength
= nLen
;
406 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
407 m_pchData
= pData
->data(); // data starts after wxStringData
408 m_pchData
[nLen
] = wxT('\0');
412 // must be called before changing this string
413 bool wxString::CopyBeforeWrite()
415 wxStringData
* pData
= GetStringData();
417 if ( pData
->IsShared() ) {
418 pData
->Unlock(); // memory not freed because shared
419 size_t nLen
= pData
->nDataLength
;
420 if ( !AllocBuffer(nLen
) ) {
421 // allocation failures are handled by the caller
424 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
427 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
432 // must be called before replacing contents of this string
433 bool wxString::AllocBeforeWrite(size_t nLen
)
435 wxASSERT( nLen
!= 0 ); // doesn't make any sense
437 // must not share string and must have enough space
438 wxStringData
* pData
= GetStringData();
439 if ( pData
->IsShared() || pData
->IsEmpty() ) {
440 // can't work with old buffer, get new one
442 if ( !AllocBuffer(nLen
) ) {
443 // allocation failures are handled by the caller
448 if ( nLen
> pData
->nAllocLength
) {
449 // realloc the buffer instead of calling malloc() again, this is more
451 STATISTICS_ADD(Length
, nLen
);
455 pData
= (wxStringData
*)
456 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
458 if ( pData
== NULL
) {
459 // allocation failures are handled by the caller
460 // keep previous data since reallocation failed
464 pData
->nAllocLength
= nLen
;
465 m_pchData
= pData
->data();
468 // now we have enough space, just update the string length
469 pData
->nDataLength
= nLen
;
472 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
477 // allocate enough memory for nLen characters
478 bool wxString::Alloc(size_t nLen
)
480 wxStringData
*pData
= GetStringData();
481 if ( pData
->nAllocLength
<= nLen
) {
482 if ( pData
->IsEmpty() ) {
485 wxStringData
* pData
= (wxStringData
*)
486 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
488 if ( pData
== NULL
) {
489 // allocation failure handled by caller
494 pData
->nDataLength
= 0;
495 pData
->nAllocLength
= nLen
;
496 m_pchData
= pData
->data(); // data starts after wxStringData
497 m_pchData
[0u] = wxT('\0');
499 else if ( pData
->IsShared() ) {
500 pData
->Unlock(); // memory not freed because shared
501 size_t nOldLen
= pData
->nDataLength
;
502 if ( !AllocBuffer(nLen
) ) {
503 // allocation failure handled by caller
506 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
511 pData
= (wxStringData
*)
512 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
514 if ( pData
== NULL
) {
515 // allocation failure handled by caller
516 // keep previous data since reallocation failed
520 // it's not important if the pointer changed or not (the check for this
521 // is not faster than assigning to m_pchData in all cases)
522 pData
->nAllocLength
= nLen
;
523 m_pchData
= pData
->data();
526 //else: we've already got enough
530 // shrink to minimal size (releasing extra memory)
531 bool wxString::Shrink()
533 wxStringData
*pData
= GetStringData();
535 size_t nLen
= pData
->nDataLength
;
536 void *p
= realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
539 wxFAIL_MSG( _T("out of memory reallocating wxString data") );
540 // keep previous data since reallocation failed
546 // contrary to what one might believe, some realloc() implementation do
547 // move the memory block even when its size is reduced
548 pData
= (wxStringData
*)p
;
550 m_pchData
= pData
->data();
553 pData
->nAllocLength
= nLen
;
558 // get the pointer to writable buffer of (at least) nLen bytes
559 wxChar
*wxString::GetWriteBuf(size_t nLen
)
561 if ( !AllocBeforeWrite(nLen
) ) {
562 // allocation failure handled by caller
566 wxASSERT( GetStringData()->nRefs
== 1 );
567 GetStringData()->Validate(FALSE
);
572 // put string back in a reasonable state after GetWriteBuf
573 void wxString::UngetWriteBuf()
575 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
576 GetStringData()->Validate(TRUE
);
579 void wxString::UngetWriteBuf(size_t nLen
)
581 GetStringData()->nDataLength
= nLen
;
582 GetStringData()->Validate(TRUE
);
585 // ---------------------------------------------------------------------------
587 // ---------------------------------------------------------------------------
589 // all functions are inline in string.h
591 // ---------------------------------------------------------------------------
592 // assignment operators
593 // ---------------------------------------------------------------------------
595 // helper function: does real copy
596 bool wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
598 if ( nSrcLen
== 0 ) {
602 if ( !AllocBeforeWrite(nSrcLen
) ) {
603 // allocation failure handled by caller
606 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
607 GetStringData()->nDataLength
= nSrcLen
;
608 m_pchData
[nSrcLen
] = wxT('\0');
613 // assigns one string to another
614 wxString
& wxString::operator=(const wxString
& stringSrc
)
616 wxASSERT( stringSrc
.GetStringData()->IsValid() );
618 // don't copy string over itself
619 if ( m_pchData
!= stringSrc
.m_pchData
) {
620 if ( stringSrc
.GetStringData()->IsEmpty() ) {
625 GetStringData()->Unlock();
626 m_pchData
= stringSrc
.m_pchData
;
627 GetStringData()->Lock();
634 // assigns a single character
635 wxString
& wxString::operator=(wxChar ch
)
637 if ( !AssignCopy(1, &ch
) ) {
638 wxFAIL_MSG( _T("out of memory in wxString::operator=(wxChar)") );
645 wxString
& wxString::operator=(const wxChar
*psz
)
647 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
648 wxFAIL_MSG( _T("out of memory in wxString::operator=(const wxChar *)") );
655 // same as 'signed char' variant
656 wxString
& wxString::operator=(const unsigned char* psz
)
658 *this = (const char *)psz
;
663 wxString
& wxString::operator=(const wchar_t *pwz
)
673 // ---------------------------------------------------------------------------
674 // string concatenation
675 // ---------------------------------------------------------------------------
677 // add something to this string
678 bool wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
680 STATISTICS_ADD(SummandLength
, nSrcLen
);
682 // concatenating an empty string is a NOP
684 wxStringData
*pData
= GetStringData();
685 size_t nLen
= pData
->nDataLength
;
686 size_t nNewLen
= nLen
+ nSrcLen
;
688 // alloc new buffer if current is too small
689 if ( pData
->IsShared() ) {
690 STATISTICS_ADD(ConcatHit
, 0);
692 // we have to allocate another buffer
693 wxStringData
* pOldData
= GetStringData();
694 if ( !AllocBuffer(nNewLen
) ) {
695 // allocation failure handled by caller
698 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
701 else if ( nNewLen
> pData
->nAllocLength
) {
702 STATISTICS_ADD(ConcatHit
, 0);
704 // we have to grow the buffer
705 if ( !Alloc(nNewLen
) ) {
706 // allocation failure handled by caller
711 STATISTICS_ADD(ConcatHit
, 1);
713 // the buffer is already big enough
716 // should be enough space
717 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
719 // fast concatenation - all is done in our buffer
720 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
722 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
723 GetStringData()->nDataLength
= nNewLen
; // and fix the length
725 //else: the string to append was empty
730 * concatenation functions come in 5 flavours:
732 * char + string and string + char
733 * C str + string and string + C str
736 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
738 wxASSERT( str1
.GetStringData()->IsValid() );
739 wxASSERT( str2
.GetStringData()->IsValid() );
747 wxString
operator+(const wxString
& str
, wxChar ch
)
749 wxASSERT( str
.GetStringData()->IsValid() );
757 wxString
operator+(wxChar ch
, const wxString
& str
)
759 wxASSERT( str
.GetStringData()->IsValid() );
767 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
769 wxASSERT( str
.GetStringData()->IsValid() );
772 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
773 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
781 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
783 wxASSERT( str
.GetStringData()->IsValid() );
786 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
787 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
795 // ===========================================================================
796 // other common string functions
797 // ===========================================================================
799 // ---------------------------------------------------------------------------
800 // simple sub-string extraction
801 // ---------------------------------------------------------------------------
803 // helper function: clone the data attached to this string
804 bool wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
806 if ( nCopyLen
== 0 ) {
810 if ( !dest
.AllocBuffer(nCopyLen
) ) {
811 // allocation failure handled by caller
814 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
819 // extract string of length nCount starting at nFirst
820 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
822 wxStringData
*pData
= GetStringData();
823 size_t nLen
= pData
->nDataLength
;
825 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
826 if ( nCount
== wxSTRING_MAXLEN
)
828 nCount
= nLen
- nFirst
;
831 // out-of-bounds requests return sensible things
832 if ( nFirst
+ nCount
> nLen
)
834 nCount
= nLen
- nFirst
;
839 // AllocCopy() will return empty string
844 if ( !AllocCopy(dest
, nCount
, nFirst
) ) {
845 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
851 // check that the tring starts with prefix and return the rest of the string
852 // in the provided pointer if it is not NULL, otherwise return FALSE
853 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
855 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
857 // first check if the beginning of the string matches the prefix: note
858 // that we don't have to check that we don't run out of this string as
859 // when we reach the terminating NUL, either prefix string ends too (and
860 // then it's ok) or we break out of the loop because there is no match
861 const wxChar
*p
= c_str();
864 if ( *prefix
++ != *p
++ )
873 // put the rest of the string into provided pointer
880 // extract nCount last (rightmost) characters
881 wxString
wxString::Right(size_t nCount
) const
883 if ( nCount
> (size_t)GetStringData()->nDataLength
)
884 nCount
= GetStringData()->nDataLength
;
887 if ( !AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
) ) {
888 wxFAIL_MSG( _T("out of memory in wxString::Right") );
893 // get all characters after the last occurence of ch
894 // (returns the whole string if ch not found)
895 wxString
wxString::AfterLast(wxChar ch
) const
898 int iPos
= Find(ch
, TRUE
);
899 if ( iPos
== wxNOT_FOUND
)
902 str
= c_str() + iPos
+ 1;
907 // extract nCount first (leftmost) characters
908 wxString
wxString::Left(size_t nCount
) const
910 if ( nCount
> (size_t)GetStringData()->nDataLength
)
911 nCount
= GetStringData()->nDataLength
;
914 if ( !AllocCopy(dest
, nCount
, 0) ) {
915 wxFAIL_MSG( _T("out of memory in wxString::Left") );
920 // get all characters before the first occurence of ch
921 // (returns the whole string if ch not found)
922 wxString
wxString::BeforeFirst(wxChar ch
) const
925 for ( const wxChar
*pc
= m_pchData
; *pc
!= wxT('\0') && *pc
!= ch
; pc
++ )
931 /// get all characters before the last occurence of ch
932 /// (returns empty string if ch not found)
933 wxString
wxString::BeforeLast(wxChar ch
) const
936 int iPos
= Find(ch
, TRUE
);
937 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
938 str
= wxString(c_str(), iPos
);
943 /// get all characters after the first occurence of ch
944 /// (returns empty string if ch not found)
945 wxString
wxString::AfterFirst(wxChar ch
) const
949 if ( iPos
!= wxNOT_FOUND
)
950 str
= c_str() + iPos
+ 1;
955 // replace first (or all) occurences of some substring with another one
956 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
958 size_t uiCount
= 0; // count of replacements made
960 size_t uiOldLen
= wxStrlen(szOld
);
963 const wxChar
*pCurrent
= m_pchData
;
964 const wxChar
*pSubstr
;
965 while ( *pCurrent
!= wxT('\0') ) {
966 pSubstr
= wxStrstr(pCurrent
, szOld
);
967 if ( pSubstr
== NULL
) {
968 // strTemp is unused if no replacements were made, so avoid the copy
972 strTemp
+= pCurrent
; // copy the rest
973 break; // exit the loop
976 // take chars before match
977 if ( !strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
) ) {
978 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
982 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
987 if ( !bReplaceAll
) {
988 strTemp
+= pCurrent
; // copy the rest
989 break; // exit the loop
994 // only done if there were replacements, otherwise would have returned above
1000 bool wxString::IsAscii() const
1002 const wxChar
*s
= (const wxChar
*) *this;
1004 if(!isascii(*s
)) return(FALSE
);
1010 bool wxString::IsWord() const
1012 const wxChar
*s
= (const wxChar
*) *this;
1014 if(!wxIsalpha(*s
)) return(FALSE
);
1020 bool wxString::IsNumber() const
1022 const wxChar
*s
= (const wxChar
*) *this;
1024 if ((s
[0] == '-') || (s
[0] == '+')) s
++;
1026 if(!wxIsdigit(*s
)) return(FALSE
);
1032 wxString
wxString::Strip(stripType w
) const
1035 if ( w
& leading
) s
.Trim(FALSE
);
1036 if ( w
& trailing
) s
.Trim(TRUE
);
1040 // ---------------------------------------------------------------------------
1042 // ---------------------------------------------------------------------------
1044 wxString
& wxString::MakeUpper()
1046 if ( !CopyBeforeWrite() ) {
1047 wxFAIL_MSG( _T("out of memory in wxString::MakeUpper") );
1051 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1052 *p
= (wxChar
)wxToupper(*p
);
1057 wxString
& wxString::MakeLower()
1059 if ( !CopyBeforeWrite() ) {
1060 wxFAIL_MSG( _T("out of memory in wxString::MakeLower") );
1064 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1065 *p
= (wxChar
)wxTolower(*p
);
1070 // ---------------------------------------------------------------------------
1071 // trimming and padding
1072 // ---------------------------------------------------------------------------
1074 // some compilers (VC++ 6.0 not to name them) return TRUE for a call to
1075 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1076 // live with this by checking that the character is a 7 bit one - even if this
1077 // may fail to detect some spaces (I don't know if Unicode doesn't have
1078 // space-like symbols somewhere except in the first 128 chars), it is arguably
1079 // still better than trimming away accented letters
1080 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1082 // trims spaces (in the sense of isspace) from left or right side
1083 wxString
& wxString::Trim(bool bFromRight
)
1085 // first check if we're going to modify the string at all
1088 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1089 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1093 // ok, there is at least one space to trim
1094 if ( !CopyBeforeWrite() ) {
1095 wxFAIL_MSG( _T("out of memory in wxString::Trim") );
1101 // find last non-space character
1102 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
1103 while ( wxSafeIsspace(*psz
) && (psz
>= m_pchData
) )
1106 // truncate at trailing space start
1108 GetStringData()->nDataLength
= psz
- m_pchData
;
1112 // find first non-space character
1113 const wxChar
*psz
= m_pchData
;
1114 while ( wxSafeIsspace(*psz
) )
1117 // fix up data and length
1118 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
1119 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
1120 GetStringData()->nDataLength
= nDataLength
;
1127 // adds nCount characters chPad to the string from either side
1128 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1130 wxString
s(chPad
, nCount
);
1143 // truncate the string
1144 wxString
& wxString::Truncate(size_t uiLen
)
1146 if ( uiLen
< Len() ) {
1147 if ( !CopyBeforeWrite() ) {
1148 wxFAIL_MSG( _T("out of memory in wxString::Truncate") );
1152 *(m_pchData
+ uiLen
) = wxT('\0');
1153 GetStringData()->nDataLength
= uiLen
;
1155 //else: nothing to do, string is already short enough
1160 // ---------------------------------------------------------------------------
1161 // finding (return wxNOT_FOUND if not found and index otherwise)
1162 // ---------------------------------------------------------------------------
1165 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1167 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
1169 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1172 // find a sub-string (like strstr)
1173 int wxString::Find(const wxChar
*pszSub
) const
1175 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
1177 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1180 // ----------------------------------------------------------------------------
1181 // conversion to numbers
1182 // ----------------------------------------------------------------------------
1184 bool wxString::ToLong(long *val
, int base
) const
1186 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToLong") );
1187 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1189 const wxChar
*start
= c_str();
1191 *val
= wxStrtol(start
, &end
, base
);
1193 // return TRUE only if scan was stopped by the terminating NUL and if the
1194 // string was not empty to start with
1195 return !*end
&& (end
!= start
);
1198 bool wxString::ToULong(unsigned long *val
, int base
) const
1200 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToULong") );
1201 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1203 const wxChar
*start
= c_str();
1205 *val
= wxStrtoul(start
, &end
, base
);
1207 // return TRUE only if scan was stopped by the terminating NUL and if the
1208 // string was not empty to start with
1209 return !*end
&& (end
!= start
);
1212 bool wxString::ToDouble(double *val
) const
1214 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToDouble") );
1216 const wxChar
*start
= c_str();
1218 *val
= wxStrtod(start
, &end
);
1220 // return TRUE only if scan was stopped by the terminating NUL and if the
1221 // string was not empty to start with
1222 return !*end
&& (end
!= start
);
1225 // ---------------------------------------------------------------------------
1227 // ---------------------------------------------------------------------------
1230 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1233 va_start(argptr
, pszFormat
);
1236 s
.PrintfV(pszFormat
, argptr
);
1244 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1247 s
.PrintfV(pszFormat
, argptr
);
1251 int wxString::Printf(const wxChar
*pszFormat
, ...)
1254 va_start(argptr
, pszFormat
);
1256 int iLen
= PrintfV(pszFormat
, argptr
);
1263 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1265 #if wxUSE_EXPERIMENTAL_PRINTF
1266 // the new implementation
1268 // buffer to avoid dynamic memory allocation each time for small strings
1269 char szScratch
[1024];
1272 for (size_t n
= 0; pszFormat
[n
]; n
++)
1273 if (pszFormat
[n
] == wxT('%')) {
1274 static char s_szFlags
[256] = "%";
1276 bool adj_left
= FALSE
, in_prec
= FALSE
,
1277 prec_dot
= FALSE
, done
= FALSE
;
1279 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1281 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1282 switch (pszFormat
[++n
]) {
1296 s_szFlags
[flagofs
++] = pszFormat
[n
];
1301 s_szFlags
[flagofs
++] = pszFormat
[n
];
1308 // dot will be auto-added to s_szFlags if non-negative number follows
1313 s_szFlags
[flagofs
++] = pszFormat
[n
];
1318 s_szFlags
[flagofs
++] = pszFormat
[n
];
1324 s_szFlags
[flagofs
++] = pszFormat
[n
];
1329 s_szFlags
[flagofs
++] = pszFormat
[n
];
1333 int len
= va_arg(argptr
, int);
1340 adj_left
= !adj_left
;
1341 s_szFlags
[flagofs
++] = '-';
1346 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1349 case wxT('1'): case wxT('2'): case wxT('3'):
1350 case wxT('4'): case wxT('5'): case wxT('6'):
1351 case wxT('7'): case wxT('8'): case wxT('9'):
1355 while ((pszFormat
[n
]>=wxT('0')) && (pszFormat
[n
]<=wxT('9'))) {
1356 s_szFlags
[flagofs
++] = pszFormat
[n
];
1357 len
= len
*10 + (pszFormat
[n
] - wxT('0'));
1360 if (in_prec
) max_width
= len
;
1361 else min_width
= len
;
1362 n
--; // the main loop pre-increments n again
1372 s_szFlags
[flagofs
++] = pszFormat
[n
];
1373 s_szFlags
[flagofs
] = '\0';
1375 int val
= va_arg(argptr
, int);
1376 ::sprintf(szScratch
, s_szFlags
, val
);
1378 else if (ilen
== -1) {
1379 short int val
= va_arg(argptr
, short int);
1380 ::sprintf(szScratch
, s_szFlags
, val
);
1382 else if (ilen
== 1) {
1383 long int val
= va_arg(argptr
, long int);
1384 ::sprintf(szScratch
, s_szFlags
, val
);
1386 else if (ilen
== 2) {
1387 #if SIZEOF_LONG_LONG
1388 long long int val
= va_arg(argptr
, long long int);
1389 ::sprintf(szScratch
, s_szFlags
, val
);
1391 long int val
= va_arg(argptr
, long int);
1392 ::sprintf(szScratch
, s_szFlags
, val
);
1395 else if (ilen
== 3) {
1396 size_t val
= va_arg(argptr
, size_t);
1397 ::sprintf(szScratch
, s_szFlags
, val
);
1399 *this += wxString(szScratch
);
1408 s_szFlags
[flagofs
++] = pszFormat
[n
];
1409 s_szFlags
[flagofs
] = '\0';
1411 long double val
= va_arg(argptr
, long double);
1412 ::sprintf(szScratch
, s_szFlags
, val
);
1414 double val
= va_arg(argptr
, double);
1415 ::sprintf(szScratch
, s_szFlags
, val
);
1417 *this += wxString(szScratch
);
1422 void *val
= va_arg(argptr
, void *);
1424 s_szFlags
[flagofs
++] = pszFormat
[n
];
1425 s_szFlags
[flagofs
] = '\0';
1426 ::sprintf(szScratch
, s_szFlags
, val
);
1427 *this += wxString(szScratch
);
1433 wxChar val
= va_arg(argptr
, int);
1434 // we don't need to honor padding here, do we?
1441 // wx extension: we'll let %hs mean non-Unicode strings
1442 char *val
= va_arg(argptr
, char *);
1444 // ASCII->Unicode constructor handles max_width right
1445 wxString
s(val
, wxConvLibc
, max_width
);
1447 size_t len
= wxSTRING_MAXLEN
;
1449 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1450 } else val
= wxT("(null)");
1451 wxString
s(val
, len
);
1453 if (s
.Len() < min_width
)
1454 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1457 wxChar
*val
= va_arg(argptr
, wxChar
*);
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
);
1463 if (s
.Len() < min_width
)
1464 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1471 int *val
= va_arg(argptr
, int *);
1474 else if (ilen
== -1) {
1475 short int *val
= va_arg(argptr
, short int *);
1478 else if (ilen
>= 1) {
1479 long int *val
= va_arg(argptr
, long int *);
1485 if (wxIsalpha(pszFormat
[n
]))
1486 // probably some flag not taken care of here yet
1487 s_szFlags
[flagofs
++] = pszFormat
[n
];
1490 *this += wxT('%'); // just to pass the glibc tst-printf.c
1498 } else *this += pszFormat
[n
];
1501 // buffer to avoid dynamic memory allocation each time for small strings
1502 char szScratch
[1024];
1504 // NB: wxVsnprintf() may return either less than the buffer size or -1 if
1505 // there is not enough place depending on implementation
1506 int iLen
= wxVsnprintfA(szScratch
, WXSIZEOF(szScratch
), (char *)pszFormat
, argptr
);
1508 // the whole string is in szScratch
1512 bool outOfMemory
= FALSE
;
1513 int size
= 2*WXSIZEOF(szScratch
);
1514 while ( !outOfMemory
) {
1515 char *buf
= GetWriteBuf(size
);
1517 iLen
= wxVsnprintfA(buf
, size
, pszFormat
, argptr
);
1524 // ok, there was enough space
1528 // still not enough, double it again
1532 if ( outOfMemory
) {
1537 #endif // wxUSE_EXPERIMENTAL_PRINTF/!wxUSE_EXPERIMENTAL_PRINTF
1542 // ----------------------------------------------------------------------------
1543 // misc other operations
1544 // ----------------------------------------------------------------------------
1546 // returns TRUE if the string matches the pattern which may contain '*' and
1547 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1549 bool wxString::Matches(const wxChar
*pszMask
) const
1551 // I disable this code as it doesn't seem to be faster (in fact, it seems
1552 // to be much slower) than the old, hand-written code below and using it
1553 // here requires always linking with libregex even if the user code doesn't
1555 #if 0 // wxUSE_REGEX
1556 // first translate the shell-like mask into a regex
1558 pattern
.reserve(wxStrlen(pszMask
));
1570 pattern
+= _T(".*");
1581 // these characters are special in a RE, quote them
1582 // (however note that we don't quote '[' and ']' to allow
1583 // using them for Unix shell like matching)
1584 pattern
+= _T('\\');
1588 pattern
+= *pszMask
;
1596 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1597 #else // !wxUSE_REGEX
1598 // TODO: this is, of course, awfully inefficient...
1600 // the char currently being checked
1601 const wxChar
*pszTxt
= c_str();
1603 // the last location where '*' matched
1604 const wxChar
*pszLastStarInText
= NULL
;
1605 const wxChar
*pszLastStarInMask
= NULL
;
1608 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1609 switch ( *pszMask
) {
1611 if ( *pszTxt
== wxT('\0') )
1614 // pszTxt and pszMask will be incremented in the loop statement
1620 // remember where we started to be able to backtrack later
1621 pszLastStarInText
= pszTxt
;
1622 pszLastStarInMask
= pszMask
;
1624 // ignore special chars immediately following this one
1625 // (should this be an error?)
1626 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1629 // if there is nothing more, match
1630 if ( *pszMask
== wxT('\0') )
1633 // are there any other metacharacters in the mask?
1635 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1637 if ( pEndMask
!= NULL
) {
1638 // we have to match the string between two metachars
1639 uiLenMask
= pEndMask
- pszMask
;
1642 // we have to match the remainder of the string
1643 uiLenMask
= wxStrlen(pszMask
);
1646 wxString
strToMatch(pszMask
, uiLenMask
);
1647 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1648 if ( pMatch
== NULL
)
1651 // -1 to compensate "++" in the loop
1652 pszTxt
= pMatch
+ uiLenMask
- 1;
1653 pszMask
+= uiLenMask
- 1;
1658 if ( *pszMask
!= *pszTxt
)
1664 // match only if nothing left
1665 if ( *pszTxt
== wxT('\0') )
1668 // if we failed to match, backtrack if we can
1669 if ( pszLastStarInText
) {
1670 pszTxt
= pszLastStarInText
+ 1;
1671 pszMask
= pszLastStarInMask
;
1673 pszLastStarInText
= NULL
;
1675 // don't bother resetting pszLastStarInMask, it's unnecessary
1681 #endif // wxUSE_REGEX/!wxUSE_REGEX
1684 // Count the number of chars
1685 int wxString::Freq(wxChar ch
) const
1689 for (int i
= 0; i
< len
; i
++)
1691 if (GetChar(i
) == ch
)
1697 // convert to upper case, return the copy of the string
1698 wxString
wxString::Upper() const
1699 { wxString
s(*this); return s
.MakeUpper(); }
1701 // convert to lower case, return the copy of the string
1702 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1704 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1707 va_start(argptr
, pszFormat
);
1708 int iLen
= PrintfV(pszFormat
, argptr
);
1713 // ---------------------------------------------------------------------------
1714 // standard C++ library string functions
1715 // ---------------------------------------------------------------------------
1717 #ifdef wxSTD_STRING_COMPATIBILITY
1719 void wxString::resize(size_t nSize
, wxChar ch
)
1721 size_t len
= length();
1727 else if ( nSize
> len
)
1729 *this += wxString(ch
, nSize
- len
);
1731 //else: we have exactly the specified length, nothing to do
1734 void wxString::swap(wxString
& str
)
1736 // this is slightly less efficient than fiddling with m_pchData directly,
1737 // but it is still quite efficient as we don't copy the string here because
1738 // ref count always stays positive
1744 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1746 wxASSERT( str
.GetStringData()->IsValid() );
1747 wxASSERT( nPos
<= Len() );
1749 if ( !str
.IsEmpty() ) {
1751 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1752 wxStrncpy(pc
, c_str(), nPos
);
1753 wxStrcpy(pc
+ nPos
, str
);
1754 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1755 strTmp
.UngetWriteBuf();
1762 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1764 wxASSERT( str
.GetStringData()->IsValid() );
1765 wxASSERT( nStart
<= Len() );
1767 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1769 return p
== NULL
? npos
: p
- c_str();
1772 // VC++ 1.5 can't cope with the default argument in the header.
1773 #if !defined(__VISUALC__) || defined(__WIN32__)
1774 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1776 return find(wxString(sz
, n
), nStart
);
1780 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1781 #if !defined(__BORLANDC__)
1782 size_t wxString::find(wxChar ch
, size_t nStart
) const
1784 wxASSERT( nStart
<= Len() );
1786 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1788 return p
== NULL
? npos
: p
- c_str();
1792 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1794 wxASSERT( str
.GetStringData()->IsValid() );
1795 wxASSERT( nStart
== npos
|| nStart
<= Len() );
1797 // TODO could be made much quicker than that
1798 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1799 while ( p
>= c_str() + str
.Len() ) {
1800 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1801 return p
- str
.Len() - c_str();
1808 // VC++ 1.5 can't cope with the default argument in the header.
1809 #if !defined(__VISUALC__) || defined(__WIN32__)
1810 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1812 return rfind(wxString(sz
, n
== npos
? wxSTRING_MAXLEN
: n
), nStart
);
1815 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1817 if ( nStart
== npos
)
1823 wxASSERT( nStart
<= Len() );
1826 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1831 size_t result
= p
- c_str();
1832 return ( result
> nStart
) ? npos
: result
;
1836 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1838 const wxChar
*start
= c_str() + nStart
;
1839 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1841 return firstOf
- c_str();
1846 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1848 if ( nStart
== npos
)
1854 wxASSERT( nStart
<= Len() );
1857 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1859 if ( wxStrchr(sz
, *p
) )
1866 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1868 if ( nStart
== npos
)
1874 wxASSERT( nStart
<= Len() );
1877 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1878 if ( nAccept
>= length() - nStart
)
1884 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1886 wxASSERT( nStart
<= Len() );
1888 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1897 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1899 if ( nStart
== npos
)
1905 wxASSERT( nStart
<= Len() );
1908 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1910 if ( !wxStrchr(sz
, *p
) )
1917 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1919 if ( nStart
== npos
)
1925 wxASSERT( nStart
<= Len() );
1928 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1937 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1939 wxString
strTmp(c_str(), nStart
);
1940 if ( nLen
!= npos
) {
1941 wxASSERT( nStart
+ nLen
<= Len() );
1943 strTmp
.append(c_str() + nStart
+ nLen
);
1950 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1952 wxASSERT_MSG( nStart
+ nLen
<= Len(),
1953 _T("index out of bounds in wxString::replace") );
1956 strTmp
.Alloc(Len()); // micro optimisation to avoid multiple mem allocs
1959 strTmp
.append(c_str(), nStart
);
1960 strTmp
<< sz
<< c_str() + nStart
+ nLen
;
1966 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1968 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1971 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1972 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1974 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1977 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1978 const wxChar
* sz
, size_t nCount
)
1980 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1983 #endif //std::string compatibility
1985 // ============================================================================
1987 // ============================================================================
1989 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1990 #define ARRAY_MAXSIZE_INCREMENT 4096
1992 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1993 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1996 #define STRING(p) ((wxString *)(&(p)))
1999 void wxArrayString::Init(bool autoSort
)
2003 m_pItems
= (wxChar
**) NULL
;
2004 m_autoSort
= autoSort
;
2008 wxArrayString::wxArrayString(const wxArrayString
& src
)
2010 Init(src
.m_autoSort
);
2015 // assignment operator
2016 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
2023 m_autoSort
= src
.m_autoSort
;
2028 void wxArrayString::Copy(const wxArrayString
& src
)
2030 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
2031 Alloc(src
.m_nCount
);
2033 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
2038 void wxArrayString::Grow(size_t nIncrement
)
2040 // only do it if no more place
2041 if ( m_nCount
== m_nSize
) {
2042 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2043 // be never resized!
2044 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2045 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2048 if ( m_nSize
== 0 ) {
2049 // was empty, alloc some memory
2050 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
2051 m_pItems
= new wxChar
*[m_nSize
];
2054 // otherwise when it's called for the first time, nIncrement would be 0
2055 // and the array would never be expanded
2056 // add 50% but not too much
2057 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
2058 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
2059 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
2060 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
2061 if ( nIncrement
< ndefIncrement
)
2062 nIncrement
= ndefIncrement
;
2063 m_nSize
+= nIncrement
;
2064 wxChar
**pNew
= new wxChar
*[m_nSize
];
2066 // copy data to new location
2067 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2069 // delete old memory (but do not release the strings!)
2070 wxDELETEA(m_pItems
);
2077 void wxArrayString::Free()
2079 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
2080 STRING(m_pItems
[n
])->GetStringData()->Unlock();
2084 // deletes all the strings from the list
2085 void wxArrayString::Empty()
2092 // as Empty, but also frees memory
2093 void wxArrayString::Clear()
2100 wxDELETEA(m_pItems
);
2104 wxArrayString::~wxArrayString()
2108 wxDELETEA(m_pItems
);
2111 // pre-allocates memory (frees the previous data!)
2112 void wxArrayString::Alloc(size_t nSize
)
2114 // only if old buffer was not big enough
2115 if ( nSize
> m_nSize
) {
2117 wxDELETEA(m_pItems
);
2118 m_pItems
= new wxChar
*[nSize
];
2125 // minimizes the memory usage by freeing unused memory
2126 void wxArrayString::Shrink()
2128 // only do it if we have some memory to free
2129 if( m_nCount
< m_nSize
) {
2130 // allocates exactly as much memory as we need
2131 wxChar
**pNew
= new wxChar
*[m_nCount
];
2133 // copy data to new location
2134 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2140 // return a wxString[] as required for some control ctors.
2141 wxString
* wxArrayString::GetStringArray() const
2143 wxString
*array
= 0;
2147 array
= new wxString
[m_nCount
];
2148 for( size_t i
= 0; i
< m_nCount
; i
++ )
2149 array
[i
] = m_pItems
[i
];
2155 // searches the array for an item (forward or backwards)
2156 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2159 // use binary search in the sorted array
2160 wxASSERT_MSG( bCase
&& !bFromEnd
,
2161 wxT("search parameters ignored for auto sorted array") );
2170 res
= wxStrcmp(sz
, m_pItems
[i
]);
2182 // use linear search in unsorted array
2184 if ( m_nCount
> 0 ) {
2185 size_t ui
= m_nCount
;
2187 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2194 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2195 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2204 // add item at the end
2205 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
2208 // insert the string at the correct position to keep the array sorted
2216 res
= wxStrcmp(str
, m_pItems
[i
]);
2227 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2229 Insert(str
, lo
, nInsert
);
2234 wxASSERT( str
.GetStringData()->IsValid() );
2238 for (size_t i
= 0; i
< nInsert
; i
++)
2240 // the string data must not be deleted!
2241 str
.GetStringData()->Lock();
2244 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2246 size_t ret
= m_nCount
;
2247 m_nCount
+= nInsert
;
2252 // add item at the given position
2253 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2255 wxASSERT( str
.GetStringData()->IsValid() );
2257 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2258 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2259 wxT("array size overflow in wxArrayString::Insert") );
2263 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2264 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2266 for (size_t i
= 0; i
< nInsert
; i
++)
2268 str
.GetStringData()->Lock();
2269 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2271 m_nCount
+= nInsert
;
2275 void wxArrayString::SetCount(size_t count
)
2280 while ( m_nCount
< count
)
2281 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2284 // removes item from array (by index)
2285 void wxArrayString::Remove(size_t nIndex
, size_t nRemove
)
2287 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2288 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2289 wxT("removing too many elements in wxArrayString::Remove") );
2292 for (size_t i
= 0; i
< nRemove
; i
++)
2293 Item(nIndex
+ i
).GetStringData()->Unlock();
2295 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2296 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2297 m_nCount
-= nRemove
;
2300 // removes item from array (by value)
2301 void wxArrayString::Remove(const wxChar
*sz
)
2303 int iIndex
= Index(sz
);
2305 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2306 wxT("removing inexistent element in wxArrayString::Remove") );
2311 // ----------------------------------------------------------------------------
2313 // ----------------------------------------------------------------------------
2315 // we can only sort one array at a time with the quick-sort based
2318 // need a critical section to protect access to gs_compareFunction and
2319 // gs_sortAscending variables
2320 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2322 // call this before the value of the global sort vars is changed/after
2323 // you're finished with them
2324 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2325 gs_critsectStringSort = new wxCriticalSection; \
2326 gs_critsectStringSort->Enter()
2327 #define END_SORT() gs_critsectStringSort->Leave(); \
2328 delete gs_critsectStringSort; \
2329 gs_critsectStringSort = NULL
2331 #define START_SORT()
2333 #endif // wxUSE_THREADS
2335 // function to use for string comparaison
2336 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2338 // if we don't use the compare function, this flag tells us if we sort the
2339 // array in ascending or descending order
2340 static bool gs_sortAscending
= TRUE
;
2342 // function which is called by quick sort
2343 extern "C" int LINKAGEMODE
2344 wxStringCompareFunction(const void *first
, const void *second
)
2346 wxString
*strFirst
= (wxString
*)first
;
2347 wxString
*strSecond
= (wxString
*)second
;
2349 if ( gs_compareFunction
) {
2350 return gs_compareFunction(*strFirst
, *strSecond
);
2353 // maybe we should use wxStrcoll
2354 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
2356 return gs_sortAscending
? result
: -result
;
2360 // sort array elements using passed comparaison function
2361 void wxArrayString::Sort(CompareFunction compareFunction
)
2365 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2366 gs_compareFunction
= compareFunction
;
2370 // reset it to NULL so that Sort(bool) will work the next time
2371 gs_compareFunction
= NULL
;
2376 void wxArrayString::Sort(bool reverseOrder
)
2380 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2381 gs_sortAscending
= !reverseOrder
;
2388 void wxArrayString::DoSort()
2390 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2392 // just sort the pointers using qsort() - of course it only works because
2393 // wxString() *is* a pointer to its data
2394 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2397 bool wxArrayString::operator==(const wxArrayString
& a
) const
2399 if ( m_nCount
!= a
.m_nCount
)
2402 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2404 if ( Item(n
) != a
[n
] )