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"
39 #include <wx/thread.h>
52 #include <wchar.h> // for wcsrtombs(), see comments where it's used
55 #ifdef WXSTRING_IS_WXOBJECT
56 IMPLEMENT_DYNAMIC_CLASS(wxString
, wxObject
)
57 #endif //WXSTRING_IS_WXOBJECT
60 #undef wxUSE_EXPERIMENTAL_PRINTF
61 #define wxUSE_EXPERIMENTAL_PRINTF 1
64 // allocating extra space for each string consumes more memory but speeds up
65 // the concatenation operations (nLen is the current string's length)
66 // NB: EXTRA_ALLOC must be >= 0!
67 #define EXTRA_ALLOC (19 - nLen % 16)
69 // ---------------------------------------------------------------------------
70 // static class variables definition
71 // ---------------------------------------------------------------------------
73 #ifdef wxSTD_STRING_COMPATIBILITY
74 const size_t wxString::npos
= wxSTRING_MAXLEN
;
75 #endif // wxSTD_STRING_COMPATIBILITY
77 // ----------------------------------------------------------------------------
79 // ----------------------------------------------------------------------------
81 // for an empty string, GetStringData() will return this address: this
82 // structure has the same layout as wxStringData and it's data() method will
83 // return the empty string (dummy pointer)
88 } g_strEmpty
= { {-1, 0, 0}, _T('\0') };
90 // empty C style string: points to 'string data' byte of g_strEmpty
91 extern const wxChar WXDLLEXPORT
*g_szNul
= &g_strEmpty
.dummy
;
93 // ----------------------------------------------------------------------------
94 // conditional compilation
95 // ----------------------------------------------------------------------------
97 // we want to find out if the current platform supports vsnprintf()-like
98 // function: for Unix this is done with configure, for Windows we test the
99 // compiler explicitly.
102 #define wxVsnprintf _vsnprintf
105 #ifdef HAVE_VSNPRINTF
106 #define wxVsnprintf vsnprintf
108 #endif // Windows/!Windows
111 // in this case we'll use vsprintf() (which is ANSI and thus should be
112 // always available), but it's unsafe because it doesn't check for buffer
113 // size - so give a warning
114 #define wxVsnprintf(buffer,len,format,argptr) vsprintf(buffer,format, argptr)
116 #if defined(__VISUALC__)
117 #pragma message("Using sprintf() because no snprintf()-like function defined")
118 #elif defined(__GNUG__) && !defined(__UNIX__)
119 #warning "Using sprintf() because no snprintf()-like function defined"
120 #elif defined(__MWERKS__)
121 #warning "Using sprintf() because no snprintf()-like function defined"
123 #endif // no vsnprintf
126 // AIX has vsnprintf, but there's no prototype in the system headers.
127 extern "C" int vsnprintf(char* str
, size_t n
, const char* format
, va_list ap
);
130 // ----------------------------------------------------------------------------
132 // ----------------------------------------------------------------------------
134 #ifdef wxSTD_STRING_COMPATIBILITY
136 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
139 // ATTN: you can _not_ use both of these in the same program!
141 istream
& operator>>(istream
& is
, wxString
& WXUNUSED(str
))
146 streambuf
*sb
= is
.rdbuf();
149 int ch
= sb
->sbumpc ();
151 is
.setstate(ios::eofbit
);
154 else if ( isspace(ch
) ) {
166 if ( str
.length() == 0 )
167 is
.setstate(ios::failbit
);
172 #endif //std::string compatibility
174 // ----------------------------------------------------------------------------
176 // ----------------------------------------------------------------------------
178 // this small class is used to gather statistics for performance tuning
179 //#define WXSTRING_STATISTICS
180 #ifdef WXSTRING_STATISTICS
184 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
186 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
188 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
191 size_t m_nCount
, m_nTotal
;
193 } g_averageLength("allocation size"),
194 g_averageSummandLength("summand length"),
195 g_averageConcatHit("hit probability in concat"),
196 g_averageInitialLength("initial string length");
198 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
200 #define STATISTICS_ADD(av, val)
201 #endif // WXSTRING_STATISTICS
203 // ===========================================================================
204 // wxString class core
205 // ===========================================================================
207 // ---------------------------------------------------------------------------
209 // ---------------------------------------------------------------------------
211 // constructs string of <nLength> copies of character <ch>
212 wxString::wxString(wxChar ch
, size_t nLength
)
217 AllocBuffer(nLength
);
220 // memset only works on char
221 for (size_t n
=0; n
<nLength
; n
++) m_pchData
[n
] = ch
;
223 memset(m_pchData
, ch
, nLength
);
228 // takes nLength elements of psz starting at nPos
229 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
233 wxASSERT( nPos
<= wxStrlen(psz
) );
235 if ( nLength
== wxSTRING_MAXLEN
)
236 nLength
= wxStrlen(psz
+ nPos
);
238 STATISTICS_ADD(InitialLength
, nLength
);
241 // trailing '\0' is written in AllocBuffer()
242 AllocBuffer(nLength
);
243 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
247 #ifdef wxSTD_STRING_COMPATIBILITY
249 // poor man's iterators are "void *" pointers
250 wxString::wxString(const void *pStart
, const void *pEnd
)
252 InitWith((const wxChar
*)pStart
, 0,
253 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
256 #endif //std::string compatibility
260 // from multibyte string
261 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
263 // first get necessary size
264 size_t nLen
= psz
? conv
.MB2WC((wchar_t *) NULL
, psz
, 0) : 0;
266 // nLength is number of *Unicode* characters here!
267 if ((nLen
!= (size_t)-1) && (nLen
> nLength
))
271 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
273 conv
.MB2WC(m_pchData
, psz
, nLen
);
284 wxString::wxString(const wchar_t *pwz
)
286 // first get necessary size
287 size_t nLen
= pwz
? wxWC2MB((char *) NULL
, pwz
, 0) : 0;
290 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
292 wxWC2MB(m_pchData
, pwz
, nLen
);
302 // ---------------------------------------------------------------------------
304 // ---------------------------------------------------------------------------
306 // allocates memory needed to store a C string of length nLen
307 void wxString::AllocBuffer(size_t nLen
)
309 wxASSERT( nLen
> 0 ); //
310 wxASSERT( nLen
<= INT_MAX
-1 ); // max size (enough room for 1 extra)
312 STATISTICS_ADD(Length
, nLen
);
315 // 1) one extra character for '\0' termination
316 // 2) sizeof(wxStringData) for housekeeping info
317 wxStringData
* pData
= (wxStringData
*)
318 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
320 pData
->nDataLength
= nLen
;
321 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
322 m_pchData
= pData
->data(); // data starts after wxStringData
323 m_pchData
[nLen
] = _T('\0');
326 // must be called before changing this string
327 void wxString::CopyBeforeWrite()
329 wxStringData
* pData
= GetStringData();
331 if ( pData
->IsShared() ) {
332 pData
->Unlock(); // memory not freed because shared
333 size_t nLen
= pData
->nDataLength
;
335 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
338 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
341 // must be called before replacing contents of this string
342 void wxString::AllocBeforeWrite(size_t nLen
)
344 wxASSERT( nLen
!= 0 ); // doesn't make any sense
346 // must not share string and must have enough space
347 wxStringData
* pData
= GetStringData();
348 if ( pData
->IsShared() || (nLen
> pData
->nAllocLength
) ) {
349 // can't work with old buffer, get new one
354 // update the string length
355 pData
->nDataLength
= nLen
;
358 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
361 // allocate enough memory for nLen characters
362 void wxString::Alloc(size_t nLen
)
364 wxStringData
*pData
= GetStringData();
365 if ( pData
->nAllocLength
<= nLen
) {
366 if ( pData
->IsEmpty() ) {
369 wxStringData
* pData
= (wxStringData
*)
370 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
372 pData
->nDataLength
= 0;
373 pData
->nAllocLength
= nLen
;
374 m_pchData
= pData
->data(); // data starts after wxStringData
375 m_pchData
[0u] = _T('\0');
377 else if ( pData
->IsShared() ) {
378 pData
->Unlock(); // memory not freed because shared
379 size_t nOldLen
= pData
->nDataLength
;
381 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
386 wxStringData
*p
= (wxStringData
*)
387 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
390 // @@@ what to do on memory error?
394 // it's not important if the pointer changed or not (the check for this
395 // is not faster than assigning to m_pchData in all cases)
396 p
->nAllocLength
= nLen
;
397 m_pchData
= p
->data();
400 //else: we've already got enough
403 // shrink to minimal size (releasing extra memory)
404 void wxString::Shrink()
406 wxStringData
*pData
= GetStringData();
408 // this variable is unused in release build, so avoid the compiler warning by
409 // just not declaring it
413 realloc(pData
, sizeof(wxStringData
) + (pData
->nDataLength
+ 1)*sizeof(wxChar
));
415 wxASSERT( p
!= NULL
); // can't free memory?
416 wxASSERT( p
== pData
); // we're decrementing the size - block shouldn't move!
419 // get the pointer to writable buffer of (at least) nLen bytes
420 wxChar
*wxString::GetWriteBuf(size_t nLen
)
422 AllocBeforeWrite(nLen
);
424 wxASSERT( GetStringData()->nRefs
== 1 );
425 GetStringData()->Validate(FALSE
);
430 // put string back in a reasonable state after GetWriteBuf
431 void wxString::UngetWriteBuf()
433 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
434 GetStringData()->Validate(TRUE
);
437 // ---------------------------------------------------------------------------
439 // ---------------------------------------------------------------------------
441 // all functions are inline in string.h
443 // ---------------------------------------------------------------------------
444 // assignment operators
445 // ---------------------------------------------------------------------------
447 // helper function: does real copy
448 void wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
450 if ( nSrcLen
== 0 ) {
454 AllocBeforeWrite(nSrcLen
);
455 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
456 GetStringData()->nDataLength
= nSrcLen
;
457 m_pchData
[nSrcLen
] = _T('\0');
461 // assigns one string to another
462 wxString
& wxString::operator=(const wxString
& stringSrc
)
464 wxASSERT( stringSrc
.GetStringData()->IsValid() );
466 // don't copy string over itself
467 if ( m_pchData
!= stringSrc
.m_pchData
) {
468 if ( stringSrc
.GetStringData()->IsEmpty() ) {
473 GetStringData()->Unlock();
474 m_pchData
= stringSrc
.m_pchData
;
475 GetStringData()->Lock();
482 // assigns a single character
483 wxString
& wxString::operator=(wxChar ch
)
490 wxString
& wxString::operator=(const wxChar
*psz
)
492 AssignCopy(wxStrlen(psz
), psz
);
498 // same as 'signed char' variant
499 wxString
& wxString::operator=(const unsigned char* psz
)
501 *this = (const char *)psz
;
506 wxString
& wxString::operator=(const wchar_t *pwz
)
516 // ---------------------------------------------------------------------------
517 // string concatenation
518 // ---------------------------------------------------------------------------
520 // add something to this string
521 void wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
523 STATISTICS_ADD(SummandLength
, nSrcLen
);
525 // concatenating an empty string is a NOP
527 wxStringData
*pData
= GetStringData();
528 size_t nLen
= pData
->nDataLength
;
529 size_t nNewLen
= nLen
+ nSrcLen
;
531 // alloc new buffer if current is too small
532 if ( pData
->IsShared() ) {
533 STATISTICS_ADD(ConcatHit
, 0);
535 // we have to allocate another buffer
536 wxStringData
* pOldData
= GetStringData();
537 AllocBuffer(nNewLen
);
538 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
541 else if ( nNewLen
> pData
->nAllocLength
) {
542 STATISTICS_ADD(ConcatHit
, 0);
544 // we have to grow the buffer
548 STATISTICS_ADD(ConcatHit
, 1);
550 // the buffer is already big enough
553 // should be enough space
554 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
556 // fast concatenation - all is done in our buffer
557 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
559 m_pchData
[nNewLen
] = _T('\0'); // put terminating '\0'
560 GetStringData()->nDataLength
= nNewLen
; // and fix the length
562 //else: the string to append was empty
566 * concatenation functions come in 5 flavours:
568 * char + string and string + char
569 * C str + string and string + C str
572 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
574 wxASSERT( string1
.GetStringData()->IsValid() );
575 wxASSERT( string2
.GetStringData()->IsValid() );
577 wxString s
= string1
;
583 wxString
operator+(const wxString
& string
, wxChar ch
)
585 wxASSERT( string
.GetStringData()->IsValid() );
593 wxString
operator+(wxChar ch
, const wxString
& string
)
595 wxASSERT( string
.GetStringData()->IsValid() );
603 wxString
operator+(const wxString
& string
, const wxChar
*psz
)
605 wxASSERT( string
.GetStringData()->IsValid() );
608 s
.Alloc(wxStrlen(psz
) + string
.Len());
615 wxString
operator+(const wxChar
*psz
, const wxString
& string
)
617 wxASSERT( string
.GetStringData()->IsValid() );
620 s
.Alloc(wxStrlen(psz
) + string
.Len());
627 // ===========================================================================
628 // other common string functions
629 // ===========================================================================
631 // ---------------------------------------------------------------------------
632 // simple sub-string extraction
633 // ---------------------------------------------------------------------------
635 // helper function: clone the data attached to this string
636 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
638 if ( nCopyLen
== 0 ) {
642 dest
.AllocBuffer(nCopyLen
);
643 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
647 // extract string of length nCount starting at nFirst
648 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
650 wxStringData
*pData
= GetStringData();
651 size_t nLen
= pData
->nDataLength
;
653 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
654 if ( nCount
== wxSTRING_MAXLEN
)
656 nCount
= nLen
- nFirst
;
659 // out-of-bounds requests return sensible things
660 if ( nFirst
+ nCount
> nLen
)
662 nCount
= nLen
- nFirst
;
667 // AllocCopy() will return empty string
672 AllocCopy(dest
, nCount
, nFirst
);
677 // extract nCount last (rightmost) characters
678 wxString
wxString::Right(size_t nCount
) const
680 if ( nCount
> (size_t)GetStringData()->nDataLength
)
681 nCount
= GetStringData()->nDataLength
;
684 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
688 // get all characters after the last occurence of ch
689 // (returns the whole string if ch not found)
690 wxString
wxString::AfterLast(wxChar ch
) const
693 int iPos
= Find(ch
, TRUE
);
694 if ( iPos
== wxNOT_FOUND
)
697 str
= c_str() + iPos
+ 1;
702 // extract nCount first (leftmost) characters
703 wxString
wxString::Left(size_t nCount
) const
705 if ( nCount
> (size_t)GetStringData()->nDataLength
)
706 nCount
= GetStringData()->nDataLength
;
709 AllocCopy(dest
, nCount
, 0);
713 // get all characters before the first occurence of ch
714 // (returns the whole string if ch not found)
715 wxString
wxString::BeforeFirst(wxChar ch
) const
718 for ( const wxChar
*pc
= m_pchData
; *pc
!= _T('\0') && *pc
!= ch
; pc
++ )
724 /// get all characters before the last occurence of ch
725 /// (returns empty string if ch not found)
726 wxString
wxString::BeforeLast(wxChar ch
) const
729 int iPos
= Find(ch
, TRUE
);
730 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
731 str
= wxString(c_str(), iPos
);
736 /// get all characters after the first occurence of ch
737 /// (returns empty string if ch not found)
738 wxString
wxString::AfterFirst(wxChar ch
) const
742 if ( iPos
!= wxNOT_FOUND
)
743 str
= c_str() + iPos
+ 1;
748 // replace first (or all) occurences of some substring with another one
749 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
751 size_t uiCount
= 0; // count of replacements made
753 size_t uiOldLen
= wxStrlen(szOld
);
756 const wxChar
*pCurrent
= m_pchData
;
757 const wxChar
*pSubstr
;
758 while ( *pCurrent
!= _T('\0') ) {
759 pSubstr
= wxStrstr(pCurrent
, szOld
);
760 if ( pSubstr
== NULL
) {
761 // strTemp is unused if no replacements were made, so avoid the copy
765 strTemp
+= pCurrent
; // copy the rest
766 break; // exit the loop
769 // take chars before match
770 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
772 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
777 if ( !bReplaceAll
) {
778 strTemp
+= pCurrent
; // copy the rest
779 break; // exit the loop
784 // only done if there were replacements, otherwise would have returned above
790 bool wxString::IsAscii() const
792 const wxChar
*s
= (const wxChar
*) *this;
794 if(!isascii(*s
)) return(FALSE
);
800 bool wxString::IsWord() const
802 const wxChar
*s
= (const wxChar
*) *this;
804 if(!wxIsalpha(*s
)) return(FALSE
);
810 bool wxString::IsNumber() const
812 const wxChar
*s
= (const wxChar
*) *this;
814 if(!wxIsdigit(*s
)) return(FALSE
);
820 wxString
wxString::Strip(stripType w
) const
823 if ( w
& leading
) s
.Trim(FALSE
);
824 if ( w
& trailing
) s
.Trim(TRUE
);
828 // ---------------------------------------------------------------------------
830 // ---------------------------------------------------------------------------
832 wxString
& wxString::MakeUpper()
836 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
837 *p
= (wxChar
)wxToupper(*p
);
842 wxString
& wxString::MakeLower()
846 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
847 *p
= (wxChar
)wxTolower(*p
);
852 // ---------------------------------------------------------------------------
853 // trimming and padding
854 // ---------------------------------------------------------------------------
856 // trims spaces (in the sense of isspace) from left or right side
857 wxString
& wxString::Trim(bool bFromRight
)
859 // first check if we're going to modify the string at all
862 (bFromRight
&& wxIsspace(GetChar(Len() - 1))) ||
863 (!bFromRight
&& wxIsspace(GetChar(0u)))
867 // ok, there is at least one space to trim
872 // find last non-space character
873 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
874 while ( wxIsspace(*psz
) && (psz
>= m_pchData
) )
877 // truncate at trailing space start
879 GetStringData()->nDataLength
= psz
- m_pchData
;
883 // find first non-space character
884 const wxChar
*psz
= m_pchData
;
885 while ( wxIsspace(*psz
) )
888 // fix up data and length
889 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
890 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
891 GetStringData()->nDataLength
= nDataLength
;
898 // adds nCount characters chPad to the string from either side
899 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
901 wxString
s(chPad
, nCount
);
914 // truncate the string
915 wxString
& wxString::Truncate(size_t uiLen
)
917 if ( uiLen
< Len() ) {
920 *(m_pchData
+ uiLen
) = _T('\0');
921 GetStringData()->nDataLength
= uiLen
;
923 //else: nothing to do, string is already short enough
928 // ---------------------------------------------------------------------------
929 // finding (return wxNOT_FOUND if not found and index otherwise)
930 // ---------------------------------------------------------------------------
933 int wxString::Find(wxChar ch
, bool bFromEnd
) const
935 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
937 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
940 // find a sub-string (like strstr)
941 int wxString::Find(const wxChar
*pszSub
) const
943 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
945 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
948 // ---------------------------------------------------------------------------
949 // stream-like operators
950 // ---------------------------------------------------------------------------
951 wxString
& wxString::operator<<(int i
)
954 res
.Printf(_T("%d"), i
);
956 return (*this) << res
;
959 wxString
& wxString::operator<<(float f
)
962 res
.Printf(_T("%f"), f
);
964 return (*this) << res
;
967 wxString
& wxString::operator<<(double d
)
970 res
.Printf(_T("%g"), d
);
972 return (*this) << res
;
975 // ---------------------------------------------------------------------------
977 // ---------------------------------------------------------------------------
978 int wxString::Printf(const wxChar
*pszFormat
, ...)
981 va_start(argptr
, pszFormat
);
983 int iLen
= PrintfV(pszFormat
, argptr
);
990 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
992 // static buffer to avoid dynamic memory allocation each time
993 char s_szScratch
[1024]; // using static buffer causes internal compiler err
996 // protect the static buffer
997 static wxCriticalSection critsect
;
998 wxCriticalSectionLocker
lock(critsect
);
1002 #if wxUSE_EXPERIMENTAL_PRINTF
1003 // the new implementation
1006 for (size_t n
= 0; pszFormat
[n
]; n
++)
1007 if (pszFormat
[n
] == _T('%')) {
1008 static char s_szFlags
[256] = "%";
1010 bool adj_left
= FALSE
, in_prec
= FALSE
,
1011 prec_dot
= FALSE
, done
= FALSE
;
1013 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1015 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1016 switch (pszFormat
[++n
]) {
1030 s_szFlags
[flagofs
++] = pszFormat
[n
];
1035 s_szFlags
[flagofs
++] = pszFormat
[n
];
1042 // dot will be auto-added to s_szFlags if non-negative number follows
1047 s_szFlags
[flagofs
++] = pszFormat
[n
];
1052 s_szFlags
[flagofs
++] = pszFormat
[n
];
1058 s_szFlags
[flagofs
++] = pszFormat
[n
];
1063 s_szFlags
[flagofs
++] = pszFormat
[n
];
1067 int len
= va_arg(argptr
, int);
1074 adj_left
= !adj_left
;
1075 s_szFlags
[flagofs
++] = '-';
1080 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1083 case _T('1'): case _T('2'): case _T('3'):
1084 case _T('4'): case _T('5'): case _T('6'):
1085 case _T('7'): case _T('8'): case _T('9'):
1089 while ((pszFormat
[n
]>=_T('0')) && (pszFormat
[n
]<=_T('9'))) {
1090 s_szFlags
[flagofs
++] = pszFormat
[n
];
1091 len
= len
*10 + (pszFormat
[n
] - _T('0'));
1094 if (in_prec
) max_width
= len
;
1095 else min_width
= len
;
1096 n
--; // the main loop pre-increments n again
1106 s_szFlags
[flagofs
++] = pszFormat
[n
];
1107 s_szFlags
[flagofs
] = '\0';
1109 int val
= va_arg(argptr
, int);
1110 ::sprintf(s_szScratch
, s_szFlags
, val
);
1112 else if (ilen
== -1) {
1113 short int val
= va_arg(argptr
, short int);
1114 ::sprintf(s_szScratch
, s_szFlags
, val
);
1116 else if (ilen
== 1) {
1117 long int val
= va_arg(argptr
, long int);
1118 ::sprintf(s_szScratch
, s_szFlags
, val
);
1120 else if (ilen
== 2) {
1121 #if SIZEOF_LONG_LONG
1122 long long int val
= va_arg(argptr
, long long int);
1123 ::sprintf(s_szScratch
, s_szFlags
, val
);
1125 long int val
= va_arg(argptr
, long int);
1126 ::sprintf(s_szScratch
, s_szFlags
, val
);
1129 else if (ilen
== 3) {
1130 size_t val
= va_arg(argptr
, size_t);
1131 ::sprintf(s_szScratch
, s_szFlags
, val
);
1133 *this += wxString(s_szScratch
);
1142 s_szFlags
[flagofs
++] = pszFormat
[n
];
1143 s_szFlags
[flagofs
] = '\0';
1145 long double val
= va_arg(argptr
, long double);
1146 ::sprintf(s_szScratch
, s_szFlags
, val
);
1148 double val
= va_arg(argptr
, double);
1149 ::sprintf(s_szScratch
, s_szFlags
, val
);
1151 *this += wxString(s_szScratch
);
1156 void *val
= va_arg(argptr
, void *);
1158 s_szFlags
[flagofs
++] = pszFormat
[n
];
1159 s_szFlags
[flagofs
] = '\0';
1160 ::sprintf(s_szScratch
, s_szFlags
, val
);
1161 *this += wxString(s_szScratch
);
1167 wxChar val
= va_arg(argptr
, int);
1168 // we don't need to honor padding here, do we?
1175 // wx extension: we'll let %hs mean non-Unicode strings
1176 char *val
= va_arg(argptr
, char *);
1178 // ASCII->Unicode constructor handles max_width right
1179 wxString
s(val
, wxConvLibc
, max_width
);
1181 size_t len
= wxSTRING_MAXLEN
;
1183 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1184 } else val
= _T("(null)");
1185 wxString
s(val
, len
);
1187 if (s
.Len() < min_width
)
1188 s
.Pad(min_width
- s
.Len(), _T(' '), adj_left
);
1191 wxChar
*val
= va_arg(argptr
, wxChar
*);
1192 size_t len
= wxSTRING_MAXLEN
;
1194 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1195 } else val
= _T("(null)");
1196 wxString
s(val
, len
);
1197 if (s
.Len() < min_width
)
1198 s
.Pad(min_width
- s
.Len(), _T(' '), adj_left
);
1205 int *val
= va_arg(argptr
, int *);
1208 else if (ilen
== -1) {
1209 short int *val
= va_arg(argptr
, short int *);
1212 else if (ilen
>= 1) {
1213 long int *val
= va_arg(argptr
, long int *);
1219 if (wxIsalpha(pszFormat
[n
]))
1220 // probably some flag not taken care of here yet
1221 s_szFlags
[flagofs
++] = pszFormat
[n
];
1224 *this += _T('%'); // just to pass the glibc tst-printf.c
1232 } else *this += pszFormat
[n
];
1235 // NB: wxVsnprintf() may return either less than the buffer size or -1 if there
1236 // is not enough place depending on implementation
1237 int iLen
= wxVsnprintf(s_szScratch
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
1239 if ( iLen
< (int)WXSIZEOF(s_szScratch
) ) {
1240 buffer
= s_szScratch
;
1243 int size
= WXSIZEOF(s_szScratch
) * 2;
1244 buffer
= (char *)malloc(size
);
1245 while ( buffer
!= NULL
) {
1246 iLen
= wxVsnprintf(buffer
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
1247 if ( iLen
< size
) {
1248 // ok, there was enough space
1252 // still not enough, double it again
1253 buffer
= (char *)realloc(buffer
, size
*= 2);
1265 if ( buffer
!= s_szScratch
)
1272 // ----------------------------------------------------------------------------
1273 // misc other operations
1274 // ----------------------------------------------------------------------------
1275 bool wxString::Matches(const wxChar
*pszMask
) const
1277 // check char by char
1278 const wxChar
*pszTxt
;
1279 for ( pszTxt
= c_str(); *pszMask
!= _T('\0'); pszMask
++, pszTxt
++ ) {
1280 switch ( *pszMask
) {
1282 if ( *pszTxt
== _T('\0') )
1291 // ignore special chars immediately following this one
1292 while ( *pszMask
== _T('*') || *pszMask
== _T('?') )
1295 // if there is nothing more, match
1296 if ( *pszMask
== _T('\0') )
1299 // are there any other metacharacters in the mask?
1301 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, _T("*?"));
1303 if ( pEndMask
!= NULL
) {
1304 // we have to match the string between two metachars
1305 uiLenMask
= pEndMask
- pszMask
;
1308 // we have to match the remainder of the string
1309 uiLenMask
= wxStrlen(pszMask
);
1312 wxString
strToMatch(pszMask
, uiLenMask
);
1313 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1314 if ( pMatch
== NULL
)
1317 // -1 to compensate "++" in the loop
1318 pszTxt
= pMatch
+ uiLenMask
- 1;
1319 pszMask
+= uiLenMask
- 1;
1324 if ( *pszMask
!= *pszTxt
)
1330 // match only if nothing left
1331 return *pszTxt
== _T('\0');
1334 // Count the number of chars
1335 int wxString::Freq(wxChar ch
) const
1339 for (int i
= 0; i
< len
; i
++)
1341 if (GetChar(i
) == ch
)
1347 // convert to upper case, return the copy of the string
1348 wxString
wxString::Upper() const
1349 { wxString
s(*this); return s
.MakeUpper(); }
1351 // convert to lower case, return the copy of the string
1352 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1354 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1357 va_start(argptr
, pszFormat
);
1358 int iLen
= PrintfV(pszFormat
, argptr
);
1363 // ---------------------------------------------------------------------------
1364 // standard C++ library string functions
1365 // ---------------------------------------------------------------------------
1366 #ifdef wxSTD_STRING_COMPATIBILITY
1368 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1370 wxASSERT( str
.GetStringData()->IsValid() );
1371 wxASSERT( nPos
<= Len() );
1373 if ( !str
.IsEmpty() ) {
1375 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1376 wxStrncpy(pc
, c_str(), nPos
);
1377 wxStrcpy(pc
+ nPos
, str
);
1378 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1379 strTmp
.UngetWriteBuf();
1386 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1388 wxASSERT( str
.GetStringData()->IsValid() );
1389 wxASSERT( nStart
<= Len() );
1391 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1393 return p
== NULL
? npos
: p
- c_str();
1396 // VC++ 1.5 can't cope with the default argument in the header.
1397 #if !defined(__VISUALC__) || defined(__WIN32__)
1398 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1400 return find(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1404 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1405 #if !defined(__BORLANDC__)
1406 size_t wxString::find(wxChar ch
, size_t nStart
) const
1408 wxASSERT( nStart
<= Len() );
1410 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1412 return p
== NULL
? npos
: p
- c_str();
1416 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1418 wxASSERT( str
.GetStringData()->IsValid() );
1419 wxASSERT( nStart
<= Len() );
1421 // TODO could be made much quicker than that
1422 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1423 while ( p
>= c_str() + str
.Len() ) {
1424 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1425 return p
- str
.Len() - c_str();
1432 // VC++ 1.5 can't cope with the default argument in the header.
1433 #if !defined(__VISUALC__) || defined(__WIN32__)
1434 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1436 return rfind(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1439 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1441 if ( nStart
== npos
)
1447 wxASSERT( nStart
<= Len() );
1450 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1455 size_t result
= p
- c_str();
1456 return ( result
> nStart
) ? npos
: result
;
1460 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1462 const wxChar
*start
= c_str() + nStart
;
1463 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1465 return firstOf
- start
;
1470 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1472 if ( nStart
== npos
)
1478 wxASSERT( nStart
<= Len() );
1481 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1483 if ( wxStrchr(sz
, *p
) )
1490 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1492 if ( nStart
== npos
)
1498 wxASSERT( nStart
<= Len() );
1501 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1502 if ( nAccept
>= length() - nStart
)
1508 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1510 wxASSERT( nStart
<= Len() );
1512 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1521 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1523 if ( nStart
== npos
)
1529 wxASSERT( nStart
<= Len() );
1532 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1534 if ( !wxStrchr(sz
, *p
) )
1541 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1543 if ( nStart
== npos
)
1549 wxASSERT( nStart
<= Len() );
1552 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1561 wxString
wxString::substr(size_t nStart
, size_t nLen
) const
1563 // npos means 'take all'
1567 wxASSERT( nStart
+ nLen
<= Len() );
1569 return wxString(c_str() + nStart
, nLen
== npos
? 0 : nLen
);
1572 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1574 wxString
strTmp(c_str(), nStart
);
1575 if ( nLen
!= npos
) {
1576 wxASSERT( nStart
+ nLen
<= Len() );
1578 strTmp
.append(c_str() + nStart
+ nLen
);
1585 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1587 wxASSERT( nStart
+ nLen
<= wxStrlen(sz
) );
1591 strTmp
.append(c_str(), nStart
);
1593 strTmp
.append(c_str() + nStart
+ nLen
);
1599 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1601 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1604 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1605 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1607 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1610 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1611 const wxChar
* sz
, size_t nCount
)
1613 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1616 #endif //std::string compatibility
1618 // ============================================================================
1620 // ============================================================================
1622 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1623 #define ARRAY_MAXSIZE_INCREMENT 4096
1624 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1625 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1628 #define STRING(p) ((wxString *)(&(p)))
1631 wxArrayString::wxArrayString()
1635 m_pItems
= (wxChar
**) NULL
;
1639 wxArrayString::wxArrayString(const wxArrayString
& src
)
1643 m_pItems
= (wxChar
**) NULL
;
1648 // assignment operator
1649 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1654 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1655 Alloc(src
.m_nCount
);
1657 // we can't just copy the pointers here because otherwise we would share
1658 // the strings with another array
1659 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1662 if ( m_nCount
!= 0 )
1663 memcpy(m_pItems
, src
.m_pItems
, m_nCount
*sizeof(wxChar
*));
1669 void wxArrayString::Grow()
1671 // only do it if no more place
1672 if( m_nCount
== m_nSize
) {
1673 if( m_nSize
== 0 ) {
1674 // was empty, alloc some memory
1675 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1676 m_pItems
= new wxChar
*[m_nSize
];
1679 // otherwise when it's called for the first time, nIncrement would be 0
1680 // and the array would never be expanded
1681 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE
!= 0 );
1683 // add 50% but not too much
1684 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1685 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1686 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1687 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1688 m_nSize
+= nIncrement
;
1689 wxChar
**pNew
= new wxChar
*[m_nSize
];
1691 // copy data to new location
1692 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1694 // delete old memory (but do not release the strings!)
1695 wxDELETEA(m_pItems
);
1702 void wxArrayString::Free()
1704 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1705 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1709 // deletes all the strings from the list
1710 void wxArrayString::Empty()
1717 // as Empty, but also frees memory
1718 void wxArrayString::Clear()
1725 wxDELETEA(m_pItems
);
1729 wxArrayString::~wxArrayString()
1733 wxDELETEA(m_pItems
);
1736 // pre-allocates memory (frees the previous data!)
1737 void wxArrayString::Alloc(size_t nSize
)
1739 wxASSERT( nSize
> 0 );
1741 // only if old buffer was not big enough
1742 if ( nSize
> m_nSize
) {
1744 wxDELETEA(m_pItems
);
1745 m_pItems
= new wxChar
*[nSize
];
1752 // minimizes the memory usage by freeing unused memory
1753 void wxArrayString::Shrink()
1755 // only do it if we have some memory to free
1756 if( m_nCount
< m_nSize
) {
1757 // allocates exactly as much memory as we need
1758 wxChar
**pNew
= new wxChar
*[m_nCount
];
1760 // copy data to new location
1761 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1767 // searches the array for an item (forward or backwards)
1768 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
1771 if ( m_nCount
> 0 ) {
1772 size_t ui
= m_nCount
;
1774 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1781 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1782 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1790 // add item at the end
1791 void wxArrayString::Add(const wxString
& str
)
1793 wxASSERT( str
.GetStringData()->IsValid() );
1797 // the string data must not be deleted!
1798 str
.GetStringData()->Lock();
1799 m_pItems
[m_nCount
++] = (wxChar
*)str
.c_str();
1802 // add item at the given position
1803 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
1805 wxASSERT( str
.GetStringData()->IsValid() );
1807 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Insert") );
1811 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
1812 (m_nCount
- nIndex
)*sizeof(wxChar
*));
1814 str
.GetStringData()->Lock();
1815 m_pItems
[nIndex
] = (wxChar
*)str
.c_str();
1820 // removes item from array (by index)
1821 void wxArrayString::Remove(size_t nIndex
)
1823 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Remove") );
1826 Item(nIndex
).GetStringData()->Unlock();
1828 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
1829 (m_nCount
- nIndex
- 1)*sizeof(wxChar
*));
1833 // removes item from array (by value)
1834 void wxArrayString::Remove(const wxChar
*sz
)
1836 int iIndex
= Index(sz
);
1838 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
1839 _("removing inexistent element in wxArrayString::Remove") );
1844 // ----------------------------------------------------------------------------
1846 // ----------------------------------------------------------------------------
1848 // we can only sort one array at a time with the quick-sort based
1851 // need a critical section to protect access to gs_compareFunction and
1852 // gs_sortAscending variables
1853 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
1855 // call this before the value of the global sort vars is changed/after
1856 // you're finished with them
1857 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
1858 gs_critsectStringSort = new wxCriticalSection; \
1859 gs_critsectStringSort->Enter()
1860 #define END_SORT() gs_critsectStringSort->Leave(); \
1861 delete gs_critsectStringSort; \
1862 gs_critsectStringSort = NULL
1864 #define START_SORT()
1866 #endif // wxUSE_THREADS
1868 // function to use for string comparaison
1869 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
1871 // if we don't use the compare function, this flag tells us if we sort the
1872 // array in ascending or descending order
1873 static bool gs_sortAscending
= TRUE
;
1875 // function which is called by quick sort
1876 static int wxStringCompareFunction(const void *first
, const void *second
)
1878 wxString
*strFirst
= (wxString
*)first
;
1879 wxString
*strSecond
= (wxString
*)second
;
1881 if ( gs_compareFunction
) {
1882 return gs_compareFunction(*strFirst
, *strSecond
);
1885 // maybe we should use wxStrcoll
1886 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
1888 return gs_sortAscending
? result
: -result
;
1892 // sort array elements using passed comparaison function
1893 void wxArrayString::Sort(CompareFunction compareFunction
)
1897 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1898 gs_compareFunction
= compareFunction
;
1905 void wxArrayString::Sort(bool reverseOrder
)
1909 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1910 gs_sortAscending
= !reverseOrder
;
1917 void wxArrayString::DoSort()
1919 // just sort the pointers using qsort() - of course it only works because
1920 // wxString() *is* a pointer to its data
1921 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
1924 // ============================================================================
1926 // ============================================================================
1928 WXDLLEXPORT_DATA(wxMBConv
*) wxConvCurrent
= &wxConvLibc
;
1930 WXDLLEXPORT_DATA(wxMBConv
) wxConvLibc
, wxConvFile
;
1935 // ----------------------------------------------------------------------------
1936 // standard libc conversion
1937 // ----------------------------------------------------------------------------
1939 WXDLLEXPORT_DATA(wxMBConv
) wxConvLibc
;
1941 size_t wxMBConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1943 return wxMB2WC(buf
, psz
, n
);
1946 size_t wxMBConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1948 return wxWC2MB(buf
, psz
, n
);
1951 // ----------------------------------------------------------------------------
1952 // standard file conversion
1953 // ----------------------------------------------------------------------------
1955 WXDLLEXPORT_DATA(wxMBConvFile
) wxConvFile
;
1957 // just use the libc conversion for now
1958 size_t wxMBConvFile::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1960 return wxMB2WC(buf
, psz
, n
);
1963 size_t wxMBConvFile::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1965 return wxWC2MB(buf
, psz
, n
);
1968 // ----------------------------------------------------------------------------
1969 // standard gdk conversion
1970 // ----------------------------------------------------------------------------
1973 WXDLLEXPORT_DATA(wxMBConvGdk
) wxConvGdk
;
1975 #include <gdk/gdk.h>
1977 size_t wxMBConvGdk::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1980 return gdk_mbstowcs((GdkWChar
*)buf
, psz
, n
);
1982 GdkWChar
*nbuf
= new GdkWChar
[n
=strlen(psz
)];
1983 size_t len
= gdk_mbstowcs(nbuf
, psz
, n
);
1989 size_t wxMBConvGdk::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1991 char *mbstr
= gdk_wcstombs((GdkWChar
*)psz
);
1992 size_t len
= mbstr
? strlen(mbstr
) : 0;
1994 if (len
> n
) len
= n
;
1995 memcpy(buf
, psz
, len
);
1996 if (len
< n
) buf
[len
] = 0;
2002 // ----------------------------------------------------------------------------
2004 // ----------------------------------------------------------------------------
2006 WXDLLEXPORT_DATA(wxMBConvUTF7
) wxConvUTF7
;
2009 static char utf7_setD
[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2010 "abcdefghijklmnopqrstuvwxyz"
2011 "0123456789'(),-./:?";
2012 static char utf7_setO
[]="!\"#$%&*;<=>@[]^_`{|}";
2013 static char utf7_setB
[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2014 "abcdefghijklmnopqrstuvwxyz"
2018 // TODO: write actual implementations of UTF-7 here
2019 size_t wxMBConvUTF7::MB2WC(wchar_t * WXUNUSED(buf
),
2020 const char * WXUNUSED(psz
),
2021 size_t WXUNUSED(n
)) const
2026 size_t wxMBConvUTF7::WC2MB(char * WXUNUSED(buf
),
2027 const wchar_t * WXUNUSED(psz
),
2028 size_t WXUNUSED(n
)) const
2033 // ----------------------------------------------------------------------------
2035 // ----------------------------------------------------------------------------
2037 WXDLLEXPORT_DATA(wxMBConvUTF8
) wxConvUTF8
;
2039 static unsigned long utf8_max
[]={0x7f,0x7ff,0xffff,0x1fffff,0x3ffffff,0x7fffffff,0xffffffff};
2041 size_t wxMBConvUTF8::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2045 while (*psz
&& ((!buf
) || (len
<n
))) {
2046 unsigned char cc
=*psz
++, fc
=cc
;
2048 for (cnt
=0; fc
&0x80; cnt
++) fc
<<=1;
2056 // invalid UTF-8 sequence
2059 unsigned ocnt
=cnt
-1;
2060 unsigned long res
=cc
&(0x3f>>cnt
);
2063 if ((cc
&0xC0)!=0x80) {
2064 // invalid UTF-8 sequence
2067 res
=(res
<<6)|(cc
&0x3f);
2069 if (res
<=utf8_max
[ocnt
]) {
2070 // illegal UTF-8 encoding
2073 if (buf
) *buf
++=res
;
2078 if (buf
&& (len
<n
)) *buf
= 0;
2082 size_t wxMBConvUTF8::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
2086 while (*psz
&& ((!buf
) || (len
<n
))) {
2087 unsigned long cc
=(*psz
++)&0x7fffffff;
2089 for (cnt
=0; cc
>utf8_max
[cnt
]; cnt
++);
2097 *buf
++=(-128>>cnt
)|((cc
>>(cnt
*6))&(0x3f>>cnt
));
2099 *buf
++=0x80|((cc
>>(cnt
*6))&0x3f);
2103 if (buf
&& (len
<n
)) *buf
= 0;
2107 // ----------------------------------------------------------------------------
2108 // specified character set
2109 // ----------------------------------------------------------------------------
2111 class wxCharacterSet
2114 wxArrayString names
;
2119 #include "wx/dynarray.h"
2120 #include "wx/filefn.h"
2121 #include "wx/textfile.h"
2122 #include "wx/tokenzr.h"
2123 #include "wx/utils.h"
2126 WX_DECLARE_OBJARRAY(wxCharacterSet
, wxCSArray
);
2127 #include "wx/arrimpl.cpp"
2128 WX_DEFINE_OBJARRAY(wxCSArray
);
2130 static wxCSArray wxCharsets
;
2132 static void wxLoadCharacterSets(void)
2134 static bool already_loaded
= FALSE
;
2136 if (already_loaded
) return;
2138 already_loaded
= TRUE
;
2139 #if defined(__UNIX__) && wxUSE_TEXTFILE
2140 // search through files in /usr/share/i18n/charmaps
2142 for (fname
= ::wxFindFirstFile(_T("/usr/share/i18n/charmaps/*"));
2144 fname
= ::wxFindNextFile()) {
2145 wxTextFile
cmap(fname
);
2147 wxCharacterSet
*cset
= new wxCharacterSet
;
2148 wxString comchar
,escchar
;
2149 bool in_charset
= FALSE
;
2151 // wxFprintf(stderr,_T("Loaded: %s\n"),fname.c_str());
2154 for (line
= cmap
.GetFirstLine();
2156 line
= cmap
.GetNextLine()) {
2157 // wxFprintf(stderr,_T("line contents: %s\n"),line.c_str());
2158 wxStringTokenizer
token(line
);
2159 wxString cmd
= token
.GetNextToken();
2160 if (cmd
== comchar
) {
2161 if (token
.GetNextToken() == _T("alias"))
2162 cset
->names
.Add(token
.GetNextToken());
2164 else if (cmd
== _T("<code_set_name>"))
2165 cset
->names
.Add(token
.GetNextToken());
2166 else if (cmd
== _T("<comment_char>"))
2167 comchar
= token
.GetNextToken();
2168 else if (cmd
== _T("<escape_char>"))
2169 escchar
= token
.GetNextToken();
2170 else if (cmd
== _T("<mb_cur_min>")) {
2172 cset
= (wxCharacterSet
*) NULL
;
2173 break; // we don't support multibyte charsets ourselves (yet)
2175 else if (cmd
== _T("CHARMAP")) {
2176 cset
->data
= (wchar_t *)calloc(256, sizeof(wchar_t));
2179 else if (cmd
== _T("END")) {
2180 if (token
.GetNextToken() == _T("CHARMAP"))
2183 else if (in_charset
) {
2184 // format: <NUL> /x00 <U0000> NULL (NUL)
2185 // <A> /x41 <U0041> LATIN CAPITAL LETTER A
2186 wxString hex
= token
.GetNextToken();
2187 // skip whitespace (why doesn't wxStringTokenizer do this?)
2188 while (wxIsEmpty(hex
) && token
.HasMoreTokens()) hex
= token
.GetNextToken();
2189 wxString uni
= token
.GetNextToken();
2190 // skip whitespace again
2191 while (wxIsEmpty(uni
) && token
.HasMoreTokens()) uni
= token
.GetNextToken();
2193 if ((hex
.Len() > 2) && (hex
.GetChar(0) == escchar
) && (hex
.GetChar(1) == _T('x')) &&
2194 (uni
.Left(2) == _T("<U"))) {
2195 hex
.MakeUpper(); uni
.MakeUpper();
2196 int pos
= ::wxHexToDec(hex
.Mid(2,2));
2198 unsigned long uni1
= ::wxHexToDec(uni
.Mid(2,2));
2199 unsigned long uni2
= ::wxHexToDec(uni
.Mid(4,2));
2200 cset
->data
[pos
] = (uni1
<< 16) | uni2
;
2201 // wxFprintf(stderr,_T("char %02x mapped to %04x (%c)\n"),pos,cset->data[pos],cset->data[pos]);
2207 cset
->names
.Shrink();
2208 wxCharsets
.Add(cset
);
2213 wxCharsets
.Shrink();
2216 static wxCharacterSet
*wxFindCharacterSet(const wxChar
*charset
)
2218 if (!charset
) return (wxCharacterSet
*)NULL
;
2219 wxLoadCharacterSets();
2220 for (size_t n
=0; n
<wxCharsets
.GetCount(); n
++)
2221 if (wxCharsets
[n
].names
.Index(charset
) != wxNOT_FOUND
)
2222 return &(wxCharsets
[n
]);
2223 return (wxCharacterSet
*)NULL
;
2226 WXDLLEXPORT_DATA(wxCSConv
) wxConvLocal((const wxChar
*)NULL
);
2228 wxCSConv::wxCSConv(const wxChar
*charset
)
2230 m_name
= (wxChar
*) NULL
;
2231 m_cset
= (wxCharacterSet
*) NULL
;
2236 wxCSConv::~wxCSConv()
2238 if (m_name
) free(m_name
);
2241 void wxCSConv::SetName(const wxChar
*charset
)
2245 // first, convert the character set name to standard form
2247 if (wxString(charset
,3).CmpNoCase(_T("ISO")) == 0) {
2248 // make sure it's represented in the standard form: ISO_8859-1
2249 codeset
= _T("ISO_");
2251 if ((*charset
== _T('-')) || (*charset
== _T('_'))) charset
++;
2252 if (wxStrlen(charset
)>4) {
2253 if (wxString(charset
,4) == _T("8859")) {
2254 codeset
<< _T("8859-");
2255 if (*charset
== _T('-')) charset
++;
2260 codeset
.MakeUpper();
2261 m_name
= wxStrdup(codeset
.c_str());
2267 void wxCSConv::LoadNow()
2269 // wxPrintf(_T("Conversion request\n"));
2273 wxChar
*lang
= wxGetenv(_T("LANG"));
2274 wxChar
*dot
= lang
? wxStrchr(lang
, _T('.')) : (wxChar
*)NULL
;
2275 if (dot
) SetName(dot
+1);
2278 m_cset
= wxFindCharacterSet(m_name
);
2283 size_t wxCSConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2285 ((wxCSConv
*)this)->LoadNow(); // discard constness
2288 for (size_t c
=0; c
<n
; c
++)
2289 buf
[c
] = m_cset
->data
[(unsigned char)(psz
[c
])];
2292 for (size_t c
=0; c
<n
; c
++)
2293 buf
[c
] = (unsigned char)(psz
[c
]);
2300 size_t wxCSConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
2302 ((wxCSConv
*)this)->LoadNow(); // discard constness
2305 for (size_t c
=0; c
<n
; c
++) {
2307 for (n
=0; (n
<256) && (m_cset
->data
[n
] != psz
[c
]); n
++);
2308 buf
[c
] = (n
>0xff) ? '?' : n
;
2312 for (size_t c
=0; c
<n
; c
++)
2313 buf
[c
] = (psz
[c
]>0xff) ? '?' : psz
[c
];
2320 #endif//wxUSE_WCHAR_T
2323 const wxWCharBuffer
wxMBConv::cMB2WC(const char *psz
) const
2326 size_t nLen
= MB2WC((wchar_t *) NULL
, psz
, 0);
2327 wxWCharBuffer
buf(nLen
);
2328 MB2WC(WCSTRINGCAST buf
, psz
, nLen
);
2330 } else return wxWCharBuffer((wchar_t *) NULL
);
2333 const wxCharBuffer
wxMBConv::cWC2MB(const wchar_t *psz
) const
2336 size_t nLen
= WC2MB((char *) NULL
, psz
, 0);
2337 wxCharBuffer
buf(nLen
);
2338 WC2MB(MBSTRINGCAST buf
, psz
, nLen
);
2340 } else return wxCharBuffer((char *) NULL
);
2343 #endif//wxUSE_WCHAR_T