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