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