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