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 #include <wchar.h> // for wcsrtombs(), see comments where it's used
53 #ifdef WXSTRING_IS_WXOBJECT
54 IMPLEMENT_DYNAMIC_CLASS(wxString
, wxObject
)
55 #endif //WXSTRING_IS_WXOBJECT
58 #undef wxUSE_EXPERIMENTAL_PRINTF
59 #define wxUSE_EXPERIMENTAL_PRINTF 1
62 // allocating extra space for each string consumes more memory but speeds up
63 // the concatenation operations (nLen is the current string's length)
64 // NB: EXTRA_ALLOC must be >= 0!
65 #define EXTRA_ALLOC (19 - nLen % 16)
67 // ---------------------------------------------------------------------------
68 // static class variables definition
69 // ---------------------------------------------------------------------------
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(wxUSE_NORLANDER_HEADERS)) && !defined(__MINGW32__)
111 #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__) && !defined(__UNIX__)
128 #warning "Using sprintf() because no snprintf()-like function defined"
129 #elif defined(__MWERKS__)
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 istream
& operator>>(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 ostream
& operator<<(ostream
& os
, const wxString
& str
)
187 #endif //std::string compatibility
189 extern int WXDLLEXPORT
wxVsnprintf(wxChar
*buf
, size_t len
,
190 const wxChar
*format
, va_list argptr
)
193 // FIXME should use wvsnprintf() or whatever if it's available
195 int iLen
= s
.PrintfV(format
, argptr
);
198 wxStrncpy(buf
, s
.c_str(), iLen
);
203 // vsnprintf() will not terminate the string with '\0' if there is not
204 // enough place, but we want the string to always be NUL terminated
205 int rc
= wxVsnprintfA(buf
, len
- 1, format
, argptr
);
212 #endif // Unicode/ANSI
215 extern int WXDLLEXPORT
wxSnprintf(wxChar
*buf
, size_t len
,
216 const wxChar
*format
, ...)
219 va_start(argptr
, format
);
221 int iLen
= wxVsnprintf(buf
, len
, format
, argptr
);
228 // ----------------------------------------------------------------------------
230 // ----------------------------------------------------------------------------
232 // this small class is used to gather statistics for performance tuning
233 //#define WXSTRING_STATISTICS
234 #ifdef WXSTRING_STATISTICS
238 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
240 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
242 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
245 size_t m_nCount
, m_nTotal
;
247 } g_averageLength("allocation size"),
248 g_averageSummandLength("summand length"),
249 g_averageConcatHit("hit probability in concat"),
250 g_averageInitialLength("initial string length");
252 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
254 #define STATISTICS_ADD(av, val)
255 #endif // WXSTRING_STATISTICS
257 // ===========================================================================
258 // wxString class core
259 // ===========================================================================
261 // ---------------------------------------------------------------------------
263 // ---------------------------------------------------------------------------
265 // constructs string of <nLength> copies of character <ch>
266 wxString::wxString(wxChar ch
, size_t nLength
)
271 AllocBuffer(nLength
);
274 // memset only works on char
275 for (size_t n
=0; n
<nLength
; n
++) m_pchData
[n
] = ch
;
277 memset(m_pchData
, ch
, nLength
);
282 // takes nLength elements of psz starting at nPos
283 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
287 wxASSERT( nPos
<= wxStrlen(psz
) );
289 if ( nLength
== wxSTRING_MAXLEN
)
290 nLength
= wxStrlen(psz
+ nPos
);
292 STATISTICS_ADD(InitialLength
, nLength
);
295 // trailing '\0' is written in AllocBuffer()
296 AllocBuffer(nLength
);
297 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
301 #ifdef wxSTD_STRING_COMPATIBILITY
303 // poor man's iterators are "void *" pointers
304 wxString::wxString(const void *pStart
, const void *pEnd
)
306 InitWith((const wxChar
*)pStart
, 0,
307 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
310 #endif //std::string compatibility
314 // from multibyte string
315 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
317 // first get necessary size
318 size_t nLen
= psz
? conv
.MB2WC((wchar_t *) NULL
, psz
, 0) : 0;
320 // nLength is number of *Unicode* characters here!
321 if ((nLen
!= (size_t)-1) && (nLen
> nLength
))
325 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
327 conv
.MB2WC(m_pchData
, psz
, nLen
);
338 wxString::wxString(const wchar_t *pwz
)
340 // first get necessary size
341 size_t nLen
= pwz
? wxWC2MB((char *) NULL
, pwz
, 0) : 0;
344 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
346 wxWC2MB(m_pchData
, pwz
, nLen
);
352 #endif // wxUSE_WCHAR_T
354 #endif // Unicode/ANSI
356 // ---------------------------------------------------------------------------
358 // ---------------------------------------------------------------------------
360 // allocates memory needed to store a C string of length nLen
361 void wxString::AllocBuffer(size_t nLen
)
363 // allocating 0 sized buffer doesn't make sense, all empty strings should
365 wxASSERT( nLen
> 0 );
367 // make sure that we don't overflow
368 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
369 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
371 STATISTICS_ADD(Length
, nLen
);
374 // 1) one extra character for '\0' termination
375 // 2) sizeof(wxStringData) for housekeeping info
376 wxStringData
* pData
= (wxStringData
*)
377 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
379 pData
->nDataLength
= nLen
;
380 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
381 m_pchData
= pData
->data(); // data starts after wxStringData
382 m_pchData
[nLen
] = wxT('\0');
385 // must be called before changing this string
386 void wxString::CopyBeforeWrite()
388 wxStringData
* pData
= GetStringData();
390 if ( pData
->IsShared() ) {
391 pData
->Unlock(); // memory not freed because shared
392 size_t nLen
= pData
->nDataLength
;
394 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
397 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
400 // must be called before replacing contents of this string
401 void wxString::AllocBeforeWrite(size_t nLen
)
403 wxASSERT( nLen
!= 0 ); // doesn't make any sense
405 // must not share string and must have enough space
406 wxStringData
* pData
= GetStringData();
407 if ( pData
->IsShared() || pData
->IsEmpty() ) {
408 // can't work with old buffer, get new one
413 if ( nLen
> pData
->nAllocLength
) {
414 // realloc the buffer instead of calling malloc() again, this is more
416 STATISTICS_ADD(Length
, nLen
);
420 wxStringData
*pDataOld
= pData
;
421 pData
= (wxStringData
*)
422 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
427 // FIXME we're going to crash...
431 pData
->nAllocLength
= nLen
;
432 m_pchData
= pData
->data();
435 // now we have enough space, just update the string length
436 pData
->nDataLength
= nLen
;
439 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
442 // allocate enough memory for nLen characters
443 void wxString::Alloc(size_t nLen
)
445 wxStringData
*pData
= GetStringData();
446 if ( pData
->nAllocLength
<= nLen
) {
447 if ( pData
->IsEmpty() ) {
450 wxStringData
* pData
= (wxStringData
*)
451 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
453 pData
->nDataLength
= 0;
454 pData
->nAllocLength
= nLen
;
455 m_pchData
= pData
->data(); // data starts after wxStringData
456 m_pchData
[0u] = wxT('\0');
458 else if ( pData
->IsShared() ) {
459 pData
->Unlock(); // memory not freed because shared
460 size_t nOldLen
= pData
->nDataLength
;
462 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
467 wxStringData
*pDataOld
= pData
;
468 wxStringData
*p
= (wxStringData
*)
469 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
475 // FIXME what to do on memory error?
479 // it's not important if the pointer changed or not (the check for this
480 // is not faster than assigning to m_pchData in all cases)
481 p
->nAllocLength
= nLen
;
482 m_pchData
= p
->data();
485 //else: we've already got enough
488 // shrink to minimal size (releasing extra memory)
489 void wxString::Shrink()
491 wxStringData
*pData
= GetStringData();
493 // this variable is unused in release build, so avoid the compiler warning
494 // by just not declaring it
498 realloc(pData
, sizeof(wxStringData
) + (pData
->nDataLength
+ 1)*sizeof(wxChar
));
500 // we rely on a reasonable realloc() implementation here - so far I haven't
501 // seen any which wouldn't behave like this
503 wxASSERT( p
!= NULL
); // can't free memory?
504 wxASSERT( p
== pData
); // we're decrementing the size - block shouldn't move!
507 // get the pointer to writable buffer of (at least) nLen bytes
508 wxChar
*wxString::GetWriteBuf(size_t nLen
)
510 AllocBeforeWrite(nLen
);
512 wxASSERT( GetStringData()->nRefs
== 1 );
513 GetStringData()->Validate(FALSE
);
518 // put string back in a reasonable state after GetWriteBuf
519 void wxString::UngetWriteBuf()
521 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
522 GetStringData()->Validate(TRUE
);
525 // ---------------------------------------------------------------------------
527 // ---------------------------------------------------------------------------
529 // all functions are inline in string.h
531 // ---------------------------------------------------------------------------
532 // assignment operators
533 // ---------------------------------------------------------------------------
535 // helper function: does real copy
536 void wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
538 if ( nSrcLen
== 0 ) {
542 AllocBeforeWrite(nSrcLen
);
543 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
544 GetStringData()->nDataLength
= nSrcLen
;
545 m_pchData
[nSrcLen
] = wxT('\0');
549 // assigns one string to another
550 wxString
& wxString::operator=(const wxString
& stringSrc
)
552 wxASSERT( stringSrc
.GetStringData()->IsValid() );
554 // don't copy string over itself
555 if ( m_pchData
!= stringSrc
.m_pchData
) {
556 if ( stringSrc
.GetStringData()->IsEmpty() ) {
561 GetStringData()->Unlock();
562 m_pchData
= stringSrc
.m_pchData
;
563 GetStringData()->Lock();
570 // assigns a single character
571 wxString
& wxString::operator=(wxChar ch
)
578 wxString
& wxString::operator=(const wxChar
*psz
)
580 AssignCopy(wxStrlen(psz
), psz
);
586 // same as 'signed char' variant
587 wxString
& wxString::operator=(const unsigned char* psz
)
589 *this = (const char *)psz
;
594 wxString
& wxString::operator=(const wchar_t *pwz
)
604 // ---------------------------------------------------------------------------
605 // string concatenation
606 // ---------------------------------------------------------------------------
608 // add something to this string
609 void wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
611 STATISTICS_ADD(SummandLength
, nSrcLen
);
613 // concatenating an empty string is a NOP
615 wxStringData
*pData
= GetStringData();
616 size_t nLen
= pData
->nDataLength
;
617 size_t nNewLen
= nLen
+ nSrcLen
;
619 // alloc new buffer if current is too small
620 if ( pData
->IsShared() ) {
621 STATISTICS_ADD(ConcatHit
, 0);
623 // we have to allocate another buffer
624 wxStringData
* pOldData
= GetStringData();
625 AllocBuffer(nNewLen
);
626 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
629 else if ( nNewLen
> pData
->nAllocLength
) {
630 STATISTICS_ADD(ConcatHit
, 0);
632 // we have to grow the buffer
636 STATISTICS_ADD(ConcatHit
, 1);
638 // the buffer is already big enough
641 // should be enough space
642 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
644 // fast concatenation - all is done in our buffer
645 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
647 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
648 GetStringData()->nDataLength
= nNewLen
; // and fix the length
650 //else: the string to append was empty
654 * concatenation functions come in 5 flavours:
656 * char + string and string + char
657 * C str + string and string + C str
660 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
662 wxASSERT( string1
.GetStringData()->IsValid() );
663 wxASSERT( string2
.GetStringData()->IsValid() );
665 wxString s
= string1
;
671 wxString
operator+(const wxString
& string
, wxChar ch
)
673 wxASSERT( string
.GetStringData()->IsValid() );
681 wxString
operator+(wxChar ch
, const wxString
& string
)
683 wxASSERT( string
.GetStringData()->IsValid() );
691 wxString
operator+(const wxString
& string
, const wxChar
*psz
)
693 wxASSERT( string
.GetStringData()->IsValid() );
696 s
.Alloc(wxStrlen(psz
) + string
.Len());
703 wxString
operator+(const wxChar
*psz
, const wxString
& string
)
705 wxASSERT( string
.GetStringData()->IsValid() );
708 s
.Alloc(wxStrlen(psz
) + string
.Len());
715 // ===========================================================================
716 // other common string functions
717 // ===========================================================================
719 // ---------------------------------------------------------------------------
720 // simple sub-string extraction
721 // ---------------------------------------------------------------------------
723 // helper function: clone the data attached to this string
724 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
726 if ( nCopyLen
== 0 ) {
730 dest
.AllocBuffer(nCopyLen
);
731 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
735 // extract string of length nCount starting at nFirst
736 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
738 wxStringData
*pData
= GetStringData();
739 size_t nLen
= pData
->nDataLength
;
741 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
742 if ( nCount
== wxSTRING_MAXLEN
)
744 nCount
= nLen
- nFirst
;
747 // out-of-bounds requests return sensible things
748 if ( nFirst
+ nCount
> nLen
)
750 nCount
= nLen
- nFirst
;
755 // AllocCopy() will return empty string
760 AllocCopy(dest
, nCount
, nFirst
);
765 // extract nCount last (rightmost) characters
766 wxString
wxString::Right(size_t nCount
) const
768 if ( nCount
> (size_t)GetStringData()->nDataLength
)
769 nCount
= GetStringData()->nDataLength
;
772 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
776 // get all characters after the last occurence of ch
777 // (returns the whole string if ch not found)
778 wxString
wxString::AfterLast(wxChar ch
) const
781 int iPos
= Find(ch
, TRUE
);
782 if ( iPos
== wxNOT_FOUND
)
785 str
= c_str() + iPos
+ 1;
790 // extract nCount first (leftmost) characters
791 wxString
wxString::Left(size_t nCount
) const
793 if ( nCount
> (size_t)GetStringData()->nDataLength
)
794 nCount
= GetStringData()->nDataLength
;
797 AllocCopy(dest
, nCount
, 0);
801 // get all characters before the first occurence of ch
802 // (returns the whole string if ch not found)
803 wxString
wxString::BeforeFirst(wxChar ch
) const
806 for ( const wxChar
*pc
= m_pchData
; *pc
!= wxT('\0') && *pc
!= ch
; pc
++ )
812 /// get all characters before the last occurence of ch
813 /// (returns empty string if ch not found)
814 wxString
wxString::BeforeLast(wxChar ch
) const
817 int iPos
= Find(ch
, TRUE
);
818 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
819 str
= wxString(c_str(), iPos
);
824 /// get all characters after the first occurence of ch
825 /// (returns empty string if ch not found)
826 wxString
wxString::AfterFirst(wxChar ch
) const
830 if ( iPos
!= wxNOT_FOUND
)
831 str
= c_str() + iPos
+ 1;
836 // replace first (or all) occurences of some substring with another one
837 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
839 size_t uiCount
= 0; // count of replacements made
841 size_t uiOldLen
= wxStrlen(szOld
);
844 const wxChar
*pCurrent
= m_pchData
;
845 const wxChar
*pSubstr
;
846 while ( *pCurrent
!= wxT('\0') ) {
847 pSubstr
= wxStrstr(pCurrent
, szOld
);
848 if ( pSubstr
== NULL
) {
849 // strTemp is unused if no replacements were made, so avoid the copy
853 strTemp
+= pCurrent
; // copy the rest
854 break; // exit the loop
857 // take chars before match
858 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
860 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
865 if ( !bReplaceAll
) {
866 strTemp
+= pCurrent
; // copy the rest
867 break; // exit the loop
872 // only done if there were replacements, otherwise would have returned above
878 bool wxString::IsAscii() const
880 const wxChar
*s
= (const wxChar
*) *this;
882 if(!isascii(*s
)) return(FALSE
);
888 bool wxString::IsWord() const
890 const wxChar
*s
= (const wxChar
*) *this;
892 if(!wxIsalpha(*s
)) return(FALSE
);
898 bool wxString::IsNumber() const
900 const wxChar
*s
= (const wxChar
*) *this;
902 if(!wxIsdigit(*s
)) return(FALSE
);
908 wxString
wxString::Strip(stripType w
) const
911 if ( w
& leading
) s
.Trim(FALSE
);
912 if ( w
& trailing
) s
.Trim(TRUE
);
916 // ---------------------------------------------------------------------------
918 // ---------------------------------------------------------------------------
920 wxString
& wxString::MakeUpper()
924 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
925 *p
= (wxChar
)wxToupper(*p
);
930 wxString
& wxString::MakeLower()
934 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
935 *p
= (wxChar
)wxTolower(*p
);
940 // ---------------------------------------------------------------------------
941 // trimming and padding
942 // ---------------------------------------------------------------------------
944 // trims spaces (in the sense of isspace) from left or right side
945 wxString
& wxString::Trim(bool bFromRight
)
947 // first check if we're going to modify the string at all
950 (bFromRight
&& wxIsspace(GetChar(Len() - 1))) ||
951 (!bFromRight
&& wxIsspace(GetChar(0u)))
955 // ok, there is at least one space to trim
960 // find last non-space character
961 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
962 while ( wxIsspace(*psz
) && (psz
>= m_pchData
) )
965 // truncate at trailing space start
967 GetStringData()->nDataLength
= psz
- m_pchData
;
971 // find first non-space character
972 const wxChar
*psz
= m_pchData
;
973 while ( wxIsspace(*psz
) )
976 // fix up data and length
977 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
978 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
979 GetStringData()->nDataLength
= nDataLength
;
986 // adds nCount characters chPad to the string from either side
987 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
989 wxString
s(chPad
, nCount
);
1002 // truncate the string
1003 wxString
& wxString::Truncate(size_t uiLen
)
1005 if ( uiLen
< Len() ) {
1008 *(m_pchData
+ uiLen
) = wxT('\0');
1009 GetStringData()->nDataLength
= uiLen
;
1011 //else: nothing to do, string is already short enough
1016 // ---------------------------------------------------------------------------
1017 // finding (return wxNOT_FOUND if not found and index otherwise)
1018 // ---------------------------------------------------------------------------
1021 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1023 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
1025 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1028 // find a sub-string (like strstr)
1029 int wxString::Find(const wxChar
*pszSub
) const
1031 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
1033 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1036 // ----------------------------------------------------------------------------
1037 // conversion to numbers
1038 // ----------------------------------------------------------------------------
1040 bool wxString::ToLong(long *val
) const
1042 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToLong") );
1044 const wxChar
*start
= c_str();
1046 *val
= wxStrtol(start
, &end
, 10);
1048 // return TRUE only if scan was stopped by the terminating NUL and if the
1049 // string was not empty to start with
1050 return !*end
&& (end
!= start
);
1053 bool wxString::ToULong(unsigned long *val
) const
1055 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToULong") );
1057 const wxChar
*start
= c_str();
1059 *val
= wxStrtoul(start
, &end
, 10);
1061 // return TRUE only if scan was stopped by the terminating NUL and if the
1062 // string was not empty to start with
1063 return !*end
&& (end
!= start
);
1066 bool wxString::ToDouble(double *val
) const
1068 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToDouble") );
1070 const wxChar
*start
= c_str();
1072 *val
= wxStrtod(start
, &end
);
1074 // return TRUE only if scan was stopped by the terminating NUL and if the
1075 // string was not empty to start with
1076 return !*end
&& (end
!= start
);
1079 // ---------------------------------------------------------------------------
1080 // stream-like operators
1081 // ---------------------------------------------------------------------------
1082 wxString
& wxString::operator<<(int i
)
1085 res
.Printf(wxT("%d"), i
);
1087 return (*this) << res
;
1090 wxString
& wxString::operator<<(float f
)
1093 res
.Printf(wxT("%f"), f
);
1095 return (*this) << res
;
1098 wxString
& wxString::operator<<(double d
)
1101 res
.Printf(wxT("%g"), d
);
1103 return (*this) << res
;
1106 // ---------------------------------------------------------------------------
1108 // ---------------------------------------------------------------------------
1111 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1114 va_start(argptr
, pszFormat
);
1117 s
.PrintfV(pszFormat
, argptr
);
1125 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1128 s
.Printf(pszFormat
, argptr
);
1132 int wxString::Printf(const wxChar
*pszFormat
, ...)
1135 va_start(argptr
, pszFormat
);
1137 int iLen
= PrintfV(pszFormat
, argptr
);
1144 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1146 #if wxUSE_EXPERIMENTAL_PRINTF
1147 // the new implementation
1149 // buffer to avoid dynamic memory allocation each time for small strings
1150 char szScratch
[1024];
1153 for (size_t n
= 0; pszFormat
[n
]; n
++)
1154 if (pszFormat
[n
] == wxT('%')) {
1155 static char s_szFlags
[256] = "%";
1157 bool adj_left
= FALSE
, in_prec
= FALSE
,
1158 prec_dot
= FALSE
, done
= FALSE
;
1160 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1162 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1163 switch (pszFormat
[++n
]) {
1177 s_szFlags
[flagofs
++] = pszFormat
[n
];
1182 s_szFlags
[flagofs
++] = pszFormat
[n
];
1189 // dot will be auto-added to s_szFlags if non-negative number follows
1194 s_szFlags
[flagofs
++] = pszFormat
[n
];
1199 s_szFlags
[flagofs
++] = pszFormat
[n
];
1205 s_szFlags
[flagofs
++] = pszFormat
[n
];
1210 s_szFlags
[flagofs
++] = pszFormat
[n
];
1214 int len
= va_arg(argptr
, int);
1221 adj_left
= !adj_left
;
1222 s_szFlags
[flagofs
++] = '-';
1227 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1230 case wxT('1'): case wxT('2'): case wxT('3'):
1231 case wxT('4'): case wxT('5'): case wxT('6'):
1232 case wxT('7'): case wxT('8'): case wxT('9'):
1236 while ((pszFormat
[n
]>=wxT('0')) && (pszFormat
[n
]<=wxT('9'))) {
1237 s_szFlags
[flagofs
++] = pszFormat
[n
];
1238 len
= len
*10 + (pszFormat
[n
] - wxT('0'));
1241 if (in_prec
) max_width
= len
;
1242 else min_width
= len
;
1243 n
--; // the main loop pre-increments n again
1253 s_szFlags
[flagofs
++] = pszFormat
[n
];
1254 s_szFlags
[flagofs
] = '\0';
1256 int val
= va_arg(argptr
, int);
1257 ::sprintf(szScratch
, s_szFlags
, val
);
1259 else if (ilen
== -1) {
1260 short int val
= va_arg(argptr
, short int);
1261 ::sprintf(szScratch
, s_szFlags
, val
);
1263 else if (ilen
== 1) {
1264 long int val
= va_arg(argptr
, long int);
1265 ::sprintf(szScratch
, s_szFlags
, val
);
1267 else if (ilen
== 2) {
1268 #if SIZEOF_LONG_LONG
1269 long long int val
= va_arg(argptr
, long long int);
1270 ::sprintf(szScratch
, s_szFlags
, val
);
1272 long int val
= va_arg(argptr
, long int);
1273 ::sprintf(szScratch
, s_szFlags
, val
);
1276 else if (ilen
== 3) {
1277 size_t val
= va_arg(argptr
, size_t);
1278 ::sprintf(szScratch
, s_szFlags
, val
);
1280 *this += wxString(szScratch
);
1289 s_szFlags
[flagofs
++] = pszFormat
[n
];
1290 s_szFlags
[flagofs
] = '\0';
1292 long double val
= va_arg(argptr
, long double);
1293 ::sprintf(szScratch
, s_szFlags
, val
);
1295 double val
= va_arg(argptr
, double);
1296 ::sprintf(szScratch
, s_szFlags
, val
);
1298 *this += wxString(szScratch
);
1303 void *val
= va_arg(argptr
, void *);
1305 s_szFlags
[flagofs
++] = pszFormat
[n
];
1306 s_szFlags
[flagofs
] = '\0';
1307 ::sprintf(szScratch
, s_szFlags
, val
);
1308 *this += wxString(szScratch
);
1314 wxChar val
= va_arg(argptr
, int);
1315 // we don't need to honor padding here, do we?
1322 // wx extension: we'll let %hs mean non-Unicode strings
1323 char *val
= va_arg(argptr
, char *);
1325 // ASCII->Unicode constructor handles max_width right
1326 wxString
s(val
, wxConvLibc
, max_width
);
1328 size_t len
= wxSTRING_MAXLEN
;
1330 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1331 } else val
= wxT("(null)");
1332 wxString
s(val
, len
);
1334 if (s
.Len() < min_width
)
1335 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1338 wxChar
*val
= va_arg(argptr
, wxChar
*);
1339 size_t len
= wxSTRING_MAXLEN
;
1341 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1342 } else val
= wxT("(null)");
1343 wxString
s(val
, len
);
1344 if (s
.Len() < min_width
)
1345 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1352 int *val
= va_arg(argptr
, int *);
1355 else if (ilen
== -1) {
1356 short int *val
= va_arg(argptr
, short int *);
1359 else if (ilen
>= 1) {
1360 long int *val
= va_arg(argptr
, long int *);
1366 if (wxIsalpha(pszFormat
[n
]))
1367 // probably some flag not taken care of here yet
1368 s_szFlags
[flagofs
++] = pszFormat
[n
];
1371 *this += wxT('%'); // just to pass the glibc tst-printf.c
1379 } else *this += pszFormat
[n
];
1382 // buffer to avoid dynamic memory allocation each time for small strings
1383 char szScratch
[1024];
1385 // NB: wxVsnprintf() may return either less than the buffer size or -1 if
1386 // there is not enough place depending on implementation
1387 int iLen
= wxVsnprintfA(szScratch
, WXSIZEOF(szScratch
), pszFormat
, argptr
);
1389 // the whole string is in szScratch
1393 bool outOfMemory
= FALSE
;
1394 int size
= 2*WXSIZEOF(szScratch
);
1395 while ( !outOfMemory
) {
1396 char *buf
= GetWriteBuf(size
);
1398 iLen
= wxVsnprintfA(buf
, size
, pszFormat
, argptr
);
1405 // ok, there was enough space
1409 // still not enough, double it again
1413 if ( outOfMemory
) {
1418 #endif // wxUSE_EXPERIMENTAL_PRINTF/!wxUSE_EXPERIMENTAL_PRINTF
1423 // ----------------------------------------------------------------------------
1424 // misc other operations
1425 // ----------------------------------------------------------------------------
1427 // returns TRUE if the string matches the pattern which may contain '*' and
1428 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1430 bool wxString::Matches(const wxChar
*pszMask
) const
1432 // check char by char
1433 const wxChar
*pszTxt
;
1434 for ( pszTxt
= c_str(); *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1435 switch ( *pszMask
) {
1437 if ( *pszTxt
== wxT('\0') )
1440 // pszText and pszMask will be incremented in the loop statement
1446 // ignore special chars immediately following this one
1447 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1450 // if there is nothing more, match
1451 if ( *pszMask
== wxT('\0') )
1454 // are there any other metacharacters in the mask?
1456 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1458 if ( pEndMask
!= NULL
) {
1459 // we have to match the string between two metachars
1460 uiLenMask
= pEndMask
- pszMask
;
1463 // we have to match the remainder of the string
1464 uiLenMask
= wxStrlen(pszMask
);
1467 wxString
strToMatch(pszMask
, uiLenMask
);
1468 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1469 if ( pMatch
== NULL
)
1472 // -1 to compensate "++" in the loop
1473 pszTxt
= pMatch
+ uiLenMask
- 1;
1474 pszMask
+= uiLenMask
- 1;
1479 if ( *pszMask
!= *pszTxt
)
1485 // match only if nothing left
1486 return *pszTxt
== wxT('\0');
1489 // Count the number of chars
1490 int wxString::Freq(wxChar ch
) const
1494 for (int i
= 0; i
< len
; i
++)
1496 if (GetChar(i
) == ch
)
1502 // convert to upper case, return the copy of the string
1503 wxString
wxString::Upper() const
1504 { wxString
s(*this); return s
.MakeUpper(); }
1506 // convert to lower case, return the copy of the string
1507 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1509 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1512 va_start(argptr
, pszFormat
);
1513 int iLen
= PrintfV(pszFormat
, argptr
);
1518 // ---------------------------------------------------------------------------
1519 // standard C++ library string functions
1520 // ---------------------------------------------------------------------------
1521 #ifdef wxSTD_STRING_COMPATIBILITY
1523 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1525 wxASSERT( str
.GetStringData()->IsValid() );
1526 wxASSERT( nPos
<= Len() );
1528 if ( !str
.IsEmpty() ) {
1530 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1531 wxStrncpy(pc
, c_str(), nPos
);
1532 wxStrcpy(pc
+ nPos
, str
);
1533 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1534 strTmp
.UngetWriteBuf();
1541 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1543 wxASSERT( str
.GetStringData()->IsValid() );
1544 wxASSERT( nStart
<= Len() );
1546 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1548 return p
== NULL
? npos
: p
- c_str();
1551 // VC++ 1.5 can't cope with the default argument in the header.
1552 #if !defined(__VISUALC__) || defined(__WIN32__)
1553 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1555 return find(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1559 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1560 #if !defined(__BORLANDC__)
1561 size_t wxString::find(wxChar ch
, size_t nStart
) const
1563 wxASSERT( nStart
<= Len() );
1565 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1567 return p
== NULL
? npos
: p
- c_str();
1571 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1573 wxASSERT( str
.GetStringData()->IsValid() );
1574 wxASSERT( nStart
<= Len() );
1576 // TODO could be made much quicker than that
1577 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1578 while ( p
>= c_str() + str
.Len() ) {
1579 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1580 return p
- str
.Len() - c_str();
1587 // VC++ 1.5 can't cope with the default argument in the header.
1588 #if !defined(__VISUALC__) || defined(__WIN32__)
1589 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1591 return rfind(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1594 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1596 if ( nStart
== npos
)
1602 wxASSERT( nStart
<= Len() );
1605 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1610 size_t result
= p
- c_str();
1611 return ( result
> nStart
) ? npos
: result
;
1615 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1617 const wxChar
*start
= c_str() + nStart
;
1618 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1620 return firstOf
- start
;
1625 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1627 if ( nStart
== npos
)
1633 wxASSERT( nStart
<= Len() );
1636 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1638 if ( wxStrchr(sz
, *p
) )
1645 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1647 if ( nStart
== npos
)
1653 wxASSERT( nStart
<= Len() );
1656 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1657 if ( nAccept
>= length() - nStart
)
1663 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1665 wxASSERT( nStart
<= Len() );
1667 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1676 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1678 if ( nStart
== npos
)
1684 wxASSERT( nStart
<= Len() );
1687 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1689 if ( !wxStrchr(sz
, *p
) )
1696 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1698 if ( nStart
== npos
)
1704 wxASSERT( nStart
<= Len() );
1707 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1716 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1718 wxString
strTmp(c_str(), nStart
);
1719 if ( nLen
!= npos
) {
1720 wxASSERT( nStart
+ nLen
<= Len() );
1722 strTmp
.append(c_str() + nStart
+ nLen
);
1729 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1731 wxASSERT( nStart
+ nLen
<= wxStrlen(sz
) );
1735 strTmp
.append(c_str(), nStart
);
1737 strTmp
.append(c_str() + nStart
+ nLen
);
1743 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1745 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1748 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1749 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1751 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1754 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1755 const wxChar
* sz
, size_t nCount
)
1757 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1760 #endif //std::string compatibility
1762 // ============================================================================
1764 // ============================================================================
1766 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1767 #define ARRAY_MAXSIZE_INCREMENT 4096
1768 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1769 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1772 #define STRING(p) ((wxString *)(&(p)))
1775 wxArrayString::wxArrayString(bool autoSort
)
1779 m_pItems
= (wxChar
**) NULL
;
1780 m_autoSort
= autoSort
;
1784 wxArrayString::wxArrayString(const wxArrayString
& src
)
1788 m_pItems
= (wxChar
**) NULL
;
1789 m_autoSort
= src
.m_autoSort
;
1794 // assignment operator
1795 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1805 void wxArrayString::Copy(const wxArrayString
& src
)
1807 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1808 Alloc(src
.m_nCount
);
1810 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1815 void wxArrayString::Grow()
1817 // only do it if no more place
1818 if( m_nCount
== m_nSize
) {
1819 if( m_nSize
== 0 ) {
1820 // was empty, alloc some memory
1821 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1822 m_pItems
= new wxChar
*[m_nSize
];
1825 // otherwise when it's called for the first time, nIncrement would be 0
1826 // and the array would never be expanded
1827 #if defined(__VISAGECPP__) && defined(__WXDEBUG__)
1828 int array_size
= ARRAY_DEFAULT_INITIAL_SIZE
;
1829 wxASSERT( array_size
!= 0 );
1831 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE
!= 0 );
1834 // add 50% but not too much
1835 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1836 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1837 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1838 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1839 m_nSize
+= nIncrement
;
1840 wxChar
**pNew
= new wxChar
*[m_nSize
];
1842 // copy data to new location
1843 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1845 // delete old memory (but do not release the strings!)
1846 wxDELETEA(m_pItems
);
1853 void wxArrayString::Free()
1855 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1856 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1860 // deletes all the strings from the list
1861 void wxArrayString::Empty()
1868 // as Empty, but also frees memory
1869 void wxArrayString::Clear()
1876 wxDELETEA(m_pItems
);
1880 wxArrayString::~wxArrayString()
1884 wxDELETEA(m_pItems
);
1887 // pre-allocates memory (frees the previous data!)
1888 void wxArrayString::Alloc(size_t nSize
)
1890 wxASSERT( nSize
> 0 );
1892 // only if old buffer was not big enough
1893 if ( nSize
> m_nSize
) {
1895 wxDELETEA(m_pItems
);
1896 m_pItems
= new wxChar
*[nSize
];
1903 // minimizes the memory usage by freeing unused memory
1904 void wxArrayString::Shrink()
1906 // only do it if we have some memory to free
1907 if( m_nCount
< m_nSize
) {
1908 // allocates exactly as much memory as we need
1909 wxChar
**pNew
= new wxChar
*[m_nCount
];
1911 // copy data to new location
1912 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1918 // searches the array for an item (forward or backwards)
1919 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
1922 // use binary search in the sorted array
1923 wxASSERT_MSG( bCase
&& !bFromEnd
,
1924 wxT("search parameters ignored for auto sorted array") );
1933 res
= wxStrcmp(sz
, m_pItems
[i
]);
1945 // use linear search in unsorted array
1947 if ( m_nCount
> 0 ) {
1948 size_t ui
= m_nCount
;
1950 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1957 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1958 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1967 // add item at the end
1968 size_t wxArrayString::Add(const wxString
& str
)
1971 // insert the string at the correct position to keep the array sorted
1979 res
= wxStrcmp(str
, m_pItems
[i
]);
1990 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
1997 wxASSERT( str
.GetStringData()->IsValid() );
2001 // the string data must not be deleted!
2002 str
.GetStringData()->Lock();
2005 m_pItems
[m_nCount
] = (wxChar
*)str
.c_str(); // const_cast
2011 // add item at the given position
2012 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
2014 wxASSERT( str
.GetStringData()->IsValid() );
2016 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2020 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
2021 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2023 str
.GetStringData()->Lock();
2024 m_pItems
[nIndex
] = (wxChar
*)str
.c_str();
2029 // removes item from array (by index)
2030 void wxArrayString::Remove(size_t nIndex
)
2032 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Remove") );
2035 Item(nIndex
).GetStringData()->Unlock();
2037 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
2038 (m_nCount
- nIndex
- 1)*sizeof(wxChar
*));
2042 // removes item from array (by value)
2043 void wxArrayString::Remove(const wxChar
*sz
)
2045 int iIndex
= Index(sz
);
2047 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2048 wxT("removing inexistent element in wxArrayString::Remove") );
2053 // ----------------------------------------------------------------------------
2055 // ----------------------------------------------------------------------------
2057 // we can only sort one array at a time with the quick-sort based
2060 // need a critical section to protect access to gs_compareFunction and
2061 // gs_sortAscending variables
2062 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2064 // call this before the value of the global sort vars is changed/after
2065 // you're finished with them
2066 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2067 gs_critsectStringSort = new wxCriticalSection; \
2068 gs_critsectStringSort->Enter()
2069 #define END_SORT() gs_critsectStringSort->Leave(); \
2070 delete gs_critsectStringSort; \
2071 gs_critsectStringSort = NULL
2073 #define START_SORT()
2075 #endif // wxUSE_THREADS
2077 // function to use for string comparaison
2078 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2080 // if we don't use the compare function, this flag tells us if we sort the
2081 // array in ascending or descending order
2082 static bool gs_sortAscending
= TRUE
;
2084 // function which is called by quick sort
2085 static int LINKAGEMODE
wxStringCompareFunction(const void *first
, const void *second
)
2087 wxString
*strFirst
= (wxString
*)first
;
2088 wxString
*strSecond
= (wxString
*)second
;
2090 if ( gs_compareFunction
) {
2091 return gs_compareFunction(*strFirst
, *strSecond
);
2094 // maybe we should use wxStrcoll
2095 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
2097 return gs_sortAscending
? result
: -result
;
2101 // sort array elements using passed comparaison function
2102 void wxArrayString::Sort(CompareFunction compareFunction
)
2106 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2107 gs_compareFunction
= compareFunction
;
2114 void wxArrayString::Sort(bool reverseOrder
)
2118 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2119 gs_sortAscending
= !reverseOrder
;
2126 void wxArrayString::DoSort()
2128 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2130 // just sort the pointers using qsort() - of course it only works because
2131 // wxString() *is* a pointer to its data
2132 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);