]> git.saurik.com Git - wxWidgets.git/blob - src/common/string.cpp
Corrected byte swapping macros.
[wxWidgets.git] / src / common / string.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: string.cpp
3 // Purpose: wxString class
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 29/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
13 #pragma implementation "string.h"
14 #endif
15
16 /*
17 * About ref counting:
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
21 */
22
23 // ===========================================================================
24 // headers, declarations, constants
25 // ===========================================================================
26
27 // For compilers that support precompilation, includes "wx.h".
28 #include "wx/wxprec.h"
29
30 #ifdef __BORLANDC__
31 #pragma hdrstop
32 #endif
33
34 #ifndef WX_PRECOMP
35 #include "wx/defs.h"
36 #include "wx/string.h"
37 #include "wx/intl.h"
38 #if wxUSE_THREADS
39 #include <wx/thread.h>
40 #endif
41 #endif
42
43 #include <ctype.h>
44 #include <string.h>
45 #include <stdlib.h>
46
47 #ifdef __SALFORDC__
48 #include <clib.h>
49 #endif
50
51 #if wxUSE_WCSRTOMBS
52 #include <wchar.h> // for wcsrtombs(), see comments where it's used
53 #endif // GNU
54
55 #ifdef WXSTRING_IS_WXOBJECT
56 IMPLEMENT_DYNAMIC_CLASS(wxString, wxObject)
57 #endif //WXSTRING_IS_WXOBJECT
58
59 // allocating extra space for each string consumes more memory but speeds up
60 // the concatenation operations (nLen is the current string's length)
61 // NB: EXTRA_ALLOC must be >= 0!
62 #define EXTRA_ALLOC (19 - nLen % 16)
63
64 // ---------------------------------------------------------------------------
65 // static class variables definition
66 // ---------------------------------------------------------------------------
67
68 #ifdef wxSTD_STRING_COMPATIBILITY
69 const size_t wxString::npos = wxSTRING_MAXLEN;
70 #endif // wxSTD_STRING_COMPATIBILITY
71
72 // ----------------------------------------------------------------------------
73 // static data
74 // ----------------------------------------------------------------------------
75
76 // for an empty string, GetStringData() will return this address: this
77 // structure has the same layout as wxStringData and it's data() method will
78 // return the empty string (dummy pointer)
79 static const struct
80 {
81 wxStringData data;
82 wxChar dummy;
83 } g_strEmpty = { {-1, 0, 0}, _T('\0') };
84
85 // empty C style string: points to 'string data' byte of g_strEmpty
86 extern const wxChar WXDLLEXPORT *g_szNul = &g_strEmpty.dummy;
87
88 // ----------------------------------------------------------------------------
89 // conditional compilation
90 // ----------------------------------------------------------------------------
91
92 // we want to find out if the current platform supports vsnprintf()-like
93 // function: for Unix this is done with configure, for Windows we test the
94 // compiler explicitly.
95 #ifdef __WXMSW__
96 #ifdef __VISUALC__
97 #define wxVsnprintf _vsnprintf
98 #endif
99 #else // !Windows
100 #ifdef HAVE_VSNPRINTF
101 #define wxVsnprintf vsnprintf
102 #endif
103 #endif // Windows/!Windows
104
105 #ifndef wxVsnprintf
106 // in this case we'll use vsprintf() (which is ANSI and thus should be
107 // always available), but it's unsafe because it doesn't check for buffer
108 // size - so give a warning
109 #define wxVsnprintf(buffer,len,format,argptr) vsprintf(buffer,format, argptr)
110
111 #if defined(__VISUALC__)
112 #pragma message("Using sprintf() because no snprintf()-like function defined")
113 #elif defined(__GNUG__) && !defined(__UNIX__)
114 #warning "Using sprintf() because no snprintf()-like function defined"
115 #elif defined(__MWERKS__)
116 #warning "Using sprintf() because no snprintf()-like function defined"
117 #endif //compiler
118 #endif // no vsnprintf
119
120 #ifdef _AIX
121 // AIX has vsnprintf, but there's no prototype in the system headers.
122 extern "C" int vsnprintf(char* str, size_t n, const char* format, va_list ap);
123 #endif
124
125 // ----------------------------------------------------------------------------
126 // global functions
127 // ----------------------------------------------------------------------------
128
129 #ifdef wxSTD_STRING_COMPATIBILITY
130
131 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
132 // iostream ones.
133 //
134 // ATTN: you can _not_ use both of these in the same program!
135
136 istream& operator>>(istream& is, wxString& WXUNUSED(str))
137 {
138 #if 0
139 int w = is.width(0);
140 if ( is.ipfx(0) ) {
141 streambuf *sb = is.rdbuf();
142 str.erase();
143 while ( true ) {
144 int ch = sb->sbumpc ();
145 if ( ch == EOF ) {
146 is.setstate(ios::eofbit);
147 break;
148 }
149 else if ( isspace(ch) ) {
150 sb->sungetc();
151 break;
152 }
153
154 str += ch;
155 if ( --w == 1 )
156 break;
157 }
158 }
159
160 is.isfx();
161 if ( str.length() == 0 )
162 is.setstate(ios::failbit);
163 #endif
164 return is;
165 }
166
167 #endif //std::string compatibility
168
169 // ----------------------------------------------------------------------------
170 // private classes
171 // ----------------------------------------------------------------------------
172
173 // this small class is used to gather statistics for performance tuning
174 //#define WXSTRING_STATISTICS
175 #ifdef WXSTRING_STATISTICS
176 class Averager
177 {
178 public:
179 Averager(const char *sz) { m_sz = sz; m_nTotal = m_nCount = 0; }
180 ~Averager()
181 { printf("wxString: average %s = %f\n", m_sz, ((float)m_nTotal)/m_nCount); }
182
183 void Add(size_t n) { m_nTotal += n; m_nCount++; }
184
185 private:
186 size_t m_nCount, m_nTotal;
187 const char *m_sz;
188 } g_averageLength("allocation size"),
189 g_averageSummandLength("summand length"),
190 g_averageConcatHit("hit probability in concat"),
191 g_averageInitialLength("initial string length");
192
193 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
194 #else
195 #define STATISTICS_ADD(av, val)
196 #endif // WXSTRING_STATISTICS
197
198 // ===========================================================================
199 // wxString class core
200 // ===========================================================================
201
202 // ---------------------------------------------------------------------------
203 // construction
204 // ---------------------------------------------------------------------------
205
206 // constructs string of <nLength> copies of character <ch>
207 wxString::wxString(wxChar ch, size_t nLength)
208 {
209 Init();
210
211 if ( nLength > 0 ) {
212 AllocBuffer(nLength);
213
214 #if wxUSE_UNICODE
215 // memset only works on char
216 for (size_t n=0; n<nLength; n++) m_pchData[n] = ch;
217 #else
218 memset(m_pchData, ch, nLength);
219 #endif
220 }
221 }
222
223 // takes nLength elements of psz starting at nPos
224 void wxString::InitWith(const wxChar *psz, size_t nPos, size_t nLength)
225 {
226 Init();
227
228 wxASSERT( nPos <= wxStrlen(psz) );
229
230 if ( nLength == wxSTRING_MAXLEN )
231 nLength = wxStrlen(psz + nPos);
232
233 STATISTICS_ADD(InitialLength, nLength);
234
235 if ( nLength > 0 ) {
236 // trailing '\0' is written in AllocBuffer()
237 AllocBuffer(nLength);
238 memcpy(m_pchData, psz + nPos, nLength*sizeof(wxChar));
239 }
240 }
241
242 #ifdef wxSTD_STRING_COMPATIBILITY
243
244 // poor man's iterators are "void *" pointers
245 wxString::wxString(const void *pStart, const void *pEnd)
246 {
247 InitWith((const wxChar *)pStart, 0,
248 (const wxChar *)pEnd - (const wxChar *)pStart);
249 }
250
251 #endif //std::string compatibility
252
253 #if wxUSE_UNICODE
254
255 // from multibyte string
256 wxString::wxString(const char *psz, wxMBConv& conv, size_t nLength)
257 {
258 // first get necessary size
259 size_t nLen = psz ? conv.MB2WC((wchar_t *) NULL, psz, 0) : 0;
260
261 // nLength is number of *Unicode* characters here!
262 if ((nLen != (size_t)-1) && (nLen > nLength))
263 nLen = nLength;
264
265 // empty?
266 if ( (nLen != 0) && (nLen != (size_t)-1) ) {
267 AllocBuffer(nLen);
268 conv.MB2WC(m_pchData, psz, nLen);
269 }
270 else {
271 Init();
272 }
273 }
274
275 #else
276
277 #if wxUSE_WCHAR_T
278 // from wide string
279 wxString::wxString(const wchar_t *pwz)
280 {
281 // first get necessary size
282 size_t nLen = pwz ? wxWC2MB((char *) NULL, pwz, 0) : 0;
283
284 // empty?
285 if ( (nLen != 0) && (nLen != (size_t)-1) ) {
286 AllocBuffer(nLen);
287 wxWC2MB(m_pchData, pwz, nLen);
288 }
289 else {
290 Init();
291 }
292 }
293 #endif
294
295 #endif
296
297 // ---------------------------------------------------------------------------
298 // memory allocation
299 // ---------------------------------------------------------------------------
300
301 // allocates memory needed to store a C string of length nLen
302 void wxString::AllocBuffer(size_t nLen)
303 {
304 wxASSERT( nLen > 0 ); //
305 wxASSERT( nLen <= INT_MAX-1 ); // max size (enough room for 1 extra)
306
307 STATISTICS_ADD(Length, nLen);
308
309 // allocate memory:
310 // 1) one extra character for '\0' termination
311 // 2) sizeof(wxStringData) for housekeeping info
312 wxStringData* pData = (wxStringData*)
313 malloc(sizeof(wxStringData) + (nLen + EXTRA_ALLOC + 1)*sizeof(wxChar));
314 pData->nRefs = 1;
315 pData->nDataLength = nLen;
316 pData->nAllocLength = nLen + EXTRA_ALLOC;
317 m_pchData = pData->data(); // data starts after wxStringData
318 m_pchData[nLen] = _T('\0');
319 }
320
321 // must be called before changing this string
322 void wxString::CopyBeforeWrite()
323 {
324 wxStringData* pData = GetStringData();
325
326 if ( pData->IsShared() ) {
327 pData->Unlock(); // memory not freed because shared
328 size_t nLen = pData->nDataLength;
329 AllocBuffer(nLen);
330 memcpy(m_pchData, pData->data(), nLen*sizeof(wxChar));
331 }
332
333 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
334 }
335
336 // must be called before replacing contents of this string
337 void wxString::AllocBeforeWrite(size_t nLen)
338 {
339 wxASSERT( nLen != 0 ); // doesn't make any sense
340
341 // must not share string and must have enough space
342 wxStringData* pData = GetStringData();
343 if ( pData->IsShared() || (nLen > pData->nAllocLength) ) {
344 // can't work with old buffer, get new one
345 pData->Unlock();
346 AllocBuffer(nLen);
347 }
348 else {
349 // update the string length
350 pData->nDataLength = nLen;
351 }
352
353 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
354 }
355
356 // allocate enough memory for nLen characters
357 void wxString::Alloc(size_t nLen)
358 {
359 wxStringData *pData = GetStringData();
360 if ( pData->nAllocLength <= nLen ) {
361 if ( pData->IsEmpty() ) {
362 nLen += EXTRA_ALLOC;
363
364 wxStringData* pData = (wxStringData*)
365 malloc(sizeof(wxStringData) + (nLen + 1)*sizeof(wxChar));
366 pData->nRefs = 1;
367 pData->nDataLength = 0;
368 pData->nAllocLength = nLen;
369 m_pchData = pData->data(); // data starts after wxStringData
370 m_pchData[0u] = _T('\0');
371 }
372 else if ( pData->IsShared() ) {
373 pData->Unlock(); // memory not freed because shared
374 size_t nOldLen = pData->nDataLength;
375 AllocBuffer(nLen);
376 memcpy(m_pchData, pData->data(), nOldLen*sizeof(wxChar));
377 }
378 else {
379 nLen += EXTRA_ALLOC;
380
381 wxStringData *p = (wxStringData *)
382 realloc(pData, sizeof(wxStringData) + (nLen + 1)*sizeof(wxChar));
383
384 if ( p == NULL ) {
385 // @@@ what to do on memory error?
386 return;
387 }
388
389 // it's not important if the pointer changed or not (the check for this
390 // is not faster than assigning to m_pchData in all cases)
391 p->nAllocLength = nLen;
392 m_pchData = p->data();
393 }
394 }
395 //else: we've already got enough
396 }
397
398 // shrink to minimal size (releasing extra memory)
399 void wxString::Shrink()
400 {
401 wxStringData *pData = GetStringData();
402
403 // this variable is unused in release build, so avoid the compiler warning by
404 // just not declaring it
405 #ifdef __WXDEBUG__
406 void *p =
407 #endif
408 realloc(pData, sizeof(wxStringData) + (pData->nDataLength + 1)*sizeof(wxChar));
409
410 wxASSERT( p != NULL ); // can't free memory?
411 wxASSERT( p == pData ); // we're decrementing the size - block shouldn't move!
412 }
413
414 // get the pointer to writable buffer of (at least) nLen bytes
415 wxChar *wxString::GetWriteBuf(size_t nLen)
416 {
417 AllocBeforeWrite(nLen);
418
419 wxASSERT( GetStringData()->nRefs == 1 );
420 GetStringData()->Validate(FALSE);
421
422 return m_pchData;
423 }
424
425 // put string back in a reasonable state after GetWriteBuf
426 void wxString::UngetWriteBuf()
427 {
428 GetStringData()->nDataLength = wxStrlen(m_pchData);
429 GetStringData()->Validate(TRUE);
430 }
431
432 // ---------------------------------------------------------------------------
433 // data access
434 // ---------------------------------------------------------------------------
435
436 // all functions are inline in string.h
437
438 // ---------------------------------------------------------------------------
439 // assignment operators
440 // ---------------------------------------------------------------------------
441
442 // helper function: does real copy
443 void wxString::AssignCopy(size_t nSrcLen, const wxChar *pszSrcData)
444 {
445 if ( nSrcLen == 0 ) {
446 Reinit();
447 }
448 else {
449 AllocBeforeWrite(nSrcLen);
450 memcpy(m_pchData, pszSrcData, nSrcLen*sizeof(wxChar));
451 GetStringData()->nDataLength = nSrcLen;
452 m_pchData[nSrcLen] = _T('\0');
453 }
454 }
455
456 // assigns one string to another
457 wxString& wxString::operator=(const wxString& stringSrc)
458 {
459 wxASSERT( stringSrc.GetStringData()->IsValid() );
460
461 // don't copy string over itself
462 if ( m_pchData != stringSrc.m_pchData ) {
463 if ( stringSrc.GetStringData()->IsEmpty() ) {
464 Reinit();
465 }
466 else {
467 // adjust references
468 GetStringData()->Unlock();
469 m_pchData = stringSrc.m_pchData;
470 GetStringData()->Lock();
471 }
472 }
473
474 return *this;
475 }
476
477 // assigns a single character
478 wxString& wxString::operator=(wxChar ch)
479 {
480 AssignCopy(1, &ch);
481 return *this;
482 }
483
484 // assigns C string
485 wxString& wxString::operator=(const wxChar *psz)
486 {
487 AssignCopy(wxStrlen(psz), psz);
488 return *this;
489 }
490
491 #if !wxUSE_UNICODE
492
493 // same as 'signed char' variant
494 wxString& wxString::operator=(const unsigned char* psz)
495 {
496 *this = (const char *)psz;
497 return *this;
498 }
499
500 #if wxUSE_WCHAR_T
501 wxString& wxString::operator=(const wchar_t *pwz)
502 {
503 wxString str(pwz);
504 *this = str;
505 return *this;
506 }
507 #endif
508
509 #endif
510
511 // ---------------------------------------------------------------------------
512 // string concatenation
513 // ---------------------------------------------------------------------------
514
515 // add something to this string
516 void wxString::ConcatSelf(int nSrcLen, const wxChar *pszSrcData)
517 {
518 STATISTICS_ADD(SummandLength, nSrcLen);
519
520 // concatenating an empty string is a NOP
521 if ( nSrcLen > 0 ) {
522 wxStringData *pData = GetStringData();
523 size_t nLen = pData->nDataLength;
524 size_t nNewLen = nLen + nSrcLen;
525
526 // alloc new buffer if current is too small
527 if ( pData->IsShared() ) {
528 STATISTICS_ADD(ConcatHit, 0);
529
530 // we have to allocate another buffer
531 wxStringData* pOldData = GetStringData();
532 AllocBuffer(nNewLen);
533 memcpy(m_pchData, pOldData->data(), nLen*sizeof(wxChar));
534 pOldData->Unlock();
535 }
536 else if ( nNewLen > pData->nAllocLength ) {
537 STATISTICS_ADD(ConcatHit, 0);
538
539 // we have to grow the buffer
540 Alloc(nNewLen);
541 }
542 else {
543 STATISTICS_ADD(ConcatHit, 1);
544
545 // the buffer is already big enough
546 }
547
548 // should be enough space
549 wxASSERT( nNewLen <= GetStringData()->nAllocLength );
550
551 // fast concatenation - all is done in our buffer
552 memcpy(m_pchData + nLen, pszSrcData, nSrcLen*sizeof(wxChar));
553
554 m_pchData[nNewLen] = _T('\0'); // put terminating '\0'
555 GetStringData()->nDataLength = nNewLen; // and fix the length
556 }
557 //else: the string to append was empty
558 }
559
560 /*
561 * concatenation functions come in 5 flavours:
562 * string + string
563 * char + string and string + char
564 * C str + string and string + C str
565 */
566
567 wxString operator+(const wxString& string1, const wxString& string2)
568 {
569 wxASSERT( string1.GetStringData()->IsValid() );
570 wxASSERT( string2.GetStringData()->IsValid() );
571
572 wxString s = string1;
573 s += string2;
574
575 return s;
576 }
577
578 wxString operator+(const wxString& string, wxChar ch)
579 {
580 wxASSERT( string.GetStringData()->IsValid() );
581
582 wxString s = string;
583 s += ch;
584
585 return s;
586 }
587
588 wxString operator+(wxChar ch, const wxString& string)
589 {
590 wxASSERT( string.GetStringData()->IsValid() );
591
592 wxString s = ch;
593 s += string;
594
595 return s;
596 }
597
598 wxString operator+(const wxString& string, const wxChar *psz)
599 {
600 wxASSERT( string.GetStringData()->IsValid() );
601
602 wxString s;
603 s.Alloc(wxStrlen(psz) + string.Len());
604 s = string;
605 s += psz;
606
607 return s;
608 }
609
610 wxString operator+(const wxChar *psz, const wxString& string)
611 {
612 wxASSERT( string.GetStringData()->IsValid() );
613
614 wxString s;
615 s.Alloc(wxStrlen(psz) + string.Len());
616 s = psz;
617 s += string;
618
619 return s;
620 }
621
622 // ===========================================================================
623 // other common string functions
624 // ===========================================================================
625
626 // ---------------------------------------------------------------------------
627 // simple sub-string extraction
628 // ---------------------------------------------------------------------------
629
630 // helper function: clone the data attached to this string
631 void wxString::AllocCopy(wxString& dest, int nCopyLen, int nCopyIndex) const
632 {
633 if ( nCopyLen == 0 ) {
634 dest.Init();
635 }
636 else {
637 dest.AllocBuffer(nCopyLen);
638 memcpy(dest.m_pchData, m_pchData + nCopyIndex, nCopyLen*sizeof(wxChar));
639 }
640 }
641
642 // extract string of length nCount starting at nFirst
643 wxString wxString::Mid(size_t nFirst, size_t nCount) const
644 {
645 wxStringData *pData = GetStringData();
646 size_t nLen = pData->nDataLength;
647
648 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
649 if ( nCount == wxSTRING_MAXLEN )
650 {
651 nCount = nLen - nFirst;
652 }
653
654 // out-of-bounds requests return sensible things
655 if ( nFirst + nCount > nLen )
656 {
657 nCount = nLen - nFirst;
658 }
659
660 if ( nFirst > nLen )
661 {
662 // AllocCopy() will return empty string
663 nCount = 0;
664 }
665
666 wxString dest;
667 AllocCopy(dest, nCount, nFirst);
668
669 return dest;
670 }
671
672 // extract nCount last (rightmost) characters
673 wxString wxString::Right(size_t nCount) const
674 {
675 if ( nCount > (size_t)GetStringData()->nDataLength )
676 nCount = GetStringData()->nDataLength;
677
678 wxString dest;
679 AllocCopy(dest, nCount, GetStringData()->nDataLength - nCount);
680 return dest;
681 }
682
683 // get all characters after the last occurence of ch
684 // (returns the whole string if ch not found)
685 wxString wxString::AfterLast(wxChar ch) const
686 {
687 wxString str;
688 int iPos = Find(ch, TRUE);
689 if ( iPos == wxNOT_FOUND )
690 str = *this;
691 else
692 str = c_str() + iPos + 1;
693
694 return str;
695 }
696
697 // extract nCount first (leftmost) characters
698 wxString wxString::Left(size_t nCount) const
699 {
700 if ( nCount > (size_t)GetStringData()->nDataLength )
701 nCount = GetStringData()->nDataLength;
702
703 wxString dest;
704 AllocCopy(dest, nCount, 0);
705 return dest;
706 }
707
708 // get all characters before the first occurence of ch
709 // (returns the whole string if ch not found)
710 wxString wxString::BeforeFirst(wxChar ch) const
711 {
712 wxString str;
713 for ( const wxChar *pc = m_pchData; *pc != _T('\0') && *pc != ch; pc++ )
714 str += *pc;
715
716 return str;
717 }
718
719 /// get all characters before the last occurence of ch
720 /// (returns empty string if ch not found)
721 wxString wxString::BeforeLast(wxChar ch) const
722 {
723 wxString str;
724 int iPos = Find(ch, TRUE);
725 if ( iPos != wxNOT_FOUND && iPos != 0 )
726 str = wxString(c_str(), iPos);
727
728 return str;
729 }
730
731 /// get all characters after the first occurence of ch
732 /// (returns empty string if ch not found)
733 wxString wxString::AfterFirst(wxChar ch) const
734 {
735 wxString str;
736 int iPos = Find(ch);
737 if ( iPos != wxNOT_FOUND )
738 str = c_str() + iPos + 1;
739
740 return str;
741 }
742
743 // replace first (or all) occurences of some substring with another one
744 size_t wxString::Replace(const wxChar *szOld, const wxChar *szNew, bool bReplaceAll)
745 {
746 size_t uiCount = 0; // count of replacements made
747
748 size_t uiOldLen = wxStrlen(szOld);
749
750 wxString strTemp;
751 const wxChar *pCurrent = m_pchData;
752 const wxChar *pSubstr;
753 while ( *pCurrent != _T('\0') ) {
754 pSubstr = wxStrstr(pCurrent, szOld);
755 if ( pSubstr == NULL ) {
756 // strTemp is unused if no replacements were made, so avoid the copy
757 if ( uiCount == 0 )
758 return 0;
759
760 strTemp += pCurrent; // copy the rest
761 break; // exit the loop
762 }
763 else {
764 // take chars before match
765 strTemp.ConcatSelf(pSubstr - pCurrent, pCurrent);
766 strTemp += szNew;
767 pCurrent = pSubstr + uiOldLen; // restart after match
768
769 uiCount++;
770
771 // stop now?
772 if ( !bReplaceAll ) {
773 strTemp += pCurrent; // copy the rest
774 break; // exit the loop
775 }
776 }
777 }
778
779 // only done if there were replacements, otherwise would have returned above
780 *this = strTemp;
781
782 return uiCount;
783 }
784
785 bool wxString::IsAscii() const
786 {
787 const wxChar *s = (const wxChar*) *this;
788 while(*s){
789 if(!isascii(*s)) return(FALSE);
790 s++;
791 }
792 return(TRUE);
793 }
794
795 bool wxString::IsWord() const
796 {
797 const wxChar *s = (const wxChar*) *this;
798 while(*s){
799 if(!wxIsalpha(*s)) return(FALSE);
800 s++;
801 }
802 return(TRUE);
803 }
804
805 bool wxString::IsNumber() const
806 {
807 const wxChar *s = (const wxChar*) *this;
808 while(*s){
809 if(!wxIsdigit(*s)) return(FALSE);
810 s++;
811 }
812 return(TRUE);
813 }
814
815 wxString wxString::Strip(stripType w) const
816 {
817 wxString s = *this;
818 if ( w & leading ) s.Trim(FALSE);
819 if ( w & trailing ) s.Trim(TRUE);
820 return s;
821 }
822
823 // ---------------------------------------------------------------------------
824 // case conversion
825 // ---------------------------------------------------------------------------
826
827 wxString& wxString::MakeUpper()
828 {
829 CopyBeforeWrite();
830
831 for ( wxChar *p = m_pchData; *p; p++ )
832 *p = (wxChar)wxToupper(*p);
833
834 return *this;
835 }
836
837 wxString& wxString::MakeLower()
838 {
839 CopyBeforeWrite();
840
841 for ( wxChar *p = m_pchData; *p; p++ )
842 *p = (wxChar)wxTolower(*p);
843
844 return *this;
845 }
846
847 // ---------------------------------------------------------------------------
848 // trimming and padding
849 // ---------------------------------------------------------------------------
850
851 // trims spaces (in the sense of isspace) from left or right side
852 wxString& wxString::Trim(bool bFromRight)
853 {
854 // first check if we're going to modify the string at all
855 if ( !IsEmpty() &&
856 (
857 (bFromRight && wxIsspace(GetChar(Len() - 1))) ||
858 (!bFromRight && wxIsspace(GetChar(0u)))
859 )
860 )
861 {
862 // ok, there is at least one space to trim
863 CopyBeforeWrite();
864
865 if ( bFromRight )
866 {
867 // find last non-space character
868 wxChar *psz = m_pchData + GetStringData()->nDataLength - 1;
869 while ( wxIsspace(*psz) && (psz >= m_pchData) )
870 psz--;
871
872 // truncate at trailing space start
873 *++psz = _T('\0');
874 GetStringData()->nDataLength = psz - m_pchData;
875 }
876 else
877 {
878 // find first non-space character
879 const wxChar *psz = m_pchData;
880 while ( wxIsspace(*psz) )
881 psz++;
882
883 // fix up data and length
884 int nDataLength = GetStringData()->nDataLength - (psz - (const wxChar*) m_pchData);
885 memmove(m_pchData, psz, (nDataLength + 1)*sizeof(wxChar));
886 GetStringData()->nDataLength = nDataLength;
887 }
888 }
889
890 return *this;
891 }
892
893 // adds nCount characters chPad to the string from either side
894 wxString& wxString::Pad(size_t nCount, wxChar chPad, bool bFromRight)
895 {
896 wxString s(chPad, nCount);
897
898 if ( bFromRight )
899 *this += s;
900 else
901 {
902 s += *this;
903 *this = s;
904 }
905
906 return *this;
907 }
908
909 // truncate the string
910 wxString& wxString::Truncate(size_t uiLen)
911 {
912 if ( uiLen < Len() ) {
913 CopyBeforeWrite();
914
915 *(m_pchData + uiLen) = _T('\0');
916 GetStringData()->nDataLength = uiLen;
917 }
918 //else: nothing to do, string is already short enough
919
920 return *this;
921 }
922
923 // ---------------------------------------------------------------------------
924 // finding (return wxNOT_FOUND if not found and index otherwise)
925 // ---------------------------------------------------------------------------
926
927 // find a character
928 int wxString::Find(wxChar ch, bool bFromEnd) const
929 {
930 const wxChar *psz = bFromEnd ? wxStrrchr(m_pchData, ch) : wxStrchr(m_pchData, ch);
931
932 return (psz == NULL) ? wxNOT_FOUND : psz - (const wxChar*) m_pchData;
933 }
934
935 // find a sub-string (like strstr)
936 int wxString::Find(const wxChar *pszSub) const
937 {
938 const wxChar *psz = wxStrstr(m_pchData, pszSub);
939
940 return (psz == NULL) ? wxNOT_FOUND : psz - (const wxChar*) m_pchData;
941 }
942
943 // ---------------------------------------------------------------------------
944 // stream-like operators
945 // ---------------------------------------------------------------------------
946 wxString& wxString::operator<<(int i)
947 {
948 wxString res;
949 res.Printf(_T("%d"), i);
950
951 return (*this) << res;
952 }
953
954 wxString& wxString::operator<<(float f)
955 {
956 wxString res;
957 res.Printf(_T("%f"), f);
958
959 return (*this) << res;
960 }
961
962 wxString& wxString::operator<<(double d)
963 {
964 wxString res;
965 res.Printf(_T("%g"), d);
966
967 return (*this) << res;
968 }
969
970 // ---------------------------------------------------------------------------
971 // formatted output
972 // ---------------------------------------------------------------------------
973 int wxString::Printf(const wxChar *pszFormat, ...)
974 {
975 va_list argptr;
976 va_start(argptr, pszFormat);
977
978 int iLen = PrintfV(pszFormat, argptr);
979
980 va_end(argptr);
981
982 return iLen;
983 }
984
985 int wxString::PrintfV(const wxChar* pszFormat, va_list argptr)
986 {
987 // static buffer to avoid dynamic memory allocation each time
988 char s_szScratch[1024]; // using static buffer causes internal compiler err
989 #if 0
990 #if wxUSE_THREADS
991 // protect the static buffer
992 static wxCriticalSection critsect;
993 wxCriticalSectionLocker lock(critsect);
994 #endif
995 #endif
996
997 #if wxUSE_EXPERIMENTAL_PRINTF
998 // the new implementation
999
1000 Reinit();
1001 for (size_t n = 0; pszFormat[n]; n++)
1002 if (pszFormat[n] == _T('%')) {
1003 static char s_szFlags[256] = "%";
1004 size_t flagofs = 1;
1005 bool adj_left = FALSE, in_prec = FALSE,
1006 prec_dot = FALSE, done = FALSE;
1007 int ilen = 0;
1008 size_t min_width = 0, max_width = wxSTRING_MAXLEN;
1009 do {
1010 #define CHECK_PREC if (in_prec && !prec_dot) { s_szFlags[flagofs++] = '.'; prec_dot = TRUE; }
1011 switch (pszFormat[++n]) {
1012 case _T('\0'):
1013 done = TRUE;
1014 break;
1015 case _T('%'):
1016 *this += _T('%');
1017 done = TRUE;
1018 break;
1019 case _T('#'):
1020 case _T('0'):
1021 case _T(' '):
1022 case _T('+'):
1023 case _T('\''):
1024 CHECK_PREC
1025 s_szFlags[flagofs++] = pszFormat[n];
1026 break;
1027 case _T('-'):
1028 CHECK_PREC
1029 adj_left = TRUE;
1030 s_szFlags[flagofs++] = pszFormat[n];
1031 break;
1032 case _T('.'):
1033 CHECK_PREC
1034 in_prec = TRUE;
1035 prec_dot = FALSE;
1036 max_width = 0;
1037 // dot will be auto-added to s_szFlags if non-negative number follows
1038 break;
1039 case _T('h'):
1040 ilen = -1;
1041 CHECK_PREC
1042 s_szFlags[flagofs++] = pszFormat[n];
1043 break;
1044 case _T('l'):
1045 ilen = 1;
1046 CHECK_PREC
1047 s_szFlags[flagofs++] = pszFormat[n];
1048 break;
1049 case _T('q'):
1050 case _T('L'):
1051 ilen = 2;
1052 CHECK_PREC
1053 s_szFlags[flagofs++] = pszFormat[n];
1054 break;
1055 case _T('Z'):
1056 ilen = 3;
1057 CHECK_PREC
1058 s_szFlags[flagofs++] = pszFormat[n];
1059 break;
1060 case _T('*'):
1061 {
1062 int len = va_arg(argptr, int);
1063 if (in_prec) {
1064 if (len<0) break;
1065 CHECK_PREC
1066 max_width = len;
1067 } else {
1068 if (len<0) {
1069 adj_left = !adj_left;
1070 s_szFlags[flagofs++] = '-';
1071 len = -len;
1072 }
1073 min_width = len;
1074 }
1075 flagofs += ::sprintf(s_szFlags+flagofs,"%d",len);
1076 }
1077 break;
1078 case _T('1'): case _T('2'): case _T('3'):
1079 case _T('4'): case _T('5'): case _T('6'):
1080 case _T('7'): case _T('8'): case _T('9'):
1081 {
1082 int len = 0;
1083 CHECK_PREC
1084 while ((pszFormat[n]>=_T('0')) && (pszFormat[n]<=_T('9'))) {
1085 s_szFlags[flagofs++] = pszFormat[n];
1086 len = len*10 + (pszFormat[n] - _T('0'));
1087 n++;
1088 }
1089 if (in_prec) max_width = len;
1090 else min_width = len;
1091 n--; // the main loop pre-increments n again
1092 }
1093 break;
1094 case _T('d'):
1095 case _T('i'):
1096 case _T('o'):
1097 case _T('u'):
1098 case _T('x'):
1099 case _T('X'):
1100 CHECK_PREC
1101 s_szFlags[flagofs++] = pszFormat[n];
1102 s_szFlags[flagofs] = '\0';
1103 if (ilen == 0 ) {
1104 int val = va_arg(argptr, int);
1105 ::sprintf(s_szScratch, s_szFlags, val);
1106 }
1107 else if (ilen == -1) {
1108 short int val = va_arg(argptr, short int);
1109 ::sprintf(s_szScratch, s_szFlags, val);
1110 }
1111 else if (ilen == 1) {
1112 long int val = va_arg(argptr, long int);
1113 ::sprintf(s_szScratch, s_szFlags, val);
1114 }
1115 else if (ilen == 2) {
1116 #if SIZEOF_LONG_LONG
1117 long long int val = va_arg(argptr, long long int);
1118 ::sprintf(s_szScratch, s_szFlags, val);
1119 #else
1120 long int val = va_arg(argptr, long int);
1121 ::sprintf(s_szScratch, s_szFlags, val);
1122 #endif
1123 }
1124 else if (ilen == 3) {
1125 size_t val = va_arg(argptr, size_t);
1126 ::sprintf(s_szScratch, s_szFlags, val);
1127 }
1128 *this += wxString(s_szScratch);
1129 done = TRUE;
1130 break;
1131 case _T('e'):
1132 case _T('E'):
1133 case _T('f'):
1134 case _T('g'):
1135 case _T('G'):
1136 CHECK_PREC
1137 s_szFlags[flagofs++] = pszFormat[n];
1138 s_szFlags[flagofs] = '\0';
1139 if (ilen == 2) {
1140 long double val = va_arg(argptr, long double);
1141 ::sprintf(s_szScratch, s_szFlags, val);
1142 } else {
1143 double val = va_arg(argptr, double);
1144 ::sprintf(s_szScratch, s_szFlags, val);
1145 }
1146 *this += wxString(s_szScratch);
1147 done = TRUE;
1148 break;
1149 case _T('p'):
1150 {
1151 void *val = va_arg(argptr, void *);
1152 CHECK_PREC
1153 s_szFlags[flagofs++] = pszFormat[n];
1154 s_szFlags[flagofs] = '\0';
1155 ::sprintf(s_szScratch, s_szFlags, val);
1156 *this += wxString(s_szScratch);
1157 done = TRUE;
1158 }
1159 break;
1160 case _T('c'):
1161 {
1162 wxChar val = va_arg(argptr, int);
1163 // we don't need to honor padding here, do we?
1164 *this += val;
1165 done = TRUE;
1166 }
1167 break;
1168 case _T('s'):
1169 if (ilen == -1) {
1170 // wx extension: we'll let %hs mean non-Unicode strings
1171 char *val = va_arg(argptr, char *);
1172 #if wxUSE_UNICODE
1173 // ASCII->Unicode constructor handles max_width right
1174 wxString s(val, wxConvLibc, max_width);
1175 #else
1176 size_t len = wxSTRING_MAXLEN;
1177 if (val) {
1178 for (len = 0; val[len] && (len<max_width); len++);
1179 } else val = _T("(null)");
1180 wxString s(val, len);
1181 #endif
1182 if (s.Len() < min_width)
1183 s.Pad(min_width - s.Len(), _T(' '), adj_left);
1184 *this += s;
1185 } else {
1186 wxChar *val = va_arg(argptr, wxChar *);
1187 size_t len = wxSTRING_MAXLEN;
1188 if (val) {
1189 for (len = 0; val[len] && (len<max_width); len++);
1190 } else val = _T("(null)");
1191 wxString s(val, len);
1192 if (s.Len() < min_width)
1193 s.Pad(min_width - s.Len(), _T(' '), adj_left);
1194 *this += s;
1195 }
1196 done = TRUE;
1197 break;
1198 case _T('n'):
1199 if (ilen == 0) {
1200 int *val = va_arg(argptr, int *);
1201 *val = Len();
1202 }
1203 else if (ilen == -1) {
1204 short int *val = va_arg(argptr, short int *);
1205 *val = Len();
1206 }
1207 else if (ilen >= 1) {
1208 long int *val = va_arg(argptr, long int *);
1209 *val = Len();
1210 }
1211 done = TRUE;
1212 break;
1213 default:
1214 if (wxIsalpha(pszFormat[n]))
1215 // probably some flag not taken care of here yet
1216 s_szFlags[flagofs++] = pszFormat[n];
1217 else {
1218 // bad format
1219 *this += _T('%'); // just to pass the glibc tst-printf.c
1220 n--;
1221 done = TRUE;
1222 }
1223 break;
1224 }
1225 #undef CHECK_PREC
1226 } while (!done);
1227 } else *this += pszFormat[n];
1228
1229 #else
1230 // NB: wxVsnprintf() may return either less than the buffer size or -1 if there
1231 // is not enough place depending on implementation
1232 int iLen = wxVsnprintf(s_szScratch, WXSIZEOF(s_szScratch), pszFormat, argptr);
1233 char *buffer;
1234 if ( iLen < (int)WXSIZEOF(s_szScratch) ) {
1235 buffer = s_szScratch;
1236 }
1237 else {
1238 int size = WXSIZEOF(s_szScratch) * 2;
1239 buffer = (char *)malloc(size);
1240 while ( buffer != NULL ) {
1241 iLen = wxVsnprintf(buffer, WXSIZEOF(s_szScratch), pszFormat, argptr);
1242 if ( iLen < size ) {
1243 // ok, there was enough space
1244 break;
1245 }
1246
1247 // still not enough, double it again
1248 buffer = (char *)realloc(buffer, size *= 2);
1249 }
1250
1251 if ( !buffer ) {
1252 // out of memory
1253 return -1;
1254 }
1255 }
1256
1257 wxString s(buffer);
1258 *this = s;
1259
1260 if ( buffer != s_szScratch )
1261 free(buffer);
1262 #endif
1263
1264 return Len();
1265 }
1266
1267 // ----------------------------------------------------------------------------
1268 // misc other operations
1269 // ----------------------------------------------------------------------------
1270 bool wxString::Matches(const wxChar *pszMask) const
1271 {
1272 // check char by char
1273 const wxChar *pszTxt;
1274 for ( pszTxt = c_str(); *pszMask != _T('\0'); pszMask++, pszTxt++ ) {
1275 switch ( *pszMask ) {
1276 case _T('?'):
1277 if ( *pszTxt == _T('\0') )
1278 return FALSE;
1279
1280 pszTxt++;
1281 pszMask++;
1282 break;
1283
1284 case _T('*'):
1285 {
1286 // ignore special chars immediately following this one
1287 while ( *pszMask == _T('*') || *pszMask == _T('?') )
1288 pszMask++;
1289
1290 // if there is nothing more, match
1291 if ( *pszMask == _T('\0') )
1292 return TRUE;
1293
1294 // are there any other metacharacters in the mask?
1295 size_t uiLenMask;
1296 const wxChar *pEndMask = wxStrpbrk(pszMask, _T("*?"));
1297
1298 if ( pEndMask != NULL ) {
1299 // we have to match the string between two metachars
1300 uiLenMask = pEndMask - pszMask;
1301 }
1302 else {
1303 // we have to match the remainder of the string
1304 uiLenMask = wxStrlen(pszMask);
1305 }
1306
1307 wxString strToMatch(pszMask, uiLenMask);
1308 const wxChar* pMatch = wxStrstr(pszTxt, strToMatch);
1309 if ( pMatch == NULL )
1310 return FALSE;
1311
1312 // -1 to compensate "++" in the loop
1313 pszTxt = pMatch + uiLenMask - 1;
1314 pszMask += uiLenMask - 1;
1315 }
1316 break;
1317
1318 default:
1319 if ( *pszMask != *pszTxt )
1320 return FALSE;
1321 break;
1322 }
1323 }
1324
1325 // match only if nothing left
1326 return *pszTxt == _T('\0');
1327 }
1328
1329 // Count the number of chars
1330 int wxString::Freq(wxChar ch) const
1331 {
1332 int count = 0;
1333 int len = Len();
1334 for (int i = 0; i < len; i++)
1335 {
1336 if (GetChar(i) == ch)
1337 count ++;
1338 }
1339 return count;
1340 }
1341
1342 // convert to upper case, return the copy of the string
1343 wxString wxString::Upper() const
1344 { wxString s(*this); return s.MakeUpper(); }
1345
1346 // convert to lower case, return the copy of the string
1347 wxString wxString::Lower() const { wxString s(*this); return s.MakeLower(); }
1348
1349 int wxString::sprintf(const wxChar *pszFormat, ...)
1350 {
1351 va_list argptr;
1352 va_start(argptr, pszFormat);
1353 int iLen = PrintfV(pszFormat, argptr);
1354 va_end(argptr);
1355 return iLen;
1356 }
1357
1358 // ---------------------------------------------------------------------------
1359 // standard C++ library string functions
1360 // ---------------------------------------------------------------------------
1361 #ifdef wxSTD_STRING_COMPATIBILITY
1362
1363 wxString& wxString::insert(size_t nPos, const wxString& str)
1364 {
1365 wxASSERT( str.GetStringData()->IsValid() );
1366 wxASSERT( nPos <= Len() );
1367
1368 if ( !str.IsEmpty() ) {
1369 wxString strTmp;
1370 wxChar *pc = strTmp.GetWriteBuf(Len() + str.Len());
1371 wxStrncpy(pc, c_str(), nPos);
1372 wxStrcpy(pc + nPos, str);
1373 wxStrcpy(pc + nPos + str.Len(), c_str() + nPos);
1374 strTmp.UngetWriteBuf();
1375 *this = strTmp;
1376 }
1377
1378 return *this;
1379 }
1380
1381 size_t wxString::find(const wxString& str, size_t nStart) const
1382 {
1383 wxASSERT( str.GetStringData()->IsValid() );
1384 wxASSERT( nStart <= Len() );
1385
1386 const wxChar *p = wxStrstr(c_str() + nStart, str);
1387
1388 return p == NULL ? npos : p - c_str();
1389 }
1390
1391 // VC++ 1.5 can't cope with the default argument in the header.
1392 #if !defined(__VISUALC__) || defined(__WIN32__)
1393 size_t wxString::find(const wxChar* sz, size_t nStart, size_t n) const
1394 {
1395 return find(wxString(sz, n == npos ? 0 : n), nStart);
1396 }
1397 #endif // VC++ 1.5
1398
1399 // Gives a duplicate symbol (presumably a case-insensitivity problem)
1400 #if !defined(__BORLANDC__)
1401 size_t wxString::find(wxChar ch, size_t nStart) const
1402 {
1403 wxASSERT( nStart <= Len() );
1404
1405 const wxChar *p = wxStrchr(c_str() + nStart, ch);
1406
1407 return p == NULL ? npos : p - c_str();
1408 }
1409 #endif
1410
1411 size_t wxString::rfind(const wxString& str, size_t nStart) const
1412 {
1413 wxASSERT( str.GetStringData()->IsValid() );
1414 wxASSERT( nStart <= Len() );
1415
1416 // TODO could be made much quicker than that
1417 const wxChar *p = c_str() + (nStart == npos ? Len() : nStart);
1418 while ( p >= c_str() + str.Len() ) {
1419 if ( wxStrncmp(p - str.Len(), str, str.Len()) == 0 )
1420 return p - str.Len() - c_str();
1421 p--;
1422 }
1423
1424 return npos;
1425 }
1426
1427 // VC++ 1.5 can't cope with the default argument in the header.
1428 #if !defined(__VISUALC__) || defined(__WIN32__)
1429 size_t wxString::rfind(const wxChar* sz, size_t nStart, size_t n) const
1430 {
1431 return rfind(wxString(sz, n == npos ? 0 : n), nStart);
1432 }
1433
1434 size_t wxString::rfind(wxChar ch, size_t nStart) const
1435 {
1436 if ( nStart == npos )
1437 {
1438 nStart = Len();
1439 }
1440 else
1441 {
1442 wxASSERT( nStart <= Len() );
1443 }
1444
1445 const wxChar *p = wxStrrchr(c_str(), ch);
1446
1447 if ( p == NULL )
1448 return npos;
1449
1450 size_t result = p - c_str();
1451 return ( result > nStart ) ? npos : result;
1452 }
1453 #endif // VC++ 1.5
1454
1455 size_t wxString::find_first_of(const wxChar* sz, size_t nStart) const
1456 {
1457 const wxChar *start = c_str() + nStart;
1458 const wxChar *firstOf = wxStrpbrk(start, sz);
1459 if ( firstOf )
1460 return firstOf - start;
1461 else
1462 return npos;
1463 }
1464
1465 size_t wxString::find_last_of(const wxChar* sz, size_t nStart) const
1466 {
1467 if ( nStart == npos )
1468 {
1469 nStart = Len();
1470 }
1471 else
1472 {
1473 wxASSERT( nStart <= Len() );
1474 }
1475
1476 for ( const wxChar *p = c_str() + length() - 1; p >= c_str(); p-- )
1477 {
1478 if ( wxStrchr(sz, *p) )
1479 return p - c_str();
1480 }
1481
1482 return npos;
1483 }
1484
1485 size_t wxString::find_first_not_of(const wxChar* sz, size_t nStart) const
1486 {
1487 if ( nStart == npos )
1488 {
1489 nStart = Len();
1490 }
1491 else
1492 {
1493 wxASSERT( nStart <= Len() );
1494 }
1495
1496 size_t nAccept = wxStrspn(c_str() + nStart, sz);
1497 if ( nAccept >= length() - nStart )
1498 return npos;
1499 else
1500 return nAccept;
1501 }
1502
1503 size_t wxString::find_first_not_of(wxChar ch, size_t nStart) const
1504 {
1505 wxASSERT( nStart <= Len() );
1506
1507 for ( const wxChar *p = c_str() + nStart; *p; p++ )
1508 {
1509 if ( *p != ch )
1510 return p - c_str();
1511 }
1512
1513 return npos;
1514 }
1515
1516 size_t wxString::find_last_not_of(const wxChar* sz, size_t nStart) const
1517 {
1518 if ( nStart == npos )
1519 {
1520 nStart = Len();
1521 }
1522 else
1523 {
1524 wxASSERT( nStart <= Len() );
1525 }
1526
1527 for ( const wxChar *p = c_str() + nStart - 1; p >= c_str(); p-- )
1528 {
1529 if ( !wxStrchr(sz, *p) )
1530 return p - c_str();
1531 }
1532
1533 return npos;
1534 }
1535
1536 size_t wxString::find_last_not_of(wxChar ch, size_t nStart) const
1537 {
1538 if ( nStart == npos )
1539 {
1540 nStart = Len();
1541 }
1542 else
1543 {
1544 wxASSERT( nStart <= Len() );
1545 }
1546
1547 for ( const wxChar *p = c_str() + nStart - 1; p >= c_str(); p-- )
1548 {
1549 if ( *p != ch )
1550 return p - c_str();
1551 }
1552
1553 return npos;
1554 }
1555
1556 wxString wxString::substr(size_t nStart, size_t nLen) const
1557 {
1558 // npos means 'take all'
1559 if ( nLen == npos )
1560 nLen = 0;
1561
1562 wxASSERT( nStart + nLen <= Len() );
1563
1564 return wxString(c_str() + nStart, nLen == npos ? 0 : nLen);
1565 }
1566
1567 wxString& wxString::erase(size_t nStart, size_t nLen)
1568 {
1569 wxString strTmp(c_str(), nStart);
1570 if ( nLen != npos ) {
1571 wxASSERT( nStart + nLen <= Len() );
1572
1573 strTmp.append(c_str() + nStart + nLen);
1574 }
1575
1576 *this = strTmp;
1577 return *this;
1578 }
1579
1580 wxString& wxString::replace(size_t nStart, size_t nLen, const wxChar *sz)
1581 {
1582 wxASSERT( nStart + nLen <= wxStrlen(sz) );
1583
1584 wxString strTmp;
1585 if ( nStart != 0 )
1586 strTmp.append(c_str(), nStart);
1587 strTmp += sz;
1588 strTmp.append(c_str() + nStart + nLen);
1589
1590 *this = strTmp;
1591 return *this;
1592 }
1593
1594 wxString& wxString::replace(size_t nStart, size_t nLen, size_t nCount, wxChar ch)
1595 {
1596 return replace(nStart, nLen, wxString(ch, nCount));
1597 }
1598
1599 wxString& wxString::replace(size_t nStart, size_t nLen,
1600 const wxString& str, size_t nStart2, size_t nLen2)
1601 {
1602 return replace(nStart, nLen, str.substr(nStart2, nLen2));
1603 }
1604
1605 wxString& wxString::replace(size_t nStart, size_t nLen,
1606 const wxChar* sz, size_t nCount)
1607 {
1608 return replace(nStart, nLen, wxString(sz, nCount));
1609 }
1610
1611 #endif //std::string compatibility
1612
1613 // ============================================================================
1614 // ArrayString
1615 // ============================================================================
1616
1617 // size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1618 #define ARRAY_MAXSIZE_INCREMENT 4096
1619 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1620 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1621 #endif
1622
1623 #define STRING(p) ((wxString *)(&(p)))
1624
1625 // ctor
1626 wxArrayString::wxArrayString()
1627 {
1628 m_nSize =
1629 m_nCount = 0;
1630 m_pItems = (wxChar **) NULL;
1631 }
1632
1633 // copy ctor
1634 wxArrayString::wxArrayString(const wxArrayString& src)
1635 {
1636 m_nSize =
1637 m_nCount = 0;
1638 m_pItems = (wxChar **) NULL;
1639
1640 *this = src;
1641 }
1642
1643 // assignment operator
1644 wxArrayString& wxArrayString::operator=(const wxArrayString& src)
1645 {
1646 if ( m_nSize > 0 )
1647 Clear();
1648
1649 if ( src.m_nCount > ARRAY_DEFAULT_INITIAL_SIZE )
1650 Alloc(src.m_nCount);
1651
1652 // we can't just copy the pointers here because otherwise we would share
1653 // the strings with another array
1654 for ( size_t n = 0; n < src.m_nCount; n++ )
1655 Add(src[n]);
1656
1657 if ( m_nCount != 0 )
1658 memcpy(m_pItems, src.m_pItems, m_nCount*sizeof(wxChar *));
1659
1660 return *this;
1661 }
1662
1663 // grow the array
1664 void wxArrayString::Grow()
1665 {
1666 // only do it if no more place
1667 if( m_nCount == m_nSize ) {
1668 if( m_nSize == 0 ) {
1669 // was empty, alloc some memory
1670 m_nSize = ARRAY_DEFAULT_INITIAL_SIZE;
1671 m_pItems = new wxChar *[m_nSize];
1672 }
1673 else {
1674 // otherwise when it's called for the first time, nIncrement would be 0
1675 // and the array would never be expanded
1676 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE != 0 );
1677
1678 // add 50% but not too much
1679 size_t nIncrement = m_nSize < ARRAY_DEFAULT_INITIAL_SIZE
1680 ? ARRAY_DEFAULT_INITIAL_SIZE : m_nSize >> 1;
1681 if ( nIncrement > ARRAY_MAXSIZE_INCREMENT )
1682 nIncrement = ARRAY_MAXSIZE_INCREMENT;
1683 m_nSize += nIncrement;
1684 wxChar **pNew = new wxChar *[m_nSize];
1685
1686 // copy data to new location
1687 memcpy(pNew, m_pItems, m_nCount*sizeof(wxChar *));
1688
1689 // delete old memory (but do not release the strings!)
1690 wxDELETEA(m_pItems);
1691
1692 m_pItems = pNew;
1693 }
1694 }
1695 }
1696
1697 void wxArrayString::Free()
1698 {
1699 for ( size_t n = 0; n < m_nCount; n++ ) {
1700 STRING(m_pItems[n])->GetStringData()->Unlock();
1701 }
1702 }
1703
1704 // deletes all the strings from the list
1705 void wxArrayString::Empty()
1706 {
1707 Free();
1708
1709 m_nCount = 0;
1710 }
1711
1712 // as Empty, but also frees memory
1713 void wxArrayString::Clear()
1714 {
1715 Free();
1716
1717 m_nSize =
1718 m_nCount = 0;
1719
1720 wxDELETEA(m_pItems);
1721 }
1722
1723 // dtor
1724 wxArrayString::~wxArrayString()
1725 {
1726 Free();
1727
1728 wxDELETEA(m_pItems);
1729 }
1730
1731 // pre-allocates memory (frees the previous data!)
1732 void wxArrayString::Alloc(size_t nSize)
1733 {
1734 wxASSERT( nSize > 0 );
1735
1736 // only if old buffer was not big enough
1737 if ( nSize > m_nSize ) {
1738 Free();
1739 wxDELETEA(m_pItems);
1740 m_pItems = new wxChar *[nSize];
1741 m_nSize = nSize;
1742 }
1743
1744 m_nCount = 0;
1745 }
1746
1747 // minimizes the memory usage by freeing unused memory
1748 void wxArrayString::Shrink()
1749 {
1750 // only do it if we have some memory to free
1751 if( m_nCount < m_nSize ) {
1752 // allocates exactly as much memory as we need
1753 wxChar **pNew = new wxChar *[m_nCount];
1754
1755 // copy data to new location
1756 memcpy(pNew, m_pItems, m_nCount*sizeof(wxChar *));
1757 delete [] m_pItems;
1758 m_pItems = pNew;
1759 }
1760 }
1761
1762 // searches the array for an item (forward or backwards)
1763 int wxArrayString::Index(const wxChar *sz, bool bCase, bool bFromEnd) const
1764 {
1765 if ( bFromEnd ) {
1766 if ( m_nCount > 0 ) {
1767 size_t ui = m_nCount;
1768 do {
1769 if ( STRING(m_pItems[--ui])->IsSameAs(sz, bCase) )
1770 return ui;
1771 }
1772 while ( ui != 0 );
1773 }
1774 }
1775 else {
1776 for( size_t ui = 0; ui < m_nCount; ui++ ) {
1777 if( STRING(m_pItems[ui])->IsSameAs(sz, bCase) )
1778 return ui;
1779 }
1780 }
1781
1782 return wxNOT_FOUND;
1783 }
1784
1785 // add item at the end
1786 void wxArrayString::Add(const wxString& str)
1787 {
1788 wxASSERT( str.GetStringData()->IsValid() );
1789
1790 Grow();
1791
1792 // the string data must not be deleted!
1793 str.GetStringData()->Lock();
1794 m_pItems[m_nCount++] = (wxChar *)str.c_str();
1795 }
1796
1797 // add item at the given position
1798 void wxArrayString::Insert(const wxString& str, size_t nIndex)
1799 {
1800 wxASSERT( str.GetStringData()->IsValid() );
1801
1802 wxCHECK_RET( nIndex <= m_nCount, _("bad index in wxArrayString::Insert") );
1803
1804 Grow();
1805
1806 memmove(&m_pItems[nIndex + 1], &m_pItems[nIndex],
1807 (m_nCount - nIndex)*sizeof(wxChar *));
1808
1809 str.GetStringData()->Lock();
1810 m_pItems[nIndex] = (wxChar *)str.c_str();
1811
1812 m_nCount++;
1813 }
1814
1815 // removes item from array (by index)
1816 void wxArrayString::Remove(size_t nIndex)
1817 {
1818 wxCHECK_RET( nIndex <= m_nCount, _("bad index in wxArrayString::Remove") );
1819
1820 // release our lock
1821 Item(nIndex).GetStringData()->Unlock();
1822
1823 memmove(&m_pItems[nIndex], &m_pItems[nIndex + 1],
1824 (m_nCount - nIndex - 1)*sizeof(wxChar *));
1825 m_nCount--;
1826 }
1827
1828 // removes item from array (by value)
1829 void wxArrayString::Remove(const wxChar *sz)
1830 {
1831 int iIndex = Index(sz);
1832
1833 wxCHECK_RET( iIndex != wxNOT_FOUND,
1834 _("removing inexistent element in wxArrayString::Remove") );
1835
1836 Remove(iIndex);
1837 }
1838
1839 // ----------------------------------------------------------------------------
1840 // sorting
1841 // ----------------------------------------------------------------------------
1842
1843 // we can only sort one array at a time with the quick-sort based
1844 // implementation
1845 #if wxUSE_THREADS
1846 // need a critical section to protect access to gs_compareFunction and
1847 // gs_sortAscending variables
1848 static wxCriticalSection *gs_critsectStringSort = NULL;
1849
1850 // call this before the value of the global sort vars is changed/after
1851 // you're finished with them
1852 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
1853 gs_critsectStringSort = new wxCriticalSection; \
1854 gs_critsectStringSort->Enter()
1855 #define END_SORT() gs_critsectStringSort->Leave(); \
1856 delete gs_critsectStringSort; \
1857 gs_critsectStringSort = NULL
1858 #else // !threads
1859 #define START_SORT()
1860 #define END_SORT()
1861 #endif // wxUSE_THREADS
1862
1863 // function to use for string comparaison
1864 static wxArrayString::CompareFunction gs_compareFunction = NULL;
1865
1866 // if we don't use the compare function, this flag tells us if we sort the
1867 // array in ascending or descending order
1868 static bool gs_sortAscending = TRUE;
1869
1870 // function which is called by quick sort
1871 static int wxStringCompareFunction(const void *first, const void *second)
1872 {
1873 wxString *strFirst = (wxString *)first;
1874 wxString *strSecond = (wxString *)second;
1875
1876 if ( gs_compareFunction ) {
1877 return gs_compareFunction(*strFirst, *strSecond);
1878 }
1879 else {
1880 // maybe we should use wxStrcoll
1881 int result = wxStrcmp(strFirst->c_str(), strSecond->c_str());
1882
1883 return gs_sortAscending ? result : -result;
1884 }
1885 }
1886
1887 // sort array elements using passed comparaison function
1888 void wxArrayString::Sort(CompareFunction compareFunction)
1889 {
1890 START_SORT();
1891
1892 wxASSERT( !gs_compareFunction ); // must have been reset to NULL
1893 gs_compareFunction = compareFunction;
1894
1895 DoSort();
1896
1897 END_SORT();
1898 }
1899
1900 void wxArrayString::Sort(bool reverseOrder)
1901 {
1902 START_SORT();
1903
1904 wxASSERT( !gs_compareFunction ); // must have been reset to NULL
1905 gs_sortAscending = !reverseOrder;
1906
1907 DoSort();
1908
1909 END_SORT();
1910 }
1911
1912 void wxArrayString::DoSort()
1913 {
1914 // just sort the pointers using qsort() - of course it only works because
1915 // wxString() *is* a pointer to its data
1916 qsort(m_pItems, m_nCount, sizeof(wxChar *), wxStringCompareFunction);
1917 }
1918
1919 // ============================================================================
1920 // MBConv
1921 // ============================================================================
1922
1923 WXDLLEXPORT_DATA(wxMBConv *) wxConvCurrent = &wxConvLibc;
1924 #if !wxUSE_WCHAR_T
1925 WXDLLEXPORT_DATA(wxMBConv) wxConvLibc, wxConvFile;
1926 #endif
1927
1928 #if wxUSE_WCHAR_T
1929
1930 // ----------------------------------------------------------------------------
1931 // standard libc conversion
1932 // ----------------------------------------------------------------------------
1933
1934 WXDLLEXPORT_DATA(wxMBConv) wxConvLibc;
1935
1936 size_t wxMBConv::MB2WC(wchar_t *buf, const char *psz, size_t n) const
1937 {
1938 return wxMB2WC(buf, psz, n);
1939 }
1940
1941 size_t wxMBConv::WC2MB(char *buf, const wchar_t *psz, size_t n) const
1942 {
1943 return wxWC2MB(buf, psz, n);
1944 }
1945
1946 // ----------------------------------------------------------------------------
1947 // standard file conversion
1948 // ----------------------------------------------------------------------------
1949
1950 WXDLLEXPORT_DATA(wxMBConvFile) wxConvFile;
1951
1952 // just use the libc conversion for now
1953 size_t wxMBConvFile::MB2WC(wchar_t *buf, const char *psz, size_t n) const
1954 {
1955 return wxMB2WC(buf, psz, n);
1956 }
1957
1958 size_t wxMBConvFile::WC2MB(char *buf, const wchar_t *psz, size_t n) const
1959 {
1960 return wxWC2MB(buf, psz, n);
1961 }
1962
1963 // ----------------------------------------------------------------------------
1964 // standard gdk conversion
1965 // ----------------------------------------------------------------------------
1966
1967 #ifdef __WXGTK12__
1968 WXDLLEXPORT_DATA(wxMBConvGdk) wxConvGdk;
1969
1970 #include <gdk/gdk.h>
1971
1972 size_t wxMBConvGdk::MB2WC(wchar_t *buf, const char *psz, size_t n) const
1973 {
1974 if (buf) {
1975 return gdk_mbstowcs((GdkWChar *)buf, psz, n);
1976 } else {
1977 GdkWChar *nbuf = new GdkWChar[n=strlen(psz)];
1978 size_t len = gdk_mbstowcs(nbuf, psz, n);
1979 delete [] nbuf;
1980 return len;
1981 }
1982 }
1983
1984 size_t wxMBConvGdk::WC2MB(char *buf, const wchar_t *psz, size_t n) const
1985 {
1986 char *mbstr = gdk_wcstombs((GdkWChar *)psz);
1987 size_t len = mbstr ? strlen(mbstr) : 0;
1988 if (buf) {
1989 if (len > n) len = n;
1990 memcpy(buf, psz, len);
1991 if (len < n) buf[len] = 0;
1992 }
1993 return len;
1994 }
1995 #endif // GTK > 1.0
1996
1997 // ----------------------------------------------------------------------------
1998 // UTF-7
1999 // ----------------------------------------------------------------------------
2000
2001 WXDLLEXPORT_DATA(wxMBConvUTF7) wxConvUTF7;
2002
2003 #if 0
2004 static char utf7_setD[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2005 "abcdefghijklmnopqrstuvwxyz"
2006 "0123456789'(),-./:?";
2007 static char utf7_setO[]="!\"#$%&*;<=>@[]^_`{|}";
2008 static char utf7_setB[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2009 "abcdefghijklmnopqrstuvwxyz"
2010 "0123456789+/";
2011 #endif
2012
2013 // TODO: write actual implementations of UTF-7 here
2014 size_t wxMBConvUTF7::MB2WC(wchar_t * WXUNUSED(buf),
2015 const char * WXUNUSED(psz),
2016 size_t WXUNUSED(n)) const
2017 {
2018 return 0;
2019 }
2020
2021 size_t wxMBConvUTF7::WC2MB(char * WXUNUSED(buf),
2022 const wchar_t * WXUNUSED(psz),
2023 size_t WXUNUSED(n)) const
2024 {
2025 return 0;
2026 }
2027
2028 // ----------------------------------------------------------------------------
2029 // UTF-8
2030 // ----------------------------------------------------------------------------
2031
2032 WXDLLEXPORT_DATA(wxMBConvUTF8) wxConvUTF8;
2033
2034 static unsigned long utf8_max[]={0x7f,0x7ff,0xffff,0x1fffff,0x3ffffff,0x7fffffff,0xffffffff};
2035
2036 size_t wxMBConvUTF8::MB2WC(wchar_t *buf, const char *psz, size_t n) const
2037 {
2038 size_t len = 0;
2039
2040 while (*psz && ((!buf) || (len<n))) {
2041 unsigned char cc=*psz++, fc=cc;
2042 unsigned cnt;
2043 for (cnt=0; fc&0x80; cnt++) fc<<=1;
2044 if (!cnt) {
2045 // plain ASCII char
2046 if (buf) *buf++=cc;
2047 len++;
2048 } else {
2049 cnt--;
2050 if (!cnt) {
2051 // invalid UTF-8 sequence
2052 return (size_t)-1;
2053 } else {
2054 unsigned ocnt=cnt-1;
2055 unsigned long res=cc&(0x3f>>cnt);
2056 while (cnt--) {
2057 cc = *psz++;
2058 if ((cc&0xC0)!=0x80) {
2059 // invalid UTF-8 sequence
2060 return (size_t)-1;
2061 }
2062 res=(res<<6)|(cc&0x3f);
2063 }
2064 if (res<=utf8_max[ocnt]) {
2065 // illegal UTF-8 encoding
2066 return (size_t)-1;
2067 }
2068 if (buf) *buf++=res;
2069 len++;
2070 }
2071 }
2072 }
2073 if (buf && (len<n)) *buf = 0;
2074 return len;
2075 }
2076
2077 size_t wxMBConvUTF8::WC2MB(char *buf, const wchar_t *psz, size_t n) const
2078 {
2079 size_t len = 0;
2080
2081 while (*psz && ((!buf) || (len<n))) {
2082 unsigned long cc=(*psz++)&0x7fffffff;
2083 unsigned cnt;
2084 for (cnt=0; cc>utf8_max[cnt]; cnt++);
2085 if (!cnt) {
2086 // plain ASCII char
2087 if (buf) *buf++=cc;
2088 len++;
2089 } else {
2090 len+=cnt+1;
2091 if (buf) {
2092 *buf++=(-128>>cnt)|((cc>>(cnt*6))&(0x3f>>cnt));
2093 while (cnt--)
2094 *buf++=0x80|((cc>>(cnt*6))&0x3f);
2095 }
2096 }
2097 }
2098 if (buf && (len<n)) *buf = 0;
2099 return len;
2100 }
2101
2102 // ----------------------------------------------------------------------------
2103 // specified character set
2104 // ----------------------------------------------------------------------------
2105
2106 class wxCharacterSet
2107 {
2108 public:
2109 wxArrayString names;
2110 wchar_t *data;
2111 };
2112
2113 #ifndef WX_PRECOMP
2114 #include "wx/dynarray.h"
2115 #include "wx/filefn.h"
2116 #include "wx/textfile.h"
2117 #include "wx/tokenzr.h"
2118 #include "wx/utils.h"
2119 #endif
2120
2121 WX_DECLARE_OBJARRAY(wxCharacterSet, wxCSArray);
2122 #include "wx/arrimpl.cpp"
2123 WX_DEFINE_OBJARRAY(wxCSArray);
2124
2125 static wxCSArray wxCharsets;
2126
2127 static void wxLoadCharacterSets(void)
2128 {
2129 static bool already_loaded = FALSE;
2130
2131 if (already_loaded) return;
2132
2133 already_loaded = TRUE;
2134 #if defined(__UNIX__) && wxUSE_TEXTFILE
2135 // search through files in /usr/share/i18n/charmaps
2136 wxString fname;
2137 for (fname = ::wxFindFirstFile(_T("/usr/share/i18n/charmaps/*"));
2138 !fname.IsEmpty();
2139 fname = ::wxFindNextFile()) {
2140 wxTextFile cmap(fname);
2141 if (cmap.Open()) {
2142 wxCharacterSet *cset = new wxCharacterSet;
2143 wxString comchar,escchar;
2144 bool in_charset = FALSE;
2145
2146 // wxFprintf(stderr,_T("Loaded: %s\n"),fname.c_str());
2147
2148 wxString line;
2149 for (line = cmap.GetFirstLine();
2150 !cmap.Eof();
2151 line = cmap.GetNextLine()) {
2152 // wxFprintf(stderr,_T("line contents: %s\n"),line.c_str());
2153 wxStringTokenizer token(line);
2154 wxString cmd = token.GetNextToken();
2155 if (cmd == comchar) {
2156 if (token.GetNextToken() == _T("alias"))
2157 cset->names.Add(token.GetNextToken());
2158 }
2159 else if (cmd == _T("<code_set_name>"))
2160 cset->names.Add(token.GetNextToken());
2161 else if (cmd == _T("<comment_char>"))
2162 comchar = token.GetNextToken();
2163 else if (cmd == _T("<escape_char>"))
2164 escchar = token.GetNextToken();
2165 else if (cmd == _T("<mb_cur_min>")) {
2166 delete cset;
2167 cset = (wxCharacterSet *) NULL;
2168 break; // we don't support multibyte charsets ourselves (yet)
2169 }
2170 else if (cmd == _T("CHARMAP")) {
2171 cset->data = (wchar_t *)calloc(256, sizeof(wchar_t));
2172 in_charset = TRUE;
2173 }
2174 else if (cmd == _T("END")) {
2175 if (token.GetNextToken() == _T("CHARMAP"))
2176 in_charset = FALSE;
2177 }
2178 else if (in_charset) {
2179 // format: <NUL> /x00 <U0000> NULL (NUL)
2180 // <A> /x41 <U0041> LATIN CAPITAL LETTER A
2181 wxString hex = token.GetNextToken();
2182 // skip whitespace (why doesn't wxStringTokenizer do this?)
2183 while (wxIsEmpty(hex) && token.HasMoreTokens()) hex = token.GetNextToken();
2184 wxString uni = token.GetNextToken();
2185 // skip whitespace again
2186 while (wxIsEmpty(uni) && token.HasMoreTokens()) uni = token.GetNextToken();
2187
2188 if ((hex.Len() > 2) && (hex.GetChar(0) == escchar) && (hex.GetChar(1) == _T('x')) &&
2189 (uni.Left(2) == _T("<U"))) {
2190 hex.MakeUpper(); uni.MakeUpper();
2191 int pos = ::wxHexToDec(hex.Mid(2,2));
2192 if (pos>=0) {
2193 unsigned long uni1 = ::wxHexToDec(uni.Mid(2,2));
2194 unsigned long uni2 = ::wxHexToDec(uni.Mid(4,2));
2195 cset->data[pos] = (uni1 << 16) | uni2;
2196 // wxFprintf(stderr,_T("char %02x mapped to %04x (%c)\n"),pos,cset->data[pos],cset->data[pos]);
2197 }
2198 }
2199 }
2200 }
2201 if (cset) {
2202 cset->names.Shrink();
2203 wxCharsets.Add(cset);
2204 }
2205 }
2206 }
2207 #endif
2208 wxCharsets.Shrink();
2209 }
2210
2211 static wxCharacterSet *wxFindCharacterSet(const wxChar *charset)
2212 {
2213 if (!charset) return (wxCharacterSet *)NULL;
2214 wxLoadCharacterSets();
2215 for (size_t n=0; n<wxCharsets.GetCount(); n++)
2216 if (wxCharsets[n].names.Index(charset) != wxNOT_FOUND)
2217 return &(wxCharsets[n]);
2218 return (wxCharacterSet *)NULL;
2219 }
2220
2221 WXDLLEXPORT_DATA(wxCSConv) wxConvLocal((const wxChar *)NULL);
2222
2223 wxCSConv::wxCSConv(const wxChar *charset)
2224 {
2225 m_name = (wxChar *) NULL;
2226 m_cset = (wxCharacterSet *) NULL;
2227 m_deferred = TRUE;
2228 SetName(charset);
2229 }
2230
2231 wxCSConv::~wxCSConv()
2232 {
2233 if (m_name) free(m_name);
2234 }
2235
2236 void wxCSConv::SetName(const wxChar *charset)
2237 {
2238 if (charset) {
2239 #ifdef __UNIX__
2240 // first, convert the character set name to standard form
2241 wxString codeset;
2242 if (wxString(charset,3).CmpNoCase(_T("ISO")) == 0) {
2243 // make sure it's represented in the standard form: ISO_8859-1
2244 codeset = _T("ISO_");
2245 charset += 3;
2246 if ((*charset == _T('-')) || (*charset == _T('_'))) charset++;
2247 if (wxStrlen(charset)>4) {
2248 if (wxString(charset,4) == _T("8859")) {
2249 codeset << _T("8859-");
2250 if (*charset == _T('-')) charset++;
2251 }
2252 }
2253 }
2254 codeset << charset;
2255 codeset.MakeUpper();
2256 m_name = wxStrdup(codeset.c_str());
2257 m_deferred = TRUE;
2258 #endif
2259 }
2260 }
2261
2262 void wxCSConv::LoadNow()
2263 {
2264 // wxPrintf(_T("Conversion request\n"));
2265 if (m_deferred) {
2266 if (!m_name) {
2267 #ifdef __UNIX__
2268 wxChar *lang = wxGetenv(_T("LANG"));
2269 wxChar *dot = lang ? wxStrchr(lang, _T('.')) : (wxChar *)NULL;
2270 if (dot) SetName(dot+1);
2271 #endif
2272 }
2273 m_cset = wxFindCharacterSet(m_name);
2274 m_deferred = FALSE;
2275 }
2276 }
2277
2278 size_t wxCSConv::MB2WC(wchar_t *buf, const char *psz, size_t n) const
2279 {
2280 ((wxCSConv *)this)->LoadNow(); // discard constness
2281 if (buf) {
2282 if (m_cset) {
2283 for (size_t c=0; c<n; c++)
2284 buf[c] = m_cset->data[(unsigned char)(psz[c])];
2285 } else {
2286 // latin-1 (direct)
2287 for (size_t c=0; c<n; c++)
2288 buf[c] = (unsigned char)(psz[c]);
2289 }
2290 return n;
2291 }
2292 return strlen(psz);
2293 }
2294
2295 size_t wxCSConv::WC2MB(char *buf, const wchar_t *psz, size_t n) const
2296 {
2297 ((wxCSConv *)this)->LoadNow(); // discard constness
2298 if (buf) {
2299 if (m_cset) {
2300 for (size_t c=0; c<n; c++) {
2301 size_t n;
2302 for (n=0; (n<256) && (m_cset->data[n] != psz[c]); n++);
2303 buf[c] = (n>0xff) ? '?' : n;
2304 }
2305 } else {
2306 // latin-1 (direct)
2307 for (size_t c=0; c<n; c++)
2308 buf[c] = (psz[c]>0xff) ? '?' : psz[c];
2309 }
2310 return n;
2311 }
2312 return wcslen(psz);
2313 }
2314
2315 #endif//wxUSE_WCHAR_T
2316
2317 #if wxUSE_WCHAR_T
2318 const wxWCharBuffer wxMBConv::cMB2WC(const char *psz) const
2319 {
2320 if (psz) {
2321 size_t nLen = MB2WC((wchar_t *) NULL, psz, 0);
2322 wxWCharBuffer buf(nLen);
2323 MB2WC(WCSTRINGCAST buf, psz, nLen);
2324 return buf;
2325 } else return wxWCharBuffer((wchar_t *) NULL);
2326 }
2327
2328 const wxCharBuffer wxMBConv::cWC2MB(const wchar_t *psz) const
2329 {
2330 if (psz) {
2331 size_t nLen = WC2MB((char *) NULL, psz, 0);
2332 wxCharBuffer buf(nLen);
2333 WC2MB(MBSTRINGCAST buf, psz, nLen);
2334 return buf;
2335 } else return wxCharBuffer((char *) NULL);
2336 }
2337
2338 #endif//wxUSE_WCHAR_T
2339