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
190 int WXDLLEXPORT
wxVsnprintf(wxChar
*buf
, size_t len
,
191 const wxChar
*format
, va_list argptr
)
195 int iLen
= s
.PrintfV(format
, argptr
);
198 wxStrncpy(buf
, s
.c_str(), len
);
199 buf
[len
-1] = wxT('\0');
204 // vsnprintf() will not terminate the string with '\0' if there is not
205 // enough place, but we want the string to always be NUL terminated
206 int rc
= wxVsnprintfA(buf
, len
- 1, format
, argptr
);
213 #endif // Unicode/ANSI
216 // GNU libc 2.2 only has for wxVsnprintf for Unicode called vswprintf
217 // so we imitate wxVsprintf using it.
218 int WXDLLEXPORT
wxVsprintf(wxChar
*buf
,
219 const wxChar
*format
,
222 return vswprintf( buf
, 10000, format
, argptr
);
227 int WXDLLEXPORT
wxSnprintf(wxChar
*buf
, size_t len
,
228 const wxChar
*format
, ...)
231 va_start(argptr
, format
);
233 int iLen
= wxVsnprintf(buf
, len
, format
, argptr
);
240 // GNU libc 2.2 only has for wxSnprintf for Unicode called swprintf
241 // so we imitate wxSprintf using it.
242 int WXDLLEXPORT
wxSprintf(wxChar
*buf
,
243 const wxChar
*format
,
244 ...) ATTRIBUTE_PRINTF_2
247 va_start(argptr
, format
);
249 int iLen
= swprintf(buf
, 10000, format
, argptr
);
257 // ----------------------------------------------------------------------------
259 // ----------------------------------------------------------------------------
261 // this small class is used to gather statistics for performance tuning
262 //#define WXSTRING_STATISTICS
263 #ifdef WXSTRING_STATISTICS
267 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
269 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
271 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
274 size_t m_nCount
, m_nTotal
;
276 } g_averageLength("allocation size"),
277 g_averageSummandLength("summand length"),
278 g_averageConcatHit("hit probability in concat"),
279 g_averageInitialLength("initial string length");
281 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
283 #define STATISTICS_ADD(av, val)
284 #endif // WXSTRING_STATISTICS
286 // ===========================================================================
287 // wxString class core
288 // ===========================================================================
290 // ---------------------------------------------------------------------------
292 // ---------------------------------------------------------------------------
294 // constructs string of <nLength> copies of character <ch>
295 wxString::wxString(wxChar ch
, size_t nLength
)
300 if ( !AllocBuffer(nLength
) ) {
301 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
306 // memset only works on char
307 for (size_t n
=0; n
<nLength
; n
++) m_pchData
[n
] = ch
;
309 memset(m_pchData
, ch
, nLength
);
314 // takes nLength elements of psz starting at nPos
315 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
319 // if the length is not given, assume the string to be NUL terminated
320 if ( nLength
== wxSTRING_MAXLEN
) {
321 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
323 nLength
= wxStrlen(psz
+ nPos
);
326 STATISTICS_ADD(InitialLength
, nLength
);
329 // trailing '\0' is written in AllocBuffer()
330 if ( !AllocBuffer(nLength
) ) {
331 wxFAIL_MSG( _T("out of memory in wxString::InitWith") );
334 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
338 #ifdef wxSTD_STRING_COMPATIBILITY
340 // poor man's iterators are "void *" pointers
341 wxString::wxString(const void *pStart
, const void *pEnd
)
343 InitWith((const wxChar
*)pStart
, 0,
344 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
347 #endif //std::string compatibility
351 // from multibyte string
352 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
354 // first get necessary size
355 size_t nLen
= psz
? conv
.MB2WC((wchar_t *) NULL
, psz
, 0) : 0;
357 // nLength is number of *Unicode* characters here!
358 if ((nLen
!= (size_t)-1) && (nLen
> nLength
))
362 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
363 if ( !AllocBuffer(nLen
) ) {
364 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
367 conv
.MB2WC(m_pchData
, psz
, nLen
);
378 wxString::wxString(const wchar_t *pwz
, wxMBConv
& conv
, size_t nLength
)
380 // first get necessary size
384 if (nLength
== wxSTRING_MAXLEN
)
385 nLen
= conv
.WC2MB((char *) NULL
, pwz
, 0);
391 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
392 if ( !AllocBuffer(nLen
) ) {
393 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
396 conv
.WC2MB(m_pchData
, pwz
, nLen
);
402 #endif // wxUSE_WCHAR_T
404 #endif // Unicode/ANSI
406 // ---------------------------------------------------------------------------
408 // ---------------------------------------------------------------------------
410 // allocates memory needed to store a C string of length nLen
411 bool wxString::AllocBuffer(size_t nLen
)
413 // allocating 0 sized buffer doesn't make sense, all empty strings should
415 wxASSERT( nLen
> 0 );
417 // make sure that we don't overflow
418 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
419 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
421 STATISTICS_ADD(Length
, nLen
);
424 // 1) one extra character for '\0' termination
425 // 2) sizeof(wxStringData) for housekeeping info
426 wxStringData
* pData
= (wxStringData
*)
427 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
429 if ( pData
== NULL
) {
430 // allocation failures are handled by the caller
435 pData
->nDataLength
= nLen
;
436 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
437 m_pchData
= pData
->data(); // data starts after wxStringData
438 m_pchData
[nLen
] = wxT('\0');
442 // must be called before changing this string
443 bool wxString::CopyBeforeWrite()
445 wxStringData
* pData
= GetStringData();
447 if ( pData
->IsShared() ) {
448 pData
->Unlock(); // memory not freed because shared
449 size_t nLen
= pData
->nDataLength
;
450 if ( !AllocBuffer(nLen
) ) {
451 // allocation failures are handled by the caller
454 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
457 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
462 // must be called before replacing contents of this string
463 bool wxString::AllocBeforeWrite(size_t nLen
)
465 wxASSERT( nLen
!= 0 ); // doesn't make any sense
467 // must not share string and must have enough space
468 wxStringData
* pData
= GetStringData();
469 if ( pData
->IsShared() || pData
->IsEmpty() ) {
470 // can't work with old buffer, get new one
472 if ( !AllocBuffer(nLen
) ) {
473 // allocation failures are handled by the caller
478 if ( nLen
> pData
->nAllocLength
) {
479 // realloc the buffer instead of calling malloc() again, this is more
481 STATISTICS_ADD(Length
, nLen
);
485 pData
= (wxStringData
*)
486 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
488 if ( pData
== NULL
) {
489 // allocation failures are handled by the caller
490 // keep previous data since reallocation failed
494 pData
->nAllocLength
= nLen
;
495 m_pchData
= pData
->data();
498 // now we have enough space, just update the string length
499 pData
->nDataLength
= nLen
;
502 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
507 // allocate enough memory for nLen characters
508 bool wxString::Alloc(size_t nLen
)
510 wxStringData
*pData
= GetStringData();
511 if ( pData
->nAllocLength
<= nLen
) {
512 if ( pData
->IsEmpty() ) {
515 wxStringData
* pData
= (wxStringData
*)
516 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
518 if ( pData
== NULL
) {
519 // allocation failure handled by caller
524 pData
->nDataLength
= 0;
525 pData
->nAllocLength
= nLen
;
526 m_pchData
= pData
->data(); // data starts after wxStringData
527 m_pchData
[0u] = wxT('\0');
529 else if ( pData
->IsShared() ) {
530 pData
->Unlock(); // memory not freed because shared
531 size_t nOldLen
= pData
->nDataLength
;
532 if ( !AllocBuffer(nLen
) ) {
533 // allocation failure handled by caller
536 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
541 pData
= (wxStringData
*)
542 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
544 if ( pData
== NULL
) {
545 // allocation failure handled by caller
546 // keep previous data since reallocation failed
550 // it's not important if the pointer changed or not (the check for this
551 // is not faster than assigning to m_pchData in all cases)
552 pData
->nAllocLength
= nLen
;
553 m_pchData
= pData
->data();
556 //else: we've already got enough
560 // shrink to minimal size (releasing extra memory)
561 bool wxString::Shrink()
563 wxStringData
*pData
= GetStringData();
565 size_t nLen
= pData
->nDataLength
;
566 void *p
= realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
569 wxFAIL_MSG( _T("out of memory reallocating wxString data") );
570 // keep previous data since reallocation failed
576 // contrary to what one might believe, some realloc() implementation do
577 // move the memory block even when its size is reduced
578 pData
= (wxStringData
*)p
;
580 m_pchData
= pData
->data();
583 pData
->nAllocLength
= nLen
;
588 // get the pointer to writable buffer of (at least) nLen bytes
589 wxChar
*wxString::GetWriteBuf(size_t nLen
)
591 if ( !AllocBeforeWrite(nLen
) ) {
592 // allocation failure handled by caller
596 wxASSERT( GetStringData()->nRefs
== 1 );
597 GetStringData()->Validate(FALSE
);
602 // put string back in a reasonable state after GetWriteBuf
603 void wxString::UngetWriteBuf()
605 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
606 GetStringData()->Validate(TRUE
);
609 void wxString::UngetWriteBuf(size_t nLen
)
611 GetStringData()->nDataLength
= nLen
;
612 GetStringData()->Validate(TRUE
);
615 // ---------------------------------------------------------------------------
617 // ---------------------------------------------------------------------------
619 // all functions are inline in string.h
621 // ---------------------------------------------------------------------------
622 // assignment operators
623 // ---------------------------------------------------------------------------
625 // helper function: does real copy
626 bool wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
628 if ( nSrcLen
== 0 ) {
632 if ( !AllocBeforeWrite(nSrcLen
) ) {
633 // allocation failure handled by caller
636 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
637 GetStringData()->nDataLength
= nSrcLen
;
638 m_pchData
[nSrcLen
] = wxT('\0');
643 // assigns one string to another
644 wxString
& wxString::operator=(const wxString
& stringSrc
)
646 wxASSERT( stringSrc
.GetStringData()->IsValid() );
648 // don't copy string over itself
649 if ( m_pchData
!= stringSrc
.m_pchData
) {
650 if ( stringSrc
.GetStringData()->IsEmpty() ) {
655 GetStringData()->Unlock();
656 m_pchData
= stringSrc
.m_pchData
;
657 GetStringData()->Lock();
664 // assigns a single character
665 wxString
& wxString::operator=(wxChar ch
)
667 if ( !AssignCopy(1, &ch
) ) {
668 wxFAIL_MSG( _T("out of memory in wxString::operator=(wxChar)") );
675 wxString
& wxString::operator=(const wxChar
*psz
)
677 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
678 wxFAIL_MSG( _T("out of memory in wxString::operator=(const wxChar *)") );
685 // same as 'signed char' variant
686 wxString
& wxString::operator=(const unsigned char* psz
)
688 *this = (const char *)psz
;
693 wxString
& wxString::operator=(const wchar_t *pwz
)
703 // ---------------------------------------------------------------------------
704 // string concatenation
705 // ---------------------------------------------------------------------------
707 // add something to this string
708 bool wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
710 STATISTICS_ADD(SummandLength
, nSrcLen
);
712 // concatenating an empty string is a NOP
714 wxStringData
*pData
= GetStringData();
715 size_t nLen
= pData
->nDataLength
;
716 size_t nNewLen
= nLen
+ nSrcLen
;
718 // alloc new buffer if current is too small
719 if ( pData
->IsShared() ) {
720 STATISTICS_ADD(ConcatHit
, 0);
722 // we have to allocate another buffer
723 wxStringData
* pOldData
= GetStringData();
724 if ( !AllocBuffer(nNewLen
) ) {
725 // allocation failure handled by caller
728 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
731 else if ( nNewLen
> pData
->nAllocLength
) {
732 STATISTICS_ADD(ConcatHit
, 0);
734 // we have to grow the buffer
735 if ( !Alloc(nNewLen
) ) {
736 // allocation failure handled by caller
741 STATISTICS_ADD(ConcatHit
, 1);
743 // the buffer is already big enough
746 // should be enough space
747 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
749 // fast concatenation - all is done in our buffer
750 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
752 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
753 GetStringData()->nDataLength
= nNewLen
; // and fix the length
755 //else: the string to append was empty
760 * concatenation functions come in 5 flavours:
762 * char + string and string + char
763 * C str + string and string + C str
766 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
768 wxASSERT( str1
.GetStringData()->IsValid() );
769 wxASSERT( str2
.GetStringData()->IsValid() );
777 wxString
operator+(const wxString
& str
, wxChar ch
)
779 wxASSERT( str
.GetStringData()->IsValid() );
787 wxString
operator+(wxChar ch
, const wxString
& str
)
789 wxASSERT( str
.GetStringData()->IsValid() );
797 wxString
operator+(const wxString
& str
, const wxChar
*psz
)
799 wxASSERT( str
.GetStringData()->IsValid() );
802 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
803 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
811 wxString
operator+(const wxChar
*psz
, const wxString
& str
)
813 wxASSERT( str
.GetStringData()->IsValid() );
816 if ( !s
.Alloc(wxStrlen(psz
) + str
.Len()) ) {
817 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
825 // ===========================================================================
826 // other common string functions
827 // ===========================================================================
829 // ---------------------------------------------------------------------------
830 // simple sub-string extraction
831 // ---------------------------------------------------------------------------
833 // helper function: clone the data attached to this string
834 bool wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
836 if ( nCopyLen
== 0 ) {
840 if ( !dest
.AllocBuffer(nCopyLen
) ) {
841 // allocation failure handled by caller
844 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
849 // extract string of length nCount starting at nFirst
850 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
852 wxStringData
*pData
= GetStringData();
853 size_t nLen
= pData
->nDataLength
;
855 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
856 if ( nCount
== wxSTRING_MAXLEN
)
858 nCount
= nLen
- nFirst
;
861 // out-of-bounds requests return sensible things
862 if ( nFirst
+ nCount
> nLen
)
864 nCount
= nLen
- nFirst
;
869 // AllocCopy() will return empty string
874 if ( !AllocCopy(dest
, nCount
, nFirst
) ) {
875 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
881 // check that the tring starts with prefix and return the rest of the string
882 // in the provided pointer if it is not NULL, otherwise return FALSE
883 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
885 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
887 // first check if the beginning of the string matches the prefix: note
888 // that we don't have to check that we don't run out of this string as
889 // when we reach the terminating NUL, either prefix string ends too (and
890 // then it's ok) or we break out of the loop because there is no match
891 const wxChar
*p
= c_str();
894 if ( *prefix
++ != *p
++ )
903 // put the rest of the string into provided pointer
910 // extract nCount last (rightmost) characters
911 wxString
wxString::Right(size_t nCount
) const
913 if ( nCount
> (size_t)GetStringData()->nDataLength
)
914 nCount
= GetStringData()->nDataLength
;
917 if ( !AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
) ) {
918 wxFAIL_MSG( _T("out of memory in wxString::Right") );
923 // get all characters after the last occurence of ch
924 // (returns the whole string if ch not found)
925 wxString
wxString::AfterLast(wxChar ch
) const
928 int iPos
= Find(ch
, TRUE
);
929 if ( iPos
== wxNOT_FOUND
)
932 str
= c_str() + iPos
+ 1;
937 // extract nCount first (leftmost) characters
938 wxString
wxString::Left(size_t nCount
) const
940 if ( nCount
> (size_t)GetStringData()->nDataLength
)
941 nCount
= GetStringData()->nDataLength
;
944 if ( !AllocCopy(dest
, nCount
, 0) ) {
945 wxFAIL_MSG( _T("out of memory in wxString::Left") );
950 // get all characters before the first occurence of ch
951 // (returns the whole string if ch not found)
952 wxString
wxString::BeforeFirst(wxChar ch
) const
955 for ( const wxChar
*pc
= m_pchData
; *pc
!= wxT('\0') && *pc
!= ch
; pc
++ )
961 /// get all characters before the last occurence of ch
962 /// (returns empty string if ch not found)
963 wxString
wxString::BeforeLast(wxChar ch
) const
966 int iPos
= Find(ch
, TRUE
);
967 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
968 str
= wxString(c_str(), iPos
);
973 /// get all characters after the first occurence of ch
974 /// (returns empty string if ch not found)
975 wxString
wxString::AfterFirst(wxChar ch
) const
979 if ( iPos
!= wxNOT_FOUND
)
980 str
= c_str() + iPos
+ 1;
985 // replace first (or all) occurences of some substring with another one
986 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
988 size_t uiCount
= 0; // count of replacements made
990 size_t uiOldLen
= wxStrlen(szOld
);
993 const wxChar
*pCurrent
= m_pchData
;
994 const wxChar
*pSubstr
;
995 while ( *pCurrent
!= wxT('\0') ) {
996 pSubstr
= wxStrstr(pCurrent
, szOld
);
997 if ( pSubstr
== NULL
) {
998 // strTemp is unused if no replacements were made, so avoid the copy
1002 strTemp
+= pCurrent
; // copy the rest
1003 break; // exit the loop
1006 // take chars before match
1007 if ( !strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
) ) {
1008 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
1012 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
1017 if ( !bReplaceAll
) {
1018 strTemp
+= pCurrent
; // copy the rest
1019 break; // exit the loop
1024 // only done if there were replacements, otherwise would have returned above
1030 bool wxString::IsAscii() const
1032 const wxChar
*s
= (const wxChar
*) *this;
1034 if(!isascii(*s
)) return(FALSE
);
1040 bool wxString::IsWord() const
1042 const wxChar
*s
= (const wxChar
*) *this;
1044 if(!wxIsalpha(*s
)) return(FALSE
);
1050 bool wxString::IsNumber() const
1052 const wxChar
*s
= (const wxChar
*) *this;
1054 if ((s
[0] == '-') || (s
[0] == '+')) s
++;
1056 if(!wxIsdigit(*s
)) return(FALSE
);
1062 wxString
wxString::Strip(stripType w
) const
1065 if ( w
& leading
) s
.Trim(FALSE
);
1066 if ( w
& trailing
) s
.Trim(TRUE
);
1070 // ---------------------------------------------------------------------------
1072 // ---------------------------------------------------------------------------
1074 wxString
& wxString::MakeUpper()
1076 if ( !CopyBeforeWrite() ) {
1077 wxFAIL_MSG( _T("out of memory in wxString::MakeUpper") );
1081 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1082 *p
= (wxChar
)wxToupper(*p
);
1087 wxString
& wxString::MakeLower()
1089 if ( !CopyBeforeWrite() ) {
1090 wxFAIL_MSG( _T("out of memory in wxString::MakeLower") );
1094 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1095 *p
= (wxChar
)wxTolower(*p
);
1100 // ---------------------------------------------------------------------------
1101 // trimming and padding
1102 // ---------------------------------------------------------------------------
1104 // some compilers (VC++ 6.0 not to name them) return TRUE for a call to
1105 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1106 // live with this by checking that the character is a 7 bit one - even if this
1107 // may fail to detect some spaces (I don't know if Unicode doesn't have
1108 // space-like symbols somewhere except in the first 128 chars), it is arguably
1109 // still better than trimming away accented letters
1110 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1112 // trims spaces (in the sense of isspace) from left or right side
1113 wxString
& wxString::Trim(bool bFromRight
)
1115 // first check if we're going to modify the string at all
1118 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1119 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1123 // ok, there is at least one space to trim
1124 if ( !CopyBeforeWrite() ) {
1125 wxFAIL_MSG( _T("out of memory in wxString::Trim") );
1131 // find last non-space character
1132 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
1133 while ( wxSafeIsspace(*psz
) && (psz
>= m_pchData
) )
1136 // truncate at trailing space start
1138 GetStringData()->nDataLength
= psz
- m_pchData
;
1142 // find first non-space character
1143 const wxChar
*psz
= m_pchData
;
1144 while ( wxSafeIsspace(*psz
) )
1147 // fix up data and length
1148 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
1149 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
1150 GetStringData()->nDataLength
= nDataLength
;
1157 // adds nCount characters chPad to the string from either side
1158 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1160 wxString
s(chPad
, nCount
);
1173 // truncate the string
1174 wxString
& wxString::Truncate(size_t uiLen
)
1176 if ( uiLen
< Len() ) {
1177 if ( !CopyBeforeWrite() ) {
1178 wxFAIL_MSG( _T("out of memory in wxString::Truncate") );
1182 *(m_pchData
+ uiLen
) = wxT('\0');
1183 GetStringData()->nDataLength
= uiLen
;
1185 //else: nothing to do, string is already short enough
1190 // ---------------------------------------------------------------------------
1191 // finding (return wxNOT_FOUND if not found and index otherwise)
1192 // ---------------------------------------------------------------------------
1195 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1197 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
1199 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1202 // find a sub-string (like strstr)
1203 int wxString::Find(const wxChar
*pszSub
) const
1205 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
1207 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1210 // ----------------------------------------------------------------------------
1211 // conversion to numbers
1212 // ----------------------------------------------------------------------------
1214 bool wxString::ToLong(long *val
, int base
) const
1216 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToLong") );
1217 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1219 const wxChar
*start
= c_str();
1221 *val
= wxStrtol(start
, &end
, base
);
1223 // return TRUE only if scan was stopped by the terminating NUL and if the
1224 // string was not empty to start with
1225 return !*end
&& (end
!= start
);
1228 bool wxString::ToULong(unsigned long *val
, int base
) const
1230 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToULong") );
1231 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1233 const wxChar
*start
= c_str();
1235 *val
= wxStrtoul(start
, &end
, base
);
1237 // return TRUE only if scan was stopped by the terminating NUL and if the
1238 // string was not empty to start with
1239 return !*end
&& (end
!= start
);
1242 bool wxString::ToDouble(double *val
) const
1244 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToDouble") );
1246 const wxChar
*start
= c_str();
1248 *val
= wxStrtod(start
, &end
);
1250 // return TRUE only if scan was stopped by the terminating NUL and if the
1251 // string was not empty to start with
1252 return !*end
&& (end
!= start
);
1255 // ---------------------------------------------------------------------------
1257 // ---------------------------------------------------------------------------
1260 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1263 va_start(argptr
, pszFormat
);
1266 s
.PrintfV(pszFormat
, argptr
);
1274 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1277 s
.PrintfV(pszFormat
, argptr
);
1281 int wxString::Printf(const wxChar
*pszFormat
, ...)
1284 va_start(argptr
, pszFormat
);
1286 int iLen
= PrintfV(pszFormat
, argptr
);
1293 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1295 #if wxUSE_EXPERIMENTAL_PRINTF
1296 // the new implementation
1298 // buffer to avoid dynamic memory allocation each time for small strings
1299 char szScratch
[1024];
1302 for (size_t n
= 0; pszFormat
[n
]; n
++)
1303 if (pszFormat
[n
] == wxT('%')) {
1304 static char s_szFlags
[256] = "%";
1306 bool adj_left
= FALSE
, in_prec
= FALSE
,
1307 prec_dot
= FALSE
, done
= FALSE
;
1309 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1311 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1312 switch (pszFormat
[++n
]) {
1326 s_szFlags
[flagofs
++] = pszFormat
[n
];
1331 s_szFlags
[flagofs
++] = pszFormat
[n
];
1338 // dot will be auto-added to s_szFlags if non-negative number follows
1343 s_szFlags
[flagofs
++] = pszFormat
[n
];
1348 s_szFlags
[flagofs
++] = pszFormat
[n
];
1354 s_szFlags
[flagofs
++] = pszFormat
[n
];
1359 s_szFlags
[flagofs
++] = pszFormat
[n
];
1363 int len
= va_arg(argptr
, int);
1370 adj_left
= !adj_left
;
1371 s_szFlags
[flagofs
++] = '-';
1376 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1379 case wxT('1'): case wxT('2'): case wxT('3'):
1380 case wxT('4'): case wxT('5'): case wxT('6'):
1381 case wxT('7'): case wxT('8'): case wxT('9'):
1385 while ((pszFormat
[n
]>=wxT('0')) && (pszFormat
[n
]<=wxT('9'))) {
1386 s_szFlags
[flagofs
++] = pszFormat
[n
];
1387 len
= len
*10 + (pszFormat
[n
] - wxT('0'));
1390 if (in_prec
) max_width
= len
;
1391 else min_width
= len
;
1392 n
--; // the main loop pre-increments n again
1402 s_szFlags
[flagofs
++] = pszFormat
[n
];
1403 s_szFlags
[flagofs
] = '\0';
1405 int val
= va_arg(argptr
, int);
1406 ::sprintf(szScratch
, s_szFlags
, val
);
1408 else if (ilen
== -1) {
1409 short int val
= va_arg(argptr
, short int);
1410 ::sprintf(szScratch
, s_szFlags
, val
);
1412 else if (ilen
== 1) {
1413 long int val
= va_arg(argptr
, long int);
1414 ::sprintf(szScratch
, s_szFlags
, val
);
1416 else if (ilen
== 2) {
1417 #if SIZEOF_LONG_LONG
1418 long long int val
= va_arg(argptr
, long long int);
1419 ::sprintf(szScratch
, s_szFlags
, val
);
1421 long int val
= va_arg(argptr
, long int);
1422 ::sprintf(szScratch
, s_szFlags
, val
);
1425 else if (ilen
== 3) {
1426 size_t val
= va_arg(argptr
, size_t);
1427 ::sprintf(szScratch
, s_szFlags
, val
);
1429 *this += wxString(szScratch
);
1438 s_szFlags
[flagofs
++] = pszFormat
[n
];
1439 s_szFlags
[flagofs
] = '\0';
1441 long double val
= va_arg(argptr
, long double);
1442 ::sprintf(szScratch
, s_szFlags
, val
);
1444 double val
= va_arg(argptr
, double);
1445 ::sprintf(szScratch
, s_szFlags
, val
);
1447 *this += wxString(szScratch
);
1452 void *val
= va_arg(argptr
, void *);
1454 s_szFlags
[flagofs
++] = pszFormat
[n
];
1455 s_szFlags
[flagofs
] = '\0';
1456 ::sprintf(szScratch
, s_szFlags
, val
);
1457 *this += wxString(szScratch
);
1463 wxChar val
= va_arg(argptr
, int);
1464 // we don't need to honor padding here, do we?
1471 // wx extension: we'll let %hs mean non-Unicode strings
1472 char *val
= va_arg(argptr
, char *);
1474 // ASCII->Unicode constructor handles max_width right
1475 wxString
s(val
, wxConvLibc
, max_width
);
1477 size_t len
= wxSTRING_MAXLEN
;
1479 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1480 } else val
= wxT("(null)");
1481 wxString
s(val
, len
);
1483 if (s
.Len() < min_width
)
1484 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1487 wxChar
*val
= va_arg(argptr
, wxChar
*);
1488 size_t len
= wxSTRING_MAXLEN
;
1490 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1491 } else val
= wxT("(null)");
1492 wxString
s(val
, len
);
1493 if (s
.Len() < min_width
)
1494 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1501 int *val
= va_arg(argptr
, int *);
1504 else if (ilen
== -1) {
1505 short int *val
= va_arg(argptr
, short int *);
1508 else if (ilen
>= 1) {
1509 long int *val
= va_arg(argptr
, long int *);
1515 if (wxIsalpha(pszFormat
[n
]))
1516 // probably some flag not taken care of here yet
1517 s_szFlags
[flagofs
++] = pszFormat
[n
];
1520 *this += wxT('%'); // just to pass the glibc tst-printf.c
1528 } else *this += pszFormat
[n
];
1531 // buffer to avoid dynamic memory allocation each time for small strings
1532 char szScratch
[1024];
1534 // NB: wxVsnprintf() may return either less than the buffer size or -1 if
1535 // there is not enough place depending on implementation
1536 int iLen
= wxVsnprintfA(szScratch
, WXSIZEOF(szScratch
), (char *)pszFormat
, argptr
);
1538 // the whole string is in szScratch
1542 bool outOfMemory
= FALSE
;
1543 int size
= 2*WXSIZEOF(szScratch
);
1544 while ( !outOfMemory
) {
1545 char *buf
= GetWriteBuf(size
);
1547 iLen
= wxVsnprintfA(buf
, size
, pszFormat
, argptr
);
1554 // ok, there was enough space
1558 // still not enough, double it again
1562 if ( outOfMemory
) {
1567 #endif // wxUSE_EXPERIMENTAL_PRINTF/!wxUSE_EXPERIMENTAL_PRINTF
1572 // ----------------------------------------------------------------------------
1573 // misc other operations
1574 // ----------------------------------------------------------------------------
1576 // returns TRUE if the string matches the pattern which may contain '*' and
1577 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1579 bool wxString::Matches(const wxChar
*pszMask
) const
1581 // I disable this code as it doesn't seem to be faster (in fact, it seems
1582 // to be much slower) than the old, hand-written code below and using it
1583 // here requires always linking with libregex even if the user code doesn't
1585 #if 0 // wxUSE_REGEX
1586 // first translate the shell-like mask into a regex
1588 pattern
.reserve(wxStrlen(pszMask
));
1600 pattern
+= _T(".*");
1611 // these characters are special in a RE, quote them
1612 // (however note that we don't quote '[' and ']' to allow
1613 // using them for Unix shell like matching)
1614 pattern
+= _T('\\');
1618 pattern
+= *pszMask
;
1626 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1627 #else // !wxUSE_REGEX
1628 // TODO: this is, of course, awfully inefficient...
1630 // the char currently being checked
1631 const wxChar
*pszTxt
= c_str();
1633 // the last location where '*' matched
1634 const wxChar
*pszLastStarInText
= NULL
;
1635 const wxChar
*pszLastStarInMask
= NULL
;
1638 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1639 switch ( *pszMask
) {
1641 if ( *pszTxt
== wxT('\0') )
1644 // pszTxt and pszMask will be incremented in the loop statement
1650 // remember where we started to be able to backtrack later
1651 pszLastStarInText
= pszTxt
;
1652 pszLastStarInMask
= pszMask
;
1654 // ignore special chars immediately following this one
1655 // (should this be an error?)
1656 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1659 // if there is nothing more, match
1660 if ( *pszMask
== wxT('\0') )
1663 // are there any other metacharacters in the mask?
1665 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1667 if ( pEndMask
!= NULL
) {
1668 // we have to match the string between two metachars
1669 uiLenMask
= pEndMask
- pszMask
;
1672 // we have to match the remainder of the string
1673 uiLenMask
= wxStrlen(pszMask
);
1676 wxString
strToMatch(pszMask
, uiLenMask
);
1677 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1678 if ( pMatch
== NULL
)
1681 // -1 to compensate "++" in the loop
1682 pszTxt
= pMatch
+ uiLenMask
- 1;
1683 pszMask
+= uiLenMask
- 1;
1688 if ( *pszMask
!= *pszTxt
)
1694 // match only if nothing left
1695 if ( *pszTxt
== wxT('\0') )
1698 // if we failed to match, backtrack if we can
1699 if ( pszLastStarInText
) {
1700 pszTxt
= pszLastStarInText
+ 1;
1701 pszMask
= pszLastStarInMask
;
1703 pszLastStarInText
= NULL
;
1705 // don't bother resetting pszLastStarInMask, it's unnecessary
1711 #endif // wxUSE_REGEX/!wxUSE_REGEX
1714 // Count the number of chars
1715 int wxString::Freq(wxChar ch
) const
1719 for (int i
= 0; i
< len
; i
++)
1721 if (GetChar(i
) == ch
)
1727 // convert to upper case, return the copy of the string
1728 wxString
wxString::Upper() const
1729 { wxString
s(*this); return s
.MakeUpper(); }
1731 // convert to lower case, return the copy of the string
1732 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1734 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1737 va_start(argptr
, pszFormat
);
1738 int iLen
= PrintfV(pszFormat
, argptr
);
1743 // ---------------------------------------------------------------------------
1744 // standard C++ library string functions
1745 // ---------------------------------------------------------------------------
1747 #ifdef wxSTD_STRING_COMPATIBILITY
1749 void wxString::resize(size_t nSize
, wxChar ch
)
1751 size_t len
= length();
1757 else if ( nSize
> len
)
1759 *this += wxString(ch
, nSize
- len
);
1761 //else: we have exactly the specified length, nothing to do
1764 void wxString::swap(wxString
& str
)
1766 // this is slightly less efficient than fiddling with m_pchData directly,
1767 // but it is still quite efficient as we don't copy the string here because
1768 // ref count always stays positive
1774 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1776 wxASSERT( str
.GetStringData()->IsValid() );
1777 wxASSERT( nPos
<= Len() );
1779 if ( !str
.IsEmpty() ) {
1781 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1782 wxStrncpy(pc
, c_str(), nPos
);
1783 wxStrcpy(pc
+ nPos
, str
);
1784 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1785 strTmp
.UngetWriteBuf();
1792 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1794 wxASSERT( str
.GetStringData()->IsValid() );
1795 wxASSERT( nStart
<= Len() );
1797 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1799 return p
== NULL
? npos
: p
- c_str();
1802 // VC++ 1.5 can't cope with the default argument in the header.
1803 #if !defined(__VISUALC__) || defined(__WIN32__)
1804 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1806 return find(wxString(sz
, n
), nStart
);
1810 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1811 #if !defined(__BORLANDC__)
1812 size_t wxString::find(wxChar ch
, size_t nStart
) const
1814 wxASSERT( nStart
<= Len() );
1816 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1818 return p
== NULL
? npos
: p
- c_str();
1822 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1824 wxASSERT( str
.GetStringData()->IsValid() );
1825 wxASSERT( nStart
== npos
|| nStart
<= Len() );
1827 // TODO could be made much quicker than that
1828 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1829 while ( p
>= c_str() + str
.Len() ) {
1830 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1831 return p
- str
.Len() - c_str();
1838 // VC++ 1.5 can't cope with the default argument in the header.
1839 #if !defined(__VISUALC__) || defined(__WIN32__)
1840 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1842 return rfind(wxString(sz
, n
== npos
? wxSTRING_MAXLEN
: n
), nStart
);
1845 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1847 if ( nStart
== npos
)
1853 wxASSERT( nStart
<= Len() );
1856 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1861 size_t result
= p
- c_str();
1862 return ( result
> nStart
) ? npos
: result
;
1866 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1868 const wxChar
*start
= c_str() + nStart
;
1869 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1871 return firstOf
- c_str();
1876 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1878 if ( nStart
== npos
)
1884 wxASSERT( nStart
<= Len() );
1887 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1889 if ( wxStrchr(sz
, *p
) )
1896 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1898 if ( nStart
== npos
)
1904 wxASSERT( nStart
<= Len() );
1907 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1908 if ( nAccept
>= length() - nStart
)
1914 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1916 wxASSERT( nStart
<= Len() );
1918 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1927 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1929 if ( nStart
== npos
)
1935 wxASSERT( nStart
<= Len() );
1938 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1940 if ( !wxStrchr(sz
, *p
) )
1947 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1949 if ( nStart
== npos
)
1955 wxASSERT( nStart
<= Len() );
1958 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1967 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1969 wxString
strTmp(c_str(), nStart
);
1970 if ( nLen
!= npos
) {
1971 wxASSERT( nStart
+ nLen
<= Len() );
1973 strTmp
.append(c_str() + nStart
+ nLen
);
1980 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1982 wxASSERT_MSG( nStart
+ nLen
<= Len(),
1983 _T("index out of bounds in wxString::replace") );
1986 strTmp
.Alloc(Len()); // micro optimisation to avoid multiple mem allocs
1989 strTmp
.append(c_str(), nStart
);
1990 strTmp
<< sz
<< c_str() + nStart
+ nLen
;
1996 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1998 return replace(nStart
, nLen
, wxString(ch
, nCount
));
2001 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
2002 const wxString
& str
, size_t nStart2
, size_t nLen2
)
2004 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
2007 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
2008 const wxChar
* sz
, size_t nCount
)
2010 return replace(nStart
, nLen
, wxString(sz
, nCount
));
2013 #endif //std::string compatibility
2015 // ============================================================================
2017 // ============================================================================
2019 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
2020 #define ARRAY_MAXSIZE_INCREMENT 4096
2022 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
2023 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
2026 #define STRING(p) ((wxString *)(&(p)))
2029 void wxArrayString::Init(bool autoSort
)
2033 m_pItems
= (wxChar
**) NULL
;
2034 m_autoSort
= autoSort
;
2038 wxArrayString::wxArrayString(const wxArrayString
& src
)
2040 Init(src
.m_autoSort
);
2045 // assignment operator
2046 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
2053 m_autoSort
= src
.m_autoSort
;
2058 void wxArrayString::Copy(const wxArrayString
& src
)
2060 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
2061 Alloc(src
.m_nCount
);
2063 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
2068 void wxArrayString::Grow(size_t nIncrement
)
2070 // only do it if no more place
2071 if ( m_nCount
== m_nSize
) {
2072 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2073 // be never resized!
2074 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2075 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2078 if ( m_nSize
== 0 ) {
2079 // was empty, alloc some memory
2080 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
2081 m_pItems
= new wxChar
*[m_nSize
];
2084 // otherwise when it's called for the first time, nIncrement would be 0
2085 // and the array would never be expanded
2086 // add 50% but not too much
2087 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
2088 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
2089 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
2090 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
2091 if ( nIncrement
< ndefIncrement
)
2092 nIncrement
= ndefIncrement
;
2093 m_nSize
+= nIncrement
;
2094 wxChar
**pNew
= new wxChar
*[m_nSize
];
2096 // copy data to new location
2097 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2099 // delete old memory (but do not release the strings!)
2100 wxDELETEA(m_pItems
);
2107 void wxArrayString::Free()
2109 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
2110 STRING(m_pItems
[n
])->GetStringData()->Unlock();
2114 // deletes all the strings from the list
2115 void wxArrayString::Empty()
2122 // as Empty, but also frees memory
2123 void wxArrayString::Clear()
2130 wxDELETEA(m_pItems
);
2134 wxArrayString::~wxArrayString()
2138 wxDELETEA(m_pItems
);
2141 // pre-allocates memory (frees the previous data!)
2142 void wxArrayString::Alloc(size_t nSize
)
2144 // only if old buffer was not big enough
2145 if ( nSize
> m_nSize
) {
2147 wxDELETEA(m_pItems
);
2148 m_pItems
= new wxChar
*[nSize
];
2155 // minimizes the memory usage by freeing unused memory
2156 void wxArrayString::Shrink()
2158 // only do it if we have some memory to free
2159 if( m_nCount
< m_nSize
) {
2160 // allocates exactly as much memory as we need
2161 wxChar
**pNew
= new wxChar
*[m_nCount
];
2163 // copy data to new location
2164 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2170 // return a wxString[] as required for some control ctors.
2171 wxString
* wxArrayString::GetStringArray() const
2173 wxString
*array
= 0;
2177 array
= new wxString
[m_nCount
];
2178 for( size_t i
= 0; i
< m_nCount
; i
++ )
2179 array
[i
] = m_pItems
[i
];
2185 // searches the array for an item (forward or backwards)
2186 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2189 // use binary search in the sorted array
2190 wxASSERT_MSG( bCase
&& !bFromEnd
,
2191 wxT("search parameters ignored for auto sorted array") );
2200 res
= wxStrcmp(sz
, m_pItems
[i
]);
2212 // use linear search in unsorted array
2214 if ( m_nCount
> 0 ) {
2215 size_t ui
= m_nCount
;
2217 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2224 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2225 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2234 // add item at the end
2235 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
2238 // insert the string at the correct position to keep the array sorted
2246 res
= wxStrcmp(str
, m_pItems
[i
]);
2257 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2259 Insert(str
, lo
, nInsert
);
2264 wxASSERT( str
.GetStringData()->IsValid() );
2268 for (size_t i
= 0; i
< nInsert
; i
++)
2270 // the string data must not be deleted!
2271 str
.GetStringData()->Lock();
2274 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2276 size_t ret
= m_nCount
;
2277 m_nCount
+= nInsert
;
2282 // add item at the given position
2283 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2285 wxASSERT( str
.GetStringData()->IsValid() );
2287 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2288 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2289 wxT("array size overflow in wxArrayString::Insert") );
2293 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2294 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2296 for (size_t i
= 0; i
< nInsert
; i
++)
2298 str
.GetStringData()->Lock();
2299 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2301 m_nCount
+= nInsert
;
2305 void wxArrayString::SetCount(size_t count
)
2310 while ( m_nCount
< count
)
2311 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2314 // removes item from array (by index)
2315 void wxArrayString::Remove(size_t nIndex
, size_t nRemove
)
2317 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2318 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2319 wxT("removing too many elements in wxArrayString::Remove") );
2322 for (size_t i
= 0; i
< nRemove
; i
++)
2323 Item(nIndex
+ i
).GetStringData()->Unlock();
2325 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2326 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2327 m_nCount
-= nRemove
;
2330 // removes item from array (by value)
2331 void wxArrayString::Remove(const wxChar
*sz
)
2333 int iIndex
= Index(sz
);
2335 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2336 wxT("removing inexistent element in wxArrayString::Remove") );
2341 // ----------------------------------------------------------------------------
2343 // ----------------------------------------------------------------------------
2345 // we can only sort one array at a time with the quick-sort based
2348 // need a critical section to protect access to gs_compareFunction and
2349 // gs_sortAscending variables
2350 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2352 // call this before the value of the global sort vars is changed/after
2353 // you're finished with them
2354 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2355 gs_critsectStringSort = new wxCriticalSection; \
2356 gs_critsectStringSort->Enter()
2357 #define END_SORT() gs_critsectStringSort->Leave(); \
2358 delete gs_critsectStringSort; \
2359 gs_critsectStringSort = NULL
2361 #define START_SORT()
2363 #endif // wxUSE_THREADS
2365 // function to use for string comparaison
2366 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2368 // if we don't use the compare function, this flag tells us if we sort the
2369 // array in ascending or descending order
2370 static bool gs_sortAscending
= TRUE
;
2372 // function which is called by quick sort
2373 extern "C" int LINKAGEMODE
2374 wxStringCompareFunction(const void *first
, const void *second
)
2376 wxString
*strFirst
= (wxString
*)first
;
2377 wxString
*strSecond
= (wxString
*)second
;
2379 if ( gs_compareFunction
) {
2380 return gs_compareFunction(*strFirst
, *strSecond
);
2383 // maybe we should use wxStrcoll
2384 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
2386 return gs_sortAscending
? result
: -result
;
2390 // sort array elements using passed comparaison function
2391 void wxArrayString::Sort(CompareFunction compareFunction
)
2395 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2396 gs_compareFunction
= compareFunction
;
2400 // reset it to NULL so that Sort(bool) will work the next time
2401 gs_compareFunction
= NULL
;
2406 void wxArrayString::Sort(bool reverseOrder
)
2410 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2411 gs_sortAscending
= !reverseOrder
;
2418 void wxArrayString::DoSort()
2420 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2422 // just sort the pointers using qsort() - of course it only works because
2423 // wxString() *is* a pointer to its data
2424 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2427 bool wxArrayString::operator==(const wxArrayString
& a
) const
2429 if ( m_nCount
!= a
.m_nCount
)
2432 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2434 if ( Item(n
) != a
[n
] )