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
260 size_t nLen
= conv
.MB2WC((wchar_t *) NULL
, psz
, 0);
262 // nLength is number of *Unicode* characters here!
269 conv
.MB2WC(m_pchData
, psz
, nLen
);
279 wxString::wxString(const wchar_t *pwz
)
281 // first get necessary size
283 size_t nLen
= wxWC2MB((char *) NULL
, pwz
, 0);
288 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
;
500 wxString
& wxString::operator=(const wchar_t *pwz
)
509 // ---------------------------------------------------------------------------
510 // string concatenation
511 // ---------------------------------------------------------------------------
513 // add something to this string
514 void wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
516 STATISTICS_ADD(SummandLength
, nSrcLen
);
518 // concatenating an empty string is a NOP
520 wxStringData
*pData
= GetStringData();
521 size_t nLen
= pData
->nDataLength
;
522 size_t nNewLen
= nLen
+ nSrcLen
;
524 // alloc new buffer if current is too small
525 if ( pData
->IsShared() ) {
526 STATISTICS_ADD(ConcatHit
, 0);
528 // we have to allocate another buffer
529 wxStringData
* pOldData
= GetStringData();
530 AllocBuffer(nNewLen
);
531 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
534 else if ( nNewLen
> pData
->nAllocLength
) {
535 STATISTICS_ADD(ConcatHit
, 0);
537 // we have to grow the buffer
541 STATISTICS_ADD(ConcatHit
, 1);
543 // the buffer is already big enough
546 // should be enough space
547 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
549 // fast concatenation - all is done in our buffer
550 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
552 m_pchData
[nNewLen
] = _T('\0'); // put terminating '\0'
553 GetStringData()->nDataLength
= nNewLen
; // and fix the length
555 //else: the string to append was empty
559 * concatenation functions come in 5 flavours:
561 * char + string and string + char
562 * C str + string and string + C str
565 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
567 wxASSERT( string1
.GetStringData()->IsValid() );
568 wxASSERT( string2
.GetStringData()->IsValid() );
570 wxString s
= string1
;
576 wxString
operator+(const wxString
& string
, wxChar ch
)
578 wxASSERT( string
.GetStringData()->IsValid() );
586 wxString
operator+(wxChar ch
, const wxString
& string
)
588 wxASSERT( string
.GetStringData()->IsValid() );
596 wxString
operator+(const wxString
& string
, const wxChar
*psz
)
598 wxASSERT( string
.GetStringData()->IsValid() );
601 s
.Alloc(wxStrlen(psz
) + string
.Len());
608 wxString
operator+(const wxChar
*psz
, const wxString
& string
)
610 wxASSERT( string
.GetStringData()->IsValid() );
613 s
.Alloc(wxStrlen(psz
) + string
.Len());
620 // ===========================================================================
621 // other common string functions
622 // ===========================================================================
624 // ---------------------------------------------------------------------------
625 // simple sub-string extraction
626 // ---------------------------------------------------------------------------
628 // helper function: clone the data attached to this string
629 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
631 if ( nCopyLen
== 0 ) {
635 dest
.AllocBuffer(nCopyLen
);
636 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
640 // extract string of length nCount starting at nFirst
641 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
643 wxStringData
*pData
= GetStringData();
644 size_t nLen
= pData
->nDataLength
;
646 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
647 if ( nCount
== wxSTRING_MAXLEN
)
649 nCount
= nLen
- nFirst
;
652 // out-of-bounds requests return sensible things
653 if ( nFirst
+ nCount
> nLen
)
655 nCount
= nLen
- nFirst
;
660 // AllocCopy() will return empty string
665 AllocCopy(dest
, nCount
, nFirst
);
670 // extract nCount last (rightmost) characters
671 wxString
wxString::Right(size_t nCount
) const
673 if ( nCount
> (size_t)GetStringData()->nDataLength
)
674 nCount
= GetStringData()->nDataLength
;
677 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
681 // get all characters after the last occurence of ch
682 // (returns the whole string if ch not found)
683 wxString
wxString::AfterLast(wxChar ch
) const
686 int iPos
= Find(ch
, TRUE
);
687 if ( iPos
== wxNOT_FOUND
)
690 str
= c_str() + iPos
+ 1;
695 // extract nCount first (leftmost) characters
696 wxString
wxString::Left(size_t nCount
) const
698 if ( nCount
> (size_t)GetStringData()->nDataLength
)
699 nCount
= GetStringData()->nDataLength
;
702 AllocCopy(dest
, nCount
, 0);
706 // get all characters before the first occurence of ch
707 // (returns the whole string if ch not found)
708 wxString
wxString::BeforeFirst(wxChar ch
) const
711 for ( const wxChar
*pc
= m_pchData
; *pc
!= _T('\0') && *pc
!= ch
; pc
++ )
717 /// get all characters before the last occurence of ch
718 /// (returns empty string if ch not found)
719 wxString
wxString::BeforeLast(wxChar ch
) const
722 int iPos
= Find(ch
, TRUE
);
723 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
724 str
= wxString(c_str(), iPos
);
729 /// get all characters after the first occurence of ch
730 /// (returns empty string if ch not found)
731 wxString
wxString::AfterFirst(wxChar ch
) const
735 if ( iPos
!= wxNOT_FOUND
)
736 str
= c_str() + iPos
+ 1;
741 // replace first (or all) occurences of some substring with another one
742 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
744 size_t uiCount
= 0; // count of replacements made
746 size_t uiOldLen
= wxStrlen(szOld
);
749 const wxChar
*pCurrent
= m_pchData
;
750 const wxChar
*pSubstr
;
751 while ( *pCurrent
!= _T('\0') ) {
752 pSubstr
= wxStrstr(pCurrent
, szOld
);
753 if ( pSubstr
== NULL
) {
754 // strTemp is unused if no replacements were made, so avoid the copy
758 strTemp
+= pCurrent
; // copy the rest
759 break; // exit the loop
762 // take chars before match
763 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
765 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
770 if ( !bReplaceAll
) {
771 strTemp
+= pCurrent
; // copy the rest
772 break; // exit the loop
777 // only done if there were replacements, otherwise would have returned above
783 bool wxString::IsAscii() const
785 const wxChar
*s
= (const wxChar
*) *this;
787 if(!isascii(*s
)) return(FALSE
);
793 bool wxString::IsWord() const
795 const wxChar
*s
= (const wxChar
*) *this;
797 if(!wxIsalpha(*s
)) return(FALSE
);
803 bool wxString::IsNumber() const
805 const wxChar
*s
= (const wxChar
*) *this;
807 if(!wxIsdigit(*s
)) return(FALSE
);
813 wxString
wxString::Strip(stripType w
) const
816 if ( w
& leading
) s
.Trim(FALSE
);
817 if ( w
& trailing
) s
.Trim(TRUE
);
821 // ---------------------------------------------------------------------------
823 // ---------------------------------------------------------------------------
825 wxString
& wxString::MakeUpper()
829 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
830 *p
= (wxChar
)wxToupper(*p
);
835 wxString
& wxString::MakeLower()
839 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
840 *p
= (wxChar
)wxTolower(*p
);
845 // ---------------------------------------------------------------------------
846 // trimming and padding
847 // ---------------------------------------------------------------------------
849 // trims spaces (in the sense of isspace) from left or right side
850 wxString
& wxString::Trim(bool bFromRight
)
852 // first check if we're going to modify the string at all
855 (bFromRight
&& wxIsspace(GetChar(Len() - 1))) ||
856 (!bFromRight
&& wxIsspace(GetChar(0u)))
860 // ok, there is at least one space to trim
865 // find last non-space character
866 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
867 while ( wxIsspace(*psz
) && (psz
>= m_pchData
) )
870 // truncate at trailing space start
872 GetStringData()->nDataLength
= psz
- m_pchData
;
876 // find first non-space character
877 const wxChar
*psz
= m_pchData
;
878 while ( wxIsspace(*psz
) )
881 // fix up data and length
882 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
883 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
884 GetStringData()->nDataLength
= nDataLength
;
891 // adds nCount characters chPad to the string from either side
892 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
894 wxString
s(chPad
, nCount
);
907 // truncate the string
908 wxString
& wxString::Truncate(size_t uiLen
)
910 if ( uiLen
< Len() ) {
913 *(m_pchData
+ uiLen
) = _T('\0');
914 GetStringData()->nDataLength
= uiLen
;
916 //else: nothing to do, string is already short enough
921 // ---------------------------------------------------------------------------
922 // finding (return wxNOT_FOUND if not found and index otherwise)
923 // ---------------------------------------------------------------------------
926 int wxString::Find(wxChar ch
, bool bFromEnd
) const
928 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
930 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
933 // find a sub-string (like strstr)
934 int wxString::Find(const wxChar
*pszSub
) const
936 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
938 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
941 // ---------------------------------------------------------------------------
942 // stream-like operators
943 // ---------------------------------------------------------------------------
944 wxString
& wxString::operator<<(int i
)
947 res
.Printf(_T("%d"), i
);
949 return (*this) << res
;
952 wxString
& wxString::operator<<(float f
)
955 res
.Printf(_T("%f"), f
);
957 return (*this) << res
;
960 wxString
& wxString::operator<<(double d
)
963 res
.Printf(_T("%g"), d
);
965 return (*this) << res
;
968 // ---------------------------------------------------------------------------
970 // ---------------------------------------------------------------------------
971 int wxString::Printf(const wxChar
*pszFormat
, ...)
974 va_start(argptr
, pszFormat
);
976 int iLen
= PrintfV(pszFormat
, argptr
);
983 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
985 // static buffer to avoid dynamic memory allocation each time
986 static char s_szScratch
[1024];
988 // protect the static buffer
989 static wxCriticalSection critsect
;
990 wxCriticalSectionLocker
lock(critsect
);
993 #if 1 // the new implementation
996 for (size_t n
= 0; pszFormat
[n
]; n
++)
997 if (pszFormat
[n
] == _T('%')) {
998 static char s_szFlags
[256] = "%";
1000 bool adj_left
= FALSE
, in_prec
= FALSE
,
1001 prec_dot
= FALSE
, done
= FALSE
;
1003 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1005 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1006 switch (pszFormat
[++n
]) {
1020 s_szFlags
[flagofs
++] = pszFormat
[n
];
1025 s_szFlags
[flagofs
++] = pszFormat
[n
];
1032 // dot will be auto-added to s_szFlags if non-negative number follows
1037 s_szFlags
[flagofs
++] = pszFormat
[n
];
1042 s_szFlags
[flagofs
++] = pszFormat
[n
];
1048 s_szFlags
[flagofs
++] = pszFormat
[n
];
1053 s_szFlags
[flagofs
++] = pszFormat
[n
];
1057 int len
= va_arg(argptr
, int);
1064 adj_left
= !adj_left
;
1065 s_szFlags
[flagofs
++] = '-';
1070 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1073 case _T('1'): case _T('2'): case _T('3'):
1074 case _T('4'): case _T('5'): case _T('6'):
1075 case _T('7'): case _T('8'): case _T('9'):
1079 while ((pszFormat
[n
]>=_T('0')) && (pszFormat
[n
]<=_T('9'))) {
1080 s_szFlags
[flagofs
++] = pszFormat
[n
];
1081 len
= len
*10 + (pszFormat
[n
] - _T('0'));
1084 if (in_prec
) max_width
= len
;
1085 else min_width
= len
;
1086 n
--; // the main loop pre-increments n again
1096 s_szFlags
[flagofs
++] = pszFormat
[n
];
1097 s_szFlags
[flagofs
] = '\0';
1099 int val
= va_arg(argptr
, int);
1100 ::sprintf(s_szScratch
, s_szFlags
, val
);
1102 else if (ilen
== -1) {
1103 short int val
= va_arg(argptr
, short int);
1104 ::sprintf(s_szScratch
, s_szFlags
, val
);
1106 else if (ilen
== 1) {
1107 long int val
= va_arg(argptr
, long int);
1108 ::sprintf(s_szScratch
, s_szFlags
, val
);
1110 else if (ilen
== 2) {
1111 #if SIZEOF_LONG_LONG
1112 long long int val
= va_arg(argptr
, long long int);
1113 ::sprintf(s_szScratch
, s_szFlags
, val
);
1115 long int val
= va_arg(argptr
, long int);
1116 ::sprintf(s_szScratch
, s_szFlags
, val
);
1119 else if (ilen
== 3) {
1120 size_t val
= va_arg(argptr
, size_t);
1121 ::sprintf(s_szScratch
, s_szFlags
, val
);
1123 *this += wxString(s_szScratch
);
1132 s_szFlags
[flagofs
++] = pszFormat
[n
];
1133 s_szFlags
[flagofs
] = '\0';
1135 long double val
= va_arg(argptr
, long double);
1136 ::sprintf(s_szScratch
, s_szFlags
, val
);
1138 double val
= va_arg(argptr
, double);
1139 ::sprintf(s_szScratch
, s_szFlags
, val
);
1141 *this += wxString(s_szScratch
);
1146 void *val
= va_arg(argptr
, void *);
1148 s_szFlags
[flagofs
++] = pszFormat
[n
];
1149 s_szFlags
[flagofs
] = '\0';
1150 ::sprintf(s_szScratch
, s_szFlags
, val
);
1151 *this += wxString(s_szScratch
);
1157 wxChar val
= va_arg(argptr
, int);
1158 // we don't need to honor padding here, do we?
1165 // wx extension: we'll let %hs mean non-Unicode strings
1166 char *val
= va_arg(argptr
, char *);
1168 // ASCII->Unicode constructor handles max_width right
1169 wxString
s(val
, wxConv_libc
, max_width
);
1171 size_t len
= wxSTRING_MAXLEN
;
1173 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1174 } else val
= _T("(null)");
1175 wxString
s(val
, len
);
1177 if (s
.Len() < min_width
)
1178 s
.Pad(min_width
- s
.Len(), _T(' '), adj_left
);
1181 wxChar
*val
= va_arg(argptr
, wxChar
*);
1182 size_t len
= wxSTRING_MAXLEN
;
1184 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1185 } else val
= _T("(null)");
1186 wxString
s(val
, len
);
1187 if (s
.Len() < min_width
)
1188 s
.Pad(min_width
- s
.Len(), _T(' '), adj_left
);
1195 int *val
= va_arg(argptr
, int *);
1198 else if (ilen
== -1) {
1199 short int *val
= va_arg(argptr
, short int *);
1202 else if (ilen
>= 1) {
1203 long int *val
= va_arg(argptr
, long int *);
1209 if (wxIsalpha(pszFormat
[n
]))
1210 // probably some flag not taken care of here yet
1211 s_szFlags
[flagofs
++] = pszFormat
[n
];
1214 *this += _T('%'); // just to pass the glibc tst-printf.c
1222 } else *this += pszFormat
[n
];
1225 // NB: wxVsnprintf() may return either less than the buffer size or -1 if there
1226 // is not enough place depending on implementation
1227 int iLen
= wxVsnprintf(s_szScratch
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
1229 if ( iLen
< (int)WXSIZEOF(s_szScratch
) ) {
1230 buffer
= s_szScratch
;
1233 int size
= WXSIZEOF(s_szScratch
) * 2;
1234 buffer
= (char *)malloc(size
);
1235 while ( buffer
!= NULL
) {
1236 iLen
= wxVsnprintf(buffer
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
1237 if ( iLen
< size
) {
1238 // ok, there was enough space
1242 // still not enough, double it again
1243 buffer
= (char *)realloc(buffer
, size
*= 2);
1255 if ( buffer
!= s_szScratch
)
1262 // ----------------------------------------------------------------------------
1263 // misc other operations
1264 // ----------------------------------------------------------------------------
1265 bool wxString::Matches(const wxChar
*pszMask
) const
1267 // check char by char
1268 const wxChar
*pszTxt
;
1269 for ( pszTxt
= c_str(); *pszMask
!= _T('\0'); pszMask
++, pszTxt
++ ) {
1270 switch ( *pszMask
) {
1272 if ( *pszTxt
== _T('\0') )
1281 // ignore special chars immediately following this one
1282 while ( *pszMask
== _T('*') || *pszMask
== _T('?') )
1285 // if there is nothing more, match
1286 if ( *pszMask
== _T('\0') )
1289 // are there any other metacharacters in the mask?
1291 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, _T("*?"));
1293 if ( pEndMask
!= NULL
) {
1294 // we have to match the string between two metachars
1295 uiLenMask
= pEndMask
- pszMask
;
1298 // we have to match the remainder of the string
1299 uiLenMask
= wxStrlen(pszMask
);
1302 wxString
strToMatch(pszMask
, uiLenMask
);
1303 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1304 if ( pMatch
== NULL
)
1307 // -1 to compensate "++" in the loop
1308 pszTxt
= pMatch
+ uiLenMask
- 1;
1309 pszMask
+= uiLenMask
- 1;
1314 if ( *pszMask
!= *pszTxt
)
1320 // match only if nothing left
1321 return *pszTxt
== _T('\0');
1324 // Count the number of chars
1325 int wxString::Freq(wxChar ch
) const
1329 for (int i
= 0; i
< len
; i
++)
1331 if (GetChar(i
) == ch
)
1337 // convert to upper case, return the copy of the string
1338 wxString
wxString::Upper() const
1339 { wxString
s(*this); return s
.MakeUpper(); }
1341 // convert to lower case, return the copy of the string
1342 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1344 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1347 va_start(argptr
, pszFormat
);
1348 int iLen
= PrintfV(pszFormat
, argptr
);
1353 // ---------------------------------------------------------------------------
1354 // standard C++ library string functions
1355 // ---------------------------------------------------------------------------
1356 #ifdef wxSTD_STRING_COMPATIBILITY
1358 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1360 wxASSERT( str
.GetStringData()->IsValid() );
1361 wxASSERT( nPos
<= Len() );
1363 if ( !str
.IsEmpty() ) {
1365 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1366 wxStrncpy(pc
, c_str(), nPos
);
1367 wxStrcpy(pc
+ nPos
, str
);
1368 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1369 strTmp
.UngetWriteBuf();
1376 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1378 wxASSERT( str
.GetStringData()->IsValid() );
1379 wxASSERT( nStart
<= Len() );
1381 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1383 return p
== NULL
? npos
: p
- c_str();
1386 // VC++ 1.5 can't cope with the default argument in the header.
1387 #if !defined(__VISUALC__) || defined(__WIN32__)
1388 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1390 return find(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1394 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1395 #if !defined(__BORLANDC__)
1396 size_t wxString::find(wxChar ch
, size_t nStart
) const
1398 wxASSERT( nStart
<= Len() );
1400 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1402 return p
== NULL
? npos
: p
- c_str();
1406 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1408 wxASSERT( str
.GetStringData()->IsValid() );
1409 wxASSERT( nStart
<= Len() );
1411 // # could be quicker than that
1412 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1413 while ( p
>= c_str() + str
.Len() ) {
1414 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1415 return p
- str
.Len() - c_str();
1422 // VC++ 1.5 can't cope with the default argument in the header.
1423 #if !defined(__VISUALC__) || defined(__WIN32__)
1424 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1426 return rfind(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1429 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1431 wxASSERT( nStart
<= Len() );
1433 const wxChar
*p
= wxStrrchr(c_str() + nStart
, ch
);
1435 return p
== NULL
? npos
: p
- c_str();
1439 wxString
wxString::substr(size_t nStart
, size_t nLen
) const
1441 // npos means 'take all'
1445 wxASSERT( nStart
+ nLen
<= Len() );
1447 return wxString(c_str() + nStart
, nLen
== npos
? 0 : nLen
);
1450 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1452 wxString
strTmp(c_str(), nStart
);
1453 if ( nLen
!= npos
) {
1454 wxASSERT( nStart
+ nLen
<= Len() );
1456 strTmp
.append(c_str() + nStart
+ nLen
);
1463 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1465 wxASSERT( nStart
+ nLen
<= wxStrlen(sz
) );
1469 strTmp
.append(c_str(), nStart
);
1471 strTmp
.append(c_str() + nStart
+ nLen
);
1477 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1479 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1482 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1483 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1485 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1488 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1489 const wxChar
* sz
, size_t nCount
)
1491 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1494 #endif //std::string compatibility
1496 // ============================================================================
1498 // ============================================================================
1500 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1501 #define ARRAY_MAXSIZE_INCREMENT 4096
1502 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1503 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1506 #define STRING(p) ((wxString *)(&(p)))
1509 wxArrayString::wxArrayString()
1513 m_pItems
= (wxChar
**) NULL
;
1517 wxArrayString::wxArrayString(const wxArrayString
& src
)
1521 m_pItems
= (wxChar
**) NULL
;
1526 // assignment operator
1527 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1532 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1533 Alloc(src
.m_nCount
);
1535 // we can't just copy the pointers here because otherwise we would share
1536 // the strings with another array
1537 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1540 if ( m_nCount
!= 0 )
1541 memcpy(m_pItems
, src
.m_pItems
, m_nCount
*sizeof(wxChar
*));
1547 void wxArrayString::Grow()
1549 // only do it if no more place
1550 if( m_nCount
== m_nSize
) {
1551 if( m_nSize
== 0 ) {
1552 // was empty, alloc some memory
1553 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1554 m_pItems
= new wxChar
*[m_nSize
];
1557 // otherwise when it's called for the first time, nIncrement would be 0
1558 // and the array would never be expanded
1559 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE
!= 0 );
1561 // add 50% but not too much
1562 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1563 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1564 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1565 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1566 m_nSize
+= nIncrement
;
1567 wxChar
**pNew
= new wxChar
*[m_nSize
];
1569 // copy data to new location
1570 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1572 // delete old memory (but do not release the strings!)
1573 wxDELETEA(m_pItems
);
1580 void wxArrayString::Free()
1582 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1583 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1587 // deletes all the strings from the list
1588 void wxArrayString::Empty()
1595 // as Empty, but also frees memory
1596 void wxArrayString::Clear()
1603 wxDELETEA(m_pItems
);
1607 wxArrayString::~wxArrayString()
1611 wxDELETEA(m_pItems
);
1614 // pre-allocates memory (frees the previous data!)
1615 void wxArrayString::Alloc(size_t nSize
)
1617 wxASSERT( nSize
> 0 );
1619 // only if old buffer was not big enough
1620 if ( nSize
> m_nSize
) {
1622 wxDELETEA(m_pItems
);
1623 m_pItems
= new wxChar
*[nSize
];
1630 // minimizes the memory usage by freeing unused memory
1631 void wxArrayString::Shrink()
1633 // only do it if we have some memory to free
1634 if( m_nCount
< m_nSize
) {
1635 // allocates exactly as much memory as we need
1636 wxChar
**pNew
= new wxChar
*[m_nCount
];
1638 // copy data to new location
1639 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1645 // searches the array for an item (forward or backwards)
1646 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
1649 if ( m_nCount
> 0 ) {
1650 size_t ui
= m_nCount
;
1652 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1659 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1660 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1668 // add item at the end
1669 void wxArrayString::Add(const wxString
& str
)
1671 wxASSERT( str
.GetStringData()->IsValid() );
1675 // the string data must not be deleted!
1676 str
.GetStringData()->Lock();
1677 m_pItems
[m_nCount
++] = (wxChar
*)str
.c_str();
1680 // add item at the given position
1681 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
1683 wxASSERT( str
.GetStringData()->IsValid() );
1685 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Insert") );
1689 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
1690 (m_nCount
- nIndex
)*sizeof(wxChar
*));
1692 str
.GetStringData()->Lock();
1693 m_pItems
[nIndex
] = (wxChar
*)str
.c_str();
1698 // removes item from array (by index)
1699 void wxArrayString::Remove(size_t nIndex
)
1701 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Remove") );
1704 Item(nIndex
).GetStringData()->Unlock();
1706 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
1707 (m_nCount
- nIndex
- 1)*sizeof(wxChar
*));
1711 // removes item from array (by value)
1712 void wxArrayString::Remove(const wxChar
*sz
)
1714 int iIndex
= Index(sz
);
1716 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
1717 _("removing inexistent element in wxArrayString::Remove") );
1722 // ----------------------------------------------------------------------------
1724 // ----------------------------------------------------------------------------
1726 // we can only sort one array at a time with the quick-sort based
1729 // need a critical section to protect access to gs_compareFunction and
1730 // gs_sortAscending variables
1731 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
1733 // call this before the value of the global sort vars is changed/after
1734 // you're finished with them
1735 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
1736 gs_critsectStringSort = new wxCriticalSection; \
1737 gs_critsectStringSort->Enter()
1738 #define END_SORT() gs_critsectStringSort->Leave(); \
1739 delete gs_critsectStringSort; \
1740 gs_critsectStringSort = NULL
1742 #define START_SORT()
1744 #endif // wxUSE_THREADS
1746 // function to use for string comparaison
1747 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
1749 // if we don't use the compare function, this flag tells us if we sort the
1750 // array in ascending or descending order
1751 static bool gs_sortAscending
= TRUE
;
1753 // function which is called by quick sort
1754 static int wxStringCompareFunction(const void *first
, const void *second
)
1756 wxString
*strFirst
= (wxString
*)first
;
1757 wxString
*strSecond
= (wxString
*)second
;
1759 if ( gs_compareFunction
) {
1760 return gs_compareFunction(*strFirst
, *strSecond
);
1763 // maybe we should use wxStrcoll
1764 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
1766 return gs_sortAscending
? result
: -result
;
1770 // sort array elements using passed comparaison function
1771 void wxArrayString::Sort(CompareFunction compareFunction
)
1775 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1776 gs_compareFunction
= compareFunction
;
1783 void wxArrayString::Sort(bool reverseOrder
)
1787 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1788 gs_sortAscending
= !reverseOrder
;
1795 void wxArrayString::DoSort()
1797 // just sort the pointers using qsort() - of course it only works because
1798 // wxString() *is* a pointer to its data
1799 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
1802 // ============================================================================
1804 // ============================================================================
1806 WXDLLEXPORT_DATA(wxMBConv
*) wxConv_current
= &wxConv_libc
;
1808 // ----------------------------------------------------------------------------
1809 // standard libc conversion
1810 // ----------------------------------------------------------------------------
1812 WXDLLEXPORT_DATA(wxMBConv
) wxConv_libc
;
1814 size_t wxMBConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1816 return wxMB2WC(buf
, psz
, n
);
1819 size_t wxMBConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1821 return wxWC2MB(buf
, psz
, n
);
1824 // ----------------------------------------------------------------------------
1825 // standard file conversion
1826 // ----------------------------------------------------------------------------
1828 WXDLLEXPORT_DATA(wxMBConv_file
) wxConv_file
;
1830 // just use the libc conversion for now
1831 size_t wxMBConv_file::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1833 return wxMB2WC(buf
, psz
, n
);
1836 size_t wxMBConv_file::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1838 return wxWC2MB(buf
, psz
, n
);
1841 // ----------------------------------------------------------------------------
1842 // standard gdk conversion
1843 // ----------------------------------------------------------------------------
1845 #if defined(__WXGTK__) && (GTK_MINOR_VERSION > 0)
1846 WXDLLEXPORT_DATA(wxMBConv_gdk
) wxConv_gdk
;
1848 #include <gdk/gdk.h>
1850 size_t wxMBConv_gdk::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1853 return gdk_mbstowcs((GdkWChar
*)buf
, psz
, n
);
1855 GdkWChar
*nbuf
= new GdkWChar
[n
=strlen(psz
)];
1856 size_t len
= gdk_mbstowcs(nbuf
, psz
, n
);
1862 size_t wxMBConv_gdk::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1864 char *mbstr
= gdk_wcstombs((GdkWChar
*)psz
);
1865 size_t len
= mbstr
? strlen(mbstr
) : 0;
1867 if (len
> n
) len
= n
;
1868 memcpy(buf
, psz
, len
);
1869 if (len
< n
) buf
[len
] = 0;
1875 // ----------------------------------------------------------------------------
1877 // ----------------------------------------------------------------------------
1879 WXDLLEXPORT_DATA(wxMBConv_UTF7
) wxConv_UTF7
;
1881 // TODO: write actual implementations of UTF-7 here
1882 size_t wxMBConv_UTF7::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1887 size_t wxMBConv_UTF7::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1892 // ----------------------------------------------------------------------------
1894 // ----------------------------------------------------------------------------
1896 WXDLLEXPORT_DATA(wxMBConv_UTF8
) wxConv_UTF8
;
1898 // TODO: write actual implementations of UTF-8 here
1899 size_t wxMBConv_UTF8::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1901 return wxMB2WC(buf
, psz
, n
);
1904 size_t wxMBConv_UTF8::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1906 return wxWC2MB(buf
, psz
, n
);
1909 // ----------------------------------------------------------------------------
1910 // specified character set
1911 // ----------------------------------------------------------------------------
1913 class wxCharacterSet
1916 wxArrayString names
;
1921 #include "wx/dynarray.h"
1922 #include "wx/filefn.h"
1923 #include "wx/textfile.h"
1924 #include "wx/tokenzr.h"
1925 #include "wx/utils.h"
1928 WX_DECLARE_OBJARRAY(wxCharacterSet
, wxCSArray
);
1929 #include "wx/arrimpl.cpp"
1930 WX_DEFINE_OBJARRAY(wxCSArray
);
1932 static wxCSArray wxCharsets
;
1934 static void wxLoadCharacterSets(void)
1936 static bool already_loaded
= FALSE
;
1938 if (already_loaded
) return;
1940 #if defined(__UNIX__)
1941 // search through files in /usr/share/i18n/charmaps
1943 for (fname
= ::wxFindFirstFile(_T("/usr/share/i18n/charmaps/*"));
1945 fname
= ::wxFindNextFile()) {
1946 wxTextFile
cmap(fname
);
1948 wxCharacterSet
*cset
= new wxCharacterSet
;
1949 wxString comchar
,escchar
;
1950 bool in_charset
= FALSE
;
1952 // wxFprintf(stderr,_T("Loaded: %s\n"),fname.c_str());
1955 for (line
= cmap
.GetFirstLine();
1957 line
= cmap
.GetNextLine()) {
1958 // wxFprintf(stderr,_T("line contents: %s\n"),line.c_str());
1959 wxStringTokenizer
token(line
);
1960 wxString cmd
= token
.GetNextToken();
1961 if (cmd
== comchar
) {
1962 if (token
.GetNextToken() == _T("alias")) {
1963 wxStringTokenizer
names(token
.GetNextToken(),_T("/"));
1965 while (!(name
= names
.GetNextToken()).IsEmpty())
1966 cset
->names
.Add(name
);
1969 else if (cmd
== _T("<code_set_name>"))
1970 cset
->names
.Add(token
.GetNextToken());
1971 else if (cmd
== _T("<comment_char>"))
1972 comchar
= token
.GetNextToken();
1973 else if (cmd
== _T("<escape_char>"))
1974 escchar
= token
.GetNextToken();
1975 else if (cmd
== _T("<mb_cur_min>")) {
1977 cset
= (wxCharacterSet
*) NULL
;
1978 break; // we don't support multibyte charsets ourselves (yet)
1980 else if (cmd
== _T("CHARMAP")) {
1981 cset
->data
= (wchar_t *)calloc(256, sizeof(wchar_t));
1984 else if (cmd
== _T("END")) {
1985 if (token
.GetNextToken() == _T("CHARMAP"))
1988 else if (in_charset
) {
1989 // format: <NUL> /x00 <U0000> NULL (NUL)
1990 // <A> /x41 <U0041> LATIN CAPITAL LETTER A
1991 wxString hex
= token
.GetNextToken();
1992 // skip whitespace (why doesn't wxStringTokenizer do this?)
1993 while (wxIsEmpty(hex
) && token
.HasMoreTokens()) hex
= token
.GetNextToken();
1994 wxString uni
= token
.GetNextToken();
1995 // skip whitespace again
1996 while (wxIsEmpty(uni
) && token
.HasMoreTokens()) uni
= token
.GetNextToken();
1998 if ((hex
.GetChar(0) == escchar
) && (hex
.GetChar(1) == _T('x')) &&
1999 (uni
.Left(2) == _T("<U"))) {
2000 hex
.MakeUpper(); uni
.MakeUpper();
2001 int pos
= ::wxHexToDec(hex
.Mid(2,2));
2003 unsigned long uni1
= ::wxHexToDec(uni
.Mid(2,2));
2004 unsigned long uni2
= ::wxHexToDec(uni
.Mid(4,2));
2005 cset
->data
[pos
] = (uni1
<< 16) | uni2
;
2006 // wxFprintf(stderr,_T("char %02x mapped to %04x (%c)\n"),pos,cset->data[pos],cset->data[pos]);
2012 cset
->names
.Shrink();
2013 wxCharsets
.Add(cset
);
2018 wxCharsets
.Shrink();
2019 already_loaded
= TRUE
;
2022 static wxCharacterSet
*wxFindCharacterSet(const wxChar
*charset
)
2024 wxLoadCharacterSets();
2025 for (size_t n
=0; n
<wxCharsets
.GetCount(); n
++)
2026 if (wxCharsets
[n
].names
.Index(charset
) != wxNOT_FOUND
)
2027 return &(wxCharsets
[n
]);
2028 return (wxCharacterSet
*)NULL
;
2031 WXDLLEXPORT_DATA(wxCSConv
) wxConv_local((const wxChar
*)NULL
);
2033 wxCSConv::wxCSConv(const wxChar
*charset
)
2037 wxChar
*lang
= wxGetenv(_T("LANG"));
2038 wxChar
*dot
= lang
? wxStrchr(lang
, _T('.')) : (wxChar
*)NULL
;
2039 if (dot
) charset
= dot
+1;
2042 m_cset
= (wxCharacterSet
*) NULL
;
2046 // first, convert the character set name to standard form
2048 if (wxString(charset
,3).CmpNoCase(_T("ISO")) == 0) {
2049 // make sure it's represented in the standard form: ISO_8859-1
2050 codeset
= _T("ISO_");
2052 if ((*charset
== _T('-')) || (*charset
== _T('_'))) charset
++;
2053 if (wxStrlen(charset
)>4) {
2054 if (wxString(charset
,4) == _T("8859")) {
2055 codeset
<< _T("8859-");
2056 if (*charset
== _T('-')) charset
++;
2061 codeset
.MakeUpper();
2062 m_name
= wxStrdup(codeset
.c_str());
2068 wxCSConv::~wxCSConv()
2073 void wxCSConv::LoadNow()
2075 // wxPrintf(_T("Conversion request\n"));
2077 m_cset
= wxFindCharacterSet(m_name
);
2082 size_t wxCSConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2084 ((wxCSConv
*)this)->LoadNow(); // discard constness
2087 for (size_t c
=0; c
<=n
; c
++)
2088 buf
[c
] = m_cset
->data
[psz
[c
]];
2091 for (size_t c
=0; c
<=n
; c
++)
2098 size_t wxCSConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
2100 ((wxCSConv
*)this)->LoadNow(); // discard constness
2103 for (size_t c
=0; c
<=n
; c
++) {
2105 for (n
=0; (n
<256) && (m_cset
->data
[n
] != psz
[c
]); n
++);
2106 buf
[c
] = (n
>0xff) ? '?' : n
;
2110 for (size_t c
=0; c
<=n
; c
++)
2111 buf
[c
] = (psz
[c
]>0xff) ? '?' : psz
[c
];