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)
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
);
209 #endif // Unicode/ANSI
212 extern int WXDLLEXPORT
wxSnprintf(wxChar
*buf
, size_t len
,
213 const wxChar
*format
, ...)
216 va_start(argptr
, format
);
218 int iLen
= wxVsnprintf(buf
, len
, format
, argptr
);
225 // ----------------------------------------------------------------------------
227 // ----------------------------------------------------------------------------
229 // this small class is used to gather statistics for performance tuning
230 //#define WXSTRING_STATISTICS
231 #ifdef WXSTRING_STATISTICS
235 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
237 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
239 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
242 size_t m_nCount
, m_nTotal
;
244 } g_averageLength("allocation size"),
245 g_averageSummandLength("summand length"),
246 g_averageConcatHit("hit probability in concat"),
247 g_averageInitialLength("initial string length");
249 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
251 #define STATISTICS_ADD(av, val)
252 #endif // WXSTRING_STATISTICS
254 // ===========================================================================
255 // wxString class core
256 // ===========================================================================
258 // ---------------------------------------------------------------------------
260 // ---------------------------------------------------------------------------
262 // constructs string of <nLength> copies of character <ch>
263 wxString::wxString(wxChar ch
, size_t nLength
)
268 AllocBuffer(nLength
);
271 // memset only works on char
272 for (size_t n
=0; n
<nLength
; n
++) m_pchData
[n
] = ch
;
274 memset(m_pchData
, ch
, nLength
);
279 // takes nLength elements of psz starting at nPos
280 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
284 wxASSERT( nPos
<= wxStrlen(psz
) );
286 if ( nLength
== wxSTRING_MAXLEN
)
287 nLength
= wxStrlen(psz
+ nPos
);
289 STATISTICS_ADD(InitialLength
, nLength
);
292 // trailing '\0' is written in AllocBuffer()
293 AllocBuffer(nLength
);
294 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
298 #ifdef wxSTD_STRING_COMPATIBILITY
300 // poor man's iterators are "void *" pointers
301 wxString::wxString(const void *pStart
, const void *pEnd
)
303 InitWith((const wxChar
*)pStart
, 0,
304 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
307 #endif //std::string compatibility
311 // from multibyte string
312 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
314 // first get necessary size
315 size_t nLen
= psz
? conv
.MB2WC((wchar_t *) NULL
, psz
, 0) : 0;
317 // nLength is number of *Unicode* characters here!
318 if ((nLen
!= (size_t)-1) && (nLen
> nLength
))
322 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
324 conv
.MB2WC(m_pchData
, psz
, nLen
);
335 wxString::wxString(const wchar_t *pwz
)
337 // first get necessary size
338 size_t nLen
= pwz
? wxWC2MB((char *) NULL
, pwz
, 0) : 0;
341 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
343 wxWC2MB(m_pchData
, pwz
, nLen
);
349 #endif // wxUSE_WCHAR_T
351 #endif // Unicode/ANSI
353 // ---------------------------------------------------------------------------
355 // ---------------------------------------------------------------------------
357 // allocates memory needed to store a C string of length nLen
358 void wxString::AllocBuffer(size_t nLen
)
360 wxASSERT( nLen
> 0 ); //
361 wxASSERT( nLen
<= INT_MAX
-1 ); // max size (enough room for 1 extra)
363 STATISTICS_ADD(Length
, nLen
);
366 // 1) one extra character for '\0' termination
367 // 2) sizeof(wxStringData) for housekeeping info
368 wxStringData
* pData
= (wxStringData
*)
369 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
371 pData
->nDataLength
= nLen
;
372 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
373 m_pchData
= pData
->data(); // data starts after wxStringData
374 m_pchData
[nLen
] = wxT('\0');
377 // must be called before changing this string
378 void wxString::CopyBeforeWrite()
380 wxStringData
* pData
= GetStringData();
382 if ( pData
->IsShared() ) {
383 pData
->Unlock(); // memory not freed because shared
384 size_t nLen
= pData
->nDataLength
;
386 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
389 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
392 // must be called before replacing contents of this string
393 void wxString::AllocBeforeWrite(size_t nLen
)
395 wxASSERT( nLen
!= 0 ); // doesn't make any sense
397 // must not share string and must have enough space
398 wxStringData
* pData
= GetStringData();
399 if ( pData
->IsShared() || pData
->IsEmpty() ) {
400 // can't work with old buffer, get new one
405 if ( nLen
> pData
->nAllocLength
) {
406 // realloc the buffer instead of calling malloc() again, this is more
408 STATISTICS_ADD(Length
, nLen
);
412 wxStringData
*pDataOld
= pData
;
413 pData
= (wxStringData
*)
414 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
419 // FIXME we're going to crash...
423 pData
->nAllocLength
= nLen
;
424 m_pchData
= pData
->data();
427 // now we have enough space, just update the string length
428 pData
->nDataLength
= nLen
;
431 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
434 // allocate enough memory for nLen characters
435 void wxString::Alloc(size_t nLen
)
437 wxStringData
*pData
= GetStringData();
438 if ( pData
->nAllocLength
<= nLen
) {
439 if ( pData
->IsEmpty() ) {
442 wxStringData
* pData
= (wxStringData
*)
443 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
445 pData
->nDataLength
= 0;
446 pData
->nAllocLength
= nLen
;
447 m_pchData
= pData
->data(); // data starts after wxStringData
448 m_pchData
[0u] = wxT('\0');
450 else if ( pData
->IsShared() ) {
451 pData
->Unlock(); // memory not freed because shared
452 size_t nOldLen
= pData
->nDataLength
;
454 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
459 wxStringData
*pDataOld
= pData
;
460 wxStringData
*p
= (wxStringData
*)
461 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
467 // FIXME what to do on memory error?
471 // it's not important if the pointer changed or not (the check for this
472 // is not faster than assigning to m_pchData in all cases)
473 p
->nAllocLength
= nLen
;
474 m_pchData
= p
->data();
477 //else: we've already got enough
480 // shrink to minimal size (releasing extra memory)
481 void wxString::Shrink()
483 wxStringData
*pData
= GetStringData();
485 // this variable is unused in release build, so avoid the compiler warning
486 // by just not declaring it
490 realloc(pData
, sizeof(wxStringData
) + (pData
->nDataLength
+ 1)*sizeof(wxChar
));
492 // we rely on a reasonable realloc() implementation here - so far I haven't
493 // seen any which wouldn't behave like this
495 wxASSERT( p
!= NULL
); // can't free memory?
496 wxASSERT( p
== pData
); // we're decrementing the size - block shouldn't move!
499 // get the pointer to writable buffer of (at least) nLen bytes
500 wxChar
*wxString::GetWriteBuf(size_t nLen
)
502 AllocBeforeWrite(nLen
);
504 wxASSERT( GetStringData()->nRefs
== 1 );
505 GetStringData()->Validate(FALSE
);
510 // put string back in a reasonable state after GetWriteBuf
511 void wxString::UngetWriteBuf()
513 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
514 GetStringData()->Validate(TRUE
);
517 // ---------------------------------------------------------------------------
519 // ---------------------------------------------------------------------------
521 // all functions are inline in string.h
523 // ---------------------------------------------------------------------------
524 // assignment operators
525 // ---------------------------------------------------------------------------
527 // helper function: does real copy
528 void wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
530 if ( nSrcLen
== 0 ) {
534 AllocBeforeWrite(nSrcLen
);
535 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
536 GetStringData()->nDataLength
= nSrcLen
;
537 m_pchData
[nSrcLen
] = wxT('\0');
541 // assigns one string to another
542 wxString
& wxString::operator=(const wxString
& stringSrc
)
544 wxASSERT( stringSrc
.GetStringData()->IsValid() );
546 // don't copy string over itself
547 if ( m_pchData
!= stringSrc
.m_pchData
) {
548 if ( stringSrc
.GetStringData()->IsEmpty() ) {
553 GetStringData()->Unlock();
554 m_pchData
= stringSrc
.m_pchData
;
555 GetStringData()->Lock();
562 // assigns a single character
563 wxString
& wxString::operator=(wxChar ch
)
570 wxString
& wxString::operator=(const wxChar
*psz
)
572 AssignCopy(wxStrlen(psz
), psz
);
578 // same as 'signed char' variant
579 wxString
& wxString::operator=(const unsigned char* psz
)
581 *this = (const char *)psz
;
586 wxString
& wxString::operator=(const wchar_t *pwz
)
596 // ---------------------------------------------------------------------------
597 // string concatenation
598 // ---------------------------------------------------------------------------
600 // add something to this string
601 void wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
603 STATISTICS_ADD(SummandLength
, nSrcLen
);
605 // concatenating an empty string is a NOP
607 wxStringData
*pData
= GetStringData();
608 size_t nLen
= pData
->nDataLength
;
609 size_t nNewLen
= nLen
+ nSrcLen
;
611 // alloc new buffer if current is too small
612 if ( pData
->IsShared() ) {
613 STATISTICS_ADD(ConcatHit
, 0);
615 // we have to allocate another buffer
616 wxStringData
* pOldData
= GetStringData();
617 AllocBuffer(nNewLen
);
618 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
621 else if ( nNewLen
> pData
->nAllocLength
) {
622 STATISTICS_ADD(ConcatHit
, 0);
624 // we have to grow the buffer
628 STATISTICS_ADD(ConcatHit
, 1);
630 // the buffer is already big enough
633 // should be enough space
634 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
636 // fast concatenation - all is done in our buffer
637 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
639 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
640 GetStringData()->nDataLength
= nNewLen
; // and fix the length
642 //else: the string to append was empty
646 * concatenation functions come in 5 flavours:
648 * char + string and string + char
649 * C str + string and string + C str
652 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
654 wxASSERT( string1
.GetStringData()->IsValid() );
655 wxASSERT( string2
.GetStringData()->IsValid() );
657 wxString s
= string1
;
663 wxString
operator+(const wxString
& string
, wxChar ch
)
665 wxASSERT( string
.GetStringData()->IsValid() );
673 wxString
operator+(wxChar ch
, const wxString
& string
)
675 wxASSERT( string
.GetStringData()->IsValid() );
683 wxString
operator+(const wxString
& string
, const wxChar
*psz
)
685 wxASSERT( string
.GetStringData()->IsValid() );
688 s
.Alloc(wxStrlen(psz
) + string
.Len());
695 wxString
operator+(const wxChar
*psz
, const wxString
& string
)
697 wxASSERT( string
.GetStringData()->IsValid() );
700 s
.Alloc(wxStrlen(psz
) + string
.Len());
707 // ===========================================================================
708 // other common string functions
709 // ===========================================================================
711 // ---------------------------------------------------------------------------
712 // simple sub-string extraction
713 // ---------------------------------------------------------------------------
715 // helper function: clone the data attached to this string
716 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
718 if ( nCopyLen
== 0 ) {
722 dest
.AllocBuffer(nCopyLen
);
723 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
727 // extract string of length nCount starting at nFirst
728 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
730 wxStringData
*pData
= GetStringData();
731 size_t nLen
= pData
->nDataLength
;
733 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
734 if ( nCount
== wxSTRING_MAXLEN
)
736 nCount
= nLen
- nFirst
;
739 // out-of-bounds requests return sensible things
740 if ( nFirst
+ nCount
> nLen
)
742 nCount
= nLen
- nFirst
;
747 // AllocCopy() will return empty string
752 AllocCopy(dest
, nCount
, nFirst
);
757 // extract nCount last (rightmost) characters
758 wxString
wxString::Right(size_t nCount
) const
760 if ( nCount
> (size_t)GetStringData()->nDataLength
)
761 nCount
= GetStringData()->nDataLength
;
764 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
768 // get all characters after the last occurence of ch
769 // (returns the whole string if ch not found)
770 wxString
wxString::AfterLast(wxChar ch
) const
773 int iPos
= Find(ch
, TRUE
);
774 if ( iPos
== wxNOT_FOUND
)
777 str
= c_str() + iPos
+ 1;
782 // extract nCount first (leftmost) characters
783 wxString
wxString::Left(size_t nCount
) const
785 if ( nCount
> (size_t)GetStringData()->nDataLength
)
786 nCount
= GetStringData()->nDataLength
;
789 AllocCopy(dest
, nCount
, 0);
793 // get all characters before the first occurence of ch
794 // (returns the whole string if ch not found)
795 wxString
wxString::BeforeFirst(wxChar ch
) const
798 for ( const wxChar
*pc
= m_pchData
; *pc
!= wxT('\0') && *pc
!= ch
; pc
++ )
804 /// get all characters before the last occurence of ch
805 /// (returns empty string if ch not found)
806 wxString
wxString::BeforeLast(wxChar ch
) const
809 int iPos
= Find(ch
, TRUE
);
810 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
811 str
= wxString(c_str(), iPos
);
816 /// get all characters after the first occurence of ch
817 /// (returns empty string if ch not found)
818 wxString
wxString::AfterFirst(wxChar ch
) const
822 if ( iPos
!= wxNOT_FOUND
)
823 str
= c_str() + iPos
+ 1;
828 // replace first (or all) occurences of some substring with another one
829 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
831 size_t uiCount
= 0; // count of replacements made
833 size_t uiOldLen
= wxStrlen(szOld
);
836 const wxChar
*pCurrent
= m_pchData
;
837 const wxChar
*pSubstr
;
838 while ( *pCurrent
!= wxT('\0') ) {
839 pSubstr
= wxStrstr(pCurrent
, szOld
);
840 if ( pSubstr
== NULL
) {
841 // strTemp is unused if no replacements were made, so avoid the copy
845 strTemp
+= pCurrent
; // copy the rest
846 break; // exit the loop
849 // take chars before match
850 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
852 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
857 if ( !bReplaceAll
) {
858 strTemp
+= pCurrent
; // copy the rest
859 break; // exit the loop
864 // only done if there were replacements, otherwise would have returned above
870 bool wxString::IsAscii() const
872 const wxChar
*s
= (const wxChar
*) *this;
874 if(!isascii(*s
)) return(FALSE
);
880 bool wxString::IsWord() const
882 const wxChar
*s
= (const wxChar
*) *this;
884 if(!wxIsalpha(*s
)) return(FALSE
);
890 bool wxString::IsNumber() const
892 const wxChar
*s
= (const wxChar
*) *this;
894 if(!wxIsdigit(*s
)) return(FALSE
);
900 wxString
wxString::Strip(stripType w
) const
903 if ( w
& leading
) s
.Trim(FALSE
);
904 if ( w
& trailing
) s
.Trim(TRUE
);
908 // ---------------------------------------------------------------------------
910 // ---------------------------------------------------------------------------
912 wxString
& wxString::MakeUpper()
916 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
917 *p
= (wxChar
)wxToupper(*p
);
922 wxString
& wxString::MakeLower()
926 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
927 *p
= (wxChar
)wxTolower(*p
);
932 // ---------------------------------------------------------------------------
933 // trimming and padding
934 // ---------------------------------------------------------------------------
936 // trims spaces (in the sense of isspace) from left or right side
937 wxString
& wxString::Trim(bool bFromRight
)
939 // first check if we're going to modify the string at all
942 (bFromRight
&& wxIsspace(GetChar(Len() - 1))) ||
943 (!bFromRight
&& wxIsspace(GetChar(0u)))
947 // ok, there is at least one space to trim
952 // find last non-space character
953 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
954 while ( wxIsspace(*psz
) && (psz
>= m_pchData
) )
957 // truncate at trailing space start
959 GetStringData()->nDataLength
= psz
- m_pchData
;
963 // find first non-space character
964 const wxChar
*psz
= m_pchData
;
965 while ( wxIsspace(*psz
) )
968 // fix up data and length
969 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
970 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
971 GetStringData()->nDataLength
= nDataLength
;
978 // adds nCount characters chPad to the string from either side
979 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
981 wxString
s(chPad
, nCount
);
994 // truncate the string
995 wxString
& wxString::Truncate(size_t uiLen
)
997 if ( uiLen
< Len() ) {
1000 *(m_pchData
+ uiLen
) = wxT('\0');
1001 GetStringData()->nDataLength
= uiLen
;
1003 //else: nothing to do, string is already short enough
1008 // ---------------------------------------------------------------------------
1009 // finding (return wxNOT_FOUND if not found and index otherwise)
1010 // ---------------------------------------------------------------------------
1013 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1015 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
1017 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1020 // find a sub-string (like strstr)
1021 int wxString::Find(const wxChar
*pszSub
) const
1023 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
1025 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1028 // ---------------------------------------------------------------------------
1029 // stream-like operators
1030 // ---------------------------------------------------------------------------
1031 wxString
& wxString::operator<<(int i
)
1034 res
.Printf(wxT("%d"), i
);
1036 return (*this) << res
;
1039 wxString
& wxString::operator<<(float f
)
1042 res
.Printf(wxT("%f"), f
);
1044 return (*this) << res
;
1047 wxString
& wxString::operator<<(double d
)
1050 res
.Printf(wxT("%g"), d
);
1052 return (*this) << res
;
1055 // ---------------------------------------------------------------------------
1057 // ---------------------------------------------------------------------------
1059 int wxString::Printf(const wxChar
*pszFormat
, ...)
1062 va_start(argptr
, pszFormat
);
1064 int iLen
= PrintfV(pszFormat
, argptr
);
1071 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1073 #if wxUSE_EXPERIMENTAL_PRINTF
1074 // the new implementation
1076 // buffer to avoid dynamic memory allocation each time for small strings
1077 char szScratch
[1024];
1080 for (size_t n
= 0; pszFormat
[n
]; n
++)
1081 if (pszFormat
[n
] == wxT('%')) {
1082 static char s_szFlags
[256] = "%";
1084 bool adj_left
= FALSE
, in_prec
= FALSE
,
1085 prec_dot
= FALSE
, done
= FALSE
;
1087 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1089 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1090 switch (pszFormat
[++n
]) {
1104 s_szFlags
[flagofs
++] = pszFormat
[n
];
1109 s_szFlags
[flagofs
++] = pszFormat
[n
];
1116 // dot will be auto-added to s_szFlags if non-negative number follows
1121 s_szFlags
[flagofs
++] = pszFormat
[n
];
1126 s_szFlags
[flagofs
++] = pszFormat
[n
];
1132 s_szFlags
[flagofs
++] = pszFormat
[n
];
1137 s_szFlags
[flagofs
++] = pszFormat
[n
];
1141 int len
= va_arg(argptr
, int);
1148 adj_left
= !adj_left
;
1149 s_szFlags
[flagofs
++] = '-';
1154 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1157 case wxT('1'): case wxT('2'): case wxT('3'):
1158 case wxT('4'): case wxT('5'): case wxT('6'):
1159 case wxT('7'): case wxT('8'): case wxT('9'):
1163 while ((pszFormat
[n
]>=wxT('0')) && (pszFormat
[n
]<=wxT('9'))) {
1164 s_szFlags
[flagofs
++] = pszFormat
[n
];
1165 len
= len
*10 + (pszFormat
[n
] - wxT('0'));
1168 if (in_prec
) max_width
= len
;
1169 else min_width
= len
;
1170 n
--; // the main loop pre-increments n again
1180 s_szFlags
[flagofs
++] = pszFormat
[n
];
1181 s_szFlags
[flagofs
] = '\0';
1183 int val
= va_arg(argptr
, int);
1184 ::sprintf(szScratch
, s_szFlags
, val
);
1186 else if (ilen
== -1) {
1187 short int val
= va_arg(argptr
, short int);
1188 ::sprintf(szScratch
, s_szFlags
, val
);
1190 else if (ilen
== 1) {
1191 long int val
= va_arg(argptr
, long int);
1192 ::sprintf(szScratch
, s_szFlags
, val
);
1194 else if (ilen
== 2) {
1195 #if SIZEOF_LONG_LONG
1196 long long int val
= va_arg(argptr
, long long int);
1197 ::sprintf(szScratch
, s_szFlags
, val
);
1199 long int val
= va_arg(argptr
, long int);
1200 ::sprintf(szScratch
, s_szFlags
, val
);
1203 else if (ilen
== 3) {
1204 size_t val
= va_arg(argptr
, size_t);
1205 ::sprintf(szScratch
, s_szFlags
, val
);
1207 *this += wxString(szScratch
);
1216 s_szFlags
[flagofs
++] = pszFormat
[n
];
1217 s_szFlags
[flagofs
] = '\0';
1219 long double val
= va_arg(argptr
, long double);
1220 ::sprintf(szScratch
, s_szFlags
, val
);
1222 double val
= va_arg(argptr
, double);
1223 ::sprintf(szScratch
, s_szFlags
, val
);
1225 *this += wxString(szScratch
);
1230 void *val
= va_arg(argptr
, void *);
1232 s_szFlags
[flagofs
++] = pszFormat
[n
];
1233 s_szFlags
[flagofs
] = '\0';
1234 ::sprintf(szScratch
, s_szFlags
, val
);
1235 *this += wxString(szScratch
);
1241 wxChar val
= va_arg(argptr
, int);
1242 // we don't need to honor padding here, do we?
1249 // wx extension: we'll let %hs mean non-Unicode strings
1250 char *val
= va_arg(argptr
, char *);
1252 // ASCII->Unicode constructor handles max_width right
1253 wxString
s(val
, wxConvLibc
, max_width
);
1255 size_t len
= wxSTRING_MAXLEN
;
1257 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1258 } else val
= wxT("(null)");
1259 wxString
s(val
, len
);
1261 if (s
.Len() < min_width
)
1262 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1265 wxChar
*val
= va_arg(argptr
, wxChar
*);
1266 size_t len
= wxSTRING_MAXLEN
;
1268 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1269 } else val
= wxT("(null)");
1270 wxString
s(val
, len
);
1271 if (s
.Len() < min_width
)
1272 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1279 int *val
= va_arg(argptr
, int *);
1282 else if (ilen
== -1) {
1283 short int *val
= va_arg(argptr
, short int *);
1286 else if (ilen
>= 1) {
1287 long int *val
= va_arg(argptr
, long int *);
1293 if (wxIsalpha(pszFormat
[n
]))
1294 // probably some flag not taken care of here yet
1295 s_szFlags
[flagofs
++] = pszFormat
[n
];
1298 *this += wxT('%'); // just to pass the glibc tst-printf.c
1306 } else *this += pszFormat
[n
];
1309 // buffer to avoid dynamic memory allocation each time for small strings
1310 char szScratch
[1024];
1312 // NB: wxVsnprintf() may return either less than the buffer size or -1 if
1313 // there is not enough place depending on implementation
1314 int iLen
= wxVsnprintfA(szScratch
, WXSIZEOF(szScratch
), pszFormat
, argptr
);
1316 // the whole string is in szScratch
1320 bool outOfMemory
= FALSE
;
1321 int size
= 2*WXSIZEOF(szScratch
);
1322 while ( !outOfMemory
) {
1323 char *buf
= GetWriteBuf(size
);
1325 iLen
= wxVsnprintfA(buf
, size
, pszFormat
, argptr
);
1332 // ok, there was enough space
1336 // still not enough, double it again
1340 if ( outOfMemory
) {
1345 #endif // wxUSE_EXPERIMENTAL_PRINTF/!wxUSE_EXPERIMENTAL_PRINTF
1350 // ----------------------------------------------------------------------------
1351 // misc other operations
1352 // ----------------------------------------------------------------------------
1354 // returns TRUE if the string matches the pattern which may contain '*' and
1355 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1357 bool wxString::Matches(const wxChar
*pszMask
) const
1359 // check char by char
1360 const wxChar
*pszTxt
;
1361 for ( pszTxt
= c_str(); *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1362 switch ( *pszMask
) {
1364 if ( *pszTxt
== wxT('\0') )
1367 // pszText and pszMask will be incremented in the loop statement
1373 // ignore special chars immediately following this one
1374 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1377 // if there is nothing more, match
1378 if ( *pszMask
== wxT('\0') )
1381 // are there any other metacharacters in the mask?
1383 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1385 if ( pEndMask
!= NULL
) {
1386 // we have to match the string between two metachars
1387 uiLenMask
= pEndMask
- pszMask
;
1390 // we have to match the remainder of the string
1391 uiLenMask
= wxStrlen(pszMask
);
1394 wxString
strToMatch(pszMask
, uiLenMask
);
1395 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1396 if ( pMatch
== NULL
)
1399 // -1 to compensate "++" in the loop
1400 pszTxt
= pMatch
+ uiLenMask
- 1;
1401 pszMask
+= uiLenMask
- 1;
1406 if ( *pszMask
!= *pszTxt
)
1412 // match only if nothing left
1413 return *pszTxt
== wxT('\0');
1416 // Count the number of chars
1417 int wxString::Freq(wxChar ch
) const
1421 for (int i
= 0; i
< len
; i
++)
1423 if (GetChar(i
) == ch
)
1429 // convert to upper case, return the copy of the string
1430 wxString
wxString::Upper() const
1431 { wxString
s(*this); return s
.MakeUpper(); }
1433 // convert to lower case, return the copy of the string
1434 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1436 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1439 va_start(argptr
, pszFormat
);
1440 int iLen
= PrintfV(pszFormat
, argptr
);
1445 // ---------------------------------------------------------------------------
1446 // standard C++ library string functions
1447 // ---------------------------------------------------------------------------
1448 #ifdef wxSTD_STRING_COMPATIBILITY
1450 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1452 wxASSERT( str
.GetStringData()->IsValid() );
1453 wxASSERT( nPos
<= Len() );
1455 if ( !str
.IsEmpty() ) {
1457 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1458 wxStrncpy(pc
, c_str(), nPos
);
1459 wxStrcpy(pc
+ nPos
, str
);
1460 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1461 strTmp
.UngetWriteBuf();
1468 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1470 wxASSERT( str
.GetStringData()->IsValid() );
1471 wxASSERT( nStart
<= Len() );
1473 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1475 return p
== NULL
? npos
: p
- c_str();
1478 // VC++ 1.5 can't cope with the default argument in the header.
1479 #if !defined(__VISUALC__) || defined(__WIN32__)
1480 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1482 return find(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1486 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1487 #if !defined(__BORLANDC__)
1488 size_t wxString::find(wxChar ch
, size_t nStart
) const
1490 wxASSERT( nStart
<= Len() );
1492 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1494 return p
== NULL
? npos
: p
- c_str();
1498 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1500 wxASSERT( str
.GetStringData()->IsValid() );
1501 wxASSERT( nStart
<= Len() );
1503 // TODO could be made much quicker than that
1504 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1505 while ( p
>= c_str() + str
.Len() ) {
1506 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1507 return p
- str
.Len() - c_str();
1514 // VC++ 1.5 can't cope with the default argument in the header.
1515 #if !defined(__VISUALC__) || defined(__WIN32__)
1516 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1518 return rfind(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1521 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1523 if ( nStart
== npos
)
1529 wxASSERT( nStart
<= Len() );
1532 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1537 size_t result
= p
- c_str();
1538 return ( result
> nStart
) ? npos
: result
;
1542 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1544 const wxChar
*start
= c_str() + nStart
;
1545 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1547 return firstOf
- start
;
1552 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1554 if ( nStart
== npos
)
1560 wxASSERT( nStart
<= Len() );
1563 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1565 if ( wxStrchr(sz
, *p
) )
1572 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1574 if ( nStart
== npos
)
1580 wxASSERT( nStart
<= Len() );
1583 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1584 if ( nAccept
>= length() - nStart
)
1590 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1592 wxASSERT( nStart
<= Len() );
1594 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1603 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1605 if ( nStart
== npos
)
1611 wxASSERT( nStart
<= Len() );
1614 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1616 if ( !wxStrchr(sz
, *p
) )
1623 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1625 if ( nStart
== npos
)
1631 wxASSERT( nStart
<= Len() );
1634 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1643 wxString
wxString::substr(size_t nStart
, size_t nLen
) const
1645 // npos means 'take all'
1649 wxASSERT( nStart
+ nLen
<= Len() );
1651 return wxString(c_str() + nStart
, nLen
== npos
? 0 : nLen
);
1654 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1656 wxString
strTmp(c_str(), nStart
);
1657 if ( nLen
!= npos
) {
1658 wxASSERT( nStart
+ nLen
<= Len() );
1660 strTmp
.append(c_str() + nStart
+ nLen
);
1667 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1669 wxASSERT( nStart
+ nLen
<= wxStrlen(sz
) );
1673 strTmp
.append(c_str(), nStart
);
1675 strTmp
.append(c_str() + nStart
+ nLen
);
1681 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1683 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1686 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1687 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1689 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1692 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1693 const wxChar
* sz
, size_t nCount
)
1695 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1698 #endif //std::string compatibility
1700 // ============================================================================
1702 // ============================================================================
1704 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1705 #define ARRAY_MAXSIZE_INCREMENT 4096
1706 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1707 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1710 #define STRING(p) ((wxString *)(&(p)))
1713 wxArrayString::wxArrayString(bool autoSort
)
1717 m_pItems
= (wxChar
**) NULL
;
1718 m_autoSort
= autoSort
;
1722 wxArrayString::wxArrayString(const wxArrayString
& src
)
1726 m_pItems
= (wxChar
**) NULL
;
1727 m_autoSort
= src
.m_autoSort
;
1732 // assignment operator
1733 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1743 void wxArrayString::Copy(const wxArrayString
& src
)
1745 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1746 Alloc(src
.m_nCount
);
1748 // we can't just copy the pointers here because otherwise we would share
1749 // the strings with another array because strings are ref counted
1751 if ( m_nCount
!= 0 )
1752 memcpy(m_pItems
, src
.m_pItems
, m_nCount
*sizeof(wxChar
*));
1755 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1758 // if the other array is auto sorted too, we're already sorted, but
1759 // otherwise we should rearrange the items
1760 if ( m_autoSort
&& !src
.m_autoSort
)
1765 void wxArrayString::Grow()
1767 // only do it if no more place
1768 if( m_nCount
== m_nSize
) {
1769 if( m_nSize
== 0 ) {
1770 // was empty, alloc some memory
1771 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1772 m_pItems
= new wxChar
*[m_nSize
];
1775 // otherwise when it's called for the first time, nIncrement would be 0
1776 // and the array would never be expanded
1777 #if defined(__VISAGECPP__) && defined(__WXDEBUG__)
1778 int array_size
= ARRAY_DEFAULT_INITIAL_SIZE
;
1779 wxASSERT( array_size
!= 0 );
1781 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE
!= 0 );
1784 // add 50% but not too much
1785 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1786 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1787 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1788 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1789 m_nSize
+= nIncrement
;
1790 wxChar
**pNew
= new wxChar
*[m_nSize
];
1792 // copy data to new location
1793 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1795 // delete old memory (but do not release the strings!)
1796 wxDELETEA(m_pItems
);
1803 void wxArrayString::Free()
1805 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1806 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1810 // deletes all the strings from the list
1811 void wxArrayString::Empty()
1818 // as Empty, but also frees memory
1819 void wxArrayString::Clear()
1826 wxDELETEA(m_pItems
);
1830 wxArrayString::~wxArrayString()
1834 wxDELETEA(m_pItems
);
1837 // pre-allocates memory (frees the previous data!)
1838 void wxArrayString::Alloc(size_t nSize
)
1840 wxASSERT( nSize
> 0 );
1842 // only if old buffer was not big enough
1843 if ( nSize
> m_nSize
) {
1845 wxDELETEA(m_pItems
);
1846 m_pItems
= new wxChar
*[nSize
];
1853 // minimizes the memory usage by freeing unused memory
1854 void wxArrayString::Shrink()
1856 // only do it if we have some memory to free
1857 if( m_nCount
< m_nSize
) {
1858 // allocates exactly as much memory as we need
1859 wxChar
**pNew
= new wxChar
*[m_nCount
];
1861 // copy data to new location
1862 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1868 // searches the array for an item (forward or backwards)
1869 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
1872 // use binary search in the sorted array
1873 wxASSERT_MSG( bCase
&& !bFromEnd
,
1874 wxT("search parameters ignored for auto sorted array") );
1883 res
= wxStrcmp(sz
, m_pItems
[i
]);
1895 // use linear search in unsorted array
1897 if ( m_nCount
> 0 ) {
1898 size_t ui
= m_nCount
;
1900 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1907 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1908 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1917 // add item at the end
1918 size_t wxArrayString::Add(const wxString
& str
)
1921 // insert the string at the correct position to keep the array sorted
1929 res
= wxStrcmp(str
, m_pItems
[i
]);
1940 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
1947 wxASSERT( str
.GetStringData()->IsValid() );
1951 // the string data must not be deleted!
1952 str
.GetStringData()->Lock();
1955 m_pItems
[m_nCount
] = (wxChar
*)str
.c_str(); // const_cast
1961 // add item at the given position
1962 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
1964 wxASSERT( str
.GetStringData()->IsValid() );
1966 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
1970 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
1971 (m_nCount
- nIndex
)*sizeof(wxChar
*));
1973 str
.GetStringData()->Lock();
1974 m_pItems
[nIndex
] = (wxChar
*)str
.c_str();
1979 // removes item from array (by index)
1980 void wxArrayString::Remove(size_t nIndex
)
1982 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Remove") );
1985 Item(nIndex
).GetStringData()->Unlock();
1987 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
1988 (m_nCount
- nIndex
- 1)*sizeof(wxChar
*));
1992 // removes item from array (by value)
1993 void wxArrayString::Remove(const wxChar
*sz
)
1995 int iIndex
= Index(sz
);
1997 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
1998 wxT("removing inexistent element in wxArrayString::Remove") );
2003 // ----------------------------------------------------------------------------
2005 // ----------------------------------------------------------------------------
2007 // we can only sort one array at a time with the quick-sort based
2010 // need a critical section to protect access to gs_compareFunction and
2011 // gs_sortAscending variables
2012 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2014 // call this before the value of the global sort vars is changed/after
2015 // you're finished with them
2016 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2017 gs_critsectStringSort = new wxCriticalSection; \
2018 gs_critsectStringSort->Enter()
2019 #define END_SORT() gs_critsectStringSort->Leave(); \
2020 delete gs_critsectStringSort; \
2021 gs_critsectStringSort = NULL
2023 #define START_SORT()
2025 #endif // wxUSE_THREADS
2027 // function to use for string comparaison
2028 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2030 // if we don't use the compare function, this flag tells us if we sort the
2031 // array in ascending or descending order
2032 static bool gs_sortAscending
= TRUE
;
2034 // function which is called by quick sort
2035 static int LINKAGEMODE
wxStringCompareFunction(const void *first
, const void *second
)
2037 wxString
*strFirst
= (wxString
*)first
;
2038 wxString
*strSecond
= (wxString
*)second
;
2040 if ( gs_compareFunction
) {
2041 return gs_compareFunction(*strFirst
, *strSecond
);
2044 // maybe we should use wxStrcoll
2045 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
2047 return gs_sortAscending
? result
: -result
;
2051 // sort array elements using passed comparaison function
2052 void wxArrayString::Sort(CompareFunction compareFunction
)
2056 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2057 gs_compareFunction
= compareFunction
;
2064 void wxArrayString::Sort(bool reverseOrder
)
2068 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2069 gs_sortAscending
= !reverseOrder
;
2076 void wxArrayString::DoSort()
2078 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2080 // just sort the pointers using qsort() - of course it only works because
2081 // wxString() *is* a pointer to its data
2082 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);