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
);
279 wxString::wxString(const wchar_t *pwz
)
281 // first get necessary size
282 size_t nLen
= pwz
? wxWC2MB((char *) NULL
, pwz
, 0) : 0;
285 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
287 wxWC2MB(m_pchData
, pwz
, nLen
);
297 // ---------------------------------------------------------------------------
299 // ---------------------------------------------------------------------------
301 // allocates memory needed to store a C string of length nLen
302 void wxString::AllocBuffer(size_t nLen
)
304 wxASSERT( nLen
> 0 ); //
305 wxASSERT( nLen
<= INT_MAX
-1 ); // max size (enough room for 1 extra)
307 STATISTICS_ADD(Length
, nLen
);
310 // 1) one extra character for '\0' termination
311 // 2) sizeof(wxStringData) for housekeeping info
312 wxStringData
* pData
= (wxStringData
*)
313 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
315 pData
->nDataLength
= nLen
;
316 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
317 m_pchData
= pData
->data(); // data starts after wxStringData
318 m_pchData
[nLen
] = _T('\0');
321 // must be called before changing this string
322 void wxString::CopyBeforeWrite()
324 wxStringData
* pData
= GetStringData();
326 if ( pData
->IsShared() ) {
327 pData
->Unlock(); // memory not freed because shared
328 size_t nLen
= pData
->nDataLength
;
330 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
333 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
336 // must be called before replacing contents of this string
337 void wxString::AllocBeforeWrite(size_t nLen
)
339 wxASSERT( nLen
!= 0 ); // doesn't make any sense
341 // must not share string and must have enough space
342 wxStringData
* pData
= GetStringData();
343 if ( pData
->IsShared() || (nLen
> pData
->nAllocLength
) ) {
344 // can't work with old buffer, get new one
349 // update the string length
350 pData
->nDataLength
= nLen
;
353 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
356 // allocate enough memory for nLen characters
357 void wxString::Alloc(size_t nLen
)
359 wxStringData
*pData
= GetStringData();
360 if ( pData
->nAllocLength
<= nLen
) {
361 if ( pData
->IsEmpty() ) {
364 wxStringData
* pData
= (wxStringData
*)
365 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
367 pData
->nDataLength
= 0;
368 pData
->nAllocLength
= nLen
;
369 m_pchData
= pData
->data(); // data starts after wxStringData
370 m_pchData
[0u] = _T('\0');
372 else if ( pData
->IsShared() ) {
373 pData
->Unlock(); // memory not freed because shared
374 size_t nOldLen
= pData
->nDataLength
;
376 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
381 wxStringData
*p
= (wxStringData
*)
382 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
385 // @@@ what to do on memory error?
389 // it's not important if the pointer changed or not (the check for this
390 // is not faster than assigning to m_pchData in all cases)
391 p
->nAllocLength
= nLen
;
392 m_pchData
= p
->data();
395 //else: we've already got enough
398 // shrink to minimal size (releasing extra memory)
399 void wxString::Shrink()
401 wxStringData
*pData
= GetStringData();
403 // this variable is unused in release build, so avoid the compiler warning by
404 // just not declaring it
408 realloc(pData
, sizeof(wxStringData
) + (pData
->nDataLength
+ 1)*sizeof(wxChar
));
410 wxASSERT( p
!= NULL
); // can't free memory?
411 wxASSERT( p
== pData
); // we're decrementing the size - block shouldn't move!
414 // get the pointer to writable buffer of (at least) nLen bytes
415 wxChar
*wxString::GetWriteBuf(size_t nLen
)
417 AllocBeforeWrite(nLen
);
419 wxASSERT( GetStringData()->nRefs
== 1 );
420 GetStringData()->Validate(FALSE
);
425 // put string back in a reasonable state after GetWriteBuf
426 void wxString::UngetWriteBuf()
428 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
429 GetStringData()->Validate(TRUE
);
432 // ---------------------------------------------------------------------------
434 // ---------------------------------------------------------------------------
436 // all functions are inline in string.h
438 // ---------------------------------------------------------------------------
439 // assignment operators
440 // ---------------------------------------------------------------------------
442 // helper function: does real copy
443 void wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
445 if ( nSrcLen
== 0 ) {
449 AllocBeforeWrite(nSrcLen
);
450 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
451 GetStringData()->nDataLength
= nSrcLen
;
452 m_pchData
[nSrcLen
] = _T('\0');
456 // assigns one string to another
457 wxString
& wxString::operator=(const wxString
& stringSrc
)
459 wxASSERT( stringSrc
.GetStringData()->IsValid() );
461 // don't copy string over itself
462 if ( m_pchData
!= stringSrc
.m_pchData
) {
463 if ( stringSrc
.GetStringData()->IsEmpty() ) {
468 GetStringData()->Unlock();
469 m_pchData
= stringSrc
.m_pchData
;
470 GetStringData()->Lock();
477 // assigns a single character
478 wxString
& wxString::operator=(wxChar ch
)
485 wxString
& wxString::operator=(const wxChar
*psz
)
487 AssignCopy(wxStrlen(psz
), psz
);
493 // same as 'signed char' variant
494 wxString
& wxString::operator=(const unsigned char* psz
)
496 *this = (const char *)psz
;
501 wxString
& wxString::operator=(const wchar_t *pwz
)
511 // ---------------------------------------------------------------------------
512 // string concatenation
513 // ---------------------------------------------------------------------------
515 // add something to this string
516 void wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
518 STATISTICS_ADD(SummandLength
, nSrcLen
);
520 // concatenating an empty string is a NOP
522 wxStringData
*pData
= GetStringData();
523 size_t nLen
= pData
->nDataLength
;
524 size_t nNewLen
= nLen
+ nSrcLen
;
526 // alloc new buffer if current is too small
527 if ( pData
->IsShared() ) {
528 STATISTICS_ADD(ConcatHit
, 0);
530 // we have to allocate another buffer
531 wxStringData
* pOldData
= GetStringData();
532 AllocBuffer(nNewLen
);
533 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
536 else if ( nNewLen
> pData
->nAllocLength
) {
537 STATISTICS_ADD(ConcatHit
, 0);
539 // we have to grow the buffer
543 STATISTICS_ADD(ConcatHit
, 1);
545 // the buffer is already big enough
548 // should be enough space
549 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
551 // fast concatenation - all is done in our buffer
552 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
554 m_pchData
[nNewLen
] = _T('\0'); // put terminating '\0'
555 GetStringData()->nDataLength
= nNewLen
; // and fix the length
557 //else: the string to append was empty
561 * concatenation functions come in 5 flavours:
563 * char + string and string + char
564 * C str + string and string + C str
567 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
569 wxASSERT( string1
.GetStringData()->IsValid() );
570 wxASSERT( string2
.GetStringData()->IsValid() );
572 wxString s
= string1
;
578 wxString
operator+(const wxString
& string
, wxChar ch
)
580 wxASSERT( string
.GetStringData()->IsValid() );
588 wxString
operator+(wxChar ch
, const wxString
& string
)
590 wxASSERT( string
.GetStringData()->IsValid() );
598 wxString
operator+(const wxString
& string
, const wxChar
*psz
)
600 wxASSERT( string
.GetStringData()->IsValid() );
603 s
.Alloc(wxStrlen(psz
) + string
.Len());
610 wxString
operator+(const wxChar
*psz
, const wxString
& string
)
612 wxASSERT( string
.GetStringData()->IsValid() );
615 s
.Alloc(wxStrlen(psz
) + string
.Len());
622 // ===========================================================================
623 // other common string functions
624 // ===========================================================================
626 // ---------------------------------------------------------------------------
627 // simple sub-string extraction
628 // ---------------------------------------------------------------------------
630 // helper function: clone the data attached to this string
631 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
633 if ( nCopyLen
== 0 ) {
637 dest
.AllocBuffer(nCopyLen
);
638 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
642 // extract string of length nCount starting at nFirst
643 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
645 wxStringData
*pData
= GetStringData();
646 size_t nLen
= pData
->nDataLength
;
648 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
649 if ( nCount
== wxSTRING_MAXLEN
)
651 nCount
= nLen
- nFirst
;
654 // out-of-bounds requests return sensible things
655 if ( nFirst
+ nCount
> nLen
)
657 nCount
= nLen
- nFirst
;
662 // AllocCopy() will return empty string
667 AllocCopy(dest
, nCount
, nFirst
);
672 // extract nCount last (rightmost) characters
673 wxString
wxString::Right(size_t nCount
) const
675 if ( nCount
> (size_t)GetStringData()->nDataLength
)
676 nCount
= GetStringData()->nDataLength
;
679 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
683 // get all characters after the last occurence of ch
684 // (returns the whole string if ch not found)
685 wxString
wxString::AfterLast(wxChar ch
) const
688 int iPos
= Find(ch
, TRUE
);
689 if ( iPos
== wxNOT_FOUND
)
692 str
= c_str() + iPos
+ 1;
697 // extract nCount first (leftmost) characters
698 wxString
wxString::Left(size_t nCount
) const
700 if ( nCount
> (size_t)GetStringData()->nDataLength
)
701 nCount
= GetStringData()->nDataLength
;
704 AllocCopy(dest
, nCount
, 0);
708 // get all characters before the first occurence of ch
709 // (returns the whole string if ch not found)
710 wxString
wxString::BeforeFirst(wxChar ch
) const
713 for ( const wxChar
*pc
= m_pchData
; *pc
!= _T('\0') && *pc
!= ch
; pc
++ )
719 /// get all characters before the last occurence of ch
720 /// (returns empty string if ch not found)
721 wxString
wxString::BeforeLast(wxChar ch
) const
724 int iPos
= Find(ch
, TRUE
);
725 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
726 str
= wxString(c_str(), iPos
);
731 /// get all characters after the first occurence of ch
732 /// (returns empty string if ch not found)
733 wxString
wxString::AfterFirst(wxChar ch
) const
737 if ( iPos
!= wxNOT_FOUND
)
738 str
= c_str() + iPos
+ 1;
743 // replace first (or all) occurences of some substring with another one
744 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
746 size_t uiCount
= 0; // count of replacements made
748 size_t uiOldLen
= wxStrlen(szOld
);
751 const wxChar
*pCurrent
= m_pchData
;
752 const wxChar
*pSubstr
;
753 while ( *pCurrent
!= _T('\0') ) {
754 pSubstr
= wxStrstr(pCurrent
, szOld
);
755 if ( pSubstr
== NULL
) {
756 // strTemp is unused if no replacements were made, so avoid the copy
760 strTemp
+= pCurrent
; // copy the rest
761 break; // exit the loop
764 // take chars before match
765 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
767 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
772 if ( !bReplaceAll
) {
773 strTemp
+= pCurrent
; // copy the rest
774 break; // exit the loop
779 // only done if there were replacements, otherwise would have returned above
785 bool wxString::IsAscii() const
787 const wxChar
*s
= (const wxChar
*) *this;
789 if(!isascii(*s
)) return(FALSE
);
795 bool wxString::IsWord() const
797 const wxChar
*s
= (const wxChar
*) *this;
799 if(!wxIsalpha(*s
)) return(FALSE
);
805 bool wxString::IsNumber() const
807 const wxChar
*s
= (const wxChar
*) *this;
809 if(!wxIsdigit(*s
)) return(FALSE
);
815 wxString
wxString::Strip(stripType w
) const
818 if ( w
& leading
) s
.Trim(FALSE
);
819 if ( w
& trailing
) s
.Trim(TRUE
);
823 // ---------------------------------------------------------------------------
825 // ---------------------------------------------------------------------------
827 wxString
& wxString::MakeUpper()
831 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
832 *p
= (wxChar
)wxToupper(*p
);
837 wxString
& wxString::MakeLower()
841 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
842 *p
= (wxChar
)wxTolower(*p
);
847 // ---------------------------------------------------------------------------
848 // trimming and padding
849 // ---------------------------------------------------------------------------
851 // trims spaces (in the sense of isspace) from left or right side
852 wxString
& wxString::Trim(bool bFromRight
)
854 // first check if we're going to modify the string at all
857 (bFromRight
&& wxIsspace(GetChar(Len() - 1))) ||
858 (!bFromRight
&& wxIsspace(GetChar(0u)))
862 // ok, there is at least one space to trim
867 // find last non-space character
868 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
869 while ( wxIsspace(*psz
) && (psz
>= m_pchData
) )
872 // truncate at trailing space start
874 GetStringData()->nDataLength
= psz
- m_pchData
;
878 // find first non-space character
879 const wxChar
*psz
= m_pchData
;
880 while ( wxIsspace(*psz
) )
883 // fix up data and length
884 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
885 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
886 GetStringData()->nDataLength
= nDataLength
;
893 // adds nCount characters chPad to the string from either side
894 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
896 wxString
s(chPad
, nCount
);
909 // truncate the string
910 wxString
& wxString::Truncate(size_t uiLen
)
912 if ( uiLen
< Len() ) {
915 *(m_pchData
+ uiLen
) = _T('\0');
916 GetStringData()->nDataLength
= uiLen
;
918 //else: nothing to do, string is already short enough
923 // ---------------------------------------------------------------------------
924 // finding (return wxNOT_FOUND if not found and index otherwise)
925 // ---------------------------------------------------------------------------
928 int wxString::Find(wxChar ch
, bool bFromEnd
) const
930 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
932 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
935 // find a sub-string (like strstr)
936 int wxString::Find(const wxChar
*pszSub
) const
938 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
940 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
943 // ---------------------------------------------------------------------------
944 // stream-like operators
945 // ---------------------------------------------------------------------------
946 wxString
& wxString::operator<<(int i
)
949 res
.Printf(_T("%d"), i
);
951 return (*this) << res
;
954 wxString
& wxString::operator<<(float f
)
957 res
.Printf(_T("%f"), f
);
959 return (*this) << res
;
962 wxString
& wxString::operator<<(double d
)
965 res
.Printf(_T("%g"), d
);
967 return (*this) << res
;
970 // ---------------------------------------------------------------------------
972 // ---------------------------------------------------------------------------
973 int wxString::Printf(const wxChar
*pszFormat
, ...)
976 va_start(argptr
, pszFormat
);
978 int iLen
= PrintfV(pszFormat
, argptr
);
985 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
987 // static buffer to avoid dynamic memory allocation each time
988 static char s_szScratch
[1024];
990 // protect the static buffer
991 static wxCriticalSection critsect
;
992 wxCriticalSectionLocker
lock(critsect
);
995 #if 1 // the new implementation
998 for (size_t n
= 0; pszFormat
[n
]; n
++)
999 if (pszFormat
[n
] == _T('%')) {
1000 static char s_szFlags
[256] = "%";
1002 bool adj_left
= FALSE
, in_prec
= FALSE
,
1003 prec_dot
= FALSE
, done
= FALSE
;
1005 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1007 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1008 switch (pszFormat
[++n
]) {
1022 s_szFlags
[flagofs
++] = pszFormat
[n
];
1027 s_szFlags
[flagofs
++] = pszFormat
[n
];
1034 // dot will be auto-added to s_szFlags if non-negative number follows
1039 s_szFlags
[flagofs
++] = pszFormat
[n
];
1044 s_szFlags
[flagofs
++] = pszFormat
[n
];
1050 s_szFlags
[flagofs
++] = pszFormat
[n
];
1055 s_szFlags
[flagofs
++] = pszFormat
[n
];
1059 int len
= va_arg(argptr
, int);
1066 adj_left
= !adj_left
;
1067 s_szFlags
[flagofs
++] = '-';
1072 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1075 case _T('1'): case _T('2'): case _T('3'):
1076 case _T('4'): case _T('5'): case _T('6'):
1077 case _T('7'): case _T('8'): case _T('9'):
1081 while ((pszFormat
[n
]>=_T('0')) && (pszFormat
[n
]<=_T('9'))) {
1082 s_szFlags
[flagofs
++] = pszFormat
[n
];
1083 len
= len
*10 + (pszFormat
[n
] - _T('0'));
1086 if (in_prec
) max_width
= len
;
1087 else min_width
= len
;
1088 n
--; // the main loop pre-increments n again
1098 s_szFlags
[flagofs
++] = pszFormat
[n
];
1099 s_szFlags
[flagofs
] = '\0';
1101 int val
= va_arg(argptr
, int);
1102 ::sprintf(s_szScratch
, s_szFlags
, val
);
1104 else if (ilen
== -1) {
1105 short int val
= va_arg(argptr
, short int);
1106 ::sprintf(s_szScratch
, s_szFlags
, val
);
1108 else if (ilen
== 1) {
1109 long int val
= va_arg(argptr
, long int);
1110 ::sprintf(s_szScratch
, s_szFlags
, val
);
1112 else if (ilen
== 2) {
1113 #if SIZEOF_LONG_LONG
1114 long long int val
= va_arg(argptr
, long long int);
1115 ::sprintf(s_szScratch
, s_szFlags
, val
);
1117 long int val
= va_arg(argptr
, long int);
1118 ::sprintf(s_szScratch
, s_szFlags
, val
);
1121 else if (ilen
== 3) {
1122 size_t val
= va_arg(argptr
, size_t);
1123 ::sprintf(s_szScratch
, s_szFlags
, val
);
1125 *this += wxString(s_szScratch
);
1134 s_szFlags
[flagofs
++] = pszFormat
[n
];
1135 s_szFlags
[flagofs
] = '\0';
1137 long double val
= va_arg(argptr
, long double);
1138 ::sprintf(s_szScratch
, s_szFlags
, val
);
1140 double val
= va_arg(argptr
, double);
1141 ::sprintf(s_szScratch
, s_szFlags
, val
);
1143 *this += wxString(s_szScratch
);
1148 void *val
= va_arg(argptr
, void *);
1150 s_szFlags
[flagofs
++] = pszFormat
[n
];
1151 s_szFlags
[flagofs
] = '\0';
1152 ::sprintf(s_szScratch
, s_szFlags
, val
);
1153 *this += wxString(s_szScratch
);
1159 wxChar val
= va_arg(argptr
, int);
1160 // we don't need to honor padding here, do we?
1167 // wx extension: we'll let %hs mean non-Unicode strings
1168 char *val
= va_arg(argptr
, char *);
1170 // ASCII->Unicode constructor handles max_width right
1171 wxString
s(val
, wxConvLibc
, max_width
);
1173 size_t len
= wxSTRING_MAXLEN
;
1175 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1176 } else val
= _T("(null)");
1177 wxString
s(val
, len
);
1179 if (s
.Len() < min_width
)
1180 s
.Pad(min_width
- s
.Len(), _T(' '), adj_left
);
1183 wxChar
*val
= va_arg(argptr
, wxChar
*);
1184 size_t len
= wxSTRING_MAXLEN
;
1186 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1187 } else val
= _T("(null)");
1188 wxString
s(val
, len
);
1189 if (s
.Len() < min_width
)
1190 s
.Pad(min_width
- s
.Len(), _T(' '), adj_left
);
1197 int *val
= va_arg(argptr
, int *);
1200 else if (ilen
== -1) {
1201 short int *val
= va_arg(argptr
, short int *);
1204 else if (ilen
>= 1) {
1205 long int *val
= va_arg(argptr
, long int *);
1211 if (wxIsalpha(pszFormat
[n
]))
1212 // probably some flag not taken care of here yet
1213 s_szFlags
[flagofs
++] = pszFormat
[n
];
1216 *this += _T('%'); // just to pass the glibc tst-printf.c
1224 } else *this += pszFormat
[n
];
1227 // NB: wxVsnprintf() may return either less than the buffer size or -1 if there
1228 // is not enough place depending on implementation
1229 int iLen
= wxVsnprintf(s_szScratch
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
1231 if ( iLen
< (int)WXSIZEOF(s_szScratch
) ) {
1232 buffer
= s_szScratch
;
1235 int size
= WXSIZEOF(s_szScratch
) * 2;
1236 buffer
= (char *)malloc(size
);
1237 while ( buffer
!= NULL
) {
1238 iLen
= wxVsnprintf(buffer
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
1239 if ( iLen
< size
) {
1240 // ok, there was enough space
1244 // still not enough, double it again
1245 buffer
= (char *)realloc(buffer
, size
*= 2);
1257 if ( buffer
!= s_szScratch
)
1264 // ----------------------------------------------------------------------------
1265 // misc other operations
1266 // ----------------------------------------------------------------------------
1267 bool wxString::Matches(const wxChar
*pszMask
) const
1269 // check char by char
1270 const wxChar
*pszTxt
;
1271 for ( pszTxt
= c_str(); *pszMask
!= _T('\0'); pszMask
++, pszTxt
++ ) {
1272 switch ( *pszMask
) {
1274 if ( *pszTxt
== _T('\0') )
1283 // ignore special chars immediately following this one
1284 while ( *pszMask
== _T('*') || *pszMask
== _T('?') )
1287 // if there is nothing more, match
1288 if ( *pszMask
== _T('\0') )
1291 // are there any other metacharacters in the mask?
1293 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, _T("*?"));
1295 if ( pEndMask
!= NULL
) {
1296 // we have to match the string between two metachars
1297 uiLenMask
= pEndMask
- pszMask
;
1300 // we have to match the remainder of the string
1301 uiLenMask
= wxStrlen(pszMask
);
1304 wxString
strToMatch(pszMask
, uiLenMask
);
1305 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1306 if ( pMatch
== NULL
)
1309 // -1 to compensate "++" in the loop
1310 pszTxt
= pMatch
+ uiLenMask
- 1;
1311 pszMask
+= uiLenMask
- 1;
1316 if ( *pszMask
!= *pszTxt
)
1322 // match only if nothing left
1323 return *pszTxt
== _T('\0');
1326 // Count the number of chars
1327 int wxString::Freq(wxChar ch
) const
1331 for (int i
= 0; i
< len
; i
++)
1333 if (GetChar(i
) == ch
)
1339 // convert to upper case, return the copy of the string
1340 wxString
wxString::Upper() const
1341 { wxString
s(*this); return s
.MakeUpper(); }
1343 // convert to lower case, return the copy of the string
1344 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1346 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1349 va_start(argptr
, pszFormat
);
1350 int iLen
= PrintfV(pszFormat
, argptr
);
1355 // ---------------------------------------------------------------------------
1356 // standard C++ library string functions
1357 // ---------------------------------------------------------------------------
1358 #ifdef wxSTD_STRING_COMPATIBILITY
1360 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1362 wxASSERT( str
.GetStringData()->IsValid() );
1363 wxASSERT( nPos
<= Len() );
1365 if ( !str
.IsEmpty() ) {
1367 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1368 wxStrncpy(pc
, c_str(), nPos
);
1369 wxStrcpy(pc
+ nPos
, str
);
1370 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1371 strTmp
.UngetWriteBuf();
1378 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1380 wxASSERT( str
.GetStringData()->IsValid() );
1381 wxASSERT( nStart
<= Len() );
1383 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1385 return p
== NULL
? npos
: p
- c_str();
1388 // VC++ 1.5 can't cope with the default argument in the header.
1389 #if !defined(__VISUALC__) || defined(__WIN32__)
1390 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1392 return find(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1396 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1397 #if !defined(__BORLANDC__)
1398 size_t wxString::find(wxChar ch
, size_t nStart
) const
1400 wxASSERT( nStart
<= Len() );
1402 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1404 return p
== NULL
? npos
: p
- c_str();
1408 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1410 wxASSERT( str
.GetStringData()->IsValid() );
1411 wxASSERT( nStart
<= Len() );
1413 // TODO could be made much quicker than that
1414 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1415 while ( p
>= c_str() + str
.Len() ) {
1416 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1417 return p
- str
.Len() - c_str();
1424 // VC++ 1.5 can't cope with the default argument in the header.
1425 #if !defined(__VISUALC__) || defined(__WIN32__)
1426 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1428 return rfind(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1431 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1433 if ( nStart
== npos
)
1439 wxASSERT( nStart
<= Len() );
1442 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1447 size_t result
= p
- c_str();
1448 return ( result
> nStart
) ? npos
: result
;
1452 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1454 const wxChar
*start
= c_str() + nStart
;
1455 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1457 return firstOf
- start
;
1462 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1464 if ( nStart
== npos
)
1470 wxASSERT( nStart
<= Len() );
1473 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1475 if ( wxStrchr(sz
, *p
) )
1482 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1484 if ( nStart
== npos
)
1490 wxASSERT( nStart
<= Len() );
1493 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1494 if ( nAccept
>= length() - nStart
)
1500 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1502 wxASSERT( nStart
<= Len() );
1504 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1513 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1515 if ( nStart
== npos
)
1521 wxASSERT( nStart
<= Len() );
1524 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1526 if ( !wxStrchr(sz
, *p
) )
1533 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1535 if ( nStart
== npos
)
1541 wxASSERT( nStart
<= Len() );
1544 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1553 wxString
wxString::substr(size_t nStart
, size_t nLen
) const
1555 // npos means 'take all'
1559 wxASSERT( nStart
+ nLen
<= Len() );
1561 return wxString(c_str() + nStart
, nLen
== npos
? 0 : nLen
);
1564 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1566 wxString
strTmp(c_str(), nStart
);
1567 if ( nLen
!= npos
) {
1568 wxASSERT( nStart
+ nLen
<= Len() );
1570 strTmp
.append(c_str() + nStart
+ nLen
);
1577 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1579 wxASSERT( nStart
+ nLen
<= wxStrlen(sz
) );
1583 strTmp
.append(c_str(), nStart
);
1585 strTmp
.append(c_str() + nStart
+ nLen
);
1591 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1593 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1596 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1597 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1599 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1602 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1603 const wxChar
* sz
, size_t nCount
)
1605 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1608 #endif //std::string compatibility
1610 // ============================================================================
1612 // ============================================================================
1614 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1615 #define ARRAY_MAXSIZE_INCREMENT 4096
1616 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1617 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1620 #define STRING(p) ((wxString *)(&(p)))
1623 wxArrayString::wxArrayString()
1627 m_pItems
= (wxChar
**) NULL
;
1631 wxArrayString::wxArrayString(const wxArrayString
& src
)
1635 m_pItems
= (wxChar
**) NULL
;
1640 // assignment operator
1641 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1646 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1647 Alloc(src
.m_nCount
);
1649 // we can't just copy the pointers here because otherwise we would share
1650 // the strings with another array
1651 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1654 if ( m_nCount
!= 0 )
1655 memcpy(m_pItems
, src
.m_pItems
, m_nCount
*sizeof(wxChar
*));
1661 void wxArrayString::Grow()
1663 // only do it if no more place
1664 if( m_nCount
== m_nSize
) {
1665 if( m_nSize
== 0 ) {
1666 // was empty, alloc some memory
1667 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1668 m_pItems
= new wxChar
*[m_nSize
];
1671 // otherwise when it's called for the first time, nIncrement would be 0
1672 // and the array would never be expanded
1673 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE
!= 0 );
1675 // add 50% but not too much
1676 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1677 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1678 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1679 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1680 m_nSize
+= nIncrement
;
1681 wxChar
**pNew
= new wxChar
*[m_nSize
];
1683 // copy data to new location
1684 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1686 // delete old memory (but do not release the strings!)
1687 wxDELETEA(m_pItems
);
1694 void wxArrayString::Free()
1696 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1697 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1701 // deletes all the strings from the list
1702 void wxArrayString::Empty()
1709 // as Empty, but also frees memory
1710 void wxArrayString::Clear()
1717 wxDELETEA(m_pItems
);
1721 wxArrayString::~wxArrayString()
1725 wxDELETEA(m_pItems
);
1728 // pre-allocates memory (frees the previous data!)
1729 void wxArrayString::Alloc(size_t nSize
)
1731 wxASSERT( nSize
> 0 );
1733 // only if old buffer was not big enough
1734 if ( nSize
> m_nSize
) {
1736 wxDELETEA(m_pItems
);
1737 m_pItems
= new wxChar
*[nSize
];
1744 // minimizes the memory usage by freeing unused memory
1745 void wxArrayString::Shrink()
1747 // only do it if we have some memory to free
1748 if( m_nCount
< m_nSize
) {
1749 // allocates exactly as much memory as we need
1750 wxChar
**pNew
= new wxChar
*[m_nCount
];
1752 // copy data to new location
1753 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1759 // searches the array for an item (forward or backwards)
1760 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
1763 if ( m_nCount
> 0 ) {
1764 size_t ui
= m_nCount
;
1766 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1773 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1774 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1782 // add item at the end
1783 void wxArrayString::Add(const wxString
& str
)
1785 wxASSERT( str
.GetStringData()->IsValid() );
1789 // the string data must not be deleted!
1790 str
.GetStringData()->Lock();
1791 m_pItems
[m_nCount
++] = (wxChar
*)str
.c_str();
1794 // add item at the given position
1795 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
1797 wxASSERT( str
.GetStringData()->IsValid() );
1799 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Insert") );
1803 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
1804 (m_nCount
- nIndex
)*sizeof(wxChar
*));
1806 str
.GetStringData()->Lock();
1807 m_pItems
[nIndex
] = (wxChar
*)str
.c_str();
1812 // removes item from array (by index)
1813 void wxArrayString::Remove(size_t nIndex
)
1815 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Remove") );
1818 Item(nIndex
).GetStringData()->Unlock();
1820 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
1821 (m_nCount
- nIndex
- 1)*sizeof(wxChar
*));
1825 // removes item from array (by value)
1826 void wxArrayString::Remove(const wxChar
*sz
)
1828 int iIndex
= Index(sz
);
1830 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
1831 _("removing inexistent element in wxArrayString::Remove") );
1836 // ----------------------------------------------------------------------------
1838 // ----------------------------------------------------------------------------
1840 // we can only sort one array at a time with the quick-sort based
1843 // need a critical section to protect access to gs_compareFunction and
1844 // gs_sortAscending variables
1845 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
1847 // call this before the value of the global sort vars is changed/after
1848 // you're finished with them
1849 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
1850 gs_critsectStringSort = new wxCriticalSection; \
1851 gs_critsectStringSort->Enter()
1852 #define END_SORT() gs_critsectStringSort->Leave(); \
1853 delete gs_critsectStringSort; \
1854 gs_critsectStringSort = NULL
1856 #define START_SORT()
1858 #endif // wxUSE_THREADS
1860 // function to use for string comparaison
1861 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
1863 // if we don't use the compare function, this flag tells us if we sort the
1864 // array in ascending or descending order
1865 static bool gs_sortAscending
= TRUE
;
1867 // function which is called by quick sort
1868 static int wxStringCompareFunction(const void *first
, const void *second
)
1870 wxString
*strFirst
= (wxString
*)first
;
1871 wxString
*strSecond
= (wxString
*)second
;
1873 if ( gs_compareFunction
) {
1874 return gs_compareFunction(*strFirst
, *strSecond
);
1877 // maybe we should use wxStrcoll
1878 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
1880 return gs_sortAscending
? result
: -result
;
1884 // sort array elements using passed comparaison function
1885 void wxArrayString::Sort(CompareFunction compareFunction
)
1889 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1890 gs_compareFunction
= compareFunction
;
1897 void wxArrayString::Sort(bool reverseOrder
)
1901 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1902 gs_sortAscending
= !reverseOrder
;
1909 void wxArrayString::DoSort()
1911 // just sort the pointers using qsort() - of course it only works because
1912 // wxString() *is* a pointer to its data
1913 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
1916 // ============================================================================
1918 // ============================================================================
1920 WXDLLEXPORT_DATA(wxMBConv
*) wxConvCurrent
= &wxConvLibc
;
1922 WXDLLEXPORT_DATA(wxMBConv
) wxConvLibc
, wxConvFile
;
1927 // ----------------------------------------------------------------------------
1928 // standard libc conversion
1929 // ----------------------------------------------------------------------------
1931 WXDLLEXPORT_DATA(wxMBConv
) wxConvLibc
;
1933 size_t wxMBConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1935 return wxMB2WC(buf
, psz
, n
);
1938 size_t wxMBConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1940 return wxWC2MB(buf
, psz
, n
);
1943 // ----------------------------------------------------------------------------
1944 // standard file conversion
1945 // ----------------------------------------------------------------------------
1947 WXDLLEXPORT_DATA(wxMBConvFile
) wxConvFile
;
1949 // just use the libc conversion for now
1950 size_t wxMBConvFile::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1952 return wxMB2WC(buf
, psz
, n
);
1955 size_t wxMBConvFile::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1957 return wxWC2MB(buf
, psz
, n
);
1960 // ----------------------------------------------------------------------------
1961 // standard gdk conversion
1962 // ----------------------------------------------------------------------------
1965 WXDLLEXPORT_DATA(wxMBConvGdk
) wxConvGdk
;
1967 #include <gdk/gdk.h>
1969 size_t wxMBConvGdk::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1972 return gdk_mbstowcs((GdkWChar
*)buf
, psz
, n
);
1974 GdkWChar
*nbuf
= new GdkWChar
[n
=strlen(psz
)];
1975 size_t len
= gdk_mbstowcs(nbuf
, psz
, n
);
1981 size_t wxMBConvGdk::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1983 char *mbstr
= gdk_wcstombs((GdkWChar
*)psz
);
1984 size_t len
= mbstr
? strlen(mbstr
) : 0;
1986 if (len
> n
) len
= n
;
1987 memcpy(buf
, psz
, len
);
1988 if (len
< n
) buf
[len
] = 0;
1994 // ----------------------------------------------------------------------------
1996 // ----------------------------------------------------------------------------
1998 WXDLLEXPORT_DATA(wxMBConvUTF7
) wxConvUTF7
;
2001 static char utf7_setD
[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2002 "abcdefghijklmnopqrstuvwxyz"
2003 "0123456789'(),-./:?";
2004 static char utf7_setO
[]="!\"#$%&*;<=>@[]^_`{|}";
2005 static char utf7_setB
[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2006 "abcdefghijklmnopqrstuvwxyz"
2010 // TODO: write actual implementations of UTF-7 here
2011 size_t wxMBConvUTF7::MB2WC(wchar_t * WXUNUSED(buf
),
2012 const char * WXUNUSED(psz
),
2013 size_t WXUNUSED(n
)) const
2018 size_t wxMBConvUTF7::WC2MB(char * WXUNUSED(buf
),
2019 const wchar_t * WXUNUSED(psz
),
2020 size_t WXUNUSED(n
)) const
2025 // ----------------------------------------------------------------------------
2027 // ----------------------------------------------------------------------------
2029 WXDLLEXPORT_DATA(wxMBConvUTF8
) wxConvUTF8
;
2031 static unsigned long utf8_max
[]={0x7f,0x7ff,0xffff,0x1fffff,0x3ffffff,0x7fffffff,0xffffffff};
2033 size_t wxMBConvUTF8::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2037 while (*psz
&& ((!buf
) || (len
<n
))) {
2038 unsigned char cc
=*psz
++, fc
=cc
;
2040 for (cnt
=0; fc
&0x80; cnt
++) fc
<<=1;
2048 // invalid UTF-8 sequence
2051 unsigned ocnt
=cnt
-1;
2052 unsigned long res
=cc
&(0x3f>>cnt
);
2055 if ((cc
&0xC0)!=0x80) {
2056 // invalid UTF-8 sequence
2059 res
=(res
<<6)|(cc
&0x3f);
2061 if (res
<=utf8_max
[ocnt
]) {
2062 // illegal UTF-8 encoding
2065 if (buf
) *buf
++=res
;
2070 if (buf
&& (len
<n
)) *buf
= 0;
2074 size_t wxMBConvUTF8::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
2078 while (*psz
&& ((!buf
) || (len
<n
))) {
2079 unsigned long cc
=(*psz
++)&0x7fffffff;
2081 for (cnt
=0; cc
>utf8_max
[cnt
]; cnt
++);
2089 *buf
++=(-128>>cnt
)|((cc
>>(cnt
*6))&(0x3f>>cnt
));
2091 *buf
++=0x80|((cc
>>(cnt
*6))&0x3f);
2095 if (buf
&& (len
<n
)) *buf
= 0;
2099 // ----------------------------------------------------------------------------
2100 // specified character set
2101 // ----------------------------------------------------------------------------
2103 class wxCharacterSet
2106 wxArrayString names
;
2111 #include "wx/dynarray.h"
2112 #include "wx/filefn.h"
2113 #include "wx/textfile.h"
2114 #include "wx/tokenzr.h"
2115 #include "wx/utils.h"
2118 WX_DECLARE_OBJARRAY(wxCharacterSet
, wxCSArray
);
2119 #include "wx/arrimpl.cpp"
2120 WX_DEFINE_OBJARRAY(wxCSArray
);
2122 static wxCSArray wxCharsets
;
2124 static void wxLoadCharacterSets(void)
2126 static bool already_loaded
= FALSE
;
2128 if (already_loaded
) return;
2130 already_loaded
= TRUE
;
2131 #if defined(__UNIX__) && wxUSE_TEXTFILE
2132 // search through files in /usr/share/i18n/charmaps
2134 for (fname
= ::wxFindFirstFile(_T("/usr/share/i18n/charmaps/*"));
2136 fname
= ::wxFindNextFile()) {
2137 wxTextFile
cmap(fname
);
2139 wxCharacterSet
*cset
= new wxCharacterSet
;
2140 wxString comchar
,escchar
;
2141 bool in_charset
= FALSE
;
2143 // wxFprintf(stderr,_T("Loaded: %s\n"),fname.c_str());
2146 for (line
= cmap
.GetFirstLine();
2148 line
= cmap
.GetNextLine()) {
2149 // wxFprintf(stderr,_T("line contents: %s\n"),line.c_str());
2150 wxStringTokenizer
token(line
);
2151 wxString cmd
= token
.GetNextToken();
2152 if (cmd
== comchar
) {
2153 if (token
.GetNextToken() == _T("alias"))
2154 cset
->names
.Add(token
.GetNextToken());
2156 else if (cmd
== _T("<code_set_name>"))
2157 cset
->names
.Add(token
.GetNextToken());
2158 else if (cmd
== _T("<comment_char>"))
2159 comchar
= token
.GetNextToken();
2160 else if (cmd
== _T("<escape_char>"))
2161 escchar
= token
.GetNextToken();
2162 else if (cmd
== _T("<mb_cur_min>")) {
2164 cset
= (wxCharacterSet
*) NULL
;
2165 break; // we don't support multibyte charsets ourselves (yet)
2167 else if (cmd
== _T("CHARMAP")) {
2168 cset
->data
= (wchar_t *)calloc(256, sizeof(wchar_t));
2171 else if (cmd
== _T("END")) {
2172 if (token
.GetNextToken() == _T("CHARMAP"))
2175 else if (in_charset
) {
2176 // format: <NUL> /x00 <U0000> NULL (NUL)
2177 // <A> /x41 <U0041> LATIN CAPITAL LETTER A
2178 wxString hex
= token
.GetNextToken();
2179 // skip whitespace (why doesn't wxStringTokenizer do this?)
2180 while (wxIsEmpty(hex
) && token
.HasMoreTokens()) hex
= token
.GetNextToken();
2181 wxString uni
= token
.GetNextToken();
2182 // skip whitespace again
2183 while (wxIsEmpty(uni
) && token
.HasMoreTokens()) uni
= token
.GetNextToken();
2185 if ((hex
.Len() > 2) && (hex
.GetChar(0) == escchar
) && (hex
.GetChar(1) == _T('x')) &&
2186 (uni
.Left(2) == _T("<U"))) {
2187 hex
.MakeUpper(); uni
.MakeUpper();
2188 int pos
= ::wxHexToDec(hex
.Mid(2,2));
2190 unsigned long uni1
= ::wxHexToDec(uni
.Mid(2,2));
2191 unsigned long uni2
= ::wxHexToDec(uni
.Mid(4,2));
2192 cset
->data
[pos
] = (uni1
<< 16) | uni2
;
2193 // wxFprintf(stderr,_T("char %02x mapped to %04x (%c)\n"),pos,cset->data[pos],cset->data[pos]);
2199 cset
->names
.Shrink();
2200 wxCharsets
.Add(cset
);
2205 wxCharsets
.Shrink();
2208 static wxCharacterSet
*wxFindCharacterSet(const wxChar
*charset
)
2210 if (!charset
) return (wxCharacterSet
*)NULL
;
2211 wxLoadCharacterSets();
2212 for (size_t n
=0; n
<wxCharsets
.GetCount(); n
++)
2213 if (wxCharsets
[n
].names
.Index(charset
) != wxNOT_FOUND
)
2214 return &(wxCharsets
[n
]);
2215 return (wxCharacterSet
*)NULL
;
2218 WXDLLEXPORT_DATA(wxCSConv
) wxConvLocal((const wxChar
*)NULL
);
2220 wxCSConv::wxCSConv(const wxChar
*charset
)
2222 m_name
= (wxChar
*) NULL
;
2223 m_cset
= (wxCharacterSet
*) NULL
;
2228 wxCSConv::~wxCSConv()
2230 if (m_name
) free(m_name
);
2233 void wxCSConv::SetName(const wxChar
*charset
)
2237 // first, convert the character set name to standard form
2239 if (wxString(charset
,3).CmpNoCase(_T("ISO")) == 0) {
2240 // make sure it's represented in the standard form: ISO_8859-1
2241 codeset
= _T("ISO_");
2243 if ((*charset
== _T('-')) || (*charset
== _T('_'))) charset
++;
2244 if (wxStrlen(charset
)>4) {
2245 if (wxString(charset
,4) == _T("8859")) {
2246 codeset
<< _T("8859-");
2247 if (*charset
== _T('-')) charset
++;
2252 codeset
.MakeUpper();
2253 m_name
= wxStrdup(codeset
.c_str());
2259 void wxCSConv::LoadNow()
2261 // wxPrintf(_T("Conversion request\n"));
2265 wxChar
*lang
= wxGetenv(_T("LANG"));
2266 wxChar
*dot
= lang
? wxStrchr(lang
, _T('.')) : (wxChar
*)NULL
;
2267 if (dot
) SetName(dot
+1);
2270 m_cset
= wxFindCharacterSet(m_name
);
2275 size_t wxCSConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2277 ((wxCSConv
*)this)->LoadNow(); // discard constness
2280 for (size_t c
=0; c
<n
; c
++)
2281 buf
[c
] = m_cset
->data
[(unsigned char)(psz
[c
])];
2284 for (size_t c
=0; c
<n
; c
++)
2285 buf
[c
] = (unsigned char)(psz
[c
]);
2292 size_t wxCSConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
2294 ((wxCSConv
*)this)->LoadNow(); // discard constness
2297 for (size_t c
=0; c
<n
; c
++) {
2299 for (n
=0; (n
<256) && (m_cset
->data
[n
] != psz
[c
]); n
++);
2300 buf
[c
] = (n
>0xff) ? '?' : n
;
2304 for (size_t c
=0; c
<n
; c
++)
2305 buf
[c
] = (psz
[c
]>0xff) ? '?' : psz
[c
];
2312 #endif//wxUSE_WCHAR_T
2315 const wxWCharBuffer
wxMBConv::cMB2WC(const char *psz
) const
2318 size_t nLen
= MB2WC((wchar_t *) NULL
, psz
, 0);
2319 wxWCharBuffer
buf(nLen
);
2320 MB2WC(WCSTRINGCAST buf
, psz
, nLen
);
2322 } else return wxWCharBuffer((wchar_t *) NULL
);
2325 const wxCharBuffer
wxMBConv::cWC2MB(const wchar_t *psz
) const
2328 size_t nLen
= WC2MB((char *) NULL
, psz
, 0);
2329 wxCharBuffer
buf(nLen
);
2330 WC2MB(MBSTRINGCAST buf
, psz
, nLen
);
2332 } else return wxCharBuffer((char *) NULL
);
2335 #endif//wxUSE_WCHAR_T