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 wxASSERT( nLen
> 0 ); //
364 wxASSERT( nLen
<= INT_MAX
-1 ); // max size (enough room for 1 extra)
366 STATISTICS_ADD(Length
, nLen
);
369 // 1) one extra character for '\0' termination
370 // 2) sizeof(wxStringData) for housekeeping info
371 wxStringData
* pData
= (wxStringData
*)
372 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
374 pData
->nDataLength
= nLen
;
375 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
376 m_pchData
= pData
->data(); // data starts after wxStringData
377 m_pchData
[nLen
] = wxT('\0');
380 // must be called before changing this string
381 void wxString::CopyBeforeWrite()
383 wxStringData
* pData
= GetStringData();
385 if ( pData
->IsShared() ) {
386 pData
->Unlock(); // memory not freed because shared
387 size_t nLen
= pData
->nDataLength
;
389 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
392 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
395 // must be called before replacing contents of this string
396 void wxString::AllocBeforeWrite(size_t nLen
)
398 wxASSERT( nLen
!= 0 ); // doesn't make any sense
400 // must not share string and must have enough space
401 wxStringData
* pData
= GetStringData();
402 if ( pData
->IsShared() || pData
->IsEmpty() ) {
403 // can't work with old buffer, get new one
408 if ( nLen
> pData
->nAllocLength
) {
409 // realloc the buffer instead of calling malloc() again, this is more
411 STATISTICS_ADD(Length
, nLen
);
415 wxStringData
*pDataOld
= pData
;
416 pData
= (wxStringData
*)
417 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
422 // FIXME we're going to crash...
426 pData
->nAllocLength
= nLen
;
427 m_pchData
= pData
->data();
430 // now we have enough space, just update the string length
431 pData
->nDataLength
= nLen
;
434 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
437 // allocate enough memory for nLen characters
438 void wxString::Alloc(size_t nLen
)
440 wxStringData
*pData
= GetStringData();
441 if ( pData
->nAllocLength
<= nLen
) {
442 if ( pData
->IsEmpty() ) {
445 wxStringData
* pData
= (wxStringData
*)
446 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
448 pData
->nDataLength
= 0;
449 pData
->nAllocLength
= nLen
;
450 m_pchData
= pData
->data(); // data starts after wxStringData
451 m_pchData
[0u] = wxT('\0');
453 else if ( pData
->IsShared() ) {
454 pData
->Unlock(); // memory not freed because shared
455 size_t nOldLen
= pData
->nDataLength
;
457 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
462 wxStringData
*pDataOld
= pData
;
463 wxStringData
*p
= (wxStringData
*)
464 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
470 // FIXME what to do on memory error?
474 // it's not important if the pointer changed or not (the check for this
475 // is not faster than assigning to m_pchData in all cases)
476 p
->nAllocLength
= nLen
;
477 m_pchData
= p
->data();
480 //else: we've already got enough
483 // shrink to minimal size (releasing extra memory)
484 void wxString::Shrink()
486 wxStringData
*pData
= GetStringData();
488 // this variable is unused in release build, so avoid the compiler warning
489 // by just not declaring it
493 realloc(pData
, sizeof(wxStringData
) + (pData
->nDataLength
+ 1)*sizeof(wxChar
));
495 // we rely on a reasonable realloc() implementation here - so far I haven't
496 // seen any which wouldn't behave like this
498 wxASSERT( p
!= NULL
); // can't free memory?
499 wxASSERT( p
== pData
); // we're decrementing the size - block shouldn't move!
502 // get the pointer to writable buffer of (at least) nLen bytes
503 wxChar
*wxString::GetWriteBuf(size_t nLen
)
505 AllocBeforeWrite(nLen
);
507 wxASSERT( GetStringData()->nRefs
== 1 );
508 GetStringData()->Validate(FALSE
);
513 // put string back in a reasonable state after GetWriteBuf
514 void wxString::UngetWriteBuf()
516 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
517 GetStringData()->Validate(TRUE
);
520 // ---------------------------------------------------------------------------
522 // ---------------------------------------------------------------------------
524 // all functions are inline in string.h
526 // ---------------------------------------------------------------------------
527 // assignment operators
528 // ---------------------------------------------------------------------------
530 // helper function: does real copy
531 void wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
533 if ( nSrcLen
== 0 ) {
537 AllocBeforeWrite(nSrcLen
);
538 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
539 GetStringData()->nDataLength
= nSrcLen
;
540 m_pchData
[nSrcLen
] = wxT('\0');
544 // assigns one string to another
545 wxString
& wxString::operator=(const wxString
& stringSrc
)
547 wxASSERT( stringSrc
.GetStringData()->IsValid() );
549 // don't copy string over itself
550 if ( m_pchData
!= stringSrc
.m_pchData
) {
551 if ( stringSrc
.GetStringData()->IsEmpty() ) {
556 GetStringData()->Unlock();
557 m_pchData
= stringSrc
.m_pchData
;
558 GetStringData()->Lock();
565 // assigns a single character
566 wxString
& wxString::operator=(wxChar ch
)
573 wxString
& wxString::operator=(const wxChar
*psz
)
575 AssignCopy(wxStrlen(psz
), psz
);
581 // same as 'signed char' variant
582 wxString
& wxString::operator=(const unsigned char* psz
)
584 *this = (const char *)psz
;
589 wxString
& wxString::operator=(const wchar_t *pwz
)
599 // ---------------------------------------------------------------------------
600 // string concatenation
601 // ---------------------------------------------------------------------------
603 // add something to this string
604 void wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
606 STATISTICS_ADD(SummandLength
, nSrcLen
);
608 // concatenating an empty string is a NOP
610 wxStringData
*pData
= GetStringData();
611 size_t nLen
= pData
->nDataLength
;
612 size_t nNewLen
= nLen
+ nSrcLen
;
614 // alloc new buffer if current is too small
615 if ( pData
->IsShared() ) {
616 STATISTICS_ADD(ConcatHit
, 0);
618 // we have to allocate another buffer
619 wxStringData
* pOldData
= GetStringData();
620 AllocBuffer(nNewLen
);
621 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
624 else if ( nNewLen
> pData
->nAllocLength
) {
625 STATISTICS_ADD(ConcatHit
, 0);
627 // we have to grow the buffer
631 STATISTICS_ADD(ConcatHit
, 1);
633 // the buffer is already big enough
636 // should be enough space
637 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
639 // fast concatenation - all is done in our buffer
640 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
642 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
643 GetStringData()->nDataLength
= nNewLen
; // and fix the length
645 //else: the string to append was empty
649 * concatenation functions come in 5 flavours:
651 * char + string and string + char
652 * C str + string and string + C str
655 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
657 wxASSERT( string1
.GetStringData()->IsValid() );
658 wxASSERT( string2
.GetStringData()->IsValid() );
660 wxString s
= string1
;
666 wxString
operator+(const wxString
& string
, wxChar ch
)
668 wxASSERT( string
.GetStringData()->IsValid() );
676 wxString
operator+(wxChar ch
, const wxString
& string
)
678 wxASSERT( string
.GetStringData()->IsValid() );
686 wxString
operator+(const wxString
& string
, const wxChar
*psz
)
688 wxASSERT( string
.GetStringData()->IsValid() );
691 s
.Alloc(wxStrlen(psz
) + string
.Len());
698 wxString
operator+(const wxChar
*psz
, const wxString
& string
)
700 wxASSERT( string
.GetStringData()->IsValid() );
703 s
.Alloc(wxStrlen(psz
) + string
.Len());
710 // ===========================================================================
711 // other common string functions
712 // ===========================================================================
714 // ---------------------------------------------------------------------------
715 // simple sub-string extraction
716 // ---------------------------------------------------------------------------
718 // helper function: clone the data attached to this string
719 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
721 if ( nCopyLen
== 0 ) {
725 dest
.AllocBuffer(nCopyLen
);
726 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
730 // extract string of length nCount starting at nFirst
731 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
733 wxStringData
*pData
= GetStringData();
734 size_t nLen
= pData
->nDataLength
;
736 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
737 if ( nCount
== wxSTRING_MAXLEN
)
739 nCount
= nLen
- nFirst
;
742 // out-of-bounds requests return sensible things
743 if ( nFirst
+ nCount
> nLen
)
745 nCount
= nLen
- nFirst
;
750 // AllocCopy() will return empty string
755 AllocCopy(dest
, nCount
, nFirst
);
760 // extract nCount last (rightmost) characters
761 wxString
wxString::Right(size_t nCount
) const
763 if ( nCount
> (size_t)GetStringData()->nDataLength
)
764 nCount
= GetStringData()->nDataLength
;
767 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
771 // get all characters after the last occurence of ch
772 // (returns the whole string if ch not found)
773 wxString
wxString::AfterLast(wxChar ch
) const
776 int iPos
= Find(ch
, TRUE
);
777 if ( iPos
== wxNOT_FOUND
)
780 str
= c_str() + iPos
+ 1;
785 // extract nCount first (leftmost) characters
786 wxString
wxString::Left(size_t nCount
) const
788 if ( nCount
> (size_t)GetStringData()->nDataLength
)
789 nCount
= GetStringData()->nDataLength
;
792 AllocCopy(dest
, nCount
, 0);
796 // get all characters before the first occurence of ch
797 // (returns the whole string if ch not found)
798 wxString
wxString::BeforeFirst(wxChar ch
) const
801 for ( const wxChar
*pc
= m_pchData
; *pc
!= wxT('\0') && *pc
!= ch
; pc
++ )
807 /// get all characters before the last occurence of ch
808 /// (returns empty string if ch not found)
809 wxString
wxString::BeforeLast(wxChar ch
) const
812 int iPos
= Find(ch
, TRUE
);
813 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
814 str
= wxString(c_str(), iPos
);
819 /// get all characters after the first occurence of ch
820 /// (returns empty string if ch not found)
821 wxString
wxString::AfterFirst(wxChar ch
) const
825 if ( iPos
!= wxNOT_FOUND
)
826 str
= c_str() + iPos
+ 1;
831 // replace first (or all) occurences of some substring with another one
832 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
834 size_t uiCount
= 0; // count of replacements made
836 size_t uiOldLen
= wxStrlen(szOld
);
839 const wxChar
*pCurrent
= m_pchData
;
840 const wxChar
*pSubstr
;
841 while ( *pCurrent
!= wxT('\0') ) {
842 pSubstr
= wxStrstr(pCurrent
, szOld
);
843 if ( pSubstr
== NULL
) {
844 // strTemp is unused if no replacements were made, so avoid the copy
848 strTemp
+= pCurrent
; // copy the rest
849 break; // exit the loop
852 // take chars before match
853 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
855 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
860 if ( !bReplaceAll
) {
861 strTemp
+= pCurrent
; // copy the rest
862 break; // exit the loop
867 // only done if there were replacements, otherwise would have returned above
873 bool wxString::IsAscii() const
875 const wxChar
*s
= (const wxChar
*) *this;
877 if(!isascii(*s
)) return(FALSE
);
883 bool wxString::IsWord() const
885 const wxChar
*s
= (const wxChar
*) *this;
887 if(!wxIsalpha(*s
)) return(FALSE
);
893 bool wxString::IsNumber() const
895 const wxChar
*s
= (const wxChar
*) *this;
897 if(!wxIsdigit(*s
)) return(FALSE
);
903 wxString
wxString::Strip(stripType w
) const
906 if ( w
& leading
) s
.Trim(FALSE
);
907 if ( w
& trailing
) s
.Trim(TRUE
);
911 // ---------------------------------------------------------------------------
913 // ---------------------------------------------------------------------------
915 wxString
& wxString::MakeUpper()
919 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
920 *p
= (wxChar
)wxToupper(*p
);
925 wxString
& wxString::MakeLower()
929 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
930 *p
= (wxChar
)wxTolower(*p
);
935 // ---------------------------------------------------------------------------
936 // trimming and padding
937 // ---------------------------------------------------------------------------
939 // trims spaces (in the sense of isspace) from left or right side
940 wxString
& wxString::Trim(bool bFromRight
)
942 // first check if we're going to modify the string at all
945 (bFromRight
&& wxIsspace(GetChar(Len() - 1))) ||
946 (!bFromRight
&& wxIsspace(GetChar(0u)))
950 // ok, there is at least one space to trim
955 // find last non-space character
956 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
957 while ( wxIsspace(*psz
) && (psz
>= m_pchData
) )
960 // truncate at trailing space start
962 GetStringData()->nDataLength
= psz
- m_pchData
;
966 // find first non-space character
967 const wxChar
*psz
= m_pchData
;
968 while ( wxIsspace(*psz
) )
971 // fix up data and length
972 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
973 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
974 GetStringData()->nDataLength
= nDataLength
;
981 // adds nCount characters chPad to the string from either side
982 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
984 wxString
s(chPad
, nCount
);
997 // truncate the string
998 wxString
& wxString::Truncate(size_t uiLen
)
1000 if ( uiLen
< Len() ) {
1003 *(m_pchData
+ uiLen
) = wxT('\0');
1004 GetStringData()->nDataLength
= uiLen
;
1006 //else: nothing to do, string is already short enough
1011 // ---------------------------------------------------------------------------
1012 // finding (return wxNOT_FOUND if not found and index otherwise)
1013 // ---------------------------------------------------------------------------
1016 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1018 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
1020 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1023 // find a sub-string (like strstr)
1024 int wxString::Find(const wxChar
*pszSub
) const
1026 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
1028 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1031 // ----------------------------------------------------------------------------
1032 // conversion to numbers
1033 // ----------------------------------------------------------------------------
1035 bool wxString::ToLong(long *val
) const
1037 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToLong") );
1039 const wxChar
*start
= c_str();
1041 *val
= wxStrtol(start
, &end
, 10);
1043 // return TRUE only if scan was stopped by the terminating NUL and if the
1044 // string was not empty to start with
1045 return !*end
&& (end
!= start
);
1048 bool wxString::ToULong(unsigned long *val
) const
1050 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToULong") );
1052 const wxChar
*start
= c_str();
1054 *val
= wxStrtoul(start
, &end
, 10);
1056 // return TRUE only if scan was stopped by the terminating NUL and if the
1057 // string was not empty to start with
1058 return !*end
&& (end
!= start
);
1061 bool wxString::ToDouble(double *val
) const
1063 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToDouble") );
1065 const wxChar
*start
= c_str();
1067 *val
= wxStrtod(start
, &end
);
1069 // return TRUE only if scan was stopped by the terminating NUL and if the
1070 // string was not empty to start with
1071 return !*end
&& (end
!= start
);
1074 // ---------------------------------------------------------------------------
1075 // stream-like operators
1076 // ---------------------------------------------------------------------------
1077 wxString
& wxString::operator<<(int i
)
1080 res
.Printf(wxT("%d"), i
);
1082 return (*this) << res
;
1085 wxString
& wxString::operator<<(float f
)
1088 res
.Printf(wxT("%f"), f
);
1090 return (*this) << res
;
1093 wxString
& wxString::operator<<(double d
)
1096 res
.Printf(wxT("%g"), d
);
1098 return (*this) << res
;
1101 // ---------------------------------------------------------------------------
1103 // ---------------------------------------------------------------------------
1106 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1109 va_start(argptr
, pszFormat
);
1111 wxString s
= FormatV(pszFormat
, argptr
);
1119 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1122 s
.Printf(pszFormat
, argptr
);
1126 int wxString::Printf(const wxChar
*pszFormat
, ...)
1129 va_start(argptr
, pszFormat
);
1131 int iLen
= PrintfV(pszFormat
, argptr
);
1138 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1140 #if wxUSE_EXPERIMENTAL_PRINTF
1141 // the new implementation
1143 // buffer to avoid dynamic memory allocation each time for small strings
1144 char szScratch
[1024];
1147 for (size_t n
= 0; pszFormat
[n
]; n
++)
1148 if (pszFormat
[n
] == wxT('%')) {
1149 static char s_szFlags
[256] = "%";
1151 bool adj_left
= FALSE
, in_prec
= FALSE
,
1152 prec_dot
= FALSE
, done
= FALSE
;
1154 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1156 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1157 switch (pszFormat
[++n
]) {
1171 s_szFlags
[flagofs
++] = pszFormat
[n
];
1176 s_szFlags
[flagofs
++] = pszFormat
[n
];
1183 // dot will be auto-added to s_szFlags if non-negative number follows
1188 s_szFlags
[flagofs
++] = pszFormat
[n
];
1193 s_szFlags
[flagofs
++] = pszFormat
[n
];
1199 s_szFlags
[flagofs
++] = pszFormat
[n
];
1204 s_szFlags
[flagofs
++] = pszFormat
[n
];
1208 int len
= va_arg(argptr
, int);
1215 adj_left
= !adj_left
;
1216 s_szFlags
[flagofs
++] = '-';
1221 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1224 case wxT('1'): case wxT('2'): case wxT('3'):
1225 case wxT('4'): case wxT('5'): case wxT('6'):
1226 case wxT('7'): case wxT('8'): case wxT('9'):
1230 while ((pszFormat
[n
]>=wxT('0')) && (pszFormat
[n
]<=wxT('9'))) {
1231 s_szFlags
[flagofs
++] = pszFormat
[n
];
1232 len
= len
*10 + (pszFormat
[n
] - wxT('0'));
1235 if (in_prec
) max_width
= len
;
1236 else min_width
= len
;
1237 n
--; // the main loop pre-increments n again
1247 s_szFlags
[flagofs
++] = pszFormat
[n
];
1248 s_szFlags
[flagofs
] = '\0';
1250 int val
= va_arg(argptr
, int);
1251 ::sprintf(szScratch
, s_szFlags
, val
);
1253 else if (ilen
== -1) {
1254 short int val
= va_arg(argptr
, short int);
1255 ::sprintf(szScratch
, s_szFlags
, val
);
1257 else if (ilen
== 1) {
1258 long int val
= va_arg(argptr
, long int);
1259 ::sprintf(szScratch
, s_szFlags
, val
);
1261 else if (ilen
== 2) {
1262 #if SIZEOF_LONG_LONG
1263 long long int val
= va_arg(argptr
, long long int);
1264 ::sprintf(szScratch
, s_szFlags
, val
);
1266 long int val
= va_arg(argptr
, long int);
1267 ::sprintf(szScratch
, s_szFlags
, val
);
1270 else if (ilen
== 3) {
1271 size_t val
= va_arg(argptr
, size_t);
1272 ::sprintf(szScratch
, s_szFlags
, val
);
1274 *this += wxString(szScratch
);
1283 s_szFlags
[flagofs
++] = pszFormat
[n
];
1284 s_szFlags
[flagofs
] = '\0';
1286 long double val
= va_arg(argptr
, long double);
1287 ::sprintf(szScratch
, s_szFlags
, val
);
1289 double val
= va_arg(argptr
, double);
1290 ::sprintf(szScratch
, s_szFlags
, val
);
1292 *this += wxString(szScratch
);
1297 void *val
= va_arg(argptr
, void *);
1299 s_szFlags
[flagofs
++] = pszFormat
[n
];
1300 s_szFlags
[flagofs
] = '\0';
1301 ::sprintf(szScratch
, s_szFlags
, val
);
1302 *this += wxString(szScratch
);
1308 wxChar val
= va_arg(argptr
, int);
1309 // we don't need to honor padding here, do we?
1316 // wx extension: we'll let %hs mean non-Unicode strings
1317 char *val
= va_arg(argptr
, char *);
1319 // ASCII->Unicode constructor handles max_width right
1320 wxString
s(val
, wxConvLibc
, max_width
);
1322 size_t len
= wxSTRING_MAXLEN
;
1324 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1325 } else val
= wxT("(null)");
1326 wxString
s(val
, len
);
1328 if (s
.Len() < min_width
)
1329 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1332 wxChar
*val
= va_arg(argptr
, wxChar
*);
1333 size_t len
= wxSTRING_MAXLEN
;
1335 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1336 } else val
= wxT("(null)");
1337 wxString
s(val
, len
);
1338 if (s
.Len() < min_width
)
1339 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1346 int *val
= va_arg(argptr
, int *);
1349 else if (ilen
== -1) {
1350 short int *val
= va_arg(argptr
, short int *);
1353 else if (ilen
>= 1) {
1354 long int *val
= va_arg(argptr
, long int *);
1360 if (wxIsalpha(pszFormat
[n
]))
1361 // probably some flag not taken care of here yet
1362 s_szFlags
[flagofs
++] = pszFormat
[n
];
1365 *this += wxT('%'); // just to pass the glibc tst-printf.c
1373 } else *this += pszFormat
[n
];
1376 // buffer to avoid dynamic memory allocation each time for small strings
1377 char szScratch
[1024];
1379 // NB: wxVsnprintf() may return either less than the buffer size or -1 if
1380 // there is not enough place depending on implementation
1381 int iLen
= wxVsnprintfA(szScratch
, WXSIZEOF(szScratch
), pszFormat
, argptr
);
1383 // the whole string is in szScratch
1387 bool outOfMemory
= FALSE
;
1388 int size
= 2*WXSIZEOF(szScratch
);
1389 while ( !outOfMemory
) {
1390 char *buf
= GetWriteBuf(size
);
1392 iLen
= wxVsnprintfA(buf
, size
, pszFormat
, argptr
);
1399 // ok, there was enough space
1403 // still not enough, double it again
1407 if ( outOfMemory
) {
1412 #endif // wxUSE_EXPERIMENTAL_PRINTF/!wxUSE_EXPERIMENTAL_PRINTF
1417 // ----------------------------------------------------------------------------
1418 // misc other operations
1419 // ----------------------------------------------------------------------------
1421 // returns TRUE if the string matches the pattern which may contain '*' and
1422 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1424 bool wxString::Matches(const wxChar
*pszMask
) const
1426 // check char by char
1427 const wxChar
*pszTxt
;
1428 for ( pszTxt
= c_str(); *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1429 switch ( *pszMask
) {
1431 if ( *pszTxt
== wxT('\0') )
1434 // pszText and pszMask will be incremented in the loop statement
1440 // ignore special chars immediately following this one
1441 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1444 // if there is nothing more, match
1445 if ( *pszMask
== wxT('\0') )
1448 // are there any other metacharacters in the mask?
1450 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1452 if ( pEndMask
!= NULL
) {
1453 // we have to match the string between two metachars
1454 uiLenMask
= pEndMask
- pszMask
;
1457 // we have to match the remainder of the string
1458 uiLenMask
= wxStrlen(pszMask
);
1461 wxString
strToMatch(pszMask
, uiLenMask
);
1462 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1463 if ( pMatch
== NULL
)
1466 // -1 to compensate "++" in the loop
1467 pszTxt
= pMatch
+ uiLenMask
- 1;
1468 pszMask
+= uiLenMask
- 1;
1473 if ( *pszMask
!= *pszTxt
)
1479 // match only if nothing left
1480 return *pszTxt
== wxT('\0');
1483 // Count the number of chars
1484 int wxString::Freq(wxChar ch
) const
1488 for (int i
= 0; i
< len
; i
++)
1490 if (GetChar(i
) == ch
)
1496 // convert to upper case, return the copy of the string
1497 wxString
wxString::Upper() const
1498 { wxString
s(*this); return s
.MakeUpper(); }
1500 // convert to lower case, return the copy of the string
1501 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1503 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1506 va_start(argptr
, pszFormat
);
1507 int iLen
= PrintfV(pszFormat
, argptr
);
1512 // ---------------------------------------------------------------------------
1513 // standard C++ library string functions
1514 // ---------------------------------------------------------------------------
1515 #ifdef wxSTD_STRING_COMPATIBILITY
1517 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1519 wxASSERT( str
.GetStringData()->IsValid() );
1520 wxASSERT( nPos
<= Len() );
1522 if ( !str
.IsEmpty() ) {
1524 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1525 wxStrncpy(pc
, c_str(), nPos
);
1526 wxStrcpy(pc
+ nPos
, str
);
1527 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1528 strTmp
.UngetWriteBuf();
1535 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1537 wxASSERT( str
.GetStringData()->IsValid() );
1538 wxASSERT( nStart
<= Len() );
1540 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1542 return p
== NULL
? npos
: p
- c_str();
1545 // VC++ 1.5 can't cope with the default argument in the header.
1546 #if !defined(__VISUALC__) || defined(__WIN32__)
1547 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1549 return find(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1553 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1554 #if !defined(__BORLANDC__)
1555 size_t wxString::find(wxChar ch
, size_t nStart
) const
1557 wxASSERT( nStart
<= Len() );
1559 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1561 return p
== NULL
? npos
: p
- c_str();
1565 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1567 wxASSERT( str
.GetStringData()->IsValid() );
1568 wxASSERT( nStart
<= Len() );
1570 // TODO could be made much quicker than that
1571 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1572 while ( p
>= c_str() + str
.Len() ) {
1573 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1574 return p
- str
.Len() - c_str();
1581 // VC++ 1.5 can't cope with the default argument in the header.
1582 #if !defined(__VISUALC__) || defined(__WIN32__)
1583 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1585 return rfind(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1588 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1590 if ( nStart
== npos
)
1596 wxASSERT( nStart
<= Len() );
1599 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1604 size_t result
= p
- c_str();
1605 return ( result
> nStart
) ? npos
: result
;
1609 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1611 const wxChar
*start
= c_str() + nStart
;
1612 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1614 return firstOf
- start
;
1619 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1621 if ( nStart
== npos
)
1627 wxASSERT( nStart
<= Len() );
1630 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1632 if ( wxStrchr(sz
, *p
) )
1639 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1641 if ( nStart
== npos
)
1647 wxASSERT( nStart
<= Len() );
1650 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1651 if ( nAccept
>= length() - nStart
)
1657 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1659 wxASSERT( nStart
<= Len() );
1661 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1670 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1672 if ( nStart
== npos
)
1678 wxASSERT( nStart
<= Len() );
1681 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1683 if ( !wxStrchr(sz
, *p
) )
1690 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1692 if ( nStart
== npos
)
1698 wxASSERT( nStart
<= Len() );
1701 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1710 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1712 wxString
strTmp(c_str(), nStart
);
1713 if ( nLen
!= npos
) {
1714 wxASSERT( nStart
+ nLen
<= Len() );
1716 strTmp
.append(c_str() + nStart
+ nLen
);
1723 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1725 wxASSERT( nStart
+ nLen
<= wxStrlen(sz
) );
1729 strTmp
.append(c_str(), nStart
);
1731 strTmp
.append(c_str() + nStart
+ nLen
);
1737 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1739 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1742 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1743 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1745 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1748 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1749 const wxChar
* sz
, size_t nCount
)
1751 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1754 #endif //std::string compatibility
1756 // ============================================================================
1758 // ============================================================================
1760 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1761 #define ARRAY_MAXSIZE_INCREMENT 4096
1762 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1763 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1766 #define STRING(p) ((wxString *)(&(p)))
1769 wxArrayString::wxArrayString(bool autoSort
)
1773 m_pItems
= (wxChar
**) NULL
;
1774 m_autoSort
= autoSort
;
1778 wxArrayString::wxArrayString(const wxArrayString
& src
)
1782 m_pItems
= (wxChar
**) NULL
;
1783 m_autoSort
= src
.m_autoSort
;
1788 // assignment operator
1789 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1799 void wxArrayString::Copy(const wxArrayString
& src
)
1801 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1802 Alloc(src
.m_nCount
);
1804 // we can't just copy the pointers here because otherwise we would share
1805 // the strings with another array because strings are ref counted
1807 if ( m_nCount
!= 0 )
1808 memcpy(m_pItems
, src
.m_pItems
, m_nCount
*sizeof(wxChar
*));
1811 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1814 // if the other array is auto sorted too, we're already sorted, but
1815 // otherwise we should rearrange the items
1816 if ( m_autoSort
&& !src
.m_autoSort
)
1821 void wxArrayString::Grow()
1823 // only do it if no more place
1824 if( m_nCount
== m_nSize
) {
1825 if( m_nSize
== 0 ) {
1826 // was empty, alloc some memory
1827 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1828 m_pItems
= new wxChar
*[m_nSize
];
1831 // otherwise when it's called for the first time, nIncrement would be 0
1832 // and the array would never be expanded
1833 #if defined(__VISAGECPP__) && defined(__WXDEBUG__)
1834 int array_size
= ARRAY_DEFAULT_INITIAL_SIZE
;
1835 wxASSERT( array_size
!= 0 );
1837 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE
!= 0 );
1840 // add 50% but not too much
1841 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1842 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1843 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1844 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1845 m_nSize
+= nIncrement
;
1846 wxChar
**pNew
= new wxChar
*[m_nSize
];
1848 // copy data to new location
1849 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1851 // delete old memory (but do not release the strings!)
1852 wxDELETEA(m_pItems
);
1859 void wxArrayString::Free()
1861 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1862 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1866 // deletes all the strings from the list
1867 void wxArrayString::Empty()
1874 // as Empty, but also frees memory
1875 void wxArrayString::Clear()
1882 wxDELETEA(m_pItems
);
1886 wxArrayString::~wxArrayString()
1890 wxDELETEA(m_pItems
);
1893 // pre-allocates memory (frees the previous data!)
1894 void wxArrayString::Alloc(size_t nSize
)
1896 wxASSERT( nSize
> 0 );
1898 // only if old buffer was not big enough
1899 if ( nSize
> m_nSize
) {
1901 wxDELETEA(m_pItems
);
1902 m_pItems
= new wxChar
*[nSize
];
1909 // minimizes the memory usage by freeing unused memory
1910 void wxArrayString::Shrink()
1912 // only do it if we have some memory to free
1913 if( m_nCount
< m_nSize
) {
1914 // allocates exactly as much memory as we need
1915 wxChar
**pNew
= new wxChar
*[m_nCount
];
1917 // copy data to new location
1918 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1924 // searches the array for an item (forward or backwards)
1925 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
1928 // use binary search in the sorted array
1929 wxASSERT_MSG( bCase
&& !bFromEnd
,
1930 wxT("search parameters ignored for auto sorted array") );
1939 res
= wxStrcmp(sz
, m_pItems
[i
]);
1951 // use linear search in unsorted array
1953 if ( m_nCount
> 0 ) {
1954 size_t ui
= m_nCount
;
1956 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1963 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1964 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1973 // add item at the end
1974 size_t wxArrayString::Add(const wxString
& str
)
1977 // insert the string at the correct position to keep the array sorted
1985 res
= wxStrcmp(str
, m_pItems
[i
]);
1996 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2003 wxASSERT( str
.GetStringData()->IsValid() );
2007 // the string data must not be deleted!
2008 str
.GetStringData()->Lock();
2011 m_pItems
[m_nCount
] = (wxChar
*)str
.c_str(); // const_cast
2017 // add item at the given position
2018 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
2020 wxASSERT( str
.GetStringData()->IsValid() );
2022 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2026 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
2027 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2029 str
.GetStringData()->Lock();
2030 m_pItems
[nIndex
] = (wxChar
*)str
.c_str();
2035 // removes item from array (by index)
2036 void wxArrayString::Remove(size_t nIndex
)
2038 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Remove") );
2041 Item(nIndex
).GetStringData()->Unlock();
2043 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
2044 (m_nCount
- nIndex
- 1)*sizeof(wxChar
*));
2048 // removes item from array (by value)
2049 void wxArrayString::Remove(const wxChar
*sz
)
2051 int iIndex
= Index(sz
);
2053 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2054 wxT("removing inexistent element in wxArrayString::Remove") );
2059 // ----------------------------------------------------------------------------
2061 // ----------------------------------------------------------------------------
2063 // we can only sort one array at a time with the quick-sort based
2066 // need a critical section to protect access to gs_compareFunction and
2067 // gs_sortAscending variables
2068 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2070 // call this before the value of the global sort vars is changed/after
2071 // you're finished with them
2072 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2073 gs_critsectStringSort = new wxCriticalSection; \
2074 gs_critsectStringSort->Enter()
2075 #define END_SORT() gs_critsectStringSort->Leave(); \
2076 delete gs_critsectStringSort; \
2077 gs_critsectStringSort = NULL
2079 #define START_SORT()
2081 #endif // wxUSE_THREADS
2083 // function to use for string comparaison
2084 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2086 // if we don't use the compare function, this flag tells us if we sort the
2087 // array in ascending or descending order
2088 static bool gs_sortAscending
= TRUE
;
2090 // function which is called by quick sort
2091 static int LINKAGEMODE
wxStringCompareFunction(const void *first
, const void *second
)
2093 wxString
*strFirst
= (wxString
*)first
;
2094 wxString
*strSecond
= (wxString
*)second
;
2096 if ( gs_compareFunction
) {
2097 return gs_compareFunction(*strFirst
, *strSecond
);
2100 // maybe we should use wxStrcoll
2101 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
2103 return gs_sortAscending
? result
: -result
;
2107 // sort array elements using passed comparaison function
2108 void wxArrayString::Sort(CompareFunction compareFunction
)
2112 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2113 gs_compareFunction
= compareFunction
;
2120 void wxArrayString::Sort(bool reverseOrder
)
2124 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2125 gs_sortAscending
= !reverseOrder
;
2132 void wxArrayString::DoSort()
2134 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2136 // just sort the pointers using qsort() - of course it only works because
2137 // wxString() *is* a pointer to its data
2138 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);