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"
49 // allocating extra space for each string consumes more memory but speeds up
50 // the concatenation operations (nLen is the current string's length)
51 // NB: EXTRA_ALLOC must be >= 0!
52 #define EXTRA_ALLOC (19 - nLen % 16)
55 // string handling functions used by wxString:
56 #if wxUSE_UNICODE_UTF8
57 #define wxStringMemcpy memcpy
58 #define wxStringMemcmp memcmp
59 #define wxStringMemchr memchr
61 #define wxStringMemcpy wxTmemcpy
62 #define wxStringMemcmp wxTmemcmp
63 #define wxStringMemchr wxTmemchr
67 // ---------------------------------------------------------------------------
68 // static class variables definition
69 // ---------------------------------------------------------------------------
71 #if !wxUSE_STL_BASED_WXSTRING
72 //According to STL _must_ be a -1 size_t
73 const size_t wxStringImpl::npos
= (size_t) -1;
76 // ----------------------------------------------------------------------------
78 // ----------------------------------------------------------------------------
80 #if wxUSE_STL_BASED_WXSTRING
82 // FIXME-UTF8: get rid of this, have only one wxEmptyString
83 #if wxUSE_UNICODE_UTF8
84 extern const wxStringCharType WXDLLIMPEXP_BASE
*wxEmptyStringImpl
= "";
86 extern const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= _T("");
90 // for an empty string, GetStringData() will return this address: this
91 // structure has the same layout as wxStringData and it's data() method will
92 // return the empty string (dummy pointer)
96 wxStringCharType dummy
;
97 } g_strEmpty
= { {-1, 0, 0}, wxT('\0') };
99 // empty C style string: points to 'string data' byte of g_strEmpty
100 #if wxUSE_UNICODE_UTF8
101 // FIXME-UTF8: get rid of this, have only one wxEmptyString
102 extern const wxStringCharType WXDLLIMPEXP_BASE
*wxEmptyStringImpl
= &g_strEmpty
.dummy
;
103 extern const wxChar WXDLLIMPEXP_BASE
*wxEmptyString
= _T("");
105 extern const wxStringCharType WXDLLIMPEXP_BASE
*wxEmptyString
= &g_strEmpty
.dummy
;
111 #if !wxUSE_STL_BASED_WXSTRING
113 // ----------------------------------------------------------------------------
115 // ----------------------------------------------------------------------------
117 // this small class is used to gather statistics for performance tuning
118 //#define WXSTRING_STATISTICS
119 #ifdef WXSTRING_STATISTICS
123 Averager(const wxStringCharType
*sz
) { m_sz
= sz
; m_nTotal
= m_nCount
= 0; }
125 { wxPrintf("wxString: average %s = %f\n", m_sz
, ((float)m_nTotal
)/m_nCount
); }
127 void Add(size_t n
) { m_nTotal
+= n
; m_nCount
++; }
130 size_t m_nCount
, m_nTotal
;
131 const wxStringCharType
*m_sz
;
132 } g_averageLength("allocation size"),
133 g_averageSummandLength("summand length"),
134 g_averageConcatHit("hit probability in concat"),
135 g_averageInitialLength("initial string length");
137 #define STATISTICS_ADD(av, val) g_average##av.Add(val)
139 #define STATISTICS_ADD(av, val)
140 #endif // WXSTRING_STATISTICS
142 // ===========================================================================
143 // wxStringData class deallocation
144 // ===========================================================================
146 #if defined(__VISUALC__) && defined(_MT) && !defined(_DLL)
147 # pragma message (__FILE__ ": building with Multithreaded non DLL runtime has a performance impact on wxString!")
148 void wxStringData::Free()
154 // ===========================================================================
156 // ===========================================================================
158 // takes nLength elements of psz starting at nPos
159 void wxStringImpl::InitWith(const wxStringCharType
*psz
,
160 size_t nPos
, size_t nLength
)
164 // if the length is not given, assume the string to be NUL terminated
165 if ( nLength
== npos
) {
166 wxASSERT_MSG( nPos
<= wxStrlen(psz
), _T("index out of bounds") );
168 nLength
= wxStrlen(psz
+ nPos
);
171 STATISTICS_ADD(InitialLength
, nLength
);
174 // trailing '\0' is written in AllocBuffer()
175 if ( !AllocBuffer(nLength
) ) {
176 wxFAIL_MSG( _T("out of memory in wxStringImpl::InitWith") );
179 wxStringMemcpy(m_pchData
, psz
+ nPos
, nLength
);
183 wxStringImpl::wxStringImpl(const_iterator first
, const_iterator last
)
187 InitWith(first
, 0, last
- first
);
191 wxFAIL_MSG( _T("first must be before last") );
196 wxStringImpl::wxStringImpl(size_type n
, wxStringCharType ch
)
202 // ---------------------------------------------------------------------------
204 // ---------------------------------------------------------------------------
206 // allocates memory needed to store a C string of length nLen
207 bool wxStringImpl::AllocBuffer(size_t nLen
)
209 // allocating 0 sized buffer doesn't make sense, all empty strings should
211 wxASSERT( nLen
> 0 );
213 // make sure that we don't overflow
214 wxASSERT( nLen
< (INT_MAX
/ sizeof(wxStringCharType
)) -
215 (sizeof(wxStringData
) + EXTRA_ALLOC
+ 1) );
217 STATISTICS_ADD(Length
, nLen
);
220 // 1) one extra character for '\0' termination
221 // 2) sizeof(wxStringData) for housekeeping info
222 wxStringData
* pData
= (wxStringData
*)
223 malloc(sizeof(wxStringData
) + (nLen
+ EXTRA_ALLOC
+ 1)*sizeof(wxStringCharType
));
225 if ( pData
== NULL
) {
226 // allocation failures are handled by the caller
231 pData
->nDataLength
= nLen
;
232 pData
->nAllocLength
= nLen
+ EXTRA_ALLOC
;
233 m_pchData
= pData
->data(); // data starts after wxStringData
234 m_pchData
[nLen
] = wxT('\0');
238 // must be called before changing this string
239 bool wxStringImpl::CopyBeforeWrite()
241 wxStringData
* pData
= GetStringData();
243 if ( pData
->IsShared() ) {
244 pData
->Unlock(); // memory not freed because shared
245 size_t nLen
= pData
->nDataLength
;
246 if ( !AllocBuffer(nLen
) ) {
247 // allocation failures are handled by the caller
250 wxStringMemcpy(m_pchData
, pData
->data(), nLen
);
253 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
258 // must be called before replacing contents of this string
259 bool wxStringImpl::AllocBeforeWrite(size_t nLen
)
261 wxASSERT( nLen
!= 0 ); // doesn't make any sense
263 // must not share string and must have enough space
264 wxStringData
* pData
= GetStringData();
265 if ( pData
->IsShared() || pData
->IsEmpty() ) {
266 // can't work with old buffer, get new one
268 if ( !AllocBuffer(nLen
) ) {
269 // allocation failures are handled by the caller
274 if ( nLen
> pData
->nAllocLength
) {
275 // realloc the buffer instead of calling malloc() again, this is more
277 STATISTICS_ADD(Length
, nLen
);
281 pData
= (wxStringData
*)
283 sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxStringCharType
));
285 if ( pData
== NULL
) {
286 // allocation failures are handled by the caller
287 // keep previous data since reallocation failed
291 pData
->nAllocLength
= nLen
;
292 m_pchData
= pData
->data();
296 wxASSERT( !GetStringData()->IsShared() ); // we must be the only owner
298 // it doesn't really matter what the string length is as it's going to be
299 // overwritten later but, for extra safety, set it to 0 for now as we may
300 // have some junk in m_pchData
301 GetStringData()->nDataLength
= 0;
306 wxStringImpl
& wxStringImpl::append(size_t n
, wxStringCharType ch
)
308 size_type len
= length();
310 if ( !Alloc(len
+ n
) || !CopyBeforeWrite() ) {
311 wxFAIL_MSG( _T("out of memory in wxStringImpl::append") );
314 GetStringData()->nDataLength
= len
+ n
;
315 m_pchData
[len
+ n
] = '\0';
316 for ( size_t i
= 0; i
< n
; ++i
)
317 m_pchData
[len
+ i
] = ch
;
321 void wxStringImpl::resize(size_t nSize
, wxStringCharType ch
)
323 size_t len
= length();
327 erase(begin() + nSize
, end());
329 else if ( nSize
> len
)
331 append(nSize
- len
, ch
);
333 //else: we have exactly the specified length, nothing to do
336 // allocate enough memory for nLen characters
337 bool wxStringImpl::Alloc(size_t nLen
)
339 wxStringData
*pData
= GetStringData();
340 if ( pData
->nAllocLength
<= nLen
) {
341 if ( pData
->IsEmpty() ) {
344 pData
= (wxStringData
*)
345 malloc(sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxStringCharType
));
347 if ( pData
== NULL
) {
348 // allocation failure handled by caller
353 pData
->nDataLength
= 0;
354 pData
->nAllocLength
= nLen
;
355 m_pchData
= pData
->data(); // data starts after wxStringData
356 m_pchData
[0u] = wxT('\0');
358 else if ( pData
->IsShared() ) {
359 pData
->Unlock(); // memory not freed because shared
360 size_t nOldLen
= pData
->nDataLength
;
361 if ( !AllocBuffer(nLen
) ) {
362 // allocation failure handled by caller
365 // +1 to copy the terminator, too
366 memcpy(m_pchData
, pData
->data(), (nOldLen
+1)*sizeof(wxStringCharType
));
367 GetStringData()->nDataLength
= nOldLen
;
372 pData
= (wxStringData
*)
373 realloc(pData
, sizeof(wxStringData
) + (nLen
+ 1)*sizeof(wxStringCharType
));
375 if ( pData
== NULL
) {
376 // allocation failure handled by caller
377 // keep previous data since reallocation failed
381 // it's not important if the pointer changed or not (the check for this
382 // is not faster than assigning to m_pchData in all cases)
383 pData
->nAllocLength
= nLen
;
384 m_pchData
= pData
->data();
387 //else: we've already got enough
391 wxStringImpl::iterator
wxStringImpl::begin()
398 wxStringImpl::iterator
wxStringImpl::end()
402 return m_pchData
+ length();
405 wxStringImpl::iterator
wxStringImpl::erase(iterator it
)
407 size_type idx
= it
- begin();
409 return begin() + idx
;
412 wxStringImpl
& wxStringImpl::erase(size_t nStart
, size_t nLen
)
414 wxASSERT(nStart
<= length());
415 size_t strLen
= length() - nStart
;
416 // delete nLen or up to the end of the string characters
417 nLen
= strLen
< nLen
? strLen
: nLen
;
418 wxStringImpl
strTmp(c_str(), nStart
);
419 strTmp
.append(c_str() + nStart
+ nLen
, length() - nStart
- nLen
);
425 wxStringImpl
& wxStringImpl::insert(size_t nPos
,
426 const wxStringCharType
*sz
, size_t n
)
428 wxASSERT( nPos
<= length() );
430 if ( n
== npos
) n
= wxStrlen(sz
);
431 if ( n
== 0 ) return *this;
433 if ( !Alloc(length() + n
) || !CopyBeforeWrite() ) {
434 wxFAIL_MSG( _T("out of memory in wxStringImpl::insert") );
438 memmove(m_pchData
+ nPos
+ n
, m_pchData
+ nPos
,
439 (length() - nPos
) * sizeof(wxStringCharType
));
440 memcpy(m_pchData
+ nPos
, sz
, n
* sizeof(wxStringCharType
));
441 GetStringData()->nDataLength
= length() + n
;
442 m_pchData
[length()] = '\0';
447 void wxStringImpl::swap(wxStringImpl
& str
)
449 wxStringCharType
* tmp
= str
.m_pchData
;
450 str
.m_pchData
= m_pchData
;
454 size_t wxStringImpl::find(const wxStringImpl
& str
, size_t nStart
) const
456 // deal with the special case of empty string first
457 const size_t nLen
= length();
458 const size_t nLenOther
= str
.length();
462 // empty string is a substring of anything
468 // the other string is non empty so can't be our substring
472 wxASSERT( str
.GetStringData()->IsValid() );
473 wxASSERT( nStart
<= nLen
);
475 const wxStringCharType
* const other
= str
.c_str();
478 const wxStringCharType
* p
=
479 (const wxStringCharType
*)wxStringMemchr(c_str() + nStart
,
486 while ( p
- c_str() + nLenOther
<= nLen
&&
487 wxStringMemcmp(p
, other
, nLenOther
) )
492 p
= (const wxStringCharType
*)
493 wxStringMemchr(p
, *other
, nLen
- (p
- c_str()));
499 return p
- c_str() + nLenOther
<= nLen
? p
- c_str() : npos
;
502 size_t wxStringImpl::find(const wxStringCharType
* sz
,
503 size_t nStart
, size_t n
) const
505 return find(wxStringImpl(sz
, n
), nStart
);
508 size_t wxStringImpl::find(wxStringCharType ch
, size_t nStart
) const
510 wxASSERT( nStart
<= length() );
512 const wxStringCharType
*p
= (const wxStringCharType
*)
513 wxStringMemchr(c_str() + nStart
, ch
, length() - nStart
);
515 return p
== NULL
? npos
: p
- c_str();
518 size_t wxStringImpl::rfind(const wxStringImpl
& str
, size_t nStart
) const
520 wxASSERT( str
.GetStringData()->IsValid() );
521 wxASSERT( nStart
== npos
|| nStart
<= length() );
523 if ( length() >= str
.length() )
525 // avoids a corner case later
526 if ( length() == 0 && str
.length() == 0 )
529 // "top" is the point where search starts from
530 size_t top
= length() - str
.length();
532 if ( nStart
== npos
)
533 nStart
= length() - 1;
537 const wxStringCharType
*cursor
= c_str() + top
;
540 if ( wxStringMemcmp(cursor
, str
.c_str(), str
.length()) == 0 )
542 return cursor
- c_str();
544 } while ( cursor
-- > c_str() );
550 size_t wxStringImpl::rfind(const wxStringCharType
* sz
,
551 size_t nStart
, size_t n
) const
553 return rfind(wxStringImpl(sz
, n
), nStart
);
556 size_t wxStringImpl::rfind(wxStringCharType ch
, size_t nStart
) const
558 if ( nStart
== npos
)
564 wxASSERT( nStart
<= length() );
567 const wxStringCharType
*actual
;
568 for ( actual
= c_str() + ( nStart
== npos
? length() : nStart
+ 1 );
569 actual
> c_str(); --actual
)
571 if ( *(actual
- 1) == ch
)
572 return (actual
- 1) - c_str();
578 wxStringImpl
& wxStringImpl::replace(size_t nStart
, size_t nLen
,
579 const wxStringCharType
*sz
, size_t nCount
)
581 // check and adjust parameters
582 const size_t lenOld
= length();
584 wxASSERT_MSG( nStart
<= lenOld
,
585 _T("index out of bounds in wxStringImpl::replace") );
586 size_t nEnd
= nStart
+ nLen
;
589 // nLen may be out of range, as it can be npos, just clump it down
590 nLen
= lenOld
- nStart
;
594 if ( nCount
== npos
)
595 nCount
= wxStrlen(sz
);
597 // build the new string from 3 pieces: part of this string before nStart,
598 // the new substring and the part of this string after nStart+nLen
600 const size_t lenNew
= lenOld
+ nCount
- nLen
;
603 tmp
.AllocBuffer(lenOld
+ nCount
- nLen
);
605 wxStringCharType
*dst
= tmp
.m_pchData
;
606 memcpy(dst
, m_pchData
, nStart
*sizeof(wxStringCharType
));
609 memcpy(dst
, sz
, nCount
*sizeof(wxStringCharType
));
612 memcpy(dst
, m_pchData
+ nEnd
, (lenOld
- nEnd
)*sizeof(wxStringCharType
));
615 // and replace this string contents with the new one
620 wxStringImpl
wxStringImpl::substr(size_t nStart
, size_t nLen
) const
623 nLen
= length() - nStart
;
624 return wxStringImpl(*this, nStart
, nLen
);
627 // assigns one string to another
628 wxStringImpl
& wxStringImpl::operator=(const wxStringImpl
& stringSrc
)
630 wxASSERT( stringSrc
.GetStringData()->IsValid() );
632 // don't copy string over itself
633 if ( m_pchData
!= stringSrc
.m_pchData
) {
634 if ( stringSrc
.GetStringData()->IsEmpty() ) {
639 GetStringData()->Unlock();
640 m_pchData
= stringSrc
.m_pchData
;
641 GetStringData()->Lock();
648 // assigns a single character
649 wxStringImpl
& wxStringImpl::operator=(wxStringCharType ch
)
651 wxStringCharType
c(ch
);
652 if ( !AssignCopy(1, &c
) ) {
653 wxFAIL_MSG( _T("out of memory in wxStringImpl::operator=(wxStringCharType)") );
659 wxStringImpl
& wxStringImpl::operator=(const wxStringCharType
*psz
)
661 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
662 wxFAIL_MSG( _T("out of memory in wxStringImpl::operator=(const wxStringCharType *)") );
667 // helper function: does real copy
668 bool wxStringImpl::AssignCopy(size_t nSrcLen
,
669 const wxStringCharType
*pszSrcData
)
671 if ( nSrcLen
== 0 ) {
675 if ( !AllocBeforeWrite(nSrcLen
) ) {
676 // allocation failure handled by caller
679 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxStringCharType
));
680 GetStringData()->nDataLength
= nSrcLen
;
681 m_pchData
[nSrcLen
] = wxT('\0');
686 // ---------------------------------------------------------------------------
687 // string concatenation
688 // ---------------------------------------------------------------------------
690 // add something to this string
691 bool wxStringImpl::ConcatSelf(size_t nSrcLen
,
692 const wxStringCharType
*pszSrcData
,
695 STATISTICS_ADD(SummandLength
, nSrcLen
);
697 nSrcLen
= nSrcLen
< nMaxLen
? nSrcLen
: nMaxLen
;
699 // concatenating an empty string is a NOP
701 wxStringData
*pData
= GetStringData();
702 size_t nLen
= pData
->nDataLength
;
704 // take special care when appending part of this string to itself: the code
705 // below reallocates our buffer and this invalidates pszSrcData pointer so
706 // we have to copy it in another temporary string in this case (but avoid
707 // doing this unnecessarily)
708 if ( pszSrcData
>= m_pchData
&& pszSrcData
< m_pchData
+ nLen
)
710 wxStringImpl
tmp(pszSrcData
, nSrcLen
);
711 return ConcatSelf(nSrcLen
, tmp
.m_pchData
, nSrcLen
);
714 size_t nNewLen
= nLen
+ nSrcLen
;
716 // alloc new buffer if current is too small
717 if ( pData
->IsShared() ) {
718 STATISTICS_ADD(ConcatHit
, 0);
720 // we have to allocate another buffer
721 wxStringData
* pOldData
= GetStringData();
722 if ( !AllocBuffer(nNewLen
) ) {
723 // allocation failure handled by caller
726 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxStringCharType
));
729 else if ( nNewLen
> pData
->nAllocLength
) {
730 STATISTICS_ADD(ConcatHit
, 0);
733 // we have to grow the buffer
734 if ( capacity() < nNewLen
) {
735 // allocation failure handled by caller
740 STATISTICS_ADD(ConcatHit
, 1);
742 // the buffer is already big enough
745 // should be enough space
746 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
748 // fast concatenation - all is done in our buffer
749 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxStringCharType
));
751 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
752 GetStringData()->nDataLength
= nNewLen
; // and fix the length
754 //else: the string to append was empty
758 // get the pointer to writable buffer of (at least) nLen bytes
759 wxStringCharType
*wxStringImpl::DoGetWriteBuf(size_t nLen
)
761 if ( !AllocBeforeWrite(nLen
) ) {
762 // allocation failure handled by caller
766 wxASSERT( GetStringData()->nRefs
== 1 );
767 GetStringData()->Validate(false);
772 // put string back in a reasonable state after GetWriteBuf
773 void wxStringImpl::DoUngetWriteBuf()
775 DoUngetWriteBuf(wxStrlen(m_pchData
));
778 void wxStringImpl::DoUngetWriteBuf(size_t nLen
)
780 wxStringData
* const pData
= GetStringData();
782 wxASSERT_MSG( nLen
< pData
->nAllocLength
, _T("buffer overrun") );
784 // the strings we store are always NUL-terminated
785 pData
->data()[nLen
] = _T('\0');
786 pData
->nDataLength
= nLen
;
787 pData
->Validate(true);
790 #endif // !wxUSE_STL_BASED_WXSTRING