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