]> git.saurik.com Git - wxWidgets.git/blob - src/common/string.cpp
fixed double deletion (patch #945491)
[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 licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
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 #include "wx/thread.h"
39 #endif
40
41 #include <ctype.h>
42 #include <string.h>
43 #include <stdlib.h>
44
45 #ifdef __SALFORDC__
46 #include <clib.h>
47 #endif
48
49 // allocating extra space for each string consumes more memory but speeds up
50 // the concatenation operations (nLen is the current string's length)
51 // NB: EXTRA_ALLOC must be >= 0!
52 #define EXTRA_ALLOC (19 - nLen % 16)
53
54 // ---------------------------------------------------------------------------
55 // static class variables definition
56 // ---------------------------------------------------------------------------
57
58 #if defined(__VISAGECPP__) && __IBMCPP__ >= 400
59 // must define this static for VA or else you get multiply defined symbols
60 // everywhere
61 const unsigned int wxSTRING_MAXLEN = UINT_MAX - 100;
62 #endif // Visual Age
63
64 #if !wxUSE_STL
65 const size_t wxStringBase::npos = wxSTRING_MAXLEN;
66 #endif
67
68 // ----------------------------------------------------------------------------
69 // static data
70 // ----------------------------------------------------------------------------
71
72 #if wxUSE_STL
73
74 extern const wxChar WXDLLIMPEXP_BASE *wxEmptyString = _T("");
75
76 #else
77
78 // for an empty string, GetStringData() will return this address: this
79 // structure has the same layout as wxStringData and it's data() method will
80 // return the empty string (dummy pointer)
81 static const struct
82 {
83 wxStringData data;
84 wxChar dummy;
85 } g_strEmpty = { {-1, 0, 0}, wxT('\0') };
86
87 // empty C style string: points to 'string data' byte of g_strEmpty
88 extern const wxChar WXDLLIMPEXP_BASE *wxEmptyString = &g_strEmpty.dummy;
89
90 #endif
91
92 // ----------------------------------------------------------------------------
93 // global functions
94 // ----------------------------------------------------------------------------
95
96 #if wxUSE_STD_IOSTREAM
97
98 // MS Visual C++ version 5.0 provides the new STL headers as well as the old
99 // iostream ones.
100 //
101 // ATTN: you can _not_ use both of these in the same program!
102
103 #include <iostream>
104
105 wxSTD istream& operator>>(wxSTD istream& is, wxString& WXUNUSED(str))
106 {
107 #if 0
108 int w = is.width(0);
109 if ( is.ipfx(0) ) {
110 streambuf *sb = is.rdbuf();
111 str.erase();
112 while ( true ) {
113 int ch = sb->sbumpc ();
114 if ( ch == EOF ) {
115 is.setstate(ios::eofbit);
116 break;
117 }
118 else if ( isspace(ch) ) {
119 sb->sungetc();
120 break;
121 }
122
123 str += ch;
124 if ( --w == 1 )
125 break;
126 }
127 }
128
129 is.isfx();
130 if ( str.length() == 0 )
131 is.setstate(ios::failbit);
132 #endif
133 return is;
134 }
135
136 wxSTD ostream& operator<<(wxSTD ostream& os, const wxString& str)
137 {
138 os << str.c_str();
139 return os;
140 }
141
142 #endif // wxUSE_STD_IOSTREAM
143
144 // ----------------------------------------------------------------------------
145 // private classes
146 // ----------------------------------------------------------------------------
147
148 // this small class is used to gather statistics for performance tuning
149 //#define WXSTRING_STATISTICS
150 #ifdef WXSTRING_STATISTICS
151 class Averager
152 {
153 public:
154 Averager(const wxChar *sz) { m_sz = sz; m_nTotal = m_nCount = 0; }
155 ~Averager()
156 { wxPrintf("wxString: average %s = %f\n", m_sz, ((float)m_nTotal)/m_nCount); }
157
158 void Add(size_t n) { m_nTotal += n; m_nCount++; }
159
160 private:
161 size_t m_nCount, m_nTotal;
162 const wxChar *m_sz;
163 } g_averageLength("allocation size"),
164 g_averageSummandLength("summand length"),
165 g_averageConcatHit("hit probability in concat"),
166 g_averageInitialLength("initial string length");
167
168 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
169 #else
170 #define STATISTICS_ADD(av, val)
171 #endif // WXSTRING_STATISTICS
172
173 #if !wxUSE_STL
174
175 // ===========================================================================
176 // wxStringData class deallocation
177 // ===========================================================================
178
179 #if defined(__VISUALC__) && defined(_MT) && !defined(_DLL)
180 # pragma message (__FILE__ ": building with Multithreaded non DLL runtime has a performance impact on wxString!")
181 void wxStringData::Free()
182 {
183 free(this);
184 }
185 #endif
186
187 // ===========================================================================
188 // wxStringBase
189 // ===========================================================================
190
191 // takes nLength elements of psz starting at nPos
192 void wxStringBase::InitWith(const wxChar *psz, size_t nPos, size_t nLength)
193 {
194 Init();
195
196 // if the length is not given, assume the string to be NUL terminated
197 if ( nLength == npos ) {
198 wxASSERT_MSG( nPos <= wxStrlen(psz), _T("index out of bounds") );
199
200 nLength = wxStrlen(psz + nPos);
201 }
202
203 STATISTICS_ADD(InitialLength, nLength);
204
205 if ( nLength > 0 ) {
206 // trailing '\0' is written in AllocBuffer()
207 if ( !AllocBuffer(nLength) ) {
208 wxFAIL_MSG( _T("out of memory in wxStringBase::InitWith") );
209 return;
210 }
211 memcpy(m_pchData, psz + nPos, nLength*sizeof(wxChar));
212 }
213 }
214
215 // poor man's iterators are "void *" pointers
216 wxStringBase::wxStringBase(const void *pStart, const void *pEnd)
217 {
218 InitWith((const wxChar *)pStart, 0,
219 (const wxChar *)pEnd - (const wxChar *)pStart);
220 }
221
222 wxStringBase::wxStringBase(size_type n, wxChar ch)
223 {
224 Init();
225 append(n, ch);
226 }
227
228 // ---------------------------------------------------------------------------
229 // memory allocation
230 // ---------------------------------------------------------------------------
231
232 // allocates memory needed to store a C string of length nLen
233 bool wxStringBase::AllocBuffer(size_t nLen)
234 {
235 // allocating 0 sized buffer doesn't make sense, all empty strings should
236 // reuse g_strEmpty
237 wxASSERT( nLen > 0 );
238
239 // make sure that we don't overflow
240 wxASSERT( nLen < (INT_MAX / sizeof(wxChar)) -
241 (sizeof(wxStringData) + EXTRA_ALLOC + 1) );
242
243 STATISTICS_ADD(Length, nLen);
244
245 // allocate memory:
246 // 1) one extra character for '\0' termination
247 // 2) sizeof(wxStringData) for housekeeping info
248 wxStringData* pData = (wxStringData*)
249 malloc(sizeof(wxStringData) + (nLen + EXTRA_ALLOC + 1)*sizeof(wxChar));
250
251 if ( pData == NULL ) {
252 // allocation failures are handled by the caller
253 return FALSE;
254 }
255
256 pData->nRefs = 1;
257 pData->nDataLength = nLen;
258 pData->nAllocLength = nLen + EXTRA_ALLOC;
259 m_pchData = pData->data(); // data starts after wxStringData
260 m_pchData[nLen] = wxT('\0');
261 return TRUE;
262 }
263
264 // must be called before changing this string
265 bool wxStringBase::CopyBeforeWrite()
266 {
267 wxStringData* pData = GetStringData();
268
269 if ( pData->IsShared() ) {
270 pData->Unlock(); // memory not freed because shared
271 size_t nLen = pData->nDataLength;
272 if ( !AllocBuffer(nLen) ) {
273 // allocation failures are handled by the caller
274 return FALSE;
275 }
276 memcpy(m_pchData, pData->data(), nLen*sizeof(wxChar));
277 }
278
279 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
280
281 return TRUE;
282 }
283
284 // must be called before replacing contents of this string
285 bool wxStringBase::AllocBeforeWrite(size_t nLen)
286 {
287 wxASSERT( nLen != 0 ); // doesn't make any sense
288
289 // must not share string and must have enough space
290 wxStringData* pData = GetStringData();
291 if ( pData->IsShared() || pData->IsEmpty() ) {
292 // can't work with old buffer, get new one
293 pData->Unlock();
294 if ( !AllocBuffer(nLen) ) {
295 // allocation failures are handled by the caller
296 return FALSE;
297 }
298 }
299 else {
300 if ( nLen > pData->nAllocLength ) {
301 // realloc the buffer instead of calling malloc() again, this is more
302 // efficient
303 STATISTICS_ADD(Length, nLen);
304
305 nLen += EXTRA_ALLOC;
306
307 pData = (wxStringData*)
308 realloc(pData, sizeof(wxStringData) + (nLen + 1)*sizeof(wxChar));
309
310 if ( pData == NULL ) {
311 // allocation failures are handled by the caller
312 // keep previous data since reallocation failed
313 return FALSE;
314 }
315
316 pData->nAllocLength = nLen;
317 m_pchData = pData->data();
318 }
319
320 // now we have enough space, just update the string length
321 pData->nDataLength = nLen;
322 }
323
324 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
325
326 return TRUE;
327 }
328
329 wxStringBase& wxStringBase::append(size_t n, wxChar ch)
330 {
331 size_type len = length();
332
333 if ( !CopyBeforeWrite() || !Alloc(len + n) ) {
334 wxFAIL_MSG( _T("out of memory in wxStringBase::append") );
335 }
336 GetStringData()->nDataLength = len + n;
337 m_pchData[len + n] = '\0';
338 for ( size_t i = 0; i < n; ++i )
339 m_pchData[len + i] = ch;
340 return *this;
341 }
342
343 void wxStringBase::resize(size_t nSize, wxChar ch)
344 {
345 size_t len = length();
346
347 if ( nSize < len )
348 {
349 erase(begin() + nSize, end());
350 }
351 else if ( nSize > len )
352 {
353 append(nSize - len, ch);
354 }
355 //else: we have exactly the specified length, nothing to do
356 }
357
358 // allocate enough memory for nLen characters
359 bool wxStringBase::Alloc(size_t nLen)
360 {
361 wxStringData *pData = GetStringData();
362 if ( pData->nAllocLength <= nLen ) {
363 if ( pData->IsEmpty() ) {
364 nLen += EXTRA_ALLOC;
365
366 wxStringData* pData = (wxStringData*)
367 malloc(sizeof(wxStringData) + (nLen + 1)*sizeof(wxChar));
368
369 if ( pData == NULL ) {
370 // allocation failure handled by caller
371 return FALSE;
372 }
373
374 pData->nRefs = 1;
375 pData->nDataLength = 0;
376 pData->nAllocLength = nLen;
377 m_pchData = pData->data(); // data starts after wxStringData
378 m_pchData[0u] = wxT('\0');
379 }
380 else if ( pData->IsShared() ) {
381 pData->Unlock(); // memory not freed because shared
382 size_t nOldLen = pData->nDataLength;
383 if ( !AllocBuffer(nLen) ) {
384 // allocation failure handled by caller
385 return FALSE;
386 }
387 memcpy(m_pchData, pData->data(), nOldLen*sizeof(wxChar));
388 }
389 else {
390 nLen += EXTRA_ALLOC;
391
392 pData = (wxStringData *)
393 realloc(pData, sizeof(wxStringData) + (nLen + 1)*sizeof(wxChar));
394
395 if ( pData == NULL ) {
396 // allocation failure handled by caller
397 // keep previous data since reallocation failed
398 return FALSE;
399 }
400
401 // it's not important if the pointer changed or not (the check for this
402 // is not faster than assigning to m_pchData in all cases)
403 pData->nAllocLength = nLen;
404 m_pchData = pData->data();
405 }
406 }
407 //else: we've already got enough
408 return TRUE;
409 }
410
411 wxStringBase::iterator wxStringBase::begin()
412 {
413 if (length() > 0)
414 CopyBeforeWrite();
415 return m_pchData;
416 }
417
418 wxStringBase::iterator wxStringBase::end()
419 {
420 if (length() > 0)
421 CopyBeforeWrite();
422 return m_pchData + length();
423 }
424
425 wxStringBase::iterator wxStringBase::erase(iterator it)
426 {
427 size_type idx = it - begin();
428 erase(idx, 1);
429 return begin() + idx;
430 }
431
432 wxStringBase& wxStringBase::erase(size_t nStart, size_t nLen)
433 {
434 wxASSERT(nStart <= length());
435 size_t strLen = length() - nStart;
436 // delete nLen or up to the end of the string characters
437 nLen = strLen < nLen ? strLen : nLen;
438 wxString strTmp(c_str(), nStart);
439 strTmp.append(c_str() + nStart + nLen, length() - nStart - nLen);
440
441 swap(strTmp);
442 return *this;
443 }
444
445 wxStringBase& wxStringBase::insert(size_t nPos, const wxChar *sz, size_t n)
446 {
447 wxASSERT( nPos <= length() );
448
449 if ( n == npos ) n = wxStrlen(sz);
450 if ( n == 0 ) return *this;
451
452 if ( !CopyBeforeWrite() || !Alloc(length() + n) ) {
453 wxFAIL_MSG( _T("out of memory in wxStringBase::insert") );
454 }
455
456 memmove(m_pchData + nPos + n, m_pchData + nPos,
457 (length() - nPos) * sizeof(wxChar));
458 memcpy(m_pchData + nPos, sz, n * sizeof(wxChar));
459 GetStringData()->nDataLength = length() + n;
460 m_pchData[length()] = '\0';
461
462 return *this;
463 }
464
465 void wxStringBase::swap(wxStringBase& str)
466 {
467 wxChar* tmp = str.m_pchData;
468 str.m_pchData = m_pchData;
469 m_pchData = tmp;
470 }
471
472 size_t wxStringBase::find(const wxStringBase& str, size_t nStart) const
473 {
474 wxASSERT( str.GetStringData()->IsValid() );
475 wxASSERT( nStart <= length() );
476
477 const wxChar *p = wxStrstr(c_str() + nStart, str.c_str());
478
479 return p == NULL ? npos : p - c_str();
480 }
481
482 size_t wxStringBase::find(const wxChar* sz, size_t nStart, size_t n) const
483 {
484 return find(wxStringBase(sz, n), nStart);
485 }
486
487 size_t wxStringBase::find(wxChar ch, size_t nStart) const
488 {
489 wxASSERT( nStart <= length() );
490
491 const wxChar *p = wxStrchr(c_str() + nStart, ch);
492
493 return p == NULL ? npos : p - c_str();
494 }
495
496 size_t wxStringBase::rfind(const wxStringBase& str, size_t nStart) const
497 {
498 wxASSERT( str.GetStringData()->IsValid() );
499 wxASSERT( nStart == npos || nStart <= length() );
500
501 if ( length() >= str.length() )
502 {
503 // avoids a corner case later
504 if ( length() == 0 && str.length() == 0 )
505 return 0;
506
507 // "top" is the point where search starts from
508 size_t top = length() - str.length();
509
510 if ( nStart == npos )
511 nStart = length() - 1;
512 if ( nStart < top )
513 top = nStart;
514
515 const wxChar *cursor = c_str() + top;
516 do
517 {
518 if ( memcmp(cursor, str.c_str(),
519 str.length() * sizeof(wxChar)) == 0 )
520 {
521 return cursor - c_str();
522 }
523 } while ( cursor-- > c_str() );
524 }
525
526 return npos;
527 }
528
529 size_t wxStringBase::rfind(const wxChar* sz, size_t nStart, size_t n) const
530 {
531 return rfind(wxStringBase(sz, n), nStart);
532 }
533
534 size_t wxStringBase::rfind(wxChar ch, size_t nStart) const
535 {
536 if ( nStart == npos )
537 {
538 nStart = length();
539 }
540 else
541 {
542 wxASSERT( nStart <= length() );
543 }
544
545 const wxChar *actual;
546 for ( actual = c_str() + ( nStart == npos ? length() : nStart + 1 );
547 actual > c_str(); --actual )
548 {
549 if ( *(actual - 1) == ch )
550 return (actual - 1) - c_str();
551 }
552
553 return npos;
554 }
555
556 size_t wxStringBase::find_first_of(const wxChar* sz, size_t nStart) const
557 {
558 const wxChar *start = c_str() + nStart;
559 const wxChar *firstOf = wxStrpbrk(start, sz);
560 if ( firstOf )
561 return firstOf - c_str();
562 else
563 return npos;
564 }
565
566 size_t wxStringBase::find_first_of(const wxChar* sz, size_t nStart,
567 size_t n) const
568 {
569 return find_first_of(wxStringBase(sz, n), nStart);
570 }
571
572 size_t wxStringBase::find_last_of(const wxChar* sz, size_t nStart) const
573 {
574 if ( nStart == npos )
575 {
576 nStart = length() - 1;
577 }
578 else
579 {
580 wxASSERT_MSG( nStart <= length(),
581 _T("invalid index in find_last_of()") );
582 }
583
584 for ( const wxChar *p = c_str() + nStart; p >= c_str(); --p )
585 {
586 if ( wxStrchr(sz, *p) )
587 return p - c_str();
588 }
589
590 return npos;
591 }
592
593 size_t wxStringBase::find_last_of(const wxChar* sz, size_t nStart,
594 size_t n) const
595 {
596 return find_last_of(wxStringBase(sz, n), nStart);
597 }
598
599 size_t wxStringBase::find_first_not_of(const wxChar* sz, size_t nStart) const
600 {
601 if ( nStart == npos )
602 {
603 nStart = length();
604 }
605 else
606 {
607 wxASSERT( nStart <= length() );
608 }
609
610 size_t nAccept = wxStrspn(c_str() + nStart, sz);
611 if ( nAccept >= length() - nStart )
612 return npos;
613 else
614 return nStart + nAccept;
615 }
616
617 size_t wxStringBase::find_first_not_of(const wxChar* sz, size_t nStart,
618 size_t n) const
619 {
620 return find_first_not_of(wxStringBase(sz, n), nStart);
621 }
622
623 size_t wxStringBase::find_first_not_of(wxChar ch, size_t nStart) const
624 {
625 wxASSERT( nStart <= length() );
626
627 for ( const wxChar *p = c_str() + nStart; *p; p++ )
628 {
629 if ( *p != ch )
630 return p - c_str();
631 }
632
633 return npos;
634 }
635
636 size_t wxStringBase::find_last_not_of(const wxChar* sz, size_t nStart) const
637 {
638 if ( nStart == npos )
639 {
640 nStart = length() - 1;
641 }
642 else
643 {
644 wxASSERT( nStart <= length() );
645 }
646
647 for ( const wxChar *p = c_str() + nStart; p >= c_str(); --p )
648 {
649 if ( !wxStrchr(sz, *p) )
650 return p - c_str();
651 }
652
653 return npos;
654 }
655
656 size_t wxStringBase::find_last_not_of(const wxChar* sz, size_t nStart,
657 size_t n) const
658 {
659 return find_last_not_of(wxStringBase(sz, n), nStart);
660 }
661
662 size_t wxStringBase::find_last_not_of(wxChar ch, size_t nStart) const
663 {
664 if ( nStart == npos )
665 {
666 nStart = length() - 1;
667 }
668 else
669 {
670 wxASSERT( nStart <= length() );
671 }
672
673 for ( const wxChar *p = c_str() + nStart; p >= c_str(); --p )
674 {
675 if ( *p != ch )
676 return p - c_str();
677 }
678
679 return npos;
680 }
681
682 wxStringBase& wxStringBase::replace(size_t nStart, size_t nLen,
683 const wxChar *sz)
684 {
685 wxASSERT_MSG( nStart <= length(),
686 _T("index out of bounds in wxStringBase::replace") );
687 size_t strLen = length() - nStart;
688 nLen = strLen < nLen ? strLen : nLen;
689
690 wxStringBase strTmp;
691 strTmp.reserve(length()); // micro optimisation to avoid multiple mem allocs
692
693 if ( nStart != 0 )
694 strTmp.append(c_str(), nStart);
695 strTmp.append(sz);
696 strTmp.append(c_str() + nStart + nLen);
697
698 swap(strTmp);
699 return *this;
700 }
701
702 wxStringBase& wxStringBase::replace(size_t nStart, size_t nLen,
703 size_t nCount, wxChar ch)
704 {
705 return replace(nStart, nLen, wxStringBase(ch, nCount).c_str());
706 }
707
708 wxStringBase& wxStringBase::replace(size_t nStart, size_t nLen,
709 const wxStringBase& str,
710 size_t nStart2, size_t nLen2)
711 {
712 return replace(nStart, nLen, str.substr(nStart2, nLen2));
713 }
714
715 wxStringBase& wxStringBase::replace(size_t nStart, size_t nLen,
716 const wxChar* sz, size_t nCount)
717 {
718 return replace(nStart, nLen, wxStringBase(sz, nCount).c_str());
719 }
720
721 wxStringBase wxStringBase::substr(size_t nStart, size_t nLen) const
722 {
723 if ( nLen == npos )
724 nLen = length() - nStart;
725 return wxStringBase(*this, nStart, nLen);
726 }
727
728 // assigns one string to another
729 wxStringBase& wxStringBase::operator=(const wxStringBase& stringSrc)
730 {
731 wxASSERT( stringSrc.GetStringData()->IsValid() );
732
733 // don't copy string over itself
734 if ( m_pchData != stringSrc.m_pchData ) {
735 if ( stringSrc.GetStringData()->IsEmpty() ) {
736 Reinit();
737 }
738 else {
739 // adjust references
740 GetStringData()->Unlock();
741 m_pchData = stringSrc.m_pchData;
742 GetStringData()->Lock();
743 }
744 }
745
746 return *this;
747 }
748
749 // assigns a single character
750 wxStringBase& wxStringBase::operator=(wxChar ch)
751 {
752 if ( !AssignCopy(1, &ch) ) {
753 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(wxChar)") );
754 }
755 return *this;
756 }
757
758 // assigns C string
759 wxStringBase& wxStringBase::operator=(const wxChar *psz)
760 {
761 if ( !AssignCopy(wxStrlen(psz), psz) ) {
762 wxFAIL_MSG( _T("out of memory in wxStringBase::operator=(const wxChar *)") );
763 }
764 return *this;
765 }
766
767 // helper function: does real copy
768 bool wxStringBase::AssignCopy(size_t nSrcLen, const wxChar *pszSrcData)
769 {
770 if ( nSrcLen == 0 ) {
771 Reinit();
772 }
773 else {
774 if ( !AllocBeforeWrite(nSrcLen) ) {
775 // allocation failure handled by caller
776 return FALSE;
777 }
778 memcpy(m_pchData, pszSrcData, nSrcLen*sizeof(wxChar));
779 GetStringData()->nDataLength = nSrcLen;
780 m_pchData[nSrcLen] = wxT('\0');
781 }
782 return TRUE;
783 }
784
785 // ---------------------------------------------------------------------------
786 // string concatenation
787 // ---------------------------------------------------------------------------
788
789 // add something to this string
790 bool wxStringBase::ConcatSelf(size_t nSrcLen, const wxChar *pszSrcData,
791 size_t nMaxLen)
792 {
793 STATISTICS_ADD(SummandLength, nSrcLen);
794
795 nSrcLen = nSrcLen < nMaxLen ? nSrcLen : nMaxLen;
796
797 // concatenating an empty string is a NOP
798 if ( nSrcLen > 0 ) {
799 wxStringData *pData = GetStringData();
800 size_t nLen = pData->nDataLength;
801 size_t nNewLen = nLen + nSrcLen;
802
803 // alloc new buffer if current is too small
804 if ( pData->IsShared() ) {
805 STATISTICS_ADD(ConcatHit, 0);
806
807 // we have to allocate another buffer
808 wxStringData* pOldData = GetStringData();
809 if ( !AllocBuffer(nNewLen) ) {
810 // allocation failure handled by caller
811 return FALSE;
812 }
813 memcpy(m_pchData, pOldData->data(), nLen*sizeof(wxChar));
814 pOldData->Unlock();
815 }
816 else if ( nNewLen > pData->nAllocLength ) {
817 STATISTICS_ADD(ConcatHit, 0);
818
819 reserve(nNewLen);
820 // we have to grow the buffer
821 if ( capacity() < nNewLen ) {
822 // allocation failure handled by caller
823 return FALSE;
824 }
825 }
826 else {
827 STATISTICS_ADD(ConcatHit, 1);
828
829 // the buffer is already big enough
830 }
831
832 // should be enough space
833 wxASSERT( nNewLen <= GetStringData()->nAllocLength );
834
835 // fast concatenation - all is done in our buffer
836 memcpy(m_pchData + nLen, pszSrcData, nSrcLen*sizeof(wxChar));
837
838 m_pchData[nNewLen] = wxT('\0'); // put terminating '\0'
839 GetStringData()->nDataLength = nNewLen; // and fix the length
840 }
841 //else: the string to append was empty
842 return TRUE;
843 }
844
845 // ---------------------------------------------------------------------------
846 // simple sub-string extraction
847 // ---------------------------------------------------------------------------
848
849 // helper function: clone the data attached to this string
850 bool wxStringBase::AllocCopy(wxString& dest, int nCopyLen, int nCopyIndex) const
851 {
852 if ( nCopyLen == 0 ) {
853 dest.Init();
854 }
855 else {
856 if ( !dest.AllocBuffer(nCopyLen) ) {
857 // allocation failure handled by caller
858 return FALSE;
859 }
860 memcpy(dest.m_pchData, m_pchData + nCopyIndex, nCopyLen*sizeof(wxChar));
861 }
862 return TRUE;
863 }
864
865 #endif // !wxUSE_STL
866
867 #if !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
868
869 #if !wxUSE_STL
870 #define STRINGCLASS wxStringBase
871 #else
872 #define STRINGCLASS wxString
873 #endif
874
875 static inline int wxDoCmp(const wxChar* s1, size_t l1,
876 const wxChar* s2, size_t l2)
877 {
878 if( l1 == l2 )
879 return wxStrncmp(s1, s2, l1);
880 else if( l1 < l2 )
881 {
882 int ret = wxStrncmp(s1, s2, l1);
883 return ret == 0 ? -1 : ret;
884 }
885 else if( l1 > l2 )
886 {
887 int ret = wxStrncmp(s1, s2, l2);
888 return ret == 0 ? +1 : ret;
889 }
890
891 wxFAIL; // must never get there
892 return 0; // quiet compilers
893 }
894
895 #if wxUSE_STL
896
897 int STRINGCLASS::compare(const wxStringBase& str) const
898 {
899 return ::wxDoCmp(data(), length(), str.data(), str.length());
900 }
901
902 #endif
903
904 int STRINGCLASS::compare(size_t nStart, size_t nLen,
905 const wxStringBase& str) const
906 {
907 wxASSERT(nStart <= length());
908 size_type strLen = length() - nStart;
909 nLen = strLen < nLen ? strLen : nLen;
910 return ::wxDoCmp(data() + nStart, nLen, str.data(), str.length());
911 }
912
913 int STRINGCLASS::compare(size_t nStart, size_t nLen,
914 const wxStringBase& str,
915 size_t nStart2, size_t nLen2) const
916 {
917 wxASSERT(nStart <= length());
918 wxASSERT(nStart2 <= str.length());
919 size_type strLen = length() - nStart,
920 strLen2 = str.length() - nStart2;
921 nLen = strLen < nLen ? strLen : nLen;
922 nLen2 = strLen2 < nLen2 ? strLen2 : nLen2;
923 return ::wxDoCmp(data() + nStart, nLen, str.data() + nStart2, nLen2);
924 }
925
926 #if wxUSE_STL
927
928 int STRINGCLASS::compare(const wxChar* sz) const
929 {
930 size_t nLen = wxStrlen(sz);
931 return ::wxDoCmp(data(), length(), sz, nLen);
932 }
933
934 #endif
935
936 int STRINGCLASS::compare(size_t nStart, size_t nLen,
937 const wxChar* sz, size_t nCount) const
938 {
939 wxASSERT(nStart <= length());
940 size_type strLen = length() - nStart;
941 nLen = strLen < nLen ? strLen : nLen;
942 if( nCount == npos )
943 nCount = wxStrlen(sz);
944
945 return ::wxDoCmp(data() + nStart, nLen, sz, nCount);
946 }
947
948 #undef STRINGCLASS
949
950 #endif // !wxUSE_STL || !defined(HAVE_STD_STRING_COMPARE)
951
952 // ===========================================================================
953 // wxString class core
954 // ===========================================================================
955
956 // ---------------------------------------------------------------------------
957 // construction
958 // ---------------------------------------------------------------------------
959
960 #if wxUSE_UNICODE
961
962 // from multibyte string
963 wxString::wxString(const char *psz, wxMBConv& conv, size_t nLength)
964 {
965 // first get the size of the buffer we need
966 size_t nLen;
967 if ( psz )
968 {
969 // calculate the needed size ourselves or use the provided one
970 nLen = nLength == npos ? conv.MB2WC(NULL, psz, 0) : nLength;
971 }
972 else
973 {
974 // nothing to convert
975 nLen = 0;
976 }
977
978 // anything to do?
979 if ( (nLen != 0) && (nLen != (size_t)-1) )
980 {
981 if ( !Alloc(nLen) )
982 {
983 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
984 }
985 else
986 {
987 // the input buffer to MB2WC must always be NUL-terminated
988 wxCharBuffer inBuf(nLen);
989 memcpy(inBuf.data(), psz, nLen);
990 inBuf.data()[nLen] = '\0';
991
992 wxWCharBuffer buf(nLen);
993 // MB2WC wants the buffer size, not the string length hence +1
994 nLen = conv.MB2WC(buf.data(), inBuf.data(), nLen + 1);
995
996 if ( nLen != (size_t)-1 )
997 {
998 // initialized ok, set the real length as nLength specified by
999 // the caller could be greater than the real string length
1000 assign(buf.data(), nLen);
1001 return;
1002 }
1003 //else: the conversion failed -- leave the string empty (what else?)
1004 }
1005 }
1006 }
1007
1008 #else // ANSI
1009
1010 #if wxUSE_WCHAR_T
1011 // from wide string
1012 wxString::wxString(const wchar_t *pwz, wxMBConv& conv, size_t nLength)
1013 {
1014 // first get the size of the buffer we need
1015 size_t nLen;
1016 if ( pwz )
1017 {
1018 // calculate the needed size ourselves or use the provided one
1019 nLen = nLength == npos ? conv.WC2MB(NULL, pwz, 0) : nLength;
1020 }
1021 else
1022 {
1023 // nothing to convert
1024 nLen = 0;
1025 }
1026
1027 // anything to do?
1028 if ( (nLen != 0) && (nLen != (size_t)-1) )
1029 {
1030 if ( !Alloc(nLen) )
1031 {
1032 wxFAIL_MSG( _T("out of memory in wxString::wxString") );
1033 }
1034 else
1035 {
1036 wxCharBuffer buf(nLen);
1037 // WC2MB wants the buffer size, not the string length
1038 if ( conv.WC2MB(buf.data(), pwz, nLen + 1) != (size_t)-1 )
1039 {
1040 // initialized ok
1041 assign(buf.data(), nLen);
1042 return;
1043 }
1044 //else: the conversion failed -- leave the string empty (what else?)
1045 }
1046 }
1047
1048 // leave empty
1049 }
1050 #endif // wxUSE_WCHAR_T
1051
1052 #endif // Unicode/ANSI
1053
1054 // shrink to minimal size (releasing extra memory)
1055 bool wxString::Shrink()
1056 {
1057 wxString tmp(begin(), end());
1058 swap(tmp);
1059 return tmp.length() == length();
1060 }
1061
1062 #if !wxUSE_STL
1063 // get the pointer to writable buffer of (at least) nLen bytes
1064 wxChar *wxString::GetWriteBuf(size_t nLen)
1065 {
1066 if ( !AllocBeforeWrite(nLen) ) {
1067 // allocation failure handled by caller
1068 return NULL;
1069 }
1070
1071 wxASSERT( GetStringData()->nRefs == 1 );
1072 GetStringData()->Validate(FALSE);
1073
1074 return m_pchData;
1075 }
1076
1077 // put string back in a reasonable state after GetWriteBuf
1078 void wxString::UngetWriteBuf()
1079 {
1080 GetStringData()->nDataLength = wxStrlen(m_pchData);
1081 GetStringData()->Validate(TRUE);
1082 }
1083
1084 void wxString::UngetWriteBuf(size_t nLen)
1085 {
1086 GetStringData()->nDataLength = nLen;
1087 GetStringData()->Validate(TRUE);
1088 }
1089 #endif
1090
1091 // ---------------------------------------------------------------------------
1092 // data access
1093 // ---------------------------------------------------------------------------
1094
1095 // all functions are inline in string.h
1096
1097 // ---------------------------------------------------------------------------
1098 // assignment operators
1099 // ---------------------------------------------------------------------------
1100
1101 #if !wxUSE_UNICODE
1102
1103 // same as 'signed char' variant
1104 wxString& wxString::operator=(const unsigned char* psz)
1105 {
1106 *this = (const char *)psz;
1107 return *this;
1108 }
1109
1110 #if wxUSE_WCHAR_T
1111 wxString& wxString::operator=(const wchar_t *pwz)
1112 {
1113 wxString str(pwz);
1114 swap(str);
1115 return *this;
1116 }
1117 #endif
1118
1119 #endif
1120
1121 /*
1122 * concatenation functions come in 5 flavours:
1123 * string + string
1124 * char + string and string + char
1125 * C str + string and string + C str
1126 */
1127
1128 wxString operator+(const wxString& str1, const wxString& str2)
1129 {
1130 #if !wxUSE_STL
1131 wxASSERT( str1.GetStringData()->IsValid() );
1132 wxASSERT( str2.GetStringData()->IsValid() );
1133 #endif
1134
1135 wxString s = str1;
1136 s += str2;
1137
1138 return s;
1139 }
1140
1141 wxString operator+(const wxString& str, wxChar ch)
1142 {
1143 #if !wxUSE_STL
1144 wxASSERT( str.GetStringData()->IsValid() );
1145 #endif
1146
1147 wxString s = str;
1148 s += ch;
1149
1150 return s;
1151 }
1152
1153 wxString operator+(wxChar ch, const wxString& str)
1154 {
1155 #if !wxUSE_STL
1156 wxASSERT( str.GetStringData()->IsValid() );
1157 #endif
1158
1159 wxString s = ch;
1160 s += str;
1161
1162 return s;
1163 }
1164
1165 wxString operator+(const wxString& str, const wxChar *psz)
1166 {
1167 #if !wxUSE_STL
1168 wxASSERT( str.GetStringData()->IsValid() );
1169 #endif
1170
1171 wxString s;
1172 if ( !s.Alloc(wxStrlen(psz) + str.Len()) ) {
1173 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1174 }
1175 s = str;
1176 s += psz;
1177
1178 return s;
1179 }
1180
1181 wxString operator+(const wxChar *psz, const wxString& str)
1182 {
1183 #if !wxUSE_STL
1184 wxASSERT( str.GetStringData()->IsValid() );
1185 #endif
1186
1187 wxString s;
1188 if ( !s.Alloc(wxStrlen(psz) + str.Len()) ) {
1189 wxFAIL_MSG( _T("out of memory in wxString::operator+") );
1190 }
1191 s = psz;
1192 s += str;
1193
1194 return s;
1195 }
1196
1197 // ===========================================================================
1198 // other common string functions
1199 // ===========================================================================
1200
1201 #if wxUSE_UNICODE
1202
1203 wxString wxString::FromAscii(const char *ascii)
1204 {
1205 if (!ascii)
1206 return wxEmptyString;
1207
1208 size_t len = strlen( ascii );
1209 wxString res;
1210
1211 if ( len )
1212 {
1213 wxStringBuffer buf(res, len);
1214
1215 wchar_t *dest = buf;
1216
1217 for ( ;; )
1218 {
1219 if ( (*dest++ = (wchar_t)(unsigned char)*ascii++) == L'\0' )
1220 break;
1221 }
1222 }
1223
1224 return res;
1225 }
1226
1227 wxString wxString::FromAscii(const char ascii)
1228 {
1229 // What do we do with '\0' ?
1230
1231 wxString res;
1232 res += (wchar_t)(unsigned char) ascii;
1233
1234 return res;
1235 }
1236
1237 const wxCharBuffer wxString::ToAscii() const
1238 {
1239 // this will allocate enough space for the terminating NUL too
1240 wxCharBuffer buffer(length());
1241
1242 signed char *dest = (signed char *)buffer.data();
1243
1244 const wchar_t *pwc = c_str();
1245 for ( ;; )
1246 {
1247 *dest++ = *pwc > SCHAR_MAX ? '_' : *pwc;
1248
1249 // the output string can't have embedded NULs anyhow, so we can safely
1250 // stop at first of them even if we do have any
1251 if ( !*pwc++ )
1252 break;
1253 }
1254
1255 return buffer;
1256 }
1257
1258 #endif // Unicode
1259
1260 // extract string of length nCount starting at nFirst
1261 wxString wxString::Mid(size_t nFirst, size_t nCount) const
1262 {
1263 size_t nLen = length();
1264
1265 // default value of nCount is npos and means "till the end"
1266 if ( nCount == npos )
1267 {
1268 nCount = nLen - nFirst;
1269 }
1270
1271 // out-of-bounds requests return sensible things
1272 if ( nFirst + nCount > nLen )
1273 {
1274 nCount = nLen - nFirst;
1275 }
1276
1277 if ( nFirst > nLen )
1278 {
1279 // AllocCopy() will return empty string
1280 nCount = 0;
1281 }
1282
1283 wxString dest(*this, nFirst, nCount);
1284 if ( dest.length() != nCount ) {
1285 wxFAIL_MSG( _T("out of memory in wxString::Mid") );
1286 }
1287
1288 return dest;
1289 }
1290
1291 // check that the string starts with prefix and return the rest of the string
1292 // in the provided pointer if it is not NULL, otherwise return FALSE
1293 bool wxString::StartsWith(const wxChar *prefix, wxString *rest) const
1294 {
1295 wxASSERT_MSG( prefix, _T("invalid parameter in wxString::StartsWith") );
1296
1297 // first check if the beginning of the string matches the prefix: note
1298 // that we don't have to check that we don't run out of this string as
1299 // when we reach the terminating NUL, either prefix string ends too (and
1300 // then it's ok) or we break out of the loop because there is no match
1301 const wxChar *p = c_str();
1302 while ( *prefix )
1303 {
1304 if ( *prefix++ != *p++ )
1305 {
1306 // no match
1307 return FALSE;
1308 }
1309 }
1310
1311 if ( rest )
1312 {
1313 // put the rest of the string into provided pointer
1314 *rest = p;
1315 }
1316
1317 return TRUE;
1318 }
1319
1320 // extract nCount last (rightmost) characters
1321 wxString wxString::Right(size_t nCount) const
1322 {
1323 if ( nCount > length() )
1324 nCount = length();
1325
1326 wxString dest(*this, length() - nCount, nCount);
1327 if ( dest.length() != nCount ) {
1328 wxFAIL_MSG( _T("out of memory in wxString::Right") );
1329 }
1330 return dest;
1331 }
1332
1333 // get all characters after the last occurence of ch
1334 // (returns the whole string if ch not found)
1335 wxString wxString::AfterLast(wxChar ch) const
1336 {
1337 wxString str;
1338 int iPos = Find(ch, TRUE);
1339 if ( iPos == wxNOT_FOUND )
1340 str = *this;
1341 else
1342 str = c_str() + iPos + 1;
1343
1344 return str;
1345 }
1346
1347 // extract nCount first (leftmost) characters
1348 wxString wxString::Left(size_t nCount) const
1349 {
1350 if ( nCount > length() )
1351 nCount = length();
1352
1353 wxString dest(*this, 0, nCount);
1354 if ( dest.length() != nCount ) {
1355 wxFAIL_MSG( _T("out of memory in wxString::Left") );
1356 }
1357 return dest;
1358 }
1359
1360 // get all characters before the first occurence of ch
1361 // (returns the whole string if ch not found)
1362 wxString wxString::BeforeFirst(wxChar ch) const
1363 {
1364 int iPos = Find(ch);
1365 if ( iPos == wxNOT_FOUND ) iPos = length();
1366 return wxString(*this, 0, iPos);
1367 }
1368
1369 /// get all characters before the last occurence of ch
1370 /// (returns empty string if ch not found)
1371 wxString wxString::BeforeLast(wxChar ch) const
1372 {
1373 wxString str;
1374 int iPos = Find(ch, TRUE);
1375 if ( iPos != wxNOT_FOUND && iPos != 0 )
1376 str = wxString(c_str(), iPos);
1377
1378 return str;
1379 }
1380
1381 /// get all characters after the first occurence of ch
1382 /// (returns empty string if ch not found)
1383 wxString wxString::AfterFirst(wxChar ch) const
1384 {
1385 wxString str;
1386 int iPos = Find(ch);
1387 if ( iPos != wxNOT_FOUND )
1388 str = c_str() + iPos + 1;
1389
1390 return str;
1391 }
1392
1393 // replace first (or all) occurences of some substring with another one
1394 size_t
1395 wxString::Replace(const wxChar *szOld, const wxChar *szNew, bool bReplaceAll)
1396 {
1397 // if we tried to replace an empty string we'd enter an infinite loop below
1398 wxCHECK_MSG( szOld && *szOld && szNew, 0,
1399 _T("wxString::Replace(): invalid parameter") );
1400
1401 size_t uiCount = 0; // count of replacements made
1402
1403 size_t uiOldLen = wxStrlen(szOld);
1404
1405 wxString strTemp;
1406 const wxChar *pCurrent = c_str();
1407 const wxChar *pSubstr;
1408 while ( *pCurrent != wxT('\0') ) {
1409 pSubstr = wxStrstr(pCurrent, szOld);
1410 if ( pSubstr == NULL ) {
1411 // strTemp is unused if no replacements were made, so avoid the copy
1412 if ( uiCount == 0 )
1413 return 0;
1414
1415 strTemp += pCurrent; // copy the rest
1416 break; // exit the loop
1417 }
1418 else {
1419 // take chars before match
1420 size_type len = strTemp.length();
1421 strTemp.append(pCurrent, pSubstr - pCurrent);
1422 if ( strTemp.length() != (size_t)(len + pSubstr - pCurrent) ) {
1423 wxFAIL_MSG( _T("out of memory in wxString::Replace") );
1424 return 0;
1425 }
1426 strTemp += szNew;
1427 pCurrent = pSubstr + uiOldLen; // restart after match
1428
1429 uiCount++;
1430
1431 // stop now?
1432 if ( !bReplaceAll ) {
1433 strTemp += pCurrent; // copy the rest
1434 break; // exit the loop
1435 }
1436 }
1437 }
1438
1439 // only done if there were replacements, otherwise would have returned above
1440 swap(strTemp);
1441
1442 return uiCount;
1443 }
1444
1445 bool wxString::IsAscii() const
1446 {
1447 const wxChar *s = (const wxChar*) *this;
1448 while(*s){
1449 if(!isascii(*s)) return(FALSE);
1450 s++;
1451 }
1452 return(TRUE);
1453 }
1454
1455 bool wxString::IsWord() const
1456 {
1457 const wxChar *s = (const wxChar*) *this;
1458 while(*s){
1459 if(!wxIsalpha(*s)) return(FALSE);
1460 s++;
1461 }
1462 return(TRUE);
1463 }
1464
1465 bool wxString::IsNumber() const
1466 {
1467 const wxChar *s = (const wxChar*) *this;
1468 if (wxStrlen(s))
1469 if ((s[0] == '-') || (s[0] == '+')) s++;
1470 while(*s){
1471 if(!wxIsdigit(*s)) return(FALSE);
1472 s++;
1473 }
1474 return(TRUE);
1475 }
1476
1477 wxString wxString::Strip(stripType w) const
1478 {
1479 wxString s = *this;
1480 if ( w & leading ) s.Trim(FALSE);
1481 if ( w & trailing ) s.Trim(TRUE);
1482 return s;
1483 }
1484
1485 // ---------------------------------------------------------------------------
1486 // case conversion
1487 // ---------------------------------------------------------------------------
1488
1489 wxString& wxString::MakeUpper()
1490 {
1491 for ( iterator it = begin(), en = end(); it != en; ++it )
1492 *it = (wxChar)wxToupper(*it);
1493
1494 return *this;
1495 }
1496
1497 wxString& wxString::MakeLower()
1498 {
1499 for ( iterator it = begin(), en = end(); it != en; ++it )
1500 *it = (wxChar)wxTolower(*it);
1501
1502 return *this;
1503 }
1504
1505 // ---------------------------------------------------------------------------
1506 // trimming and padding
1507 // ---------------------------------------------------------------------------
1508
1509 // some compilers (VC++ 6.0 not to name them) return TRUE for a call to
1510 // isspace('ê') in the C locale which seems to be broken to me, but we have to
1511 // live with this by checking that the character is a 7 bit one - even if this
1512 // may fail to detect some spaces (I don't know if Unicode doesn't have
1513 // space-like symbols somewhere except in the first 128 chars), it is arguably
1514 // still better than trimming away accented letters
1515 inline int wxSafeIsspace(wxChar ch) { return (ch < 127) && wxIsspace(ch); }
1516
1517 // trims spaces (in the sense of isspace) from left or right side
1518 wxString& wxString::Trim(bool bFromRight)
1519 {
1520 // first check if we're going to modify the string at all
1521 if ( !IsEmpty() &&
1522 (
1523 (bFromRight && wxSafeIsspace(GetChar(Len() - 1))) ||
1524 (!bFromRight && wxSafeIsspace(GetChar(0u)))
1525 )
1526 )
1527 {
1528 if ( bFromRight )
1529 {
1530 // find last non-space character
1531 iterator psz = begin() + length() - 1;
1532 while ( wxSafeIsspace(*psz) && (psz >= begin()) )
1533 psz--;
1534
1535 // truncate at trailing space start
1536 *++psz = wxT('\0');
1537 erase(psz, end());
1538 }
1539 else
1540 {
1541 // find first non-space character
1542 iterator psz = begin();
1543 while ( wxSafeIsspace(*psz) )
1544 psz++;
1545
1546 // fix up data and length
1547 erase(begin(), psz);
1548 }
1549 }
1550
1551 return *this;
1552 }
1553
1554 // adds nCount characters chPad to the string from either side
1555 wxString& wxString::Pad(size_t nCount, wxChar chPad, bool bFromRight)
1556 {
1557 wxString s(chPad, nCount);
1558
1559 if ( bFromRight )
1560 *this += s;
1561 else
1562 {
1563 s += *this;
1564 swap(s);
1565 }
1566
1567 return *this;
1568 }
1569
1570 // truncate the string
1571 wxString& wxString::Truncate(size_t uiLen)
1572 {
1573 if ( uiLen < Len() ) {
1574 erase(begin() + uiLen, end());
1575 }
1576 //else: nothing to do, string is already short enough
1577
1578 return *this;
1579 }
1580
1581 // ---------------------------------------------------------------------------
1582 // finding (return wxNOT_FOUND if not found and index otherwise)
1583 // ---------------------------------------------------------------------------
1584
1585 // find a character
1586 int wxString::Find(wxChar ch, bool bFromEnd) const
1587 {
1588 size_type idx = bFromEnd ? find_last_of(ch) : find_first_of(ch);
1589
1590 return (idx == npos) ? wxNOT_FOUND : (int)idx;
1591 }
1592
1593 // find a sub-string (like strstr)
1594 int wxString::Find(const wxChar *pszSub) const
1595 {
1596 size_type idx = find(pszSub);
1597
1598 return (idx == npos) ? wxNOT_FOUND : (int)idx;
1599 }
1600
1601 // ----------------------------------------------------------------------------
1602 // conversion to numbers
1603 // ----------------------------------------------------------------------------
1604
1605 bool wxString::ToLong(long *val, int base) const
1606 {
1607 wxCHECK_MSG( val, FALSE, _T("NULL pointer in wxString::ToLong") );
1608 wxASSERT_MSG( !base || (base > 1 && base <= 36), _T("invalid base") );
1609
1610 const wxChar *start = c_str();
1611 wxChar *end;
1612 *val = wxStrtol(start, &end, base);
1613
1614 // return TRUE only if scan was stopped by the terminating NUL and if the
1615 // string was not empty to start with
1616 return !*end && (end != start);
1617 }
1618
1619 bool wxString::ToULong(unsigned long *val, int base) const
1620 {
1621 wxCHECK_MSG( val, FALSE, _T("NULL pointer in wxString::ToULong") );
1622 wxASSERT_MSG( !base || (base > 1 && base <= 36), _T("invalid base") );
1623
1624 const wxChar *start = c_str();
1625 wxChar *end;
1626 *val = wxStrtoul(start, &end, base);
1627
1628 // return TRUE only if scan was stopped by the terminating NUL and if the
1629 // string was not empty to start with
1630 return !*end && (end != start);
1631 }
1632
1633 bool wxString::ToDouble(double *val) const
1634 {
1635 wxCHECK_MSG( val, FALSE, _T("NULL pointer in wxString::ToDouble") );
1636
1637 const wxChar *start = c_str();
1638 wxChar *end;
1639 *val = wxStrtod(start, &end);
1640
1641 // return TRUE only if scan was stopped by the terminating NUL and if the
1642 // string was not empty to start with
1643 return !*end && (end != start);
1644 }
1645
1646 // ---------------------------------------------------------------------------
1647 // formatted output
1648 // ---------------------------------------------------------------------------
1649
1650 /* static */
1651 wxString wxString::Format(const wxChar *pszFormat, ...)
1652 {
1653 va_list argptr;
1654 va_start(argptr, pszFormat);
1655
1656 wxString s;
1657 s.PrintfV(pszFormat, argptr);
1658
1659 va_end(argptr);
1660
1661 return s;
1662 }
1663
1664 /* static */
1665 wxString wxString::FormatV(const wxChar *pszFormat, va_list argptr)
1666 {
1667 wxString s;
1668 s.PrintfV(pszFormat, argptr);
1669 return s;
1670 }
1671
1672 int wxString::Printf(const wxChar *pszFormat, ...)
1673 {
1674 va_list argptr;
1675 va_start(argptr, pszFormat);
1676
1677 int iLen = PrintfV(pszFormat, argptr);
1678
1679 va_end(argptr);
1680
1681 return iLen;
1682 }
1683
1684 int wxString::PrintfV(const wxChar* pszFormat, va_list argptr)
1685 {
1686 int size = 1024;
1687 int len;
1688
1689 for ( ;; )
1690 {
1691 {
1692 wxStringBuffer tmp(*this, size + 1);
1693 wxChar* buf = tmp;
1694
1695 if ( !buf )
1696 {
1697 // out of memory
1698 return -1;
1699 }
1700
1701 len = wxVsnprintf(buf, size, pszFormat, argptr);
1702
1703 // some implementations of vsnprintf() don't NUL terminate
1704 // the string if there is not enough space for it so
1705 // always do it manually
1706 buf[size] = _T('\0');
1707 }
1708
1709 // vsnprintf() may return either -1 (traditional Unix behaviour) or the
1710 // total number of characters which would have been written if the
1711 // buffer were large enough
1712 if ( len >= 0 && len <= size )
1713 {
1714 // ok, there was enough space
1715 break;
1716 }
1717
1718 // still not enough, double it again
1719 size *= 2;
1720 }
1721
1722 // we could have overshot
1723 Shrink();
1724
1725 return Len();
1726 }
1727
1728 // ----------------------------------------------------------------------------
1729 // misc other operations
1730 // ----------------------------------------------------------------------------
1731
1732 // returns TRUE if the string matches the pattern which may contain '*' and
1733 // '?' metacharacters (as usual, '?' matches any character and '*' any number
1734 // of them)
1735 bool wxString::Matches(const wxChar *pszMask) const
1736 {
1737 // I disable this code as it doesn't seem to be faster (in fact, it seems
1738 // to be much slower) than the old, hand-written code below and using it
1739 // here requires always linking with libregex even if the user code doesn't
1740 // use it
1741 #if 0 // wxUSE_REGEX
1742 // first translate the shell-like mask into a regex
1743 wxString pattern;
1744 pattern.reserve(wxStrlen(pszMask));
1745
1746 pattern += _T('^');
1747 while ( *pszMask )
1748 {
1749 switch ( *pszMask )
1750 {
1751 case _T('?'):
1752 pattern += _T('.');
1753 break;
1754
1755 case _T('*'):
1756 pattern += _T(".*");
1757 break;
1758
1759 case _T('^'):
1760 case _T('.'):
1761 case _T('$'):
1762 case _T('('):
1763 case _T(')'):
1764 case _T('|'):
1765 case _T('+'):
1766 case _T('\\'):
1767 // these characters are special in a RE, quote them
1768 // (however note that we don't quote '[' and ']' to allow
1769 // using them for Unix shell like matching)
1770 pattern += _T('\\');
1771 // fall through
1772
1773 default:
1774 pattern += *pszMask;
1775 }
1776
1777 pszMask++;
1778 }
1779 pattern += _T('$');
1780
1781 // and now use it
1782 return wxRegEx(pattern, wxRE_NOSUB | wxRE_EXTENDED).Matches(c_str());
1783 #else // !wxUSE_REGEX
1784 // TODO: this is, of course, awfully inefficient...
1785
1786 // the char currently being checked
1787 const wxChar *pszTxt = c_str();
1788
1789 // the last location where '*' matched
1790 const wxChar *pszLastStarInText = NULL;
1791 const wxChar *pszLastStarInMask = NULL;
1792
1793 match:
1794 for ( ; *pszMask != wxT('\0'); pszMask++, pszTxt++ ) {
1795 switch ( *pszMask ) {
1796 case wxT('?'):
1797 if ( *pszTxt == wxT('\0') )
1798 return FALSE;
1799
1800 // pszTxt and pszMask will be incremented in the loop statement
1801
1802 break;
1803
1804 case wxT('*'):
1805 {
1806 // remember where we started to be able to backtrack later
1807 pszLastStarInText = pszTxt;
1808 pszLastStarInMask = pszMask;
1809
1810 // ignore special chars immediately following this one
1811 // (should this be an error?)
1812 while ( *pszMask == wxT('*') || *pszMask == wxT('?') )
1813 pszMask++;
1814
1815 // if there is nothing more, match
1816 if ( *pszMask == wxT('\0') )
1817 return TRUE;
1818
1819 // are there any other metacharacters in the mask?
1820 size_t uiLenMask;
1821 const wxChar *pEndMask = wxStrpbrk(pszMask, wxT("*?"));
1822
1823 if ( pEndMask != NULL ) {
1824 // we have to match the string between two metachars
1825 uiLenMask = pEndMask - pszMask;
1826 }
1827 else {
1828 // we have to match the remainder of the string
1829 uiLenMask = wxStrlen(pszMask);
1830 }
1831
1832 wxString strToMatch(pszMask, uiLenMask);
1833 const wxChar* pMatch = wxStrstr(pszTxt, strToMatch);
1834 if ( pMatch == NULL )
1835 return FALSE;
1836
1837 // -1 to compensate "++" in the loop
1838 pszTxt = pMatch + uiLenMask - 1;
1839 pszMask += uiLenMask - 1;
1840 }
1841 break;
1842
1843 default:
1844 if ( *pszMask != *pszTxt )
1845 return FALSE;
1846 break;
1847 }
1848 }
1849
1850 // match only if nothing left
1851 if ( *pszTxt == wxT('\0') )
1852 return TRUE;
1853
1854 // if we failed to match, backtrack if we can
1855 if ( pszLastStarInText ) {
1856 pszTxt = pszLastStarInText + 1;
1857 pszMask = pszLastStarInMask;
1858
1859 pszLastStarInText = NULL;
1860
1861 // don't bother resetting pszLastStarInMask, it's unnecessary
1862
1863 goto match;
1864 }
1865
1866 return FALSE;
1867 #endif // wxUSE_REGEX/!wxUSE_REGEX
1868 }
1869
1870 // Count the number of chars
1871 int wxString::Freq(wxChar ch) const
1872 {
1873 int count = 0;
1874 int len = Len();
1875 for (int i = 0; i < len; i++)
1876 {
1877 if (GetChar(i) == ch)
1878 count ++;
1879 }
1880 return count;
1881 }
1882
1883 // convert to upper case, return the copy of the string
1884 wxString wxString::Upper() const
1885 { wxString s(*this); return s.MakeUpper(); }
1886
1887 // convert to lower case, return the copy of the string
1888 wxString wxString::Lower() const { wxString s(*this); return s.MakeLower(); }
1889
1890 int wxString::sprintf(const wxChar *pszFormat, ...)
1891 {
1892 va_list argptr;
1893 va_start(argptr, pszFormat);
1894 int iLen = PrintfV(pszFormat, argptr);
1895 va_end(argptr);
1896 return iLen;
1897 }
1898
1899 // ============================================================================
1900 // ArrayString
1901 // ============================================================================
1902
1903 #include "wx/arrstr.h"
1904
1905 #if !wxUSE_STL
1906
1907 // size increment = min(50% of current size, ARRAY_MAXSIZE_INCREMENT)
1908 #define ARRAY_MAXSIZE_INCREMENT 4096
1909
1910 #ifndef ARRAY_DEFAULT_INITIAL_SIZE // also defined in dynarray.h
1911 #define ARRAY_DEFAULT_INITIAL_SIZE (16)
1912 #endif
1913
1914 #define STRING(p) ((wxString *)(&(p)))
1915
1916 // ctor
1917 void wxArrayString::Init(bool autoSort)
1918 {
1919 m_nSize =
1920 m_nCount = 0;
1921 m_pItems = (wxChar **) NULL;
1922 m_autoSort = autoSort;
1923 }
1924
1925 // copy ctor
1926 wxArrayString::wxArrayString(const wxArrayString& src)
1927 {
1928 Init(src.m_autoSort);
1929
1930 *this = src;
1931 }
1932
1933 // assignment operator
1934 wxArrayString& wxArrayString::operator=(const wxArrayString& src)
1935 {
1936 if ( m_nSize > 0 )
1937 Clear();
1938
1939 Copy(src);
1940
1941 m_autoSort = src.m_autoSort;
1942
1943 return *this;
1944 }
1945
1946 void wxArrayString::Copy(const wxArrayString& src)
1947 {
1948 if ( src.m_nCount > ARRAY_DEFAULT_INITIAL_SIZE )
1949 Alloc(src.m_nCount);
1950
1951 for ( size_t n = 0; n < src.m_nCount; n++ )
1952 Add(src[n]);
1953 }
1954
1955 // grow the array
1956 void wxArrayString::Grow(size_t nIncrement)
1957 {
1958 // only do it if no more place
1959 if ( (m_nSize - m_nCount) < nIncrement ) {
1960 // if ARRAY_DEFAULT_INITIAL_SIZE were set to 0, the initially empty would
1961 // be never resized!
1962 #if ARRAY_DEFAULT_INITIAL_SIZE == 0
1963 #error "ARRAY_DEFAULT_INITIAL_SIZE must be > 0!"
1964 #endif
1965
1966 if ( m_nSize == 0 ) {
1967 // was empty, alloc some memory
1968 m_nSize = ARRAY_DEFAULT_INITIAL_SIZE;
1969 if (m_nSize < nIncrement)
1970 m_nSize = nIncrement;
1971 m_pItems = new wxChar *[m_nSize];
1972 }
1973 else {
1974 // otherwise when it's called for the first time, nIncrement would be 0
1975 // and the array would never be expanded
1976 // add 50% but not too much
1977 size_t ndefIncrement = m_nSize < ARRAY_DEFAULT_INITIAL_SIZE
1978 ? ARRAY_DEFAULT_INITIAL_SIZE : m_nSize >> 1;
1979 if ( ndefIncrement > ARRAY_MAXSIZE_INCREMENT )
1980 ndefIncrement = ARRAY_MAXSIZE_INCREMENT;
1981 if ( nIncrement < ndefIncrement )
1982 nIncrement = ndefIncrement;
1983 m_nSize += nIncrement;
1984 wxChar **pNew = new wxChar *[m_nSize];
1985
1986 // copy data to new location
1987 memcpy(pNew, m_pItems, m_nCount*sizeof(wxChar *));
1988
1989 // delete old memory (but do not release the strings!)
1990 wxDELETEA(m_pItems);
1991
1992 m_pItems = pNew;
1993 }
1994 }
1995 }
1996
1997 void wxArrayString::Free()
1998 {
1999 for ( size_t n = 0; n < m_nCount; n++ ) {
2000 STRING(m_pItems[n])->GetStringData()->Unlock();
2001 }
2002 }
2003
2004 // deletes all the strings from the list
2005 void wxArrayString::Empty()
2006 {
2007 Free();
2008
2009 m_nCount = 0;
2010 }
2011
2012 // as Empty, but also frees memory
2013 void wxArrayString::Clear()
2014 {
2015 Free();
2016
2017 m_nSize =
2018 m_nCount = 0;
2019
2020 wxDELETEA(m_pItems);
2021 }
2022
2023 // dtor
2024 wxArrayString::~wxArrayString()
2025 {
2026 Free();
2027
2028 wxDELETEA(m_pItems);
2029 }
2030
2031 void wxArrayString::reserve(size_t nSize)
2032 {
2033 Alloc(nSize);
2034 }
2035
2036 // pre-allocates memory (frees the previous data!)
2037 void wxArrayString::Alloc(size_t nSize)
2038 {
2039 // only if old buffer was not big enough
2040 if ( nSize > m_nSize ) {
2041 Free();
2042 wxDELETEA(m_pItems);
2043 m_pItems = new wxChar *[nSize];
2044 m_nSize = nSize;
2045 }
2046
2047 m_nCount = 0;
2048 }
2049
2050 // minimizes the memory usage by freeing unused memory
2051 void wxArrayString::Shrink()
2052 {
2053 // only do it if we have some memory to free
2054 if( m_nCount < m_nSize ) {
2055 // allocates exactly as much memory as we need
2056 wxChar **pNew = new wxChar *[m_nCount];
2057
2058 // copy data to new location
2059 memcpy(pNew, m_pItems, m_nCount*sizeof(wxChar *));
2060 delete [] m_pItems;
2061 m_pItems = pNew;
2062 }
2063 }
2064
2065 #if WXWIN_COMPATIBILITY_2_4
2066
2067 // return a wxString[] as required for some control ctors.
2068 wxString* wxArrayString::GetStringArray() const
2069 {
2070 wxString *array = 0;
2071
2072 if( m_nCount > 0 )
2073 {
2074 array = new wxString[m_nCount];
2075 for( size_t i = 0; i < m_nCount; i++ )
2076 array[i] = m_pItems[i];
2077 }
2078
2079 return array;
2080 }
2081
2082 #endif // WXWIN_COMPATIBILITY_2_4
2083
2084 // searches the array for an item (forward or backwards)
2085 int wxArrayString::Index(const wxChar *sz, bool bCase, bool bFromEnd) const
2086 {
2087 if ( m_autoSort ) {
2088 // use binary search in the sorted array
2089 wxASSERT_MSG( bCase && !bFromEnd,
2090 wxT("search parameters ignored for auto sorted array") );
2091
2092 size_t i,
2093 lo = 0,
2094 hi = m_nCount;
2095 int res;
2096 while ( lo < hi ) {
2097 i = (lo + hi)/2;
2098
2099 res = wxStrcmp(sz, m_pItems[i]);
2100 if ( res < 0 )
2101 hi = i;
2102 else if ( res > 0 )
2103 lo = i + 1;
2104 else
2105 return i;
2106 }
2107
2108 return wxNOT_FOUND;
2109 }
2110 else {
2111 // use linear search in unsorted array
2112 if ( bFromEnd ) {
2113 if ( m_nCount > 0 ) {
2114 size_t ui = m_nCount;
2115 do {
2116 if ( STRING(m_pItems[--ui])->IsSameAs(sz, bCase) )
2117 return ui;
2118 }
2119 while ( ui != 0 );
2120 }
2121 }
2122 else {
2123 for( size_t ui = 0; ui < m_nCount; ui++ ) {
2124 if( STRING(m_pItems[ui])->IsSameAs(sz, bCase) )
2125 return ui;
2126 }
2127 }
2128 }
2129
2130 return wxNOT_FOUND;
2131 }
2132
2133 // add item at the end
2134 size_t wxArrayString::Add(const wxString& str, size_t nInsert)
2135 {
2136 if ( m_autoSort ) {
2137 // insert the string at the correct position to keep the array sorted
2138 size_t i,
2139 lo = 0,
2140 hi = m_nCount;
2141 int res;
2142 while ( lo < hi ) {
2143 i = (lo + hi)/2;
2144
2145 res = wxStrcmp(str, m_pItems[i]);
2146 if ( res < 0 )
2147 hi = i;
2148 else if ( res > 0 )
2149 lo = i + 1;
2150 else {
2151 lo = hi = i;
2152 break;
2153 }
2154 }
2155
2156 wxASSERT_MSG( lo == hi, wxT("binary search broken") );
2157
2158 Insert(str, lo, nInsert);
2159
2160 return (size_t)lo;
2161 }
2162 else {
2163 wxASSERT( str.GetStringData()->IsValid() );
2164
2165 Grow(nInsert);
2166
2167 for (size_t i = 0; i < nInsert; i++)
2168 {
2169 // the string data must not be deleted!
2170 str.GetStringData()->Lock();
2171
2172 // just append
2173 m_pItems[m_nCount + i] = (wxChar *)str.c_str(); // const_cast
2174 }
2175 size_t ret = m_nCount;
2176 m_nCount += nInsert;
2177 return ret;
2178 }
2179 }
2180
2181 // add item at the given position
2182 void wxArrayString::Insert(const wxString& str, size_t nIndex, size_t nInsert)
2183 {
2184 wxASSERT( str.GetStringData()->IsValid() );
2185
2186 wxCHECK_RET( nIndex <= m_nCount, wxT("bad index in wxArrayString::Insert") );
2187 wxCHECK_RET( m_nCount <= m_nCount + nInsert,
2188 wxT("array size overflow in wxArrayString::Insert") );
2189
2190 Grow(nInsert);
2191
2192 memmove(&m_pItems[nIndex + nInsert], &m_pItems[nIndex],
2193 (m_nCount - nIndex)*sizeof(wxChar *));
2194
2195 for (size_t i = 0; i < nInsert; i++)
2196 {
2197 str.GetStringData()->Lock();
2198 m_pItems[nIndex + i] = (wxChar *)str.c_str();
2199 }
2200 m_nCount += nInsert;
2201 }
2202
2203 // expand the array
2204 void wxArrayString::SetCount(size_t count)
2205 {
2206 Alloc(count);
2207
2208 wxString s;
2209 while ( m_nCount < count )
2210 m_pItems[m_nCount++] = (wxChar *)s.c_str();
2211 }
2212
2213 // removes item from array (by index)
2214 void wxArrayString::RemoveAt(size_t nIndex, size_t nRemove)
2215 {
2216 wxCHECK_RET( nIndex < m_nCount, wxT("bad index in wxArrayString::Remove") );
2217 wxCHECK_RET( nIndex + nRemove <= m_nCount,
2218 wxT("removing too many elements in wxArrayString::Remove") );
2219
2220 // release our lock
2221 for (size_t i = 0; i < nRemove; i++)
2222 Item(nIndex + i).GetStringData()->Unlock();
2223
2224 memmove(&m_pItems[nIndex], &m_pItems[nIndex + nRemove],
2225 (m_nCount - nIndex - nRemove)*sizeof(wxChar *));
2226 m_nCount -= nRemove;
2227 }
2228
2229 // removes item from array (by value)
2230 void wxArrayString::Remove(const wxChar *sz)
2231 {
2232 int iIndex = Index(sz);
2233
2234 wxCHECK_RET( iIndex != wxNOT_FOUND,
2235 wxT("removing inexistent element in wxArrayString::Remove") );
2236
2237 RemoveAt(iIndex);
2238 }
2239
2240 void wxArrayString::assign(const_iterator first, const_iterator last)
2241 {
2242 reserve(last - first);
2243 for(; first != last; ++first)
2244 push_back(*first);
2245 }
2246
2247 // ----------------------------------------------------------------------------
2248 // sorting
2249 // ----------------------------------------------------------------------------
2250
2251 // we can only sort one array at a time with the quick-sort based
2252 // implementation
2253 #if wxUSE_THREADS
2254 // need a critical section to protect access to gs_compareFunction and
2255 // gs_sortAscending variables
2256 static wxCriticalSection *gs_critsectStringSort = NULL;
2257
2258 // call this before the value of the global sort vars is changed/after
2259 // you're finished with them
2260 #define START_SORT() wxASSERT( !gs_critsectStringSort ); \
2261 gs_critsectStringSort = new wxCriticalSection; \
2262 gs_critsectStringSort->Enter()
2263 #define END_SORT() gs_critsectStringSort->Leave(); \
2264 delete gs_critsectStringSort; \
2265 gs_critsectStringSort = NULL
2266 #else // !threads
2267 #define START_SORT()
2268 #define END_SORT()
2269 #endif // wxUSE_THREADS
2270
2271 // function to use for string comparaison
2272 static wxArrayString::CompareFunction gs_compareFunction = NULL;
2273
2274 // if we don't use the compare function, this flag tells us if we sort the
2275 // array in ascending or descending order
2276 static bool gs_sortAscending = TRUE;
2277
2278 // function which is called by quick sort
2279 extern "C" int wxC_CALLING_CONV // LINKAGEMODE
2280 wxStringCompareFunction(const void *first, const void *second)
2281 {
2282 wxString *strFirst = (wxString *)first;
2283 wxString *strSecond = (wxString *)second;
2284
2285 if ( gs_compareFunction ) {
2286 return gs_compareFunction(*strFirst, *strSecond);
2287 }
2288 else {
2289 // maybe we should use wxStrcoll
2290 int result = wxStrcmp(strFirst->c_str(), strSecond->c_str());
2291
2292 return gs_sortAscending ? result : -result;
2293 }
2294 }
2295
2296 // sort array elements using passed comparaison function
2297 void wxArrayString::Sort(CompareFunction compareFunction)
2298 {
2299 START_SORT();
2300
2301 wxASSERT( !gs_compareFunction ); // must have been reset to NULL
2302 gs_compareFunction = compareFunction;
2303
2304 DoSort();
2305
2306 // reset it to NULL so that Sort(bool) will work the next time
2307 gs_compareFunction = NULL;
2308
2309 END_SORT();
2310 }
2311
2312 typedef int (wxC_CALLING_CONV * wxStringCompareFn)(const void *first, const void *second);
2313
2314 void wxArrayString::Sort(CompareFunction2 compareFunction)
2315 {
2316 qsort(m_pItems, m_nCount, sizeof(wxChar *), (wxStringCompareFn)compareFunction);
2317 }
2318
2319 void wxArrayString::Sort(bool reverseOrder)
2320 {
2321 Sort(reverseOrder ? wxStringSortDescending : wxStringSortAscending);
2322 }
2323
2324 void wxArrayString::DoSort()
2325 {
2326 wxCHECK_RET( !m_autoSort, wxT("can't use this method with sorted arrays") );
2327
2328 // just sort the pointers using qsort() - of course it only works because
2329 // wxString() *is* a pointer to its data
2330 qsort(m_pItems, m_nCount, sizeof(wxChar *), wxStringCompareFunction);
2331 }
2332
2333 bool wxArrayString::operator==(const wxArrayString& a) const
2334 {
2335 if ( m_nCount != a.m_nCount )
2336 return FALSE;
2337
2338 for ( size_t n = 0; n < m_nCount; n++ )
2339 {
2340 if ( Item(n) != a[n] )
2341 return FALSE;
2342 }
2343
2344 return TRUE;
2345 }
2346
2347 #endif // !wxUSE_STL
2348
2349 int wxCMPFUNC_CONV wxStringSortAscending(wxString* s1, wxString* s2)
2350 {
2351 return wxStrcmp(s1->c_str(), s2->c_str());
2352 }
2353
2354 int wxCMPFUNC_CONV wxStringSortDescending(wxString* s1, wxString* s2)
2355 {
2356 return -wxStrcmp(s1->c_str(), s2->c_str());
2357 }