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
59 // allocating extra space for each string consumes more memory but speeds up
60 // the concatenation operations (nLen is the current string's length)
61 // NB: EXTRA_ALLOC must be >= 0!
62 #define EXTRA_ALLOC (19 - nLen % 16)
64 // ---------------------------------------------------------------------------
65 // static class variables definition
66 // ---------------------------------------------------------------------------
68 #ifdef wxSTD_STRING_COMPATIBILITY
69 const size_t wxString::npos
= wxSTRING_MAXLEN
;
70 #endif // wxSTD_STRING_COMPATIBILITY
72 // ----------------------------------------------------------------------------
74 // ----------------------------------------------------------------------------
76 // for an empty string, GetStringData() will return this address: this
77 // structure has the same layout as wxStringData and it's data() method will
78 // return the empty string (dummy pointer)
83 } g_strEmpty
= { {-1, 0, 0}, _T('\0') };
85 // empty C style string: points to 'string data' byte of g_strEmpty
86 extern const wxChar WXDLLEXPORT
*g_szNul
= &g_strEmpty
.dummy
;
88 // ----------------------------------------------------------------------------
89 // conditional compilation
90 // ----------------------------------------------------------------------------
92 // we want to find out if the current platform supports vsnprintf()-like
93 // function: for Unix this is done with configure, for Windows we test the
94 // compiler explicitly.
97 #define wxVsnprintf _vsnprintf
100 #ifdef HAVE_VSNPRINTF
101 #define wxVsnprintf vsnprintf
103 #endif // Windows/!Windows
106 // in this case we'll use vsprintf() (which is ANSI and thus should be
107 // always available), but it's unsafe because it doesn't check for buffer
108 // size - so give a warning
109 #define wxVsnprintf(buffer,len,format,argptr) vsprintf(buffer,format, argptr)
111 #if defined(__VISUALC__)
112 #pragma message("Using sprintf() because no snprintf()-like function defined")
113 #elif defined(__GNUG__) && !defined(__UNIX__)
114 #warning "Using sprintf() because no snprintf()-like function defined"
115 #elif defined(__MWERKS__)
116 #warning "Using sprintf() because no snprintf()-like function defined"
118 #endif // no vsnprintf
121 // AIX has vsnprintf, but there's no prototype in the system headers.
122 extern "C" int vsnprintf(char* str
, size_t n
, const char* format
, va_list ap
);
125 // ----------------------------------------------------------------------------
127 // ----------------------------------------------------------------------------
129 #ifdef wxSTD_STRING_COMPATIBILITY
131 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
134 // ATTN: you can _not_ use both of these in the same program!
136 istream
& operator>>(istream
& is
, wxString
& WXUNUSED(str
))
141 streambuf
*sb
= is
.rdbuf();
144 int ch
= sb
->sbumpc ();
146 is
.setstate(ios::eofbit
);
149 else if ( isspace(ch
) ) {
161 if ( str
.length() == 0 )
162 is
.setstate(ios::failbit
);
167 #endif //std::string compatibility
169 // ----------------------------------------------------------------------------
171 // ----------------------------------------------------------------------------
173 // this small class is used to gather statistics for performance tuning
174 //#define WXSTRING_STATISTICS
175 #ifdef WXSTRING_STATISTICS
179 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
181 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
183 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
186 size_t m_nCount
, m_nTotal
;
188 } g_averageLength("allocation size"),
189 g_averageSummandLength("summand length"),
190 g_averageConcatHit("hit probability in concat"),
191 g_averageInitialLength("initial string length");
193 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
195 #define STATISTICS_ADD(av, val)
196 #endif // WXSTRING_STATISTICS
198 // ===========================================================================
199 // wxString class core
200 // ===========================================================================
202 // ---------------------------------------------------------------------------
204 // ---------------------------------------------------------------------------
206 // constructs string of <nLength> copies of character <ch>
207 wxString::wxString(wxChar ch
, size_t nLength
)
212 AllocBuffer(nLength
);
215 // memset only works on char
216 for (size_t n
=0; n
<nLength
; n
++) m_pchData
[n
] = ch
;
218 memset(m_pchData
, ch
, nLength
);
223 // takes nLength elements of psz starting at nPos
224 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
228 wxASSERT( nPos
<= wxStrlen(psz
) );
230 if ( nLength
== wxSTRING_MAXLEN
)
231 nLength
= wxStrlen(psz
+ nPos
);
233 STATISTICS_ADD(InitialLength
, nLength
);
236 // trailing '\0' is written in AllocBuffer()
237 AllocBuffer(nLength
);
238 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
242 #ifdef wxSTD_STRING_COMPATIBILITY
244 // poor man's iterators are "void *" pointers
245 wxString::wxString(const void *pStart
, const void *pEnd
)
247 InitWith((const wxChar
*)pStart
, 0,
248 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
251 #endif //std::string compatibility
255 // from multibyte string
256 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
258 // first get necessary size
259 size_t nLen
= psz
? conv
.MB2WC((wchar_t *) NULL
, psz
, 0) : 0;
261 // nLength is number of *Unicode* characters here!
262 if ((nLen
!= (size_t)-1) && (nLen
> nLength
))
266 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
268 conv
.MB2WC(m_pchData
, psz
, nLen
);
278 wxString::wxString(const wchar_t *pwz
)
280 // first get necessary size
281 size_t nLen
= pwz
? wxWC2MB((char *) NULL
, pwz
, 0) : 0;
284 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
286 wxWC2MB(m_pchData
, pwz
, nLen
);
295 // ---------------------------------------------------------------------------
297 // ---------------------------------------------------------------------------
299 // allocates memory needed to store a C string of length nLen
300 void wxString::AllocBuffer(size_t nLen
)
302 wxASSERT( nLen
> 0 ); //
303 wxASSERT( nLen
<= INT_MAX
-1 ); // max size (enough room for 1 extra)
305 STATISTICS_ADD(Length
, nLen
);
308 // 1) one extra character for '\0' termination
309 // 2) sizeof(wxStringData) for housekeeping info
310 wxStringData
* pData
= (wxStringData
*)
311 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
313 pData
->nDataLength
= nLen
;
314 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
315 m_pchData
= pData
->data(); // data starts after wxStringData
316 m_pchData
[nLen
] = _T('\0');
319 // must be called before changing this string
320 void wxString::CopyBeforeWrite()
322 wxStringData
* pData
= GetStringData();
324 if ( pData
->IsShared() ) {
325 pData
->Unlock(); // memory not freed because shared
326 size_t nLen
= pData
->nDataLength
;
328 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
331 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
334 // must be called before replacing contents of this string
335 void wxString::AllocBeforeWrite(size_t nLen
)
337 wxASSERT( nLen
!= 0 ); // doesn't make any sense
339 // must not share string and must have enough space
340 wxStringData
* pData
= GetStringData();
341 if ( pData
->IsShared() || (nLen
> pData
->nAllocLength
) ) {
342 // can't work with old buffer, get new one
347 // update the string length
348 pData
->nDataLength
= nLen
;
351 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
354 // allocate enough memory for nLen characters
355 void wxString::Alloc(size_t nLen
)
357 wxStringData
*pData
= GetStringData();
358 if ( pData
->nAllocLength
<= nLen
) {
359 if ( pData
->IsEmpty() ) {
362 wxStringData
* pData
= (wxStringData
*)
363 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
365 pData
->nDataLength
= 0;
366 pData
->nAllocLength
= nLen
;
367 m_pchData
= pData
->data(); // data starts after wxStringData
368 m_pchData
[0u] = _T('\0');
370 else if ( pData
->IsShared() ) {
371 pData
->Unlock(); // memory not freed because shared
372 size_t nOldLen
= pData
->nDataLength
;
374 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
379 wxStringData
*p
= (wxStringData
*)
380 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
383 // @@@ what to do on memory error?
387 // it's not important if the pointer changed or not (the check for this
388 // is not faster than assigning to m_pchData in all cases)
389 p
->nAllocLength
= nLen
;
390 m_pchData
= p
->data();
393 //else: we've already got enough
396 // shrink to minimal size (releasing extra memory)
397 void wxString::Shrink()
399 wxStringData
*pData
= GetStringData();
401 // this variable is unused in release build, so avoid the compiler warning by
402 // just not declaring it
406 realloc(pData
, sizeof(wxStringData
) + (pData
->nDataLength
+ 1)*sizeof(wxChar
));
408 wxASSERT( p
!= NULL
); // can't free memory?
409 wxASSERT( p
== pData
); // we're decrementing the size - block shouldn't move!
412 // get the pointer to writable buffer of (at least) nLen bytes
413 wxChar
*wxString::GetWriteBuf(size_t nLen
)
415 AllocBeforeWrite(nLen
);
417 wxASSERT( GetStringData()->nRefs
== 1 );
418 GetStringData()->Validate(FALSE
);
423 // put string back in a reasonable state after GetWriteBuf
424 void wxString::UngetWriteBuf()
426 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
427 GetStringData()->Validate(TRUE
);
430 // ---------------------------------------------------------------------------
432 // ---------------------------------------------------------------------------
434 // all functions are inline in string.h
436 // ---------------------------------------------------------------------------
437 // assignment operators
438 // ---------------------------------------------------------------------------
440 // helper function: does real copy
441 void wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
443 if ( nSrcLen
== 0 ) {
447 AllocBeforeWrite(nSrcLen
);
448 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
449 GetStringData()->nDataLength
= nSrcLen
;
450 m_pchData
[nSrcLen
] = _T('\0');
454 // assigns one string to another
455 wxString
& wxString::operator=(const wxString
& stringSrc
)
457 wxASSERT( stringSrc
.GetStringData()->IsValid() );
459 // don't copy string over itself
460 if ( m_pchData
!= stringSrc
.m_pchData
) {
461 if ( stringSrc
.GetStringData()->IsEmpty() ) {
466 GetStringData()->Unlock();
467 m_pchData
= stringSrc
.m_pchData
;
468 GetStringData()->Lock();
475 // assigns a single character
476 wxString
& wxString::operator=(wxChar ch
)
483 wxString
& wxString::operator=(const wxChar
*psz
)
485 AssignCopy(wxStrlen(psz
), psz
);
491 // same as 'signed char' variant
492 wxString
& wxString::operator=(const unsigned char* psz
)
494 *this = (const char *)psz
;
498 wxString
& wxString::operator=(const wchar_t *pwz
)
507 // ---------------------------------------------------------------------------
508 // string concatenation
509 // ---------------------------------------------------------------------------
511 // add something to this string
512 void wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
514 STATISTICS_ADD(SummandLength
, nSrcLen
);
516 // concatenating an empty string is a NOP
518 wxStringData
*pData
= GetStringData();
519 size_t nLen
= pData
->nDataLength
;
520 size_t nNewLen
= nLen
+ nSrcLen
;
522 // alloc new buffer if current is too small
523 if ( pData
->IsShared() ) {
524 STATISTICS_ADD(ConcatHit
, 0);
526 // we have to allocate another buffer
527 wxStringData
* pOldData
= GetStringData();
528 AllocBuffer(nNewLen
);
529 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
532 else if ( nNewLen
> pData
->nAllocLength
) {
533 STATISTICS_ADD(ConcatHit
, 0);
535 // we have to grow the buffer
539 STATISTICS_ADD(ConcatHit
, 1);
541 // the buffer is already big enough
544 // should be enough space
545 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
547 // fast concatenation - all is done in our buffer
548 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
550 m_pchData
[nNewLen
] = _T('\0'); // put terminating '\0'
551 GetStringData()->nDataLength
= nNewLen
; // and fix the length
553 //else: the string to append was empty
557 * concatenation functions come in 5 flavours:
559 * char + string and string + char
560 * C str + string and string + C str
563 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
565 wxASSERT( string1
.GetStringData()->IsValid() );
566 wxASSERT( string2
.GetStringData()->IsValid() );
568 wxString s
= string1
;
574 wxString
operator+(const wxString
& string
, wxChar ch
)
576 wxASSERT( string
.GetStringData()->IsValid() );
584 wxString
operator+(wxChar ch
, const wxString
& string
)
586 wxASSERT( string
.GetStringData()->IsValid() );
594 wxString
operator+(const wxString
& string
, const wxChar
*psz
)
596 wxASSERT( string
.GetStringData()->IsValid() );
599 s
.Alloc(wxStrlen(psz
) + string
.Len());
606 wxString
operator+(const wxChar
*psz
, const wxString
& string
)
608 wxASSERT( string
.GetStringData()->IsValid() );
611 s
.Alloc(wxStrlen(psz
) + string
.Len());
618 // ===========================================================================
619 // other common string functions
620 // ===========================================================================
622 // ---------------------------------------------------------------------------
623 // simple sub-string extraction
624 // ---------------------------------------------------------------------------
626 // helper function: clone the data attached to this string
627 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
629 if ( nCopyLen
== 0 ) {
633 dest
.AllocBuffer(nCopyLen
);
634 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
638 // extract string of length nCount starting at nFirst
639 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
641 wxStringData
*pData
= GetStringData();
642 size_t nLen
= pData
->nDataLength
;
644 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
645 if ( nCount
== wxSTRING_MAXLEN
)
647 nCount
= nLen
- nFirst
;
650 // out-of-bounds requests return sensible things
651 if ( nFirst
+ nCount
> nLen
)
653 nCount
= nLen
- nFirst
;
658 // AllocCopy() will return empty string
663 AllocCopy(dest
, nCount
, nFirst
);
668 // extract nCount last (rightmost) characters
669 wxString
wxString::Right(size_t nCount
) const
671 if ( nCount
> (size_t)GetStringData()->nDataLength
)
672 nCount
= GetStringData()->nDataLength
;
675 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
679 // get all characters after the last occurence of ch
680 // (returns the whole string if ch not found)
681 wxString
wxString::AfterLast(wxChar ch
) const
684 int iPos
= Find(ch
, TRUE
);
685 if ( iPos
== wxNOT_FOUND
)
688 str
= c_str() + iPos
+ 1;
693 // extract nCount first (leftmost) characters
694 wxString
wxString::Left(size_t nCount
) const
696 if ( nCount
> (size_t)GetStringData()->nDataLength
)
697 nCount
= GetStringData()->nDataLength
;
700 AllocCopy(dest
, nCount
, 0);
704 // get all characters before the first occurence of ch
705 // (returns the whole string if ch not found)
706 wxString
wxString::BeforeFirst(wxChar ch
) const
709 for ( const wxChar
*pc
= m_pchData
; *pc
!= _T('\0') && *pc
!= ch
; pc
++ )
715 /// get all characters before the last occurence of ch
716 /// (returns empty string if ch not found)
717 wxString
wxString::BeforeLast(wxChar ch
) const
720 int iPos
= Find(ch
, TRUE
);
721 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
722 str
= wxString(c_str(), iPos
);
727 /// get all characters after the first occurence of ch
728 /// (returns empty string if ch not found)
729 wxString
wxString::AfterFirst(wxChar ch
) const
733 if ( iPos
!= wxNOT_FOUND
)
734 str
= c_str() + iPos
+ 1;
739 // replace first (or all) occurences of some substring with another one
740 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
742 size_t uiCount
= 0; // count of replacements made
744 size_t uiOldLen
= wxStrlen(szOld
);
747 const wxChar
*pCurrent
= m_pchData
;
748 const wxChar
*pSubstr
;
749 while ( *pCurrent
!= _T('\0') ) {
750 pSubstr
= wxStrstr(pCurrent
, szOld
);
751 if ( pSubstr
== NULL
) {
752 // strTemp is unused if no replacements were made, so avoid the copy
756 strTemp
+= pCurrent
; // copy the rest
757 break; // exit the loop
760 // take chars before match
761 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
763 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
768 if ( !bReplaceAll
) {
769 strTemp
+= pCurrent
; // copy the rest
770 break; // exit the loop
775 // only done if there were replacements, otherwise would have returned above
781 bool wxString::IsAscii() const
783 const wxChar
*s
= (const wxChar
*) *this;
785 if(!isascii(*s
)) return(FALSE
);
791 bool wxString::IsWord() const
793 const wxChar
*s
= (const wxChar
*) *this;
795 if(!wxIsalpha(*s
)) return(FALSE
);
801 bool wxString::IsNumber() const
803 const wxChar
*s
= (const wxChar
*) *this;
805 if(!wxIsdigit(*s
)) return(FALSE
);
811 wxString
wxString::Strip(stripType w
) const
814 if ( w
& leading
) s
.Trim(FALSE
);
815 if ( w
& trailing
) s
.Trim(TRUE
);
819 // ---------------------------------------------------------------------------
821 // ---------------------------------------------------------------------------
823 wxString
& wxString::MakeUpper()
827 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
828 *p
= (wxChar
)wxToupper(*p
);
833 wxString
& wxString::MakeLower()
837 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
838 *p
= (wxChar
)wxTolower(*p
);
843 // ---------------------------------------------------------------------------
844 // trimming and padding
845 // ---------------------------------------------------------------------------
847 // trims spaces (in the sense of isspace) from left or right side
848 wxString
& wxString::Trim(bool bFromRight
)
850 // first check if we're going to modify the string at all
853 (bFromRight
&& wxIsspace(GetChar(Len() - 1))) ||
854 (!bFromRight
&& wxIsspace(GetChar(0u)))
858 // ok, there is at least one space to trim
863 // find last non-space character
864 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
865 while ( wxIsspace(*psz
) && (psz
>= m_pchData
) )
868 // truncate at trailing space start
870 GetStringData()->nDataLength
= psz
- m_pchData
;
874 // find first non-space character
875 const wxChar
*psz
= m_pchData
;
876 while ( wxIsspace(*psz
) )
879 // fix up data and length
880 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
881 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
882 GetStringData()->nDataLength
= nDataLength
;
889 // adds nCount characters chPad to the string from either side
890 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
892 wxString
s(chPad
, nCount
);
905 // truncate the string
906 wxString
& wxString::Truncate(size_t uiLen
)
908 if ( uiLen
< Len() ) {
911 *(m_pchData
+ uiLen
) = _T('\0');
912 GetStringData()->nDataLength
= uiLen
;
914 //else: nothing to do, string is already short enough
919 // ---------------------------------------------------------------------------
920 // finding (return wxNOT_FOUND if not found and index otherwise)
921 // ---------------------------------------------------------------------------
924 int wxString::Find(wxChar ch
, bool bFromEnd
) const
926 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
928 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
931 // find a sub-string (like strstr)
932 int wxString::Find(const wxChar
*pszSub
) const
934 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
936 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
939 // ---------------------------------------------------------------------------
940 // stream-like operators
941 // ---------------------------------------------------------------------------
942 wxString
& wxString::operator<<(int i
)
945 res
.Printf(_T("%d"), i
);
947 return (*this) << res
;
950 wxString
& wxString::operator<<(float f
)
953 res
.Printf(_T("%f"), f
);
955 return (*this) << res
;
958 wxString
& wxString::operator<<(double d
)
961 res
.Printf(_T("%g"), d
);
963 return (*this) << res
;
966 // ---------------------------------------------------------------------------
968 // ---------------------------------------------------------------------------
969 int wxString::Printf(const wxChar
*pszFormat
, ...)
972 va_start(argptr
, pszFormat
);
974 int iLen
= PrintfV(pszFormat
, argptr
);
981 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
983 // static buffer to avoid dynamic memory allocation each time
984 static char s_szScratch
[1024];
986 // protect the static buffer
987 static wxCriticalSection critsect
;
988 wxCriticalSectionLocker
lock(critsect
);
991 #if 1 // the new implementation
994 for (size_t n
= 0; pszFormat
[n
]; n
++)
995 if (pszFormat
[n
] == _T('%')) {
996 static char s_szFlags
[256] = "%";
998 bool adj_left
= FALSE
, in_prec
= FALSE
,
999 prec_dot
= FALSE
, done
= FALSE
;
1001 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1003 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1004 switch (pszFormat
[++n
]) {
1018 s_szFlags
[flagofs
++] = pszFormat
[n
];
1023 s_szFlags
[flagofs
++] = pszFormat
[n
];
1030 // dot will be auto-added to s_szFlags if non-negative number follows
1035 s_szFlags
[flagofs
++] = pszFormat
[n
];
1040 s_szFlags
[flagofs
++] = pszFormat
[n
];
1046 s_szFlags
[flagofs
++] = pszFormat
[n
];
1051 s_szFlags
[flagofs
++] = pszFormat
[n
];
1055 int len
= va_arg(argptr
, int);
1062 adj_left
= !adj_left
;
1063 s_szFlags
[flagofs
++] = '-';
1068 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1071 case _T('1'): case _T('2'): case _T('3'):
1072 case _T('4'): case _T('5'): case _T('6'):
1073 case _T('7'): case _T('8'): case _T('9'):
1077 while ((pszFormat
[n
]>=_T('0')) && (pszFormat
[n
]<=_T('9'))) {
1078 s_szFlags
[flagofs
++] = pszFormat
[n
];
1079 len
= len
*10 + (pszFormat
[n
] - _T('0'));
1082 if (in_prec
) max_width
= len
;
1083 else min_width
= len
;
1084 n
--; // the main loop pre-increments n again
1094 s_szFlags
[flagofs
++] = pszFormat
[n
];
1095 s_szFlags
[flagofs
] = '\0';
1097 int val
= va_arg(argptr
, int);
1098 ::sprintf(s_szScratch
, s_szFlags
, val
);
1100 else if (ilen
== -1) {
1101 short int val
= va_arg(argptr
, short int);
1102 ::sprintf(s_szScratch
, s_szFlags
, val
);
1104 else if (ilen
== 1) {
1105 long int val
= va_arg(argptr
, long int);
1106 ::sprintf(s_szScratch
, s_szFlags
, val
);
1108 else if (ilen
== 2) {
1109 #if SIZEOF_LONG_LONG
1110 long long int val
= va_arg(argptr
, long long int);
1111 ::sprintf(s_szScratch
, s_szFlags
, val
);
1113 long int val
= va_arg(argptr
, long int);
1114 ::sprintf(s_szScratch
, s_szFlags
, val
);
1117 else if (ilen
== 3) {
1118 size_t val
= va_arg(argptr
, size_t);
1119 ::sprintf(s_szScratch
, s_szFlags
, val
);
1121 *this += wxString(s_szScratch
);
1130 s_szFlags
[flagofs
++] = pszFormat
[n
];
1131 s_szFlags
[flagofs
] = '\0';
1133 long double val
= va_arg(argptr
, long double);
1134 ::sprintf(s_szScratch
, s_szFlags
, val
);
1136 double val
= va_arg(argptr
, double);
1137 ::sprintf(s_szScratch
, s_szFlags
, val
);
1139 *this += wxString(s_szScratch
);
1144 void *val
= va_arg(argptr
, void *);
1146 s_szFlags
[flagofs
++] = pszFormat
[n
];
1147 s_szFlags
[flagofs
] = '\0';
1148 ::sprintf(s_szScratch
, s_szFlags
, val
);
1149 *this += wxString(s_szScratch
);
1155 wxChar val
= va_arg(argptr
, int);
1156 // we don't need to honor padding here, do we?
1163 // wx extension: we'll let %hs mean non-Unicode strings
1164 char *val
= va_arg(argptr
, char *);
1166 // ASCII->Unicode constructor handles max_width right
1167 wxString
s(val
, wxConvLibc
, max_width
);
1169 size_t len
= wxSTRING_MAXLEN
;
1171 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1172 } else val
= _T("(null)");
1173 wxString
s(val
, len
);
1175 if (s
.Len() < min_width
)
1176 s
.Pad(min_width
- s
.Len(), _T(' '), adj_left
);
1179 wxChar
*val
= va_arg(argptr
, wxChar
*);
1180 size_t len
= wxSTRING_MAXLEN
;
1182 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1183 } else val
= _T("(null)");
1184 wxString
s(val
, len
);
1185 if (s
.Len() < min_width
)
1186 s
.Pad(min_width
- s
.Len(), _T(' '), adj_left
);
1193 int *val
= va_arg(argptr
, int *);
1196 else if (ilen
== -1) {
1197 short int *val
= va_arg(argptr
, short int *);
1200 else if (ilen
>= 1) {
1201 long int *val
= va_arg(argptr
, long int *);
1207 if (wxIsalpha(pszFormat
[n
]))
1208 // probably some flag not taken care of here yet
1209 s_szFlags
[flagofs
++] = pszFormat
[n
];
1212 *this += _T('%'); // just to pass the glibc tst-printf.c
1220 } else *this += pszFormat
[n
];
1223 // NB: wxVsnprintf() may return either less than the buffer size or -1 if there
1224 // is not enough place depending on implementation
1225 int iLen
= wxVsnprintf(s_szScratch
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
1227 if ( iLen
< (int)WXSIZEOF(s_szScratch
) ) {
1228 buffer
= s_szScratch
;
1231 int size
= WXSIZEOF(s_szScratch
) * 2;
1232 buffer
= (char *)malloc(size
);
1233 while ( buffer
!= NULL
) {
1234 iLen
= wxVsnprintf(buffer
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
1235 if ( iLen
< size
) {
1236 // ok, there was enough space
1240 // still not enough, double it again
1241 buffer
= (char *)realloc(buffer
, size
*= 2);
1253 if ( buffer
!= s_szScratch
)
1260 // ----------------------------------------------------------------------------
1261 // misc other operations
1262 // ----------------------------------------------------------------------------
1263 bool wxString::Matches(const wxChar
*pszMask
) const
1265 // check char by char
1266 const wxChar
*pszTxt
;
1267 for ( pszTxt
= c_str(); *pszMask
!= _T('\0'); pszMask
++, pszTxt
++ ) {
1268 switch ( *pszMask
) {
1270 if ( *pszTxt
== _T('\0') )
1279 // ignore special chars immediately following this one
1280 while ( *pszMask
== _T('*') || *pszMask
== _T('?') )
1283 // if there is nothing more, match
1284 if ( *pszMask
== _T('\0') )
1287 // are there any other metacharacters in the mask?
1289 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, _T("*?"));
1291 if ( pEndMask
!= NULL
) {
1292 // we have to match the string between two metachars
1293 uiLenMask
= pEndMask
- pszMask
;
1296 // we have to match the remainder of the string
1297 uiLenMask
= wxStrlen(pszMask
);
1300 wxString
strToMatch(pszMask
, uiLenMask
);
1301 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1302 if ( pMatch
== NULL
)
1305 // -1 to compensate "++" in the loop
1306 pszTxt
= pMatch
+ uiLenMask
- 1;
1307 pszMask
+= uiLenMask
- 1;
1312 if ( *pszMask
!= *pszTxt
)
1318 // match only if nothing left
1319 return *pszTxt
== _T('\0');
1322 // Count the number of chars
1323 int wxString::Freq(wxChar ch
) const
1327 for (int i
= 0; i
< len
; i
++)
1329 if (GetChar(i
) == ch
)
1335 // convert to upper case, return the copy of the string
1336 wxString
wxString::Upper() const
1337 { wxString
s(*this); return s
.MakeUpper(); }
1339 // convert to lower case, return the copy of the string
1340 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1342 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1345 va_start(argptr
, pszFormat
);
1346 int iLen
= PrintfV(pszFormat
, argptr
);
1351 // ---------------------------------------------------------------------------
1352 // standard C++ library string functions
1353 // ---------------------------------------------------------------------------
1354 #ifdef wxSTD_STRING_COMPATIBILITY
1356 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1358 wxASSERT( str
.GetStringData()->IsValid() );
1359 wxASSERT( nPos
<= Len() );
1361 if ( !str
.IsEmpty() ) {
1363 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1364 wxStrncpy(pc
, c_str(), nPos
);
1365 wxStrcpy(pc
+ nPos
, str
);
1366 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1367 strTmp
.UngetWriteBuf();
1374 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1376 wxASSERT( str
.GetStringData()->IsValid() );
1377 wxASSERT( nStart
<= Len() );
1379 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1381 return p
== NULL
? npos
: p
- c_str();
1384 // VC++ 1.5 can't cope with the default argument in the header.
1385 #if !defined(__VISUALC__) || defined(__WIN32__)
1386 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1388 return find(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1392 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1393 #if !defined(__BORLANDC__)
1394 size_t wxString::find(wxChar ch
, size_t nStart
) const
1396 wxASSERT( nStart
<= Len() );
1398 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1400 return p
== NULL
? npos
: p
- c_str();
1404 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1406 wxASSERT( str
.GetStringData()->IsValid() );
1407 wxASSERT( nStart
<= Len() );
1409 // # could be quicker than that
1410 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1411 while ( p
>= c_str() + str
.Len() ) {
1412 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1413 return p
- str
.Len() - c_str();
1420 // VC++ 1.5 can't cope with the default argument in the header.
1421 #if !defined(__VISUALC__) || defined(__WIN32__)
1422 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1424 return rfind(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1427 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1429 wxASSERT( nStart
<= Len() );
1431 const wxChar
*p
= wxStrrchr(c_str() + nStart
, ch
);
1433 return p
== NULL
? npos
: p
- c_str();
1437 wxString
wxString::substr(size_t nStart
, size_t nLen
) const
1439 // npos means 'take all'
1443 wxASSERT( nStart
+ nLen
<= Len() );
1445 return wxString(c_str() + nStart
, nLen
== npos
? 0 : nLen
);
1448 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1450 wxString
strTmp(c_str(), nStart
);
1451 if ( nLen
!= npos
) {
1452 wxASSERT( nStart
+ nLen
<= Len() );
1454 strTmp
.append(c_str() + nStart
+ nLen
);
1461 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1463 wxASSERT( nStart
+ nLen
<= wxStrlen(sz
) );
1467 strTmp
.append(c_str(), nStart
);
1469 strTmp
.append(c_str() + nStart
+ nLen
);
1475 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1477 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1480 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1481 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1483 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1486 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1487 const wxChar
* sz
, size_t nCount
)
1489 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1492 #endif //std::string compatibility
1494 // ============================================================================
1496 // ============================================================================
1498 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1499 #define ARRAY_MAXSIZE_INCREMENT 4096
1500 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1501 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1504 #define STRING(p) ((wxString *)(&(p)))
1507 wxArrayString::wxArrayString()
1511 m_pItems
= (wxChar
**) NULL
;
1515 wxArrayString::wxArrayString(const wxArrayString
& src
)
1519 m_pItems
= (wxChar
**) NULL
;
1524 // assignment operator
1525 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1530 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1531 Alloc(src
.m_nCount
);
1533 // we can't just copy the pointers here because otherwise we would share
1534 // the strings with another array
1535 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1538 if ( m_nCount
!= 0 )
1539 memcpy(m_pItems
, src
.m_pItems
, m_nCount
*sizeof(wxChar
*));
1545 void wxArrayString::Grow()
1547 // only do it if no more place
1548 if( m_nCount
== m_nSize
) {
1549 if( m_nSize
== 0 ) {
1550 // was empty, alloc some memory
1551 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1552 m_pItems
= new wxChar
*[m_nSize
];
1555 // otherwise when it's called for the first time, nIncrement would be 0
1556 // and the array would never be expanded
1557 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE
!= 0 );
1559 // add 50% but not too much
1560 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1561 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1562 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1563 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1564 m_nSize
+= nIncrement
;
1565 wxChar
**pNew
= new wxChar
*[m_nSize
];
1567 // copy data to new location
1568 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1570 // delete old memory (but do not release the strings!)
1571 wxDELETEA(m_pItems
);
1578 void wxArrayString::Free()
1580 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1581 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1585 // deletes all the strings from the list
1586 void wxArrayString::Empty()
1593 // as Empty, but also frees memory
1594 void wxArrayString::Clear()
1601 wxDELETEA(m_pItems
);
1605 wxArrayString::~wxArrayString()
1609 wxDELETEA(m_pItems
);
1612 // pre-allocates memory (frees the previous data!)
1613 void wxArrayString::Alloc(size_t nSize
)
1615 wxASSERT( nSize
> 0 );
1617 // only if old buffer was not big enough
1618 if ( nSize
> m_nSize
) {
1620 wxDELETEA(m_pItems
);
1621 m_pItems
= new wxChar
*[nSize
];
1628 // minimizes the memory usage by freeing unused memory
1629 void wxArrayString::Shrink()
1631 // only do it if we have some memory to free
1632 if( m_nCount
< m_nSize
) {
1633 // allocates exactly as much memory as we need
1634 wxChar
**pNew
= new wxChar
*[m_nCount
];
1636 // copy data to new location
1637 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1643 // searches the array for an item (forward or backwards)
1644 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
1647 if ( m_nCount
> 0 ) {
1648 size_t ui
= m_nCount
;
1650 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1657 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1658 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1666 // add item at the end
1667 void wxArrayString::Add(const wxString
& str
)
1669 wxASSERT( str
.GetStringData()->IsValid() );
1673 // the string data must not be deleted!
1674 str
.GetStringData()->Lock();
1675 m_pItems
[m_nCount
++] = (wxChar
*)str
.c_str();
1678 // add item at the given position
1679 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
1681 wxASSERT( str
.GetStringData()->IsValid() );
1683 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Insert") );
1687 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
1688 (m_nCount
- nIndex
)*sizeof(wxChar
*));
1690 str
.GetStringData()->Lock();
1691 m_pItems
[nIndex
] = (wxChar
*)str
.c_str();
1696 // removes item from array (by index)
1697 void wxArrayString::Remove(size_t nIndex
)
1699 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Remove") );
1702 Item(nIndex
).GetStringData()->Unlock();
1704 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
1705 (m_nCount
- nIndex
- 1)*sizeof(wxChar
*));
1709 // removes item from array (by value)
1710 void wxArrayString::Remove(const wxChar
*sz
)
1712 int iIndex
= Index(sz
);
1714 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
1715 _("removing inexistent element in wxArrayString::Remove") );
1720 // ----------------------------------------------------------------------------
1722 // ----------------------------------------------------------------------------
1724 // we can only sort one array at a time with the quick-sort based
1727 // need a critical section to protect access to gs_compareFunction and
1728 // gs_sortAscending variables
1729 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
1731 // call this before the value of the global sort vars is changed/after
1732 // you're finished with them
1733 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
1734 gs_critsectStringSort = new wxCriticalSection; \
1735 gs_critsectStringSort->Enter()
1736 #define END_SORT() gs_critsectStringSort->Leave(); \
1737 delete gs_critsectStringSort; \
1738 gs_critsectStringSort = NULL
1740 #define START_SORT()
1742 #endif // wxUSE_THREADS
1744 // function to use for string comparaison
1745 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
1747 // if we don't use the compare function, this flag tells us if we sort the
1748 // array in ascending or descending order
1749 static bool gs_sortAscending
= TRUE
;
1751 // function which is called by quick sort
1752 static int wxStringCompareFunction(const void *first
, const void *second
)
1754 wxString
*strFirst
= (wxString
*)first
;
1755 wxString
*strSecond
= (wxString
*)second
;
1757 if ( gs_compareFunction
) {
1758 return gs_compareFunction(*strFirst
, *strSecond
);
1761 // maybe we should use wxStrcoll
1762 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
1764 return gs_sortAscending
? result
: -result
;
1768 // sort array elements using passed comparaison function
1769 void wxArrayString::Sort(CompareFunction compareFunction
)
1773 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1774 gs_compareFunction
= compareFunction
;
1781 void wxArrayString::Sort(bool reverseOrder
)
1785 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1786 gs_sortAscending
= !reverseOrder
;
1793 void wxArrayString::DoSort()
1795 // just sort the pointers using qsort() - of course it only works because
1796 // wxString() *is* a pointer to its data
1797 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
1800 // ============================================================================
1802 // ============================================================================
1804 WXDLLEXPORT_DATA(wxMBConv
*) wxConvCurrent
= &wxConvLibc
;
1806 WXDLLEXPORT_DATA(wxMBConv
) wxConvLibc
, wxConvFile
;
1811 // ----------------------------------------------------------------------------
1812 // standard libc conversion
1813 // ----------------------------------------------------------------------------
1815 WXDLLEXPORT_DATA(wxMBConv
) wxConvLibc
;
1817 size_t wxMBConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1819 return wxMB2WC(buf
, psz
, n
);
1822 size_t wxMBConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1824 return wxWC2MB(buf
, psz
, n
);
1827 // ----------------------------------------------------------------------------
1828 // standard file conversion
1829 // ----------------------------------------------------------------------------
1831 WXDLLEXPORT_DATA(wxMBConvFile
) wxConvFile
;
1833 // just use the libc conversion for now
1834 size_t wxMBConvFile::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1836 return wxMB2WC(buf
, psz
, n
);
1839 size_t wxMBConvFile::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1841 return wxWC2MB(buf
, psz
, n
);
1844 // ----------------------------------------------------------------------------
1845 // standard gdk conversion
1846 // ----------------------------------------------------------------------------
1849 WXDLLEXPORT_DATA(wxMBConvGdk
) wxConvGdk
;
1851 #include <gdk/gdk.h>
1853 size_t wxMBConvGdk::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1856 return gdk_mbstowcs((GdkWChar
*)buf
, psz
, n
);
1858 GdkWChar
*nbuf
= new GdkWChar
[n
=strlen(psz
)];
1859 size_t len
= gdk_mbstowcs(nbuf
, psz
, n
);
1865 size_t wxMBConvGdk::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1867 char *mbstr
= gdk_wcstombs((GdkWChar
*)psz
);
1868 size_t len
= mbstr
? strlen(mbstr
) : 0;
1870 if (len
> n
) len
= n
;
1871 memcpy(buf
, psz
, len
);
1872 if (len
< n
) buf
[len
] = 0;
1878 // ----------------------------------------------------------------------------
1880 // ----------------------------------------------------------------------------
1882 WXDLLEXPORT_DATA(wxMBConvUTF7
) wxConvUTF7
;
1885 static char utf7_setD
[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1886 "abcdefghijklmnopqrstuvwxyz"
1887 "0123456789'(),-./:?";
1888 static char utf7_setO
[]="!\"#$%&*;<=>@[]^_`{|}";
1889 static char utf7_setB
[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1890 "abcdefghijklmnopqrstuvwxyz"
1894 // TODO: write actual implementations of UTF-7 here
1895 size_t wxMBConvUTF7::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1900 size_t wxMBConvUTF7::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1905 // ----------------------------------------------------------------------------
1907 // ----------------------------------------------------------------------------
1909 WXDLLEXPORT_DATA(wxMBConvUTF8
) wxConvUTF8
;
1911 static unsigned long utf8_max
[]={0x7f,0x7ff,0xffff,0x1fffff,0x3ffffff,0x7fffffff,0xffffffff};
1913 size_t wxMBConvUTF8::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1917 while (*psz
&& ((!buf
) || (len
<n
))) {
1918 unsigned char cc
=*psz
++, fc
=cc
;
1920 for (cnt
=0; fc
&0x80; cnt
++) fc
<<=1;
1928 // invalid UTF-8 sequence
1931 unsigned ocnt
=cnt
-1;
1932 unsigned long res
=cc
&(0x3f>>cnt
);
1935 if ((cc
&0xC0)!=0x80) {
1936 // invalid UTF-8 sequence
1939 res
=(res
<<6)|(cc
&0x3f);
1941 if (res
<=utf8_max
[ocnt
]) {
1942 // illegal UTF-8 encoding
1945 if (buf
) *buf
++=res
;
1950 if (buf
&& (len
<n
)) *buf
= 0;
1954 size_t wxMBConvUTF8::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1958 while (*psz
&& ((!buf
) || (len
<n
))) {
1959 unsigned long cc
=(*psz
++)&0x7fffffff;
1961 for (cnt
=0; cc
>utf8_max
[cnt
]; cnt
++);
1969 *buf
++=(-128>>cnt
)|((cc
>>(cnt
*6))&(0x3f>>cnt
));
1971 *buf
++=0x80|((cc
>>(cnt
*6))&0x3f);
1975 if (buf
&& (len
<n
)) *buf
= 0;
1979 // ----------------------------------------------------------------------------
1980 // specified character set
1981 // ----------------------------------------------------------------------------
1983 class wxCharacterSet
1986 wxArrayString names
;
1991 #include "wx/dynarray.h"
1992 #include "wx/filefn.h"
1993 #include "wx/textfile.h"
1994 #include "wx/tokenzr.h"
1995 #include "wx/utils.h"
1998 WX_DECLARE_OBJARRAY(wxCharacterSet
, wxCSArray
);
1999 #include "wx/arrimpl.cpp"
2000 WX_DEFINE_OBJARRAY(wxCSArray
);
2002 static wxCSArray wxCharsets
;
2004 static void wxLoadCharacterSets(void)
2006 static bool already_loaded
= FALSE
;
2008 if (already_loaded
) return;
2010 already_loaded
= TRUE
;
2011 #if defined(__UNIX__)
2012 // search through files in /usr/share/i18n/charmaps
2014 for (fname
= ::wxFindFirstFile(_T("/usr/share/i18n/charmaps/*"));
2016 fname
= ::wxFindNextFile()) {
2017 wxTextFile
cmap(fname
);
2019 wxCharacterSet
*cset
= new wxCharacterSet
;
2020 wxString comchar
,escchar
;
2021 bool in_charset
= FALSE
;
2023 // wxFprintf(stderr,_T("Loaded: %s\n"),fname.c_str());
2026 for (line
= cmap
.GetFirstLine();
2028 line
= cmap
.GetNextLine()) {
2029 // wxFprintf(stderr,_T("line contents: %s\n"),line.c_str());
2030 wxStringTokenizer
token(line
);
2031 wxString cmd
= token
.GetNextToken();
2032 if (cmd
== comchar
) {
2033 if (token
.GetNextToken() == _T("alias"))
2034 cset
->names
.Add(token
.GetNextToken());
2036 else if (cmd
== _T("<code_set_name>"))
2037 cset
->names
.Add(token
.GetNextToken());
2038 else if (cmd
== _T("<comment_char>"))
2039 comchar
= token
.GetNextToken();
2040 else if (cmd
== _T("<escape_char>"))
2041 escchar
= token
.GetNextToken();
2042 else if (cmd
== _T("<mb_cur_min>")) {
2044 cset
= (wxCharacterSet
*) NULL
;
2045 break; // we don't support multibyte charsets ourselves (yet)
2047 else if (cmd
== _T("CHARMAP")) {
2048 cset
->data
= (wchar_t *)calloc(256, sizeof(wchar_t));
2051 else if (cmd
== _T("END")) {
2052 if (token
.GetNextToken() == _T("CHARMAP"))
2055 else if (in_charset
) {
2056 // format: <NUL> /x00 <U0000> NULL (NUL)
2057 // <A> /x41 <U0041> LATIN CAPITAL LETTER A
2058 wxString hex
= token
.GetNextToken();
2059 // skip whitespace (why doesn't wxStringTokenizer do this?)
2060 while (wxIsEmpty(hex
) && token
.HasMoreTokens()) hex
= token
.GetNextToken();
2061 wxString uni
= token
.GetNextToken();
2062 // skip whitespace again
2063 while (wxIsEmpty(uni
) && token
.HasMoreTokens()) uni
= token
.GetNextToken();
2065 if ((hex
.Len() > 2) && (hex
.GetChar(0) == escchar
) && (hex
.GetChar(1) == _T('x')) &&
2066 (uni
.Left(2) == _T("<U"))) {
2067 hex
.MakeUpper(); uni
.MakeUpper();
2068 int pos
= ::wxHexToDec(hex
.Mid(2,2));
2070 unsigned long uni1
= ::wxHexToDec(uni
.Mid(2,2));
2071 unsigned long uni2
= ::wxHexToDec(uni
.Mid(4,2));
2072 cset
->data
[pos
] = (uni1
<< 16) | uni2
;
2073 // wxFprintf(stderr,_T("char %02x mapped to %04x (%c)\n"),pos,cset->data[pos],cset->data[pos]);
2079 cset
->names
.Shrink();
2080 wxCharsets
.Add(cset
);
2085 wxCharsets
.Shrink();
2088 static wxCharacterSet
*wxFindCharacterSet(const wxChar
*charset
)
2090 if (!charset
) return (wxCharacterSet
*)NULL
;
2091 wxLoadCharacterSets();
2092 for (size_t n
=0; n
<wxCharsets
.GetCount(); n
++)
2093 if (wxCharsets
[n
].names
.Index(charset
) != wxNOT_FOUND
)
2094 return &(wxCharsets
[n
]);
2095 return (wxCharacterSet
*)NULL
;
2098 WXDLLEXPORT_DATA(wxCSConv
) wxConvLocal((const wxChar
*)NULL
);
2100 wxCSConv::wxCSConv(const wxChar
*charset
)
2102 m_name
= (wxChar
*) NULL
;
2103 m_cset
= (wxCharacterSet
*) NULL
;
2108 wxCSConv::~wxCSConv()
2110 if (m_name
) free(m_name
);
2113 void wxCSConv::SetName(const wxChar
*charset
)
2117 // first, convert the character set name to standard form
2119 if (wxString(charset
,3).CmpNoCase(_T("ISO")) == 0) {
2120 // make sure it's represented in the standard form: ISO_8859-1
2121 codeset
= _T("ISO_");
2123 if ((*charset
== _T('-')) || (*charset
== _T('_'))) charset
++;
2124 if (wxStrlen(charset
)>4) {
2125 if (wxString(charset
,4) == _T("8859")) {
2126 codeset
<< _T("8859-");
2127 if (*charset
== _T('-')) charset
++;
2132 codeset
.MakeUpper();
2133 m_name
= wxStrdup(codeset
.c_str());
2139 void wxCSConv::LoadNow()
2141 // wxPrintf(_T("Conversion request\n"));
2145 wxChar
*lang
= wxGetenv(_T("LANG"));
2146 wxChar
*dot
= lang
? wxStrchr(lang
, _T('.')) : (wxChar
*)NULL
;
2147 if (dot
) SetName(dot
+1);
2150 m_cset
= wxFindCharacterSet(m_name
);
2155 size_t wxCSConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2157 ((wxCSConv
*)this)->LoadNow(); // discard constness
2160 for (size_t c
=0; c
<n
; c
++)
2161 buf
[c
] = m_cset
->data
[(unsigned char)(psz
[c
])];
2164 for (size_t c
=0; c
<n
; c
++)
2165 buf
[c
] = (unsigned char)(psz
[c
]);
2172 size_t wxCSConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
2174 ((wxCSConv
*)this)->LoadNow(); // discard constness
2177 for (size_t c
=0; c
<n
; c
++) {
2179 for (n
=0; (n
<256) && (m_cset
->data
[n
] != psz
[c
]); n
++);
2180 buf
[c
] = (n
>0xff) ? '?' : n
;
2184 for (size_t c
=0; c
<n
; c
++)
2185 buf
[c
] = (psz
[c
]>0xff) ? '?' : psz
[c
];
2192 #endif//wxUSE_WCHAR_T