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"
49 #include <wchar.h> // for wcsrtombs(), see comments where it's used
52 #ifdef WXSTRING_IS_WXOBJECT
53 IMPLEMENT_DYNAMIC_CLASS(wxString
, wxObject
)
54 #endif //WXSTRING_IS_WXOBJECT
56 // allocating extra space for each string consumes more memory but speeds up
57 // the concatenation operations (nLen is the current string's length)
58 // NB: EXTRA_ALLOC must be >= 0!
59 #define EXTRA_ALLOC (19 - nLen % 16)
61 // ---------------------------------------------------------------------------
62 // static class variables definition
63 // ---------------------------------------------------------------------------
65 #ifdef wxSTD_STRING_COMPATIBILITY
66 const size_t wxString::npos
= wxSTRING_MAXLEN
;
67 #endif // wxSTD_STRING_COMPATIBILITY
69 // ----------------------------------------------------------------------------
71 // ----------------------------------------------------------------------------
73 // for an empty string, GetStringData() will return this address: this
74 // structure has the same layout as wxStringData and it's data() method will
75 // return the empty string (dummy pointer)
80 } g_strEmpty
= { {-1, 0, 0}, _T('\0') };
82 // empty C style string: points to 'string data' byte of g_strEmpty
83 extern const wxChar WXDLLEXPORT
*g_szNul
= &g_strEmpty
.dummy
;
85 // ----------------------------------------------------------------------------
86 // conditional compilation
87 // ----------------------------------------------------------------------------
89 // we want to find out if the current platform supports vsnprintf()-like
90 // function: for Unix this is done with configure, for Windows we test the
91 // compiler explicitly.
94 #define wxVsnprintf _vsnprintf
98 #define wxVsnprintf vsnprintf
100 #endif // Windows/!Windows
103 // in this case we'll use vsprintf() (which is ANSI and thus should be
104 // always available), but it's unsafe because it doesn't check for buffer
105 // size - so give a warning
106 #define wxVsnprintf(buffer,len,format,argptr) vsprintf(buffer,format, argptr)
108 #if defined(__VISUALC__)
109 #pragma message("Using sprintf() because no snprintf()-like function defined")
110 #elif defined(__GNUG__) && !defined(__UNIX__)
111 #warning "Using sprintf() because no snprintf()-like function defined"
112 #elif defined(__MWERKS__)
113 #warning "Using sprintf() because no snprintf()-like function defined"
115 #endif // no vsnprintf
118 // AIX has vsnprintf, but there's no prototype in the system headers.
119 extern "C" int vsnprintf(char* str
, size_t n
, const char* format
, va_list ap
);
122 // ----------------------------------------------------------------------------
124 // ----------------------------------------------------------------------------
126 #ifdef wxSTD_STRING_COMPATIBILITY
128 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
131 // ATTN: you can _not_ use both of these in the same program!
133 istream
& operator>>(istream
& is
, wxString
& WXUNUSED(str
))
138 streambuf
*sb
= is
.rdbuf();
141 int ch
= sb
->sbumpc ();
143 is
.setstate(ios::eofbit
);
146 else if ( isspace(ch
) ) {
158 if ( str
.length() == 0 )
159 is
.setstate(ios::failbit
);
164 #endif //std::string compatibility
166 // ----------------------------------------------------------------------------
168 // ----------------------------------------------------------------------------
170 // this small class is used to gather statistics for performance tuning
171 //#define WXSTRING_STATISTICS
172 #ifdef WXSTRING_STATISTICS
176 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
178 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
180 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
183 size_t m_nCount
, m_nTotal
;
185 } g_averageLength("allocation size"),
186 g_averageSummandLength("summand length"),
187 g_averageConcatHit("hit probability in concat"),
188 g_averageInitialLength("initial string length");
190 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
192 #define STATISTICS_ADD(av, val)
193 #endif // WXSTRING_STATISTICS
195 // ===========================================================================
196 // wxString class core
197 // ===========================================================================
199 // ---------------------------------------------------------------------------
201 // ---------------------------------------------------------------------------
203 // constructs string of <nLength> copies of character <ch>
204 wxString::wxString(wxChar ch
, size_t nLength
)
209 AllocBuffer(nLength
);
212 // memset only works on char
213 for (size_t n
=0; n
<nLength
; n
++) m_pchData
[n
] = ch
;
215 memset(m_pchData
, ch
, nLength
);
220 // takes nLength elements of psz starting at nPos
221 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
225 wxASSERT( nPos
<= wxStrlen(psz
) );
227 if ( nLength
== wxSTRING_MAXLEN
)
228 nLength
= wxStrlen(psz
+ nPos
);
230 STATISTICS_ADD(InitialLength
, nLength
);
233 // trailing '\0' is written in AllocBuffer()
234 AllocBuffer(nLength
);
235 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
239 #ifdef wxSTD_STRING_COMPATIBILITY
241 // poor man's iterators are "void *" pointers
242 wxString::wxString(const void *pStart
, const void *pEnd
)
244 InitWith((const wxChar
*)pStart
, 0,
245 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
248 #endif //std::string compatibility
252 // from multibyte string
253 wxString::wxString(const char *psz
, wxMBConvv
& conv
, size_t nLength
)
255 // first get necessary size
257 size_t nLen
= conv
.MB2WC((wchar_t *) NULL
, psz
, 0);
259 // nLength is number of *Unicode* characters here!
266 conv
.MB2WC(m_pchData
, psz
, nLen
);
276 wxString::wxString(const wchar_t *pwz
)
278 // first get necessary size
280 size_t nLen
= wxWC2MB((char *) NULL
, pwz
, 0);
285 wxWC2MB(m_pchData
, pwz
, nLen
);
294 // ---------------------------------------------------------------------------
295 // multibyte<->Unicode conversion
296 // ---------------------------------------------------------------------------
299 const wxCharBuffer
& mb_str(wxMBConv
& conv
) const
301 size_t nLen
= conv
.WC2MB((char *) NULL
, m_pchData
, 0);
302 wxCharBuffer
buf(nLen
);
303 conv
.WC2MB(buf
, m_pchData
, nLen
);
306 const wxWCharBuffer
& wc_str(wxMBConv
& conv
) const
308 size_t nLen
= conv
.MB2WC((wchar_t *) NULL
, m_pchData
, 0);
309 wxCharBuffer
buf(nLen
);
310 conv
.MB2WC(buf
, m_pchData
, nLen
);
314 // ---------------------------------------------------------------------------
316 // ---------------------------------------------------------------------------
318 // allocates memory needed to store a C string of length nLen
319 void wxString::AllocBuffer(size_t nLen
)
321 wxASSERT( nLen
> 0 ); //
322 wxASSERT( nLen
<= INT_MAX
-1 ); // max size (enough room for 1 extra)
324 STATISTICS_ADD(Length
, nLen
);
327 // 1) one extra character for '\0' termination
328 // 2) sizeof(wxStringData) for housekeeping info
329 wxStringData
* pData
= (wxStringData
*)
330 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
332 pData
->nDataLength
= nLen
;
333 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
334 m_pchData
= pData
->data(); // data starts after wxStringData
335 m_pchData
[nLen
] = _T('\0');
338 // must be called before changing this string
339 void wxString::CopyBeforeWrite()
341 wxStringData
* pData
= GetStringData();
343 if ( pData
->IsShared() ) {
344 pData
->Unlock(); // memory not freed because shared
345 size_t nLen
= pData
->nDataLength
;
347 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
350 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
353 // must be called before replacing contents of this string
354 void wxString::AllocBeforeWrite(size_t nLen
)
356 wxASSERT( nLen
!= 0 ); // doesn't make any sense
358 // must not share string and must have enough space
359 wxStringData
* pData
= GetStringData();
360 if ( pData
->IsShared() || (nLen
> pData
->nAllocLength
) ) {
361 // can't work with old buffer, get new one
366 // update the string length
367 pData
->nDataLength
= nLen
;
370 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
373 // allocate enough memory for nLen characters
374 void wxString::Alloc(size_t nLen
)
376 wxStringData
*pData
= GetStringData();
377 if ( pData
->nAllocLength
<= nLen
) {
378 if ( pData
->IsEmpty() ) {
381 wxStringData
* pData
= (wxStringData
*)
382 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
384 pData
->nDataLength
= 0;
385 pData
->nAllocLength
= nLen
;
386 m_pchData
= pData
->data(); // data starts after wxStringData
387 m_pchData
[0u] = _T('\0');
389 else if ( pData
->IsShared() ) {
390 pData
->Unlock(); // memory not freed because shared
391 size_t nOldLen
= pData
->nDataLength
;
393 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
398 wxStringData
*p
= (wxStringData
*)
399 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
402 // @@@ what to do on memory error?
406 // it's not important if the pointer changed or not (the check for this
407 // is not faster than assigning to m_pchData in all cases)
408 p
->nAllocLength
= nLen
;
409 m_pchData
= p
->data();
412 //else: we've already got enough
415 // shrink to minimal size (releasing extra memory)
416 void wxString::Shrink()
418 wxStringData
*pData
= GetStringData();
420 // this variable is unused in release build, so avoid the compiler warning by
421 // just not declaring it
425 realloc(pData
, sizeof(wxStringData
) + (pData
->nDataLength
+ 1)*sizeof(wxChar
));
427 wxASSERT( p
!= NULL
); // can't free memory?
428 wxASSERT( p
== pData
); // we're decrementing the size - block shouldn't move!
431 // get the pointer to writable buffer of (at least) nLen bytes
432 wxChar
*wxString::GetWriteBuf(size_t nLen
)
434 AllocBeforeWrite(nLen
);
436 wxASSERT( GetStringData()->nRefs
== 1 );
437 GetStringData()->Validate(FALSE
);
442 // put string back in a reasonable state after GetWriteBuf
443 void wxString::UngetWriteBuf()
445 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
446 GetStringData()->Validate(TRUE
);
449 // ---------------------------------------------------------------------------
451 // ---------------------------------------------------------------------------
453 // all functions are inline in string.h
455 // ---------------------------------------------------------------------------
456 // assignment operators
457 // ---------------------------------------------------------------------------
459 // helper function: does real copy
460 void wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
462 if ( nSrcLen
== 0 ) {
466 AllocBeforeWrite(nSrcLen
);
467 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
468 GetStringData()->nDataLength
= nSrcLen
;
469 m_pchData
[nSrcLen
] = _T('\0');
473 // assigns one string to another
474 wxString
& wxString::operator=(const wxString
& stringSrc
)
476 wxASSERT( stringSrc
.GetStringData()->IsValid() );
478 // don't copy string over itself
479 if ( m_pchData
!= stringSrc
.m_pchData
) {
480 if ( stringSrc
.GetStringData()->IsEmpty() ) {
485 GetStringData()->Unlock();
486 m_pchData
= stringSrc
.m_pchData
;
487 GetStringData()->Lock();
494 // assigns a single character
495 wxString
& wxString::operator=(wxChar ch
)
502 wxString
& wxString::operator=(const wxChar
*psz
)
504 AssignCopy(wxStrlen(psz
), psz
);
510 // same as 'signed char' variant
511 wxString
& wxString::operator=(const unsigned char* psz
)
513 *this = (const char *)psz
;
517 wxString
& wxString::operator=(const wchar_t *pwz
)
526 // ---------------------------------------------------------------------------
527 // string concatenation
528 // ---------------------------------------------------------------------------
530 // add something to this string
531 void wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
533 STATISTICS_ADD(SummandLength
, nSrcLen
);
535 // concatenating an empty string is a NOP
537 wxStringData
*pData
= GetStringData();
538 size_t nLen
= pData
->nDataLength
;
539 size_t nNewLen
= nLen
+ nSrcLen
;
541 // alloc new buffer if current is too small
542 if ( pData
->IsShared() ) {
543 STATISTICS_ADD(ConcatHit
, 0);
545 // we have to allocate another buffer
546 wxStringData
* pOldData
= GetStringData();
547 AllocBuffer(nNewLen
);
548 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
551 else if ( nNewLen
> pData
->nAllocLength
) {
552 STATISTICS_ADD(ConcatHit
, 0);
554 // we have to grow the buffer
558 STATISTICS_ADD(ConcatHit
, 1);
560 // the buffer is already big enough
563 // should be enough space
564 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
566 // fast concatenation - all is done in our buffer
567 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
569 m_pchData
[nNewLen
] = _T('\0'); // put terminating '\0'
570 GetStringData()->nDataLength
= nNewLen
; // and fix the length
572 //else: the string to append was empty
576 * concatenation functions come in 5 flavours:
578 * char + string and string + char
579 * C str + string and string + C str
582 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
584 wxASSERT( string1
.GetStringData()->IsValid() );
585 wxASSERT( string2
.GetStringData()->IsValid() );
587 wxString s
= string1
;
593 wxString
operator+(const wxString
& string
, wxChar ch
)
595 wxASSERT( string
.GetStringData()->IsValid() );
603 wxString
operator+(wxChar ch
, const wxString
& string
)
605 wxASSERT( string
.GetStringData()->IsValid() );
613 wxString
operator+(const wxString
& string
, const wxChar
*psz
)
615 wxASSERT( string
.GetStringData()->IsValid() );
618 s
.Alloc(wxStrlen(psz
) + string
.Len());
625 wxString
operator+(const wxChar
*psz
, const wxString
& string
)
627 wxASSERT( string
.GetStringData()->IsValid() );
630 s
.Alloc(wxStrlen(psz
) + string
.Len());
637 // ===========================================================================
638 // other common string functions
639 // ===========================================================================
641 // ---------------------------------------------------------------------------
642 // simple sub-string extraction
643 // ---------------------------------------------------------------------------
645 // helper function: clone the data attached to this string
646 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
648 if ( nCopyLen
== 0 ) {
652 dest
.AllocBuffer(nCopyLen
);
653 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
657 // extract string of length nCount starting at nFirst
658 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
660 wxStringData
*pData
= GetStringData();
661 size_t nLen
= pData
->nDataLength
;
663 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
664 if ( nCount
== wxSTRING_MAXLEN
)
666 nCount
= nLen
- nFirst
;
669 // out-of-bounds requests return sensible things
670 if ( nFirst
+ nCount
> nLen
)
672 nCount
= nLen
- nFirst
;
677 // AllocCopy() will return empty string
682 AllocCopy(dest
, nCount
, nFirst
);
687 // extract nCount last (rightmost) characters
688 wxString
wxString::Right(size_t nCount
) const
690 if ( nCount
> (size_t)GetStringData()->nDataLength
)
691 nCount
= GetStringData()->nDataLength
;
694 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
698 // get all characters after the last occurence of ch
699 // (returns the whole string if ch not found)
700 wxString
wxString::AfterLast(wxChar ch
) const
703 int iPos
= Find(ch
, TRUE
);
704 if ( iPos
== wxNOT_FOUND
)
707 str
= c_str() + iPos
+ 1;
712 // extract nCount first (leftmost) characters
713 wxString
wxString::Left(size_t nCount
) const
715 if ( nCount
> (size_t)GetStringData()->nDataLength
)
716 nCount
= GetStringData()->nDataLength
;
719 AllocCopy(dest
, nCount
, 0);
723 // get all characters before the first occurence of ch
724 // (returns the whole string if ch not found)
725 wxString
wxString::BeforeFirst(wxChar ch
) const
728 for ( const wxChar
*pc
= m_pchData
; *pc
!= _T('\0') && *pc
!= ch
; pc
++ )
734 /// get all characters before the last occurence of ch
735 /// (returns empty string if ch not found)
736 wxString
wxString::BeforeLast(wxChar ch
) const
739 int iPos
= Find(ch
, TRUE
);
740 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
741 str
= wxString(c_str(), iPos
);
746 /// get all characters after the first occurence of ch
747 /// (returns empty string if ch not found)
748 wxString
wxString::AfterFirst(wxChar ch
) const
752 if ( iPos
!= wxNOT_FOUND
)
753 str
= c_str() + iPos
+ 1;
758 // replace first (or all) occurences of some substring with another one
759 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
761 size_t uiCount
= 0; // count of replacements made
763 size_t uiOldLen
= wxStrlen(szOld
);
766 const wxChar
*pCurrent
= m_pchData
;
767 const wxChar
*pSubstr
;
768 while ( *pCurrent
!= _T('\0') ) {
769 pSubstr
= wxStrstr(pCurrent
, szOld
);
770 if ( pSubstr
== NULL
) {
771 // strTemp is unused if no replacements were made, so avoid the copy
775 strTemp
+= pCurrent
; // copy the rest
776 break; // exit the loop
779 // take chars before match
780 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
782 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
787 if ( !bReplaceAll
) {
788 strTemp
+= pCurrent
; // copy the rest
789 break; // exit the loop
794 // only done if there were replacements, otherwise would have returned above
800 bool wxString::IsAscii() const
802 const wxChar
*s
= (const wxChar
*) *this;
804 if(!isascii(*s
)) return(FALSE
);
810 bool wxString::IsWord() const
812 const wxChar
*s
= (const wxChar
*) *this;
814 if(!wxIsalpha(*s
)) return(FALSE
);
820 bool wxString::IsNumber() const
822 const wxChar
*s
= (const wxChar
*) *this;
824 if(!wxIsdigit(*s
)) return(FALSE
);
830 wxString
wxString::Strip(stripType w
) const
833 if ( w
& leading
) s
.Trim(FALSE
);
834 if ( w
& trailing
) s
.Trim(TRUE
);
838 // ---------------------------------------------------------------------------
840 // ---------------------------------------------------------------------------
842 wxString
& wxString::MakeUpper()
846 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
847 *p
= (wxChar
)wxToupper(*p
);
852 wxString
& wxString::MakeLower()
856 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
857 *p
= (wxChar
)wxTolower(*p
);
862 // ---------------------------------------------------------------------------
863 // trimming and padding
864 // ---------------------------------------------------------------------------
866 // trims spaces (in the sense of isspace) from left or right side
867 wxString
& wxString::Trim(bool bFromRight
)
869 // first check if we're going to modify the string at all
872 (bFromRight
&& wxIsspace(GetChar(Len() - 1))) ||
873 (!bFromRight
&& wxIsspace(GetChar(0u)))
877 // ok, there is at least one space to trim
882 // find last non-space character
883 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
884 while ( wxIsspace(*psz
) && (psz
>= m_pchData
) )
887 // truncate at trailing space start
889 GetStringData()->nDataLength
= psz
- m_pchData
;
893 // find first non-space character
894 const wxChar
*psz
= m_pchData
;
895 while ( wxIsspace(*psz
) )
898 // fix up data and length
899 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
900 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
901 GetStringData()->nDataLength
= nDataLength
;
908 // adds nCount characters chPad to the string from either side
909 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
911 wxString
s(chPad
, nCount
);
924 // truncate the string
925 wxString
& wxString::Truncate(size_t uiLen
)
927 if ( uiLen
< Len() ) {
930 *(m_pchData
+ uiLen
) = _T('\0');
931 GetStringData()->nDataLength
= uiLen
;
933 //else: nothing to do, string is already short enough
938 // ---------------------------------------------------------------------------
939 // finding (return wxNOT_FOUND if not found and index otherwise)
940 // ---------------------------------------------------------------------------
943 int wxString::Find(wxChar ch
, bool bFromEnd
) const
945 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
947 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
950 // find a sub-string (like strstr)
951 int wxString::Find(const wxChar
*pszSub
) const
953 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
955 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
958 // ---------------------------------------------------------------------------
959 // stream-like operators
960 // ---------------------------------------------------------------------------
961 wxString
& wxString::operator<<(int i
)
964 res
.Printf(_T("%d"), i
);
966 return (*this) << res
;
969 wxString
& wxString::operator<<(float f
)
972 res
.Printf(_T("%f"), f
);
974 return (*this) << res
;
977 wxString
& wxString::operator<<(double d
)
980 res
.Printf(_T("%g"), d
);
982 return (*this) << res
;
985 // ---------------------------------------------------------------------------
987 // ---------------------------------------------------------------------------
988 int wxString::Printf(const wxChar
*pszFormat
, ...)
991 va_start(argptr
, pszFormat
);
993 int iLen
= PrintfV(pszFormat
, argptr
);
1000 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1002 // static buffer to avoid dynamic memory allocation each time
1003 static char s_szScratch
[1024];
1005 // protect the static buffer
1006 static wxCriticalSection critsect
;
1007 wxCriticalSectionLocker
lock(critsect
);
1010 #if 1 // the new implementation
1013 for (size_t n
= 0; pszFormat
[n
]; n
++)
1014 if (pszFormat
[n
] == _T('%')) {
1015 static char s_szFlags
[256] = "%";
1017 bool adj_left
= FALSE
, in_prec
= FALSE
,
1018 prec_dot
= FALSE
, done
= FALSE
;
1020 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1022 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1023 switch (pszFormat
[++n
]) {
1037 s_szFlags
[flagofs
++] = pszFormat
[n
];
1042 s_szFlags
[flagofs
++] = pszFormat
[n
];
1049 // dot will be auto-added to s_szFlags if non-negative number follows
1054 s_szFlags
[flagofs
++] = pszFormat
[n
];
1059 s_szFlags
[flagofs
++] = pszFormat
[n
];
1065 s_szFlags
[flagofs
++] = pszFormat
[n
];
1070 s_szFlags
[flagofs
++] = pszFormat
[n
];
1074 int len
= va_arg(argptr
, int);
1081 adj_left
= !adj_left
;
1082 s_szFlags
[flagofs
++] = '-';
1087 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1090 case _T('1'): case _T('2'): case _T('3'):
1091 case _T('4'): case _T('5'): case _T('6'):
1092 case _T('7'): case _T('8'): case _T('9'):
1096 while ((pszFormat
[n
]>=_T('0')) && (pszFormat
[n
]<=_T('9'))) {
1097 s_szFlags
[flagofs
++] = pszFormat
[n
];
1098 len
= len
*10 + (pszFormat
[n
] - _T('0'));
1101 if (in_prec
) max_width
= len
;
1102 else min_width
= len
;
1103 n
--; // the main loop pre-increments n again
1113 s_szFlags
[flagofs
++] = pszFormat
[n
];
1114 s_szFlags
[flagofs
] = '\0';
1116 int val
= va_arg(argptr
, int);
1117 ::sprintf(s_szScratch
, s_szFlags
, val
);
1119 else if (ilen
== -1) {
1120 short int val
= va_arg(argptr
, short int);
1121 ::sprintf(s_szScratch
, s_szFlags
, val
);
1123 else if (ilen
== 1) {
1124 long int val
= va_arg(argptr
, long int);
1125 ::sprintf(s_szScratch
, s_szFlags
, val
);
1127 else if (ilen
== 2) {
1128 #if SIZEOF_LONG_LONG
1129 long long int val
= va_arg(argptr
, long long int);
1130 ::sprintf(s_szScratch
, s_szFlags
, val
);
1132 long int val
= va_arg(argptr
, long int);
1133 ::sprintf(s_szScratch
, s_szFlags
, val
);
1136 else if (ilen
== 3) {
1137 size_t val
= va_arg(argptr
, size_t);
1138 ::sprintf(s_szScratch
, s_szFlags
, val
);
1140 *this += wxString(s_szScratch
);
1149 s_szFlags
[flagofs
++] = pszFormat
[n
];
1150 s_szFlags
[flagofs
] = '\0';
1152 long double val
= va_arg(argptr
, long double);
1153 ::sprintf(s_szScratch
, s_szFlags
, val
);
1155 double val
= va_arg(argptr
, double);
1156 ::sprintf(s_szScratch
, s_szFlags
, val
);
1158 *this += wxString(s_szScratch
);
1163 void *val
= va_arg(argptr
, void *);
1165 s_szFlags
[flagofs
++] = pszFormat
[n
];
1166 s_szFlags
[flagofs
] = '\0';
1167 ::sprintf(s_szScratch
, s_szFlags
, val
);
1168 *this += wxString(s_szScratch
);
1174 wxChar val
= va_arg(argptr
, int);
1175 // we don't need to honor padding here, do we?
1182 // wx extension: we'll let %hs mean non-Unicode strings
1183 char *val
= va_arg(argptr
, char *);
1185 // ASCII->Unicode constructor handles max_width right
1186 wxString
s(val
, max_width
);
1188 size_t len
= wxSTRING_MAXLEN
;
1190 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1191 } else val
= _T("(null)");
1192 wxString
s(val
, len
);
1194 if (s
.Len() < min_width
)
1195 s
.Pad(min_width
- s
.Len(), _T(' '), adj_left
);
1198 wxChar
*val
= va_arg(argptr
, wxChar
*);
1199 size_t len
= wxSTRING_MAXLEN
;
1201 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1202 } else val
= _T("(null)");
1203 wxString
s(val
, len
);
1204 if (s
.Len() < min_width
)
1205 s
.Pad(min_width
- s
.Len(), _T(' '), adj_left
);
1212 int *val
= va_arg(argptr
, int *);
1215 else if (ilen
== -1) {
1216 short int *val
= va_arg(argptr
, short int *);
1219 else if (ilen
>= 1) {
1220 long int *val
= va_arg(argptr
, long int *);
1226 if (wxIsalpha(pszFormat
[n
]))
1227 // probably some flag not taken care of here yet
1228 s_szFlags
[flagofs
++] = pszFormat
[n
];
1231 *this += _T('%'); // just to pass the glibc tst-printf.c
1239 } else *this += pszFormat
[n
];
1242 // NB: wxVsnprintf() may return either less than the buffer size or -1 if there
1243 // is not enough place depending on implementation
1244 int iLen
= wxVsnprintf(s_szScratch
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
1246 if ( iLen
< (int)WXSIZEOF(s_szScratch
) ) {
1247 buffer
= s_szScratch
;
1250 int size
= WXSIZEOF(s_szScratch
) * 2;
1251 buffer
= (char *)malloc(size
);
1252 while ( buffer
!= NULL
) {
1253 iLen
= wxVsnprintf(buffer
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
1254 if ( iLen
< size
) {
1255 // ok, there was enough space
1259 // still not enough, double it again
1260 buffer
= (char *)realloc(buffer
, size
*= 2);
1272 if ( buffer
!= s_szScratch
)
1279 // ----------------------------------------------------------------------------
1280 // misc other operations
1281 // ----------------------------------------------------------------------------
1282 bool wxString::Matches(const wxChar
*pszMask
) const
1284 // check char by char
1285 const wxChar
*pszTxt
;
1286 for ( pszTxt
= c_str(); *pszMask
!= _T('\0'); pszMask
++, pszTxt
++ ) {
1287 switch ( *pszMask
) {
1289 if ( *pszTxt
== _T('\0') )
1298 // ignore special chars immediately following this one
1299 while ( *pszMask
== _T('*') || *pszMask
== _T('?') )
1302 // if there is nothing more, match
1303 if ( *pszMask
== _T('\0') )
1306 // are there any other metacharacters in the mask?
1308 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, _T("*?"));
1310 if ( pEndMask
!= NULL
) {
1311 // we have to match the string between two metachars
1312 uiLenMask
= pEndMask
- pszMask
;
1315 // we have to match the remainder of the string
1316 uiLenMask
= wxStrlen(pszMask
);
1319 wxString
strToMatch(pszMask
, uiLenMask
);
1320 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1321 if ( pMatch
== NULL
)
1324 // -1 to compensate "++" in the loop
1325 pszTxt
= pMatch
+ uiLenMask
- 1;
1326 pszMask
+= uiLenMask
- 1;
1331 if ( *pszMask
!= *pszTxt
)
1337 // match only if nothing left
1338 return *pszTxt
== _T('\0');
1341 // Count the number of chars
1342 int wxString::Freq(wxChar ch
) const
1346 for (int i
= 0; i
< len
; i
++)
1348 if (GetChar(i
) == ch
)
1354 // convert to upper case, return the copy of the string
1355 wxString
wxString::Upper() const
1356 { wxString
s(*this); return s
.MakeUpper(); }
1358 // convert to lower case, return the copy of the string
1359 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1361 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1364 va_start(argptr
, pszFormat
);
1365 int iLen
= PrintfV(pszFormat
, argptr
);
1370 // ---------------------------------------------------------------------------
1371 // standard C++ library string functions
1372 // ---------------------------------------------------------------------------
1373 #ifdef wxSTD_STRING_COMPATIBILITY
1375 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1377 wxASSERT( str
.GetStringData()->IsValid() );
1378 wxASSERT( nPos
<= Len() );
1380 if ( !str
.IsEmpty() ) {
1382 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1383 wxStrncpy(pc
, c_str(), nPos
);
1384 wxStrcpy(pc
+ nPos
, str
);
1385 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1386 strTmp
.UngetWriteBuf();
1393 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1395 wxASSERT( str
.GetStringData()->IsValid() );
1396 wxASSERT( nStart
<= Len() );
1398 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1400 return p
== NULL
? npos
: p
- c_str();
1403 // VC++ 1.5 can't cope with the default argument in the header.
1404 #if !defined(__VISUALC__) || defined(__WIN32__)
1405 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1407 return find(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1411 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1412 #if !defined(__BORLANDC__)
1413 size_t wxString::find(wxChar ch
, size_t nStart
) const
1415 wxASSERT( nStart
<= Len() );
1417 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1419 return p
== NULL
? npos
: p
- c_str();
1423 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1425 wxASSERT( str
.GetStringData()->IsValid() );
1426 wxASSERT( nStart
<= Len() );
1428 // # could be quicker than that
1429 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1430 while ( p
>= c_str() + str
.Len() ) {
1431 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1432 return p
- str
.Len() - c_str();
1439 // VC++ 1.5 can't cope with the default argument in the header.
1440 #if !defined(__VISUALC__) || defined(__WIN32__)
1441 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1443 return rfind(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1446 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1448 wxASSERT( nStart
<= Len() );
1450 const wxChar
*p
= wxStrrchr(c_str() + nStart
, ch
);
1452 return p
== NULL
? npos
: p
- c_str();
1456 wxString
wxString::substr(size_t nStart
, size_t nLen
) const
1458 // npos means 'take all'
1462 wxASSERT( nStart
+ nLen
<= Len() );
1464 return wxString(c_str() + nStart
, nLen
== npos
? 0 : nLen
);
1467 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1469 wxString
strTmp(c_str(), nStart
);
1470 if ( nLen
!= npos
) {
1471 wxASSERT( nStart
+ nLen
<= Len() );
1473 strTmp
.append(c_str() + nStart
+ nLen
);
1480 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1482 wxASSERT( nStart
+ nLen
<= wxStrlen(sz
) );
1486 strTmp
.append(c_str(), nStart
);
1488 strTmp
.append(c_str() + nStart
+ nLen
);
1494 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1496 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1499 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1500 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1502 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1505 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1506 const wxChar
* sz
, size_t nCount
)
1508 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1511 #endif //std::string compatibility
1513 // ============================================================================
1515 // ============================================================================
1517 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1518 #define ARRAY_MAXSIZE_INCREMENT 4096
1519 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1520 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1523 #define STRING(p) ((wxString *)(&(p)))
1526 wxArrayString::wxArrayString()
1530 m_pItems
= (wxChar
**) NULL
;
1534 wxArrayString::wxArrayString(const wxArrayString
& src
)
1538 m_pItems
= (wxChar
**) NULL
;
1543 // assignment operator
1544 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1549 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1550 Alloc(src
.m_nCount
);
1552 // we can't just copy the pointers here because otherwise we would share
1553 // the strings with another array
1554 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1557 if ( m_nCount
!= 0 )
1558 memcpy(m_pItems
, src
.m_pItems
, m_nCount
*sizeof(wxChar
*));
1564 void wxArrayString::Grow()
1566 // only do it if no more place
1567 if( m_nCount
== m_nSize
) {
1568 if( m_nSize
== 0 ) {
1569 // was empty, alloc some memory
1570 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1571 m_pItems
= new wxChar
*[m_nSize
];
1574 // otherwise when it's called for the first time, nIncrement would be 0
1575 // and the array would never be expanded
1576 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE
!= 0 );
1578 // add 50% but not too much
1579 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1580 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1581 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1582 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1583 m_nSize
+= nIncrement
;
1584 wxChar
**pNew
= new wxChar
*[m_nSize
];
1586 // copy data to new location
1587 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1589 // delete old memory (but do not release the strings!)
1590 wxDELETEA(m_pItems
);
1597 void wxArrayString::Free()
1599 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1600 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1604 // deletes all the strings from the list
1605 void wxArrayString::Empty()
1612 // as Empty, but also frees memory
1613 void wxArrayString::Clear()
1620 wxDELETEA(m_pItems
);
1624 wxArrayString::~wxArrayString()
1628 wxDELETEA(m_pItems
);
1631 // pre-allocates memory (frees the previous data!)
1632 void wxArrayString::Alloc(size_t nSize
)
1634 wxASSERT( nSize
> 0 );
1636 // only if old buffer was not big enough
1637 if ( nSize
> m_nSize
) {
1639 wxDELETEA(m_pItems
);
1640 m_pItems
= new wxChar
*[nSize
];
1647 // searches the array for an item (forward or backwards)
1648 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
1651 if ( m_nCount
> 0 ) {
1652 size_t ui
= m_nCount
;
1654 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1661 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1662 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1670 // add item at the end
1671 void wxArrayString::Add(const wxString
& str
)
1673 wxASSERT( str
.GetStringData()->IsValid() );
1677 // the string data must not be deleted!
1678 str
.GetStringData()->Lock();
1679 m_pItems
[m_nCount
++] = (wxChar
*)str
.c_str();
1682 // add item at the given position
1683 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
1685 wxASSERT( str
.GetStringData()->IsValid() );
1687 wxCHECK_RET( nIndex
<= m_nCount
, ("bad index in wxArrayString::Insert") );
1691 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
1692 (m_nCount
- nIndex
)*sizeof(wxChar
*));
1694 str
.GetStringData()->Lock();
1695 m_pItems
[nIndex
] = (wxChar
*)str
.c_str();
1700 // removes item from array (by index)
1701 void wxArrayString::Remove(size_t nIndex
)
1703 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Remove") );
1706 Item(nIndex
).GetStringData()->Unlock();
1708 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
1709 (m_nCount
- nIndex
- 1)*sizeof(wxChar
*));
1713 // removes item from array (by value)
1714 void wxArrayString::Remove(const wxChar
*sz
)
1716 int iIndex
= Index(sz
);
1718 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
1719 _("removing inexistent element in wxArrayString::Remove") );
1724 // ----------------------------------------------------------------------------
1726 // ----------------------------------------------------------------------------
1728 // we can only sort one array at a time with the quick-sort based
1731 #include <wx/thread.h>
1733 // need a critical section to protect access to gs_compareFunction and
1734 // gs_sortAscending variables
1735 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
1737 // call this before the value of the global sort vars is changed/after
1738 // you're finished with them
1739 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
1740 gs_critsectStringSort = new wxCriticalSection; \
1741 gs_critsectStringSort->Enter()
1742 #define END_SORT() gs_critsectStringSort->Leave(); \
1743 delete gs_critsectStringSort; \
1744 gs_critsectStringSort = NULL
1746 #define START_SORT()
1748 #endif // wxUSE_THREADS
1750 // function to use for string comparaison
1751 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
1753 // if we don't use the compare function, this flag tells us if we sort the
1754 // array in ascending or descending order
1755 static bool gs_sortAscending
= TRUE
;
1757 // function which is called by quick sort
1758 static int wxStringCompareFunction(const void *first
, const void *second
)
1760 wxString
*strFirst
= (wxString
*)first
;
1761 wxString
*strSecond
= (wxString
*)second
;
1763 if ( gs_compareFunction
) {
1764 return gs_compareFunction(*strFirst
, *strSecond
);
1767 // maybe we should use wxStrcoll
1768 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
1770 return gs_sortAscending
? result
: -result
;
1774 // sort array elements using passed comparaison function
1775 void wxArrayString::Sort(CompareFunction compareFunction
)
1779 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1780 gs_compareFunction
= compareFunction
;
1787 void wxArrayString::Sort(bool reverseOrder
)
1791 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1792 gs_sortAscending
= !reverseOrder
;
1799 void wxArrayString::DoSort()
1801 // just sort the pointers using qsort() - of course it only works because
1802 // wxString() *is* a pointer to its data
1803 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
1806 // ============================================================================
1808 // ============================================================================
1810 WXDLLEXPORT_DATA(wxMBConv
) wxConv_libc
;
1812 // ----------------------------------------------------------------------------
1813 // standard libc conversion
1814 // ----------------------------------------------------------------------------
1816 size_t wxMBConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
)
1818 return wxMB2WC(buf
, psz
, n
);
1821 size_t wxMBConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
)
1823 return wxWC2MB(buf
, psz
, n
);
1826 // ----------------------------------------------------------------------------
1828 // ----------------------------------------------------------------------------
1832 virtual size_t MB2WC(wchar_t *buf
, const char *psz
, size_t n
);
1833 virtual size_t WC2MB(char *buf
, const wchar_t *psz
, size_t n
);
1836 WXDLLEXPORT_DATA(wxMBConv_UTF7
) wxConv_UTF7
;
1838 // TODO: write actual implementations of UTF-7 here
1839 size_t wxMBConv_UTF7::MB2WC(wchar_t *buf
, const char *psz
, size_t n
)
1844 size_t wxMBConv_UTF7::WC2MB(char *buf
, const wchar_t *psz
, size_t n
)
1849 // ----------------------------------------------------------------------------
1851 // ----------------------------------------------------------------------------
1855 virtual size_t MB2WC(wchar_t *buf
, const char *psz
, size_t n
);
1856 virtual size_t WC2MB(char *buf
, const wchar_t *psz
, size_t n
);
1859 WXDLLEXPORT_DATA(wxMBConv_UTF8
) wxConv_UTF8
;
1861 // TODO: write actual implementations of UTF-8 here
1862 size_t wxMBConv_UTF8::MB2WC(wchar_t *buf
, const char *psz
, size_t n
)
1864 return wxMB2WC(buf
, psz
, n
);
1867 size_t wxMBConv_UTF8::WC2MB(char *buf
, const wchar_t *psz
, size_t n
)
1869 return wxWC2MB(buf
, psz
, n
);
1872 // ----------------------------------------------------------------------------
1873 // specified character set
1874 // ----------------------------------------------------------------------------
1876 // TODO: write actual implementation of character set conversion here
1877 wxCSConv::wxCSConv(const wxChar
*charset
)
1879 data
= (wxChar
*) NULL
;
1882 size_t wxCSConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
)
1886 for (size_t c
=0; c
<=n
; c
++)
1892 size_t wxCSConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
)
1896 for (size_t c
=0; c
<=n
; c
++)
1897 buf
[c
] = (psz
[c
]>0xff) ? '?' : psz
[c
];