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"
17 #define LINKAGECPP _Optlink
24 * 1) all empty strings use g_strEmpty, nRefs = -1 (set in Init())
25 * 2) AllocBuffer() sets nRefs to 1, Lock() increments it by one
26 * 3) Unlock() decrements nRefs and frees memory if it goes to 0
29 // ===========================================================================
30 // headers, declarations, constants
31 // ===========================================================================
33 // For compilers that support precompilation, includes "wx.h".
34 #include "wx/wxprec.h"
42 #include "wx/string.h"
45 #include <wx/thread.h>
58 #include <wchar.h> // for wcsrtombs(), see comments where it's used
61 #ifdef WXSTRING_IS_WXOBJECT
62 IMPLEMENT_DYNAMIC_CLASS(wxString
, wxObject
)
63 #endif //WXSTRING_IS_WXOBJECT
66 #undef wxUSE_EXPERIMENTAL_PRINTF
67 #define wxUSE_EXPERIMENTAL_PRINTF 1
70 // allocating extra space for each string consumes more memory but speeds up
71 // the concatenation operations (nLen is the current string's length)
72 // NB: EXTRA_ALLOC must be >= 0!
73 #define EXTRA_ALLOC (19 - nLen % 16)
75 // ---------------------------------------------------------------------------
76 // static class variables definition
77 // ---------------------------------------------------------------------------
79 #ifdef wxSTD_STRING_COMPATIBILITY
80 const size_t wxString::npos
= wxSTRING_MAXLEN
;
81 #endif // wxSTD_STRING_COMPATIBILITY
83 // ----------------------------------------------------------------------------
85 // ----------------------------------------------------------------------------
87 // for an empty string, GetStringData() will return this address: this
88 // structure has the same layout as wxStringData and it's data() method will
89 // return the empty string (dummy pointer)
94 } g_strEmpty
= { {-1, 0, 0}, _T('\0') };
96 // empty C style string: points to 'string data' byte of g_strEmpty
97 extern const wxChar WXDLLEXPORT
*g_szNul
= &g_strEmpty
.dummy
;
99 // ----------------------------------------------------------------------------
100 // conditional compilation
101 // ----------------------------------------------------------------------------
103 #if !defined(__WXSW__) && wxUSE_UNICODE
104 #ifdef wxUSE_EXPERIMENTAL_PRINTF
105 #undef wxUSE_EXPERIMENTAL_PRINTF
107 #define wxUSE_EXPERIMENTAL_PRINTF 1
110 // we want to find out if the current platform supports vsnprintf()-like
111 // function: for Unix this is done with configure, for Windows we test the
112 // compiler explicitly.
115 #define wxVsnprintf _vsnprintf
118 #ifdef HAVE_VSNPRINTF
119 #define wxVsnprintf vsnprintf
121 #endif // Windows/!Windows
124 // in this case we'll use vsprintf() (which is ANSI and thus should be
125 // always available), but it's unsafe because it doesn't check for buffer
126 // size - so give a warning
127 #define wxVsnprintf(buffer,len,format,argptr) vsprintf(buffer,format, argptr)
129 #if defined(__VISUALC__)
130 #pragma message("Using sprintf() because no snprintf()-like function defined")
131 #elif defined(__GNUG__) && !defined(__UNIX__)
132 #warning "Using sprintf() because no snprintf()-like function defined"
133 #elif defined(__MWERKS__)
134 #warning "Using sprintf() because no snprintf()-like function defined"
136 #endif // no vsnprintf
139 // AIX has vsnprintf, but there's no prototype in the system headers.
140 extern "C" int vsnprintf(char* str
, size_t n
, const char* format
, va_list ap
);
143 // ----------------------------------------------------------------------------
145 // ----------------------------------------------------------------------------
147 #if defined(wxSTD_STRING_COMPATIBILITY) && wxUSE_STD_IOSTREAM
149 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
152 // ATTN: you can _not_ use both of these in the same program!
154 istream
& operator>>(istream
& is
, wxString
& WXUNUSED(str
))
159 streambuf
*sb
= is
.rdbuf();
162 int ch
= sb
->sbumpc ();
164 is
.setstate(ios::eofbit
);
167 else if ( isspace(ch
) ) {
179 if ( str
.length() == 0 )
180 is
.setstate(ios::failbit
);
185 #endif //std::string compatibility
187 // ----------------------------------------------------------------------------
189 // ----------------------------------------------------------------------------
191 // this small class is used to gather statistics for performance tuning
192 //#define WXSTRING_STATISTICS
193 #ifdef WXSTRING_STATISTICS
197 Averager(const char *sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
199 { printf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
201 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
204 size_t m_nCount
, m_nTotal
;
206 } g_averageLength("allocation size"),
207 g_averageSummandLength("summand length"),
208 g_averageConcatHit("hit probability in concat"),
209 g_averageInitialLength("initial string length");
211 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
213 #define STATISTICS_ADD(av, val)
214 #endif // WXSTRING_STATISTICS
216 // ===========================================================================
217 // wxString class core
218 // ===========================================================================
220 // ---------------------------------------------------------------------------
222 // ---------------------------------------------------------------------------
224 // constructs string of <nLength> copies of character <ch>
225 wxString::wxString(wxChar ch
, size_t nLength
)
230 AllocBuffer(nLength
);
233 // memset only works on char
234 for (size_t n
=0; n
<nLength
; n
++) m_pchData
[n
] = ch
;
236 memset(m_pchData
, ch
, nLength
);
241 // takes nLength elements of psz starting at nPos
242 void wxString::InitWith(const wxChar
*psz
, size_t nPos
, size_t nLength
)
246 wxASSERT( nPos
<= wxStrlen(psz
) );
248 if ( nLength
== wxSTRING_MAXLEN
)
249 nLength
= wxStrlen(psz
+ nPos
);
251 STATISTICS_ADD(InitialLength
, nLength
);
254 // trailing '\0' is written in AllocBuffer()
255 AllocBuffer(nLength
);
256 memcpy(m_pchData
, psz
+ nPos
, nLength
*sizeof(wxChar
));
260 #ifdef wxSTD_STRING_COMPATIBILITY
262 // poor man's iterators are "void *" pointers
263 wxString::wxString(const void *pStart
, const void *pEnd
)
265 InitWith((const wxChar
*)pStart
, 0,
266 (const wxChar
*)pEnd
- (const wxChar
*)pStart
);
269 #endif //std::string compatibility
273 // from multibyte string
274 wxString::wxString(const char *psz
, wxMBConv
& conv
, size_t nLength
)
276 // first get necessary size
277 size_t nLen
= psz
? conv
.MB2WC((wchar_t *) NULL
, psz
, 0) : 0;
279 // nLength is number of *Unicode* characters here!
280 if ((nLen
!= (size_t)-1) && (nLen
> nLength
))
284 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
286 conv
.MB2WC(m_pchData
, psz
, nLen
);
297 wxString::wxString(const wchar_t *pwz
)
299 // first get necessary size
300 size_t nLen
= pwz
? wxWC2MB((char *) NULL
, pwz
, 0) : 0;
303 if ( (nLen
!= 0) && (nLen
!= (size_t)-1) ) {
305 wxWC2MB(m_pchData
, pwz
, nLen
);
315 // ---------------------------------------------------------------------------
317 // ---------------------------------------------------------------------------
319 // allocates memory needed to store a C string of length nLen
320 void wxString::AllocBuffer(size_t nLen
)
322 wxASSERT( nLen
> 0 ); //
323 wxASSERT( nLen
<= INT_MAX
-1 ); // max size (enough room for 1 extra)
325 STATISTICS_ADD(Length
, nLen
);
328 // 1) one extra character for '\0' termination
329 // 2) sizeof(wxStringData) for housekeeping info
330 wxStringData
* pData
= (wxStringData
*)
331 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxChar
));
333 pData
->nDataLength
= nLen
;
334 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
335 m_pchData
= pData
->data(); // data starts after wxStringData
336 m_pchData
[nLen
] = _T('\0');
339 // must be called before changing this string
340 void wxString::CopyBeforeWrite()
342 wxStringData
* pData
= GetStringData();
344 if ( pData
->IsShared() ) {
345 pData
->Unlock(); // memory not freed because shared
346 size_t nLen
= pData
->nDataLength
;
348 memcpy(m_pchData
, pData
->data(), nLen
*sizeof(wxChar
));
351 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
354 // must be called before replacing contents of this string
355 void wxString::AllocBeforeWrite(size_t nLen
)
357 wxASSERT( nLen
!= 0 ); // doesn't make any sense
359 // must not share string and must have enough space
360 wxStringData
* pData
= GetStringData();
361 if ( pData
->IsShared() || (nLen
> pData
->nAllocLength
) ) {
362 // can't work with old buffer, get new one
367 // update the string length
368 pData
->nDataLength
= nLen
;
371 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
374 // allocate enough memory for nLen characters
375 void wxString::Alloc(size_t nLen
)
377 wxStringData
*pData
= GetStringData();
378 if ( pData
->nAllocLength
<= nLen
) {
379 if ( pData
->IsEmpty() ) {
382 wxStringData
* pData
= (wxStringData
*)
383 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
385 pData
->nDataLength
= 0;
386 pData
->nAllocLength
= nLen
;
387 m_pchData
= pData
->data(); // data starts after wxStringData
388 m_pchData
[0u] = _T('\0');
390 else if ( pData
->IsShared() ) {
391 pData
->Unlock(); // memory not freed because shared
392 size_t nOldLen
= pData
->nDataLength
;
394 memcpy(m_pchData
, pData
->data(), nOldLen
*sizeof(wxChar
));
399 wxStringData
*p
= (wxStringData
*)
400 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxChar
));
403 // @@@ what to do on memory error?
407 // it's not important if the pointer changed or not (the check for this
408 // is not faster than assigning to m_pchData in all cases)
409 p
->nAllocLength
= nLen
;
410 m_pchData
= p
->data();
413 //else: we've already got enough
416 // shrink to minimal size (releasing extra memory)
417 void wxString::Shrink()
419 wxStringData
*pData
= GetStringData();
421 // this variable is unused in release build, so avoid the compiler warning by
422 // just not declaring it
426 realloc(pData
, sizeof(wxStringData
) + (pData
->nDataLength
+ 1)*sizeof(wxChar
));
428 wxASSERT( p
!= NULL
); // can't free memory?
429 wxASSERT( p
== pData
); // we're decrementing the size - block shouldn't move!
432 // get the pointer to writable buffer of (at least) nLen bytes
433 wxChar
*wxString::GetWriteBuf(size_t nLen
)
435 AllocBeforeWrite(nLen
);
437 wxASSERT( GetStringData()->nRefs
== 1 );
438 GetStringData()->Validate(FALSE
);
443 // put string back in a reasonable state after GetWriteBuf
444 void wxString::UngetWriteBuf()
446 GetStringData()->nDataLength
= wxStrlen(m_pchData
);
447 GetStringData()->Validate(TRUE
);
450 // ---------------------------------------------------------------------------
452 // ---------------------------------------------------------------------------
454 // all functions are inline in string.h
456 // ---------------------------------------------------------------------------
457 // assignment operators
458 // ---------------------------------------------------------------------------
460 // helper function: does real copy
461 void wxString::AssignCopy(size_t nSrcLen
, const wxChar
*pszSrcData
)
463 if ( nSrcLen
== 0 ) {
467 AllocBeforeWrite(nSrcLen
);
468 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
469 GetStringData()->nDataLength
= nSrcLen
;
470 m_pchData
[nSrcLen
] = _T('\0');
474 // assigns one string to another
475 wxString
& wxString::operator=(const wxString
& stringSrc
)
477 wxASSERT( stringSrc
.GetStringData()->IsValid() );
479 // don't copy string over itself
480 if ( m_pchData
!= stringSrc
.m_pchData
) {
481 if ( stringSrc
.GetStringData()->IsEmpty() ) {
486 GetStringData()->Unlock();
487 m_pchData
= stringSrc
.m_pchData
;
488 GetStringData()->Lock();
495 // assigns a single character
496 wxString
& wxString::operator=(wxChar ch
)
503 wxString
& wxString::operator=(const wxChar
*psz
)
505 AssignCopy(wxStrlen(psz
), psz
);
511 // same as 'signed char' variant
512 wxString
& wxString::operator=(const unsigned char* psz
)
514 *this = (const char *)psz
;
519 wxString
& wxString::operator=(const wchar_t *pwz
)
529 // ---------------------------------------------------------------------------
530 // string concatenation
531 // ---------------------------------------------------------------------------
533 // add something to this string
534 void wxString::ConcatSelf(int nSrcLen
, const wxChar
*pszSrcData
)
536 STATISTICS_ADD(SummandLength
, nSrcLen
);
538 // concatenating an empty string is a NOP
540 wxStringData
*pData
= GetStringData();
541 size_t nLen
= pData
->nDataLength
;
542 size_t nNewLen
= nLen
+ nSrcLen
;
544 // alloc new buffer if current is too small
545 if ( pData
->IsShared() ) {
546 STATISTICS_ADD(ConcatHit
, 0);
548 // we have to allocate another buffer
549 wxStringData
* pOldData
= GetStringData();
550 AllocBuffer(nNewLen
);
551 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxChar
));
554 else if ( nNewLen
> pData
->nAllocLength
) {
555 STATISTICS_ADD(ConcatHit
, 0);
557 // we have to grow the buffer
561 STATISTICS_ADD(ConcatHit
, 1);
563 // the buffer is already big enough
566 // should be enough space
567 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
569 // fast concatenation - all is done in our buffer
570 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxChar
));
572 m_pchData
[nNewLen
] = _T('\0'); // put terminating '\0'
573 GetStringData()->nDataLength
= nNewLen
; // and fix the length
575 //else: the string to append was empty
579 * concatenation functions come in 5 flavours:
581 * char + string and string + char
582 * C str + string and string + C str
585 wxString
operator+(const wxString
& string1
, const wxString
& string2
)
587 wxASSERT( string1
.GetStringData()->IsValid() );
588 wxASSERT( string2
.GetStringData()->IsValid() );
590 wxString s
= string1
;
596 wxString
operator+(const wxString
& string
, wxChar ch
)
598 wxASSERT( string
.GetStringData()->IsValid() );
606 wxString
operator+(wxChar ch
, const wxString
& string
)
608 wxASSERT( string
.GetStringData()->IsValid() );
616 wxString
operator+(const wxString
& string
, const wxChar
*psz
)
618 wxASSERT( string
.GetStringData()->IsValid() );
621 s
.Alloc(wxStrlen(psz
) + string
.Len());
628 wxString
operator+(const wxChar
*psz
, const wxString
& string
)
630 wxASSERT( string
.GetStringData()->IsValid() );
633 s
.Alloc(wxStrlen(psz
) + string
.Len());
640 // ===========================================================================
641 // other common string functions
642 // ===========================================================================
644 // ---------------------------------------------------------------------------
645 // simple sub-string extraction
646 // ---------------------------------------------------------------------------
648 // helper function: clone the data attached to this string
649 void wxString::AllocCopy(wxString
& dest
, int nCopyLen
, int nCopyIndex
) const
651 if ( nCopyLen
== 0 ) {
655 dest
.AllocBuffer(nCopyLen
);
656 memcpy(dest
.m_pchData
, m_pchData
+ nCopyIndex
, nCopyLen
*sizeof(wxChar
));
660 // extract string of length nCount starting at nFirst
661 wxString
wxString::Mid(size_t nFirst
, size_t nCount
) const
663 wxStringData
*pData
= GetStringData();
664 size_t nLen
= pData
->nDataLength
;
666 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
667 if ( nCount
== wxSTRING_MAXLEN
)
669 nCount
= nLen
- nFirst
;
672 // out-of-bounds requests return sensible things
673 if ( nFirst
+ nCount
> nLen
)
675 nCount
= nLen
- nFirst
;
680 // AllocCopy() will return empty string
685 AllocCopy(dest
, nCount
, nFirst
);
690 // extract nCount last (rightmost) characters
691 wxString
wxString::Right(size_t nCount
) const
693 if ( nCount
> (size_t)GetStringData()->nDataLength
)
694 nCount
= GetStringData()->nDataLength
;
697 AllocCopy(dest
, nCount
, GetStringData()->nDataLength
- nCount
);
701 // get all characters after the last occurence of ch
702 // (returns the whole string if ch not found)
703 wxString
wxString::AfterLast(wxChar ch
) const
706 int iPos
= Find(ch
, TRUE
);
707 if ( iPos
== wxNOT_FOUND
)
710 str
= c_str() + iPos
+ 1;
715 // extract nCount first (leftmost) characters
716 wxString
wxString::Left(size_t nCount
) const
718 if ( nCount
> (size_t)GetStringData()->nDataLength
)
719 nCount
= GetStringData()->nDataLength
;
722 AllocCopy(dest
, nCount
, 0);
726 // get all characters before the first occurence of ch
727 // (returns the whole string if ch not found)
728 wxString
wxString::BeforeFirst(wxChar ch
) const
731 for ( const wxChar
*pc
= m_pchData
; *pc
!= _T('\0') && *pc
!= ch
; pc
++ )
737 /// get all characters before the last occurence of ch
738 /// (returns empty string if ch not found)
739 wxString
wxString::BeforeLast(wxChar ch
) const
742 int iPos
= Find(ch
, TRUE
);
743 if ( iPos
!= wxNOT_FOUND
&& iPos
!= 0 )
744 str
= wxString(c_str(), iPos
);
749 /// get all characters after the first occurence of ch
750 /// (returns empty string if ch not found)
751 wxString
wxString::AfterFirst(wxChar ch
) const
755 if ( iPos
!= wxNOT_FOUND
)
756 str
= c_str() + iPos
+ 1;
761 // replace first (or all) occurences of some substring with another one
762 size_t wxString::Replace(const wxChar
*szOld
, const wxChar
*szNew
, bool bReplaceAll
)
764 size_t uiCount
= 0; // count of replacements made
766 size_t uiOldLen
= wxStrlen(szOld
);
769 const wxChar
*pCurrent
= m_pchData
;
770 const wxChar
*pSubstr
;
771 while ( *pCurrent
!= _T('\0') ) {
772 pSubstr
= wxStrstr(pCurrent
, szOld
);
773 if ( pSubstr
== NULL
) {
774 // strTemp is unused if no replacements were made, so avoid the copy
778 strTemp
+= pCurrent
; // copy the rest
779 break; // exit the loop
782 // take chars before match
783 strTemp
.ConcatSelf(pSubstr
- pCurrent
, pCurrent
);
785 pCurrent
= pSubstr
+ uiOldLen
; // restart after match
790 if ( !bReplaceAll
) {
791 strTemp
+= pCurrent
; // copy the rest
792 break; // exit the loop
797 // only done if there were replacements, otherwise would have returned above
803 bool wxString::IsAscii() const
805 const wxChar
*s
= (const wxChar
*) *this;
807 if(!isascii(*s
)) return(FALSE
);
813 bool wxString::IsWord() const
815 const wxChar
*s
= (const wxChar
*) *this;
817 if(!wxIsalpha(*s
)) return(FALSE
);
823 bool wxString::IsNumber() const
825 const wxChar
*s
= (const wxChar
*) *this;
827 if(!wxIsdigit(*s
)) return(FALSE
);
833 wxString
wxString::Strip(stripType w
) const
836 if ( w
& leading
) s
.Trim(FALSE
);
837 if ( w
& trailing
) s
.Trim(TRUE
);
841 // ---------------------------------------------------------------------------
843 // ---------------------------------------------------------------------------
845 wxString
& wxString::MakeUpper()
849 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
850 *p
= (wxChar
)wxToupper(*p
);
855 wxString
& wxString::MakeLower()
859 for ( wxChar
*p
= m_pchData
; *p
; p
++ )
860 *p
= (wxChar
)wxTolower(*p
);
865 // ---------------------------------------------------------------------------
866 // trimming and padding
867 // ---------------------------------------------------------------------------
869 // trims spaces (in the sense of isspace) from left or right side
870 wxString
& wxString::Trim(bool bFromRight
)
872 // first check if we're going to modify the string at all
875 (bFromRight
&& wxIsspace(GetChar(Len() - 1))) ||
876 (!bFromRight
&& wxIsspace(GetChar(0u)))
880 // ok, there is at least one space to trim
885 // find last non-space character
886 wxChar
*psz
= m_pchData
+ GetStringData()->nDataLength
- 1;
887 while ( wxIsspace(*psz
) && (psz
>= m_pchData
) )
890 // truncate at trailing space start
892 GetStringData()->nDataLength
= psz
- m_pchData
;
896 // find first non-space character
897 const wxChar
*psz
= m_pchData
;
898 while ( wxIsspace(*psz
) )
901 // fix up data and length
902 int nDataLength
= GetStringData()->nDataLength
- (psz
- (const wxChar
*) m_pchData
);
903 memmove(m_pchData
, psz
, (nDataLength
+ 1)*sizeof(wxChar
));
904 GetStringData()->nDataLength
= nDataLength
;
911 // adds nCount characters chPad to the string from either side
912 wxString
& wxString::Pad(size_t nCount
, wxChar chPad
, bool bFromRight
)
914 wxString
s(chPad
, nCount
);
927 // truncate the string
928 wxString
& wxString::Truncate(size_t uiLen
)
930 if ( uiLen
< Len() ) {
933 *(m_pchData
+ uiLen
) = _T('\0');
934 GetStringData()->nDataLength
= uiLen
;
936 //else: nothing to do, string is already short enough
941 // ---------------------------------------------------------------------------
942 // finding (return wxNOT_FOUND if not found and index otherwise)
943 // ---------------------------------------------------------------------------
946 int wxString::Find(wxChar ch
, bool bFromEnd
) const
948 const wxChar
*psz
= bFromEnd
? wxStrrchr(m_pchData
, ch
) : wxStrchr(m_pchData
, ch
);
950 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
953 // find a sub-string (like strstr)
954 int wxString::Find(const wxChar
*pszSub
) const
956 const wxChar
*psz
= wxStrstr(m_pchData
, pszSub
);
958 return (psz
== NULL
) ? wxNOT_FOUND
: psz
- (const wxChar
*) m_pchData
;
961 // ---------------------------------------------------------------------------
962 // stream-like operators
963 // ---------------------------------------------------------------------------
964 wxString
& wxString::operator<<(int i
)
967 res
.Printf(_T("%d"), i
);
969 return (*this) << res
;
972 wxString
& wxString::operator<<(float f
)
975 res
.Printf(_T("%f"), f
);
977 return (*this) << res
;
980 wxString
& wxString::operator<<(double d
)
983 res
.Printf(_T("%g"), d
);
985 return (*this) << res
;
988 // ---------------------------------------------------------------------------
990 // ---------------------------------------------------------------------------
991 int wxString::Printf(const wxChar
*pszFormat
, ...)
994 va_start(argptr
, pszFormat
);
996 int iLen
= PrintfV(pszFormat
, argptr
);
1003 int wxString::PrintfV(const wxChar
* pszFormat
, va_list argptr
)
1005 // static buffer to avoid dynamic memory allocation each time
1006 char s_szScratch
[1024]; // using static buffer causes internal compiler err
1009 // protect the static buffer
1010 static wxCriticalSection critsect
;
1011 wxCriticalSectionLocker
lock(critsect
);
1015 #if wxUSE_EXPERIMENTAL_PRINTF
1016 // the new implementation
1019 for (size_t n
= 0; pszFormat
[n
]; n
++)
1020 if (pszFormat
[n
] == _T('%')) {
1021 static char s_szFlags
[256] = "%";
1023 bool adj_left
= FALSE
, in_prec
= FALSE
,
1024 prec_dot
= FALSE
, done
= FALSE
;
1026 size_t min_width
= 0, max_width
= wxSTRING_MAXLEN
;
1028 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1029 switch (pszFormat
[++n
]) {
1043 s_szFlags
[flagofs
++] = pszFormat
[n
];
1048 s_szFlags
[flagofs
++] = pszFormat
[n
];
1055 // dot will be auto-added to s_szFlags if non-negative number follows
1060 s_szFlags
[flagofs
++] = pszFormat
[n
];
1065 s_szFlags
[flagofs
++] = pszFormat
[n
];
1071 s_szFlags
[flagofs
++] = pszFormat
[n
];
1076 s_szFlags
[flagofs
++] = pszFormat
[n
];
1080 int len
= va_arg(argptr
, int);
1087 adj_left
= !adj_left
;
1088 s_szFlags
[flagofs
++] = '-';
1093 flagofs
+= ::sprintf(s_szFlags
+flagofs
,"%d",len
);
1096 case _T('1'): case _T('2'): case _T('3'):
1097 case _T('4'): case _T('5'): case _T('6'):
1098 case _T('7'): case _T('8'): case _T('9'):
1102 while ((pszFormat
[n
]>=_T('0')) && (pszFormat
[n
]<=_T('9'))) {
1103 s_szFlags
[flagofs
++] = pszFormat
[n
];
1104 len
= len
*10 + (pszFormat
[n
] - _T('0'));
1107 if (in_prec
) max_width
= len
;
1108 else min_width
= len
;
1109 n
--; // the main loop pre-increments n again
1119 s_szFlags
[flagofs
++] = pszFormat
[n
];
1120 s_szFlags
[flagofs
] = '\0';
1122 int val
= va_arg(argptr
, int);
1123 ::sprintf(s_szScratch
, s_szFlags
, val
);
1125 else if (ilen
== -1) {
1126 short int val
= va_arg(argptr
, short int);
1127 ::sprintf(s_szScratch
, s_szFlags
, val
);
1129 else if (ilen
== 1) {
1130 long int val
= va_arg(argptr
, long int);
1131 ::sprintf(s_szScratch
, s_szFlags
, val
);
1133 else if (ilen
== 2) {
1134 #if SIZEOF_LONG_LONG
1135 long long int val
= va_arg(argptr
, long long int);
1136 ::sprintf(s_szScratch
, s_szFlags
, val
);
1138 long int val
= va_arg(argptr
, long int);
1139 ::sprintf(s_szScratch
, s_szFlags
, val
);
1142 else if (ilen
== 3) {
1143 size_t val
= va_arg(argptr
, size_t);
1144 ::sprintf(s_szScratch
, s_szFlags
, val
);
1146 *this += wxString(s_szScratch
);
1155 s_szFlags
[flagofs
++] = pszFormat
[n
];
1156 s_szFlags
[flagofs
] = '\0';
1158 long double val
= va_arg(argptr
, long double);
1159 ::sprintf(s_szScratch
, s_szFlags
, val
);
1161 double val
= va_arg(argptr
, double);
1162 ::sprintf(s_szScratch
, s_szFlags
, val
);
1164 *this += wxString(s_szScratch
);
1169 void *val
= va_arg(argptr
, void *);
1171 s_szFlags
[flagofs
++] = pszFormat
[n
];
1172 s_szFlags
[flagofs
] = '\0';
1173 ::sprintf(s_szScratch
, s_szFlags
, val
);
1174 *this += wxString(s_szScratch
);
1180 wxChar val
= va_arg(argptr
, int);
1181 // we don't need to honor padding here, do we?
1188 // wx extension: we'll let %hs mean non-Unicode strings
1189 char *val
= va_arg(argptr
, char *);
1191 // ASCII->Unicode constructor handles max_width right
1192 wxString
s(val
, wxConvLibc
, max_width
);
1194 size_t len
= wxSTRING_MAXLEN
;
1196 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1197 } else val
= _T("(null)");
1198 wxString
s(val
, len
);
1200 if (s
.Len() < min_width
)
1201 s
.Pad(min_width
- s
.Len(), _T(' '), adj_left
);
1204 wxChar
*val
= va_arg(argptr
, wxChar
*);
1205 size_t len
= wxSTRING_MAXLEN
;
1207 for (len
= 0; val
[len
] && (len
<max_width
); len
++);
1208 } else val
= _T("(null)");
1209 wxString
s(val
, len
);
1210 if (s
.Len() < min_width
)
1211 s
.Pad(min_width
- s
.Len(), _T(' '), adj_left
);
1218 int *val
= va_arg(argptr
, int *);
1221 else if (ilen
== -1) {
1222 short int *val
= va_arg(argptr
, short int *);
1225 else if (ilen
>= 1) {
1226 long int *val
= va_arg(argptr
, long int *);
1232 if (wxIsalpha(pszFormat
[n
]))
1233 // probably some flag not taken care of here yet
1234 s_szFlags
[flagofs
++] = pszFormat
[n
];
1237 *this += _T('%'); // just to pass the glibc tst-printf.c
1245 } else *this += pszFormat
[n
];
1248 // NB: wxVsnprintf() may return either less than the buffer size or -1 if there
1249 // is not enough place depending on implementation
1250 int iLen
= wxVsnprintf(s_szScratch
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
1252 if ( iLen
< (int)WXSIZEOF(s_szScratch
) ) {
1253 buffer
= s_szScratch
;
1256 int size
= WXSIZEOF(s_szScratch
) * 2;
1257 buffer
= (char *)malloc(size
);
1258 while ( buffer
!= NULL
) {
1259 iLen
= wxVsnprintf(buffer
, WXSIZEOF(s_szScratch
), pszFormat
, argptr
);
1260 if ( iLen
< size
) {
1261 // ok, there was enough space
1265 // still not enough, double it again
1266 buffer
= (char *)realloc(buffer
, size
*= 2);
1278 if ( buffer
!= s_szScratch
)
1285 // ----------------------------------------------------------------------------
1286 // misc other operations
1287 // ----------------------------------------------------------------------------
1288 bool wxString::Matches(const wxChar
*pszMask
) const
1290 // check char by char
1291 const wxChar
*pszTxt
;
1292 for ( pszTxt
= c_str(); *pszMask
!= _T('\0'); pszMask
++, pszTxt
++ ) {
1293 switch ( *pszMask
) {
1295 if ( *pszTxt
== _T('\0') )
1304 // ignore special chars immediately following this one
1305 while ( *pszMask
== _T('*') || *pszMask
== _T('?') )
1308 // if there is nothing more, match
1309 if ( *pszMask
== _T('\0') )
1312 // are there any other metacharacters in the mask?
1314 const wxChar
*pEndMask
= wxStrpbrk(pszMask
, _T("*?"));
1316 if ( pEndMask
!= NULL
) {
1317 // we have to match the string between two metachars
1318 uiLenMask
= pEndMask
- pszMask
;
1321 // we have to match the remainder of the string
1322 uiLenMask
= wxStrlen(pszMask
);
1325 wxString
strToMatch(pszMask
, uiLenMask
);
1326 const wxChar
* pMatch
= wxStrstr(pszTxt
, strToMatch
);
1327 if ( pMatch
== NULL
)
1330 // -1 to compensate "++" in the loop
1331 pszTxt
= pMatch
+ uiLenMask
- 1;
1332 pszMask
+= uiLenMask
- 1;
1337 if ( *pszMask
!= *pszTxt
)
1343 // match only if nothing left
1344 return *pszTxt
== _T('\0');
1347 // Count the number of chars
1348 int wxString::Freq(wxChar ch
) const
1352 for (int i
= 0; i
< len
; i
++)
1354 if (GetChar(i
) == ch
)
1360 // convert to upper case, return the copy of the string
1361 wxString
wxString::Upper() const
1362 { wxString
s(*this); return s
.MakeUpper(); }
1364 // convert to lower case, return the copy of the string
1365 wxString
wxString::Lower() const { wxString
s(*this); return s
.MakeLower(); }
1367 int wxString::sprintf(const wxChar
*pszFormat
, ...)
1370 va_start(argptr
, pszFormat
);
1371 int iLen
= PrintfV(pszFormat
, argptr
);
1376 // ---------------------------------------------------------------------------
1377 // standard C++ library string functions
1378 // ---------------------------------------------------------------------------
1379 #ifdef wxSTD_STRING_COMPATIBILITY
1381 wxString
& wxString::insert(size_t nPos
, const wxString
& str
)
1383 wxASSERT( str
.GetStringData()->IsValid() );
1384 wxASSERT( nPos
<= Len() );
1386 if ( !str
.IsEmpty() ) {
1388 wxChar
*pc
= strTmp
.GetWriteBuf(Len() + str
.Len());
1389 wxStrncpy(pc
, c_str(), nPos
);
1390 wxStrcpy(pc
+ nPos
, str
);
1391 wxStrcpy(pc
+ nPos
+ str
.Len(), c_str() + nPos
);
1392 strTmp
.UngetWriteBuf();
1399 size_t wxString::find(const wxString
& str
, size_t nStart
) const
1401 wxASSERT( str
.GetStringData()->IsValid() );
1402 wxASSERT( nStart
<= Len() );
1404 const wxChar
*p
= wxStrstr(c_str() + nStart
, str
);
1406 return p
== NULL
? npos
: p
- c_str();
1409 // VC++ 1.5 can't cope with the default argument in the header.
1410 #if !defined(__VISUALC__) || defined(__WIN32__)
1411 size_t wxString::find(const wxChar
* sz
, size_t nStart
, size_t n
) const
1413 return find(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1417 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1418 #if !defined(__BORLANDC__)
1419 size_t wxString::find(wxChar ch
, size_t nStart
) const
1421 wxASSERT( nStart
<= Len() );
1423 const wxChar
*p
= wxStrchr(c_str() + nStart
, ch
);
1425 return p
== NULL
? npos
: p
- c_str();
1429 size_t wxString::rfind(const wxString
& str
, size_t nStart
) const
1431 wxASSERT( str
.GetStringData()->IsValid() );
1432 wxASSERT( nStart
<= Len() );
1434 // TODO could be made much quicker than that
1435 const wxChar
*p
= c_str() + (nStart
== npos
? Len() : nStart
);
1436 while ( p
>= c_str() + str
.Len() ) {
1437 if ( wxStrncmp(p
- str
.Len(), str
, str
.Len()) == 0 )
1438 return p
- str
.Len() - c_str();
1445 // VC++ 1.5 can't cope with the default argument in the header.
1446 #if !defined(__VISUALC__) || defined(__WIN32__)
1447 size_t wxString::rfind(const wxChar
* sz
, size_t nStart
, size_t n
) const
1449 return rfind(wxString(sz
, n
== npos
? 0 : n
), nStart
);
1452 size_t wxString::rfind(wxChar ch
, size_t nStart
) const
1454 if ( nStart
== npos
)
1460 wxASSERT( nStart
<= Len() );
1463 const wxChar
*p
= wxStrrchr(c_str(), ch
);
1468 size_t result
= p
- c_str();
1469 return ( result
> nStart
) ? npos
: result
;
1473 size_t wxString::find_first_of(const wxChar
* sz
, size_t nStart
) const
1475 const wxChar
*start
= c_str() + nStart
;
1476 const wxChar
*firstOf
= wxStrpbrk(start
, sz
);
1478 return firstOf
- start
;
1483 size_t wxString::find_last_of(const wxChar
* sz
, size_t nStart
) const
1485 if ( nStart
== npos
)
1491 wxASSERT( nStart
<= Len() );
1494 for ( const wxChar
*p
= c_str() + length() - 1; p
>= c_str(); p
-- )
1496 if ( wxStrchr(sz
, *p
) )
1503 size_t wxString::find_first_not_of(const wxChar
* sz
, size_t nStart
) const
1505 if ( nStart
== npos
)
1511 wxASSERT( nStart
<= Len() );
1514 size_t nAccept
= wxStrspn(c_str() + nStart
, sz
);
1515 if ( nAccept
>= length() - nStart
)
1521 size_t wxString::find_first_not_of(wxChar ch
, size_t nStart
) const
1523 wxASSERT( nStart
<= Len() );
1525 for ( const wxChar
*p
= c_str() + nStart
; *p
; p
++ )
1534 size_t wxString::find_last_not_of(const wxChar
* sz
, size_t nStart
) const
1536 if ( nStart
== npos
)
1542 wxASSERT( nStart
<= Len() );
1545 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1547 if ( !wxStrchr(sz
, *p
) )
1554 size_t wxString::find_last_not_of(wxChar ch
, size_t nStart
) const
1556 if ( nStart
== npos
)
1562 wxASSERT( nStart
<= Len() );
1565 for ( const wxChar
*p
= c_str() + nStart
- 1; p
>= c_str(); p
-- )
1574 wxString
wxString::substr(size_t nStart
, size_t nLen
) const
1576 // npos means 'take all'
1580 wxASSERT( nStart
+ nLen
<= Len() );
1582 return wxString(c_str() + nStart
, nLen
== npos
? 0 : nLen
);
1585 wxString
& wxString::erase(size_t nStart
, size_t nLen
)
1587 wxString
strTmp(c_str(), nStart
);
1588 if ( nLen
!= npos
) {
1589 wxASSERT( nStart
+ nLen
<= Len() );
1591 strTmp
.append(c_str() + nStart
+ nLen
);
1598 wxString
& wxString::replace(size_t nStart
, size_t nLen
, const wxChar
*sz
)
1600 wxASSERT( nStart
+ nLen
<= wxStrlen(sz
) );
1604 strTmp
.append(c_str(), nStart
);
1606 strTmp
.append(c_str() + nStart
+ nLen
);
1612 wxString
& wxString::replace(size_t nStart
, size_t nLen
, size_t nCount
, wxChar ch
)
1614 return replace(nStart
, nLen
, wxString(ch
, nCount
));
1617 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1618 const wxString
& str
, size_t nStart2
, size_t nLen2
)
1620 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
1623 wxString
& wxString::replace(size_t nStart
, size_t nLen
,
1624 const wxChar
* sz
, size_t nCount
)
1626 return replace(nStart
, nLen
, wxString(sz
, nCount
));
1629 #endif //std::string compatibility
1631 // ============================================================================
1633 // ============================================================================
1635 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1636 #define ARRAY_MAXSIZE_INCREMENT 4096
1637 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1638 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1641 #define STRING(p) ((wxString *)(&(p)))
1644 wxArrayString::wxArrayString()
1648 m_pItems
= (wxChar
**) NULL
;
1652 wxArrayString::wxArrayString(const wxArrayString
& src
)
1656 m_pItems
= (wxChar
**) NULL
;
1661 // assignment operator
1662 wxArrayString
& wxArrayString::operator=(const wxArrayString
& src
)
1667 if ( src
.m_nCount
> ARRAY_DEFAULT_INITIAL_SIZE
)
1668 Alloc(src
.m_nCount
);
1670 // we can't just copy the pointers here because otherwise we would share
1671 // the strings with another array
1672 for ( size_t n
= 0; n
< src
.m_nCount
; n
++ )
1675 if ( m_nCount
!= 0 )
1676 memcpy(m_pItems
, src
.m_pItems
, m_nCount
*sizeof(wxChar
*));
1682 void wxArrayString::Grow()
1684 // only do it if no more place
1685 if( m_nCount
== m_nSize
) {
1686 if( m_nSize
== 0 ) {
1687 // was empty, alloc some memory
1688 m_nSize
= ARRAY_DEFAULT_INITIAL_SIZE
;
1689 m_pItems
= new wxChar
*[m_nSize
];
1692 // otherwise when it's called for the first time, nIncrement would be 0
1693 // and the array would never be expanded
1694 #if defined(__VISAGECPP__)
1695 int array_size
= ARRAY_DEFAULT_INITIAL_SIZE
;
1696 wxASSERT( array_size
!= 0 );
1698 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE
!= 0 );
1701 // add 50% but not too much
1702 size_t nIncrement
= m_nSize
< ARRAY_DEFAULT_INITIAL_SIZE
1703 ? ARRAY_DEFAULT_INITIAL_SIZE
: m_nSize
>> 1;
1704 if ( nIncrement
> ARRAY_MAXSIZE_INCREMENT
)
1705 nIncrement
= ARRAY_MAXSIZE_INCREMENT
;
1706 m_nSize
+= nIncrement
;
1707 wxChar
**pNew
= new wxChar
*[m_nSize
];
1709 // copy data to new location
1710 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1712 // delete old memory (but do not release the strings!)
1713 wxDELETEA(m_pItems
);
1720 void wxArrayString::Free()
1722 for ( size_t n
= 0; n
< m_nCount
; n
++ ) {
1723 STRING(m_pItems
[n
])->GetStringData()->Unlock();
1727 // deletes all the strings from the list
1728 void wxArrayString::Empty()
1735 // as Empty, but also frees memory
1736 void wxArrayString::Clear()
1743 wxDELETEA(m_pItems
);
1747 wxArrayString::~wxArrayString()
1751 wxDELETEA(m_pItems
);
1754 // pre-allocates memory (frees the previous data!)
1755 void wxArrayString::Alloc(size_t nSize
)
1757 wxASSERT( nSize
> 0 );
1759 // only if old buffer was not big enough
1760 if ( nSize
> m_nSize
) {
1762 wxDELETEA(m_pItems
);
1763 m_pItems
= new wxChar
*[nSize
];
1770 // minimizes the memory usage by freeing unused memory
1771 void wxArrayString::Shrink()
1773 // only do it if we have some memory to free
1774 if( m_nCount
< m_nSize
) {
1775 // allocates exactly as much memory as we need
1776 wxChar
**pNew
= new wxChar
*[m_nCount
];
1778 // copy data to new location
1779 memcpy(pNew
, m_pItems
, m_nCount
*sizeof(wxChar
*));
1785 // searches the array for an item (forward or backwards)
1786 int wxArrayString::Index(const wxChar
*sz
, bool bCase
, bool bFromEnd
) const
1789 if ( m_nCount
> 0 ) {
1790 size_t ui
= m_nCount
;
1792 if ( STRING(m_pItems
[--ui
])->IsSameAs(sz
, bCase
) )
1799 for( size_t ui
= 0; ui
< m_nCount
; ui
++ ) {
1800 if( STRING(m_pItems
[ui
])->IsSameAs(sz
, bCase
) )
1808 // add item at the end
1809 void wxArrayString::Add(const wxString
& str
)
1811 wxASSERT( str
.GetStringData()->IsValid() );
1815 // the string data must not be deleted!
1816 str
.GetStringData()->Lock();
1817 m_pItems
[m_nCount
++] = (wxChar
*)str
.c_str();
1820 // add item at the given position
1821 void wxArrayString::Insert(const wxString
& str
, size_t nIndex
)
1823 wxASSERT( str
.GetStringData()->IsValid() );
1825 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Insert") );
1829 memmove(&m_pItems
[nIndex
+ 1], &m_pItems
[nIndex
],
1830 (m_nCount
- nIndex
)*sizeof(wxChar
*));
1832 str
.GetStringData()->Lock();
1833 m_pItems
[nIndex
] = (wxChar
*)str
.c_str();
1838 // removes item from array (by index)
1839 void wxArrayString::Remove(size_t nIndex
)
1841 wxCHECK_RET( nIndex
<= m_nCount
, _("bad index in wxArrayString::Remove") );
1844 Item(nIndex
).GetStringData()->Unlock();
1846 memmove(&m_pItems
[nIndex
], &m_pItems
[nIndex
+ 1],
1847 (m_nCount
- nIndex
- 1)*sizeof(wxChar
*));
1851 // removes item from array (by value)
1852 void wxArrayString::Remove(const wxChar
*sz
)
1854 int iIndex
= Index(sz
);
1856 wxCHECK_RET( iIndex
!= wxNOT_FOUND
,
1857 _("removing inexistent element in wxArrayString::Remove") );
1862 // ----------------------------------------------------------------------------
1864 // ----------------------------------------------------------------------------
1866 // we can only sort one array at a time with the quick-sort based
1869 // need a critical section to protect access to gs_compareFunction and
1870 // gs_sortAscending variables
1871 static wxCriticalSection
*gs_critsectStringSort
= NULL
;
1873 // call this before the value of the global sort vars is changed/after
1874 // you're finished with them
1875 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
1876 gs_critsectStringSort = new wxCriticalSection; \
1877 gs_critsectStringSort->Enter()
1878 #define END_SORT() gs_critsectStringSort->Leave(); \
1879 delete gs_critsectStringSort; \
1880 gs_critsectStringSort = NULL
1882 #define START_SORT()
1884 #endif // wxUSE_THREADS
1886 // function to use for string comparaison
1887 static wxArrayString::CompareFunction gs_compareFunction
= NULL
;
1889 // if we don't use the compare function, this flag tells us if we sort the
1890 // array in ascending or descending order
1891 static bool gs_sortAscending
= TRUE
;
1893 // function which is called by quick sort
1894 static int LINKAGEMODE
wxStringCompareFunction(const void *first
, const void *second
)
1896 wxString
*strFirst
= (wxString
*)first
;
1897 wxString
*strSecond
= (wxString
*)second
;
1899 if ( gs_compareFunction
) {
1900 return gs_compareFunction(*strFirst
, *strSecond
);
1903 // maybe we should use wxStrcoll
1904 int result
= wxStrcmp(strFirst
->c_str(), strSecond
->c_str());
1906 return gs_sortAscending
? result
: -result
;
1910 // sort array elements using passed comparaison function
1911 void wxArrayString::Sort(CompareFunction compareFunction
)
1915 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1916 gs_compareFunction
= compareFunction
;
1923 void wxArrayString::Sort(bool reverseOrder
)
1927 wxASSERT( !gs_compareFunction
); // must have been reset to NULL
1928 gs_sortAscending
= !reverseOrder
;
1935 void wxArrayString::DoSort()
1937 // just sort the pointers using qsort() - of course it only works because
1938 // wxString() *is* a pointer to its data
1939 qsort(m_pItems
, m_nCount
, sizeof(wxChar
*), wxStringCompareFunction
);
1942 // ============================================================================
1944 // ============================================================================
1946 WXDLLEXPORT_DATA(wxMBConv
*) wxConvCurrent
= &wxConvLibc
;
1948 WXDLLEXPORT_DATA(wxMBConv
) wxConvLibc
, wxConvFile
;
1953 // ----------------------------------------------------------------------------
1954 // standard libc conversion
1955 // ----------------------------------------------------------------------------
1957 WXDLLEXPORT_DATA(wxMBConv
) wxConvLibc
;
1959 size_t wxMBConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1961 return wxMB2WC(buf
, psz
, n
);
1964 size_t wxMBConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1966 return wxWC2MB(buf
, psz
, n
);
1969 // ----------------------------------------------------------------------------
1970 // standard file conversion
1971 // ----------------------------------------------------------------------------
1973 WXDLLEXPORT_DATA(wxMBConvFile
) wxConvFile
;
1975 // just use the libc conversion for now
1976 size_t wxMBConvFile::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1978 return wxMB2WC(buf
, psz
, n
);
1981 size_t wxMBConvFile::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1983 return wxWC2MB(buf
, psz
, n
);
1986 // ----------------------------------------------------------------------------
1987 // standard gdk conversion
1988 // ----------------------------------------------------------------------------
1991 WXDLLEXPORT_DATA(wxMBConvGdk
) wxConvGdk
;
1993 #include <gdk/gdk.h>
1995 size_t wxMBConvGdk::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1998 return gdk_mbstowcs((GdkWChar
*)buf
, psz
, n
);
2000 GdkWChar
*nbuf
= new GdkWChar
[n
=strlen(psz
)];
2001 size_t len
= gdk_mbstowcs(nbuf
, psz
, n
);
2007 size_t wxMBConvGdk::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
2009 char *mbstr
= gdk_wcstombs((GdkWChar
*)psz
);
2010 size_t len
= mbstr
? strlen(mbstr
) : 0;
2012 if (len
> n
) len
= n
;
2013 memcpy(buf
, psz
, len
);
2014 if (len
< n
) buf
[len
] = 0;
2020 // ----------------------------------------------------------------------------
2022 // ----------------------------------------------------------------------------
2024 WXDLLEXPORT_DATA(wxMBConvUTF7
) wxConvUTF7
;
2027 static char utf7_setD
[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2028 "abcdefghijklmnopqrstuvwxyz"
2029 "0123456789'(),-./:?";
2030 static char utf7_setO
[]="!\"#$%&*;<=>@[]^_`{|}";
2031 static char utf7_setB
[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2032 "abcdefghijklmnopqrstuvwxyz"
2036 // TODO: write actual implementations of UTF-7 here
2037 size_t wxMBConvUTF7::MB2WC(wchar_t * WXUNUSED(buf
),
2038 const char * WXUNUSED(psz
),
2039 size_t WXUNUSED(n
)) const
2044 size_t wxMBConvUTF7::WC2MB(char * WXUNUSED(buf
),
2045 const wchar_t * WXUNUSED(psz
),
2046 size_t WXUNUSED(n
)) const
2051 // ----------------------------------------------------------------------------
2053 // ----------------------------------------------------------------------------
2055 WXDLLEXPORT_DATA(wxMBConvUTF8
) wxConvUTF8
;
2057 static unsigned long utf8_max
[]={0x7f,0x7ff,0xffff,0x1fffff,0x3ffffff,0x7fffffff,0xffffffff};
2059 size_t wxMBConvUTF8::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2063 while (*psz
&& ((!buf
) || (len
<n
))) {
2064 unsigned char cc
=*psz
++, fc
=cc
;
2066 for (cnt
=0; fc
&0x80; cnt
++) fc
<<=1;
2074 // invalid UTF-8 sequence
2077 unsigned ocnt
=cnt
-1;
2078 unsigned long res
=cc
&(0x3f>>cnt
);
2081 if ((cc
&0xC0)!=0x80) {
2082 // invalid UTF-8 sequence
2085 res
=(res
<<6)|(cc
&0x3f);
2087 if (res
<=utf8_max
[ocnt
]) {
2088 // illegal UTF-8 encoding
2091 if (buf
) *buf
++=res
;
2096 if (buf
&& (len
<n
)) *buf
= 0;
2100 size_t wxMBConvUTF8::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
2104 while (*psz
&& ((!buf
) || (len
<n
))) {
2105 unsigned long cc
=(*psz
++)&0x7fffffff;
2107 for (cnt
=0; cc
>utf8_max
[cnt
]; cnt
++);
2115 *buf
++=(-128>>cnt
)|((cc
>>(cnt
*6))&(0x3f>>cnt
));
2117 *buf
++=0x80|((cc
>>(cnt
*6))&0x3f);
2121 if (buf
&& (len
<n
)) *buf
= 0;
2125 // ----------------------------------------------------------------------------
2126 // specified character set
2127 // ----------------------------------------------------------------------------
2129 class wxCharacterSet
2132 wxArrayString names
;
2137 #include "wx/dynarray.h"
2138 #include "wx/filefn.h"
2139 #include "wx/textfile.h"
2140 #include "wx/tokenzr.h"
2141 #include "wx/utils.h"
2144 WX_DECLARE_OBJARRAY(wxCharacterSet
, wxCSArray
);
2145 #include "wx/arrimpl.cpp"
2146 WX_DEFINE_OBJARRAY(wxCSArray
);
2148 static wxCSArray wxCharsets
;
2150 static void wxLoadCharacterSets(void)
2152 static bool already_loaded
= FALSE
;
2154 if (already_loaded
) return;
2156 already_loaded
= TRUE
;
2157 #if defined(__UNIX__) && wxUSE_TEXTFILE
2158 // search through files in /usr/share/i18n/charmaps
2160 for (fname
= ::wxFindFirstFile(_T("/usr/share/i18n/charmaps/*"));
2162 fname
= ::wxFindNextFile()) {
2163 wxTextFile
cmap(fname
);
2165 wxCharacterSet
*cset
= new wxCharacterSet
;
2166 wxString comchar
,escchar
;
2167 bool in_charset
= FALSE
;
2169 // wxFprintf(stderr,_T("Loaded: %s\n"),fname.c_str());
2172 for (line
= cmap
.GetFirstLine();
2174 line
= cmap
.GetNextLine()) {
2175 // wxFprintf(stderr,_T("line contents: %s\n"),line.c_str());
2176 wxStringTokenizer
token(line
);
2177 wxString cmd
= token
.GetNextToken();
2178 if (cmd
== comchar
) {
2179 if (token
.GetNextToken() == _T("alias"))
2180 cset
->names
.Add(token
.GetNextToken());
2182 else if (cmd
== _T("<code_set_name>"))
2183 cset
->names
.Add(token
.GetNextToken());
2184 else if (cmd
== _T("<comment_char>"))
2185 comchar
= token
.GetNextToken();
2186 else if (cmd
== _T("<escape_char>"))
2187 escchar
= token
.GetNextToken();
2188 else if (cmd
== _T("<mb_cur_min>")) {
2190 cset
= (wxCharacterSet
*) NULL
;
2191 break; // we don't support multibyte charsets ourselves (yet)
2193 else if (cmd
== _T("CHARMAP")) {
2194 cset
->data
= (wchar_t *)calloc(256, sizeof(wchar_t));
2197 else if (cmd
== _T("END")) {
2198 if (token
.GetNextToken() == _T("CHARMAP"))
2201 else if (in_charset
) {
2202 // format: <NUL> /x00 <U0000> NULL (NUL)
2203 // <A> /x41 <U0041> LATIN CAPITAL LETTER A
2204 wxString hex
= token
.GetNextToken();
2205 // skip whitespace (why doesn't wxStringTokenizer do this?)
2206 while (wxIsEmpty(hex
) && token
.HasMoreTokens()) hex
= token
.GetNextToken();
2207 wxString uni
= token
.GetNextToken();
2208 // skip whitespace again
2209 while (wxIsEmpty(uni
) && token
.HasMoreTokens()) uni
= token
.GetNextToken();
2210 if ((hex
.Len() > 2) && (wxString(hex
.GetChar(0)) == escchar
) && (hex
.GetChar(1) == _T('x')) &&
2211 (uni
.Left(2) == _T("<U"))) {
2212 hex
.MakeUpper(); uni
.MakeUpper();
2213 int pos
= ::wxHexToDec(hex
.Mid(2,2));
2215 unsigned long uni1
= ::wxHexToDec(uni
.Mid(2,2));
2216 unsigned long uni2
= ::wxHexToDec(uni
.Mid(4,2));
2217 cset
->data
[pos
] = (uni1
<< 16) | uni2
;
2218 // wxFprintf(stderr,_T("char %02x mapped to %04x (%c)\n"),pos,cset->data[pos],cset->data[pos]);
2224 cset
->names
.Shrink();
2225 wxCharsets
.Add(cset
);
2230 wxCharsets
.Shrink();
2233 static wxCharacterSet
*wxFindCharacterSet(const wxChar
*charset
)
2235 if (!charset
) return (wxCharacterSet
*)NULL
;
2236 wxLoadCharacterSets();
2237 for (size_t n
=0; n
<wxCharsets
.GetCount(); n
++)
2238 if (wxCharsets
[n
].names
.Index(charset
) != wxNOT_FOUND
)
2239 return &(wxCharsets
[n
]);
2240 return (wxCharacterSet
*)NULL
;
2243 WXDLLEXPORT_DATA(wxCSConv
) wxConvLocal((const wxChar
*)NULL
);
2245 wxCSConv::wxCSConv(const wxChar
*charset
)
2247 m_name
= (wxChar
*) NULL
;
2248 m_cset
= (wxCharacterSet
*) NULL
;
2253 wxCSConv::~wxCSConv()
2255 if (m_name
) free(m_name
);
2258 void wxCSConv::SetName(const wxChar
*charset
)
2262 // first, convert the character set name to standard form
2264 if (wxString(charset
,3).CmpNoCase(_T("ISO")) == 0) {
2265 // make sure it's represented in the standard form: ISO_8859-1
2266 codeset
= _T("ISO_");
2268 if ((*charset
== _T('-')) || (*charset
== _T('_'))) charset
++;
2269 if (wxStrlen(charset
)>4) {
2270 if (wxString(charset
,4) == _T("8859")) {
2271 codeset
<< _T("8859-");
2272 if (*charset
== _T('-')) charset
++;
2277 codeset
.MakeUpper();
2278 m_name
= wxStrdup(codeset
.c_str());
2284 void wxCSConv::LoadNow()
2286 // wxPrintf(_T("Conversion request\n"));
2290 wxChar
*lang
= wxGetenv(_T("LANG"));
2291 wxChar
*dot
= lang
? wxStrchr(lang
, _T('.')) : (wxChar
*)NULL
;
2292 if (dot
) SetName(dot
+1);
2295 m_cset
= wxFindCharacterSet(m_name
);
2300 size_t wxCSConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2302 ((wxCSConv
*)this)->LoadNow(); // discard constness
2305 for (size_t c
=0; c
<n
; c
++)
2306 buf
[c
] = m_cset
->data
[(unsigned char)(psz
[c
])];
2309 for (size_t c
=0; c
<n
; c
++)
2310 buf
[c
] = (unsigned char)(psz
[c
]);
2317 size_t wxCSConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
2319 ((wxCSConv
*)this)->LoadNow(); // discard constness
2322 for (size_t c
=0; c
<n
; c
++) {
2324 for (n
=0; (n
<256) && (m_cset
->data
[n
] != psz
[c
]); n
++);
2325 buf
[c
] = (n
>0xff) ? '?' : n
;
2329 for (size_t c
=0; c
<n
; c
++)
2330 buf
[c
] = (psz
[c
]>0xff) ? '?' : psz
[c
];
2337 #endif//wxUSE_WCHAR_T
2340 const wxWCharBuffer
wxMBConv::cMB2WC(const char *psz
) const
2343 size_t nLen
= MB2WC((wchar_t *) NULL
, psz
, 0);
2344 wxWCharBuffer
buf(nLen
);
2345 MB2WC(WCSTRINGCAST buf
, psz
, nLen
);
2347 } else return wxWCharBuffer((wchar_t *) NULL
);
2350 const wxCharBuffer
wxMBConv::cWC2MB(const wchar_t *psz
) const
2353 size_t nLen
= WC2MB((char *) NULL
, psz
, 0);
2354 wxCharBuffer
buf(nLen
);
2355 WC2MB(MBSTRINGCAST buf
, psz
, nLen
);
2357 } else return wxCharBuffer((char *) NULL
);
2360 #endif//wxUSE_WCHAR_T