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 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
89 // must define this static for VA or else you get multiply defined symbols everywhere
90 const unsigned int wxSTRING_MAXLEN
= UINT_MAX
- 100;
94 // empty C style string: points to 'string data' byte of g_strEmpty
95 extern const wxChar WXDLLEXPORT
*wxEmptyString
= &g_strEmpty
.dummy
;
97 // ----------------------------------------------------------------------------
98 // conditional compilation
99 // ----------------------------------------------------------------------------
101 #if !defined(__WXSW__) && wxUSE_UNICODE
102 #ifdef wxUSE_EXPERIMENTAL_PRINTF
103 #undef wxUSE_EXPERIMENTAL_PRINTF
105 #define wxUSE_EXPERIMENTAL_PRINTF 1
108 // we want to find out if the current platform supports vsnprintf()-like
109 // function: for Unix this is done with configure, for Windows we test the
110 // compiler explicitly.
112 // FIXME currently, this is only for ANSI (!Unicode) strings, so we call this
113 // function wxVsnprintfA (A for ANSI), should also find one for Unicode
114 // strings in Unicode build
116 #if defined(__VISUALC__) || (defined(__MINGW32__) && wxUSE_NORLANDER_HEADERS)
117 #define wxVsnprintfA _vsnprintf
119 #elif defined(__WXMAC__)
120 #define wxVsnprintfA vsnprintf
122 #ifdef HAVE_VSNPRINTF
123 #define wxVsnprintfA vsnprintf
125 #endif // Windows/!Windows
128 // in this case we'll use vsprintf() (which is ANSI and thus should be
129 // always available), but it's unsafe because it doesn't check for buffer
130 // size - so give a warning
131 #define wxVsnprintfA(buf, len, format, arg) vsprintf(buf, format, arg)
133 #if defined(__VISUALC__)
134 #pragma message("Using sprintf() because no snprintf()-like function defined")
135 #elif defined(__GNUG__)
136 #warning "Using sprintf() because no snprintf()-like function defined"
138 #endif // no vsnprintf
141 // AIX has vsnprintf, but there's no prototype in the system headers.
142 extern "C" int vsnprintf(char* str
, size_t n
, const char* format
, va_list ap
);
145 // ----------------------------------------------------------------------------
147 // ----------------------------------------------------------------------------
149 #if defined(wxSTD_STRING_COMPATIBILITY) && wxUSE_STD_IOSTREAM
151 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
154 // ATTN: you can _not_ use both of these in the same program!
156 istream
& operator>>(istream
& is
, wxString
& WXUNUSED(str
))
161 streambuf
*sb
= is
.rdbuf();
164 int ch
= sb
->sbumpc ();
166 is
.setstate(ios::eofbit
);
169 else if ( isspace(ch
) ) {
181 if ( str
.length() == 0 )
182 is
.setstate(ios::failbit
);
187 ostream
& operator<<(ostream
& os
, const wxString
& str
)
193 #endif //std::string compatibility
195 extern int WXDLLEXPORT
wxVsnprintf(wxChar
*buf
, size_t len
,
196 const wxChar
*format
, va_list argptr
)
199 // FIXME should use wvsnprintf() or whatever if it's available
201 int iLen
= s
.PrintfV(format
, argptr
);
204 wxStrncpy(buf
, s
.c_str(), iLen
);
209 // vsnprintf() will not terminate the string with '\0' if there is not
210 // enough place, but we want the string to always be NUL terminated
211 int rc
= wxVsnprintfA(buf
, len
- 1, format
, argptr
);
218 #endif // Unicode/ANSI
221 extern int WXDLLEXPORT
wxSnprintf(wxChar
*buf
, size_t len
,
222 const wxChar
*format
, ...)
225 va_start(argptr
, format
);
227 int iLen
= wxVsnprintf(buf
, len
, format
, argptr
);
234 // ----------------------------------------------------------------------------
236 // ----------------------------------------------------------------------------
238 // this small class is used to gather statistics for performance tuning
239 //#define WXSTRING_STATISTICS
240 #ifdef WXSTRING_STATISTICS
244 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
246 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
248 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
251 size_t m_nCount
, m_nTotal
;
253 } g_averageLength("allocation size"),
254 g_averageSummandLength("summand length"),
255 g_averageConcatHit("hit probability in concat"),
256 g_averageInitialLength("initial string length");
258 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
260 #define STATISTICS_ADD(av, val)
261 #endif // WXSTRING_STATISTICS
263 // ===========================================================================
264 // wxString class core
265 // ===========================================================================
267 // ---------------------------------------------------------------------------
269 // ---------------------------------------------------------------------------
271 // constructs string of <nLength> copies of character <ch>
272 wxString::wxString(wxChar ch
, size_t nLength
)
277 AllocBuffer(nLength
);
280 // memset only works on char
281 for (size_t n
=0; n
<nLength
; n
++) m_pchData
[n
] = ch
;
283 memset(m_pchData
, ch
, nLength
);
288 // takes nLength elements of psz starting at nPos
289 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
293 // if the length is not given, assume the string to be NUL terminated
294 if ( nLength
== wxSTRING_MAXLEN
) {
295 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
297 nLength
= wxStrlen(psz
+ nPos
);
300 STATISTICS_ADD(InitialLength
, nLength
);
303 // trailing '\0' is written in AllocBuffer()
304 AllocBuffer(nLength
);
305 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
309 #ifdef wxSTD_STRING_COMPATIBILITY
311 // poor man's iterators are "void *" pointers
312 wxString::wxString(const void *pStart
, const void *pEnd
)
314 InitWith((const wxChar
*)pStart
, 0,
315 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
318 #endif //std::string compatibility
322 // from multibyte string
323 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
325 // first get necessary size
326 size_t nLen
= psz
? conv
.MB2WC((wchar_t *) NULL
, psz
, 0) : 0;
328 // nLength is number of *Unicode* characters here!
329 if ((nLen
!= (size_t)-1) && (nLen
> nLength
))
333 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
335 conv
.MB2WC(m_pchData
, psz
, nLen
);
346 wxString::wxString(const wchar_t *pwz
, wxMBConv
& conv
)
348 // first get necessary size
349 size_t nLen
= pwz
? conv
.WC2MB((char *) NULL
, pwz
, 0) : 0;
352 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
354 conv
.WC2MB(m_pchData
, pwz
, nLen
);
360 #endif // wxUSE_WCHAR_T
362 #endif // Unicode/ANSI
364 // ---------------------------------------------------------------------------
366 // ---------------------------------------------------------------------------
368 // allocates memory needed to store a C string of length nLen
369 void wxString::AllocBuffer(size_t nLen
)
371 // allocating 0 sized buffer doesn't make sense, all empty strings should
373 wxASSERT( nLen
> 0 );
375 // make sure that we don't overflow
376 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
377 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
379 STATISTICS_ADD(Length
, nLen
);
382 // 1) one extra character for '\0' termination
383 // 2) sizeof(wxStringData) for housekeeping info
384 wxStringData
* pData
= (wxStringData
*)
385 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
387 pData
->nDataLength
= nLen
;
388 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
389 m_pchData
= pData
->data(); // data starts after wxStringData
390 m_pchData
[nLen
] = wxT('\0');
393 // must be called before changing this string
394 void wxString::CopyBeforeWrite()
396 wxStringData
* pData
= GetStringData();
398 if ( pData
->IsShared() ) {
399 pData
->Unlock(); // memory not freed because shared
400 size_t nLen
= pData
->nDataLength
;
402 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
405 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
408 // must be called before replacing contents of this string
409 void wxString::AllocBeforeWrite(size_t nLen
)
411 wxASSERT( nLen
!= 0 ); // doesn't make any sense
413 // must not share string and must have enough space
414 wxStringData
* pData
= GetStringData();
415 if ( pData
->IsShared() || pData
->IsEmpty() ) {
416 // can't work with old buffer, get new one
421 if ( nLen
> pData
->nAllocLength
) {
422 // realloc the buffer instead of calling malloc() again, this is more
424 STATISTICS_ADD(Length
, nLen
);
428 wxStringData
*pDataOld
= pData
;
429 pData
= (wxStringData
*)
430 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
435 // FIXME we're going to crash...
439 pData
->nAllocLength
= nLen
;
440 m_pchData
= pData
->data();
443 // now we have enough space, just update the string length
444 pData
->nDataLength
= nLen
;
447 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
450 // allocate enough memory for nLen characters
451 void wxString::Alloc(size_t nLen
)
453 wxStringData
*pData
= GetStringData();
454 if ( pData
->nAllocLength
<= nLen
) {
455 if ( pData
->IsEmpty() ) {
458 wxStringData
* pData
= (wxStringData
*)
459 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
461 pData
->nDataLength
= 0;
462 pData
->nAllocLength
= nLen
;
463 m_pchData
= pData
->data(); // data starts after wxStringData
464 m_pchData
[0u] = wxT('\0');
466 else if ( pData
->IsShared() ) {
467 pData
->Unlock(); // memory not freed because shared
468 size_t nOldLen
= pData
->nDataLength
;
470 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
475 wxStringData
*pDataOld
= pData
;
476 wxStringData
*p
= (wxStringData
*)
477 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
483 // FIXME what to do on memory error?
487 // it's not important if the pointer changed or not (the check for this
488 // is not faster than assigning to m_pchData in all cases)
489 p
->nAllocLength
= nLen
;
490 m_pchData
= p
->data();
493 //else: we've already got enough
496 // shrink to minimal size (releasing extra memory)
497 void wxString::Shrink()
499 wxStringData
*pData
= GetStringData();
501 // this variable is unused in release build, so avoid the compiler warning
502 // by just not declaring it
506 realloc(pData
, sizeof(wxStringData
) + (pData
->nDataLength
+ 1)*sizeof(wxChar
));
508 // we rely on a reasonable realloc() implementation here - so far I haven't
509 // seen any which wouldn't behave like this
511 wxASSERT( p
!= NULL
); // can't free memory?
512 wxASSERT( p
== pData
); // we're decrementing the size - block shouldn't move!
515 // get the pointer to writable buffer of (at least) nLen bytes
516 wxChar
*wxString::GetWriteBuf(size_t nLen
)
518 AllocBeforeWrite(nLen
);
520 wxASSERT( GetStringData()->nRefs
== 1 );
521 GetStringData()->Validate(FALSE
);
526 // put string back in a reasonable state after GetWriteBuf
527 void wxString::UngetWriteBuf()
529 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
530 GetStringData()->Validate(TRUE
);
533 void wxString::UngetWriteBuf(size_t nLen
)
535 GetStringData()->nDataLength
= nLen
;
536 GetStringData()->Validate(TRUE
);
539 // ---------------------------------------------------------------------------
541 // ---------------------------------------------------------------------------
543 // all functions are inline in string.h
545 // ---------------------------------------------------------------------------
546 // assignment operators
547 // ---------------------------------------------------------------------------
549 // helper function: does real copy
550 void wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
552 if ( nSrcLen
== 0 ) {
556 AllocBeforeWrite(nSrcLen
);
557 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
558 GetStringData()->nDataLength
= nSrcLen
;
559 m_pchData
[nSrcLen
] = wxT('\0');
563 // assigns one string to another
564 wxString
& wxString::operator=(const wxString
& stringSrc
)
566 wxASSERT( stringSrc
.GetStringData()->IsValid() );
568 // don't copy string over itself
569 if ( m_pchData
!= stringSrc
.m_pchData
) {
570 if ( stringSrc
.GetStringData()->IsEmpty() ) {
575 GetStringData()->Unlock();
576 m_pchData
= stringSrc
.m_pchData
;
577 GetStringData()->Lock();
584 // assigns a single character
585 wxString
& wxString::operator=(wxChar ch
)
592 wxString
& wxString::operator=(const wxChar
*psz
)
594 AssignCopy(wxStrlen(psz
), psz
);
600 // same as 'signed char' variant
601 wxString
& wxString::operator=(const unsigned char* psz
)
603 *this = (const char *)psz
;
608 wxString
& wxString::operator=(const wchar_t *pwz
)
618 // ---------------------------------------------------------------------------
619 // string concatenation
620 // ---------------------------------------------------------------------------
622 // add something to this string
623 void wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
625 STATISTICS_ADD(SummandLength
, nSrcLen
);
627 // concatenating an empty string is a NOP
629 wxStringData
*pData
= GetStringData();
630 size_t nLen
= pData
->nDataLength
;
631 size_t nNewLen
= nLen
+ nSrcLen
;
633 // alloc new buffer if current is too small
634 if ( pData
->IsShared() ) {
635 STATISTICS_ADD(ConcatHit
, 0);
637 // we have to allocate another buffer
638 wxStringData
* pOldData
= GetStringData();
639 AllocBuffer(nNewLen
);
640 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
643 else if ( nNewLen
> pData
->nAllocLength
) {
644 STATISTICS_ADD(ConcatHit
, 0);
646 // we have to grow the buffer
650 STATISTICS_ADD(ConcatHit
, 1);
652 // the buffer is already big enough
655 // should be enough space
656 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
658 // fast concatenation - all is done in our buffer
659 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
661 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
662 GetStringData()->nDataLength
= nNewLen
; // and fix the length
664 //else: the string to append was empty
668 * concatenation functions come in 5 flavours:
670 * char + string and string + char
671 * C str + string and string + C str
674 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
676 wxASSERT( string1
.GetStringData()->IsValid() );
677 wxASSERT( string2
.GetStringData()->IsValid() );
679 wxString s
= string1
;
685 wxString
operator+(const wxString
& string
, wxChar ch
)
687 wxASSERT( string
.GetStringData()->IsValid() );
695 wxString
operator+(wxChar ch
, const wxString
& string
)
697 wxASSERT( string
.GetStringData()->IsValid() );
705 wxString
operator+(const wxString
& string
, const wxChar
*psz
)
707 wxASSERT( string
.GetStringData()->IsValid() );
710 s
.Alloc(wxStrlen(psz
) + string
.Len());
717 wxString
operator+(const wxChar
*psz
, const wxString
& string
)
719 wxASSERT( string
.GetStringData()->IsValid() );
722 s
.Alloc(wxStrlen(psz
) + string
.Len());
729 // ===========================================================================
730 // other common string functions
731 // ===========================================================================
733 // ---------------------------------------------------------------------------
734 // simple sub-string extraction
735 // ---------------------------------------------------------------------------
737 // helper function: clone the data attached to this string
738 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
740 if ( nCopyLen
== 0 ) {
744 dest
.AllocBuffer(nCopyLen
);
745 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
749 // extract string of length nCount starting at nFirst
750 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
752 wxStringData
*pData
= GetStringData();
753 size_t nLen
= pData
->nDataLength
;
755 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
756 if ( nCount
== wxSTRING_MAXLEN
)
758 nCount
= nLen
- nFirst
;
761 // out-of-bounds requests return sensible things
762 if ( nFirst
+ nCount
> nLen
)
764 nCount
= nLen
- nFirst
;
769 // AllocCopy() will return empty string
774 AllocCopy(dest
, nCount
, nFirst
);
779 // check that the tring starts with prefix and return the rest of the string
780 // in the provided pointer if it is not NULL, otherwise return FALSE
781 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
783 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
785 // first check if the beginning of the string matches the prefix: note
786 // that we don't have to check that we don't run out of this string as
787 // when we reach the terminating NUL, either prefix string ends too (and
788 // then it's ok) or we break out of the loop because there is no match
789 const wxChar
*p
= c_str();
792 if ( *prefix
++ != *p
++ )
801 // put the rest of the string into provided pointer
808 // extract nCount last (rightmost) characters
809 wxString
wxString::Right(size_t nCount
) const
811 if ( nCount
> (size_t)GetStringData()->nDataLength
)
812 nCount
= GetStringData()->nDataLength
;
815 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
819 // get all characters after the last occurence of ch
820 // (returns the whole string if ch not found)
821 wxString
wxString::AfterLast(wxChar ch
) const
824 int iPos
= Find(ch
, TRUE
);
825 if ( iPos
== wxNOT_FOUND
)
828 str
= c_str() + iPos
+ 1;
833 // extract nCount first (leftmost) characters
834 wxString
wxString::Left(size_t nCount
) const
836 if ( nCount
> (size_t)GetStringData()->nDataLength
)
837 nCount
= GetStringData()->nDataLength
;
840 AllocCopy(dest
, nCount
, 0);
844 // get all characters before the first occurence of ch
845 // (returns the whole string if ch not found)
846 wxString
wxString::BeforeFirst(wxChar ch
) const
849 for ( const wxChar
*pc
= m_pchData
; *pc
!= wxT('\0') && *pc
!= ch
; pc
++ )
855 /// get all characters before the last occurence of ch
856 /// (returns empty string if ch not found)
857 wxString
wxString::BeforeLast(wxChar ch
) const
860 int iPos
= Find(ch
, TRUE
);
861 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
862 str
= wxString(c_str(), iPos
);
867 /// get all characters after the first occurence of ch
868 /// (returns empty string if ch not found)
869 wxString
wxString::AfterFirst(wxChar ch
) const
873 if ( iPos
!= wxNOT_FOUND
)
874 str
= c_str() + iPos
+ 1;
879 // replace first (or all) occurences of some substring with another one
880 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
882 size_t uiCount
= 0; // count of replacements made
884 size_t uiOldLen
= wxStrlen(szOld
);
887 const wxChar
*pCurrent
= m_pchData
;
888 const wxChar
*pSubstr
;
889 while ( *pCurrent
!= wxT('\0') ) {
890 pSubstr
= wxStrstr(pCurrent
, szOld
);
891 if ( pSubstr
== NULL
) {
892 // strTemp is unused if no replacements were made, so avoid the copy
896 strTemp
+= pCurrent
; // copy the rest
897 break; // exit the loop
900 // take chars before match
901 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
903 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
908 if ( !bReplaceAll
) {
909 strTemp
+= pCurrent
; // copy the rest
910 break; // exit the loop
915 // only done if there were replacements, otherwise would have returned above
921 bool wxString::IsAscii() const
923 const wxChar
*s
= (const wxChar
*) *this;
925 if(!isascii(*s
)) return(FALSE
);
931 bool wxString::IsWord() const
933 const wxChar
*s
= (const wxChar
*) *this;
935 if(!wxIsalpha(*s
)) return(FALSE
);
941 bool wxString::IsNumber() const
943 const wxChar
*s
= (const wxChar
*) *this;
945 if ((s
[0] == '-') || (s
[0] == '+')) s
++;
947 if(!wxIsdigit(*s
)) return(FALSE
);
953 wxString
wxString::Strip(stripType w
) const
956 if ( w
& leading
) s
.Trim(FALSE
);
957 if ( w
& trailing
) s
.Trim(TRUE
);
961 // ---------------------------------------------------------------------------
963 // ---------------------------------------------------------------------------
965 wxString
& wxString::MakeUpper()
969 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
970 *p
= (wxChar
)wxToupper(*p
);
975 wxString
& wxString::MakeLower()
979 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
980 *p
= (wxChar
)wxTolower(*p
);
985 // ---------------------------------------------------------------------------
986 // trimming and padding
987 // ---------------------------------------------------------------------------
989 // some compilers (VC++ 6.0 not to name them) return TRUE for a call to
990 // isspace('ê') in the C locale which seems to be broken to me, but we have to
991 // live with this by checking that the character is a 7 bit one - even if this
992 // may fail to detect some spaces (I don't know if Unicode doesn't have
993 // space-like symbols somewhere except in the first 128 chars), it is arguably
994 // still better than trimming away accented letters
995 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
997 // trims spaces (in the sense of isspace) from left or right side
998 wxString
& wxString::Trim(bool bFromRight
)
1000 // first check if we're going to modify the string at all
1003 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1004 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1008 // ok, there is at least one space to trim
1013 // find last non-space character
1014 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
1015 while ( wxSafeIsspace(*psz
) && (psz
>= m_pchData
) )
1018 // truncate at trailing space start
1020 GetStringData()->nDataLength
= psz
- m_pchData
;
1024 // find first non-space character
1025 const wxChar
*psz
= m_pchData
;
1026 while ( wxSafeIsspace(*psz
) )
1029 // fix up data and length
1030 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
1031 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
1032 GetStringData()->nDataLength
= nDataLength
;
1039 // adds nCount characters chPad to the string from either side
1040 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1042 wxString
s(chPad
, nCount
);
1055 // truncate the string
1056 wxString
& wxString::Truncate(size_t uiLen
)
1058 if ( uiLen
< Len() ) {
1061 *(m_pchData
+ uiLen
) = wxT('\0');
1062 GetStringData()->nDataLength
= uiLen
;
1064 //else: nothing to do, string is already short enough
1069 // ---------------------------------------------------------------------------
1070 // finding (return wxNOT_FOUND if not found and index otherwise)
1071 // ---------------------------------------------------------------------------
1074 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1076 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
1078 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1081 // find a sub-string (like strstr)
1082 int wxString::Find(const wxChar
*pszSub
) const
1084 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
1086 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1089 // ----------------------------------------------------------------------------
1090 // conversion to numbers
1091 // ----------------------------------------------------------------------------
1093 bool wxString::ToLong(long *val
) const
1095 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToLong") );
1097 const wxChar
*start
= c_str();
1099 *val
= wxStrtol(start
, &end
, 10);
1101 // return TRUE only if scan was stopped by the terminating NUL and if the
1102 // string was not empty to start with
1103 return !*end
&& (end
!= start
);
1106 bool wxString::ToULong(unsigned long *val
) const
1108 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToULong") );
1110 const wxChar
*start
= c_str();
1112 *val
= wxStrtoul(start
, &end
, 10);
1114 // return TRUE only if scan was stopped by the terminating NUL and if the
1115 // string was not empty to start with
1116 return !*end
&& (end
!= start
);
1119 bool wxString::ToDouble(double *val
) const
1121 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToDouble") );
1123 const wxChar
*start
= c_str();
1125 *val
= wxStrtod(start
, &end
);
1127 // return TRUE only if scan was stopped by the terminating NUL and if the
1128 // string was not empty to start with
1129 return !*end
&& (end
!= start
);
1132 // ---------------------------------------------------------------------------
1134 // ---------------------------------------------------------------------------
1137 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1140 va_start(argptr
, pszFormat
);
1143 s
.PrintfV(pszFormat
, argptr
);
1151 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1154 s
.Printf(pszFormat
, argptr
);
1158 int wxString::Printf(const wxChar
*pszFormat
, ...)
1161 va_start(argptr
, pszFormat
);
1163 int iLen
= PrintfV(pszFormat
, argptr
);
1170 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1172 #if wxUSE_EXPERIMENTAL_PRINTF
1173 // the new implementation
1175 // buffer to avoid dynamic memory allocation each time for small strings
1176 char szScratch
[1024];
1179 for (size_t n
= 0; pszFormat
[n
]; n
++)
1180 if (pszFormat
[n
] == wxT('%')) {
1181 static char s_szFlags
[256] = "%";
1183 bool adj_left
= FALSE
, in_prec
= FALSE
,
1184 prec_dot
= FALSE
, done
= FALSE
;
1186 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1188 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1189 switch (pszFormat
[++n
]) {
1203 s_szFlags
[flagofs
++] = pszFormat
[n
];
1208 s_szFlags
[flagofs
++] = pszFormat
[n
];
1215 // dot will be auto-added to s_szFlags if non-negative number follows
1220 s_szFlags
[flagofs
++] = pszFormat
[n
];
1225 s_szFlags
[flagofs
++] = pszFormat
[n
];
1231 s_szFlags
[flagofs
++] = pszFormat
[n
];
1236 s_szFlags
[flagofs
++] = pszFormat
[n
];
1240 int len
= va_arg(argptr
, int);
1247 adj_left
= !adj_left
;
1248 s_szFlags
[flagofs
++] = '-';
1253 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1256 case wxT('1'): case wxT('2'): case wxT('3'):
1257 case wxT('4'): case wxT('5'): case wxT('6'):
1258 case wxT('7'): case wxT('8'): case wxT('9'):
1262 while ((pszFormat
[n
]>=wxT('0')) && (pszFormat
[n
]<=wxT('9'))) {
1263 s_szFlags
[flagofs
++] = pszFormat
[n
];
1264 len
= len
*10 + (pszFormat
[n
] - wxT('0'));
1267 if (in_prec
) max_width
= len
;
1268 else min_width
= len
;
1269 n
--; // the main loop pre-increments n again
1279 s_szFlags
[flagofs
++] = pszFormat
[n
];
1280 s_szFlags
[flagofs
] = '\0';
1282 int val
= va_arg(argptr
, int);
1283 ::sprintf(szScratch
, s_szFlags
, val
);
1285 else if (ilen
== -1) {
1286 short int val
= va_arg(argptr
, short int);
1287 ::sprintf(szScratch
, s_szFlags
, val
);
1289 else if (ilen
== 1) {
1290 long int val
= va_arg(argptr
, long int);
1291 ::sprintf(szScratch
, s_szFlags
, val
);
1293 else if (ilen
== 2) {
1294 #if SIZEOF_LONG_LONG
1295 long long int val
= va_arg(argptr
, long long int);
1296 ::sprintf(szScratch
, s_szFlags
, val
);
1298 long int val
= va_arg(argptr
, long int);
1299 ::sprintf(szScratch
, s_szFlags
, val
);
1302 else if (ilen
== 3) {
1303 size_t val
= va_arg(argptr
, size_t);
1304 ::sprintf(szScratch
, s_szFlags
, val
);
1306 *this += wxString(szScratch
);
1315 s_szFlags
[flagofs
++] = pszFormat
[n
];
1316 s_szFlags
[flagofs
] = '\0';
1318 long double val
= va_arg(argptr
, long double);
1319 ::sprintf(szScratch
, s_szFlags
, val
);
1321 double val
= va_arg(argptr
, double);
1322 ::sprintf(szScratch
, s_szFlags
, val
);
1324 *this += wxString(szScratch
);
1329 void *val
= va_arg(argptr
, void *);
1331 s_szFlags
[flagofs
++] = pszFormat
[n
];
1332 s_szFlags
[flagofs
] = '\0';
1333 ::sprintf(szScratch
, s_szFlags
, val
);
1334 *this += wxString(szScratch
);
1340 wxChar val
= va_arg(argptr
, int);
1341 // we don't need to honor padding here, do we?
1348 // wx extension: we'll let %hs mean non-Unicode strings
1349 char *val
= va_arg(argptr
, char *);
1351 // ASCII->Unicode constructor handles max_width right
1352 wxString
s(val
, wxConvLibc
, max_width
);
1354 size_t len
= wxSTRING_MAXLEN
;
1356 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1357 } else val
= wxT("(null)");
1358 wxString
s(val
, len
);
1360 if (s
.Len() < min_width
)
1361 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1364 wxChar
*val
= va_arg(argptr
, wxChar
*);
1365 size_t len
= wxSTRING_MAXLEN
;
1367 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1368 } else val
= wxT("(null)");
1369 wxString
s(val
, len
);
1370 if (s
.Len() < min_width
)
1371 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1378 int *val
= va_arg(argptr
, int *);
1381 else if (ilen
== -1) {
1382 short int *val
= va_arg(argptr
, short int *);
1385 else if (ilen
>= 1) {
1386 long int *val
= va_arg(argptr
, long int *);
1392 if (wxIsalpha(pszFormat
[n
]))
1393 // probably some flag not taken care of here yet
1394 s_szFlags
[flagofs
++] = pszFormat
[n
];
1397 *this += wxT('%'); // just to pass the glibc tst-printf.c
1405 } else *this += pszFormat
[n
];
1408 // buffer to avoid dynamic memory allocation each time for small strings
1409 char szScratch
[1024];
1411 // NB: wxVsnprintf() may return either less than the buffer size or -1 if
1412 // there is not enough place depending on implementation
1413 int iLen
= wxVsnprintfA(szScratch
, WXSIZEOF(szScratch
), (char *)pszFormat
, argptr
);
1415 // the whole string is in szScratch
1419 bool outOfMemory
= FALSE
;
1420 int size
= 2*WXSIZEOF(szScratch
);
1421 while ( !outOfMemory
) {
1422 char *buf
= GetWriteBuf(size
);
1424 iLen
= wxVsnprintfA(buf
, size
, pszFormat
, argptr
);
1431 // ok, there was enough space
1435 // still not enough, double it again
1439 if ( outOfMemory
) {
1444 #endif // wxUSE_EXPERIMENTAL_PRINTF/!wxUSE_EXPERIMENTAL_PRINTF
1449 // ----------------------------------------------------------------------------
1450 // misc other operations
1451 // ----------------------------------------------------------------------------
1453 // returns TRUE if the string matches the pattern which may contain '*' and
1454 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1456 bool wxString::Matches(const wxChar
*pszMask
) const
1458 // check char by char
1459 const wxChar
*pszTxt
;
1460 for ( pszTxt
= c_str(); *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1461 switch ( *pszMask
) {
1463 if ( *pszTxt
== wxT('\0') )
1466 // pszText and pszMask will be incremented in the loop statement
1472 // ignore special chars immediately following this one
1473 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1476 // if there is nothing more, match
1477 if ( *pszMask
== wxT('\0') )
1480 // are there any other metacharacters in the mask?
1482 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1484 if ( pEndMask
!= NULL
) {
1485 // we have to match the string between two metachars
1486 uiLenMask
= pEndMask
- pszMask
;
1489 // we have to match the remainder of the string
1490 uiLenMask
= wxStrlen(pszMask
);
1493 wxString
strToMatch(pszMask
, uiLenMask
);
1494 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1495 if ( pMatch
== NULL
)
1498 // -1 to compensate "++" in the loop
1499 pszTxt
= pMatch
+ uiLenMask
- 1;
1500 pszMask
+= uiLenMask
- 1;
1505 if ( *pszMask
!= *pszTxt
)
1511 // match only if nothing left
1512 return *pszTxt
== wxT('\0');
1515 // Count the number of chars
1516 int wxString::Freq(wxChar ch
) const
1520 for (int i
= 0; i
< len
; i
++)
1522 if (GetChar(i
) == ch
)
1528 // convert to upper case, return the copy of the string
1529 wxString
wxString::Upper() const
1530 { wxString
s(*this); return s
.MakeUpper(); }
1532 // convert to lower case, return the copy of the string
1533 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1535 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1538 va_start(argptr
, pszFormat
);
1539 int iLen
= PrintfV(pszFormat
, argptr
);
1544 // ---------------------------------------------------------------------------
1545 // standard C++ library string functions
1546 // ---------------------------------------------------------------------------
1548 #ifdef wxSTD_STRING_COMPATIBILITY
1550 void wxString::resize(size_t nSize
, wxChar ch
)
1552 size_t len
= length();
1558 else if ( nSize
> len
)
1560 *this += wxString(ch
, len
- nSize
);
1562 //else: we have exactly the specified length, nothing to do
1565 void wxString::swap(wxString
& str
)
1567 // this is slightly less efficient than fiddling with m_pchData directly,
1568 // but it is still quite efficient as we don't copy the string here because
1569 // ref count always stays positive
1575 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1577 wxASSERT( str
.GetStringData()->IsValid() );
1578 wxASSERT( nPos
<= Len() );
1580 if ( !str
.IsEmpty() ) {
1582 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1583 wxStrncpy(pc
, c_str(), nPos
);
1584 wxStrcpy(pc
+ nPos
, str
);
1585 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1586 strTmp
.UngetWriteBuf();
1593 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1595 wxASSERT( str
.GetStringData()->IsValid() );
1596 wxASSERT( nStart
<= Len() );
1598 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1600 return p
== NULL
? npos
: p
- c_str();
1603 // VC++ 1.5 can't cope with the default argument in the header.
1604 #if !defined(__VISUALC__) || defined(__WIN32__)
1605 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1607 return find(wxString(sz
, n
), nStart
);
1611 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1612 #if !defined(__BORLANDC__)
1613 size_t wxString::find(wxChar ch
, size_t nStart
) const
1615 wxASSERT( nStart
<= Len() );
1617 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1619 return p
== NULL
? npos
: p
- c_str();
1623 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1625 wxASSERT( str
.GetStringData()->IsValid() );
1626 wxASSERT( nStart
<= Len() );
1628 // TODO could be made much quicker than that
1629 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1630 while ( p
>= c_str() + str
.Len() ) {
1631 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1632 return p
- str
.Len() - c_str();
1639 // VC++ 1.5 can't cope with the default argument in the header.
1640 #if !defined(__VISUALC__) || defined(__WIN32__)
1641 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1643 return rfind(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1646 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1648 if ( nStart
== npos
)
1654 wxASSERT( nStart
<= Len() );
1657 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1662 size_t result
= p
- c_str();
1663 return ( result
> nStart
) ? npos
: result
;
1667 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1669 const wxChar
*start
= c_str() + nStart
;
1670 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1672 return firstOf
- c_str();
1677 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1679 if ( nStart
== npos
)
1685 wxASSERT( nStart
<= Len() );
1688 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1690 if ( wxStrchr(sz
, *p
) )
1697 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1699 if ( nStart
== npos
)
1705 wxASSERT( nStart
<= Len() );
1708 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1709 if ( nAccept
>= length() - nStart
)
1715 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1717 wxASSERT( nStart
<= Len() );
1719 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1728 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1730 if ( nStart
== npos
)
1736 wxASSERT( nStart
<= Len() );
1739 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1741 if ( !wxStrchr(sz
, *p
) )
1748 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1750 if ( nStart
== npos
)
1756 wxASSERT( nStart
<= Len() );
1759 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1768 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1770 wxString
strTmp(c_str(), nStart
);
1771 if ( nLen
!= npos
) {
1772 wxASSERT( nStart
+ nLen
<= Len() );
1774 strTmp
.append(c_str() + nStart
+ nLen
);
1781 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1783 wxASSERT_MSG( nStart
+ nLen
<= Len(),
1784 _T("index out of bounds in wxString::replace") );
1787 strTmp
.Alloc(Len()); // micro optimisation to avoid multiple mem allocs
1790 strTmp
.append(c_str(), nStart
);
1791 strTmp
<< sz
<< c_str() + nStart
+ nLen
;
1797 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1799 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1802 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1803 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1805 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1808 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1809 const wxChar
* sz
, size_t nCount
)
1811 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1814 #endif //std::string compatibility
1816 // ============================================================================
1818 // ============================================================================
1820 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1821 #define ARRAY_MAXSIZE_INCREMENT 4096
1822 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1823 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1826 #define STRING(p) ((wxString *)(&(p)))
1829 wxArrayString::wxArrayString(bool autoSort
)
1833 m_pItems
= (wxChar
**) NULL
;
1834 m_autoSort
= autoSort
;
1838 wxArrayString::wxArrayString(const wxArrayString
& src
)
1842 m_pItems
= (wxChar
**) NULL
;
1843 m_autoSort
= src
.m_autoSort
;
1848 // assignment operator
1849 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1859 void wxArrayString::Copy(const wxArrayString
& src
)
1861 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1862 Alloc(src
.m_nCount
);
1864 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1869 void wxArrayString::Grow()
1871 // only do it if no more place
1872 if( m_nCount
== m_nSize
) {
1873 if( m_nSize
== 0 ) {
1874 // was empty, alloc some memory
1875 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1876 m_pItems
= new wxChar
*[m_nSize
];
1879 // otherwise when it's called for the first time, nIncrement would be 0
1880 // and the array would never be expanded
1881 #if defined(__VISAGECPP__) && defined(__WXDEBUG__)
1882 int array_size
= ARRAY_DEFAULT_INITIAL_SIZE
;
1883 wxASSERT( array_size
!= 0 );
1885 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE
!= 0 );
1888 // add 50% but not too much
1889 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1890 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1891 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1892 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1893 m_nSize
+= nIncrement
;
1894 wxChar
**pNew
= new wxChar
*[m_nSize
];
1896 // copy data to new location
1897 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1899 // delete old memory (but do not release the strings!)
1900 wxDELETEA(m_pItems
);
1907 void wxArrayString::Free()
1909 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1910 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1914 // deletes all the strings from the list
1915 void wxArrayString::Empty()
1922 // as Empty, but also frees memory
1923 void wxArrayString::Clear()
1930 wxDELETEA(m_pItems
);
1934 wxArrayString::~wxArrayString()
1938 wxDELETEA(m_pItems
);
1941 // pre-allocates memory (frees the previous data!)
1942 void wxArrayString::Alloc(size_t nSize
)
1944 wxASSERT( nSize
> 0 );
1946 // only if old buffer was not big enough
1947 if ( nSize
> m_nSize
) {
1949 wxDELETEA(m_pItems
);
1950 m_pItems
= new wxChar
*[nSize
];
1957 // minimizes the memory usage by freeing unused memory
1958 void wxArrayString::Shrink()
1960 // only do it if we have some memory to free
1961 if( m_nCount
< m_nSize
) {
1962 // allocates exactly as much memory as we need
1963 wxChar
**pNew
= new wxChar
*[m_nCount
];
1965 // copy data to new location
1966 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1972 // searches the array for an item (forward or backwards)
1973 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
1976 // use binary search in the sorted array
1977 wxASSERT_MSG( bCase
&& !bFromEnd
,
1978 wxT("search parameters ignored for auto sorted array") );
1987 res
= wxStrcmp(sz
, m_pItems
[i
]);
1999 // use linear search in unsorted array
2001 if ( m_nCount
> 0 ) {
2002 size_t ui
= m_nCount
;
2004 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2011 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2012 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2021 // add item at the end
2022 size_t wxArrayString::Add(const wxString
& str
)
2025 // insert the string at the correct position to keep the array sorted
2033 res
= wxStrcmp(str
, m_pItems
[i
]);
2044 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2051 wxASSERT( str
.GetStringData()->IsValid() );
2055 // the string data must not be deleted!
2056 str
.GetStringData()->Lock();
2059 m_pItems
[m_nCount
] = (wxChar
*)str
.c_str(); // const_cast
2065 // add item at the given position
2066 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
2068 wxASSERT( str
.GetStringData()->IsValid() );
2070 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2074 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
2075 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2077 str
.GetStringData()->Lock();
2078 m_pItems
[nIndex
] = (wxChar
*)str
.c_str();
2083 // removes item from array (by index)
2084 void wxArrayString::Remove(size_t nIndex
)
2086 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Remove") );
2089 Item(nIndex
).GetStringData()->Unlock();
2091 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
2092 (m_nCount
- nIndex
- 1)*sizeof(wxChar
*));
2096 // removes item from array (by value)
2097 void wxArrayString::Remove(const wxChar
*sz
)
2099 int iIndex
= Index(sz
);
2101 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2102 wxT("removing inexistent element in wxArrayString::Remove") );
2107 // ----------------------------------------------------------------------------
2109 // ----------------------------------------------------------------------------
2111 // we can only sort one array at a time with the quick-sort based
2114 // need a critical section to protect access to gs_compareFunction and
2115 // gs_sortAscending variables
2116 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2118 // call this before the value of the global sort vars is changed/after
2119 // you're finished with them
2120 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2121 gs_critsectStringSort = new wxCriticalSection; \
2122 gs_critsectStringSort->Enter()
2123 #define END_SORT() gs_critsectStringSort->Leave(); \
2124 delete gs_critsectStringSort; \
2125 gs_critsectStringSort = NULL
2127 #define START_SORT()
2129 #endif // wxUSE_THREADS
2131 // function to use for string comparaison
2132 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2134 // if we don't use the compare function, this flag tells us if we sort the
2135 // array in ascending or descending order
2136 static bool gs_sortAscending
= TRUE
;
2138 // function which is called by quick sort
2139 static int LINKAGEMODE
wxStringCompareFunction(const void *first
, const void *second
)
2141 wxString
*strFirst
= (wxString
*)first
;
2142 wxString
*strSecond
= (wxString
*)second
;
2144 if ( gs_compareFunction
) {
2145 return gs_compareFunction(*strFirst
, *strSecond
);
2148 // maybe we should use wxStrcoll
2149 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
2151 return gs_sortAscending
? result
: -result
;
2155 // sort array elements using passed comparaison function
2156 void wxArrayString::Sort(CompareFunction compareFunction
)
2160 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2161 gs_compareFunction
= compareFunction
;
2165 // reset it to NULL so that Sort(bool) will work the next time
2166 gs_compareFunction
= NULL
;
2171 void wxArrayString::Sort(bool reverseOrder
)
2175 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2176 gs_sortAscending
= !reverseOrder
;
2183 void wxArrayString::DoSort()
2185 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2187 // just sort the pointers using qsort() - of course it only works because
2188 // wxString() *is* a pointer to its data
2189 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2192 bool wxArrayString::operator==(const wxArrayString
& a
) const
2194 if ( m_nCount
!= a
.m_nCount
)
2197 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2199 if ( Item(n
) != a
[n
] )