1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/stringimpl.cpp
3 // Purpose: wxString class
4 // Author: Vadim Zeitlin, Ryan Norton
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // (c) 2004 Ryan Norton <wxprojects@comcast.net>
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
15 * 1) all empty strings use g_strEmpty, nRefs = -1 (set in Init())
16 * 2) AllocBuffer() sets nRefs to 1, Lock() increments it by one
17 * 3) Unlock() decrements nRefs and frees memory if it goes to 0
20 // ===========================================================================
21 // headers, declarations, constants
22 // ===========================================================================
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
32 #include "wx/stringimpl.h"
45 // allocating extra space for each string consumes more memory but speeds up
46 // the concatenation operations (nLen is the current string's length)
47 // NB: EXTRA_ALLOC must be >= 0!
48 #define EXTRA_ALLOC (19 - nLen % 16)
51 // string handling functions used by wxString:
52 #if wxUSE_UNICODE_UTF8
53 #define wxStringMemcpy memcpy
54 #define wxStringMemcmp memcmp
55 #define wxStringMemchr memchr
57 #define wxStringMemcpy wxTmemcpy
58 #define wxStringMemcmp wxTmemcmp
59 #define wxStringMemchr wxTmemchr
63 // ---------------------------------------------------------------------------
64 // static class variables definition
65 // ---------------------------------------------------------------------------
67 #if !wxUSE_STL_BASED_WXSTRING
68 //According to STL _must_ be a -1 size_t
69 const size_t wxStringImpl::npos
= (size_t) -1;
72 // ----------------------------------------------------------------------------
74 // ----------------------------------------------------------------------------
76 #if wxUSE_STL_BASED_WXSTRING
78 // FIXME-UTF8: get rid of this, have only one wxEmptyString
79 #if wxUSE_UNICODE_UTF8
80 const wxStringCharType WXDLLIMPEXP_BASE
*wxEmptyStringImpl
= "";
82 const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= wxT("");
86 // for an empty string, GetStringData() will return this address: this
87 // structure has the same layout as wxStringData and it's data() method will
88 // return the empty string (dummy pointer)
92 wxStringCharType dummy
;
93 } g_strEmpty
= { {-1, 0, 0}, wxT('\0') };
95 // empty C style string: points to 'string data' byte of g_strEmpty
96 #if wxUSE_UNICODE_UTF8
97 // FIXME-UTF8: get rid of this, have only one wxEmptyString
98 const wxStringCharType WXDLLIMPEXP_BASE
*wxEmptyStringImpl
= &g_strEmpty
.dummy
;
99 const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= wxT("");
101 const wxStringCharType WXDLLIMPEXP_BASE
*wxEmptyString
= &g_strEmpty
.dummy
;
107 #if !wxUSE_STL_BASED_WXSTRING
109 // ----------------------------------------------------------------------------
111 // ----------------------------------------------------------------------------
113 // this small class is used to gather statistics for performance tuning
115 // uncomment this to enable gathering of some statistics about wxString
117 //#define WXSTRING_STATISTICS
119 #ifdef WXSTRING_STATISTICS
123 Averager(const wxStringCharType
*sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
126 wxPrintf("wxString %s: total = %lu, average = %f\n",
127 m_sz
, m_nTotal
, ((float)m_nTotal
)/m_nCount
);
130 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
133 unsigned long m_nCount
, m_nTotal
;
134 const wxStringCharType
*m_sz
;
135 } g_averageLength("allocation size"),
136 g_averageSummandLength("summand length"),
137 g_averageConcatHit("hit probability in concat"),
138 g_averageInitialLength("initial string length");
140 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
142 #define STATISTICS_ADD(av, val)
143 #endif // WXSTRING_STATISTICS
145 // ===========================================================================
146 // wxStringData class deallocation
147 // ===========================================================================
149 #if defined(__VISUALC__) && defined(_MT) && !defined(_DLL)
150 # pragma message (__FILE__ ": building with Multithreaded non DLL runtime has a performance impact on wxString!")
151 void wxStringData::Free()
157 // ===========================================================================
159 // ===========================================================================
161 // takes nLength elements of psz starting at nPos
162 void wxStringImpl::InitWith(const wxStringCharType
*psz
,
163 size_t nPos
, size_t nLength
)
167 // if the length is not given, assume the string to be NUL terminated
168 if ( nLength
== npos
) {
169 wxASSERT_MSG( nPos
<= wxStrlen(psz
), wxT("index out of bounds") );
171 nLength
= wxStrlen(psz
+ nPos
);
174 STATISTICS_ADD(InitialLength
, nLength
);
177 // trailing '\0' is written in AllocBuffer()
178 if ( !AllocBuffer(nLength
) ) {
179 wxFAIL_MSG( wxT("out of memory in wxStringImpl::InitWith") );
182 wxStringMemcpy(m_pchData
, psz
+ nPos
, nLength
);
186 wxStringImpl::wxStringImpl(const_iterator first
, const_iterator last
)
190 InitWith(first
.GetPtr(), 0, last
- first
);
194 wxFAIL_MSG( wxT("first must be before last") );
199 wxStringImpl::wxStringImpl(size_type n
, wxStringCharType ch
)
205 // ---------------------------------------------------------------------------
207 // ---------------------------------------------------------------------------
209 // allocates memory needed to store a C string of length nLen
210 bool wxStringImpl::AllocBuffer(size_t nLen
)
212 // allocating 0 sized buffer doesn't make sense, all empty strings should
214 wxASSERT( nLen
> 0 );
216 // make sure that we don't overflow
217 wxCHECK( nLen
< (INT_MAX
/ sizeof(wxStringCharType
)) -
218 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1), false );
220 STATISTICS_ADD(Length
, nLen
);
223 // 1) one extra character for '\0' termination
224 // 2) sizeof(wxStringData) for housekeeping info
225 wxStringData
* pData
= (wxStringData
*)
226 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxStringCharType
));
228 if ( pData
== NULL
) {
229 // allocation failures are handled by the caller
234 pData
->nDataLength
= nLen
;
235 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
236 m_pchData
= pData
->data(); // data starts after wxStringData
237 m_pchData
[nLen
] = wxT('\0');
241 // must be called before changing this string
242 bool wxStringImpl::CopyBeforeWrite()
244 wxStringData
* pData
= GetStringData();
246 if ( pData
->IsShared() ) {
247 pData
->Unlock(); // memory not freed because shared
248 size_t nLen
= pData
->nDataLength
;
249 if ( !AllocBuffer(nLen
) ) {
250 // allocation failures are handled by the caller
253 wxStringMemcpy(m_pchData
, pData
->data(), nLen
);
256 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
261 // must be called before replacing contents of this string
262 bool wxStringImpl::AllocBeforeWrite(size_t nLen
)
264 wxASSERT( nLen
!= 0 ); // doesn't make any sense
266 // must not share string and must have enough space
267 wxStringData
* pData
= GetStringData();
268 if ( pData
->IsShared() || pData
->IsEmpty() ) {
269 // can't work with old buffer, get new one
271 if ( !AllocBuffer(nLen
) ) {
272 // allocation failures are handled by the caller
277 if ( nLen
> pData
->nAllocLength
) {
278 // realloc the buffer instead of calling malloc() again, this is more
280 STATISTICS_ADD(Length
, nLen
);
284 pData
= (wxStringData
*)
286 sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxStringCharType
));
288 if ( pData
== NULL
) {
289 // allocation failures are handled by the caller
290 // keep previous data since reallocation failed
294 pData
->nAllocLength
= nLen
;
295 m_pchData
= pData
->data();
299 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
301 // it doesn't really matter what the string length is as it's going to be
302 // overwritten later but, for extra safety, set it to 0 for now as we may
303 // have some junk in m_pchData
304 GetStringData()->nDataLength
= 0;
309 wxStringImpl
& wxStringImpl::append(size_t n
, wxStringCharType ch
)
311 size_type len
= length();
313 if ( !Alloc(len
+ n
) || !CopyBeforeWrite() ) {
314 wxFAIL_MSG( wxT("out of memory in wxStringImpl::append") );
317 GetStringData()->nDataLength
= len
+ n
;
318 m_pchData
[len
+ n
] = '\0';
319 for ( size_t i
= 0; i
< n
; ++i
)
320 m_pchData
[len
+ i
] = ch
;
324 void wxStringImpl::resize(size_t nSize
, wxStringCharType ch
)
326 size_t len
= length();
330 erase(begin() + nSize
, end());
332 else if ( nSize
> len
)
334 append(nSize
- len
, ch
);
336 //else: we have exactly the specified length, nothing to do
339 // allocate enough memory for nLen characters
340 bool wxStringImpl::Alloc(size_t nLen
)
342 wxStringData
*pData
= GetStringData();
343 if ( pData
->nAllocLength
<= nLen
) {
344 if ( pData
->IsEmpty() ) {
345 STATISTICS_ADD(Length
, nLen
);
349 pData
= (wxStringData
*)
350 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxStringCharType
));
352 if ( pData
== NULL
) {
353 // allocation failure handled by caller
358 pData
->nDataLength
= 0;
359 pData
->nAllocLength
= nLen
;
360 m_pchData
= pData
->data(); // data starts after wxStringData
361 m_pchData
[0u] = wxT('\0');
363 else if ( pData
->IsShared() ) {
364 pData
->Unlock(); // memory not freed because shared
365 size_t nOldLen
= pData
->nDataLength
;
366 if ( !AllocBuffer(nLen
) ) {
367 // allocation failure handled by caller
370 // +1 to copy the terminator, too
371 memcpy(m_pchData
, pData
->data(), (nOldLen
+1)*sizeof(wxStringCharType
));
372 GetStringData()->nDataLength
= nOldLen
;
377 pData
= (wxStringData
*)
378 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxStringCharType
));
380 if ( pData
== NULL
) {
381 // allocation failure handled by caller
382 // keep previous data since reallocation failed
386 // it's not important if the pointer changed or not (the check for this
387 // is not faster than assigning to m_pchData in all cases)
388 pData
->nAllocLength
= nLen
;
389 m_pchData
= pData
->data();
392 //else: we've already got enough
396 wxStringImpl::iterator
wxStringImpl::begin()
403 wxStringImpl::iterator
wxStringImpl::end()
407 return m_pchData
+ length();
410 wxStringImpl::iterator
wxStringImpl::erase(iterator it
)
412 size_type idx
= it
- begin();
414 return begin() + idx
;
417 wxStringImpl
& wxStringImpl::erase(size_t nStart
, size_t nLen
)
419 wxASSERT(nStart
<= length());
420 size_t strLen
= length() - nStart
;
421 // delete nLen or up to the end of the string characters
422 nLen
= strLen
< nLen
? strLen
: nLen
;
423 wxStringImpl
strTmp(c_str(), nStart
);
424 strTmp
.append(c_str() + nStart
+ nLen
, length() - nStart
- nLen
);
430 wxStringImpl
& wxStringImpl::insert(size_t nPos
,
431 const wxStringCharType
*sz
, size_t n
)
433 wxASSERT( nPos
<= length() );
435 if ( n
== npos
) n
= wxStrlen(sz
);
436 if ( n
== 0 ) return *this;
438 if ( !Alloc(length() + n
) || !CopyBeforeWrite() ) {
439 wxFAIL_MSG( wxT("out of memory in wxStringImpl::insert") );
443 memmove(m_pchData
+ nPos
+ n
, m_pchData
+ nPos
,
444 (length() - nPos
) * sizeof(wxStringCharType
));
445 memcpy(m_pchData
+ nPos
, sz
, n
* sizeof(wxStringCharType
));
446 GetStringData()->nDataLength
= length() + n
;
447 m_pchData
[length()] = '\0';
452 void wxStringImpl::swap(wxStringImpl
& str
)
454 wxStringCharType
* tmp
= str
.m_pchData
;
455 str
.m_pchData
= m_pchData
;
459 size_t wxStringImpl::find(const wxStringImpl
& str
, size_t nStart
) const
461 // deal with the special case of empty string first
462 const size_t nLen
= length();
463 const size_t nLenOther
= str
.length();
467 // empty string is a substring of anything
473 // the other string is non empty so can't be our substring
477 wxASSERT( str
.GetStringData()->IsValid() );
478 wxASSERT( nStart
<= nLen
);
480 const wxStringCharType
* const other
= str
.c_str();
483 const wxStringCharType
* p
=
484 (const wxStringCharType
*)wxStringMemchr(c_str() + nStart
,
491 while ( p
- c_str() + nLenOther
<= nLen
&&
492 wxStringMemcmp(p
, other
, nLenOther
) )
497 p
= (const wxStringCharType
*)
498 wxStringMemchr(p
, *other
, nLen
- (p
- c_str()));
504 return p
- c_str() + nLenOther
<= nLen
? p
- c_str() : npos
;
507 size_t wxStringImpl::find(const wxStringCharType
* sz
,
508 size_t nStart
, size_t n
) const
510 return find(wxStringImpl(sz
, n
), nStart
);
513 size_t wxStringImpl::find(wxStringCharType ch
, size_t nStart
) const
515 wxASSERT( nStart
<= length() );
517 const wxStringCharType
*p
= (const wxStringCharType
*)
518 wxStringMemchr(c_str() + nStart
, ch
, length() - nStart
);
520 return p
== NULL
? npos
: p
- c_str();
523 size_t wxStringImpl::rfind(const wxStringImpl
& str
, size_t nStart
) const
525 wxASSERT( str
.GetStringData()->IsValid() );
526 wxASSERT( nStart
== npos
|| nStart
<= length() );
528 if ( length() >= str
.length() )
530 // avoids a corner case later
531 if ( length() == 0 && str
.length() == 0 )
534 // "top" is the point where search starts from
535 size_t top
= length() - str
.length();
537 if ( nStart
== npos
)
538 nStart
= length() - 1;
542 const wxStringCharType
*cursor
= c_str() + top
;
545 if ( wxStringMemcmp(cursor
, str
.c_str(), str
.length()) == 0 )
547 return cursor
- c_str();
549 } while ( cursor
-- > c_str() );
555 size_t wxStringImpl::rfind(const wxStringCharType
* sz
,
556 size_t nStart
, size_t n
) const
558 return rfind(wxStringImpl(sz
, n
), nStart
);
561 size_t wxStringImpl::rfind(wxStringCharType ch
, size_t nStart
) const
563 if ( nStart
== npos
)
569 wxASSERT( nStart
<= length() );
572 const wxStringCharType
*actual
;
573 for ( actual
= c_str() + ( nStart
== npos
? length() : nStart
+ 1 );
574 actual
> c_str(); --actual
)
576 if ( *(actual
- 1) == ch
)
577 return (actual
- 1) - c_str();
583 wxStringImpl
& wxStringImpl::replace(size_t nStart
, size_t nLen
,
584 const wxStringCharType
*sz
, size_t nCount
)
586 // check and adjust parameters
587 const size_t lenOld
= length();
589 wxASSERT_MSG( nStart
<= lenOld
,
590 wxT("index out of bounds in wxStringImpl::replace") );
591 size_t nEnd
= nStart
+ nLen
;
592 if ( nLen
> lenOld
- nStart
)
594 // nLen may be out of range, as it can be npos, just clump it down
595 nLen
= lenOld
- nStart
;
599 if ( nCount
== npos
)
600 nCount
= wxStrlen(sz
);
602 // build the new string from 3 pieces: part of this string before nStart,
603 // the new substring and the part of this string after nStart+nLen
605 const size_t lenNew
= lenOld
+ nCount
- nLen
;
608 tmp
.AllocBuffer(lenOld
+ nCount
- nLen
);
610 wxStringCharType
*dst
= tmp
.m_pchData
;
611 memcpy(dst
, m_pchData
, nStart
*sizeof(wxStringCharType
));
614 memcpy(dst
, sz
, nCount
*sizeof(wxStringCharType
));
617 memcpy(dst
, m_pchData
+ nEnd
, (lenOld
- nEnd
)*sizeof(wxStringCharType
));
620 // and replace this string contents with the new one
625 wxStringImpl
wxStringImpl::substr(size_t nStart
, size_t nLen
) const
628 nLen
= length() - nStart
;
629 return wxStringImpl(*this, nStart
, nLen
);
632 // assigns one string to another
633 wxStringImpl
& wxStringImpl::operator=(const wxStringImpl
& stringSrc
)
635 wxASSERT( stringSrc
.GetStringData()->IsValid() );
637 // don't copy string over itself
638 if ( m_pchData
!= stringSrc
.m_pchData
) {
639 if ( stringSrc
.GetStringData()->IsEmpty() ) {
644 GetStringData()->Unlock();
645 m_pchData
= stringSrc
.m_pchData
;
646 GetStringData()->Lock();
653 // assigns a single character
654 wxStringImpl
& wxStringImpl::operator=(wxStringCharType ch
)
656 wxStringCharType
c(ch
);
657 if ( !AssignCopy(1, &c
) ) {
658 wxFAIL_MSG( wxT("out of memory in wxStringImpl::operator=(wxStringCharType)") );
664 wxStringImpl
& wxStringImpl::operator=(const wxStringCharType
*psz
)
666 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
667 wxFAIL_MSG( wxT("out of memory in wxStringImpl::operator=(const wxStringCharType *)") );
672 // helper function: does real copy
673 bool wxStringImpl::AssignCopy(size_t nSrcLen
,
674 const wxStringCharType
*pszSrcData
)
676 if ( nSrcLen
== 0 ) {
680 if ( !AllocBeforeWrite(nSrcLen
) ) {
681 // allocation failure handled by caller
684 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxStringCharType
));
685 GetStringData()->nDataLength
= nSrcLen
;
686 m_pchData
[nSrcLen
] = wxT('\0');
691 // ---------------------------------------------------------------------------
692 // string concatenation
693 // ---------------------------------------------------------------------------
695 // add something to this string
696 bool wxStringImpl::ConcatSelf(size_t nSrcLen
,
697 const wxStringCharType
*pszSrcData
,
700 STATISTICS_ADD(SummandLength
, nSrcLen
);
702 nSrcLen
= nSrcLen
< nMaxLen
? nSrcLen
: nMaxLen
;
704 // concatenating an empty string is a NOP
706 wxStringData
*pData
= GetStringData();
707 size_t nLen
= pData
->nDataLength
;
709 // take special care when appending part of this string to itself: the code
710 // below reallocates our buffer and this invalidates pszSrcData pointer so
711 // we have to copy it in another temporary string in this case (but avoid
712 // doing this unnecessarily)
713 if ( pszSrcData
>= m_pchData
&& pszSrcData
< m_pchData
+ nLen
)
715 wxStringImpl
tmp(pszSrcData
, nSrcLen
);
716 return ConcatSelf(nSrcLen
, tmp
.m_pchData
, nSrcLen
);
719 size_t nNewLen
= nLen
+ nSrcLen
;
721 // alloc new buffer if current is too small
722 if ( pData
->IsShared() ) {
723 STATISTICS_ADD(ConcatHit
, 0);
725 // we have to allocate another buffer
726 wxStringData
* pOldData
= GetStringData();
727 if ( !AllocBuffer(nNewLen
) ) {
728 // allocation failure handled by caller
731 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxStringCharType
));
734 else if ( nNewLen
> pData
->nAllocLength
) {
735 STATISTICS_ADD(ConcatHit
, 0);
738 // we have to grow the buffer
739 if ( capacity() < nNewLen
) {
740 // allocation failure handled by caller
745 STATISTICS_ADD(ConcatHit
, 1);
747 // the buffer is already big enough
750 // should be enough space
751 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
753 // fast concatenation - all is done in our buffer
754 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxStringCharType
));
756 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
757 GetStringData()->nDataLength
= nNewLen
; // and fix the length
759 //else: the string to append was empty
763 // get the pointer to writable buffer of (at least) nLen bytes
764 wxStringCharType
*wxStringImpl::DoGetWriteBuf(size_t nLen
)
766 if ( !AllocBeforeWrite(nLen
) ) {
767 // allocation failure handled by caller
771 wxASSERT( GetStringData()->nRefs
== 1 );
772 GetStringData()->Validate(false);
777 // put string back in a reasonable state after GetWriteBuf
778 void wxStringImpl::DoUngetWriteBuf()
780 DoUngetWriteBuf(wxStrlen(m_pchData
));
783 void wxStringImpl::DoUngetWriteBuf(size_t nLen
)
785 wxStringData
* const pData
= GetStringData();
787 wxASSERT_MSG( nLen
< pData
->nAllocLength
, wxT("buffer overrun") );
789 // the strings we store are always NUL-terminated
790 pData
->data()[nLen
] = wxT('\0');
791 pData
->nDataLength
= nLen
;
792 pData
->Validate(true);
795 #endif // !wxUSE_STL_BASED_WXSTRING