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