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