1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/string.cpp
3 // Purpose: wxString class
4 // Author: Vadim Zeitlin, Ryan Norton
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // (c) 2004 Ryan Norton <wxprojects@comcast.net>
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
13 // ===========================================================================
14 // headers, declarations, constants
15 // ===========================================================================
17 // For compilers that support precompilation, includes "wx.h".
18 #include "wx/wxprec.h"
25 #include "wx/string.h"
26 #include "wx/wxcrtvararg.h"
38 #include "wx/hashmap.h"
40 // string handling functions used by wxString:
41 #if wxUSE_UNICODE_UTF8
42 #define wxStringMemcpy memcpy
43 #define wxStringMemcmp memcmp
44 #define wxStringMemchr memchr
45 #define wxStringStrlen strlen
47 #define wxStringMemcpy wxTmemcpy
48 #define wxStringMemcmp wxTmemcmp
49 #define wxStringMemchr wxTmemchr
50 #define wxStringStrlen wxStrlen
54 // ---------------------------------------------------------------------------
55 // static class variables definition
56 // ---------------------------------------------------------------------------
58 //According to STL _must_ be a -1 size_t
59 const size_t wxString::npos
= (size_t) -1;
61 #if wxUSE_STRING_POS_CACHE
63 #ifdef wxHAS_COMPILER_TLS
65 wxTLS_TYPE(wxString::Cache
) wxString::ms_cache
;
67 #else // !wxHAS_COMPILER_TLS
69 struct wxStrCacheInitializer
71 wxStrCacheInitializer()
73 // calling this function triggers s_cache initialization in it, and
74 // from now on it becomes safe to call from multiple threads
79 static wxStrCacheInitializer gs_stringCacheInit
;
81 #endif // wxHAS_COMPILER_TLS/!wxHAS_COMPILER_TLS
83 // gdb seems to be unable to display thread-local variables correctly, at least
84 // not my 6.4.98 version under amd64, so provide this debugging helper to do it
87 struct wxStrCacheDumper
91 puts("*** wxString cache dump:");
92 for ( unsigned n
= 0; n
< wxString::Cache::SIZE
; n
++ )
94 const wxString::Cache::Element
&
95 c
= wxString::GetCacheBegin()[n
];
97 printf("\t%u%s\t%p: pos=(%lu, %lu), len=%ld\n",
99 n
== wxString::LastUsedCacheElement() ? " [*]" : "",
101 (unsigned long)c
.pos
,
102 (unsigned long)c
.impl
,
108 void wxDumpStrCache() { wxStrCacheDumper::ShowAll(); }
110 #endif // __WXDEBUG__
112 #ifdef wxPROFILE_STRING_CACHE
114 wxString::CacheStats
wxString::ms_cacheStats
;
116 struct wxStrCacheStatsDumper
118 ~wxStrCacheStatsDumper()
120 const wxString::CacheStats
& stats
= wxString::ms_cacheStats
;
124 puts("*** wxString cache statistics:");
125 printf("\tTotal non-trivial calls to PosToImpl(): %u\n",
127 printf("\tHits %u (of which %u not used) or %.2f%%\n",
130 100.*float(stats
.poshits
- stats
.mishits
)/stats
.postot
);
131 printf("\tAverage position requested: %.2f\n",
132 float(stats
.sumpos
) / stats
.postot
);
133 printf("\tAverage offset after cached hint: %.2f\n",
134 float(stats
.sumofs
) / stats
.postot
);
139 printf("\tNumber of calls to length(): %u, hits=%.2f%%\n",
140 stats
.lentot
, 100.*float(stats
.lenhits
)/stats
.lentot
);
145 static wxStrCacheStatsDumper s_showCacheStats
;
147 #endif // wxPROFILE_STRING_CACHE
149 #endif // wxUSE_STRING_POS_CACHE
151 // ----------------------------------------------------------------------------
153 // ----------------------------------------------------------------------------
155 #if wxUSE_STD_IOSTREAM
159 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxCStrData
& str
)
161 #if wxUSE_UNICODE && !wxUSE_UNICODE_UTF8
162 return os
<< (const char *)str
.AsCharBuf();
164 return os
<< str
.AsInternal();
168 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxString
& str
)
170 return os
<< str
.c_str();
173 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxCharBuffer
& str
)
175 return os
<< str
.data();
179 wxSTD ostream
& operator<<(wxSTD ostream
& os
, const wxWCharBuffer
& str
)
181 return os
<< str
.data();
185 #if wxUSE_UNICODE && defined(HAVE_WOSTREAM)
187 wxSTD wostream
& operator<<(wxSTD wostream
& wos
, const wxString
& str
)
189 return wos
<< str
.wc_str();
192 wxSTD wostream
& operator<<(wxSTD wostream
& wos
, const wxCStrData
& str
)
194 return wos
<< str
.AsWChar();
197 wxSTD wostream
& operator<<(wxSTD wostream
& wos
, const wxWCharBuffer
& str
)
199 return wos
<< str
.data();
202 #endif // wxUSE_UNICODE && defined(HAVE_WOSTREAM)
204 #endif // wxUSE_STD_IOSTREAM
206 // ===========================================================================
207 // wxString class core
208 // ===========================================================================
210 #if wxUSE_UNICODE_UTF8
212 void wxString::PosLenToImpl(size_t pos
, size_t len
,
213 size_t *implPos
, size_t *implLen
) const
219 else // have valid start position
221 const const_iterator b
= GetIterForNthChar(pos
);
222 *implPos
= wxStringImpl::const_iterator(b
.impl()) - m_impl
.begin();
227 else // have valid length too
229 // we need to handle the case of length specifying a substring
230 // going beyond the end of the string, just as std::string does
231 const const_iterator
e(end());
233 while ( len
&& i
<= e
)
239 *implLen
= i
.impl() - b
.impl();
244 #endif // wxUSE_UNICODE_UTF8
246 // ----------------------------------------------------------------------------
247 // wxCStrData converted strings caching
248 // ----------------------------------------------------------------------------
250 // FIXME-UTF8: temporarily disabled because it doesn't work with global
251 // string objects; re-enable after fixing this bug and benchmarking
252 // performance to see if using a hash is a good idea at all
255 // For backward compatibility reasons, it must be possible to assign the value
256 // returned by wxString::c_str() to a char* or wchar_t* variable and work with
257 // it. Returning wxCharBuffer from (const char*)c_str() wouldn't do the trick,
258 // because the memory would be freed immediately, but it has to be valid as long
259 // as the string is not modified, so that code like this still works:
261 // const wxChar *s = str.c_str();
262 // while ( s ) { ... }
264 // FIXME-UTF8: not thread safe!
265 // FIXME-UTF8: we currently clear the cached conversion only when the string is
266 // destroyed, but we should do it when the string is modified, to
267 // keep memory usage down
268 // FIXME-UTF8: we do the conversion every time As[W]Char() is called, but if we
269 // invalidated the cache on every change, we could keep the previous
271 // FIXME-UTF8: add tracing of usage of these two methods - new code is supposed
272 // to use mb_str() or wc_str() instead of (const [w]char*)c_str()
275 static inline void DeleteStringFromConversionCache(T
& hash
, const wxString
*s
)
277 typename
T::iterator i
= hash
.find(wxConstCast(s
, wxString
));
278 if ( i
!= hash
.end() )
286 // NB: non-STL implementation doesn't compile with "const wxString*" key type,
287 // so we have to use wxString* here and const-cast when used
288 WX_DECLARE_HASH_MAP(wxString
*, char*, wxPointerHash
, wxPointerEqual
,
289 wxStringCharConversionCache
);
290 static wxStringCharConversionCache gs_stringsCharCache
;
292 const char* wxCStrData::AsChar() const
294 // remove previously cache value, if any (see FIXMEs above):
295 DeleteStringFromConversionCache(gs_stringsCharCache
, m_str
);
297 // convert the string and keep it:
298 const char *s
= gs_stringsCharCache
[wxConstCast(m_str
, wxString
)] =
299 m_str
->mb_str().release();
303 #endif // wxUSE_UNICODE
305 #if !wxUSE_UNICODE_WCHAR
306 WX_DECLARE_HASH_MAP(wxString
*, wchar_t*, wxPointerHash
, wxPointerEqual
,
307 wxStringWCharConversionCache
);
308 static wxStringWCharConversionCache gs_stringsWCharCache
;
310 const wchar_t* wxCStrData::AsWChar() const
312 // remove previously cache value, if any (see FIXMEs above):
313 DeleteStringFromConversionCache(gs_stringsWCharCache
, m_str
);
315 // convert the string and keep it:
316 const wchar_t *s
= gs_stringsWCharCache
[wxConstCast(m_str
, wxString
)] =
317 m_str
->wc_str().release();
321 #endif // !wxUSE_UNICODE_WCHAR
323 wxString::~wxString()
326 // FIXME-UTF8: do this only if locale is not UTF8 if wxUSE_UNICODE_UTF8
327 DeleteStringFromConversionCache(gs_stringsCharCache
, this);
329 #if !wxUSE_UNICODE_WCHAR
330 DeleteStringFromConversionCache(gs_stringsWCharCache
, this);
335 #if wxUSE_UNICODE && !wxUSE_UTF8_LOCALE_ONLY
336 const char* wxCStrData::AsChar() const
338 #if wxUSE_UNICODE_UTF8
339 if ( wxLocaleIsUtf8
)
342 // under non-UTF8 locales, we have to convert the internal UTF-8
343 // representation using wxConvLibc and cache the result
345 wxString
*str
= wxConstCast(m_str
, wxString
);
347 // convert the string:
349 // FIXME-UTF8: we'd like to do the conversion in the existing buffer (if we
350 // have it) but it's unfortunately not obvious to implement
351 // because we don't know how big buffer do we need for the
352 // given string length (in case of multibyte encodings, e.g.
353 // ISO-2022-JP or UTF-8 when internal representation is wchar_t)
355 // One idea would be to store more than just m_convertedToChar
356 // in wxString: then we could record the length of the string
357 // which was converted the last time and try to reuse the same
358 // buffer if the current length is not greater than it (this
359 // could still fail because string could have been modified in
360 // place but it would work most of the time, so we'd do it and
361 // only allocate the new buffer if in-place conversion returned
362 // an error). We could also store a bit saying if the string
363 // was modified since the last conversion (and update it in all
364 // operation modifying the string, of course) to avoid unneeded
365 // consequential conversions. But both of these ideas require
366 // adding more fields to wxString and require profiling results
367 // to be sure that we really gain enough from them to justify
369 wxCharBuffer
buf(str
->mb_str());
371 // if it failed, return empty string and not NULL to avoid crashes in code
372 // written with either wxWidgets 2 wxString or std::string behaviour in
373 // mind: neither of them ever returns NULL and so we shouldn't neither
377 if ( str
->m_convertedToChar
&&
378 strlen(buf
) == strlen(str
->m_convertedToChar
) )
380 // keep the same buffer for as long as possible, so that several calls
381 // to c_str() in a row still work:
382 strcpy(str
->m_convertedToChar
, buf
);
386 str
->m_convertedToChar
= buf
.release();
390 return str
->m_convertedToChar
+ m_offset
;
392 #endif // wxUSE_UNICODE && !wxUSE_UTF8_LOCALE_ONLY
394 #if !wxUSE_UNICODE_WCHAR
395 const wchar_t* wxCStrData::AsWChar() const
397 wxString
*str
= wxConstCast(m_str
, wxString
);
399 // convert the string:
400 wxWCharBuffer
buf(str
->wc_str());
402 // notice that here, unlike above in AsChar(), conversion can't fail as our
403 // internal UTF-8 is always well-formed -- or the string was corrupted and
404 // all bets are off anyhow
406 // FIXME-UTF8: do the conversion in-place in the existing buffer
407 if ( str
->m_convertedToWChar
&&
408 wxWcslen(buf
) == wxWcslen(str
->m_convertedToWChar
) )
410 // keep the same buffer for as long as possible, so that several calls
411 // to c_str() in a row still work:
412 memcpy(str
->m_convertedToWChar
, buf
, sizeof(wchar_t) * wxWcslen(buf
));
416 str
->m_convertedToWChar
= buf
.release();
420 return str
->m_convertedToWChar
+ m_offset
;
422 #endif // !wxUSE_UNICODE_WCHAR
424 // ===========================================================================
425 // wxString class core
426 // ===========================================================================
428 // ---------------------------------------------------------------------------
429 // construction and conversion
430 // ---------------------------------------------------------------------------
432 #if wxUSE_UNICODE_WCHAR
434 wxString::SubstrBufFromMB
wxString::ConvertStr(const char *psz
, size_t nLength
,
435 const wxMBConv
& conv
)
438 if ( !psz
|| nLength
== 0 )
439 return SubstrBufFromMB(L
"", 0);
441 if ( nLength
== npos
)
445 wxWCharBuffer
wcBuf(conv
.cMB2WC(psz
, nLength
, &wcLen
));
447 return SubstrBufFromMB(_T(""), 0);
449 return SubstrBufFromMB(wcBuf
, wcLen
);
451 #endif // wxUSE_UNICODE_WCHAR
453 #if wxUSE_UNICODE_UTF8
455 wxString::SubstrBufFromMB
wxString::ConvertStr(const char *psz
, size_t nLength
,
456 const wxMBConv
& conv
)
459 if ( !psz
|| nLength
== 0 )
460 return SubstrBufFromMB("", 0);
462 // if psz is already in UTF-8, we don't have to do the roundtrip to
463 // wchar_t* and back:
466 // we need to validate the input because UTF8 iterators assume valid
467 // UTF-8 sequence and psz may be invalid:
468 if ( wxStringOperations::IsValidUtf8String(psz
, nLength
) )
470 // we must pass the real string length to SubstrBufFromMB ctor
471 if ( nLength
== npos
)
472 nLength
= psz
? strlen(psz
) : 0;
473 return SubstrBufFromMB(wxCharBuffer::CreateNonOwned(psz
), nLength
);
475 // else: do the roundtrip through wchar_t*
478 if ( nLength
== npos
)
481 // first convert to wide string:
483 wxWCharBuffer
wcBuf(conv
.cMB2WC(psz
, nLength
, &wcLen
));
485 return SubstrBufFromMB("", 0);
487 // and then to UTF-8:
488 SubstrBufFromMB
buf(ConvertStr(wcBuf
, wcLen
, wxMBConvStrictUTF8()));
489 // widechar -> UTF-8 conversion isn't supposed to ever fail:
490 wxASSERT_MSG( buf
.data
, _T("conversion to UTF-8 failed") );
494 #endif // wxUSE_UNICODE_UTF8
496 #if wxUSE_UNICODE_UTF8 || !wxUSE_UNICODE
498 wxString::SubstrBufFromWC
wxString::ConvertStr(const wchar_t *pwz
, size_t nLength
,
499 const wxMBConv
& conv
)
502 if ( !pwz
|| nLength
== 0 )
503 return SubstrBufFromWC("", 0);
505 if ( nLength
== npos
)
509 wxCharBuffer
mbBuf(conv
.cWC2MB(pwz
, nLength
, &mbLen
));
511 return SubstrBufFromWC("", 0);
513 return SubstrBufFromWC(mbBuf
, mbLen
);
515 #endif // wxUSE_UNICODE_UTF8 || !wxUSE_UNICODE
518 #if wxUSE_UNICODE_WCHAR
520 //Convert wxString in Unicode mode to a multi-byte string
521 const wxCharBuffer
wxString::mb_str(const wxMBConv
& conv
) const
523 return conv
.cWC2MB(wx_str(), length() + 1 /* size, not length */, NULL
);
526 #elif wxUSE_UNICODE_UTF8
528 const wxWCharBuffer
wxString::wc_str() const
530 return wxMBConvStrictUTF8().cMB2WC
533 m_impl
.length() + 1, // size, not length
538 const wxCharBuffer
wxString::mb_str(const wxMBConv
& conv
) const
541 return wxCharBuffer::CreateNonOwned(m_impl
.c_str());
543 // FIXME-UTF8: use wc_str() here once we have buffers with length
546 wxWCharBuffer
wcBuf(wxMBConvStrictUTF8().cMB2WC
549 m_impl
.length() + 1, // size
553 return wxCharBuffer("");
555 return conv
.cWC2MB(wcBuf
, wcLen
+1, NULL
);
560 //Converts this string to a wide character string if unicode
561 //mode is not enabled and wxUSE_WCHAR_T is enabled
562 const wxWCharBuffer
wxString::wc_str(const wxMBConv
& conv
) const
564 return conv
.cMB2WC(wx_str(), length() + 1 /* size, not length */, NULL
);
567 #endif // Unicode/ANSI
569 // shrink to minimal size (releasing extra memory)
570 bool wxString::Shrink()
572 wxString
tmp(begin(), end());
574 return tmp
.length() == length();
577 // deprecated compatibility code:
578 #if WXWIN_COMPATIBILITY_2_8 && !wxUSE_STL_BASED_WXSTRING && !wxUSE_UNICODE_UTF8
579 wxStringCharType
*wxString::GetWriteBuf(size_t nLen
)
581 return DoGetWriteBuf(nLen
);
584 void wxString::UngetWriteBuf()
589 void wxString::UngetWriteBuf(size_t nLen
)
591 DoUngetWriteBuf(nLen
);
593 #endif // WXWIN_COMPATIBILITY_2_8 && !wxUSE_STL_BASED_WXSTRING && !wxUSE_UNICODE_UTF8
596 // ---------------------------------------------------------------------------
598 // ---------------------------------------------------------------------------
600 // all functions are inline in string.h
602 // ---------------------------------------------------------------------------
603 // concatenation operators
604 // ---------------------------------------------------------------------------
607 * concatenation functions come in 5 flavours:
609 * char + string and string + char
610 * C str + string and string + C str
613 wxString
operator+(const wxString
& str1
, const wxString
& str2
)
615 #if !wxUSE_STL_BASED_WXSTRING
616 wxASSERT( str1
.IsValid() );
617 wxASSERT( str2
.IsValid() );
626 wxString
operator+(const wxString
& str
, wxUniChar ch
)
628 #if !wxUSE_STL_BASED_WXSTRING
629 wxASSERT( str
.IsValid() );
638 wxString
operator+(wxUniChar ch
, const wxString
& str
)
640 #if !wxUSE_STL_BASED_WXSTRING
641 wxASSERT( str
.IsValid() );
650 wxString
operator+(const wxString
& str
, const char *psz
)
652 #if !wxUSE_STL_BASED_WXSTRING
653 wxASSERT( str
.IsValid() );
657 if ( !s
.Alloc(strlen(psz
) + str
.length()) ) {
658 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
666 wxString
operator+(const wxString
& str
, const wchar_t *pwz
)
668 #if !wxUSE_STL_BASED_WXSTRING
669 wxASSERT( str
.IsValid() );
673 if ( !s
.Alloc(wxWcslen(pwz
) + str
.length()) ) {
674 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
682 wxString
operator+(const char *psz
, const wxString
& str
)
684 #if !wxUSE_STL_BASED_WXSTRING
685 wxASSERT( str
.IsValid() );
689 if ( !s
.Alloc(strlen(psz
) + str
.length()) ) {
690 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
698 wxString
operator+(const wchar_t *pwz
, const wxString
& str
)
700 #if !wxUSE_STL_BASED_WXSTRING
701 wxASSERT( str
.IsValid() );
705 if ( !s
.Alloc(wxWcslen(pwz
) + str
.length()) ) {
706 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
714 // ---------------------------------------------------------------------------
716 // ---------------------------------------------------------------------------
718 bool wxString::IsSameAs(wxUniChar c
, bool compareWithCase
) const
720 return (length() == 1) && (compareWithCase
? GetChar(0u) == c
721 : wxToupper(GetChar(0u)) == wxToupper(c
));
724 #ifdef HAVE_STD_STRING_COMPARE
726 // NB: Comparison code (both if HAVE_STD_STRING_COMPARE and if not) works with
727 // UTF-8 encoded strings too, thanks to UTF-8's design which allows us to
728 // sort strings in characters code point order by sorting the byte sequence
729 // in byte values order (i.e. what strcmp() and memcmp() do).
731 int wxString::compare(const wxString
& str
) const
733 return m_impl
.compare(str
.m_impl
);
736 int wxString::compare(size_t nStart
, size_t nLen
,
737 const wxString
& str
) const
740 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
741 return m_impl
.compare(pos
, len
, str
.m_impl
);
744 int wxString::compare(size_t nStart
, size_t nLen
,
746 size_t nStart2
, size_t nLen2
) const
749 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
752 str
.PosLenToImpl(nStart2
, nLen2
, &pos2
, &len2
);
754 return m_impl
.compare(pos
, len
, str
.m_impl
, pos2
, len2
);
757 int wxString::compare(const char* sz
) const
759 return m_impl
.compare(ImplStr(sz
));
762 int wxString::compare(const wchar_t* sz
) const
764 return m_impl
.compare(ImplStr(sz
));
767 int wxString::compare(size_t nStart
, size_t nLen
,
768 const char* sz
, size_t nCount
) const
771 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
773 SubstrBufFromMB
str(ImplStr(sz
, nCount
));
775 return m_impl
.compare(pos
, len
, str
.data
, str
.len
);
778 int wxString::compare(size_t nStart
, size_t nLen
,
779 const wchar_t* sz
, size_t nCount
) const
782 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
784 SubstrBufFromWC
str(ImplStr(sz
, nCount
));
786 return m_impl
.compare(pos
, len
, str
.data
, str
.len
);
789 #else // !HAVE_STD_STRING_COMPARE
791 static inline int wxDoCmp(const wxStringCharType
* s1
, size_t l1
,
792 const wxStringCharType
* s2
, size_t l2
)
795 return wxStringMemcmp(s1
, s2
, l1
);
798 int ret
= wxStringMemcmp(s1
, s2
, l1
);
799 return ret
== 0 ? -1 : ret
;
803 int ret
= wxStringMemcmp(s1
, s2
, l2
);
804 return ret
== 0 ? +1 : ret
;
808 int wxString::compare(const wxString
& str
) const
810 return ::wxDoCmp(m_impl
.data(), m_impl
.length(),
811 str
.m_impl
.data(), str
.m_impl
.length());
814 int wxString::compare(size_t nStart
, size_t nLen
,
815 const wxString
& str
) const
817 wxASSERT(nStart
<= length());
818 size_type strLen
= length() - nStart
;
819 nLen
= strLen
< nLen
? strLen
: nLen
;
822 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
824 return ::wxDoCmp(m_impl
.data() + pos
, len
,
825 str
.m_impl
.data(), str
.m_impl
.length());
828 int wxString::compare(size_t nStart
, size_t nLen
,
830 size_t nStart2
, size_t nLen2
) const
832 wxASSERT(nStart
<= length());
833 wxASSERT(nStart2
<= str
.length());
834 size_type strLen
= length() - nStart
,
835 strLen2
= str
.length() - nStart2
;
836 nLen
= strLen
< nLen
? strLen
: nLen
;
837 nLen2
= strLen2
< nLen2
? strLen2
: nLen2
;
840 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
842 str
.PosLenToImpl(nStart2
, nLen2
, &pos2
, &len2
);
844 return ::wxDoCmp(m_impl
.data() + pos
, len
,
845 str
.m_impl
.data() + pos2
, len2
);
848 int wxString::compare(const char* sz
) const
850 SubstrBufFromMB
str(ImplStr(sz
, npos
));
851 if ( str
.len
== npos
)
852 str
.len
= wxStringStrlen(str
.data
);
853 return ::wxDoCmp(m_impl
.data(), m_impl
.length(), str
.data
, str
.len
);
856 int wxString::compare(const wchar_t* sz
) const
858 SubstrBufFromWC
str(ImplStr(sz
, npos
));
859 if ( str
.len
== npos
)
860 str
.len
= wxStringStrlen(str
.data
);
861 return ::wxDoCmp(m_impl
.data(), m_impl
.length(), str
.data
, str
.len
);
864 int wxString::compare(size_t nStart
, size_t nLen
,
865 const char* sz
, size_t nCount
) const
867 wxASSERT(nStart
<= length());
868 size_type strLen
= length() - nStart
;
869 nLen
= strLen
< nLen
? strLen
: nLen
;
872 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
874 SubstrBufFromMB
str(ImplStr(sz
, nCount
));
875 if ( str
.len
== npos
)
876 str
.len
= wxStringStrlen(str
.data
);
878 return ::wxDoCmp(m_impl
.data() + pos
, len
, str
.data
, str
.len
);
881 int wxString::compare(size_t nStart
, size_t nLen
,
882 const wchar_t* sz
, size_t nCount
) const
884 wxASSERT(nStart
<= length());
885 size_type strLen
= length() - nStart
;
886 nLen
= strLen
< nLen
? strLen
: nLen
;
889 PosLenToImpl(nStart
, nLen
, &pos
, &len
);
891 SubstrBufFromWC
str(ImplStr(sz
, nCount
));
892 if ( str
.len
== npos
)
893 str
.len
= wxStringStrlen(str
.data
);
895 return ::wxDoCmp(m_impl
.data() + pos
, len
, str
.data
, str
.len
);
898 #endif // HAVE_STD_STRING_COMPARE/!HAVE_STD_STRING_COMPARE
901 // ---------------------------------------------------------------------------
902 // find_{first,last}_[not]_of functions
903 // ---------------------------------------------------------------------------
905 #if !wxUSE_STL_BASED_WXSTRING || wxUSE_UNICODE_UTF8
907 // NB: All these functions are implemented with the argument being wxChar*,
908 // i.e. widechar string in any Unicode build, even though native string
909 // representation is char* in the UTF-8 build. This is because we couldn't
910 // use memchr() to determine if a character is in a set encoded as UTF-8.
912 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
914 return find_first_of(sz
, nStart
, wxStrlen(sz
));
917 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
919 return find_first_not_of(sz
, nStart
, wxStrlen(sz
));
922 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
, size_t n
) const
924 wxASSERT_MSG( nStart
<= length(), _T("invalid index") );
927 for ( const_iterator i
= begin() + nStart
; i
!= end(); ++idx
, ++i
)
929 if ( wxTmemchr(sz
, *i
, n
) )
936 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
, size_t n
) const
938 wxASSERT_MSG( nStart
<= length(), _T("invalid index") );
941 for ( const_iterator i
= begin() + nStart
; i
!= end(); ++idx
, ++i
)
943 if ( !wxTmemchr(sz
, *i
, n
) )
951 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
953 return find_last_of(sz
, nStart
, wxStrlen(sz
));
956 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
958 return find_last_not_of(sz
, nStart
, wxStrlen(sz
));
961 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
, size_t n
) const
963 size_t len
= length();
965 if ( nStart
== npos
)
971 wxASSERT_MSG( nStart
<= len
, _T("invalid index") );
975 for ( const_reverse_iterator i
= rbegin() + (len
- nStart
- 1);
976 i
!= rend(); --idx
, ++i
)
978 if ( wxTmemchr(sz
, *i
, n
) )
985 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
, size_t n
) const
987 size_t len
= length();
989 if ( nStart
== npos
)
995 wxASSERT_MSG( nStart
<= len
, _T("invalid index") );
999 for ( const_reverse_iterator i
= rbegin() + (len
- nStart
- 1);
1000 i
!= rend(); --idx
, ++i
)
1002 if ( !wxTmemchr(sz
, *i
, n
) )
1009 size_t wxString::find_first_not_of(wxUniChar ch
, size_t nStart
) const
1011 wxASSERT_MSG( nStart
<= length(), _T("invalid index") );
1013 size_t idx
= nStart
;
1014 for ( const_iterator i
= begin() + nStart
; i
!= end(); ++idx
, ++i
)
1023 size_t wxString::find_last_not_of(wxUniChar ch
, size_t nStart
) const
1025 size_t len
= length();
1027 if ( nStart
== npos
)
1033 wxASSERT_MSG( nStart
<= len
, _T("invalid index") );
1036 size_t idx
= nStart
;
1037 for ( const_reverse_iterator i
= rbegin() + (len
- nStart
- 1);
1038 i
!= rend(); --idx
, ++i
)
1047 // the functions above were implemented for wchar_t* arguments in Unicode
1048 // build and char* in ANSI build; below are implementations for the other
1051 #define wxOtherCharType char
1052 #define STRCONV (const wxChar*)wxConvLibc.cMB2WC
1054 #define wxOtherCharType wchar_t
1055 #define STRCONV (const wxChar*)wxConvLibc.cWC2MB
1058 size_t wxString::find_first_of(const wxOtherCharType
* sz
, size_t nStart
) const
1059 { return find_first_of(STRCONV(sz
), nStart
); }
1061 size_t wxString::find_first_of(const wxOtherCharType
* sz
, size_t nStart
,
1063 { return find_first_of(STRCONV(sz
, n
, NULL
), nStart
, n
); }
1064 size_t wxString::find_last_of(const wxOtherCharType
* sz
, size_t nStart
) const
1065 { return find_last_of(STRCONV(sz
), nStart
); }
1066 size_t wxString::find_last_of(const wxOtherCharType
* sz
, size_t nStart
,
1068 { return find_last_of(STRCONV(sz
, n
, NULL
), nStart
, n
); }
1069 size_t wxString::find_first_not_of(const wxOtherCharType
* sz
, size_t nStart
) const
1070 { return find_first_not_of(STRCONV(sz
), nStart
); }
1071 size_t wxString::find_first_not_of(const wxOtherCharType
* sz
, size_t nStart
,
1073 { return find_first_not_of(STRCONV(sz
, n
, NULL
), nStart
, n
); }
1074 size_t wxString::find_last_not_of(const wxOtherCharType
* sz
, size_t nStart
) const
1075 { return find_last_not_of(STRCONV(sz
), nStart
); }
1076 size_t wxString::find_last_not_of(const wxOtherCharType
* sz
, size_t nStart
,
1078 { return find_last_not_of(STRCONV(sz
, n
, NULL
), nStart
, n
); }
1080 #undef wxOtherCharType
1083 #endif // !wxUSE_STL_BASED_WXSTRING || wxUSE_UNICODE_UTF8
1085 // ===========================================================================
1086 // other common string functions
1087 // ===========================================================================
1089 int wxString::CmpNoCase(const wxString
& s
) const
1091 // FIXME-UTF8: use wxUniChar::ToLower/ToUpper once added
1093 const_iterator i1
= begin();
1094 const_iterator end1
= end();
1095 const_iterator i2
= s
.begin();
1096 const_iterator end2
= s
.end();
1098 for ( ; i1
!= end1
&& i2
!= end2
; ++i1
, ++i2
)
1100 wxUniChar lower1
= (wxChar
)wxTolower(*i1
);
1101 wxUniChar lower2
= (wxChar
)wxTolower(*i2
);
1102 if ( lower1
!= lower2
)
1103 return lower1
< lower2
? -1 : 1;
1106 size_t len1
= length();
1107 size_t len2
= s
.length();
1111 else if ( len1
> len2
)
1120 #ifndef __SCHAR_MAX__
1121 #define __SCHAR_MAX__ 127
1125 wxString
wxString::FromAscii(const char *ascii
, size_t len
)
1127 if (!ascii
|| len
== 0)
1128 return wxEmptyString
;
1133 wxStringInternalBuffer
buf(res
, len
);
1134 wxStringCharType
*dest
= buf
;
1136 for ( ; len
> 0; --len
)
1138 unsigned char c
= (unsigned char)*ascii
++;
1139 wxASSERT_MSG( c
< 0x80,
1140 _T("Non-ASCII value passed to FromAscii().") );
1142 *dest
++ = (wchar_t)c
;
1149 wxString
wxString::FromAscii(const char *ascii
)
1151 return FromAscii(ascii
, wxStrlen(ascii
));
1154 wxString
wxString::FromAscii(char ascii
)
1156 // What do we do with '\0' ?
1158 unsigned char c
= (unsigned char)ascii
;
1160 wxASSERT_MSG( c
< 0x80, _T("Non-ASCII value passed to FromAscii().") );
1162 // NB: the cast to wchar_t causes interpretation of 'ascii' as Latin1 value
1163 return wxString(wxUniChar((wchar_t)c
));
1166 const wxCharBuffer
wxString::ToAscii() const
1168 // this will allocate enough space for the terminating NUL too
1169 wxCharBuffer
buffer(length());
1170 char *dest
= buffer
.data();
1172 for ( const_iterator i
= begin(); i
!= end(); ++i
)
1175 // FIXME-UTF8: unify substituted char ('_') with wxUniChar ('?')
1176 *dest
++ = c
.IsAscii() ? (char)c
: '_';
1178 // the output string can't have embedded NULs anyhow, so we can safely
1179 // stop at first of them even if we do have any
1187 #endif // wxUSE_UNICODE
1189 // extract string of length nCount starting at nFirst
1190 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
1192 size_t nLen
= length();
1194 // default value of nCount is npos and means "till the end"
1195 if ( nCount
== npos
)
1197 nCount
= nLen
- nFirst
;
1200 // out-of-bounds requests return sensible things
1201 if ( nFirst
+ nCount
> nLen
)
1203 nCount
= nLen
- nFirst
;
1206 if ( nFirst
> nLen
)
1208 // AllocCopy() will return empty string
1209 return wxEmptyString
;
1212 wxString
dest(*this, nFirst
, nCount
);
1213 if ( dest
.length() != nCount
)
1215 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
1221 // check that the string starts with prefix and return the rest of the string
1222 // in the provided pointer if it is not NULL, otherwise return false
1223 bool wxString::StartsWith(const wxString
& prefix
, wxString
*rest
) const
1225 if ( compare(0, prefix
.length(), prefix
) != 0 )
1230 // put the rest of the string into provided pointer
1231 rest
->assign(*this, prefix
.length(), npos
);
1238 // check that the string ends with suffix and return the rest of it in the
1239 // provided pointer if it is not NULL, otherwise return false
1240 bool wxString::EndsWith(const wxString
& suffix
, wxString
*rest
) const
1242 int start
= length() - suffix
.length();
1244 if ( start
< 0 || compare(start
, npos
, suffix
) != 0 )
1249 // put the rest of the string into provided pointer
1250 rest
->assign(*this, 0, start
);
1257 // extract nCount last (rightmost) characters
1258 wxString
wxString::Right(size_t nCount
) const
1260 if ( nCount
> length() )
1263 wxString
dest(*this, length() - nCount
, nCount
);
1264 if ( dest
.length() != nCount
) {
1265 wxFAIL_MSG( _T("out of memory in wxString::Right") );
1270 // get all characters after the last occurence of ch
1271 // (returns the whole string if ch not found)
1272 wxString
wxString::AfterLast(wxUniChar ch
) const
1275 int iPos
= Find(ch
, true);
1276 if ( iPos
== wxNOT_FOUND
)
1279 str
= wx_str() + iPos
+ 1;
1284 // extract nCount first (leftmost) characters
1285 wxString
wxString::Left(size_t nCount
) const
1287 if ( nCount
> length() )
1290 wxString
dest(*this, 0, nCount
);
1291 if ( dest
.length() != nCount
) {
1292 wxFAIL_MSG( _T("out of memory in wxString::Left") );
1297 // get all characters before the first occurence of ch
1298 // (returns the whole string if ch not found)
1299 wxString
wxString::BeforeFirst(wxUniChar ch
) const
1301 int iPos
= Find(ch
);
1302 if ( iPos
== wxNOT_FOUND
) iPos
= length();
1303 return wxString(*this, 0, iPos
);
1306 /// get all characters before the last occurence of ch
1307 /// (returns empty string if ch not found)
1308 wxString
wxString::BeforeLast(wxUniChar ch
) const
1311 int iPos
= Find(ch
, true);
1312 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
1313 str
= wxString(c_str(), iPos
);
1318 /// get all characters after the first occurence of ch
1319 /// (returns empty string if ch not found)
1320 wxString
wxString::AfterFirst(wxUniChar ch
) const
1323 int iPos
= Find(ch
);
1324 if ( iPos
!= wxNOT_FOUND
)
1325 str
= wx_str() + iPos
+ 1;
1330 // replace first (or all) occurences of some substring with another one
1331 size_t wxString::Replace(const wxString
& strOld
,
1332 const wxString
& strNew
, bool bReplaceAll
)
1334 // if we tried to replace an empty string we'd enter an infinite loop below
1335 wxCHECK_MSG( !strOld
.empty(), 0,
1336 _T("wxString::Replace(): invalid parameter") );
1338 wxSTRING_INVALIDATE_CACHE();
1340 size_t uiCount
= 0; // count of replacements made
1342 // optimize the special common case: replacement of one character by
1343 // another one (in UTF-8 case we can only do this for ASCII characters)
1345 // benchmarks show that this special version is around 3 times faster
1346 // (depending on the proportion of matching characters and UTF-8/wchar_t
1348 if ( strOld
.m_impl
.length() == 1 && strNew
.m_impl
.length() == 1 )
1350 const wxStringCharType chOld
= strOld
.m_impl
[0],
1351 chNew
= strNew
.m_impl
[0];
1353 // this loop is the simplified version of the one below
1354 for ( size_t pos
= 0; ; )
1356 pos
= m_impl
.find(chOld
, pos
);
1360 m_impl
[pos
++] = chNew
;
1368 else // general case
1370 const size_t uiOldLen
= strOld
.m_impl
.length();
1371 const size_t uiNewLen
= strNew
.m_impl
.length();
1373 for ( size_t pos
= 0; ; )
1375 pos
= m_impl
.find(strOld
.m_impl
, pos
);
1379 // replace this occurrence of the old string with the new one
1380 m_impl
.replace(pos
, uiOldLen
, strNew
.m_impl
);
1382 // move up pos past the string that was replaced
1385 // increase replace count
1388 // stop after the first one?
1397 bool wxString::IsAscii() const
1399 for ( const_iterator i
= begin(); i
!= end(); ++i
)
1401 if ( !(*i
).IsAscii() )
1408 bool wxString::IsWord() const
1410 for ( const_iterator i
= begin(); i
!= end(); ++i
)
1412 if ( !wxIsalpha(*i
) )
1419 bool wxString::IsNumber() const
1424 const_iterator i
= begin();
1426 if ( *i
== _T('-') || *i
== _T('+') )
1429 for ( ; i
!= end(); ++i
)
1431 if ( !wxIsdigit(*i
) )
1438 wxString
wxString::Strip(stripType w
) const
1441 if ( w
& leading
) s
.Trim(false);
1442 if ( w
& trailing
) s
.Trim(true);
1446 // ---------------------------------------------------------------------------
1448 // ---------------------------------------------------------------------------
1450 wxString
& wxString::MakeUpper()
1452 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1453 *it
= (wxChar
)wxToupper(*it
);
1458 wxString
& wxString::MakeLower()
1460 for ( iterator it
= begin(), en
= end(); it
!= en
; ++it
)
1461 *it
= (wxChar
)wxTolower(*it
);
1466 wxString
& wxString::MakeCapitalized()
1468 const iterator en
= end();
1469 iterator it
= begin();
1472 *it
= (wxChar
)wxToupper(*it
);
1473 for ( ++it
; it
!= en
; ++it
)
1474 *it
= (wxChar
)wxTolower(*it
);
1480 // ---------------------------------------------------------------------------
1481 // trimming and padding
1482 // ---------------------------------------------------------------------------
1484 // some compilers (VC++ 6.0 not to name them) return true for a call to
1485 // isspace('\xEA') in the C locale which seems to be broken to me, but we have
1486 // to live with this by checking that the character is a 7 bit one - even if
1487 // this may fail to detect some spaces (I don't know if Unicode doesn't have
1488 // space-like symbols somewhere except in the first 128 chars), it is arguably
1489 // still better than trimming away accented letters
1490 inline int wxSafeIsspace(wxChar ch
) { return (ch
< 127) && wxIsspace(ch
); }
1492 // trims spaces (in the sense of isspace) from left or right side
1493 wxString
& wxString::Trim(bool bFromRight
)
1495 // first check if we're going to modify the string at all
1498 (bFromRight
&& wxSafeIsspace(GetChar(length() - 1))) ||
1499 (!bFromRight
&& wxSafeIsspace(GetChar(0u)))
1505 // find last non-space character
1506 reverse_iterator psz
= rbegin();
1507 while ( (psz
!= rend()) && wxSafeIsspace(*psz
) )
1510 // truncate at trailing space start
1511 erase(psz
.base(), end());
1515 // find first non-space character
1516 iterator psz
= begin();
1517 while ( (psz
!= end()) && wxSafeIsspace(*psz
) )
1520 // fix up data and length
1521 erase(begin(), psz
);
1528 // adds nCount characters chPad to the string from either side
1529 wxString
& wxString::Pad(size_t nCount
, wxUniChar chPad
, bool bFromRight
)
1531 wxString
s(chPad
, nCount
);
1544 // truncate the string
1545 wxString
& wxString::Truncate(size_t uiLen
)
1547 if ( uiLen
< length() )
1549 erase(begin() + uiLen
, end());
1551 //else: nothing to do, string is already short enough
1556 // ---------------------------------------------------------------------------
1557 // finding (return wxNOT_FOUND if not found and index otherwise)
1558 // ---------------------------------------------------------------------------
1561 int wxString::Find(wxUniChar ch
, bool bFromEnd
) const
1563 size_type idx
= bFromEnd
? find_last_of(ch
) : find_first_of(ch
);
1565 return (idx
== npos
) ? wxNOT_FOUND
: (int)idx
;
1568 // ----------------------------------------------------------------------------
1569 // conversion to numbers
1570 // ----------------------------------------------------------------------------
1572 // The implementation of all the functions below is exactly the same so factor
1573 // it out. Note that number extraction works correctly on UTF-8 strings, so
1574 // we can use wxStringCharType and wx_str() for maximum efficiency.
1577 #define DO_IF_NOT_WINCE(x) x
1579 #define DO_IF_NOT_WINCE(x)
1582 #define WX_STRING_TO_INT_TYPE(out, base, func, T) \
1583 wxCHECK_MSG( out, false, _T("NULL output pointer") ); \
1584 wxASSERT_MSG( !base || (base > 1 && base <= 36), _T("invalid base") ); \
1586 DO_IF_NOT_WINCE( errno = 0; ) \
1588 const wxStringCharType *start = wx_str(); \
1589 wxStringCharType *end; \
1590 T val = func(start, &end, base); \
1592 /* return true only if scan was stopped by the terminating NUL and */ \
1593 /* if the string was not empty to start with and no under/overflow */ \
1595 if ( *end || end == start DO_IF_NOT_WINCE(|| errno == ERANGE) ) \
1600 bool wxString::ToLong(long *pVal
, int base
) const
1602 WX_STRING_TO_INT_TYPE(pVal
, base
, wxStrtol
, long);
1605 bool wxString::ToULong(unsigned long *pVal
, int base
) const
1607 WX_STRING_TO_INT_TYPE(pVal
, base
, wxStrtoul
, unsigned long);
1610 bool wxString::ToLongLong(wxLongLong_t
*pVal
, int base
) const
1612 WX_STRING_TO_INT_TYPE(pVal
, base
, wxStrtoll
, wxLongLong_t
);
1615 bool wxString::ToULongLong(wxULongLong_t
*pVal
, int base
) const
1617 WX_STRING_TO_INT_TYPE(pVal
, base
, wxStrtoull
, wxULongLong_t
);
1620 bool wxString::ToDouble(double *pVal
) const
1622 wxCHECK_MSG( pVal
, false, _T("NULL output pointer") );
1624 DO_IF_NOT_WINCE( errno
= 0; )
1626 const wxChar
*start
= c_str();
1628 double val
= wxStrtod(start
, &end
);
1630 // return true only if scan was stopped by the terminating NUL and if the
1631 // string was not empty to start with and no under/overflow occurred
1632 if ( *end
|| end
== start
DO_IF_NOT_WINCE(|| errno
== ERANGE
) )
1640 // ---------------------------------------------------------------------------
1642 // ---------------------------------------------------------------------------
1644 #if !wxUSE_UTF8_LOCALE_ONLY
1646 #ifdef wxNEEDS_WXSTRING_PRINTF_MIXIN
1647 wxString
wxStringPrintfMixinBase::DoFormatWchar(const wxChar
*format
, ...)
1649 wxString
wxString::DoFormatWchar(const wxChar
*format
, ...)
1653 va_start(argptr
, format
);
1656 s
.PrintfV(format
, argptr
);
1662 #endif // !wxUSE_UTF8_LOCALE_ONLY
1664 #if wxUSE_UNICODE_UTF8
1666 wxString
wxString::DoFormatUtf8(const char *format
, ...)
1669 va_start(argptr
, format
);
1672 s
.PrintfV(format
, argptr
);
1678 #endif // wxUSE_UNICODE_UTF8
1681 wxString
wxString::FormatV(const wxString
& format
, va_list argptr
)
1684 s
.PrintfV(format
, argptr
);
1688 #if !wxUSE_UTF8_LOCALE_ONLY
1689 #ifdef wxNEEDS_WXSTRING_PRINTF_MIXIN
1690 int wxStringPrintfMixinBase::DoPrintfWchar(const wxChar
*format
, ...)
1692 int wxString::DoPrintfWchar(const wxChar
*format
, ...)
1696 va_start(argptr
, format
);
1698 #ifdef wxNEEDS_WXSTRING_PRINTF_MIXIN
1699 // get a pointer to the wxString instance; we have to use dynamic_cast<>
1700 // because it's the only cast that works safely for downcasting when
1701 // multiple inheritance is used:
1702 wxString
*str
= static_cast<wxString
*>(this);
1704 wxString
*str
= this;
1707 int iLen
= str
->PrintfV(format
, argptr
);
1713 #endif // !wxUSE_UTF8_LOCALE_ONLY
1715 #if wxUSE_UNICODE_UTF8
1716 int wxString::DoPrintfUtf8(const char *format
, ...)
1719 va_start(argptr
, format
);
1721 int iLen
= PrintfV(format
, argptr
);
1727 #endif // wxUSE_UNICODE_UTF8
1730 Uses wxVsnprintf and places the result into the this string.
1732 In ANSI build, wxVsnprintf is effectively vsnprintf but in Unicode build
1733 it is vswprintf. Due to a discrepancy between vsnprintf and vswprintf in
1734 the ISO C99 (and thus SUSv3) standard the return value for the case of
1735 an undersized buffer is inconsistent. For conforming vsnprintf
1736 implementations the function must return the number of characters that
1737 would have been printed had the buffer been large enough. For conforming
1738 vswprintf implementations the function must return a negative number
1741 What vswprintf sets errno to is undefined but Darwin seems to set it to
1742 EOVERFLOW. The only expected errno are EILSEQ and EINVAL. Both of
1743 those are defined in the standard and backed up by several conformance
1744 statements. Note that ENOMEM mentioned in the manual page does not
1745 apply to swprintf, only wprintf and fwprintf.
1747 Official manual page:
1748 http://www.opengroup.org/onlinepubs/009695399/functions/swprintf.html
1750 Some conformance statements (AIX, Solaris):
1751 http://www.opengroup.org/csq/view.mhtml?RID=ibm%2FSD1%2F3
1752 http://www.theopengroup.org/csq/view.mhtml?norationale=1&noreferences=1&RID=Fujitsu%2FSE2%2F10
1754 Since EILSEQ and EINVAL are rather common but EOVERFLOW is not and since
1755 EILSEQ and EINVAL are specifically defined to mean the error is other than
1756 an undersized buffer and no other errno are defined we treat those two
1757 as meaning hard errors and everything else gets the old behavior which
1758 is to keep looping and increasing buffer size until the function succeeds.
1760 In practice it's impossible to determine before compilation which behavior
1761 may be used. The vswprintf function may have vsnprintf-like behavior or
1762 vice-versa. Behavior detected on one release can theoretically change
1763 with an updated release. Not to mention that configure testing for it
1764 would require the test to be run on the host system, not the build system
1765 which makes cross compilation difficult. Therefore, we make no assumptions
1766 about behavior and try our best to handle every known case, including the
1767 case where wxVsnprintf returns a negative number and fails to set errno.
1769 There is yet one more non-standard implementation and that is our own.
1770 Fortunately, that can be detected at compile-time.
1772 On top of all that, ISO C99 explicitly defines snprintf to write a null
1773 character to the last position of the specified buffer. That would be at
1774 at the given buffer size minus 1. It is supposed to do this even if it
1775 turns out that the buffer is sized too small.
1777 Darwin (tested on 10.5) follows the C99 behavior exactly.
1779 Glibc 2.6 almost follows the C99 behavior except vswprintf never sets
1780 errno even when it fails. However, it only seems to ever fail due
1781 to an undersized buffer.
1783 #if wxUSE_UNICODE_UTF8
1784 template<typename BufferType
>
1786 // we only need one version in non-UTF8 builds and at least two Windows
1787 // compilers have problems with this function template, so use just one
1788 // normal function here
1790 static int DoStringPrintfV(wxString
& str
,
1791 const wxString
& format
, va_list argptr
)
1797 #if wxUSE_UNICODE_UTF8
1798 BufferType
tmp(str
, size
+ 1);
1799 typename
BufferType::CharType
*buf
= tmp
;
1801 wxStringBuffer
tmp(str
, size
+ 1);
1809 // in UTF-8 build, leaving uninitialized junk in the buffer
1810 // could result in invalid non-empty UTF-8 string, so just
1811 // reset the string to empty on failure:
1816 // wxVsnprintf() may modify the original arg pointer, so pass it
1819 wxVaCopy(argptrcopy
, argptr
);
1822 // Set errno to 0 to make it determinate if wxVsnprintf fails to set it.
1825 int len
= wxVsnprintf(buf
, size
, format
, argptrcopy
);
1828 // some implementations of vsnprintf() don't NUL terminate
1829 // the string if there is not enough space for it so
1830 // always do it manually
1831 // FIXME: This really seems to be the wrong and would be an off-by-one
1832 // bug except the code above allocates an extra character.
1833 buf
[size
] = _T('\0');
1835 // vsnprintf() may return either -1 (traditional Unix behaviour) or the
1836 // total number of characters which would have been written if the
1837 // buffer were large enough (newer standards such as Unix98)
1840 // NB: wxVsnprintf() may call either wxCRT_VsnprintfW or
1841 // wxCRT_VsnprintfA in UTF-8 build; wxUSE_WXVSNPRINTF
1842 // is true if *both* of them use our own implementation,
1843 // otherwise we can't be sure
1844 #if wxUSE_WXVSNPRINTF
1845 // we know that our own implementation of wxVsnprintf() returns -1
1846 // only for a format error - thus there's something wrong with
1847 // the user's format string
1850 #else // possibly using system version
1851 // assume it only returns error if there is not enough space, but
1852 // as we don't know how much we need, double the current size of
1855 if( (errno
== EILSEQ
) || (errno
== EINVAL
) )
1856 // If errno was set to one of the two well-known hard errors
1857 // then fail immediately to avoid an infinite loop.
1860 #endif // __WXWINCE__
1861 // still not enough, as we don't know how much we need, double the
1862 // current size of the buffer
1864 #endif // wxUSE_WXVSNPRINTF/!wxUSE_WXVSNPRINTF
1866 else if ( len
>= size
)
1868 #if wxUSE_WXVSNPRINTF
1869 // we know that our own implementation of wxVsnprintf() returns
1870 // size+1 when there's not enough space but that's not the size
1871 // of the required buffer!
1872 size
*= 2; // so we just double the current size of the buffer
1874 // some vsnprintf() implementations NUL-terminate the buffer and
1875 // some don't in len == size case, to be safe always add 1
1876 // FIXME: I don't quite understand this comment. The vsnprintf
1877 // function is specifically defined to return the number of
1878 // characters printed not including the null terminator.
1879 // So OF COURSE you need to add 1 to get the right buffer size.
1880 // The following line is definitely correct, no question.
1884 else // ok, there was enough space
1890 // we could have overshot
1893 return str
.length();
1896 int wxString::PrintfV(const wxString
& format
, va_list argptr
)
1898 #if wxUSE_UNICODE_UTF8
1899 #if wxUSE_STL_BASED_WXSTRING
1900 typedef wxStringTypeBuffer
<char> Utf8Buffer
;
1902 typedef wxStringInternalBuffer Utf8Buffer
;
1906 #if wxUSE_UTF8_LOCALE_ONLY
1907 return DoStringPrintfV
<Utf8Buffer
>(*this, format
, argptr
);
1909 #if wxUSE_UNICODE_UTF8
1910 if ( wxLocaleIsUtf8
)
1911 return DoStringPrintfV
<Utf8Buffer
>(*this, format
, argptr
);
1914 return DoStringPrintfV
<wxStringBuffer
>(*this, format
, argptr
);
1916 return DoStringPrintfV(*this, format
, argptr
);
1917 #endif // UTF8/WCHAR
1921 // ----------------------------------------------------------------------------
1922 // misc other operations
1923 // ----------------------------------------------------------------------------
1925 // returns true if the string matches the pattern which may contain '*' and
1926 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1928 bool wxString::Matches(const wxString
& mask
) const
1930 // I disable this code as it doesn't seem to be faster (in fact, it seems
1931 // to be much slower) than the old, hand-written code below and using it
1932 // here requires always linking with libregex even if the user code doesn't
1934 #if 0 // wxUSE_REGEX
1935 // first translate the shell-like mask into a regex
1937 pattern
.reserve(wxStrlen(pszMask
));
1949 pattern
+= _T(".*");
1960 // these characters are special in a RE, quote them
1961 // (however note that we don't quote '[' and ']' to allow
1962 // using them for Unix shell like matching)
1963 pattern
+= _T('\\');
1967 pattern
+= *pszMask
;
1975 return wxRegEx(pattern
, wxRE_NOSUB
| wxRE_EXTENDED
).Matches(c_str());
1976 #else // !wxUSE_REGEX
1977 // TODO: this is, of course, awfully inefficient...
1979 // FIXME-UTF8: implement using iterators, remove #if
1980 #if wxUSE_UNICODE_UTF8
1981 wxWCharBuffer maskBuf
= mask
.wc_str();
1982 wxWCharBuffer txtBuf
= wc_str();
1983 const wxChar
*pszMask
= maskBuf
.data();
1984 const wxChar
*pszTxt
= txtBuf
.data();
1986 const wxChar
*pszMask
= mask
.wx_str();
1987 // the char currently being checked
1988 const wxChar
*pszTxt
= wx_str();
1991 // the last location where '*' matched
1992 const wxChar
*pszLastStarInText
= NULL
;
1993 const wxChar
*pszLastStarInMask
= NULL
;
1996 for ( ; *pszMask
!= wxT('\0'); pszMask
++, pszTxt
++ ) {
1997 switch ( *pszMask
) {
1999 if ( *pszTxt
== wxT('\0') )
2002 // pszTxt and pszMask will be incremented in the loop statement
2008 // remember where we started to be able to backtrack later
2009 pszLastStarInText
= pszTxt
;
2010 pszLastStarInMask
= pszMask
;
2012 // ignore special chars immediately following this one
2013 // (should this be an error?)
2014 while ( *pszMask
== wxT('*') || *pszMask
== wxT('?') )
2017 // if there is nothing more, match
2018 if ( *pszMask
== wxT('\0') )
2021 // are there any other metacharacters in the mask?
2023 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, wxT("*?"));
2025 if ( pEndMask
!= NULL
) {
2026 // we have to match the string between two metachars
2027 uiLenMask
= pEndMask
- pszMask
;
2030 // we have to match the remainder of the string
2031 uiLenMask
= wxStrlen(pszMask
);
2034 wxString
strToMatch(pszMask
, uiLenMask
);
2035 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
2036 if ( pMatch
== NULL
)
2039 // -1 to compensate "++" in the loop
2040 pszTxt
= pMatch
+ uiLenMask
- 1;
2041 pszMask
+= uiLenMask
- 1;
2046 if ( *pszMask
!= *pszTxt
)
2052 // match only if nothing left
2053 if ( *pszTxt
== wxT('\0') )
2056 // if we failed to match, backtrack if we can
2057 if ( pszLastStarInText
) {
2058 pszTxt
= pszLastStarInText
+ 1;
2059 pszMask
= pszLastStarInMask
;
2061 pszLastStarInText
= NULL
;
2063 // don't bother resetting pszLastStarInMask, it's unnecessary
2069 #endif // wxUSE_REGEX/!wxUSE_REGEX
2072 // Count the number of chars
2073 int wxString::Freq(wxUniChar ch
) const
2076 for ( const_iterator i
= begin(); i
!= end(); ++i
)
2084 // ----------------------------------------------------------------------------
2085 // wxUTF8StringBuffer
2086 // ----------------------------------------------------------------------------
2088 #if wxUSE_UNICODE_WCHAR
2089 wxUTF8StringBuffer::~wxUTF8StringBuffer()
2091 wxMBConvStrictUTF8 conv
;
2092 size_t wlen
= conv
.ToWChar(NULL
, 0, m_buf
);
2093 wxCHECK_RET( wlen
!= wxCONV_FAILED
, "invalid UTF-8 data in string buffer?" );
2095 wxStringInternalBuffer
wbuf(m_str
, wlen
);
2096 conv
.ToWChar(wbuf
, wlen
, m_buf
);
2099 wxUTF8StringBufferLength::~wxUTF8StringBufferLength()
2101 wxCHECK_RET(m_lenSet
, "length not set");
2103 wxMBConvStrictUTF8 conv
;
2104 size_t wlen
= conv
.ToWChar(NULL
, 0, m_buf
, m_len
);
2105 wxCHECK_RET( wlen
!= wxCONV_FAILED
, "invalid UTF-8 data in string buffer?" );
2107 wxStringInternalBufferLength
wbuf(m_str
, wlen
);
2108 conv
.ToWChar(wbuf
, wlen
, m_buf
, m_len
);
2109 wbuf
.SetLength(wlen
);
2111 #endif // wxUSE_UNICODE_WCHAR
2113 // ----------------------------------------------------------------------------
2114 // wxCharBufferType<T>
2115 // ----------------------------------------------------------------------------
2118 wxCharTypeBuffer
<char>::Data
2119 wxCharTypeBuffer
<char>::NullData(NULL
);
2122 wxCharTypeBuffer
<wchar_t>::Data
2123 wxCharTypeBuffer
<wchar_t>::NullData(NULL
);