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