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
)
581 wxASSERT_MSG( nStart
<= length(),
582 _T("index out of bounds in wxStringImpl::replace") );
583 size_t strLen
= length() - nStart
;
584 nLen
= strLen
< nLen
? strLen
: nLen
;
587 strTmp
.reserve(length()); // micro optimisation to avoid multiple mem allocs
589 //This is kind of inefficient, but its pretty good considering...
590 //we don't want to use character access operators here because on STL
591 //it will freeze the reference count of strTmp, which means a deep copy
592 //at the end when swap is called
594 //Also, we can't use append with the full character pointer and must
595 //do it manually because this string can contain null characters
596 for(size_t i1
= 0; i1
< nStart
; ++i1
)
597 strTmp
.append(1, this->c_str()[i1
]);
599 //its safe to do the full version here because
600 //sz must be a normal c string
603 for(size_t i2
= nStart
+ nLen
; i2
< length(); ++i2
)
604 strTmp
.append(1, this->c_str()[i2
]);
610 wxStringImpl
& wxStringImpl::replace(size_t nStart
, size_t nLen
,
611 size_t nCount
, wxStringCharType ch
)
613 return replace(nStart
, nLen
, wxStringImpl(nCount
, ch
).c_str());
616 wxStringImpl
& wxStringImpl::replace(size_t nStart
, size_t nLen
,
617 const wxStringImpl
& str
,
618 size_t nStart2
, size_t nLen2
)
620 return replace(nStart
, nLen
, str
.substr(nStart2
, nLen2
));
623 wxStringImpl
& wxStringImpl::replace(size_t nStart
, size_t nLen
,
624 const wxStringCharType
* sz
, size_t nCount
)
626 return replace(nStart
, nLen
, wxStringImpl(sz
, nCount
).c_str());
629 wxStringImpl
wxStringImpl::substr(size_t nStart
, size_t nLen
) const
632 nLen
= length() - nStart
;
633 return wxStringImpl(*this, nStart
, nLen
);
636 // assigns one string to another
637 wxStringImpl
& wxStringImpl::operator=(const wxStringImpl
& stringSrc
)
639 wxASSERT( stringSrc
.GetStringData()->IsValid() );
641 // don't copy string over itself
642 if ( m_pchData
!= stringSrc
.m_pchData
) {
643 if ( stringSrc
.GetStringData()->IsEmpty() ) {
648 GetStringData()->Unlock();
649 m_pchData
= stringSrc
.m_pchData
;
650 GetStringData()->Lock();
657 // assigns a single character
658 wxStringImpl
& wxStringImpl::operator=(wxStringCharType ch
)
660 wxStringCharType
c(ch
);
661 if ( !AssignCopy(1, &c
) ) {
662 wxFAIL_MSG( _T("out of memory in wxStringImpl::operator=(wxStringCharType)") );
668 wxStringImpl
& wxStringImpl::operator=(const wxStringCharType
*psz
)
670 if ( !AssignCopy(wxStrlen(psz
), psz
) ) {
671 wxFAIL_MSG( _T("out of memory in wxStringImpl::operator=(const wxStringCharType *)") );
676 // helper function: does real copy
677 bool wxStringImpl::AssignCopy(size_t nSrcLen
,
678 const wxStringCharType
*pszSrcData
)
680 if ( nSrcLen
== 0 ) {
684 if ( !AllocBeforeWrite(nSrcLen
) ) {
685 // allocation failure handled by caller
688 memcpy(m_pchData
, pszSrcData
, nSrcLen
*sizeof(wxStringCharType
));
689 GetStringData()->nDataLength
= nSrcLen
;
690 m_pchData
[nSrcLen
] = wxT('\0');
695 // ---------------------------------------------------------------------------
696 // string concatenation
697 // ---------------------------------------------------------------------------
699 // add something to this string
700 bool wxStringImpl::ConcatSelf(size_t nSrcLen
,
701 const wxStringCharType
*pszSrcData
,
704 STATISTICS_ADD(SummandLength
, nSrcLen
);
706 nSrcLen
= nSrcLen
< nMaxLen
? nSrcLen
: nMaxLen
;
708 // concatenating an empty string is a NOP
710 wxStringData
*pData
= GetStringData();
711 size_t nLen
= pData
->nDataLength
;
712 size_t nNewLen
= nLen
+ nSrcLen
;
714 // alloc new buffer if current is too small
715 if ( pData
->IsShared() ) {
716 STATISTICS_ADD(ConcatHit
, 0);
718 // we have to allocate another buffer
719 wxStringData
* pOldData
= GetStringData();
720 if ( !AllocBuffer(nNewLen
) ) {
721 // allocation failure handled by caller
724 memcpy(m_pchData
, pOldData
->data(), nLen
*sizeof(wxStringCharType
));
727 else if ( nNewLen
> pData
->nAllocLength
) {
728 STATISTICS_ADD(ConcatHit
, 0);
731 // we have to grow the buffer
732 if ( capacity() < nNewLen
) {
733 // allocation failure handled by caller
738 STATISTICS_ADD(ConcatHit
, 1);
740 // the buffer is already big enough
743 // should be enough space
744 wxASSERT( nNewLen
<= GetStringData()->nAllocLength
);
746 // fast concatenation - all is done in our buffer
747 memcpy(m_pchData
+ nLen
, pszSrcData
, nSrcLen
*sizeof(wxStringCharType
));
749 m_pchData
[nNewLen
] = wxT('\0'); // put terminating '\0'
750 GetStringData()->nDataLength
= nNewLen
; // and fix the length
752 //else: the string to append was empty
756 // get the pointer to writable buffer of (at least) nLen bytes
757 wxStringCharType
*wxStringImpl::DoGetWriteBuf(size_t nLen
)
759 if ( !AllocBeforeWrite(nLen
) ) {
760 // allocation failure handled by caller
764 wxASSERT( GetStringData()->nRefs
== 1 );
765 GetStringData()->Validate(false);
770 // put string back in a reasonable state after GetWriteBuf
771 void wxStringImpl::DoUngetWriteBuf()
773 DoUngetWriteBuf(wxStrlen(m_pchData
));
776 void wxStringImpl::DoUngetWriteBuf(size_t nLen
)
778 wxStringData
* const pData
= GetStringData();
780 wxASSERT_MSG( nLen
< pData
->nAllocLength
, _T("buffer overrun") );
782 // the strings we store are always NUL-terminated
783 pData
->data()[nLen
] = _T('\0');
784 pData
->nDataLength
= nLen
;
785 pData
->Validate(true);
788 #endif // !wxUSE_STL_BASED_WXSTRING