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