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