1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxString class
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "string.h"
18 * 1) all empty strings use g_strEmpty, nRefs = -1 (set in Init())
19 * 2) AllocBuffer() sets nRefs to 1, Lock() increments it by one
20 * 3) Unlock() decrements nRefs and frees memory if it goes to 0
23 // ===========================================================================
24 // headers, declarations, constants
25 // ===========================================================================
27 // For compilers that support precompilation, includes "wx.h".
28 #include "wx/wxprec.h"
36 #include "wx/string.h"
38 #include "wx/thread.h"
50 #undef wxUSE_EXPERIMENTAL_PRINTF
51 #define wxUSE_EXPERIMENTAL_PRINTF 1
54 // allocating extra space for each string consumes more memory but speeds up
55 // the concatenation operations (nLen is the current string's length)
56 // NB: EXTRA_ALLOC must be >= 0!
57 #define EXTRA_ALLOC (19 - nLen % 16)
59 // ---------------------------------------------------------------------------
60 // static class variables definition
61 // ---------------------------------------------------------------------------
63 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
64 // must define this static for VA or else you get multiply defined symbols
66 const unsigned int wxSTRING_MAXLEN
= UINT_MAX
- 100;
69 #ifdef wxSTD_STRING_COMPATIBILITY
70 const size_t wxString::npos
= wxSTRING_MAXLEN
;
71 #endif // wxSTD_STRING_COMPATIBILITY
73 // ----------------------------------------------------------------------------
75 // ----------------------------------------------------------------------------
77 // for an empty string, GetStringData() will return this address: this
78 // structure has the same layout as wxStringData and it's data() method will
79 // return the empty string (dummy pointer)
84 } g_strEmpty
= { {-1, 0, 0}, wxT('\0') };
86 // empty C style string: points to 'string data' byte of g_strEmpty
87 extern const wxChar WXDLLEXPORT
*wxEmptyString
= &g_strEmpty
.dummy
;
89 // ----------------------------------------------------------------------------
90 // conditional compilation
91 // ----------------------------------------------------------------------------
93 #if !defined(__WXSW__) && wxUSE_UNICODE
94 #ifdef wxUSE_EXPERIMENTAL_PRINTF
95 #undef wxUSE_EXPERIMENTAL_PRINTF
97 #define wxUSE_EXPERIMENTAL_PRINTF 1
100 // we want to find out if the current platform supports vsnprintf()-like
101 // function: for Unix this is done with configure, for Windows we test the
102 // compiler explicitly.
104 // FIXME currently, this is only for ANSI (!Unicode) strings, so we call this
105 // function wxVsnprintfA (A for ANSI), should also find one for Unicode
106 // strings in Unicode build
108 #if defined(__VISUALC__) || (defined(__MINGW32__) && wxUSE_NORLANDER_HEADERS)
109 #define wxVsnprintfA _vsnprintf
111 #elif defined(__WXMAC__)
112 #define wxVsnprintfA vsnprintf
114 #ifdef HAVE_VSNPRINTF
115 #define wxVsnprintfA vsnprintf
117 #endif // Windows/!Windows
120 // in this case we'll use vsprintf() (which is ANSI and thus should be
121 // always available), but it's unsafe because it doesn't check for buffer
122 // size - so give a warning
123 #define wxVsnprintfA(buf, len, format, arg) vsprintf(buf, format, arg)
125 #if defined(__VISUALC__)
126 #pragma message("Using sprintf() because no snprintf()-like function defined")
127 #elif defined(__GNUG__)
128 #warning "Using sprintf() because no snprintf()-like function defined"
130 #endif // no vsnprintf
133 // AIX has vsnprintf, but there's no prototype in the system headers.
134 extern "C" int vsnprintf(char* str
, size_t n
, const char* format
, va_list ap
);
137 // ----------------------------------------------------------------------------
139 // ----------------------------------------------------------------------------
141 #if defined(wxSTD_STRING_COMPATIBILITY) && wxUSE_STD_IOSTREAM
143 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
146 // ATTN: you can _not_ use both of these in the same program!
148 wxSTD istream
& operator>>(wxSTD istream
& is
, wxString
& WXUNUSED(str
))
153 streambuf
*sb
= is
.rdbuf();
156 int ch
= sb
->sbumpc ();
158 is
.setstate(ios::eofbit
);
161 else if ( isspace(ch
) ) {
173 if ( str
.length() == 0 )
174 is
.setstate(ios::failbit
);
179 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
185 #endif //std::string compatibility
187 extern int WXDLLEXPORT
wxVsnprintf(wxChar
*buf
, size_t len
,
188 const wxChar
*format
, va_list argptr
)
191 // FIXME should use wvsnprintf() or whatever if it's available
193 int iLen
= s
.PrintfV(format
, argptr
);
196 wxStrncpy(buf
, s
.c_str(), len
);
197 buf
[len
-1] = wxT('\0');
202 // vsnprintf() will not terminate the string with '\0' if there is not
203 // enough place, but we want the string to always be NUL terminated
204 int rc
= wxVsnprintfA(buf
, len
- 1, format
, argptr
);
211 #endif // Unicode/ANSI
214 extern int WXDLLEXPORT
wxSnprintf(wxChar
*buf
, size_t len
,
215 const wxChar
*format
, ...)
218 va_start(argptr
, format
);
220 int iLen
= wxVsnprintf(buf
, len
, format
, argptr
);
227 // ----------------------------------------------------------------------------
229 // ----------------------------------------------------------------------------
231 // this small class is used to gather statistics for performance tuning
232 //#define WXSTRING_STATISTICS
233 #ifdef WXSTRING_STATISTICS
237 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
239 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
241 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
244 size_t m_nCount
, m_nTotal
;
246 } g_averageLength("allocation size"),
247 g_averageSummandLength("summand length"),
248 g_averageConcatHit("hit probability in concat"),
249 g_averageInitialLength("initial string length");
251 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
253 #define STATISTICS_ADD(av, val)
254 #endif // WXSTRING_STATISTICS
256 // ===========================================================================
257 // wxString class core
258 // ===========================================================================
260 // ---------------------------------------------------------------------------
262 // ---------------------------------------------------------------------------
264 // constructs string of <nLength> copies of character <ch>
265 wxString::wxString(wxChar ch
, size_t nLength
)
270 AllocBuffer(nLength
);
273 // memset only works on char
274 for (size_t n
=0; n
<nLength
; n
++) m_pchData
[n
] = ch
;
276 memset(m_pchData
, ch
, nLength
);
281 // takes nLength elements of psz starting at nPos
282 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
286 // if the length is not given, assume the string to be NUL terminated
287 if ( nLength
== wxSTRING_MAXLEN
) {
288 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
290 nLength
= wxStrlen(psz
+ nPos
);
293 STATISTICS_ADD(InitialLength
, nLength
);
296 // trailing '\0' is written in AllocBuffer()
297 AllocBuffer(nLength
);
298 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
302 #ifdef wxSTD_STRING_COMPATIBILITY
304 // poor man's iterators are "void *" pointers
305 wxString::wxString(const void *pStart
, const void *pEnd
)
307 InitWith((const wxChar
*)pStart
, 0,
308 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
311 #endif //std::string compatibility
315 // from multibyte string
316 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
318 // first get necessary size
319 size_t nLen
= psz
? conv
.MB2WC((wchar_t *) NULL
, psz
, 0) : 0;
321 // nLength is number of *Unicode* characters here!
322 if ((nLen
!= (size_t)-1) && (nLen
> nLength
))
326 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
328 conv
.MB2WC(m_pchData
, psz
, nLen
);
339 wxString::wxString(const wchar_t *pwz
, wxMBConv
& conv
, size_t nLength
)
341 // first get necessary size
345 if (nLength
== wxSTRING_MAXLEN
)
346 nLen
= conv
.WC2MB((char *) NULL
, pwz
, 0);
352 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
354 conv
.WC2MB(m_pchData
, pwz
, nLen
);
360 #endif // wxUSE_WCHAR_T
362 #endif // Unicode/ANSI
364 // ---------------------------------------------------------------------------
366 // ---------------------------------------------------------------------------
368 // allocates memory needed to store a C string of length nLen
369 void wxString::AllocBuffer(size_t nLen
)
371 // allocating 0 sized buffer doesn't make sense, all empty strings should
373 wxASSERT( nLen
> 0 );
375 // make sure that we don't overflow
376 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
377 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
379 STATISTICS_ADD(Length
, nLen
);
382 // 1) one extra character for '\0' termination
383 // 2) sizeof(wxStringData) for housekeeping info
384 wxStringData
* pData
= (wxStringData
*)
385 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
387 pData
->nDataLength
= nLen
;
388 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
389 m_pchData
= pData
->data(); // data starts after wxStringData
390 m_pchData
[nLen
] = wxT('\0');
393 // must be called before changing this string
394 void wxString::CopyBeforeWrite()
396 wxStringData
* pData
= GetStringData();
398 if ( pData
->IsShared() ) {
399 pData
->Unlock(); // memory not freed because shared
400 size_t nLen
= pData
->nDataLength
;
402 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
405 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
408 // must be called before replacing contents of this string
409 void wxString::AllocBeforeWrite(size_t nLen
)
411 wxASSERT( nLen
!= 0 ); // doesn't make any sense
413 // must not share string and must have enough space
414 wxStringData
* pData
= GetStringData();
415 if ( pData
->IsShared() || pData
->IsEmpty() ) {
416 // can't work with old buffer, get new one
421 if ( nLen
> pData
->nAllocLength
) {
422 // realloc the buffer instead of calling malloc() again, this is more
424 STATISTICS_ADD(Length
, nLen
);
428 wxStringData
*pDataOld
= pData
;
429 pData
= (wxStringData
*)
430 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
435 // FIXME we're going to crash...
439 pData
->nAllocLength
= nLen
;
440 m_pchData
= pData
->data();
443 // now we have enough space, just update the string length
444 pData
->nDataLength
= nLen
;
447 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
450 // allocate enough memory for nLen characters
451 void wxString::Alloc(size_t nLen
)
453 wxStringData
*pData
= GetStringData();
454 if ( pData
->nAllocLength
<= nLen
) {
455 if ( pData
->IsEmpty() ) {
458 wxStringData
* pData
= (wxStringData
*)
459 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
461 pData
->nDataLength
= 0;
462 pData
->nAllocLength
= nLen
;
463 m_pchData
= pData
->data(); // data starts after wxStringData
464 m_pchData
[0u] = wxT('\0');
466 else if ( pData
->IsShared() ) {
467 pData
->Unlock(); // memory not freed because shared
468 size_t nOldLen
= pData
->nDataLength
;
470 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
475 wxStringData
*pDataOld
= pData
;
476 wxStringData
*p
= (wxStringData
*)
477 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
483 // FIXME what to do on memory error?
487 // it's not important if the pointer changed or not (the check for this
488 // is not faster than assigning to m_pchData in all cases)
489 p
->nAllocLength
= nLen
;
490 m_pchData
= p
->data();
493 //else: we've already got enough
496 // shrink to minimal size (releasing extra memory)
497 void wxString::Shrink()
499 wxStringData
*pData
= GetStringData();
501 size_t nLen
= pData
->nDataLength
;
502 void *p
= realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
504 wxASSERT_MSG( p
!= NULL
, _T("can't free memory?") );
508 // contrary to what one might believe, some realloc() implementation do
509 // move the memory block even when its size is reduced
510 pData
= (wxStringData
*)p
;
512 m_pchData
= pData
->data();
515 pData
->nAllocLength
= nLen
;
518 // get the pointer to writable buffer of (at least) nLen bytes
519 wxChar
*wxString::GetWriteBuf(size_t nLen
)
521 AllocBeforeWrite(nLen
);
523 wxASSERT( GetStringData()->nRefs
== 1 );
524 GetStringData()->Validate(FALSE
);
529 // put string back in a reasonable state after GetWriteBuf
530 void wxString::UngetWriteBuf()
532 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
533 GetStringData()->Validate(TRUE
);
536 void wxString::UngetWriteBuf(size_t nLen
)
538 GetStringData()->nDataLength
= nLen
;
539 GetStringData()->Validate(TRUE
);
542 // ---------------------------------------------------------------------------
544 // ---------------------------------------------------------------------------
546 // all functions are inline in string.h
548 // ---------------------------------------------------------------------------
549 // assignment operators
550 // ---------------------------------------------------------------------------
552 // helper function: does real copy
553 void wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
555 if ( nSrcLen
== 0 ) {
559 AllocBeforeWrite(nSrcLen
);
560 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
561 GetStringData()->nDataLength
= nSrcLen
;
562 m_pchData
[nSrcLen
] = wxT('\0');
566 // assigns one string to another
567 wxString
& wxString::operator=(const wxString
& stringSrc
)
569 wxASSERT( stringSrc
.GetStringData()->IsValid() );
571 // don't copy string over itself
572 if ( m_pchData
!= stringSrc
.m_pchData
) {
573 if ( stringSrc
.GetStringData()->IsEmpty() ) {
578 GetStringData()->Unlock();
579 m_pchData
= stringSrc
.m_pchData
;
580 GetStringData()->Lock();
587 // assigns a single character
588 wxString
& wxString::operator=(wxChar ch
)
596 wxString
& wxString::operator=(const wxChar
*psz
)
598 AssignCopy(wxStrlen(psz
), psz
);
604 // same as 'signed char' variant
605 wxString
& wxString::operator=(const unsigned char* psz
)
607 *this = (const char *)psz
;
612 wxString
& wxString::operator=(const wchar_t *pwz
)
622 // ---------------------------------------------------------------------------
623 // string concatenation
624 // ---------------------------------------------------------------------------
626 // add something to this string
627 void wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
629 STATISTICS_ADD(SummandLength
, nSrcLen
);
631 // concatenating an empty string is a NOP
633 wxStringData
*pData
= GetStringData();
634 size_t nLen
= pData
->nDataLength
;
635 size_t nNewLen
= nLen
+ nSrcLen
;
637 // alloc new buffer if current is too small
638 if ( pData
->IsShared() ) {
639 STATISTICS_ADD(ConcatHit
, 0);
641 // we have to allocate another buffer
642 wxStringData
* pOldData
= GetStringData();
643 AllocBuffer(nNewLen
);
644 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
647 else if ( nNewLen
> pData
->nAllocLength
) {
648 STATISTICS_ADD(ConcatHit
, 0);
650 // we have to grow the buffer
654 STATISTICS_ADD(ConcatHit
, 1);
656 // the buffer is already big enough
659 // should be enough space
660 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
662 // fast concatenation - all is done in our buffer
663 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
665 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
666 GetStringData()->nDataLength
= nNewLen
; // and fix the length
668 //else: the string to append was empty
672 * concatenation functions come in 5 flavours:
674 * char + string and string + char
675 * C str + string and string + C str
678 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
680 wxASSERT( string1
.GetStringData()->IsValid() );
681 wxASSERT( string2
.GetStringData()->IsValid() );
683 wxString s
= string1
;
689 wxString
operator+(const wxString
& string
, wxChar ch
)
691 wxASSERT( string
.GetStringData()->IsValid() );
699 wxString
operator+(wxChar ch
, const wxString
& string
)
701 wxASSERT( string
.GetStringData()->IsValid() );
709 wxString
operator+(const wxString
& string
, const wxChar
*psz
)
711 wxASSERT( string
.GetStringData()->IsValid() );
714 s
.Alloc(wxStrlen(psz
) + string
.Len());
721 wxString
operator+(const wxChar
*psz
, const wxString
& string
)
723 wxASSERT( string
.GetStringData()->IsValid() );
726 s
.Alloc(wxStrlen(psz
) + string
.Len());
733 // ===========================================================================
734 // other common string functions
735 // ===========================================================================
737 // ---------------------------------------------------------------------------
738 // simple sub-string extraction
739 // ---------------------------------------------------------------------------
741 // helper function: clone the data attached to this string
742 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
744 if ( nCopyLen
== 0 ) {
748 dest
.AllocBuffer(nCopyLen
);
749 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
753 // extract string of length nCount starting at nFirst
754 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
756 wxStringData
*pData
= GetStringData();
757 size_t nLen
= pData
->nDataLength
;
759 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
760 if ( nCount
== wxSTRING_MAXLEN
)
762 nCount
= nLen
- nFirst
;
765 // out-of-bounds requests return sensible things
766 if ( nFirst
+ nCount
> nLen
)
768 nCount
= nLen
- nFirst
;
773 // AllocCopy() will return empty string
778 AllocCopy(dest
, nCount
, nFirst
);
783 // check that the tring starts with prefix and return the rest of the string
784 // in the provided pointer if it is not NULL, otherwise return FALSE
785 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
787 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
789 // first check if the beginning of the string matches the prefix: note
790 // that we don't have to check that we don't run out of this string as
791 // when we reach the terminating NUL, either prefix string ends too (and
792 // then it's ok) or we break out of the loop because there is no match
793 const wxChar
*p
= c_str();
796 if ( *prefix
++ != *p
++ )
805 // put the rest of the string into provided pointer
812 // extract nCount last (rightmost) characters
813 wxString
wxString::Right(size_t nCount
) const
815 if ( nCount
> (size_t)GetStringData()->nDataLength
)
816 nCount
= GetStringData()->nDataLength
;
819 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
823 // get all characters after the last occurence of ch
824 // (returns the whole string if ch not found)
825 wxString
wxString::AfterLast(wxChar ch
) const
828 int iPos
= Find(ch
, TRUE
);
829 if ( iPos
== wxNOT_FOUND
)
832 str
= c_str() + iPos
+ 1;
837 // extract nCount first (leftmost) characters
838 wxString
wxString::Left(size_t nCount
) const
840 if ( nCount
> (size_t)GetStringData()->nDataLength
)
841 nCount
= GetStringData()->nDataLength
;
844 AllocCopy(dest
, nCount
, 0);
848 // get all characters before the first occurence of ch
849 // (returns the whole string if ch not found)
850 wxString
wxString::BeforeFirst(wxChar ch
) const
853 for ( const wxChar
*pc
= m_pchData
; *pc
!= wxT('\0') && *pc
!= ch
; pc
++ )
859 /// get all characters before the last occurence of ch
860 /// (returns empty string if ch not found)
861 wxString
wxString::BeforeLast(wxChar ch
) const
864 int iPos
= Find(ch
, TRUE
);
865 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
866 str
= wxString(c_str(), iPos
);
871 /// get all characters after the first occurence of ch
872 /// (returns empty string if ch not found)
873 wxString
wxString::AfterFirst(wxChar ch
) const
877 if ( iPos
!= wxNOT_FOUND
)
878 str
= c_str() + iPos
+ 1;
883 // replace first (or all) occurences of some substring with another one
884 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
886 size_t uiCount
= 0; // count of replacements made
888 size_t uiOldLen
= wxStrlen(szOld
);
891 const wxChar
*pCurrent
= m_pchData
;
892 const wxChar
*pSubstr
;
893 while ( *pCurrent
!= wxT('\0') ) {
894 pSubstr
= wxStrstr(pCurrent
, szOld
);
895 if ( pSubstr
== NULL
) {
896 // strTemp is unused if no replacements were made, so avoid the copy
900 strTemp
+= pCurrent
; // copy the rest
901 break; // exit the loop
904 // take chars before match
905 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
907 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
912 if ( !bReplaceAll
) {
913 strTemp
+= pCurrent
; // copy the rest
914 break; // exit the loop
919 // only done if there were replacements, otherwise would have returned above
925 bool wxString::IsAscii() const
927 const wxChar
*s
= (const wxChar
*) *this;
929 if(!isascii(*s
)) return(FALSE
);
935 bool wxString::IsWord() const
937 const wxChar
*s
= (const wxChar
*) *this;
939 if(!wxIsalpha(*s
)) return(FALSE
);
945 bool wxString::IsNumber() const
947 const wxChar
*s
= (const wxChar
*) *this;
949 if ((s
[0] == '-') || (s
[0] == '+')) s
++;
951 if(!wxIsdigit(*s
)) return(FALSE
);
957 wxString
wxString::Strip(stripType w
) const
960 if ( w
& leading
) s
.Trim(FALSE
);
961 if ( w
& trailing
) s
.Trim(TRUE
);
965 // ---------------------------------------------------------------------------
967 // ---------------------------------------------------------------------------
969 wxString
& wxString::MakeUpper()
973 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
974 *p
= (wxChar
)wxToupper(*p
);
979 wxString
& wxString::MakeLower()
983 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
984 *p
= (wxChar
)wxTolower(*p
);
989 // ---------------------------------------------------------------------------
990 // trimming and padding
991 // ---------------------------------------------------------------------------
993 // some compilers (VC++ 6.0 not to name them) return TRUE for a call to
994 // isspace('ê') in the C locale which seems to be broken to me, but we have to
995 // live with this by checking that the character is a 7 bit one - even if this
996 // may fail to detect some spaces (I don't know if Unicode doesn't have
997 // space-like symbols somewhere except in the first 128 chars), it is arguably
998 // still better than trimming away accented letters
999 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1001 // trims spaces (in the sense of isspace) from left or right side
1002 wxString
& wxString::Trim(bool bFromRight
)
1004 // first check if we're going to modify the string at all
1007 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1008 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1012 // ok, there is at least one space to trim
1017 // find last non-space character
1018 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
1019 while ( wxSafeIsspace(*psz
) && (psz
>= m_pchData
) )
1022 // truncate at trailing space start
1024 GetStringData()->nDataLength
= psz
- m_pchData
;
1028 // find first non-space character
1029 const wxChar
*psz
= m_pchData
;
1030 while ( wxSafeIsspace(*psz
) )
1033 // fix up data and length
1034 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
1035 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
1036 GetStringData()->nDataLength
= nDataLength
;
1043 // adds nCount characters chPad to the string from either side
1044 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1046 wxString
s(chPad
, nCount
);
1059 // truncate the string
1060 wxString
& wxString::Truncate(size_t uiLen
)
1062 if ( uiLen
< Len() ) {
1065 *(m_pchData
+ uiLen
) = wxT('\0');
1066 GetStringData()->nDataLength
= uiLen
;
1068 //else: nothing to do, string is already short enough
1073 // ---------------------------------------------------------------------------
1074 // finding (return wxNOT_FOUND if not found and index otherwise)
1075 // ---------------------------------------------------------------------------
1078 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1080 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
1082 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1085 // find a sub-string (like strstr)
1086 int wxString::Find(const wxChar
*pszSub
) const
1088 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
1090 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1093 // ----------------------------------------------------------------------------
1094 // conversion to numbers
1095 // ----------------------------------------------------------------------------
1097 bool wxString::ToLong(long *val
, int base
) const
1099 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToLong") );
1101 const wxChar
*start
= c_str();
1103 *val
= wxStrtol(start
, &end
, base
);
1105 // return TRUE only if scan was stopped by the terminating NUL and if the
1106 // string was not empty to start with
1107 return !*end
&& (end
!= start
);
1110 bool wxString::ToULong(unsigned long *val
, int base
) const
1112 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToULong") );
1114 const wxChar
*start
= c_str();
1116 *val
= wxStrtoul(start
, &end
, base
);
1118 // return TRUE only if scan was stopped by the terminating NUL and if the
1119 // string was not empty to start with
1120 return !*end
&& (end
!= start
);
1123 bool wxString::ToDouble(double *val
) const
1125 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToDouble") );
1127 const wxChar
*start
= c_str();
1129 *val
= wxStrtod(start
, &end
);
1131 // return TRUE only if scan was stopped by the terminating NUL and if the
1132 // string was not empty to start with
1133 return !*end
&& (end
!= start
);
1136 // ---------------------------------------------------------------------------
1138 // ---------------------------------------------------------------------------
1141 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1144 va_start(argptr
, pszFormat
);
1147 s
.PrintfV(pszFormat
, argptr
);
1155 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1158 s
.PrintfV(pszFormat
, argptr
);
1162 int wxString::Printf(const wxChar
*pszFormat
, ...)
1165 va_start(argptr
, pszFormat
);
1167 int iLen
= PrintfV(pszFormat
, argptr
);
1174 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1176 #if wxUSE_EXPERIMENTAL_PRINTF
1177 // the new implementation
1179 // buffer to avoid dynamic memory allocation each time for small strings
1180 char szScratch
[1024];
1183 for (size_t n
= 0; pszFormat
[n
]; n
++)
1184 if (pszFormat
[n
] == wxT('%')) {
1185 static char s_szFlags
[256] = "%";
1187 bool adj_left
= FALSE
, in_prec
= FALSE
,
1188 prec_dot
= FALSE
, done
= FALSE
;
1190 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1192 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1193 switch (pszFormat
[++n
]) {
1207 s_szFlags
[flagofs
++] = pszFormat
[n
];
1212 s_szFlags
[flagofs
++] = pszFormat
[n
];
1219 // dot will be auto-added to s_szFlags if non-negative number follows
1224 s_szFlags
[flagofs
++] = pszFormat
[n
];
1229 s_szFlags
[flagofs
++] = pszFormat
[n
];
1235 s_szFlags
[flagofs
++] = pszFormat
[n
];
1240 s_szFlags
[flagofs
++] = pszFormat
[n
];
1244 int len
= va_arg(argptr
, int);
1251 adj_left
= !adj_left
;
1252 s_szFlags
[flagofs
++] = '-';
1257 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1260 case wxT('1'): case wxT('2'): case wxT('3'):
1261 case wxT('4'): case wxT('5'): case wxT('6'):
1262 case wxT('7'): case wxT('8'): case wxT('9'):
1266 while ((pszFormat
[n
]>=wxT('0')) && (pszFormat
[n
]<=wxT('9'))) {
1267 s_szFlags
[flagofs
++] = pszFormat
[n
];
1268 len
= len
*10 + (pszFormat
[n
] - wxT('0'));
1271 if (in_prec
) max_width
= len
;
1272 else min_width
= len
;
1273 n
--; // the main loop pre-increments n again
1283 s_szFlags
[flagofs
++] = pszFormat
[n
];
1284 s_szFlags
[flagofs
] = '\0';
1286 int val
= va_arg(argptr
, int);
1287 ::sprintf(szScratch
, s_szFlags
, val
);
1289 else if (ilen
== -1) {
1290 short int val
= va_arg(argptr
, short int);
1291 ::sprintf(szScratch
, s_szFlags
, val
);
1293 else if (ilen
== 1) {
1294 long int val
= va_arg(argptr
, long int);
1295 ::sprintf(szScratch
, s_szFlags
, val
);
1297 else if (ilen
== 2) {
1298 #if SIZEOF_LONG_LONG
1299 long long int val
= va_arg(argptr
, long long int);
1300 ::sprintf(szScratch
, s_szFlags
, val
);
1302 long int val
= va_arg(argptr
, long int);
1303 ::sprintf(szScratch
, s_szFlags
, val
);
1306 else if (ilen
== 3) {
1307 size_t val
= va_arg(argptr
, size_t);
1308 ::sprintf(szScratch
, s_szFlags
, val
);
1310 *this += wxString(szScratch
);
1319 s_szFlags
[flagofs
++] = pszFormat
[n
];
1320 s_szFlags
[flagofs
] = '\0';
1322 long double val
= va_arg(argptr
, long double);
1323 ::sprintf(szScratch
, s_szFlags
, val
);
1325 double val
= va_arg(argptr
, double);
1326 ::sprintf(szScratch
, s_szFlags
, val
);
1328 *this += wxString(szScratch
);
1333 void *val
= va_arg(argptr
, void *);
1335 s_szFlags
[flagofs
++] = pszFormat
[n
];
1336 s_szFlags
[flagofs
] = '\0';
1337 ::sprintf(szScratch
, s_szFlags
, val
);
1338 *this += wxString(szScratch
);
1344 wxChar val
= va_arg(argptr
, int);
1345 // we don't need to honor padding here, do we?
1352 // wx extension: we'll let %hs mean non-Unicode strings
1353 char *val
= va_arg(argptr
, char *);
1355 // ASCII->Unicode constructor handles max_width right
1356 wxString
s(val
, wxConvLibc
, max_width
);
1358 size_t len
= wxSTRING_MAXLEN
;
1360 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1361 } else val
= wxT("(null)");
1362 wxString
s(val
, len
);
1364 if (s
.Len() < min_width
)
1365 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1368 wxChar
*val
= va_arg(argptr
, wxChar
*);
1369 size_t len
= wxSTRING_MAXLEN
;
1371 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1372 } else val
= wxT("(null)");
1373 wxString
s(val
, len
);
1374 if (s
.Len() < min_width
)
1375 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1382 int *val
= va_arg(argptr
, int *);
1385 else if (ilen
== -1) {
1386 short int *val
= va_arg(argptr
, short int *);
1389 else if (ilen
>= 1) {
1390 long int *val
= va_arg(argptr
, long int *);
1396 if (wxIsalpha(pszFormat
[n
]))
1397 // probably some flag not taken care of here yet
1398 s_szFlags
[flagofs
++] = pszFormat
[n
];
1401 *this += wxT('%'); // just to pass the glibc tst-printf.c
1409 } else *this += pszFormat
[n
];
1412 // buffer to avoid dynamic memory allocation each time for small strings
1413 char szScratch
[1024];
1415 // NB: wxVsnprintf() may return either less than the buffer size or -1 if
1416 // there is not enough place depending on implementation
1417 int iLen
= wxVsnprintfA(szScratch
, WXSIZEOF(szScratch
), (char *)pszFormat
, argptr
);
1419 // the whole string is in szScratch
1423 bool outOfMemory
= FALSE
;
1424 int size
= 2*WXSIZEOF(szScratch
);
1425 while ( !outOfMemory
) {
1426 char *buf
= GetWriteBuf(size
);
1428 iLen
= wxVsnprintfA(buf
, size
, pszFormat
, argptr
);
1435 // ok, there was enough space
1439 // still not enough, double it again
1443 if ( outOfMemory
) {
1448 #endif // wxUSE_EXPERIMENTAL_PRINTF/!wxUSE_EXPERIMENTAL_PRINTF
1453 // ----------------------------------------------------------------------------
1454 // misc other operations
1455 // ----------------------------------------------------------------------------
1457 // returns TRUE if the string matches the pattern which may contain '*' and
1458 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1460 bool wxString::Matches(const wxChar
*pszMask
) const
1462 // I disable this code as it doesn't seem to be faster (in fact, it seems
1463 // to be much slower) than the old, hand-written code below and using it
1464 // here requires always linking with libregex even if the user code doesn't
1466 #if 0 // wxUSE_REGEX
1467 // first translate the shell-like mask into a regex
1469 pattern
.reserve(wxStrlen(pszMask
));
1481 pattern
+= _T(".*");
1492 // these characters are special in a RE, quote them
1493 // (however note that we don't quote '[' and ']' to allow
1494 // using them for Unix shell like matching)
1495 pattern
+= _T('\\');
1499 pattern
+= *pszMask
;
1507 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1508 #else // !wxUSE_REGEX
1509 // TODO: this is, of course, awfully inefficient...
1511 // the char currently being checked
1512 const wxChar
*pszTxt
= c_str();
1514 // the last location where '*' matched
1515 const wxChar
*pszLastStarInText
= NULL
;
1516 const wxChar
*pszLastStarInMask
= NULL
;
1519 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1520 switch ( *pszMask
) {
1522 if ( *pszTxt
== wxT('\0') )
1525 // pszTxt and pszMask will be incremented in the loop statement
1531 // remember where we started to be able to backtrack later
1532 pszLastStarInText
= pszTxt
;
1533 pszLastStarInMask
= pszMask
;
1535 // ignore special chars immediately following this one
1536 // (should this be an error?)
1537 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1540 // if there is nothing more, match
1541 if ( *pszMask
== wxT('\0') )
1544 // are there any other metacharacters in the mask?
1546 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1548 if ( pEndMask
!= NULL
) {
1549 // we have to match the string between two metachars
1550 uiLenMask
= pEndMask
- pszMask
;
1553 // we have to match the remainder of the string
1554 uiLenMask
= wxStrlen(pszMask
);
1557 wxString
strToMatch(pszMask
, uiLenMask
);
1558 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1559 if ( pMatch
== NULL
)
1562 // -1 to compensate "++" in the loop
1563 pszTxt
= pMatch
+ uiLenMask
- 1;
1564 pszMask
+= uiLenMask
- 1;
1569 if ( *pszMask
!= *pszTxt
)
1575 // match only if nothing left
1576 if ( *pszTxt
== wxT('\0') )
1579 // if we failed to match, backtrack if we can
1580 if ( pszLastStarInText
) {
1581 pszTxt
= pszLastStarInText
+ 1;
1582 pszMask
= pszLastStarInMask
;
1584 pszLastStarInText
= NULL
;
1586 // don't bother resetting pszLastStarInMask, it's unnecessary
1592 #endif // wxUSE_REGEX/!wxUSE_REGEX
1595 // Count the number of chars
1596 int wxString::Freq(wxChar ch
) const
1600 for (int i
= 0; i
< len
; i
++)
1602 if (GetChar(i
) == ch
)
1608 // convert to upper case, return the copy of the string
1609 wxString
wxString::Upper() const
1610 { wxString
s(*this); return s
.MakeUpper(); }
1612 // convert to lower case, return the copy of the string
1613 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1615 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1618 va_start(argptr
, pszFormat
);
1619 int iLen
= PrintfV(pszFormat
, argptr
);
1624 // ---------------------------------------------------------------------------
1625 // standard C++ library string functions
1626 // ---------------------------------------------------------------------------
1628 #ifdef wxSTD_STRING_COMPATIBILITY
1630 void wxString::resize(size_t nSize
, wxChar ch
)
1632 size_t len
= length();
1638 else if ( nSize
> len
)
1640 *this += wxString(ch
, nSize
- len
);
1642 //else: we have exactly the specified length, nothing to do
1645 void wxString::swap(wxString
& str
)
1647 // this is slightly less efficient than fiddling with m_pchData directly,
1648 // but it is still quite efficient as we don't copy the string here because
1649 // ref count always stays positive
1655 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1657 wxASSERT( str
.GetStringData()->IsValid() );
1658 wxASSERT( nPos
<= Len() );
1660 if ( !str
.IsEmpty() ) {
1662 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1663 wxStrncpy(pc
, c_str(), nPos
);
1664 wxStrcpy(pc
+ nPos
, str
);
1665 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1666 strTmp
.UngetWriteBuf();
1673 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1675 wxASSERT( str
.GetStringData()->IsValid() );
1676 wxASSERT( nStart
<= Len() );
1678 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1680 return p
== NULL
? npos
: p
- c_str();
1683 // VC++ 1.5 can't cope with the default argument in the header.
1684 #if !defined(__VISUALC__) || defined(__WIN32__)
1685 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1687 return find(wxString(sz
, n
), nStart
);
1691 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1692 #if !defined(__BORLANDC__)
1693 size_t wxString::find(wxChar ch
, size_t nStart
) const
1695 wxASSERT( nStart
<= Len() );
1697 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1699 return p
== NULL
? npos
: p
- c_str();
1703 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1705 wxASSERT( str
.GetStringData()->IsValid() );
1706 wxASSERT( nStart
== npos
|| nStart
<= Len() );
1708 // TODO could be made much quicker than that
1709 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1710 while ( p
>= c_str() + str
.Len() ) {
1711 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1712 return p
- str
.Len() - c_str();
1719 // VC++ 1.5 can't cope with the default argument in the header.
1720 #if !defined(__VISUALC__) || defined(__WIN32__)
1721 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1723 return rfind(wxString(sz
, n
== npos
? wxSTRING_MAXLEN
: n
), nStart
);
1726 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1728 if ( nStart
== npos
)
1734 wxASSERT( nStart
<= Len() );
1737 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1742 size_t result
= p
- c_str();
1743 return ( result
> nStart
) ? npos
: result
;
1747 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1749 const wxChar
*start
= c_str() + nStart
;
1750 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1752 return firstOf
- c_str();
1757 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1759 if ( nStart
== npos
)
1765 wxASSERT( nStart
<= Len() );
1768 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1770 if ( wxStrchr(sz
, *p
) )
1777 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1779 if ( nStart
== npos
)
1785 wxASSERT( nStart
<= Len() );
1788 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1789 if ( nAccept
>= length() - nStart
)
1795 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1797 wxASSERT( nStart
<= Len() );
1799 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1808 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1810 if ( nStart
== npos
)
1816 wxASSERT( nStart
<= Len() );
1819 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1821 if ( !wxStrchr(sz
, *p
) )
1828 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1830 if ( nStart
== npos
)
1836 wxASSERT( nStart
<= Len() );
1839 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1848 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1850 wxString
strTmp(c_str(), nStart
);
1851 if ( nLen
!= npos
) {
1852 wxASSERT( nStart
+ nLen
<= Len() );
1854 strTmp
.append(c_str() + nStart
+ nLen
);
1861 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1863 wxASSERT_MSG( nStart
+ nLen
<= Len(),
1864 _T("index out of bounds in wxString::replace") );
1867 strTmp
.Alloc(Len()); // micro optimisation to avoid multiple mem allocs
1870 strTmp
.append(c_str(), nStart
);
1871 strTmp
<< sz
<< c_str() + nStart
+ nLen
;
1877 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1879 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1882 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1883 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1885 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1888 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1889 const wxChar
* sz
, size_t nCount
)
1891 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1894 #endif //std::string compatibility
1896 // ============================================================================
1898 // ============================================================================
1900 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1901 #define ARRAY_MAXSIZE_INCREMENT 4096
1903 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1904 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1907 #define STRING(p) ((wxString *)(&(p)))
1910 void wxArrayString::Init(bool autoSort
)
1914 m_pItems
= (wxChar
**) NULL
;
1915 m_autoSort
= autoSort
;
1919 wxArrayString::wxArrayString(const wxArrayString
& src
)
1921 Init(src
.m_autoSort
);
1926 // assignment operator
1927 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1934 m_autoSort
= src
.m_autoSort
;
1939 void wxArrayString::Copy(const wxArrayString
& src
)
1941 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1942 Alloc(src
.m_nCount
);
1944 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1949 void wxArrayString::Grow()
1951 // only do it if no more place
1952 if ( m_nCount
== m_nSize
) {
1953 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
1954 // be never resized!
1955 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
1956 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
1959 if ( m_nSize
== 0 ) {
1960 // was empty, alloc some memory
1961 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1962 m_pItems
= new wxChar
*[m_nSize
];
1965 // otherwise when it's called for the first time, nIncrement would be 0
1966 // and the array would never be expanded
1967 // add 50% but not too much
1968 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1969 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1970 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1971 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1972 m_nSize
+= nIncrement
;
1973 wxChar
**pNew
= new wxChar
*[m_nSize
];
1975 // copy data to new location
1976 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1978 // delete old memory (but do not release the strings!)
1979 wxDELETEA(m_pItems
);
1986 void wxArrayString::Free()
1988 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1989 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1993 // deletes all the strings from the list
1994 void wxArrayString::Empty()
2001 // as Empty, but also frees memory
2002 void wxArrayString::Clear()
2009 wxDELETEA(m_pItems
);
2013 wxArrayString::~wxArrayString()
2017 wxDELETEA(m_pItems
);
2020 // pre-allocates memory (frees the previous data!)
2021 void wxArrayString::Alloc(size_t nSize
)
2023 // only if old buffer was not big enough
2024 if ( nSize
> m_nSize
) {
2026 wxDELETEA(m_pItems
);
2027 m_pItems
= new wxChar
*[nSize
];
2034 // minimizes the memory usage by freeing unused memory
2035 void wxArrayString::Shrink()
2037 // only do it if we have some memory to free
2038 if( m_nCount
< m_nSize
) {
2039 // allocates exactly as much memory as we need
2040 wxChar
**pNew
= new wxChar
*[m_nCount
];
2042 // copy data to new location
2043 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2049 // return a wxString[] as required for some control ctors.
2050 wxString
* wxArrayString::GetStringArray() const
2052 wxString
*array
= 0;
2056 array
= new wxString
[m_nCount
];
2057 for( size_t i
= 0; i
< m_nCount
; i
++ )
2058 array
[i
] = m_pItems
[i
];
2064 // searches the array for an item (forward or backwards)
2065 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2068 // use binary search in the sorted array
2069 wxASSERT_MSG( bCase
&& !bFromEnd
,
2070 wxT("search parameters ignored for auto sorted array") );
2079 res
= wxStrcmp(sz
, m_pItems
[i
]);
2091 // use linear search in unsorted array
2093 if ( m_nCount
> 0 ) {
2094 size_t ui
= m_nCount
;
2096 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2103 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2104 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2113 // add item at the end
2114 size_t wxArrayString::Add(const wxString
& str
)
2117 // insert the string at the correct position to keep the array sorted
2125 res
= wxStrcmp(str
, m_pItems
[i
]);
2136 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2143 wxASSERT( str
.GetStringData()->IsValid() );
2147 // the string data must not be deleted!
2148 str
.GetStringData()->Lock();
2151 m_pItems
[m_nCount
] = (wxChar
*)str
.c_str(); // const_cast
2157 // add item at the given position
2158 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
2160 wxASSERT( str
.GetStringData()->IsValid() );
2162 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2166 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
2167 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2169 str
.GetStringData()->Lock();
2170 m_pItems
[nIndex
] = (wxChar
*)str
.c_str();
2176 void wxArrayString::SetCount(size_t count
)
2181 while ( m_nCount
< count
)
2182 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2185 // removes item from array (by index)
2186 void wxArrayString::Remove(size_t nIndex
)
2188 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Remove") );
2191 Item(nIndex
).GetStringData()->Unlock();
2193 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
2194 (m_nCount
- nIndex
- 1)*sizeof(wxChar
*));
2198 // removes item from array (by value)
2199 void wxArrayString::Remove(const wxChar
*sz
)
2201 int iIndex
= Index(sz
);
2203 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2204 wxT("removing inexistent element in wxArrayString::Remove") );
2209 // ----------------------------------------------------------------------------
2211 // ----------------------------------------------------------------------------
2213 // we can only sort one array at a time with the quick-sort based
2216 // need a critical section to protect access to gs_compareFunction and
2217 // gs_sortAscending variables
2218 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2220 // call this before the value of the global sort vars is changed/after
2221 // you're finished with them
2222 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2223 gs_critsectStringSort = new wxCriticalSection; \
2224 gs_critsectStringSort->Enter()
2225 #define END_SORT() gs_critsectStringSort->Leave(); \
2226 delete gs_critsectStringSort; \
2227 gs_critsectStringSort = NULL
2229 #define START_SORT()
2231 #endif // wxUSE_THREADS
2233 // function to use for string comparaison
2234 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2236 // if we don't use the compare function, this flag tells us if we sort the
2237 // array in ascending or descending order
2238 static bool gs_sortAscending
= TRUE
;
2240 // function which is called by quick sort
2241 extern "C" int LINKAGEMODE
2242 wxStringCompareFunction(const void *first
, const void *second
)
2244 wxString
*strFirst
= (wxString
*)first
;
2245 wxString
*strSecond
= (wxString
*)second
;
2247 if ( gs_compareFunction
) {
2248 return gs_compareFunction(*strFirst
, *strSecond
);
2251 // maybe we should use wxStrcoll
2252 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
2254 return gs_sortAscending
? result
: -result
;
2258 // sort array elements using passed comparaison function
2259 void wxArrayString::Sort(CompareFunction compareFunction
)
2263 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2264 gs_compareFunction
= compareFunction
;
2268 // reset it to NULL so that Sort(bool) will work the next time
2269 gs_compareFunction
= NULL
;
2274 void wxArrayString::Sort(bool reverseOrder
)
2278 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2279 gs_sortAscending
= !reverseOrder
;
2286 void wxArrayString::DoSort()
2288 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2290 // just sort the pointers using qsort() - of course it only works because
2291 // wxString() *is* a pointer to its data
2292 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2295 bool wxArrayString::operator==(const wxArrayString
& a
) const
2297 if ( m_nCount
!= a
.m_nCount
)
2300 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2302 if ( Item(n
) != a
[n
] )