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