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