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 // ===========================================================================
830 wxString
wxString::FromAscii( char *ascii
)
833 return wxEmptyString
;
835 size_t len
= strlen( ascii
);
837 res
.AllocBuffer( len
);
838 wchar_t *dest
= (wchar_t*)(const wchar_t*) res
.c_str();
840 for (size_t i
= 0; i
< len
+1; i
++)
841 dest
[i
] = (wchar_t) ascii
[i
];
846 const wxCharBuffer
wxString::ToAscii() const
849 return wxCharBuffer( (const char*)NULL
);
852 wxCharBuffer
buffer( len
); // allocates len+1
854 char *dest
= (char*)(const char*) buffer
;
856 for (size_t i
= 0; i
< len
+1; i
++)
858 if (m_pchData
[i
] > 127)
861 dest
[i
] = (char) m_pchData
[i
];
868 // ---------------------------------------------------------------------------
869 // simple sub-string extraction
870 // ---------------------------------------------------------------------------
872 // helper function: clone the data attached to this string
873 bool wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
875 if ( nCopyLen
== 0 ) {
879 if ( !dest
.AllocBuffer(nCopyLen
) ) {
880 // allocation failure handled by caller
883 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
888 // extract string of length nCount starting at nFirst
889 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
891 wxStringData
*pData
= GetStringData();
892 size_t nLen
= pData
->nDataLength
;
894 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
895 if ( nCount
== wxSTRING_MAXLEN
)
897 nCount
= nLen
- nFirst
;
900 // out-of-bounds requests return sensible things
901 if ( nFirst
+ nCount
> nLen
)
903 nCount
= nLen
- nFirst
;
908 // AllocCopy() will return empty string
913 if ( !AllocCopy(dest
, nCount
, nFirst
) ) {
914 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
920 // check that the tring starts with prefix and return the rest of the string
921 // in the provided pointer if it is not NULL, otherwise return FALSE
922 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
924 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
926 // first check if the beginning of the string matches the prefix: note
927 // that we don't have to check that we don't run out of this string as
928 // when we reach the terminating NUL, either prefix string ends too (and
929 // then it's ok) or we break out of the loop because there is no match
930 const wxChar
*p
= c_str();
933 if ( *prefix
++ != *p
++ )
942 // put the rest of the string into provided pointer
949 // extract nCount last (rightmost) characters
950 wxString
wxString::Right(size_t nCount
) const
952 if ( nCount
> (size_t)GetStringData()->nDataLength
)
953 nCount
= GetStringData()->nDataLength
;
956 if ( !AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
) ) {
957 wxFAIL_MSG( _T("out of memory in wxString::Right") );
962 // get all characters after the last occurence of ch
963 // (returns the whole string if ch not found)
964 wxString
wxString::AfterLast(wxChar ch
) const
967 int iPos
= Find(ch
, TRUE
);
968 if ( iPos
== wxNOT_FOUND
)
971 str
= c_str() + iPos
+ 1;
976 // extract nCount first (leftmost) characters
977 wxString
wxString::Left(size_t nCount
) const
979 if ( nCount
> (size_t)GetStringData()->nDataLength
)
980 nCount
= GetStringData()->nDataLength
;
983 if ( !AllocCopy(dest
, nCount
, 0) ) {
984 wxFAIL_MSG( _T("out of memory in wxString::Left") );
989 // get all characters before the first occurence of ch
990 // (returns the whole string if ch not found)
991 wxString
wxString::BeforeFirst(wxChar ch
) const
994 for ( const wxChar
*pc
= m_pchData
; *pc
!= wxT('\0') && *pc
!= ch
; pc
++ )
1000 /// get all characters before the last occurence of ch
1001 /// (returns empty string if ch not found)
1002 wxString
wxString::BeforeLast(wxChar ch
) const
1005 int iPos
= Find(ch
, TRUE
);
1006 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
1007 str
= wxString(c_str(), iPos
);
1012 /// get all characters after the first occurence of ch
1013 /// (returns empty string if ch not found)
1014 wxString
wxString::AfterFirst(wxChar ch
) const
1017 int iPos
= Find(ch
);
1018 if ( iPos
!= wxNOT_FOUND
)
1019 str
= c_str() + iPos
+ 1;
1024 // replace first (or all) occurences of some substring with another one
1025 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
1027 size_t uiCount
= 0; // count of replacements made
1029 size_t uiOldLen
= wxStrlen(szOld
);
1032 const wxChar
*pCurrent
= m_pchData
;
1033 const wxChar
*pSubstr
;
1034 while ( *pCurrent
!= wxT('\0') ) {
1035 pSubstr
= wxStrstr(pCurrent
, szOld
);
1036 if ( pSubstr
== NULL
) {
1037 // strTemp is unused if no replacements were made, so avoid the copy
1041 strTemp
+= pCurrent
; // copy the rest
1042 break; // exit the loop
1045 // take chars before match
1046 if ( !strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
) ) {
1047 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
1051 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
1056 if ( !bReplaceAll
) {
1057 strTemp
+= pCurrent
; // copy the rest
1058 break; // exit the loop
1063 // only done if there were replacements, otherwise would have returned above
1069 bool wxString::IsAscii() const
1071 const wxChar
*s
= (const wxChar
*) *this;
1073 if(!isascii(*s
)) return(FALSE
);
1079 bool wxString::IsWord() const
1081 const wxChar
*s
= (const wxChar
*) *this;
1083 if(!wxIsalpha(*s
)) return(FALSE
);
1089 bool wxString::IsNumber() const
1091 const wxChar
*s
= (const wxChar
*) *this;
1093 if ((s
[0] == '-') || (s
[0] == '+')) s
++;
1095 if(!wxIsdigit(*s
)) return(FALSE
);
1101 wxString
wxString::Strip(stripType w
) const
1104 if ( w
& leading
) s
.Trim(FALSE
);
1105 if ( w
& trailing
) s
.Trim(TRUE
);
1109 // ---------------------------------------------------------------------------
1111 // ---------------------------------------------------------------------------
1113 wxString
& wxString::MakeUpper()
1115 if ( !CopyBeforeWrite() ) {
1116 wxFAIL_MSG( _T("out of memory in wxString::MakeUpper") );
1120 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1121 *p
= (wxChar
)wxToupper(*p
);
1126 wxString
& wxString::MakeLower()
1128 if ( !CopyBeforeWrite() ) {
1129 wxFAIL_MSG( _T("out of memory in wxString::MakeLower") );
1133 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
1134 *p
= (wxChar
)wxTolower(*p
);
1139 // ---------------------------------------------------------------------------
1140 // trimming and padding
1141 // ---------------------------------------------------------------------------
1143 // some compilers (VC++ 6.0 not to name them) return TRUE for a call to
1144 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1145 // live with this by checking that the character is a 7 bit one - even if this
1146 // may fail to detect some spaces (I don't know if Unicode doesn't have
1147 // space-like symbols somewhere except in the first 128 chars), it is arguably
1148 // still better than trimming away accented letters
1149 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1151 // trims spaces (in the sense of isspace) from left or right side
1152 wxString
& wxString::Trim(bool bFromRight
)
1154 // first check if we're going to modify the string at all
1157 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1158 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1162 // ok, there is at least one space to trim
1163 if ( !CopyBeforeWrite() ) {
1164 wxFAIL_MSG( _T("out of memory in wxString::Trim") );
1170 // find last non-space character
1171 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
1172 while ( wxSafeIsspace(*psz
) && (psz
>= m_pchData
) )
1175 // truncate at trailing space start
1177 GetStringData()->nDataLength
= psz
- m_pchData
;
1181 // find first non-space character
1182 const wxChar
*psz
= m_pchData
;
1183 while ( wxSafeIsspace(*psz
) )
1186 // fix up data and length
1187 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
1188 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
1189 GetStringData()->nDataLength
= nDataLength
;
1196 // adds nCount characters chPad to the string from either side
1197 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1199 wxString
s(chPad
, nCount
);
1212 // truncate the string
1213 wxString
& wxString::Truncate(size_t uiLen
)
1215 if ( uiLen
< Len() ) {
1216 if ( !CopyBeforeWrite() ) {
1217 wxFAIL_MSG( _T("out of memory in wxString::Truncate") );
1221 *(m_pchData
+ uiLen
) = wxT('\0');
1222 GetStringData()->nDataLength
= uiLen
;
1224 //else: nothing to do, string is already short enough
1229 // ---------------------------------------------------------------------------
1230 // finding (return wxNOT_FOUND if not found and index otherwise)
1231 // ---------------------------------------------------------------------------
1234 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1236 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
1238 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1241 // find a sub-string (like strstr)
1242 int wxString::Find(const wxChar
*pszSub
) const
1244 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
1246 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1249 // ----------------------------------------------------------------------------
1250 // conversion to numbers
1251 // ----------------------------------------------------------------------------
1253 bool wxString::ToLong(long *val
, int base
) const
1255 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToLong") );
1256 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1258 const wxChar
*start
= c_str();
1260 *val
= wxStrtol(start
, &end
, base
);
1262 // return TRUE only if scan was stopped by the terminating NUL and if the
1263 // string was not empty to start with
1264 return !*end
&& (end
!= start
);
1267 bool wxString::ToULong(unsigned long *val
, int base
) const
1269 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToULong") );
1270 wxASSERT_MSG( !base
|| (base
> 1 && base
<= 36), _T("invalid base") );
1272 const wxChar
*start
= c_str();
1274 *val
= wxStrtoul(start
, &end
, base
);
1276 // return TRUE only if scan was stopped by the terminating NUL and if the
1277 // string was not empty to start with
1278 return !*end
&& (end
!= start
);
1281 bool wxString::ToDouble(double *val
) const
1283 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToDouble") );
1285 const wxChar
*start
= c_str();
1287 *val
= wxStrtod(start
, &end
);
1289 // return TRUE only if scan was stopped by the terminating NUL and if the
1290 // string was not empty to start with
1291 return !*end
&& (end
!= start
);
1294 // ---------------------------------------------------------------------------
1296 // ---------------------------------------------------------------------------
1299 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1302 va_start(argptr
, pszFormat
);
1305 s
.PrintfV(pszFormat
, argptr
);
1313 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1316 s
.PrintfV(pszFormat
, argptr
);
1320 int wxString::Printf(const wxChar
*pszFormat
, ...)
1323 va_start(argptr
, pszFormat
);
1325 int iLen
= PrintfV(pszFormat
, argptr
);
1332 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1334 #if wxUSE_EXPERIMENTAL_PRINTF
1335 // the new implementation
1337 // buffer to avoid dynamic memory allocation each time for small strings
1338 char szScratch
[1024];
1341 for (size_t n
= 0; pszFormat
[n
]; n
++)
1342 if (pszFormat
[n
] == wxT('%')) {
1343 static char s_szFlags
[256] = "%";
1345 bool adj_left
= FALSE
, in_prec
= FALSE
,
1346 prec_dot
= FALSE
, done
= FALSE
;
1348 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1350 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1351 switch (pszFormat
[++n
]) {
1365 s_szFlags
[flagofs
++] = pszFormat
[n
];
1370 s_szFlags
[flagofs
++] = pszFormat
[n
];
1377 // dot will be auto-added to s_szFlags if non-negative number follows
1382 s_szFlags
[flagofs
++] = pszFormat
[n
];
1387 s_szFlags
[flagofs
++] = pszFormat
[n
];
1393 s_szFlags
[flagofs
++] = pszFormat
[n
];
1398 s_szFlags
[flagofs
++] = pszFormat
[n
];
1402 int len
= va_arg(argptr
, int);
1409 adj_left
= !adj_left
;
1410 s_szFlags
[flagofs
++] = '-';
1415 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1418 case wxT('1'): case wxT('2'): case wxT('3'):
1419 case wxT('4'): case wxT('5'): case wxT('6'):
1420 case wxT('7'): case wxT('8'): case wxT('9'):
1424 while ((pszFormat
[n
]>=wxT('0')) && (pszFormat
[n
]<=wxT('9'))) {
1425 s_szFlags
[flagofs
++] = pszFormat
[n
];
1426 len
= len
*10 + (pszFormat
[n
] - wxT('0'));
1429 if (in_prec
) max_width
= len
;
1430 else min_width
= len
;
1431 n
--; // the main loop pre-increments n again
1441 s_szFlags
[flagofs
++] = pszFormat
[n
];
1442 s_szFlags
[flagofs
] = '\0';
1444 int val
= va_arg(argptr
, int);
1445 ::sprintf(szScratch
, s_szFlags
, val
);
1447 else if (ilen
== -1) {
1448 short int val
= va_arg(argptr
, short int);
1449 ::sprintf(szScratch
, s_szFlags
, val
);
1451 else if (ilen
== 1) {
1452 long int val
= va_arg(argptr
, long int);
1453 ::sprintf(szScratch
, s_szFlags
, val
);
1455 else if (ilen
== 2) {
1456 #if SIZEOF_LONG_LONG
1457 long long int val
= va_arg(argptr
, long long int);
1458 ::sprintf(szScratch
, s_szFlags
, val
);
1460 long int val
= va_arg(argptr
, long int);
1461 ::sprintf(szScratch
, s_szFlags
, val
);
1464 else if (ilen
== 3) {
1465 size_t val
= va_arg(argptr
, size_t);
1466 ::sprintf(szScratch
, s_szFlags
, val
);
1468 *this += wxString(szScratch
);
1477 s_szFlags
[flagofs
++] = pszFormat
[n
];
1478 s_szFlags
[flagofs
] = '\0';
1480 long double val
= va_arg(argptr
, long double);
1481 ::sprintf(szScratch
, s_szFlags
, val
);
1483 double val
= va_arg(argptr
, double);
1484 ::sprintf(szScratch
, s_szFlags
, val
);
1486 *this += wxString(szScratch
);
1491 void *val
= va_arg(argptr
, void *);
1493 s_szFlags
[flagofs
++] = pszFormat
[n
];
1494 s_szFlags
[flagofs
] = '\0';
1495 ::sprintf(szScratch
, s_szFlags
, val
);
1496 *this += wxString(szScratch
);
1502 wxChar val
= va_arg(argptr
, int);
1503 // we don't need to honor padding here, do we?
1510 // wx extension: we'll let %hs mean non-Unicode strings
1511 char *val
= va_arg(argptr
, char *);
1513 // ASCII->Unicode constructor handles max_width right
1514 wxString
s(val
, wxConvLibc
, max_width
);
1516 size_t len
= wxSTRING_MAXLEN
;
1518 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1519 } else val
= wxT("(null)");
1520 wxString
s(val
, len
);
1522 if (s
.Len() < min_width
)
1523 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1526 wxChar
*val
= va_arg(argptr
, wxChar
*);
1527 size_t len
= wxSTRING_MAXLEN
;
1529 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1530 } else val
= wxT("(null)");
1531 wxString
s(val
, len
);
1532 if (s
.Len() < min_width
)
1533 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1540 int *val
= va_arg(argptr
, int *);
1543 else if (ilen
== -1) {
1544 short int *val
= va_arg(argptr
, short int *);
1547 else if (ilen
>= 1) {
1548 long int *val
= va_arg(argptr
, long int *);
1554 if (wxIsalpha(pszFormat
[n
]))
1555 // probably some flag not taken care of here yet
1556 s_szFlags
[flagofs
++] = pszFormat
[n
];
1559 *this += wxT('%'); // just to pass the glibc tst-printf.c
1567 } else *this += pszFormat
[n
];
1570 // buffer to avoid dynamic memory allocation each time for small strings
1571 char szScratch
[1024];
1573 // NB: wxVsnprintf() may return either less than the buffer size or -1 if
1574 // there is not enough place depending on implementation
1575 int iLen
= wxVsnprintfA(szScratch
, WXSIZEOF(szScratch
), (char *)pszFormat
, argptr
);
1577 // the whole string is in szScratch
1581 bool outOfMemory
= FALSE
;
1582 int size
= 2*WXSIZEOF(szScratch
);
1583 while ( !outOfMemory
) {
1584 char *buf
= GetWriteBuf(size
);
1586 iLen
= wxVsnprintfA(buf
, size
, pszFormat
, argptr
);
1593 // ok, there was enough space
1597 // still not enough, double it again
1601 if ( outOfMemory
) {
1606 #endif // wxUSE_EXPERIMENTAL_PRINTF/!wxUSE_EXPERIMENTAL_PRINTF
1611 // ----------------------------------------------------------------------------
1612 // misc other operations
1613 // ----------------------------------------------------------------------------
1615 // returns TRUE if the string matches the pattern which may contain '*' and
1616 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1618 bool wxString::Matches(const wxChar
*pszMask
) const
1620 // I disable this code as it doesn't seem to be faster (in fact, it seems
1621 // to be much slower) than the old, hand-written code below and using it
1622 // here requires always linking with libregex even if the user code doesn't
1624 #if 0 // wxUSE_REGEX
1625 // first translate the shell-like mask into a regex
1627 pattern
.reserve(wxStrlen(pszMask
));
1639 pattern
+= _T(".*");
1650 // these characters are special in a RE, quote them
1651 // (however note that we don't quote '[' and ']' to allow
1652 // using them for Unix shell like matching)
1653 pattern
+= _T('\\');
1657 pattern
+= *pszMask
;
1665 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1666 #else // !wxUSE_REGEX
1667 // TODO: this is, of course, awfully inefficient...
1669 // the char currently being checked
1670 const wxChar
*pszTxt
= c_str();
1672 // the last location where '*' matched
1673 const wxChar
*pszLastStarInText
= NULL
;
1674 const wxChar
*pszLastStarInMask
= NULL
;
1677 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1678 switch ( *pszMask
) {
1680 if ( *pszTxt
== wxT('\0') )
1683 // pszTxt and pszMask will be incremented in the loop statement
1689 // remember where we started to be able to backtrack later
1690 pszLastStarInText
= pszTxt
;
1691 pszLastStarInMask
= pszMask
;
1693 // ignore special chars immediately following this one
1694 // (should this be an error?)
1695 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1698 // if there is nothing more, match
1699 if ( *pszMask
== wxT('\0') )
1702 // are there any other metacharacters in the mask?
1704 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1706 if ( pEndMask
!= NULL
) {
1707 // we have to match the string between two metachars
1708 uiLenMask
= pEndMask
- pszMask
;
1711 // we have to match the remainder of the string
1712 uiLenMask
= wxStrlen(pszMask
);
1715 wxString
strToMatch(pszMask
, uiLenMask
);
1716 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1717 if ( pMatch
== NULL
)
1720 // -1 to compensate "++" in the loop
1721 pszTxt
= pMatch
+ uiLenMask
- 1;
1722 pszMask
+= uiLenMask
- 1;
1727 if ( *pszMask
!= *pszTxt
)
1733 // match only if nothing left
1734 if ( *pszTxt
== wxT('\0') )
1737 // if we failed to match, backtrack if we can
1738 if ( pszLastStarInText
) {
1739 pszTxt
= pszLastStarInText
+ 1;
1740 pszMask
= pszLastStarInMask
;
1742 pszLastStarInText
= NULL
;
1744 // don't bother resetting pszLastStarInMask, it's unnecessary
1750 #endif // wxUSE_REGEX/!wxUSE_REGEX
1753 // Count the number of chars
1754 int wxString::Freq(wxChar ch
) const
1758 for (int i
= 0; i
< len
; i
++)
1760 if (GetChar(i
) == ch
)
1766 // convert to upper case, return the copy of the string
1767 wxString
wxString::Upper() const
1768 { wxString
s(*this); return s
.MakeUpper(); }
1770 // convert to lower case, return the copy of the string
1771 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1773 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1776 va_start(argptr
, pszFormat
);
1777 int iLen
= PrintfV(pszFormat
, argptr
);
1782 // ---------------------------------------------------------------------------
1783 // standard C++ library string functions
1784 // ---------------------------------------------------------------------------
1786 #ifdef wxSTD_STRING_COMPATIBILITY
1788 void wxString::resize(size_t nSize
, wxChar ch
)
1790 size_t len
= length();
1796 else if ( nSize
> len
)
1798 *this += wxString(ch
, nSize
- len
);
1800 //else: we have exactly the specified length, nothing to do
1803 void wxString::swap(wxString
& str
)
1805 // this is slightly less efficient than fiddling with m_pchData directly,
1806 // but it is still quite efficient as we don't copy the string here because
1807 // ref count always stays positive
1813 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1815 wxASSERT( str
.GetStringData()->IsValid() );
1816 wxASSERT( nPos
<= Len() );
1818 if ( !str
.IsEmpty() ) {
1820 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1821 wxStrncpy(pc
, c_str(), nPos
);
1822 wxStrcpy(pc
+ nPos
, str
);
1823 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1824 strTmp
.UngetWriteBuf();
1831 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1833 wxASSERT( str
.GetStringData()->IsValid() );
1834 wxASSERT( nStart
<= Len() );
1836 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1838 return p
== NULL
? npos
: p
- c_str();
1841 // VC++ 1.5 can't cope with the default argument in the header.
1842 #if !defined(__VISUALC__) || defined(__WIN32__)
1843 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1845 return find(wxString(sz
, n
), nStart
);
1849 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1850 #if !defined(__BORLANDC__)
1851 size_t wxString::find(wxChar ch
, size_t nStart
) const
1853 wxASSERT( nStart
<= Len() );
1855 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1857 return p
== NULL
? npos
: p
- c_str();
1861 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1863 wxASSERT( str
.GetStringData()->IsValid() );
1864 wxASSERT( nStart
== npos
|| nStart
<= Len() );
1866 // TODO could be made much quicker than that
1867 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1868 while ( p
>= c_str() + str
.Len() ) {
1869 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1870 return p
- str
.Len() - c_str();
1877 // VC++ 1.5 can't cope with the default argument in the header.
1878 #if !defined(__VISUALC__) || defined(__WIN32__)
1879 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1881 return rfind(wxString(sz
, n
== npos
? wxSTRING_MAXLEN
: n
), nStart
);
1884 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1886 if ( nStart
== npos
)
1892 wxASSERT( nStart
<= Len() );
1895 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1900 size_t result
= p
- c_str();
1901 return ( result
> nStart
) ? npos
: result
;
1905 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1907 const wxChar
*start
= c_str() + nStart
;
1908 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1910 return firstOf
- c_str();
1915 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1917 if ( nStart
== npos
)
1923 wxASSERT( nStart
<= Len() );
1926 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1928 if ( wxStrchr(sz
, *p
) )
1935 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1937 if ( nStart
== npos
)
1943 wxASSERT( nStart
<= Len() );
1946 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1947 if ( nAccept
>= length() - nStart
)
1953 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1955 wxASSERT( nStart
<= Len() );
1957 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1966 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1968 if ( nStart
== npos
)
1974 wxASSERT( nStart
<= Len() );
1977 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1979 if ( !wxStrchr(sz
, *p
) )
1986 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1988 if ( nStart
== npos
)
1994 wxASSERT( nStart
<= Len() );
1997 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
2006 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
2008 wxString
strTmp(c_str(), nStart
);
2009 if ( nLen
!= npos
) {
2010 wxASSERT( nStart
+ nLen
<= Len() );
2012 strTmp
.append(c_str() + nStart
+ nLen
);
2019 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
2021 wxASSERT_MSG( nStart
+ nLen
<= Len(),
2022 _T("index out of bounds in wxString::replace") );
2025 strTmp
.Alloc(Len()); // micro optimisation to avoid multiple mem allocs
2028 strTmp
.append(c_str(), nStart
);
2029 strTmp
<< sz
<< c_str() + nStart
+ nLen
;
2035 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
2037 return replace(nStart
, nLen
, wxString(ch
, nCount
));
2040 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
2041 const wxString
& str
, size_t nStart2
, size_t nLen2
)
2043 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
2046 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
2047 const wxChar
* sz
, size_t nCount
)
2049 return replace(nStart
, nLen
, wxString(sz
, nCount
));
2052 #endif //std::string compatibility
2054 // ============================================================================
2056 // ============================================================================
2058 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
2059 #define ARRAY_MAXSIZE_INCREMENT 4096
2061 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
2062 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
2065 #define STRING(p) ((wxString *)(&(p)))
2068 void wxArrayString::Init(bool autoSort
)
2072 m_pItems
= (wxChar
**) NULL
;
2073 m_autoSort
= autoSort
;
2077 wxArrayString::wxArrayString(const wxArrayString
& src
)
2079 Init(src
.m_autoSort
);
2084 // assignment operator
2085 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
2092 m_autoSort
= src
.m_autoSort
;
2097 void wxArrayString::Copy(const wxArrayString
& src
)
2099 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
2100 Alloc(src
.m_nCount
);
2102 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
2107 void wxArrayString::Grow(size_t nIncrement
)
2109 // only do it if no more place
2110 if ( m_nCount
== m_nSize
) {
2111 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
2112 // be never resized!
2113 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
2114 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
2117 if ( m_nSize
== 0 ) {
2118 // was empty, alloc some memory
2119 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
2120 m_pItems
= new wxChar
*[m_nSize
];
2123 // otherwise when it's called for the first time, nIncrement would be 0
2124 // and the array would never be expanded
2125 // add 50% but not too much
2126 size_t ndefIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
2127 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
2128 if ( ndefIncrement
> ARRAY_MAXSIZE_INCREMENT
)
2129 ndefIncrement
= ARRAY_MAXSIZE_INCREMENT
;
2130 if ( nIncrement
< ndefIncrement
)
2131 nIncrement
= ndefIncrement
;
2132 m_nSize
+= nIncrement
;
2133 wxChar
**pNew
= new wxChar
*[m_nSize
];
2135 // copy data to new location
2136 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2138 // delete old memory (but do not release the strings!)
2139 wxDELETEA(m_pItems
);
2146 void wxArrayString::Free()
2148 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
2149 STRING(m_pItems
[n
])->GetStringData()->Unlock();
2153 // deletes all the strings from the list
2154 void wxArrayString::Empty()
2161 // as Empty, but also frees memory
2162 void wxArrayString::Clear()
2169 wxDELETEA(m_pItems
);
2173 wxArrayString::~wxArrayString()
2177 wxDELETEA(m_pItems
);
2180 // pre-allocates memory (frees the previous data!)
2181 void wxArrayString::Alloc(size_t nSize
)
2183 // only if old buffer was not big enough
2184 if ( nSize
> m_nSize
) {
2186 wxDELETEA(m_pItems
);
2187 m_pItems
= new wxChar
*[nSize
];
2194 // minimizes the memory usage by freeing unused memory
2195 void wxArrayString::Shrink()
2197 // only do it if we have some memory to free
2198 if( m_nCount
< m_nSize
) {
2199 // allocates exactly as much memory as we need
2200 wxChar
**pNew
= new wxChar
*[m_nCount
];
2202 // copy data to new location
2203 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2209 // return a wxString[] as required for some control ctors.
2210 wxString
* wxArrayString::GetStringArray() const
2212 wxString
*array
= 0;
2216 array
= new wxString
[m_nCount
];
2217 for( size_t i
= 0; i
< m_nCount
; i
++ )
2218 array
[i
] = m_pItems
[i
];
2224 // searches the array for an item (forward or backwards)
2225 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2228 // use binary search in the sorted array
2229 wxASSERT_MSG( bCase
&& !bFromEnd
,
2230 wxT("search parameters ignored for auto sorted array") );
2239 res
= wxStrcmp(sz
, m_pItems
[i
]);
2251 // use linear search in unsorted array
2253 if ( m_nCount
> 0 ) {
2254 size_t ui
= m_nCount
;
2256 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2263 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2264 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2273 // add item at the end
2274 size_t wxArrayString::Add(const wxString
& str
, size_t nInsert
)
2277 // insert the string at the correct position to keep the array sorted
2285 res
= wxStrcmp(str
, m_pItems
[i
]);
2296 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2298 Insert(str
, lo
, nInsert
);
2303 wxASSERT( str
.GetStringData()->IsValid() );
2307 for (size_t i
= 0; i
< nInsert
; i
++)
2309 // the string data must not be deleted!
2310 str
.GetStringData()->Lock();
2313 m_pItems
[m_nCount
+ i
] = (wxChar
*)str
.c_str(); // const_cast
2315 size_t ret
= m_nCount
;
2316 m_nCount
+= nInsert
;
2321 // add item at the given position
2322 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
, size_t nInsert
)
2324 wxASSERT( str
.GetStringData()->IsValid() );
2326 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2327 wxCHECK_RET( m_nCount
<= m_nCount
+ nInsert
,
2328 wxT("array size overflow in wxArrayString::Insert") );
2332 memmove(&m_pItems
[nIndex
+ nInsert
], &m_pItems
[nIndex
],
2333 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2335 for (size_t i
= 0; i
< nInsert
; i
++)
2337 str
.GetStringData()->Lock();
2338 m_pItems
[nIndex
+ i
] = (wxChar
*)str
.c_str();
2340 m_nCount
+= nInsert
;
2344 void wxArrayString::SetCount(size_t count
)
2349 while ( m_nCount
< count
)
2350 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2353 // removes item from array (by index)
2354 void wxArrayString::Remove(size_t nIndex
, size_t nRemove
)
2356 wxCHECK_RET( nIndex
< m_nCount
, wxT("bad index in wxArrayString::Remove") );
2357 wxCHECK_RET( nIndex
+ nRemove
<= m_nCount
,
2358 wxT("removing too many elements in wxArrayString::Remove") );
2361 for (size_t i
= 0; i
< nRemove
; i
++)
2362 Item(nIndex
+ i
).GetStringData()->Unlock();
2364 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ nRemove
],
2365 (m_nCount
- nIndex
- nRemove
)*sizeof(wxChar
*));
2366 m_nCount
-= nRemove
;
2369 // removes item from array (by value)
2370 void wxArrayString::Remove(const wxChar
*sz
)
2372 int iIndex
= Index(sz
);
2374 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2375 wxT("removing inexistent element in wxArrayString::Remove") );
2380 // ----------------------------------------------------------------------------
2382 // ----------------------------------------------------------------------------
2384 // we can only sort one array at a time with the quick-sort based
2387 // need a critical section to protect access to gs_compareFunction and
2388 // gs_sortAscending variables
2389 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2391 // call this before the value of the global sort vars is changed/after
2392 // you're finished with them
2393 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2394 gs_critsectStringSort = new wxCriticalSection; \
2395 gs_critsectStringSort->Enter()
2396 #define END_SORT() gs_critsectStringSort->Leave(); \
2397 delete gs_critsectStringSort; \
2398 gs_critsectStringSort = NULL
2400 #define START_SORT()
2402 #endif // wxUSE_THREADS
2404 // function to use for string comparaison
2405 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2407 // if we don't use the compare function, this flag tells us if we sort the
2408 // array in ascending or descending order
2409 static bool gs_sortAscending
= TRUE
;
2411 // function which is called by quick sort
2412 extern "C" int LINKAGEMODE
2413 wxStringCompareFunction(const void *first
, const void *second
)
2415 wxString
*strFirst
= (wxString
*)first
;
2416 wxString
*strSecond
= (wxString
*)second
;
2418 if ( gs_compareFunction
) {
2419 return gs_compareFunction(*strFirst
, *strSecond
);
2422 // maybe we should use wxStrcoll
2423 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
2425 return gs_sortAscending
? result
: -result
;
2429 // sort array elements using passed comparaison function
2430 void wxArrayString::Sort(CompareFunction compareFunction
)
2434 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2435 gs_compareFunction
= compareFunction
;
2439 // reset it to NULL so that Sort(bool) will work the next time
2440 gs_compareFunction
= NULL
;
2445 void wxArrayString::Sort(bool reverseOrder
)
2449 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2450 gs_sortAscending
= !reverseOrder
;
2457 void wxArrayString::DoSort()
2459 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2461 // just sort the pointers using qsort() - of course it only works because
2462 // wxString() *is* a pointer to its data
2463 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2466 bool wxArrayString::operator==(const wxArrayString
& a
) const
2468 if ( m_nCount
!= a
.m_nCount
)
2471 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2473 if ( Item(n
) != a
[n
] )