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"
49 #ifdef WXSTRING_IS_WXOBJECT
50 IMPLEMENT_DYNAMIC_CLASS(wxString
, wxObject
)
51 #endif //WXSTRING_IS_WXOBJECT
54 #undef wxUSE_EXPERIMENTAL_PRINTF
55 #define wxUSE_EXPERIMENTAL_PRINTF 1
58 // allocating extra space for each string consumes more memory but speeds up
59 // the concatenation operations (nLen is the current string's length)
60 // NB: EXTRA_ALLOC must be >= 0!
61 #define EXTRA_ALLOC (19 - nLen % 16)
63 // ---------------------------------------------------------------------------
64 // static class variables definition
65 // ---------------------------------------------------------------------------
67 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
68 // must define this static for VA or else you get multiply defined symbols
70 const unsigned int wxSTRING_MAXLEN
= UINT_MAX
- 100;
73 #ifdef wxSTD_STRING_COMPATIBILITY
74 const size_t wxString::npos
= wxSTRING_MAXLEN
;
75 #endif // wxSTD_STRING_COMPATIBILITY
77 // ----------------------------------------------------------------------------
79 // ----------------------------------------------------------------------------
81 // for an empty string, GetStringData() will return this address: this
82 // structure has the same layout as wxStringData and it's data() method will
83 // return the empty string (dummy pointer)
88 } g_strEmpty
= { {-1, 0, 0}, wxT('\0') };
90 // empty C style string: points to 'string data' byte of g_strEmpty
91 extern const wxChar WXDLLEXPORT
*wxEmptyString
= &g_strEmpty
.dummy
;
93 // ----------------------------------------------------------------------------
94 // conditional compilation
95 // ----------------------------------------------------------------------------
97 #if !defined(__WXSW__) && wxUSE_UNICODE
98 #ifdef wxUSE_EXPERIMENTAL_PRINTF
99 #undef wxUSE_EXPERIMENTAL_PRINTF
101 #define wxUSE_EXPERIMENTAL_PRINTF 1
104 // we want to find out if the current platform supports vsnprintf()-like
105 // function: for Unix this is done with configure, for Windows we test the
106 // compiler explicitly.
108 // FIXME currently, this is only for ANSI (!Unicode) strings, so we call this
109 // function wxVsnprintfA (A for ANSI), should also find one for Unicode
110 // strings in Unicode build
112 #if defined(__VISUALC__) || (defined(__MINGW32__) && wxUSE_NORLANDER_HEADERS)
113 #define wxVsnprintfA _vsnprintf
115 #elif defined(__WXMAC__)
116 #define wxVsnprintfA vsnprintf
118 #ifdef HAVE_VSNPRINTF
119 #define wxVsnprintfA vsnprintf
121 #endif // Windows/!Windows
124 // in this case we'll use vsprintf() (which is ANSI and thus should be
125 // always available), but it's unsafe because it doesn't check for buffer
126 // size - so give a warning
127 #define wxVsnprintfA(buf, len, format, arg) vsprintf(buf, format, arg)
129 #if defined(__VISUALC__)
130 #pragma message("Using sprintf() because no snprintf()-like function defined")
131 #elif defined(__GNUG__)
132 #warning "Using sprintf() because no snprintf()-like function defined"
134 #endif // no vsnprintf
137 // AIX has vsnprintf, but there's no prototype in the system headers.
138 extern "C" int vsnprintf(char* str
, size_t n
, const char* format
, va_list ap
);
141 // ----------------------------------------------------------------------------
143 // ----------------------------------------------------------------------------
145 #if defined(wxSTD_STRING_COMPATIBILITY) && wxUSE_STD_IOSTREAM
147 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
150 // ATTN: you can _not_ use both of these in the same program!
152 wxSTD istream
& operator>>(wxSTD istream
& is
, wxString
& WXUNUSED(str
))
157 streambuf
*sb
= is
.rdbuf();
160 int ch
= sb
->sbumpc ();
162 is
.setstate(ios::eofbit
);
165 else if ( isspace(ch
) ) {
177 if ( str
.length() == 0 )
178 is
.setstate(ios::failbit
);
183 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
189 #endif //std::string compatibility
191 extern int WXDLLEXPORT
wxVsnprintf(wxChar
*buf
, size_t len
,
192 const wxChar
*format
, va_list argptr
)
195 // FIXME should use wvsnprintf() or whatever if it's available
197 int iLen
= s
.PrintfV(format
, argptr
);
200 wxStrncpy(buf
, s
.c_str(), len
);
201 buf
[len
-1] = wxT('\0');
206 // vsnprintf() will not terminate the string with '\0' if there is not
207 // enough place, but we want the string to always be NUL terminated
208 int rc
= wxVsnprintfA(buf
, len
- 1, format
, argptr
);
215 #endif // Unicode/ANSI
218 extern int WXDLLEXPORT
wxSnprintf(wxChar
*buf
, size_t len
,
219 const wxChar
*format
, ...)
222 va_start(argptr
, format
);
224 int iLen
= wxVsnprintf(buf
, len
, format
, argptr
);
231 // ----------------------------------------------------------------------------
233 // ----------------------------------------------------------------------------
235 // this small class is used to gather statistics for performance tuning
236 //#define WXSTRING_STATISTICS
237 #ifdef WXSTRING_STATISTICS
241 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
243 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
245 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
248 size_t m_nCount
, m_nTotal
;
250 } g_averageLength("allocation size"),
251 g_averageSummandLength("summand length"),
252 g_averageConcatHit("hit probability in concat"),
253 g_averageInitialLength("initial string length");
255 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
257 #define STATISTICS_ADD(av, val)
258 #endif // WXSTRING_STATISTICS
260 // ===========================================================================
261 // wxString class core
262 // ===========================================================================
264 // ---------------------------------------------------------------------------
266 // ---------------------------------------------------------------------------
268 // constructs string of <nLength> copies of character <ch>
269 wxString::wxString(wxChar ch
, size_t nLength
)
274 AllocBuffer(nLength
);
277 // memset only works on char
278 for (size_t n
=0; n
<nLength
; n
++) m_pchData
[n
] = ch
;
280 memset(m_pchData
, ch
, nLength
);
285 // takes nLength elements of psz starting at nPos
286 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
290 // if the length is not given, assume the string to be NUL terminated
291 if ( nLength
== wxSTRING_MAXLEN
) {
292 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
294 nLength
= wxStrlen(psz
+ nPos
);
297 STATISTICS_ADD(InitialLength
, nLength
);
300 // trailing '\0' is written in AllocBuffer()
301 AllocBuffer(nLength
);
302 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
306 #ifdef wxSTD_STRING_COMPATIBILITY
308 // poor man's iterators are "void *" pointers
309 wxString::wxString(const void *pStart
, const void *pEnd
)
311 InitWith((const wxChar
*)pStart
, 0,
312 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
315 #endif //std::string compatibility
319 // from multibyte string
320 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
322 // first get necessary size
323 size_t nLen
= psz
? conv
.MB2WC((wchar_t *) NULL
, psz
, 0) : 0;
325 // nLength is number of *Unicode* characters here!
326 if ((nLen
!= (size_t)-1) && (nLen
> nLength
))
330 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
332 conv
.MB2WC(m_pchData
, psz
, nLen
);
343 wxString::wxString(const wchar_t *pwz
, wxMBConv
& conv
, size_t nLength
)
345 // first get necessary size
349 if (nLength
== wxSTRING_MAXLEN
)
350 nLen
= conv
.WC2MB((char *) NULL
, pwz
, 0);
356 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
358 conv
.WC2MB(m_pchData
, pwz
, nLen
);
364 #endif // wxUSE_WCHAR_T
366 #endif // Unicode/ANSI
368 // ---------------------------------------------------------------------------
370 // ---------------------------------------------------------------------------
372 // allocates memory needed to store a C string of length nLen
373 void wxString::AllocBuffer(size_t nLen
)
375 // allocating 0 sized buffer doesn't make sense, all empty strings should
377 wxASSERT( nLen
> 0 );
379 // make sure that we don't overflow
380 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxChar
)) -
381 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
383 STATISTICS_ADD(Length
, nLen
);
386 // 1) one extra character for '\0' termination
387 // 2) sizeof(wxStringData) for housekeeping info
388 wxStringData
* pData
= (wxStringData
*)
389 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
391 pData
->nDataLength
= nLen
;
392 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
393 m_pchData
= pData
->data(); // data starts after wxStringData
394 m_pchData
[nLen
] = wxT('\0');
397 // must be called before changing this string
398 void wxString::CopyBeforeWrite()
400 wxStringData
* pData
= GetStringData();
402 if ( pData
->IsShared() ) {
403 pData
->Unlock(); // memory not freed because shared
404 size_t nLen
= pData
->nDataLength
;
406 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
409 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
412 // must be called before replacing contents of this string
413 void wxString::AllocBeforeWrite(size_t nLen
)
415 wxASSERT( nLen
!= 0 ); // doesn't make any sense
417 // must not share string and must have enough space
418 wxStringData
* pData
= GetStringData();
419 if ( pData
->IsShared() || pData
->IsEmpty() ) {
420 // can't work with old buffer, get new one
425 if ( nLen
> pData
->nAllocLength
) {
426 // realloc the buffer instead of calling malloc() again, this is more
428 STATISTICS_ADD(Length
, nLen
);
432 wxStringData
*pDataOld
= pData
;
433 pData
= (wxStringData
*)
434 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
439 // FIXME we're going to crash...
443 pData
->nAllocLength
= nLen
;
444 m_pchData
= pData
->data();
447 // now we have enough space, just update the string length
448 pData
->nDataLength
= nLen
;
451 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
454 // allocate enough memory for nLen characters
455 void wxString::Alloc(size_t nLen
)
457 wxStringData
*pData
= GetStringData();
458 if ( pData
->nAllocLength
<= nLen
) {
459 if ( pData
->IsEmpty() ) {
462 wxStringData
* pData
= (wxStringData
*)
463 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
465 pData
->nDataLength
= 0;
466 pData
->nAllocLength
= nLen
;
467 m_pchData
= pData
->data(); // data starts after wxStringData
468 m_pchData
[0u] = wxT('\0');
470 else if ( pData
->IsShared() ) {
471 pData
->Unlock(); // memory not freed because shared
472 size_t nOldLen
= pData
->nDataLength
;
474 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
479 wxStringData
*pDataOld
= pData
;
480 wxStringData
*p
= (wxStringData
*)
481 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
487 // FIXME what to do on memory error?
491 // it's not important if the pointer changed or not (the check for this
492 // is not faster than assigning to m_pchData in all cases)
493 p
->nAllocLength
= nLen
;
494 m_pchData
= p
->data();
497 //else: we've already got enough
500 // shrink to minimal size (releasing extra memory)
501 void wxString::Shrink()
503 wxStringData
*pData
= GetStringData();
505 size_t nLen
= pData
->nDataLength
;
506 void *p
= realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
508 wxASSERT_MSG( p
!= NULL
, _T("can't free memory?") );
512 // contrary to what one might believe, some realloc() implementation do
513 // move the memory block even when its size is reduced
514 pData
= (wxStringData
*)p
;
516 m_pchData
= pData
->data();
519 pData
->nAllocLength
= nLen
;
522 // get the pointer to writable buffer of (at least) nLen bytes
523 wxChar
*wxString::GetWriteBuf(size_t nLen
)
525 AllocBeforeWrite(nLen
);
527 wxASSERT( GetStringData()->nRefs
== 1 );
528 GetStringData()->Validate(FALSE
);
533 // put string back in a reasonable state after GetWriteBuf
534 void wxString::UngetWriteBuf()
536 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
537 GetStringData()->Validate(TRUE
);
540 void wxString::UngetWriteBuf(size_t nLen
)
542 GetStringData()->nDataLength
= nLen
;
543 GetStringData()->Validate(TRUE
);
546 // ---------------------------------------------------------------------------
548 // ---------------------------------------------------------------------------
550 // all functions are inline in string.h
552 // ---------------------------------------------------------------------------
553 // assignment operators
554 // ---------------------------------------------------------------------------
556 // helper function: does real copy
557 void wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
559 if ( nSrcLen
== 0 ) {
563 AllocBeforeWrite(nSrcLen
);
564 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
565 GetStringData()->nDataLength
= nSrcLen
;
566 m_pchData
[nSrcLen
] = wxT('\0');
570 // assigns one string to another
571 wxString
& wxString::operator=(const wxString
& stringSrc
)
573 wxASSERT( stringSrc
.GetStringData()->IsValid() );
575 // don't copy string over itself
576 if ( m_pchData
!= stringSrc
.m_pchData
) {
577 if ( stringSrc
.GetStringData()->IsEmpty() ) {
582 GetStringData()->Unlock();
583 m_pchData
= stringSrc
.m_pchData
;
584 GetStringData()->Lock();
591 // assigns a single character
592 wxString
& wxString::operator=(wxChar ch
)
600 wxString
& wxString::operator=(const wxChar
*psz
)
602 AssignCopy(wxStrlen(psz
), psz
);
608 // same as 'signed char' variant
609 wxString
& wxString::operator=(const unsigned char* psz
)
611 *this = (const char *)psz
;
616 wxString
& wxString::operator=(const wchar_t *pwz
)
626 // ---------------------------------------------------------------------------
627 // string concatenation
628 // ---------------------------------------------------------------------------
630 // add something to this string
631 void wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
633 STATISTICS_ADD(SummandLength
, nSrcLen
);
635 // concatenating an empty string is a NOP
637 wxStringData
*pData
= GetStringData();
638 size_t nLen
= pData
->nDataLength
;
639 size_t nNewLen
= nLen
+ nSrcLen
;
641 // alloc new buffer if current is too small
642 if ( pData
->IsShared() ) {
643 STATISTICS_ADD(ConcatHit
, 0);
645 // we have to allocate another buffer
646 wxStringData
* pOldData
= GetStringData();
647 AllocBuffer(nNewLen
);
648 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
651 else if ( nNewLen
> pData
->nAllocLength
) {
652 STATISTICS_ADD(ConcatHit
, 0);
654 // we have to grow the buffer
658 STATISTICS_ADD(ConcatHit
, 1);
660 // the buffer is already big enough
663 // should be enough space
664 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
666 // fast concatenation - all is done in our buffer
667 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
669 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
670 GetStringData()->nDataLength
= nNewLen
; // and fix the length
672 //else: the string to append was empty
676 * concatenation functions come in 5 flavours:
678 * char + string and string + char
679 * C str + string and string + C str
682 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
684 wxASSERT( string1
.GetStringData()->IsValid() );
685 wxASSERT( string2
.GetStringData()->IsValid() );
687 wxString s
= string1
;
693 wxString
operator+(const wxString
& string
, wxChar ch
)
695 wxASSERT( string
.GetStringData()->IsValid() );
703 wxString
operator+(wxChar ch
, const wxString
& string
)
705 wxASSERT( string
.GetStringData()->IsValid() );
713 wxString
operator+(const wxString
& string
, const wxChar
*psz
)
715 wxASSERT( string
.GetStringData()->IsValid() );
718 s
.Alloc(wxStrlen(psz
) + string
.Len());
725 wxString
operator+(const wxChar
*psz
, const wxString
& string
)
727 wxASSERT( string
.GetStringData()->IsValid() );
730 s
.Alloc(wxStrlen(psz
) + string
.Len());
737 // ===========================================================================
738 // other common string functions
739 // ===========================================================================
741 // ---------------------------------------------------------------------------
742 // simple sub-string extraction
743 // ---------------------------------------------------------------------------
745 // helper function: clone the data attached to this string
746 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
748 if ( nCopyLen
== 0 ) {
752 dest
.AllocBuffer(nCopyLen
);
753 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
757 // extract string of length nCount starting at nFirst
758 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
760 wxStringData
*pData
= GetStringData();
761 size_t nLen
= pData
->nDataLength
;
763 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
764 if ( nCount
== wxSTRING_MAXLEN
)
766 nCount
= nLen
- nFirst
;
769 // out-of-bounds requests return sensible things
770 if ( nFirst
+ nCount
> nLen
)
772 nCount
= nLen
- nFirst
;
777 // AllocCopy() will return empty string
782 AllocCopy(dest
, nCount
, nFirst
);
787 // check that the tring starts with prefix and return the rest of the string
788 // in the provided pointer if it is not NULL, otherwise return FALSE
789 bool wxString::StartsWith(const wxChar
*prefix
, wxString
*rest
) const
791 wxASSERT_MSG( prefix
, _T("invalid parameter in wxString::StartsWith") );
793 // first check if the beginning of the string matches the prefix: note
794 // that we don't have to check that we don't run out of this string as
795 // when we reach the terminating NUL, either prefix string ends too (and
796 // then it's ok) or we break out of the loop because there is no match
797 const wxChar
*p
= c_str();
800 if ( *prefix
++ != *p
++ )
809 // put the rest of the string into provided pointer
816 // extract nCount last (rightmost) characters
817 wxString
wxString::Right(size_t nCount
) const
819 if ( nCount
> (size_t)GetStringData()->nDataLength
)
820 nCount
= GetStringData()->nDataLength
;
823 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
827 // get all characters after the last occurence of ch
828 // (returns the whole string if ch not found)
829 wxString
wxString::AfterLast(wxChar ch
) const
832 int iPos
= Find(ch
, TRUE
);
833 if ( iPos
== wxNOT_FOUND
)
836 str
= c_str() + iPos
+ 1;
841 // extract nCount first (leftmost) characters
842 wxString
wxString::Left(size_t nCount
) const
844 if ( nCount
> (size_t)GetStringData()->nDataLength
)
845 nCount
= GetStringData()->nDataLength
;
848 AllocCopy(dest
, nCount
, 0);
852 // get all characters before the first occurence of ch
853 // (returns the whole string if ch not found)
854 wxString
wxString::BeforeFirst(wxChar ch
) const
857 for ( const wxChar
*pc
= m_pchData
; *pc
!= wxT('\0') && *pc
!= ch
; pc
++ )
863 /// get all characters before the last occurence of ch
864 /// (returns empty string if ch not found)
865 wxString
wxString::BeforeLast(wxChar ch
) const
868 int iPos
= Find(ch
, TRUE
);
869 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
870 str
= wxString(c_str(), iPos
);
875 /// get all characters after the first occurence of ch
876 /// (returns empty string if ch not found)
877 wxString
wxString::AfterFirst(wxChar ch
) const
881 if ( iPos
!= wxNOT_FOUND
)
882 str
= c_str() + iPos
+ 1;
887 // replace first (or all) occurences of some substring with another one
888 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
890 size_t uiCount
= 0; // count of replacements made
892 size_t uiOldLen
= wxStrlen(szOld
);
895 const wxChar
*pCurrent
= m_pchData
;
896 const wxChar
*pSubstr
;
897 while ( *pCurrent
!= wxT('\0') ) {
898 pSubstr
= wxStrstr(pCurrent
, szOld
);
899 if ( pSubstr
== NULL
) {
900 // strTemp is unused if no replacements were made, so avoid the copy
904 strTemp
+= pCurrent
; // copy the rest
905 break; // exit the loop
908 // take chars before match
909 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
911 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
916 if ( !bReplaceAll
) {
917 strTemp
+= pCurrent
; // copy the rest
918 break; // exit the loop
923 // only done if there were replacements, otherwise would have returned above
929 bool wxString::IsAscii() const
931 const wxChar
*s
= (const wxChar
*) *this;
933 if(!isascii(*s
)) return(FALSE
);
939 bool wxString::IsWord() const
941 const wxChar
*s
= (const wxChar
*) *this;
943 if(!wxIsalpha(*s
)) return(FALSE
);
949 bool wxString::IsNumber() const
951 const wxChar
*s
= (const wxChar
*) *this;
953 if ((s
[0] == '-') || (s
[0] == '+')) s
++;
955 if(!wxIsdigit(*s
)) return(FALSE
);
961 wxString
wxString::Strip(stripType w
) const
964 if ( w
& leading
) s
.Trim(FALSE
);
965 if ( w
& trailing
) s
.Trim(TRUE
);
969 // ---------------------------------------------------------------------------
971 // ---------------------------------------------------------------------------
973 wxString
& wxString::MakeUpper()
977 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
978 *p
= (wxChar
)wxToupper(*p
);
983 wxString
& wxString::MakeLower()
987 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
988 *p
= (wxChar
)wxTolower(*p
);
993 // ---------------------------------------------------------------------------
994 // trimming and padding
995 // ---------------------------------------------------------------------------
997 // some compilers (VC++ 6.0 not to name them) return TRUE for a call to
998 // isspace('ê') in the C locale which seems to be broken to me, but we have to
999 // live with this by checking that the character is a 7 bit one - even if this
1000 // may fail to detect some spaces (I don't know if Unicode doesn't have
1001 // space-like symbols somewhere except in the first 128 chars), it is arguably
1002 // still better than trimming away accented letters
1003 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1005 // trims spaces (in the sense of isspace) from left or right side
1006 wxString
& wxString::Trim(bool bFromRight
)
1008 // first check if we're going to modify the string at all
1011 (bFromRight
&& wxSafeIsspace(GetChar(Len() - 1))) ||
1012 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1016 // ok, there is at least one space to trim
1021 // find last non-space character
1022 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
1023 while ( wxSafeIsspace(*psz
) && (psz
>= m_pchData
) )
1026 // truncate at trailing space start
1028 GetStringData()->nDataLength
= psz
- m_pchData
;
1032 // find first non-space character
1033 const wxChar
*psz
= m_pchData
;
1034 while ( wxSafeIsspace(*psz
) )
1037 // fix up data and length
1038 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
1039 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
1040 GetStringData()->nDataLength
= nDataLength
;
1047 // adds nCount characters chPad to the string from either side
1048 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
1050 wxString
s(chPad
, nCount
);
1063 // truncate the string
1064 wxString
& wxString::Truncate(size_t uiLen
)
1066 if ( uiLen
< Len() ) {
1069 *(m_pchData
+ uiLen
) = wxT('\0');
1070 GetStringData()->nDataLength
= uiLen
;
1072 //else: nothing to do, string is already short enough
1077 // ---------------------------------------------------------------------------
1078 // finding (return wxNOT_FOUND if not found and index otherwise)
1079 // ---------------------------------------------------------------------------
1082 int wxString::Find(wxChar ch
, bool bFromEnd
) const
1084 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
1086 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1089 // find a sub-string (like strstr)
1090 int wxString::Find(const wxChar
*pszSub
) const
1092 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
1094 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
1097 // ----------------------------------------------------------------------------
1098 // conversion to numbers
1099 // ----------------------------------------------------------------------------
1101 bool wxString::ToLong(long *val
, int base
) const
1103 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToLong") );
1105 const wxChar
*start
= c_str();
1107 *val
= wxStrtol(start
, &end
, base
);
1109 // return TRUE only if scan was stopped by the terminating NUL and if the
1110 // string was not empty to start with
1111 return !*end
&& (end
!= start
);
1114 bool wxString::ToULong(unsigned long *val
, int base
) const
1116 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToULong") );
1118 const wxChar
*start
= c_str();
1120 *val
= wxStrtoul(start
, &end
, base
);
1122 // return TRUE only if scan was stopped by the terminating NUL and if the
1123 // string was not empty to start with
1124 return !*end
&& (end
!= start
);
1127 bool wxString::ToDouble(double *val
) const
1129 wxCHECK_MSG( val
, FALSE
, _T("NULL pointer in wxString::ToDouble") );
1131 const wxChar
*start
= c_str();
1133 *val
= wxStrtod(start
, &end
);
1135 // return TRUE only if scan was stopped by the terminating NUL and if the
1136 // string was not empty to start with
1137 return !*end
&& (end
!= start
);
1140 // ---------------------------------------------------------------------------
1142 // ---------------------------------------------------------------------------
1145 wxString
wxString::Format(const wxChar
*pszFormat
, ...)
1148 va_start(argptr
, pszFormat
);
1151 s
.PrintfV(pszFormat
, argptr
);
1159 wxString
wxString::FormatV(const wxChar
*pszFormat
, va_list argptr
)
1162 s
.PrintfV(pszFormat
, argptr
);
1166 int wxString::Printf(const wxChar
*pszFormat
, ...)
1169 va_start(argptr
, pszFormat
);
1171 int iLen
= PrintfV(pszFormat
, argptr
);
1178 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1180 #if wxUSE_EXPERIMENTAL_PRINTF
1181 // the new implementation
1183 // buffer to avoid dynamic memory allocation each time for small strings
1184 char szScratch
[1024];
1187 for (size_t n
= 0; pszFormat
[n
]; n
++)
1188 if (pszFormat
[n
] == wxT('%')) {
1189 static char s_szFlags
[256] = "%";
1191 bool adj_left
= FALSE
, in_prec
= FALSE
,
1192 prec_dot
= FALSE
, done
= FALSE
;
1194 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1196 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1197 switch (pszFormat
[++n
]) {
1211 s_szFlags
[flagofs
++] = pszFormat
[n
];
1216 s_szFlags
[flagofs
++] = pszFormat
[n
];
1223 // dot will be auto-added to s_szFlags if non-negative number follows
1228 s_szFlags
[flagofs
++] = pszFormat
[n
];
1233 s_szFlags
[flagofs
++] = pszFormat
[n
];
1239 s_szFlags
[flagofs
++] = pszFormat
[n
];
1244 s_szFlags
[flagofs
++] = pszFormat
[n
];
1248 int len
= va_arg(argptr
, int);
1255 adj_left
= !adj_left
;
1256 s_szFlags
[flagofs
++] = '-';
1261 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1264 case wxT('1'): case wxT('2'): case wxT('3'):
1265 case wxT('4'): case wxT('5'): case wxT('6'):
1266 case wxT('7'): case wxT('8'): case wxT('9'):
1270 while ((pszFormat
[n
]>=wxT('0')) && (pszFormat
[n
]<=wxT('9'))) {
1271 s_szFlags
[flagofs
++] = pszFormat
[n
];
1272 len
= len
*10 + (pszFormat
[n
] - wxT('0'));
1275 if (in_prec
) max_width
= len
;
1276 else min_width
= len
;
1277 n
--; // the main loop pre-increments n again
1287 s_szFlags
[flagofs
++] = pszFormat
[n
];
1288 s_szFlags
[flagofs
] = '\0';
1290 int val
= va_arg(argptr
, int);
1291 ::sprintf(szScratch
, s_szFlags
, val
);
1293 else if (ilen
== -1) {
1294 short int val
= va_arg(argptr
, short int);
1295 ::sprintf(szScratch
, s_szFlags
, val
);
1297 else if (ilen
== 1) {
1298 long int val
= va_arg(argptr
, long int);
1299 ::sprintf(szScratch
, s_szFlags
, val
);
1301 else if (ilen
== 2) {
1302 #if SIZEOF_LONG_LONG
1303 long long int val
= va_arg(argptr
, long long int);
1304 ::sprintf(szScratch
, s_szFlags
, val
);
1306 long int val
= va_arg(argptr
, long int);
1307 ::sprintf(szScratch
, s_szFlags
, val
);
1310 else if (ilen
== 3) {
1311 size_t val
= va_arg(argptr
, size_t);
1312 ::sprintf(szScratch
, s_szFlags
, val
);
1314 *this += wxString(szScratch
);
1323 s_szFlags
[flagofs
++] = pszFormat
[n
];
1324 s_szFlags
[flagofs
] = '\0';
1326 long double val
= va_arg(argptr
, long double);
1327 ::sprintf(szScratch
, s_szFlags
, val
);
1329 double val
= va_arg(argptr
, double);
1330 ::sprintf(szScratch
, s_szFlags
, val
);
1332 *this += wxString(szScratch
);
1337 void *val
= va_arg(argptr
, void *);
1339 s_szFlags
[flagofs
++] = pszFormat
[n
];
1340 s_szFlags
[flagofs
] = '\0';
1341 ::sprintf(szScratch
, s_szFlags
, val
);
1342 *this += wxString(szScratch
);
1348 wxChar val
= va_arg(argptr
, int);
1349 // we don't need to honor padding here, do we?
1356 // wx extension: we'll let %hs mean non-Unicode strings
1357 char *val
= va_arg(argptr
, char *);
1359 // ASCII->Unicode constructor handles max_width right
1360 wxString
s(val
, wxConvLibc
, max_width
);
1362 size_t len
= wxSTRING_MAXLEN
;
1364 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1365 } else val
= wxT("(null)");
1366 wxString
s(val
, len
);
1368 if (s
.Len() < min_width
)
1369 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1372 wxChar
*val
= va_arg(argptr
, wxChar
*);
1373 size_t len
= wxSTRING_MAXLEN
;
1375 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1376 } else val
= wxT("(null)");
1377 wxString
s(val
, len
);
1378 if (s
.Len() < min_width
)
1379 s
.Pad(min_width
- s
.Len(), wxT(' '), adj_left
);
1386 int *val
= va_arg(argptr
, int *);
1389 else if (ilen
== -1) {
1390 short int *val
= va_arg(argptr
, short int *);
1393 else if (ilen
>= 1) {
1394 long int *val
= va_arg(argptr
, long int *);
1400 if (wxIsalpha(pszFormat
[n
]))
1401 // probably some flag not taken care of here yet
1402 s_szFlags
[flagofs
++] = pszFormat
[n
];
1405 *this += wxT('%'); // just to pass the glibc tst-printf.c
1413 } else *this += pszFormat
[n
];
1416 // buffer to avoid dynamic memory allocation each time for small strings
1417 char szScratch
[1024];
1419 // NB: wxVsnprintf() may return either less than the buffer size or -1 if
1420 // there is not enough place depending on implementation
1421 int iLen
= wxVsnprintfA(szScratch
, WXSIZEOF(szScratch
), (char *)pszFormat
, argptr
);
1423 // the whole string is in szScratch
1427 bool outOfMemory
= FALSE
;
1428 int size
= 2*WXSIZEOF(szScratch
);
1429 while ( !outOfMemory
) {
1430 char *buf
= GetWriteBuf(size
);
1432 iLen
= wxVsnprintfA(buf
, size
, pszFormat
, argptr
);
1439 // ok, there was enough space
1443 // still not enough, double it again
1447 if ( outOfMemory
) {
1452 #endif // wxUSE_EXPERIMENTAL_PRINTF/!wxUSE_EXPERIMENTAL_PRINTF
1457 // ----------------------------------------------------------------------------
1458 // misc other operations
1459 // ----------------------------------------------------------------------------
1461 // returns TRUE if the string matches the pattern which may contain '*' and
1462 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1464 bool wxString::Matches(const wxChar
*pszMask
) const
1466 // I disable this code as it doesn't seem to be faster (in fact, it seems
1467 // to be much slower) than the old, hand-written code below and using it
1468 // here requires always linking with libregex even if the user code doesn't
1470 #if 0 // wxUSE_REGEX
1471 // first translate the shell-like mask into a regex
1473 pattern
.reserve(wxStrlen(pszMask
));
1485 pattern
+= _T(".*");
1496 // these characters are special in a RE, quote them
1497 // (however note that we don't quote '[' and ']' to allow
1498 // using them for Unix shell like matching)
1499 pattern
+= _T('\\');
1503 pattern
+= *pszMask
;
1511 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1512 #else // !wxUSE_REGEX
1513 // TODO: this is, of course, awfully inefficient...
1515 // the char currently being checked
1516 const wxChar
*pszTxt
= c_str();
1518 // the last location where '*' matched
1519 const wxChar
*pszLastStarInText
= NULL
;
1520 const wxChar
*pszLastStarInMask
= NULL
;
1523 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1524 switch ( *pszMask
) {
1526 if ( *pszTxt
== wxT('\0') )
1529 // pszTxt and pszMask will be incremented in the loop statement
1535 // remember where we started to be able to backtrack later
1536 pszLastStarInText
= pszTxt
;
1537 pszLastStarInMask
= pszMask
;
1539 // ignore special chars immediately following this one
1540 // (should this be an error?)
1541 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
1544 // if there is nothing more, match
1545 if ( *pszMask
== wxT('\0') )
1548 // are there any other metacharacters in the mask?
1550 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
1552 if ( pEndMask
!= NULL
) {
1553 // we have to match the string between two metachars
1554 uiLenMask
= pEndMask
- pszMask
;
1557 // we have to match the remainder of the string
1558 uiLenMask
= wxStrlen(pszMask
);
1561 wxString
strToMatch(pszMask
, uiLenMask
);
1562 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1563 if ( pMatch
== NULL
)
1566 // -1 to compensate "++" in the loop
1567 pszTxt
= pMatch
+ uiLenMask
- 1;
1568 pszMask
+= uiLenMask
- 1;
1573 if ( *pszMask
!= *pszTxt
)
1579 // match only if nothing left
1580 if ( *pszTxt
== wxT('\0') )
1583 // if we failed to match, backtrack if we can
1584 if ( pszLastStarInText
) {
1585 pszTxt
= pszLastStarInText
+ 1;
1586 pszMask
= pszLastStarInMask
;
1588 pszLastStarInText
= NULL
;
1590 // don't bother resetting pszLastStarInMask, it's unnecessary
1596 #endif // wxUSE_REGEX/!wxUSE_REGEX
1599 // Count the number of chars
1600 int wxString::Freq(wxChar ch
) const
1604 for (int i
= 0; i
< len
; i
++)
1606 if (GetChar(i
) == ch
)
1612 // convert to upper case, return the copy of the string
1613 wxString
wxString::Upper() const
1614 { wxString
s(*this); return s
.MakeUpper(); }
1616 // convert to lower case, return the copy of the string
1617 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1619 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1622 va_start(argptr
, pszFormat
);
1623 int iLen
= PrintfV(pszFormat
, argptr
);
1628 // ---------------------------------------------------------------------------
1629 // standard C++ library string functions
1630 // ---------------------------------------------------------------------------
1632 #ifdef wxSTD_STRING_COMPATIBILITY
1634 void wxString::resize(size_t nSize
, wxChar ch
)
1636 size_t len
= length();
1642 else if ( nSize
> len
)
1644 *this += wxString(ch
, nSize
- len
);
1646 //else: we have exactly the specified length, nothing to do
1649 void wxString::swap(wxString
& str
)
1651 // this is slightly less efficient than fiddling with m_pchData directly,
1652 // but it is still quite efficient as we don't copy the string here because
1653 // ref count always stays positive
1659 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1661 wxASSERT( str
.GetStringData()->IsValid() );
1662 wxASSERT( nPos
<= Len() );
1664 if ( !str
.IsEmpty() ) {
1666 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1667 wxStrncpy(pc
, c_str(), nPos
);
1668 wxStrcpy(pc
+ nPos
, str
);
1669 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1670 strTmp
.UngetWriteBuf();
1677 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1679 wxASSERT( str
.GetStringData()->IsValid() );
1680 wxASSERT( nStart
<= Len() );
1682 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1684 return p
== NULL
? npos
: p
- c_str();
1687 // VC++ 1.5 can't cope with the default argument in the header.
1688 #if !defined(__VISUALC__) || defined(__WIN32__)
1689 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1691 return find(wxString(sz
, n
), nStart
);
1695 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1696 #if !defined(__BORLANDC__)
1697 size_t wxString::find(wxChar ch
, size_t nStart
) const
1699 wxASSERT( nStart
<= Len() );
1701 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1703 return p
== NULL
? npos
: p
- c_str();
1707 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1709 wxASSERT( str
.GetStringData()->IsValid() );
1710 wxASSERT( nStart
== npos
|| nStart
<= Len() );
1712 // TODO could be made much quicker than that
1713 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1714 while ( p
>= c_str() + str
.Len() ) {
1715 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1716 return p
- str
.Len() - c_str();
1723 // VC++ 1.5 can't cope with the default argument in the header.
1724 #if !defined(__VISUALC__) || defined(__WIN32__)
1725 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1727 return rfind(wxString(sz
, n
== npos
? wxSTRING_MAXLEN
: n
), nStart
);
1730 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1732 if ( nStart
== npos
)
1738 wxASSERT( nStart
<= Len() );
1741 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1746 size_t result
= p
- c_str();
1747 return ( result
> nStart
) ? npos
: result
;
1751 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1753 const wxChar
*start
= c_str() + nStart
;
1754 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1756 return firstOf
- c_str();
1761 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1763 if ( nStart
== npos
)
1769 wxASSERT( nStart
<= Len() );
1772 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1774 if ( wxStrchr(sz
, *p
) )
1781 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1783 if ( nStart
== npos
)
1789 wxASSERT( nStart
<= Len() );
1792 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1793 if ( nAccept
>= length() - nStart
)
1799 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1801 wxASSERT( nStart
<= Len() );
1803 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1812 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1814 if ( nStart
== npos
)
1820 wxASSERT( nStart
<= Len() );
1823 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1825 if ( !wxStrchr(sz
, *p
) )
1832 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1834 if ( nStart
== npos
)
1840 wxASSERT( nStart
<= Len() );
1843 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1852 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1854 wxString
strTmp(c_str(), nStart
);
1855 if ( nLen
!= npos
) {
1856 wxASSERT( nStart
+ nLen
<= Len() );
1858 strTmp
.append(c_str() + nStart
+ nLen
);
1865 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1867 wxASSERT_MSG( nStart
+ nLen
<= Len(),
1868 _T("index out of bounds in wxString::replace") );
1871 strTmp
.Alloc(Len()); // micro optimisation to avoid multiple mem allocs
1874 strTmp
.append(c_str(), nStart
);
1875 strTmp
<< sz
<< c_str() + nStart
+ nLen
;
1881 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1883 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1886 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1887 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1889 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1892 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1893 const wxChar
* sz
, size_t nCount
)
1895 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1898 #endif //std::string compatibility
1900 // ============================================================================
1902 // ============================================================================
1904 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1905 #define ARRAY_MAXSIZE_INCREMENT 4096
1907 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1908 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1911 #define STRING(p) ((wxString *)(&(p)))
1914 void wxArrayString::Init(bool autoSort
)
1918 m_pItems
= (wxChar
**) NULL
;
1919 m_autoSort
= autoSort
;
1923 wxArrayString::wxArrayString(const wxArrayString
& src
)
1925 Init(src
.m_autoSort
);
1930 // assignment operator
1931 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1938 m_autoSort
= src
.m_autoSort
;
1943 void wxArrayString::Copy(const wxArrayString
& src
)
1945 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1946 Alloc(src
.m_nCount
);
1948 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1953 void wxArrayString::Grow()
1955 // only do it if no more place
1956 if ( m_nCount
== m_nSize
) {
1957 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
1958 // be never resized!
1959 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
1960 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
1963 if ( m_nSize
== 0 ) {
1964 // was empty, alloc some memory
1965 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1966 m_pItems
= new wxChar
*[m_nSize
];
1969 // otherwise when it's called for the first time, nIncrement would be 0
1970 // and the array would never be expanded
1971 // add 50% but not too much
1972 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1973 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1974 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1975 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1976 m_nSize
+= nIncrement
;
1977 wxChar
**pNew
= new wxChar
*[m_nSize
];
1979 // copy data to new location
1980 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1982 // delete old memory (but do not release the strings!)
1983 wxDELETEA(m_pItems
);
1990 void wxArrayString::Free()
1992 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1993 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1997 // deletes all the strings from the list
1998 void wxArrayString::Empty()
2005 // as Empty, but also frees memory
2006 void wxArrayString::Clear()
2013 wxDELETEA(m_pItems
);
2017 wxArrayString::~wxArrayString()
2021 wxDELETEA(m_pItems
);
2024 // pre-allocates memory (frees the previous data!)
2025 void wxArrayString::Alloc(size_t nSize
)
2027 // only if old buffer was not big enough
2028 if ( nSize
> m_nSize
) {
2030 wxDELETEA(m_pItems
);
2031 m_pItems
= new wxChar
*[nSize
];
2038 // minimizes the memory usage by freeing unused memory
2039 void wxArrayString::Shrink()
2041 // only do it if we have some memory to free
2042 if( m_nCount
< m_nSize
) {
2043 // allocates exactly as much memory as we need
2044 wxChar
**pNew
= new wxChar
*[m_nCount
];
2046 // copy data to new location
2047 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
2053 // return a wxString[] as required for some control ctors.
2054 wxString
* wxArrayString::GetStringArray() const
2056 wxString
*array
= 0;
2060 array
= new wxString
[m_nCount
];
2061 for( size_t i
= 0; i
< m_nCount
; i
++ )
2062 array
[i
] = m_pItems
[i
];
2068 // searches the array for an item (forward or backwards)
2069 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
2072 // use binary search in the sorted array
2073 wxASSERT_MSG( bCase
&& !bFromEnd
,
2074 wxT("search parameters ignored for auto sorted array") );
2083 res
= wxStrcmp(sz
, m_pItems
[i
]);
2095 // use linear search in unsorted array
2097 if ( m_nCount
> 0 ) {
2098 size_t ui
= m_nCount
;
2100 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
2107 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
2108 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
2117 // add item at the end
2118 size_t wxArrayString::Add(const wxString
& str
)
2121 // insert the string at the correct position to keep the array sorted
2129 res
= wxStrcmp(str
, m_pItems
[i
]);
2140 wxASSERT_MSG( lo
== hi
, wxT("binary search broken") );
2147 wxASSERT( str
.GetStringData()->IsValid() );
2151 // the string data must not be deleted!
2152 str
.GetStringData()->Lock();
2155 m_pItems
[m_nCount
] = (wxChar
*)str
.c_str(); // const_cast
2161 // add item at the given position
2162 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
2164 wxASSERT( str
.GetStringData()->IsValid() );
2166 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Insert") );
2170 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
2171 (m_nCount
- nIndex
)*sizeof(wxChar
*));
2173 str
.GetStringData()->Lock();
2174 m_pItems
[nIndex
] = (wxChar
*)str
.c_str();
2180 void wxArrayString::SetCount(size_t count
)
2185 while ( m_nCount
< count
)
2186 m_pItems
[m_nCount
++] = (wxChar
*)s
.c_str();
2189 // removes item from array (by index)
2190 void wxArrayString::Remove(size_t nIndex
)
2192 wxCHECK_RET( nIndex
<= m_nCount
, wxT("bad index in wxArrayString::Remove") );
2195 Item(nIndex
).GetStringData()->Unlock();
2197 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
2198 (m_nCount
- nIndex
- 1)*sizeof(wxChar
*));
2202 // removes item from array (by value)
2203 void wxArrayString::Remove(const wxChar
*sz
)
2205 int iIndex
= Index(sz
);
2207 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
2208 wxT("removing inexistent element in wxArrayString::Remove") );
2213 // ----------------------------------------------------------------------------
2215 // ----------------------------------------------------------------------------
2217 // we can only sort one array at a time with the quick-sort based
2220 // need a critical section to protect access to gs_compareFunction and
2221 // gs_sortAscending variables
2222 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
2224 // call this before the value of the global sort vars is changed/after
2225 // you're finished with them
2226 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2227 gs_critsectStringSort = new wxCriticalSection; \
2228 gs_critsectStringSort->Enter()
2229 #define END_SORT() gs_critsectStringSort->Leave(); \
2230 delete gs_critsectStringSort; \
2231 gs_critsectStringSort = NULL
2233 #define START_SORT()
2235 #endif // wxUSE_THREADS
2237 // function to use for string comparaison
2238 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
2240 // if we don't use the compare function, this flag tells us if we sort the
2241 // array in ascending or descending order
2242 static bool gs_sortAscending
= TRUE
;
2244 // function which is called by quick sort
2245 extern "C" int LINKAGEMODE
2246 wxStringCompareFunction(const void *first
, const void *second
)
2248 wxString
*strFirst
= (wxString
*)first
;
2249 wxString
*strSecond
= (wxString
*)second
;
2251 if ( gs_compareFunction
) {
2252 return gs_compareFunction(*strFirst
, *strSecond
);
2255 // maybe we should use wxStrcoll
2256 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
2258 return gs_sortAscending
? result
: -result
;
2262 // sort array elements using passed comparaison function
2263 void wxArrayString::Sort(CompareFunction compareFunction
)
2267 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2268 gs_compareFunction
= compareFunction
;
2272 // reset it to NULL so that Sort(bool) will work the next time
2273 gs_compareFunction
= NULL
;
2278 void wxArrayString::Sort(bool reverseOrder
)
2282 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
2283 gs_sortAscending
= !reverseOrder
;
2290 void wxArrayString::DoSort()
2292 wxCHECK_RET( !m_autoSort
, wxT("can't use this method with sorted arrays") );
2294 // just sort the pointers using qsort() - of course it only works because
2295 // wxString() *is* a pointer to its data
2296 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
2299 bool wxArrayString::operator==(const wxArrayString
& a
) const
2301 if ( m_nCount
!= a
.m_nCount
)
2304 for ( size_t n
= 0; n
< m_nCount
; n
++ )
2306 if ( Item(n
) != a
[n
] )