]> git.saurik.com Git - wxWidgets.git/blame - src/common/string.cpp
Motif cell highlighting problem fixed
[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"
c801d85f
KB
38#endif
39
40#include <ctype.h>
41#include <string.h>
42#include <stdlib.h>
43
ce3ed50d 44#ifdef __SALFORDC__
30b21f9a 45 #include <clib.h>
ce3ed50d
JS
46#endif
47
ede25f5b 48#if wxUSE_WCSRTOMBS
fb4e5803
VZ
49 #include <wchar.h> // for wcsrtombs(), see comments where it's used
50#endif // GNU
51
c801d85f
KB
52#ifdef WXSTRING_IS_WXOBJECT
53 IMPLEMENT_DYNAMIC_CLASS(wxString, wxObject)
54#endif //WXSTRING_IS_WXOBJECT
55
3168a13f
VZ
56// allocating extra space for each string consumes more memory but speeds up
57// the concatenation operations (nLen is the current string's length)
77ca46e7
VZ
58// NB: EXTRA_ALLOC must be >= 0!
59#define EXTRA_ALLOC (19 - nLen % 16)
3168a13f 60
c801d85f
KB
61// ---------------------------------------------------------------------------
62// static class variables definition
63// ---------------------------------------------------------------------------
64
8de2e39c 65#ifdef wxSTD_STRING_COMPATIBILITY
566b84d2 66 const size_t wxString::npos = wxSTRING_MAXLEN;
8de2e39c 67#endif // wxSTD_STRING_COMPATIBILITY
c801d85f 68
3168a13f
VZ
69// ----------------------------------------------------------------------------
70// static data
71// ----------------------------------------------------------------------------
c801d85f 72
3c024cc2
VZ
73// for an empty string, GetStringData() will return this address: this
74// structure has the same layout as wxStringData and it's data() method will
75// return the empty string (dummy pointer)
76static const struct
77{
78 wxStringData data;
79 char dummy;
80} g_strEmpty = { {-1, 0, 0}, '\0' };
81
c801d85f 82// empty C style string: points to 'string data' byte of g_strEmpty
ba681060 83extern const char WXDLLEXPORT *g_szNul = &g_strEmpty.dummy;
c801d85f 84
89b892a2
VZ
85// ----------------------------------------------------------------------------
86// conditional compilation
87// ----------------------------------------------------------------------------
88
89// we want to find out if the current platform supports vsnprintf()-like
90// function: for Unix this is done with configure, for Windows we test the
91// compiler explicitly.
92#ifdef __WXMSW__
3f4a0c5b 93 #ifdef __VISUALC__
89b892a2
VZ
94 #define wxVsprintf _vsnprintf
95 #endif
96#else // !Windows
97 #ifdef HAVE_VSNPRINTF
98 #define wxVsprintf vsnprintf
99 #endif
100#endif // Windows/!Windows
101
102#ifndef wxVsprintf
103 // in this case we'll use vsprintf() (which is ANSI and thus should be
104 // always available), but it's unsafe because it doesn't check for buffer
105 // size - so give a warning
106 #define wxVsprintf(buffer,len,format,argptr) vsprintf(buffer,format, argptr)
566b84d2 107
57493f9f
VZ
108 #if defined(__VISUALC__)
109 #pragma message("Using sprintf() because no snprintf()-like function defined")
110 #elif defined(__GNUG__) && !defined(__UNIX__)
111 #warning "Using sprintf() because no snprintf()-like function defined"
112 #elif defined(__MWERKS__)
113 #warning "Using sprintf() because no snprintf()-like function defined"
114 #endif //compiler
3f4a0c5b 115#endif // no vsnprintf
89b892a2 116
3168a13f 117// ----------------------------------------------------------------------------
c801d85f 118// global functions
3168a13f 119// ----------------------------------------------------------------------------
c801d85f 120
8de2e39c 121#ifdef wxSTD_STRING_COMPATIBILITY
c801d85f
KB
122
123// MS Visual C++ version 5.0 provides the new STL headers as well as the old
124// iostream ones.
125//
126// ATTN: you can _not_ use both of these in the same program!
a38b83c3 127
3f4a0c5b 128istream& operator>>(istream& is, wxString& WXUNUSED(str))
c801d85f
KB
129{
130#if 0
131 int w = is.width(0);
132 if ( is.ipfx(0) ) {
3f4a0c5b 133 streambuf *sb = is.rdbuf();
c801d85f
KB
134 str.erase();
135 while ( true ) {
136 int ch = sb->sbumpc ();
137 if ( ch == EOF ) {
3f4a0c5b 138 is.setstate(ios::eofbit);
c801d85f
KB
139 break;
140 }
141 else if ( isspace(ch) ) {
142 sb->sungetc();
143 break;
144 }
dd1eaa89 145
c801d85f
KB
146 str += ch;
147 if ( --w == 1 )
148 break;
149 }
150 }
151
152 is.isfx();
153 if ( str.length() == 0 )
3f4a0c5b 154 is.setstate(ios::failbit);
c801d85f
KB
155#endif
156 return is;
157}
158
159#endif //std::string compatibility
160
3168a13f
VZ
161// ----------------------------------------------------------------------------
162// private classes
163// ----------------------------------------------------------------------------
164
165// this small class is used to gather statistics for performance tuning
166//#define WXSTRING_STATISTICS
167#ifdef WXSTRING_STATISTICS
168 class Averager
169 {
170 public:
171 Averager(const char *sz) { m_sz = sz; m_nTotal = m_nCount = 0; }
2c3b684c 172 ~Averager()
3168a13f
VZ
173 { printf("wxString: average %s = %f\n", m_sz, ((float)m_nTotal)/m_nCount); }
174
c86f1403 175 void Add(size_t n) { m_nTotal += n; m_nCount++; }
3168a13f
VZ
176
177 private:
c86f1403 178 size_t m_nCount, m_nTotal;
3168a13f
VZ
179 const char *m_sz;
180 } g_averageLength("allocation size"),
181 g_averageSummandLength("summand length"),
182 g_averageConcatHit("hit probability in concat"),
183 g_averageInitialLength("initial string length");
184
185 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
186#else
187 #define STATISTICS_ADD(av, val)
188#endif // WXSTRING_STATISTICS
189
c801d85f
KB
190// ===========================================================================
191// wxString class core
192// ===========================================================================
193
194// ---------------------------------------------------------------------------
195// construction
196// ---------------------------------------------------------------------------
197
c801d85f
KB
198// constructs string of <nLength> copies of character <ch>
199wxString::wxString(char ch, size_t nLength)
200{
201 Init();
202
203 if ( nLength > 0 ) {
204 AllocBuffer(nLength);
f1da2f03 205
c801d85f
KB
206 wxASSERT( sizeof(char) == 1 ); // can't use memset if not
207
208 memset(m_pchData, ch, nLength);
209 }
210}
211
212// takes nLength elements of psz starting at nPos
213void wxString::InitWith(const char *psz, size_t nPos, size_t nLength)
214{
215 Init();
216
217 wxASSERT( nPos <= Strlen(psz) );
218
566b84d2 219 if ( nLength == wxSTRING_MAXLEN )
c801d85f
KB
220 nLength = Strlen(psz + nPos);
221
3168a13f
VZ
222 STATISTICS_ADD(InitialLength, nLength);
223
c801d85f
KB
224 if ( nLength > 0 ) {
225 // trailing '\0' is written in AllocBuffer()
226 AllocBuffer(nLength);
227 memcpy(m_pchData, psz + nPos, nLength*sizeof(char));
228 }
229}
dd1eaa89 230
c801d85f
KB
231// the same as previous constructor, but for compilers using unsigned char
232wxString::wxString(const unsigned char* psz, size_t nLength)
233{
234 InitWith((const char *)psz, 0, nLength);
dd1eaa89
VZ
235}
236
8de2e39c 237#ifdef wxSTD_STRING_COMPATIBILITY
c801d85f 238
c801d85f
KB
239// poor man's iterators are "void *" pointers
240wxString::wxString(const void *pStart, const void *pEnd)
241{
dd1eaa89 242 InitWith((const char *)pStart, 0,
c801d85f
KB
243 (const char *)pEnd - (const char *)pStart);
244}
245
246#endif //std::string compatibility
247
248// from wide string
249wxString::wxString(const wchar_t *pwz)
250{
251 // first get necessary size
fb4e5803
VZ
252
253 // NB: GNU libc5 wcstombs() is completely broken, don't use it (it doesn't
254 // honor the 3rd parameter, thus it will happily crash here).
ede25f5b 255#if wxUSE_WCSRTOMBS
fb4e5803
VZ
256 // don't know if it's really needed (or if we can pass NULL), but better safe
257 // than quick
258 mbstate_t mbstate;
259 size_t nLen = wcsrtombs((char *) NULL, &pwz, 0, &mbstate);
260#else // !GNU libc
c67daf87 261 size_t nLen = wcstombs((char *) NULL, pwz, 0);
fb4e5803 262#endif // GNU
c801d85f
KB
263
264 // empty?
265 if ( nLen != 0 ) {
266 AllocBuffer(nLen);
267 wcstombs(m_pchData, pwz, nLen);
268 }
269 else {
270 Init();
271 }
272}
273
274// ---------------------------------------------------------------------------
275// memory allocation
276// ---------------------------------------------------------------------------
277
278// allocates memory needed to store a C string of length nLen
279void wxString::AllocBuffer(size_t nLen)
280{
281 wxASSERT( nLen > 0 ); //
282 wxASSERT( nLen <= INT_MAX-1 ); // max size (enough room for 1 extra)
283
3168a13f
VZ
284 STATISTICS_ADD(Length, nLen);
285
c801d85f
KB
286 // allocate memory:
287 // 1) one extra character for '\0' termination
288 // 2) sizeof(wxStringData) for housekeeping info
3168a13f
VZ
289 wxStringData* pData = (wxStringData*)
290 malloc(sizeof(wxStringData) + (nLen + EXTRA_ALLOC + 1)*sizeof(char));
c801d85f 291 pData->nRefs = 1;
c801d85f 292 pData->nDataLength = nLen;
3168a13f 293 pData->nAllocLength = nLen + EXTRA_ALLOC;
c801d85f 294 m_pchData = pData->data(); // data starts after wxStringData
3168a13f 295 m_pchData[nLen] = '\0';
c801d85f
KB
296}
297
c801d85f
KB
298// must be called before changing this string
299void wxString::CopyBeforeWrite()
300{
301 wxStringData* pData = GetStringData();
302
303 if ( pData->IsShared() ) {
304 pData->Unlock(); // memory not freed because shared
c86f1403 305 size_t nLen = pData->nDataLength;
3168a13f
VZ
306 AllocBuffer(nLen);
307 memcpy(m_pchData, pData->data(), nLen*sizeof(char));
c801d85f
KB
308 }
309
3bbb630a 310 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
c801d85f
KB
311}
312
313// must be called before replacing contents of this string
314void wxString::AllocBeforeWrite(size_t nLen)
315{
316 wxASSERT( nLen != 0 ); // doesn't make any sense
317
318 // must not share string and must have enough space
3168a13f 319 wxStringData* pData = GetStringData();
c801d85f
KB
320 if ( pData->IsShared() || (nLen > pData->nAllocLength) ) {
321 // can't work with old buffer, get new one
322 pData->Unlock();
323 AllocBuffer(nLen);
324 }
471aebdd
VZ
325 else {
326 // update the string length
327 pData->nDataLength = nLen;
328 }
c801d85f 329
f1da2f03 330 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
c801d85f
KB
331}
332
dd1eaa89 333// allocate enough memory for nLen characters
c86f1403 334void wxString::Alloc(size_t nLen)
dd1eaa89
VZ
335{
336 wxStringData *pData = GetStringData();
337 if ( pData->nAllocLength <= nLen ) {
9fbd8b8d
VZ
338 if ( pData->IsEmpty() ) {
339 nLen += EXTRA_ALLOC;
340
341 wxStringData* pData = (wxStringData*)
342 malloc(sizeof(wxStringData) + (nLen + 1)*sizeof(char));
343 pData->nRefs = 1;
344 pData->nDataLength = 0;
345 pData->nAllocLength = nLen;
346 m_pchData = pData->data(); // data starts after wxStringData
347 m_pchData[0u] = '\0';
348 }
3168a13f
VZ
349 else if ( pData->IsShared() ) {
350 pData->Unlock(); // memory not freed because shared
c86f1403 351 size_t nOldLen = pData->nDataLength;
3168a13f 352 AllocBuffer(nLen);
9fbd8b8d 353 memcpy(m_pchData, pData->data(), nOldLen*sizeof(char));
3168a13f 354 }
dd1eaa89 355 else {
3168a13f
VZ
356 nLen += EXTRA_ALLOC;
357
dd1eaa89
VZ
358 wxStringData *p = (wxStringData *)
359 realloc(pData, sizeof(wxStringData) + (nLen + 1)*sizeof(char));
3168a13f
VZ
360
361 if ( p == NULL ) {
362 // @@@ what to do on memory error?
363 return;
dd1eaa89 364 }
3168a13f
VZ
365
366 // it's not important if the pointer changed or not (the check for this
367 // is not faster than assigning to m_pchData in all cases)
368 p->nAllocLength = nLen;
369 m_pchData = p->data();
dd1eaa89
VZ
370 }
371 }
372 //else: we've already got enough
373}
374
375// shrink to minimal size (releasing extra memory)
376void wxString::Shrink()
377{
378 wxStringData *pData = GetStringData();
3bbb630a
VZ
379
380 // this variable is unused in release build, so avoid the compiler warning by
381 // just not declaring it
382#ifdef __WXDEBUG__
383 void *p =
384#endif
385 realloc(pData, sizeof(wxStringData) + (pData->nDataLength + 1)*sizeof(char));
386
3168a13f 387 wxASSERT( p != NULL ); // can't free memory?
dd1eaa89
VZ
388 wxASSERT( p == pData ); // we're decrementing the size - block shouldn't move!
389}
390
c801d85f 391// get the pointer to writable buffer of (at least) nLen bytes
c86f1403 392char *wxString::GetWriteBuf(size_t nLen)
c801d85f
KB
393{
394 AllocBeforeWrite(nLen);
097c080b
VZ
395
396 wxASSERT( GetStringData()->nRefs == 1 );
397 GetStringData()->Validate(FALSE);
398
c801d85f
KB
399 return m_pchData;
400}
401
097c080b
VZ
402// put string back in a reasonable state after GetWriteBuf
403void wxString::UngetWriteBuf()
404{
405 GetStringData()->nDataLength = strlen(m_pchData);
406 GetStringData()->Validate(TRUE);
407}
408
c801d85f
KB
409// ---------------------------------------------------------------------------
410// data access
411// ---------------------------------------------------------------------------
412
413// all functions are inline in string.h
414
415// ---------------------------------------------------------------------------
416// assignment operators
417// ---------------------------------------------------------------------------
418
dd1eaa89 419// helper function: does real copy
c801d85f
KB
420void wxString::AssignCopy(size_t nSrcLen, const char *pszSrcData)
421{
422 if ( nSrcLen == 0 ) {
423 Reinit();
424 }
425 else {
426 AllocBeforeWrite(nSrcLen);
427 memcpy(m_pchData, pszSrcData, nSrcLen*sizeof(char));
428 GetStringData()->nDataLength = nSrcLen;
429 m_pchData[nSrcLen] = '\0';
430 }
431}
432
433// assigns one string to another
434wxString& wxString::operator=(const wxString& stringSrc)
435{
097c080b
VZ
436 wxASSERT( stringSrc.GetStringData()->IsValid() );
437
c801d85f
KB
438 // don't copy string over itself
439 if ( m_pchData != stringSrc.m_pchData ) {
440 if ( stringSrc.GetStringData()->IsEmpty() ) {
441 Reinit();
442 }
443 else {
444 // adjust references
445 GetStringData()->Unlock();
446 m_pchData = stringSrc.m_pchData;
447 GetStringData()->Lock();
448 }
449 }
450
451 return *this;
452}
453
454// assigns a single character
455wxString& wxString::operator=(char ch)
456{
457 AssignCopy(1, &ch);
458 return *this;
459}
460
461// assigns C string
462wxString& wxString::operator=(const char *psz)
463{
464 AssignCopy(Strlen(psz), psz);
465 return *this;
466}
467
468// same as 'signed char' variant
469wxString& wxString::operator=(const unsigned char* psz)
470{
471 *this = (const char *)psz;
472 return *this;
473}
474
475wxString& wxString::operator=(const wchar_t *pwz)
476{
477 wxString str(pwz);
478 *this = str;
479 return *this;
480}
481
482// ---------------------------------------------------------------------------
483// string concatenation
484// ---------------------------------------------------------------------------
485
c801d85f
KB
486// add something to this string
487void wxString::ConcatSelf(int nSrcLen, const char *pszSrcData)
488{
3168a13f 489 STATISTICS_ADD(SummandLength, nSrcLen);
c801d85f 490
05488905
VZ
491 // concatenating an empty string is a NOP
492 if ( nSrcLen > 0 ) {
493 wxStringData *pData = GetStringData();
494 size_t nLen = pData->nDataLength;
495 size_t nNewLen = nLen + nSrcLen;
c801d85f 496
05488905
VZ
497 // alloc new buffer if current is too small
498 if ( pData->IsShared() ) {
499 STATISTICS_ADD(ConcatHit, 0);
3168a13f 500
05488905
VZ
501 // we have to allocate another buffer
502 wxStringData* pOldData = GetStringData();
503 AllocBuffer(nNewLen);
504 memcpy(m_pchData, pOldData->data(), nLen*sizeof(char));
505 pOldData->Unlock();
506 }
507 else if ( nNewLen > pData->nAllocLength ) {
508 STATISTICS_ADD(ConcatHit, 0);
3168a13f 509
05488905
VZ
510 // we have to grow the buffer
511 Alloc(nNewLen);
512 }
513 else {
514 STATISTICS_ADD(ConcatHit, 1);
3168a13f 515
05488905
VZ
516 // the buffer is already big enough
517 }
3168a13f 518
05488905
VZ
519 // should be enough space
520 wxASSERT( nNewLen <= GetStringData()->nAllocLength );
3168a13f 521
05488905
VZ
522 // fast concatenation - all is done in our buffer
523 memcpy(m_pchData + nLen, pszSrcData, nSrcLen*sizeof(char));
3168a13f 524
05488905
VZ
525 m_pchData[nNewLen] = '\0'; // put terminating '\0'
526 GetStringData()->nDataLength = nNewLen; // and fix the length
527 }
528 //else: the string to append was empty
c801d85f
KB
529}
530
531/*
c801d85f
KB
532 * concatenation functions come in 5 flavours:
533 * string + string
534 * char + string and string + char
535 * C str + string and string + C str
536 */
537
538wxString operator+(const wxString& string1, const wxString& string2)
539{
097c080b
VZ
540 wxASSERT( string1.GetStringData()->IsValid() );
541 wxASSERT( string2.GetStringData()->IsValid() );
542
3168a13f
VZ
543 wxString s = string1;
544 s += string2;
545
c801d85f
KB
546 return s;
547}
548
3168a13f 549wxString operator+(const wxString& string, char ch)
c801d85f 550{
3168a13f
VZ
551 wxASSERT( string.GetStringData()->IsValid() );
552
553 wxString s = string;
554 s += ch;
097c080b 555
c801d85f
KB
556 return s;
557}
558
559wxString operator+(char ch, const wxString& string)
560{
097c080b
VZ
561 wxASSERT( string.GetStringData()->IsValid() );
562
3168a13f
VZ
563 wxString s = ch;
564 s += string;
565
c801d85f
KB
566 return s;
567}
568
569wxString operator+(const wxString& string, const char *psz)
570{
097c080b
VZ
571 wxASSERT( string.GetStringData()->IsValid() );
572
c801d85f 573 wxString s;
3168a13f
VZ
574 s.Alloc(Strlen(psz) + string.Len());
575 s = string;
576 s += psz;
577
c801d85f
KB
578 return s;
579}
580
581wxString operator+(const char *psz, const wxString& string)
582{
097c080b
VZ
583 wxASSERT( string.GetStringData()->IsValid() );
584
c801d85f 585 wxString s;
3168a13f
VZ
586 s.Alloc(Strlen(psz) + string.Len());
587 s = psz;
588 s += string;
589
c801d85f
KB
590 return s;
591}
592
593// ===========================================================================
594// other common string functions
595// ===========================================================================
596
597// ---------------------------------------------------------------------------
598// simple sub-string extraction
599// ---------------------------------------------------------------------------
600
601// helper function: clone the data attached to this string
602void wxString::AllocCopy(wxString& dest, int nCopyLen, int nCopyIndex) const
603{
3168a13f 604 if ( nCopyLen == 0 ) {
c801d85f
KB
605 dest.Init();
606 }
3168a13f 607 else {
c801d85f
KB
608 dest.AllocBuffer(nCopyLen);
609 memcpy(dest.m_pchData, m_pchData + nCopyIndex, nCopyLen*sizeof(char));
610 }
611}
612
613// extract string of length nCount starting at nFirst
c801d85f
KB
614wxString wxString::Mid(size_t nFirst, size_t nCount) const
615{
30d9011f
VZ
616 wxStringData *pData = GetStringData();
617 size_t nLen = pData->nDataLength;
618
566b84d2
VZ
619 // default value of nCount is wxSTRING_MAXLEN and means "till the end"
620 if ( nCount == wxSTRING_MAXLEN )
30d9011f
VZ
621 {
622 nCount = nLen - nFirst;
623 }
624
c801d85f 625 // out-of-bounds requests return sensible things
30d9011f
VZ
626 if ( nFirst + nCount > nLen )
627 {
628 nCount = nLen - nFirst;
629 }
c801d85f 630
30d9011f
VZ
631 if ( nFirst > nLen )
632 {
633 // AllocCopy() will return empty string
c801d85f 634 nCount = 0;
30d9011f 635 }
c801d85f
KB
636
637 wxString dest;
638 AllocCopy(dest, nCount, nFirst);
30d9011f 639
c801d85f
KB
640 return dest;
641}
642
643// extract nCount last (rightmost) characters
644wxString wxString::Right(size_t nCount) const
645{
646 if ( nCount > (size_t)GetStringData()->nDataLength )
647 nCount = GetStringData()->nDataLength;
648
649 wxString dest;
650 AllocCopy(dest, nCount, GetStringData()->nDataLength - nCount);
651 return dest;
652}
653
654// get all characters after the last occurence of ch
655// (returns the whole string if ch not found)
3c67202d 656wxString wxString::AfterLast(char ch) const
c801d85f
KB
657{
658 wxString str;
659 int iPos = Find(ch, TRUE);
3c67202d 660 if ( iPos == wxNOT_FOUND )
c801d85f
KB
661 str = *this;
662 else
c8cfb486 663 str = c_str() + iPos + 1;
c801d85f
KB
664
665 return str;
666}
667
668// extract nCount first (leftmost) characters
669wxString wxString::Left(size_t nCount) const
670{
671 if ( nCount > (size_t)GetStringData()->nDataLength )
672 nCount = GetStringData()->nDataLength;
673
674 wxString dest;
675 AllocCopy(dest, nCount, 0);
676 return dest;
677}
678
679// get all characters before the first occurence of ch
680// (returns the whole string if ch not found)
3c67202d 681wxString wxString::BeforeFirst(char ch) const
c801d85f
KB
682{
683 wxString str;
684 for ( const char *pc = m_pchData; *pc != '\0' && *pc != ch; pc++ )
685 str += *pc;
686
687 return str;
688}
689
690/// get all characters before the last occurence of ch
691/// (returns empty string if ch not found)
3c67202d 692wxString wxString::BeforeLast(char ch) const
c801d85f
KB
693{
694 wxString str;
695 int iPos = Find(ch, TRUE);
3c67202d 696 if ( iPos != wxNOT_FOUND && iPos != 0 )
d1c9bbf6 697 str = wxString(c_str(), iPos);
c801d85f
KB
698
699 return str;
700}
701
702/// get all characters after the first occurence of ch
703/// (returns empty string if ch not found)
3c67202d 704wxString wxString::AfterFirst(char ch) const
c801d85f
KB
705{
706 wxString str;
707 int iPos = Find(ch);
3c67202d 708 if ( iPos != wxNOT_FOUND )
c801d85f
KB
709 str = c_str() + iPos + 1;
710
711 return str;
712}
713
714// replace first (or all) occurences of some substring with another one
c86f1403 715size_t wxString::Replace(const char *szOld, const char *szNew, bool bReplaceAll)
c801d85f 716{
c86f1403 717 size_t uiCount = 0; // count of replacements made
c801d85f 718
c86f1403 719 size_t uiOldLen = Strlen(szOld);
c801d85f
KB
720
721 wxString strTemp;
722 const char *pCurrent = m_pchData;
dd1eaa89 723 const char *pSubstr;
c801d85f
KB
724 while ( *pCurrent != '\0' ) {
725 pSubstr = strstr(pCurrent, szOld);
726 if ( pSubstr == NULL ) {
727 // strTemp is unused if no replacements were made, so avoid the copy
728 if ( uiCount == 0 )
729 return 0;
730
731 strTemp += pCurrent; // copy the rest
732 break; // exit the loop
733 }
734 else {
735 // take chars before match
736 strTemp.ConcatSelf(pSubstr - pCurrent, pCurrent);
737 strTemp += szNew;
738 pCurrent = pSubstr + uiOldLen; // restart after match
739
740 uiCount++;
741
742 // stop now?
743 if ( !bReplaceAll ) {
744 strTemp += pCurrent; // copy the rest
745 break; // exit the loop
746 }
747 }
748 }
749
750 // only done if there were replacements, otherwise would have returned above
751 *this = strTemp;
752
753 return uiCount;
754}
755
756bool wxString::IsAscii() const
757{
758 const char *s = (const char*) *this;
759 while(*s){
760 if(!isascii(*s)) return(FALSE);
761 s++;
762 }
763 return(TRUE);
764}
dd1eaa89 765
c801d85f
KB
766bool wxString::IsWord() const
767{
768 const char *s = (const char*) *this;
769 while(*s){
770 if(!isalpha(*s)) return(FALSE);
771 s++;
772 }
773 return(TRUE);
774}
dd1eaa89 775
c801d85f
KB
776bool wxString::IsNumber() const
777{
778 const char *s = (const char*) *this;
779 while(*s){
780 if(!isdigit(*s)) return(FALSE);
781 s++;
782 }
783 return(TRUE);
784}
785
c801d85f
KB
786wxString wxString::Strip(stripType w) const
787{
788 wxString s = *this;
789 if ( w & leading ) s.Trim(FALSE);
790 if ( w & trailing ) s.Trim(TRUE);
791 return s;
792}
793
c801d85f
KB
794// ---------------------------------------------------------------------------
795// case conversion
796// ---------------------------------------------------------------------------
797
798wxString& wxString::MakeUpper()
799{
800 CopyBeforeWrite();
801
802 for ( char *p = m_pchData; *p; p++ )
803 *p = (char)toupper(*p);
804
805 return *this;
806}
807
808wxString& wxString::MakeLower()
809{
810 CopyBeforeWrite();
dd1eaa89 811
c801d85f
KB
812 for ( char *p = m_pchData; *p; p++ )
813 *p = (char)tolower(*p);
814
815 return *this;
816}
817
818// ---------------------------------------------------------------------------
819// trimming and padding
820// ---------------------------------------------------------------------------
821
822// trims spaces (in the sense of isspace) from left or right side
823wxString& wxString::Trim(bool bFromRight)
824{
2c3b684c
VZ
825 // first check if we're going to modify the string at all
826 if ( !IsEmpty() &&
827 (
828 (bFromRight && isspace(GetChar(Len() - 1))) ||
829 (!bFromRight && isspace(GetChar(0u)))
830 )
831 )
c801d85f 832 {
2c3b684c
VZ
833 // ok, there is at least one space to trim
834 CopyBeforeWrite();
835
836 if ( bFromRight )
837 {
838 // find last non-space character
839 char *psz = m_pchData + GetStringData()->nDataLength - 1;
840 while ( isspace(*psz) && (psz >= m_pchData) )
841 psz--;
842
843 // truncate at trailing space start
844 *++psz = '\0';
845 GetStringData()->nDataLength = psz - m_pchData;
846 }
847 else
848 {
849 // find first non-space character
850 const char *psz = m_pchData;
851 while ( isspace(*psz) )
852 psz++;
853
854 // fix up data and length
ce3ed50d 855 int nDataLength = GetStringData()->nDataLength - (psz - (const char*) m_pchData);
2c3b684c
VZ
856 memmove(m_pchData, psz, (nDataLength + 1)*sizeof(char));
857 GetStringData()->nDataLength = nDataLength;
858 }
c801d85f
KB
859 }
860
861 return *this;
862}
863
864// adds nCount characters chPad to the string from either side
865wxString& wxString::Pad(size_t nCount, char chPad, bool bFromRight)
866{
867 wxString s(chPad, nCount);
868
869 if ( bFromRight )
870 *this += s;
871 else
872 {
873 s += *this;
874 *this = s;
875 }
876
877 return *this;
878}
879
880// truncate the string
881wxString& wxString::Truncate(size_t uiLen)
882{
79a773ba
VZ
883 if ( uiLen < Len() ) {
884 CopyBeforeWrite();
885
886 *(m_pchData + uiLen) = '\0';
887 GetStringData()->nDataLength = uiLen;
888 }
889 //else: nothing to do, string is already short enough
c801d85f
KB
890
891 return *this;
892}
893
894// ---------------------------------------------------------------------------
3c67202d 895// finding (return wxNOT_FOUND if not found and index otherwise)
c801d85f
KB
896// ---------------------------------------------------------------------------
897
898// find a character
899int wxString::Find(char ch, bool bFromEnd) const
900{
901 const char *psz = bFromEnd ? strrchr(m_pchData, ch) : strchr(m_pchData, ch);
902
ce3ed50d 903 return (psz == NULL) ? wxNOT_FOUND : psz - (const char*) m_pchData;
c801d85f
KB
904}
905
906// find a sub-string (like strstr)
907int wxString::Find(const char *pszSub) const
908{
909 const char *psz = strstr(m_pchData, pszSub);
910
ce3ed50d 911 return (psz == NULL) ? wxNOT_FOUND : psz - (const char*) m_pchData;
c801d85f
KB
912}
913
7be07660
VZ
914// ---------------------------------------------------------------------------
915// stream-like operators
916// ---------------------------------------------------------------------------
917wxString& wxString::operator<<(int i)
918{
919 wxString res;
920 res.Printf("%d", i);
921
922 return (*this) << res;
923}
924
925wxString& wxString::operator<<(float f)
926{
927 wxString res;
928 res.Printf("%f", f);
929
930 return (*this) << res;
931}
932
933wxString& wxString::operator<<(double d)
934{
935 wxString res;
936 res.Printf("%g", d);
937
938 return (*this) << res;
939}
940
c801d85f 941// ---------------------------------------------------------------------------
9efd3367 942// formatted output
c801d85f
KB
943// ---------------------------------------------------------------------------
944int wxString::Printf(const char *pszFormat, ...)
945{
946 va_list argptr;
947 va_start(argptr, pszFormat);
948
949 int iLen = PrintfV(pszFormat, argptr);
950
951 va_end(argptr);
952
953 return iLen;
954}
955
956int wxString::PrintfV(const char* pszFormat, va_list argptr)
957{
7be07660 958 // static buffer to avoid dynamic memory allocation each time
9efd3367 959 static char s_szScratch[1024];
c801d85f 960
89b892a2
VZ
961 // NB: wxVsprintf() may return either less than the buffer size or -1 if there
962 // is not enough place depending on implementation
7be07660
VZ
963 int iLen = wxVsprintf(s_szScratch, WXSIZEOF(s_szScratch), pszFormat, argptr);
964 char *buffer;
89b892a2 965 if ( iLen < (int)WXSIZEOF(s_szScratch) ) {
7be07660
VZ
966 buffer = s_szScratch;
967 }
968 else {
969 int size = WXSIZEOF(s_szScratch) * 2;
970 buffer = (char *)malloc(size);
971 while ( buffer != NULL ) {
972 iLen = wxVsprintf(buffer, WXSIZEOF(s_szScratch), pszFormat, argptr);
973 if ( iLen < size ) {
974 // ok, there was enough space
975 break;
976 }
977
978 // still not enough, double it again
979 buffer = (char *)realloc(buffer, size *= 2);
980 }
981
982 if ( !buffer ) {
983 // out of memory
984 return -1;
985 }
986 }
987
c801d85f 988 AllocBeforeWrite(iLen);
7be07660
VZ
989 strcpy(m_pchData, buffer);
990
991 if ( buffer != s_szScratch )
992 free(buffer);
c801d85f
KB
993
994 return iLen;
995}
996
097c080b
VZ
997// ----------------------------------------------------------------------------
998// misc other operations
999// ----------------------------------------------------------------------------
1000bool wxString::Matches(const char *pszMask) const
1001{
1002 // check char by char
1003 const char *pszTxt;
1004 for ( pszTxt = c_str(); *pszMask != '\0'; pszMask++, pszTxt++ ) {
1005 switch ( *pszMask ) {
1006 case '?':
1007 if ( *pszTxt == '\0' )
1008 return FALSE;
1009
1010 pszTxt++;
1011 pszMask++;
1012 break;
1013
1014 case '*':
1015 {
1016 // ignore special chars immediately following this one
1017 while ( *pszMask == '*' || *pszMask == '?' )
1018 pszMask++;
1019
1020 // if there is nothing more, match
1021 if ( *pszMask == '\0' )
1022 return TRUE;
1023
1024 // are there any other metacharacters in the mask?
c86f1403 1025 size_t uiLenMask;
097c080b
VZ
1026 const char *pEndMask = strpbrk(pszMask, "*?");
1027
1028 if ( pEndMask != NULL ) {
1029 // we have to match the string between two metachars
1030 uiLenMask = pEndMask - pszMask;
1031 }
1032 else {
1033 // we have to match the remainder of the string
1034 uiLenMask = strlen(pszMask);
1035 }
1036
1037 wxString strToMatch(pszMask, uiLenMask);
1038 const char* pMatch = strstr(pszTxt, strToMatch);
1039 if ( pMatch == NULL )
1040 return FALSE;
1041
1042 // -1 to compensate "++" in the loop
1043 pszTxt = pMatch + uiLenMask - 1;
1044 pszMask += uiLenMask - 1;
1045 }
1046 break;
1047
1048 default:
1049 if ( *pszMask != *pszTxt )
1050 return FALSE;
1051 break;
1052 }
1053 }
1054
1055 // match only if nothing left
1056 return *pszTxt == '\0';
1057}
1058
1fc5dd6f
JS
1059// Count the number of chars
1060int wxString::Freq(char ch) const
1061{
1062 int count = 0;
1063 int len = Len();
1064 for (int i = 0; i < len; i++)
1065 {
1066 if (GetChar(i) == ch)
1067 count ++;
1068 }
1069 return count;
1070}
1071
03ab016d
JS
1072// convert to upper case, return the copy of the string
1073wxString wxString::Upper() const
1074{ wxString s(*this); return s.MakeUpper(); }
1075
1076// convert to lower case, return the copy of the string
1077wxString wxString::Lower() const { wxString s(*this); return s.MakeLower(); }
1078
8870c26e
JS
1079int wxString::sprintf(const char *pszFormat, ...)
1080 {
1081 va_list argptr;
1082 va_start(argptr, pszFormat);
1083 int iLen = PrintfV(pszFormat, argptr);
1084 va_end(argptr);
1085 return iLen;
1086 }
1087
c801d85f
KB
1088// ---------------------------------------------------------------------------
1089// standard C++ library string functions
1090// ---------------------------------------------------------------------------
8de2e39c 1091#ifdef wxSTD_STRING_COMPATIBILITY
c801d85f
KB
1092
1093wxString& wxString::insert(size_t nPos, const wxString& str)
1094{
097c080b 1095 wxASSERT( str.GetStringData()->IsValid() );
c801d85f
KB
1096 wxASSERT( nPos <= Len() );
1097
cb6780ff
VZ
1098 if ( !str.IsEmpty() ) {
1099 wxString strTmp;
1100 char *pc = strTmp.GetWriteBuf(Len() + str.Len());
1101 strncpy(pc, c_str(), nPos);
1102 strcpy(pc + nPos, str);
1103 strcpy(pc + nPos + str.Len(), c_str() + nPos);
1104 strTmp.UngetWriteBuf();
1105 *this = strTmp;
1106 }
dd1eaa89
VZ
1107
1108 return *this;
c801d85f
KB
1109}
1110
1111size_t wxString::find(const wxString& str, size_t nStart) const
1112{
097c080b 1113 wxASSERT( str.GetStringData()->IsValid() );
c801d85f
KB
1114 wxASSERT( nStart <= Len() );
1115
1116 const char *p = strstr(c_str() + nStart, str);
dd1eaa89 1117
c801d85f
KB
1118 return p == NULL ? npos : p - c_str();
1119}
1120
f0b3249b 1121// VC++ 1.5 can't cope with the default argument in the header.
3f4a0c5b 1122#if !defined(__VISUALC__) || defined(__WIN32__)
c801d85f
KB
1123size_t wxString::find(const char* sz, size_t nStart, size_t n) const
1124{
1125 return find(wxString(sz, n == npos ? 0 : n), nStart);
1126}
3f4a0c5b 1127#endif // VC++ 1.5
dd1eaa89 1128
62448488
JS
1129// Gives a duplicate symbol (presumably a case-insensitivity problem)
1130#if !defined(__BORLANDC__)
c801d85f
KB
1131size_t wxString::find(char ch, size_t nStart) const
1132{
1133 wxASSERT( nStart <= Len() );
1134
1135 const char *p = strchr(c_str() + nStart, ch);
dd1eaa89 1136
c801d85f
KB
1137 return p == NULL ? npos : p - c_str();
1138}
62448488 1139#endif
c801d85f
KB
1140
1141size_t wxString::rfind(const wxString& str, size_t nStart) const
1142{
097c080b 1143 wxASSERT( str.GetStringData()->IsValid() );
c801d85f
KB
1144 wxASSERT( nStart <= Len() );
1145
1146 // # could be quicker than that
1147 const char *p = c_str() + (nStart == npos ? Len() : nStart);
1148 while ( p >= c_str() + str.Len() ) {
1149 if ( strncmp(p - str.Len(), str, str.Len()) == 0 )
1150 return p - str.Len() - c_str();
1151 p--;
1152 }
dd1eaa89 1153
c801d85f
KB
1154 return npos;
1155}
dd1eaa89 1156
f0b3249b 1157// VC++ 1.5 can't cope with the default argument in the header.
3f4a0c5b 1158#if !defined(__VISUALC__) || defined(__WIN32__)
c801d85f
KB
1159size_t wxString::rfind(const char* sz, size_t nStart, size_t n) const
1160{
1161 return rfind(wxString(sz, n == npos ? 0 : n), nStart);
1162}
1163
1164size_t wxString::rfind(char ch, size_t nStart) const
1165{
1166 wxASSERT( nStart <= Len() );
1167
1168 const char *p = strrchr(c_str() + nStart, ch);
dd1eaa89 1169
c801d85f
KB
1170 return p == NULL ? npos : p - c_str();
1171}
3f4a0c5b 1172#endif // VC++ 1.5
c801d85f
KB
1173
1174wxString wxString::substr(size_t nStart, size_t nLen) const
1175{
1176 // npos means 'take all'
1177 if ( nLen == npos )
1178 nLen = 0;
1179
1180 wxASSERT( nStart + nLen <= Len() );
1181
1182 return wxString(c_str() + nStart, nLen == npos ? 0 : nLen);
1183}
1184
1185wxString& wxString::erase(size_t nStart, size_t nLen)
1186{
1187 wxString strTmp(c_str(), nStart);
1188 if ( nLen != npos ) {
1189 wxASSERT( nStart + nLen <= Len() );
1190
1191 strTmp.append(c_str() + nStart + nLen);
1192 }
1193
1194 *this = strTmp;
1195 return *this;
1196}
1197
1198wxString& wxString::replace(size_t nStart, size_t nLen, const char *sz)
1199{
1200 wxASSERT( nStart + nLen <= Strlen(sz) );
1201
1202 wxString strTmp;
1203 if ( nStart != 0 )
1204 strTmp.append(c_str(), nStart);
1205 strTmp += sz;
1206 strTmp.append(c_str() + nStart + nLen);
dd1eaa89 1207
c801d85f
KB
1208 *this = strTmp;
1209 return *this;
1210}
1211
1212wxString& wxString::replace(size_t nStart, size_t nLen, size_t nCount, char ch)
1213{
1214 return replace(nStart, nLen, wxString(ch, nCount));
1215}
1216
dd1eaa89 1217wxString& wxString::replace(size_t nStart, size_t nLen,
097c080b 1218 const wxString& str, size_t nStart2, size_t nLen2)
c801d85f
KB
1219{
1220 return replace(nStart, nLen, str.substr(nStart2, nLen2));
1221}
1222
dd1eaa89 1223wxString& wxString::replace(size_t nStart, size_t nLen,
c801d85f
KB
1224 const char* sz, size_t nCount)
1225{
1226 return replace(nStart, nLen, wxString(sz, nCount));
1227}
1228
1229#endif //std::string compatibility
1230
1231// ============================================================================
1232// ArrayString
1233// ============================================================================
1234
1235// size increment = max(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1236#define ARRAY_MAXSIZE_INCREMENT 4096
1237#ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1238 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1239#endif
1240
1241#define STRING(p) ((wxString *)(&(p)))
1242
1243// ctor
1244wxArrayString::wxArrayString()
1245{
1246 m_nSize =
1247 m_nCount = 0;
c67daf87 1248 m_pItems = (char **) NULL;
c801d85f
KB
1249}
1250
1251// copy ctor
1252wxArrayString::wxArrayString(const wxArrayString& src)
1253{
3bbb630a
VZ
1254 m_nSize =
1255 m_nCount = 0;
c67daf87 1256 m_pItems = (char **) NULL;
c801d85f 1257
4d14b524 1258 *this = src;
c801d85f
KB
1259}
1260
4d14b524 1261// assignment operator
c801d85f
KB
1262wxArrayString& wxArrayString::operator=(const wxArrayString& src)
1263{
d93f63db
VZ
1264 if ( m_nSize > 0 )
1265 Clear();
c801d85f 1266
4d14b524
VZ
1267 if ( src.m_nCount > ARRAY_DEFAULT_INITIAL_SIZE )
1268 Alloc(src.m_nCount);
c801d85f 1269
4d14b524
VZ
1270 // we can't just copy the pointers here because otherwise we would share
1271 // the strings with another array
c86f1403 1272 for ( size_t n = 0; n < src.m_nCount; n++ )
4d14b524 1273 Add(src[n]);
c801d85f 1274
3bbb630a
VZ
1275 if ( m_nCount != 0 )
1276 memcpy(m_pItems, src.m_pItems, m_nCount*sizeof(char *));
1277
c801d85f
KB
1278 return *this;
1279}
1280
1281// grow the array
1282void wxArrayString::Grow()
1283{
1284 // only do it if no more place
1285 if( m_nCount == m_nSize ) {
1286 if( m_nSize == 0 ) {
1287 // was empty, alloc some memory
1288 m_nSize = ARRAY_DEFAULT_INITIAL_SIZE;
1289 m_pItems = new char *[m_nSize];
1290 }
1291 else {
3bbb630a
VZ
1292 // otherwise when it's called for the first time, nIncrement would be 0
1293 // and the array would never be expanded
1294 wxASSERT( ARRAY_DEFAULT_INITIAL_SIZE != 0 );
1295
c801d85f 1296 // add 50% but not too much
3bbb630a 1297 size_t nIncrement = m_nSize < ARRAY_DEFAULT_INITIAL_SIZE
4d14b524 1298 ? ARRAY_DEFAULT_INITIAL_SIZE : m_nSize >> 1;
c801d85f
KB
1299 if ( nIncrement > ARRAY_MAXSIZE_INCREMENT )
1300 nIncrement = ARRAY_MAXSIZE_INCREMENT;
1301 m_nSize += nIncrement;
1302 char **pNew = new char *[m_nSize];
1303
1304 // copy data to new location
1305 memcpy(pNew, m_pItems, m_nCount*sizeof(char *));
1306
1307 // delete old memory (but do not release the strings!)
a3622daa 1308 wxDELETEA(m_pItems);
c801d85f
KB
1309
1310 m_pItems = pNew;
1311 }
1312 }
1313}
1314
1315void wxArrayString::Free()
1316{
1317 for ( size_t n = 0; n < m_nCount; n++ ) {
1318 STRING(m_pItems[n])->GetStringData()->Unlock();
1319 }
1320}
1321
1322// deletes all the strings from the list
1323void wxArrayString::Empty()
1324{
1325 Free();
1326
1327 m_nCount = 0;
1328}
1329
1330// as Empty, but also frees memory
1331void wxArrayString::Clear()
1332{
1333 Free();
1334
dd1eaa89 1335 m_nSize =
c801d85f
KB
1336 m_nCount = 0;
1337
a3622daa 1338 wxDELETEA(m_pItems);
c801d85f
KB
1339}
1340
1341// dtor
1342wxArrayString::~wxArrayString()
1343{
1344 Free();
1345
a3622daa 1346 wxDELETEA(m_pItems);
c801d85f
KB
1347}
1348
1349// pre-allocates memory (frees the previous data!)
1350void wxArrayString::Alloc(size_t nSize)
1351{
1352 wxASSERT( nSize > 0 );
1353
1354 // only if old buffer was not big enough
1355 if ( nSize > m_nSize ) {
1356 Free();
a3622daa 1357 wxDELETEA(m_pItems);
c801d85f
KB
1358 m_pItems = new char *[nSize];
1359 m_nSize = nSize;
1360 }
1361
1362 m_nCount = 0;
1363}
1364
1365// searches the array for an item (forward or backwards)
c801d85f
KB
1366int wxArrayString::Index(const char *sz, bool bCase, bool bFromEnd) const
1367{
1368 if ( bFromEnd ) {
1369 if ( m_nCount > 0 ) {
c86f1403 1370 size_t ui = m_nCount;
c801d85f
KB
1371 do {
1372 if ( STRING(m_pItems[--ui])->IsSameAs(sz, bCase) )
1373 return ui;
1374 }
1375 while ( ui != 0 );
1376 }
1377 }
1378 else {
c86f1403 1379 for( size_t ui = 0; ui < m_nCount; ui++ ) {
c801d85f
KB
1380 if( STRING(m_pItems[ui])->IsSameAs(sz, bCase) )
1381 return ui;
1382 }
1383 }
1384
3c67202d 1385 return wxNOT_FOUND;
c801d85f
KB
1386}
1387
1388// add item at the end
097c080b 1389void wxArrayString::Add(const wxString& str)
c801d85f 1390{
097c080b
VZ
1391 wxASSERT( str.GetStringData()->IsValid() );
1392
c801d85f
KB
1393 Grow();
1394
1395 // the string data must not be deleted!
097c080b
VZ
1396 str.GetStringData()->Lock();
1397 m_pItems[m_nCount++] = (char *)str.c_str();
c801d85f
KB
1398}
1399
1400// add item at the given position
097c080b 1401void wxArrayString::Insert(const wxString& str, size_t nIndex)
c801d85f 1402{
097c080b
VZ
1403 wxASSERT( str.GetStringData()->IsValid() );
1404
1a5a8367 1405 wxCHECK_RET( nIndex <= m_nCount, ("bad index in wxArrayString::Insert") );
c801d85f
KB
1406
1407 Grow();
1408
dd1eaa89 1409 memmove(&m_pItems[nIndex + 1], &m_pItems[nIndex],
c801d85f
KB
1410 (m_nCount - nIndex)*sizeof(char *));
1411
097c080b
VZ
1412 str.GetStringData()->Lock();
1413 m_pItems[nIndex] = (char *)str.c_str();
c801d85f
KB
1414
1415 m_nCount++;
1416}
1417
1418// removes item from array (by index)
1419void wxArrayString::Remove(size_t nIndex)
1420{
1a5a8367 1421 wxCHECK_RET( nIndex <= m_nCount, _("bad index in wxArrayString::Remove") );
c801d85f
KB
1422
1423 // release our lock
1424 Item(nIndex).GetStringData()->Unlock();
1425
dd1eaa89 1426 memmove(&m_pItems[nIndex], &m_pItems[nIndex + 1],
c801d85f
KB
1427 (m_nCount - nIndex - 1)*sizeof(char *));
1428 m_nCount--;
1429}
1430
1431// removes item from array (by value)
1432void wxArrayString::Remove(const char *sz)
1433{
1434 int iIndex = Index(sz);
1435
3c67202d 1436 wxCHECK_RET( iIndex != wxNOT_FOUND,
1a5a8367 1437 _("removing inexistent element in wxArrayString::Remove") );
c801d85f 1438
c86f1403 1439 Remove(iIndex);
c801d85f
KB
1440}
1441
30b21f9a
VZ
1442// ----------------------------------------------------------------------------
1443// sorting
1444// ----------------------------------------------------------------------------
1445
1446// we can only sort one array at a time with the quick-sort based
1447// implementation
1448#if wxUSE_THREADS
1449 #include <wx/thread.h>
1450
1451 // need a critical section to protect access to gs_compareFunction and
1452 // gs_sortAscending variables
26128999 1453 static wxCriticalSection *gs_critsectStringSort = NULL;
30b21f9a
VZ
1454
1455 // call this before the value of the global sort vars is changed/after
1456 // you're finished with them
26128999
VZ
1457 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
1458 gs_critsectStringSort = new wxCriticalSection; \
1459 gs_critsectStringSort->Enter()
1460 #define END_SORT() gs_critsectStringSort->Leave(); \
1461 delete gs_critsectStringSort; \
1462 gs_critsectStringSort = NULL
30b21f9a
VZ
1463#else // !threads
1464 #define START_SORT()
1465 #define END_SORT()
1466#endif // wxUSE_THREADS
1467
1468// function to use for string comparaison
1469static wxArrayString::CompareFunction gs_compareFunction = NULL;
1470
1471// if we don't use the compare function, this flag tells us if we sort the
1472// array in ascending or descending order
1473static bool gs_sortAscending = TRUE;
1474
1475// function which is called by quick sort
1476static int wxStringCompareFunction(const void *first, const void *second)
1477{
1478 wxString *strFirst = (wxString *)first;
1479 wxString *strSecond = (wxString *)second;
1480
64716cd7 1481 if ( gs_compareFunction ) {
30b21f9a 1482 return gs_compareFunction(*strFirst, *strSecond);
64716cd7 1483 }
30b21f9a
VZ
1484 else {
1485 int result = strcmp(strFirst->c_str(), strSecond->c_str());
1486
1487 return gs_sortAscending ? result : -result;
1488 }
1489}
1490
c801d85f 1491// sort array elements using passed comparaison function
30b21f9a
VZ
1492void wxArrayString::Sort(CompareFunction compareFunction)
1493{
1494 START_SORT();
1495
1496 wxASSERT( !gs_compareFunction ); // must have been reset to NULL
1497 gs_compareFunction = compareFunction;
1498
1499 DoSort();
1500
1501 END_SORT();
1502}
1503
1504void wxArrayString::Sort(bool reverseOrder)
1505{
1506 START_SORT();
1507
1508 wxASSERT( !gs_compareFunction ); // must have been reset to NULL
1509 gs_sortAscending = !reverseOrder;
1510
1511 DoSort();
1512
1513 END_SORT();
1514}
c801d85f 1515
30b21f9a 1516void wxArrayString::DoSort()
c801d85f 1517{
30b21f9a
VZ
1518 // just sort the pointers using qsort() - of course it only works because
1519 // wxString() *is* a pointer to its data
1520 qsort(m_pItems, m_nCount, sizeof(char *), wxStringCompareFunction);
c801d85f 1521}