1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxString class
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "string.h"
18 * 1) all empty strings use g_strEmpty, nRefs = -1 (set in Init())
19 * 2) AllocBuffer() sets nRefs to 1, Lock() increments it by one
20 * 3) Unlock() decrements nRefs and frees memory if it goes to 0
23 // ===========================================================================
24 // headers, declarations, constants
25 // ===========================================================================
27 // For compilers that support precompilation, includes "wx.h".
28 #include "wx/wxprec.h"
36 #include "wx/string.h"
39 #include <wx/thread.h>
52 #include <wchar.h> // for wcsrtombs(), see comments where it's used
55 #ifdef WXSTRING_IS_WXOBJECT
56 IMPLEMENT_DYNAMIC_CLASS(wxString
, wxObject
)
57 #endif //WXSTRING_IS_WXOBJECT
60 #undef wxUSE_EXPERIMENTAL_PRINTF
61 #define wxUSE_EXPERIMENTAL_PRINTF 1
64 // allocating extra space for each string consumes more memory but speeds up
65 // the concatenation operations (nLen is the current string's length)
66 // NB: EXTRA_ALLOC must be >= 0!
67 #define EXTRA_ALLOC (19 - nLen % 16)
69 // ---------------------------------------------------------------------------
70 // static class variables definition
71 // ---------------------------------------------------------------------------
73 #ifdef wxSTD_STRING_COMPATIBILITY
74 const size_t wxString::npos
= wxSTRING_MAXLEN
;
75 #endif // wxSTD_STRING_COMPATIBILITY
77 // ----------------------------------------------------------------------------
79 // ----------------------------------------------------------------------------
81 // for an empty string, GetStringData() will return this address: this
82 // structure has the same layout as wxStringData and it's data() method will
83 // return the empty string (dummy pointer)
88 } g_strEmpty
= { {-1, 0, 0}, _T('\0') };
90 // empty C style string: points to 'string data' byte of g_strEmpty
91 extern const wxChar WXDLLEXPORT
*g_szNul
= &g_strEmpty
.dummy
;
93 // ----------------------------------------------------------------------------
94 // conditional compilation
95 // ----------------------------------------------------------------------------
97 #if !defined(__WXSW__) && wxUSE_UNICODE
98 #ifdef wxUSE_EXPERIMENTAL_PRINTF
99 #undef wxUSE_EXPERIMENTAL_PRINTF
101 #define wxUSE_EXPERIMENTAL_PRINTF 1
104 // we want to find out if the current platform supports vsnprintf()-like
105 // function: for Unix this is done with configure, for Windows we test the
106 // compiler explicitly.
109 #define wxVsnprintf _vsnprintf
112 #ifdef HAVE_VSNPRINTF
113 #define wxVsnprintf vsnprintf
115 #endif // Windows/!Windows
118 // in this case we'll use vsprintf() (which is ANSI and thus should be
119 // always available), but it's unsafe because it doesn't check for buffer
120 // size - so give a warning
121 #define wxVsnprintf(buffer,len,format,argptr) vsprintf(buffer,format, argptr)
123 #if defined(__VISUALC__)
124 #pragma message("Using sprintf() because no snprintf()-like function defined")
125 #elif defined(__GNUG__) && !defined(__UNIX__)
126 #warning "Using sprintf() because no snprintf()-like function defined"
127 #elif defined(__MWERKS__)
128 #warning "Using sprintf() because no snprintf()-like function defined"
130 #endif // no vsnprintf
133 // AIX has vsnprintf, but there's no prototype in the system headers.
134 extern "C" int vsnprintf(char* str
, size_t n
, const char* format
, va_list ap
);
137 // ----------------------------------------------------------------------------
139 // ----------------------------------------------------------------------------
141 #if defined(wxSTD_STRING_COMPATIBILITY) && wxUSE_STD_IOSTREAM
143 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
146 // ATTN: you can _not_ use both of these in the same program!
148 istream
& operator>>(istream
& is
, wxString
& WXUNUSED(str
))
153 streambuf
*sb
= is
.rdbuf();
156 int ch
= sb
->sbumpc ();
158 is
.setstate(ios::eofbit
);
161 else if ( isspace(ch
) ) {
173 if ( str
.length() == 0 )
174 is
.setstate(ios::failbit
);
179 #endif //std::string compatibility
181 // ----------------------------------------------------------------------------
183 // ----------------------------------------------------------------------------
185 // this small class is used to gather statistics for performance tuning
186 //#define WXSTRING_STATISTICS
187 #ifdef WXSTRING_STATISTICS
191 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
193 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
195 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
198 size_t m_nCount
, m_nTotal
;
200 } g_averageLength("allocation size"),
201 g_averageSummandLength("summand length"),
202 g_averageConcatHit("hit probability in concat"),
203 g_averageInitialLength("initial string length");
205 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
207 #define STATISTICS_ADD(av, val)
208 #endif // WXSTRING_STATISTICS
210 // ===========================================================================
211 // wxString class core
212 // ===========================================================================
214 // ---------------------------------------------------------------------------
216 // ---------------------------------------------------------------------------
218 // constructs string of <nLength> copies of character <ch>
219 wxString::wxString(wxChar ch
, size_t nLength
)
224 AllocBuffer(nLength
);
227 // memset only works on char
228 for (size_t n
=0; n
<nLength
; n
++) m_pchData
[n
] = ch
;
230 memset(m_pchData
, ch
, nLength
);
235 // takes nLength elements of psz starting at nPos
236 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
240 wxASSERT( nPos
<= wxStrlen(psz
) );
242 if ( nLength
== wxSTRING_MAXLEN
)
243 nLength
= wxStrlen(psz
+ nPos
);
245 STATISTICS_ADD(InitialLength
, nLength
);
248 // trailing '\0' is written in AllocBuffer()
249 AllocBuffer(nLength
);
250 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
254 #ifdef wxSTD_STRING_COMPATIBILITY
256 // poor man's iterators are "void *" pointers
257 wxString::wxString(const void *pStart
, const void *pEnd
)
259 InitWith((const wxChar
*)pStart
, 0,
260 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
263 #endif //std::string compatibility
267 // from multibyte string
268 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
270 // first get necessary size
271 size_t nLen
= psz
? conv
.MB2WC((wchar_t *) NULL
, psz
, 0) : 0;
273 // nLength is number of *Unicode* characters here!
274 if ((nLen
!= (size_t)-1) && (nLen
> nLength
))
278 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
280 conv
.MB2WC(m_pchData
, psz
, nLen
);
291 wxString::wxString(const wchar_t *pwz
)
293 // first get necessary size
294 size_t nLen
= pwz
? wxWC2MB((char *) NULL
, pwz
, 0) : 0;
297 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
299 wxWC2MB(m_pchData
, pwz
, nLen
);
309 // ---------------------------------------------------------------------------
311 // ---------------------------------------------------------------------------
313 // allocates memory needed to store a C string of length nLen
314 void wxString::AllocBuffer(size_t nLen
)
316 wxASSERT( nLen
> 0 ); //
317 wxASSERT( nLen
<= INT_MAX
-1 ); // max size (enough room for 1 extra)
319 STATISTICS_ADD(Length
, nLen
);
322 // 1) one extra character for '\0' termination
323 // 2) sizeof(wxStringData) for housekeeping info
324 wxStringData
* pData
= (wxStringData
*)
325 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
327 pData
->nDataLength
= nLen
;
328 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
329 m_pchData
= pData
->data(); // data starts after wxStringData
330 m_pchData
[nLen
] = _T('\0');
333 // must be called before changing this string
334 void wxString::CopyBeforeWrite()
336 wxStringData
* pData
= GetStringData();
338 if ( pData
->IsShared() ) {
339 pData
->Unlock(); // memory not freed because shared
340 size_t nLen
= pData
->nDataLength
;
342 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
345 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
348 // must be called before replacing contents of this string
349 void wxString::AllocBeforeWrite(size_t nLen
)
351 wxASSERT( nLen
!= 0 ); // doesn't make any sense
353 // must not share string and must have enough space
354 wxStringData
* pData
= GetStringData();
355 if ( pData
->IsShared() || (nLen
> pData
->nAllocLength
) ) {
356 // can't work with old buffer, get new one
361 // update the string length
362 pData
->nDataLength
= nLen
;
365 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
368 // allocate enough memory for nLen characters
369 void wxString::Alloc(size_t nLen
)
371 wxStringData
*pData
= GetStringData();
372 if ( pData
->nAllocLength
<= nLen
) {
373 if ( pData
->IsEmpty() ) {
376 wxStringData
* pData
= (wxStringData
*)
377 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
379 pData
->nDataLength
= 0;
380 pData
->nAllocLength
= nLen
;
381 m_pchData
= pData
->data(); // data starts after wxStringData
382 m_pchData
[0u] = _T('\0');
384 else if ( pData
->IsShared() ) {
385 pData
->Unlock(); // memory not freed because shared
386 size_t nOldLen
= pData
->nDataLength
;
388 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
393 wxStringData
*p
= (wxStringData
*)
394 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
397 // @@@ what to do on memory error?
401 // it's not important if the pointer changed or not (the check for this
402 // is not faster than assigning to m_pchData in all cases)
403 p
->nAllocLength
= nLen
;
404 m_pchData
= p
->data();
407 //else: we've already got enough
410 // shrink to minimal size (releasing extra memory)
411 void wxString::Shrink()
413 wxStringData
*pData
= GetStringData();
415 // this variable is unused in release build, so avoid the compiler warning by
416 // just not declaring it
420 realloc(pData
, sizeof(wxStringData
) + (pData
->nDataLength
+ 1)*sizeof(wxChar
));
422 wxASSERT( p
!= NULL
); // can't free memory?
423 wxASSERT( p
== pData
); // we're decrementing the size - block shouldn't move!
426 // get the pointer to writable buffer of (at least) nLen bytes
427 wxChar
*wxString::GetWriteBuf(size_t nLen
)
429 AllocBeforeWrite(nLen
);
431 wxASSERT( GetStringData()->nRefs
== 1 );
432 GetStringData()->Validate(FALSE
);
437 // put string back in a reasonable state after GetWriteBuf
438 void wxString::UngetWriteBuf()
440 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
441 GetStringData()->Validate(TRUE
);
444 // ---------------------------------------------------------------------------
446 // ---------------------------------------------------------------------------
448 // all functions are inline in string.h
450 // ---------------------------------------------------------------------------
451 // assignment operators
452 // ---------------------------------------------------------------------------
454 // helper function: does real copy
455 void wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
457 if ( nSrcLen
== 0 ) {
461 AllocBeforeWrite(nSrcLen
);
462 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
463 GetStringData()->nDataLength
= nSrcLen
;
464 m_pchData
[nSrcLen
] = _T('\0');
468 // assigns one string to another
469 wxString
& wxString::operator=(const wxString
& stringSrc
)
471 wxASSERT( stringSrc
.GetStringData()->IsValid() );
473 // don't copy string over itself
474 if ( m_pchData
!= stringSrc
.m_pchData
) {
475 if ( stringSrc
.GetStringData()->IsEmpty() ) {
480 GetStringData()->Unlock();
481 m_pchData
= stringSrc
.m_pchData
;
482 GetStringData()->Lock();
489 // assigns a single character
490 wxString
& wxString::operator=(wxChar ch
)
497 wxString
& wxString::operator=(const wxChar
*psz
)
499 AssignCopy(wxStrlen(psz
), psz
);
505 // same as 'signed char' variant
506 wxString
& wxString::operator=(const unsigned char* psz
)
508 *this = (const char *)psz
;
513 wxString
& wxString::operator=(const wchar_t *pwz
)
523 // ---------------------------------------------------------------------------
524 // string concatenation
525 // ---------------------------------------------------------------------------
527 // add something to this string
528 void wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
530 STATISTICS_ADD(SummandLength
, nSrcLen
);
532 // concatenating an empty string is a NOP
534 wxStringData
*pData
= GetStringData();
535 size_t nLen
= pData
->nDataLength
;
536 size_t nNewLen
= nLen
+ nSrcLen
;
538 // alloc new buffer if current is too small
539 if ( pData
->IsShared() ) {
540 STATISTICS_ADD(ConcatHit
, 0);
542 // we have to allocate another buffer
543 wxStringData
* pOldData
= GetStringData();
544 AllocBuffer(nNewLen
);
545 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
548 else if ( nNewLen
> pData
->nAllocLength
) {
549 STATISTICS_ADD(ConcatHit
, 0);
551 // we have to grow the buffer
555 STATISTICS_ADD(ConcatHit
, 1);
557 // the buffer is already big enough
560 // should be enough space
561 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
563 // fast concatenation - all is done in our buffer
564 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
566 m_pchData
[nNewLen
] = _T('\0'); // put terminating '\0'
567 GetStringData()->nDataLength
= nNewLen
; // and fix the length
569 //else: the string to append was empty
573 * concatenation functions come in 5 flavours:
575 * char + string and string + char
576 * C str + string and string + C str
579 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
581 wxASSERT( string1
.GetStringData()->IsValid() );
582 wxASSERT( string2
.GetStringData()->IsValid() );
584 wxString s
= string1
;
590 wxString
operator+(const wxString
& string
, wxChar ch
)
592 wxASSERT( string
.GetStringData()->IsValid() );
600 wxString
operator+(wxChar ch
, const wxString
& string
)
602 wxASSERT( string
.GetStringData()->IsValid() );
610 wxString
operator+(const wxString
& string
, const wxChar
*psz
)
612 wxASSERT( string
.GetStringData()->IsValid() );
615 s
.Alloc(wxStrlen(psz
) + string
.Len());
622 wxString
operator+(const wxChar
*psz
, const wxString
& string
)
624 wxASSERT( string
.GetStringData()->IsValid() );
627 s
.Alloc(wxStrlen(psz
) + string
.Len());
634 // ===========================================================================
635 // other common string functions
636 // ===========================================================================
638 // ---------------------------------------------------------------------------
639 // simple sub-string extraction
640 // ---------------------------------------------------------------------------
642 // helper function: clone the data attached to this string
643 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
645 if ( nCopyLen
== 0 ) {
649 dest
.AllocBuffer(nCopyLen
);
650 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
654 // extract string of length nCount starting at nFirst
655 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
657 wxStringData
*pData
= GetStringData();
658 size_t nLen
= pData
->nDataLength
;
660 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
661 if ( nCount
== wxSTRING_MAXLEN
)
663 nCount
= nLen
- nFirst
;
666 // out-of-bounds requests return sensible things
667 if ( nFirst
+ nCount
> nLen
)
669 nCount
= nLen
- nFirst
;
674 // AllocCopy() will return empty string
679 AllocCopy(dest
, nCount
, nFirst
);
684 // extract nCount last (rightmost) characters
685 wxString
wxString::Right(size_t nCount
) const
687 if ( nCount
> (size_t)GetStringData()->nDataLength
)
688 nCount
= GetStringData()->nDataLength
;
691 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
695 // get all characters after the last occurence of ch
696 // (returns the whole string if ch not found)
697 wxString
wxString::AfterLast(wxChar ch
) const
700 int iPos
= Find(ch
, TRUE
);
701 if ( iPos
== wxNOT_FOUND
)
704 str
= c_str() + iPos
+ 1;
709 // extract nCount first (leftmost) characters
710 wxString
wxString::Left(size_t nCount
) const
712 if ( nCount
> (size_t)GetStringData()->nDataLength
)
713 nCount
= GetStringData()->nDataLength
;
716 AllocCopy(dest
, nCount
, 0);
720 // get all characters before the first occurence of ch
721 // (returns the whole string if ch not found)
722 wxString
wxString::BeforeFirst(wxChar ch
) const
725 for ( const wxChar
*pc
= m_pchData
; *pc
!= _T('\0') && *pc
!= ch
; pc
++ )
731 /// get all characters before the last occurence of ch
732 /// (returns empty string if ch not found)
733 wxString
wxString::BeforeLast(wxChar ch
) const
736 int iPos
= Find(ch
, TRUE
);
737 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
738 str
= wxString(c_str(), iPos
);
743 /// get all characters after the first occurence of ch
744 /// (returns empty string if ch not found)
745 wxString
wxString::AfterFirst(wxChar ch
) const
749 if ( iPos
!= wxNOT_FOUND
)
750 str
= c_str() + iPos
+ 1;
755 // replace first (or all) occurences of some substring with another one
756 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
758 size_t uiCount
= 0; // count of replacements made
760 size_t uiOldLen
= wxStrlen(szOld
);
763 const wxChar
*pCurrent
= m_pchData
;
764 const wxChar
*pSubstr
;
765 while ( *pCurrent
!= _T('\0') ) {
766 pSubstr
= wxStrstr(pCurrent
, szOld
);
767 if ( pSubstr
== NULL
) {
768 // strTemp is unused if no replacements were made, so avoid the copy
772 strTemp
+= pCurrent
; // copy the rest
773 break; // exit the loop
776 // take chars before match
777 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
779 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
784 if ( !bReplaceAll
) {
785 strTemp
+= pCurrent
; // copy the rest
786 break; // exit the loop
791 // only done if there were replacements, otherwise would have returned above
797 bool wxString::IsAscii() const
799 const wxChar
*s
= (const wxChar
*) *this;
801 if(!isascii(*s
)) return(FALSE
);
807 bool wxString::IsWord() const
809 const wxChar
*s
= (const wxChar
*) *this;
811 if(!wxIsalpha(*s
)) return(FALSE
);
817 bool wxString::IsNumber() const
819 const wxChar
*s
= (const wxChar
*) *this;
821 if(!wxIsdigit(*s
)) return(FALSE
);
827 wxString
wxString::Strip(stripType w
) const
830 if ( w
& leading
) s
.Trim(FALSE
);
831 if ( w
& trailing
) s
.Trim(TRUE
);
835 // ---------------------------------------------------------------------------
837 // ---------------------------------------------------------------------------
839 wxString
& wxString::MakeUpper()
843 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
844 *p
= (wxChar
)wxToupper(*p
);
849 wxString
& wxString::MakeLower()
853 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
854 *p
= (wxChar
)wxTolower(*p
);
859 // ---------------------------------------------------------------------------
860 // trimming and padding
861 // ---------------------------------------------------------------------------
863 // trims spaces (in the sense of isspace) from left or right side
864 wxString
& wxString::Trim(bool bFromRight
)
866 // first check if we're going to modify the string at all
869 (bFromRight
&& wxIsspace(GetChar(Len() - 1))) ||
870 (!bFromRight
&& wxIsspace(GetChar(0u)))
874 // ok, there is at least one space to trim
879 // find last non-space character
880 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
881 while ( wxIsspace(*psz
) && (psz
>= m_pchData
) )
884 // truncate at trailing space start
886 GetStringData()->nDataLength
= psz
- m_pchData
;
890 // find first non-space character
891 const wxChar
*psz
= m_pchData
;
892 while ( wxIsspace(*psz
) )
895 // fix up data and length
896 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
897 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
898 GetStringData()->nDataLength
= nDataLength
;
905 // adds nCount characters chPad to the string from either side
906 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
908 wxString
s(chPad
, nCount
);
921 // truncate the string
922 wxString
& wxString::Truncate(size_t uiLen
)
924 if ( uiLen
< Len() ) {
927 *(m_pchData
+ uiLen
) = _T('\0');
928 GetStringData()->nDataLength
= uiLen
;
930 //else: nothing to do, string is already short enough
935 // ---------------------------------------------------------------------------
936 // finding (return wxNOT_FOUND if not found and index otherwise)
937 // ---------------------------------------------------------------------------
940 int wxString::Find(wxChar ch
, bool bFromEnd
) const
942 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
944 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
947 // find a sub-string (like strstr)
948 int wxString::Find(const wxChar
*pszSub
) const
950 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
952 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
955 // ---------------------------------------------------------------------------
956 // stream-like operators
957 // ---------------------------------------------------------------------------
958 wxString
& wxString::operator<<(int i
)
961 res
.Printf(_T("%d"), i
);
963 return (*this) << res
;
966 wxString
& wxString::operator<<(float f
)
969 res
.Printf(_T("%f"), f
);
971 return (*this) << res
;
974 wxString
& wxString::operator<<(double d
)
977 res
.Printf(_T("%g"), d
);
979 return (*this) << res
;
982 // ---------------------------------------------------------------------------
984 // ---------------------------------------------------------------------------
985 int wxString::Printf(const wxChar
*pszFormat
, ...)
988 va_start(argptr
, pszFormat
);
990 int iLen
= PrintfV(pszFormat
, argptr
);
997 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
999 // static buffer to avoid dynamic memory allocation each time
1000 char s_szScratch
[1024]; // using static buffer causes internal compiler err
1003 // protect the static buffer
1004 static wxCriticalSection critsect
;
1005 wxCriticalSectionLocker
lock(critsect
);
1009 #if wxUSE_EXPERIMENTAL_PRINTF
1010 // the new implementation
1013 for (size_t n
= 0; pszFormat
[n
]; n
++)
1014 if (pszFormat
[n
] == _T('%')) {
1015 static char s_szFlags
[256] = "%";
1017 bool adj_left
= FALSE
, in_prec
= FALSE
,
1018 prec_dot
= FALSE
, done
= FALSE
;
1020 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1022 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1023 switch (pszFormat
[++n
]) {
1037 s_szFlags
[flagofs
++] = pszFormat
[n
];
1042 s_szFlags
[flagofs
++] = pszFormat
[n
];
1049 // dot will be auto-added to s_szFlags if non-negative number follows
1054 s_szFlags
[flagofs
++] = pszFormat
[n
];
1059 s_szFlags
[flagofs
++] = pszFormat
[n
];
1065 s_szFlags
[flagofs
++] = pszFormat
[n
];
1070 s_szFlags
[flagofs
++] = pszFormat
[n
];
1074 int len
= va_arg(argptr
, int);
1081 adj_left
= !adj_left
;
1082 s_szFlags
[flagofs
++] = '-';
1087 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1090 case _T('1'): case _T('2'): case _T('3'):
1091 case _T('4'): case _T('5'): case _T('6'):
1092 case _T('7'): case _T('8'): case _T('9'):
1096 while ((pszFormat
[n
]>=_T('0')) && (pszFormat
[n
]<=_T('9'))) {
1097 s_szFlags
[flagofs
++] = pszFormat
[n
];
1098 len
= len
*10 + (pszFormat
[n
] - _T('0'));
1101 if (in_prec
) max_width
= len
;
1102 else min_width
= len
;
1103 n
--; // the main loop pre-increments n again
1113 s_szFlags
[flagofs
++] = pszFormat
[n
];
1114 s_szFlags
[flagofs
] = '\0';
1116 int val
= va_arg(argptr
, int);
1117 ::sprintf(s_szScratch
, s_szFlags
, val
);
1119 else if (ilen
== -1) {
1120 short int val
= va_arg(argptr
, short int);
1121 ::sprintf(s_szScratch
, s_szFlags
, val
);
1123 else if (ilen
== 1) {
1124 long int val
= va_arg(argptr
, long int);
1125 ::sprintf(s_szScratch
, s_szFlags
, val
);
1127 else if (ilen
== 2) {
1128 #if SIZEOF_LONG_LONG
1129 long long int val
= va_arg(argptr
, long long int);
1130 ::sprintf(s_szScratch
, s_szFlags
, val
);
1132 long int val
= va_arg(argptr
, long int);
1133 ::sprintf(s_szScratch
, s_szFlags
, val
);
1136 else if (ilen
== 3) {
1137 size_t val
= va_arg(argptr
, size_t);
1138 ::sprintf(s_szScratch
, s_szFlags
, val
);
1140 *this += wxString(s_szScratch
);
1149 s_szFlags
[flagofs
++] = pszFormat
[n
];
1150 s_szFlags
[flagofs
] = '\0';
1152 long double val
= va_arg(argptr
, long double);
1153 ::sprintf(s_szScratch
, s_szFlags
, val
);
1155 double val
= va_arg(argptr
, double);
1156 ::sprintf(s_szScratch
, s_szFlags
, val
);
1158 *this += wxString(s_szScratch
);
1163 void *val
= va_arg(argptr
, void *);
1165 s_szFlags
[flagofs
++] = pszFormat
[n
];
1166 s_szFlags
[flagofs
] = '\0';
1167 ::sprintf(s_szScratch
, s_szFlags
, val
);
1168 *this += wxString(s_szScratch
);
1174 wxChar val
= va_arg(argptr
, int);
1175 // we don't need to honor padding here, do we?
1182 // wx extension: we'll let %hs mean non-Unicode strings
1183 char *val
= va_arg(argptr
, char *);
1185 // ASCII->Unicode constructor handles max_width right
1186 wxString
s(val
, wxConvLibc
, max_width
);
1188 size_t len
= wxSTRING_MAXLEN
;
1190 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1191 } else val
= _T("(null)");
1192 wxString
s(val
, len
);
1194 if (s
.Len() < min_width
)
1195 s
.Pad(min_width
- s
.Len(), _T(' '), adj_left
);
1198 wxChar
*val
= va_arg(argptr
, wxChar
*);
1199 size_t len
= wxSTRING_MAXLEN
;
1201 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1202 } else val
= _T("(null)");
1203 wxString
s(val
, len
);
1204 if (s
.Len() < min_width
)
1205 s
.Pad(min_width
- s
.Len(), _T(' '), adj_left
);
1212 int *val
= va_arg(argptr
, int *);
1215 else if (ilen
== -1) {
1216 short int *val
= va_arg(argptr
, short int *);
1219 else if (ilen
>= 1) {
1220 long int *val
= va_arg(argptr
, long int *);
1226 if (wxIsalpha(pszFormat
[n
]))
1227 // probably some flag not taken care of here yet
1228 s_szFlags
[flagofs
++] = pszFormat
[n
];
1231 *this += _T('%'); // just to pass the glibc tst-printf.c
1239 } else *this += pszFormat
[n
];
1242 // NB: wxVsnprintf() may return either less than the buffer size or -1 if there
1243 // is not enough place depending on implementation
1244 int iLen
= wxVsnprintf(s_szScratch
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
1246 if ( iLen
< (int)WXSIZEOF(s_szScratch
) ) {
1247 buffer
= s_szScratch
;
1250 int size
= WXSIZEOF(s_szScratch
) * 2;
1251 buffer
= (char *)malloc(size
);
1252 while ( buffer
!= NULL
) {
1253 iLen
= wxVsnprintf(buffer
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
1254 if ( iLen
< size
) {
1255 // ok, there was enough space
1259 // still not enough, double it again
1260 buffer
= (char *)realloc(buffer
, size
*= 2);
1272 if ( buffer
!= s_szScratch
)
1279 // ----------------------------------------------------------------------------
1280 // misc other operations
1281 // ----------------------------------------------------------------------------
1282 bool wxString::Matches(const wxChar
*pszMask
) const
1284 // check char by char
1285 const wxChar
*pszTxt
;
1286 for ( pszTxt
= c_str(); *pszMask
!= _T('\0'); pszMask
++, pszTxt
++ ) {
1287 switch ( *pszMask
) {
1289 if ( *pszTxt
== _T('\0') )
1298 // ignore special chars immediately following this one
1299 while ( *pszMask
== _T('*') || *pszMask
== _T('?') )
1302 // if there is nothing more, match
1303 if ( *pszMask
== _T('\0') )
1306 // are there any other metacharacters in the mask?
1308 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, _T("*?"));
1310 if ( pEndMask
!= NULL
) {
1311 // we have to match the string between two metachars
1312 uiLenMask
= pEndMask
- pszMask
;
1315 // we have to match the remainder of the string
1316 uiLenMask
= wxStrlen(pszMask
);
1319 wxString
strToMatch(pszMask
, uiLenMask
);
1320 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1321 if ( pMatch
== NULL
)
1324 // -1 to compensate "++" in the loop
1325 pszTxt
= pMatch
+ uiLenMask
- 1;
1326 pszMask
+= uiLenMask
- 1;
1331 if ( *pszMask
!= *pszTxt
)
1337 // match only if nothing left
1338 return *pszTxt
== _T('\0');
1341 // Count the number of chars
1342 int wxString::Freq(wxChar ch
) const
1346 for (int i
= 0; i
< len
; i
++)
1348 if (GetChar(i
) == ch
)
1354 // convert to upper case, return the copy of the string
1355 wxString
wxString::Upper() const
1356 { wxString
s(*this); return s
.MakeUpper(); }
1358 // convert to lower case, return the copy of the string
1359 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1361 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1364 va_start(argptr
, pszFormat
);
1365 int iLen
= PrintfV(pszFormat
, argptr
);
1370 // ---------------------------------------------------------------------------
1371 // standard C++ library string functions
1372 // ---------------------------------------------------------------------------
1373 #ifdef wxSTD_STRING_COMPATIBILITY
1375 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1377 wxASSERT( str
.GetStringData()->IsValid() );
1378 wxASSERT( nPos
<= Len() );
1380 if ( !str
.IsEmpty() ) {
1382 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1383 wxStrncpy(pc
, c_str(), nPos
);
1384 wxStrcpy(pc
+ nPos
, str
);
1385 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1386 strTmp
.UngetWriteBuf();
1393 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1395 wxASSERT( str
.GetStringData()->IsValid() );
1396 wxASSERT( nStart
<= Len() );
1398 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1400 return p
== NULL
? npos
: p
- c_str();
1403 // VC++ 1.5 can't cope with the default argument in the header.
1404 #if !defined(__VISUALC__) || defined(__WIN32__)
1405 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1407 return find(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1411 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1412 #if !defined(__BORLANDC__)
1413 size_t wxString::find(wxChar ch
, size_t nStart
) const
1415 wxASSERT( nStart
<= Len() );
1417 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1419 return p
== NULL
? npos
: p
- c_str();
1423 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1425 wxASSERT( str
.GetStringData()->IsValid() );
1426 wxASSERT( nStart
<= Len() );
1428 // TODO could be made much quicker than that
1429 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1430 while ( p
>= c_str() + str
.Len() ) {
1431 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1432 return p
- str
.Len() - c_str();
1439 // VC++ 1.5 can't cope with the default argument in the header.
1440 #if !defined(__VISUALC__) || defined(__WIN32__)
1441 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1443 return rfind(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1446 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1448 if ( nStart
== npos
)
1454 wxASSERT( nStart
<= Len() );
1457 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1462 size_t result
= p
- c_str();
1463 return ( result
> nStart
) ? npos
: result
;
1467 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1469 const wxChar
*start
= c_str() + nStart
;
1470 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1472 return firstOf
- start
;
1477 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1479 if ( nStart
== npos
)
1485 wxASSERT( nStart
<= Len() );
1488 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1490 if ( wxStrchr(sz
, *p
) )
1497 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1499 if ( nStart
== npos
)
1505 wxASSERT( nStart
<= Len() );
1508 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1509 if ( nAccept
>= length() - nStart
)
1515 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1517 wxASSERT( nStart
<= Len() );
1519 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1528 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1530 if ( nStart
== npos
)
1536 wxASSERT( nStart
<= Len() );
1539 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1541 if ( !wxStrchr(sz
, *p
) )
1548 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1550 if ( nStart
== npos
)
1556 wxASSERT( nStart
<= Len() );
1559 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1568 wxString
wxString::substr(size_t nStart
, size_t nLen
) const
1570 // npos means 'take all'
1574 wxASSERT( nStart
+ nLen
<= Len() );
1576 return wxString(c_str() + nStart
, nLen
== npos
? 0 : nLen
);
1579 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1581 wxString
strTmp(c_str(), nStart
);
1582 if ( nLen
!= npos
) {
1583 wxASSERT( nStart
+ nLen
<= Len() );
1585 strTmp
.append(c_str() + nStart
+ nLen
);
1592 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1594 wxASSERT( nStart
+ nLen
<= wxStrlen(sz
) );
1598 strTmp
.append(c_str(), nStart
);
1600 strTmp
.append(c_str() + nStart
+ nLen
);
1606 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1608 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1611 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1612 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1614 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1617 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1618 const wxChar
* sz
, size_t nCount
)
1620 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1623 #endif //std::string compatibility
1625 // ============================================================================
1627 // ============================================================================
1629 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1630 #define ARRAY_MAXSIZE_INCREMENT 4096
1631 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1632 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1635 #define STRING(p) ((wxString *)(&(p)))
1638 wxArrayString::wxArrayString()
1642 m_pItems
= (wxChar
**) NULL
;
1646 wxArrayString::wxArrayString(const wxArrayString
& src
)
1650 m_pItems
= (wxChar
**) NULL
;
1655 // assignment operator
1656 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1661 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1662 Alloc(src
.m_nCount
);
1664 // we can't just copy the pointers here because otherwise we would share
1665 // the strings with another array
1666 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1669 if ( m_nCount
!= 0 )
1670 memcpy(m_pItems
, src
.m_pItems
, m_nCount
*sizeof(wxChar
*));
1676 void wxArrayString::Grow()
1678 // only do it if no more place
1679 if( m_nCount
== m_nSize
) {
1680 if( m_nSize
== 0 ) {
1681 // was empty, alloc some memory
1682 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1683 m_pItems
= new wxChar
*[m_nSize
];
1686 // otherwise when it's called for the first time, nIncrement would be 0
1687 // and the array would never be expanded
1688 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE
!= 0 );
1690 // add 50% but not too much
1691 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1692 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1693 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1694 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1695 m_nSize
+= nIncrement
;
1696 wxChar
**pNew
= new wxChar
*[m_nSize
];
1698 // copy data to new location
1699 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1701 // delete old memory (but do not release the strings!)
1702 wxDELETEA(m_pItems
);
1709 void wxArrayString::Free()
1711 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1712 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1716 // deletes all the strings from the list
1717 void wxArrayString::Empty()
1724 // as Empty, but also frees memory
1725 void wxArrayString::Clear()
1732 wxDELETEA(m_pItems
);
1736 wxArrayString::~wxArrayString()
1740 wxDELETEA(m_pItems
);
1743 // pre-allocates memory (frees the previous data!)
1744 void wxArrayString::Alloc(size_t nSize
)
1746 wxASSERT( nSize
> 0 );
1748 // only if old buffer was not big enough
1749 if ( nSize
> m_nSize
) {
1751 wxDELETEA(m_pItems
);
1752 m_pItems
= new wxChar
*[nSize
];
1759 // minimizes the memory usage by freeing unused memory
1760 void wxArrayString::Shrink()
1762 // only do it if we have some memory to free
1763 if( m_nCount
< m_nSize
) {
1764 // allocates exactly as much memory as we need
1765 wxChar
**pNew
= new wxChar
*[m_nCount
];
1767 // copy data to new location
1768 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1774 // searches the array for an item (forward or backwards)
1775 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
1778 if ( m_nCount
> 0 ) {
1779 size_t ui
= m_nCount
;
1781 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1788 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1789 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1797 // add item at the end
1798 void wxArrayString::Add(const wxString
& str
)
1800 wxASSERT( str
.GetStringData()->IsValid() );
1804 // the string data must not be deleted!
1805 str
.GetStringData()->Lock();
1806 m_pItems
[m_nCount
++] = (wxChar
*)str
.c_str();
1809 // add item at the given position
1810 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
1812 wxASSERT( str
.GetStringData()->IsValid() );
1814 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Insert") );
1818 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
1819 (m_nCount
- nIndex
)*sizeof(wxChar
*));
1821 str
.GetStringData()->Lock();
1822 m_pItems
[nIndex
] = (wxChar
*)str
.c_str();
1827 // removes item from array (by index)
1828 void wxArrayString::Remove(size_t nIndex
)
1830 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Remove") );
1833 Item(nIndex
).GetStringData()->Unlock();
1835 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
1836 (m_nCount
- nIndex
- 1)*sizeof(wxChar
*));
1840 // removes item from array (by value)
1841 void wxArrayString::Remove(const wxChar
*sz
)
1843 int iIndex
= Index(sz
);
1845 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
1846 _("removing inexistent element in wxArrayString::Remove") );
1851 // ----------------------------------------------------------------------------
1853 // ----------------------------------------------------------------------------
1855 // we can only sort one array at a time with the quick-sort based
1858 // need a critical section to protect access to gs_compareFunction and
1859 // gs_sortAscending variables
1860 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
1862 // call this before the value of the global sort vars is changed/after
1863 // you're finished with them
1864 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
1865 gs_critsectStringSort = new wxCriticalSection; \
1866 gs_critsectStringSort->Enter()
1867 #define END_SORT() gs_critsectStringSort->Leave(); \
1868 delete gs_critsectStringSort; \
1869 gs_critsectStringSort = NULL
1871 #define START_SORT()
1873 #endif // wxUSE_THREADS
1875 // function to use for string comparaison
1876 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
1878 // if we don't use the compare function, this flag tells us if we sort the
1879 // array in ascending or descending order
1880 static bool gs_sortAscending
= TRUE
;
1882 // function which is called by quick sort
1883 static int wxStringCompareFunction(const void *first
, const void *second
)
1885 wxString
*strFirst
= (wxString
*)first
;
1886 wxString
*strSecond
= (wxString
*)second
;
1888 if ( gs_compareFunction
) {
1889 return gs_compareFunction(*strFirst
, *strSecond
);
1892 // maybe we should use wxStrcoll
1893 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
1895 return gs_sortAscending
? result
: -result
;
1899 // sort array elements using passed comparaison function
1900 void wxArrayString::Sort(CompareFunction compareFunction
)
1904 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1905 gs_compareFunction
= compareFunction
;
1912 void wxArrayString::Sort(bool reverseOrder
)
1916 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1917 gs_sortAscending
= !reverseOrder
;
1924 void wxArrayString::DoSort()
1926 // just sort the pointers using qsort() - of course it only works because
1927 // wxString() *is* a pointer to its data
1928 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
1931 // ============================================================================
1933 // ============================================================================
1935 WXDLLEXPORT_DATA(wxMBConv
*) wxConvCurrent
= &wxConvLibc
;
1937 WXDLLEXPORT_DATA(wxMBConv
) wxConvLibc
, wxConvFile
;
1942 // ----------------------------------------------------------------------------
1943 // standard libc conversion
1944 // ----------------------------------------------------------------------------
1946 WXDLLEXPORT_DATA(wxMBConv
) wxConvLibc
;
1948 size_t wxMBConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1950 return wxMB2WC(buf
, psz
, n
);
1953 size_t wxMBConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1955 return wxWC2MB(buf
, psz
, n
);
1958 // ----------------------------------------------------------------------------
1959 // standard file conversion
1960 // ----------------------------------------------------------------------------
1962 WXDLLEXPORT_DATA(wxMBConvFile
) wxConvFile
;
1964 // just use the libc conversion for now
1965 size_t wxMBConvFile::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1967 return wxMB2WC(buf
, psz
, n
);
1970 size_t wxMBConvFile::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1972 return wxWC2MB(buf
, psz
, n
);
1975 // ----------------------------------------------------------------------------
1976 // standard gdk conversion
1977 // ----------------------------------------------------------------------------
1980 WXDLLEXPORT_DATA(wxMBConvGdk
) wxConvGdk
;
1982 #include <gdk/gdk.h>
1984 size_t wxMBConvGdk::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1987 return gdk_mbstowcs((GdkWChar
*)buf
, psz
, n
);
1989 GdkWChar
*nbuf
= new GdkWChar
[n
=strlen(psz
)];
1990 size_t len
= gdk_mbstowcs(nbuf
, psz
, n
);
1996 size_t wxMBConvGdk::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1998 char *mbstr
= gdk_wcstombs((GdkWChar
*)psz
);
1999 size_t len
= mbstr
? strlen(mbstr
) : 0;
2001 if (len
> n
) len
= n
;
2002 memcpy(buf
, psz
, len
);
2003 if (len
< n
) buf
[len
] = 0;
2009 // ----------------------------------------------------------------------------
2011 // ----------------------------------------------------------------------------
2013 WXDLLEXPORT_DATA(wxMBConvUTF7
) wxConvUTF7
;
2016 static char utf7_setD
[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2017 "abcdefghijklmnopqrstuvwxyz"
2018 "0123456789'(),-./:?";
2019 static char utf7_setO
[]="!\"#$%&*;<=>@[]^_`{|}";
2020 static char utf7_setB
[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2021 "abcdefghijklmnopqrstuvwxyz"
2025 // TODO: write actual implementations of UTF-7 here
2026 size_t wxMBConvUTF7::MB2WC(wchar_t * WXUNUSED(buf
),
2027 const char * WXUNUSED(psz
),
2028 size_t WXUNUSED(n
)) const
2033 size_t wxMBConvUTF7::WC2MB(char * WXUNUSED(buf
),
2034 const wchar_t * WXUNUSED(psz
),
2035 size_t WXUNUSED(n
)) const
2040 // ----------------------------------------------------------------------------
2042 // ----------------------------------------------------------------------------
2044 WXDLLEXPORT_DATA(wxMBConvUTF8
) wxConvUTF8
;
2046 static unsigned long utf8_max
[]={0x7f,0x7ff,0xffff,0x1fffff,0x3ffffff,0x7fffffff,0xffffffff};
2048 size_t wxMBConvUTF8::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2052 while (*psz
&& ((!buf
) || (len
<n
))) {
2053 unsigned char cc
=*psz
++, fc
=cc
;
2055 for (cnt
=0; fc
&0x80; cnt
++) fc
<<=1;
2063 // invalid UTF-8 sequence
2066 unsigned ocnt
=cnt
-1;
2067 unsigned long res
=cc
&(0x3f>>cnt
);
2070 if ((cc
&0xC0)!=0x80) {
2071 // invalid UTF-8 sequence
2074 res
=(res
<<6)|(cc
&0x3f);
2076 if (res
<=utf8_max
[ocnt
]) {
2077 // illegal UTF-8 encoding
2080 if (buf
) *buf
++=res
;
2085 if (buf
&& (len
<n
)) *buf
= 0;
2089 size_t wxMBConvUTF8::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
2093 while (*psz
&& ((!buf
) || (len
<n
))) {
2094 unsigned long cc
=(*psz
++)&0x7fffffff;
2096 for (cnt
=0; cc
>utf8_max
[cnt
]; cnt
++);
2104 *buf
++=(-128>>cnt
)|((cc
>>(cnt
*6))&(0x3f>>cnt
));
2106 *buf
++=0x80|((cc
>>(cnt
*6))&0x3f);
2110 if (buf
&& (len
<n
)) *buf
= 0;
2114 // ----------------------------------------------------------------------------
2115 // specified character set
2116 // ----------------------------------------------------------------------------
2118 class wxCharacterSet
2121 wxArrayString names
;
2126 #include "wx/dynarray.h"
2127 #include "wx/filefn.h"
2128 #include "wx/textfile.h"
2129 #include "wx/tokenzr.h"
2130 #include "wx/utils.h"
2133 WX_DECLARE_OBJARRAY(wxCharacterSet
, wxCSArray
);
2134 #include "wx/arrimpl.cpp"
2135 WX_DEFINE_OBJARRAY(wxCSArray
);
2137 static wxCSArray wxCharsets
;
2139 static void wxLoadCharacterSets(void)
2141 static bool already_loaded
= FALSE
;
2143 if (already_loaded
) return;
2145 already_loaded
= TRUE
;
2146 #if defined(__UNIX__) && wxUSE_TEXTFILE
2147 // search through files in /usr/share/i18n/charmaps
2149 for (fname
= ::wxFindFirstFile(_T("/usr/share/i18n/charmaps/*"));
2151 fname
= ::wxFindNextFile()) {
2152 wxTextFile
cmap(fname
);
2154 wxCharacterSet
*cset
= new wxCharacterSet
;
2155 wxString comchar
,escchar
;
2156 bool in_charset
= FALSE
;
2158 // wxFprintf(stderr,_T("Loaded: %s\n"),fname.c_str());
2161 for (line
= cmap
.GetFirstLine();
2163 line
= cmap
.GetNextLine()) {
2164 // wxFprintf(stderr,_T("line contents: %s\n"),line.c_str());
2165 wxStringTokenizer
token(line
);
2166 wxString cmd
= token
.GetNextToken();
2167 if (cmd
== comchar
) {
2168 if (token
.GetNextToken() == _T("alias"))
2169 cset
->names
.Add(token
.GetNextToken());
2171 else if (cmd
== _T("<code_set_name>"))
2172 cset
->names
.Add(token
.GetNextToken());
2173 else if (cmd
== _T("<comment_char>"))
2174 comchar
= token
.GetNextToken();
2175 else if (cmd
== _T("<escape_char>"))
2176 escchar
= token
.GetNextToken();
2177 else if (cmd
== _T("<mb_cur_min>")) {
2179 cset
= (wxCharacterSet
*) NULL
;
2180 break; // we don't support multibyte charsets ourselves (yet)
2182 else if (cmd
== _T("CHARMAP")) {
2183 cset
->data
= (wchar_t *)calloc(256, sizeof(wchar_t));
2186 else if (cmd
== _T("END")) {
2187 if (token
.GetNextToken() == _T("CHARMAP"))
2190 else if (in_charset
) {
2191 // format: <NUL> /x00 <U0000> NULL (NUL)
2192 // <A> /x41 <U0041> LATIN CAPITAL LETTER A
2193 wxString hex
= token
.GetNextToken();
2194 // skip whitespace (why doesn't wxStringTokenizer do this?)
2195 while (wxIsEmpty(hex
) && token
.HasMoreTokens()) hex
= token
.GetNextToken();
2196 wxString uni
= token
.GetNextToken();
2197 // skip whitespace again
2198 while (wxIsEmpty(uni
) && token
.HasMoreTokens()) uni
= token
.GetNextToken();
2199 if ((hex
.Len() > 2) && (wxString(hex
.GetChar(0)) == escchar
) && (hex
.GetChar(1) == _T('x')) &&
2200 (uni
.Left(2) == _T("<U"))) {
2201 hex
.MakeUpper(); uni
.MakeUpper();
2202 int pos
= ::wxHexToDec(hex
.Mid(2,2));
2204 unsigned long uni1
= ::wxHexToDec(uni
.Mid(2,2));
2205 unsigned long uni2
= ::wxHexToDec(uni
.Mid(4,2));
2206 cset
->data
[pos
] = (uni1
<< 16) | uni2
;
2207 // wxFprintf(stderr,_T("char %02x mapped to %04x (%c)\n"),pos,cset->data[pos],cset->data[pos]);
2213 cset
->names
.Shrink();
2214 wxCharsets
.Add(cset
);
2219 wxCharsets
.Shrink();
2222 static wxCharacterSet
*wxFindCharacterSet(const wxChar
*charset
)
2224 if (!charset
) return (wxCharacterSet
*)NULL
;
2225 wxLoadCharacterSets();
2226 for (size_t n
=0; n
<wxCharsets
.GetCount(); n
++)
2227 if (wxCharsets
[n
].names
.Index(charset
) != wxNOT_FOUND
)
2228 return &(wxCharsets
[n
]);
2229 return (wxCharacterSet
*)NULL
;
2232 WXDLLEXPORT_DATA(wxCSConv
) wxConvLocal((const wxChar
*)NULL
);
2234 wxCSConv::wxCSConv(const wxChar
*charset
)
2236 m_name
= (wxChar
*) NULL
;
2237 m_cset
= (wxCharacterSet
*) NULL
;
2242 wxCSConv::~wxCSConv()
2244 if (m_name
) free(m_name
);
2247 void wxCSConv::SetName(const wxChar
*charset
)
2251 // first, convert the character set name to standard form
2253 if (wxString(charset
,3).CmpNoCase(_T("ISO")) == 0) {
2254 // make sure it's represented in the standard form: ISO_8859-1
2255 codeset
= _T("ISO_");
2257 if ((*charset
== _T('-')) || (*charset
== _T('_'))) charset
++;
2258 if (wxStrlen(charset
)>4) {
2259 if (wxString(charset
,4) == _T("8859")) {
2260 codeset
<< _T("8859-");
2261 if (*charset
== _T('-')) charset
++;
2266 codeset
.MakeUpper();
2267 m_name
= wxStrdup(codeset
.c_str());
2273 void wxCSConv::LoadNow()
2275 // wxPrintf(_T("Conversion request\n"));
2279 wxChar
*lang
= wxGetenv(_T("LANG"));
2280 wxChar
*dot
= lang
? wxStrchr(lang
, _T('.')) : (wxChar
*)NULL
;
2281 if (dot
) SetName(dot
+1);
2284 m_cset
= wxFindCharacterSet(m_name
);
2289 size_t wxCSConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2291 ((wxCSConv
*)this)->LoadNow(); // discard constness
2294 for (size_t c
=0; c
<n
; c
++)
2295 buf
[c
] = m_cset
->data
[(unsigned char)(psz
[c
])];
2298 for (size_t c
=0; c
<n
; c
++)
2299 buf
[c
] = (unsigned char)(psz
[c
]);
2306 size_t wxCSConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
2308 ((wxCSConv
*)this)->LoadNow(); // discard constness
2311 for (size_t c
=0; c
<n
; c
++) {
2313 for (n
=0; (n
<256) && (m_cset
->data
[n
] != psz
[c
]); n
++);
2314 buf
[c
] = (n
>0xff) ? '?' : n
;
2318 for (size_t c
=0; c
<n
; c
++)
2319 buf
[c
] = (psz
[c
]>0xff) ? '?' : psz
[c
];
2326 #endif//wxUSE_WCHAR_T
2329 const wxWCharBuffer
wxMBConv::cMB2WC(const char *psz
) const
2332 size_t nLen
= MB2WC((wchar_t *) NULL
, psz
, 0);
2333 wxWCharBuffer
buf(nLen
);
2334 MB2WC(WCSTRINGCAST buf
, psz
, nLen
);
2336 } else return wxWCharBuffer((wchar_t *) NULL
);
2339 const wxCharBuffer
wxMBConv::cWC2MB(const wchar_t *psz
) const
2342 size_t nLen
= WC2MB((char *) NULL
, psz
, 0);
2343 wxCharBuffer
buf(nLen
);
2344 WC2MB(MBSTRINGCAST buf
, psz
, nLen
);
2346 } else return wxCharBuffer((char *) NULL
);
2349 #endif//wxUSE_WCHAR_T