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