1 // Reference-counted versatile string base -*- C++ -*-
3 // Copyright (C) 2005, 2006, 2007 Free Software Foundation, Inc.
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 2, or (at your option)
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License along
17 // with this library; see the file COPYING. If not, write to the Free
18 // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
21 // As a special exception, you may use this file as part of a free software
22 // library without restriction. Specifically, if other files instantiate
23 // templates or use macros or inline functions from this file, or you compile
24 // this file and link it with other files to produce an executable, this
25 // file does not by itself cause the resulting executable to be covered by
26 // the GNU General Public License. This exception does not however
27 // invalidate any other reasons why the executable file might be covered by
28 // the GNU General Public License.
30 /** @file ext/rc_string_base.h
31 * This file is a GNU extension to the Standard C++ Library.
32 * This is an internal header file, included by other library headers.
33 * You should not attempt to use it directly.
36 #ifndef _RC_STRING_BASE_H
37 #define _RC_STRING_BASE_H 1
39 #include <ext/atomicity.h>
40 #include <bits/stl_iterator_base_funcs.h>
42 _GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx)
46 * Documentation? What's that?
47 * Nathan Myers <ncm@cantrip.org>.
49 * A string looks like this:
54 * [__rc_string_base<char_type>] _M_capacity
55 * _M_dataplus _M_refcount
56 * _M_p ----------------> unnamed array of char_type
59 * Where the _M_p points to the first character in the string, and
60 * you cast it to a pointer-to-_Rep and subtract 1 to get a
61 * pointer to the header.
63 * This approach has the enormous advantage that a string object
64 * requires only one allocation. All the ugliness is confined
65 * within a single pair of inline functions, which each compile to
66 * a single "add" instruction: _Rep::_M_refdata(), and
67 * __rc_string_base::_M_rep(); and the allocation function which gets a
68 * block of raw bytes and with room enough and constructs a _Rep
69 * object at the front.
71 * The reason you want _M_data pointing to the character array and
72 * not the _Rep is so that the debugger can see the string
73 * contents. (Probably we should add a non-inline member to get
74 * the _Rep for the debugger to use, so users can check the actual
77 * Note that the _Rep object is a POD so that you can have a
78 * static "empty string" _Rep object already "constructed" before
79 * static constructors have run. The reference-count encoding is
80 * chosen so that a 0 indicates one reference, so you never try to
81 * destroy the empty-string _Rep object.
83 * All but the last paragraph is considered pretty conventional
84 * for a C++ string implementation.
87 template<typename _CharT, typename _Traits, typename _Alloc>
88 class __rc_string_base
89 : protected __vstring_utility<_CharT, _Traits, _Alloc>
92 typedef _Traits traits_type;
93 typedef typename _Traits::char_type value_type;
94 typedef _Alloc allocator_type;
96 typedef __vstring_utility<_CharT, _Traits, _Alloc> _Util_Base;
97 typedef typename _Util_Base::_CharT_alloc_type _CharT_alloc_type;
98 typedef typename _CharT_alloc_type::size_type size_type;
101 // _Rep: string representation
103 // 1. String really contains _M_length + 1 characters: due to 21.3.4
104 // must be kept null-terminated.
105 // 2. _M_capacity >= _M_length
106 // Allocated memory is always (_M_capacity + 1) * sizeof(_CharT).
107 // 3. _M_refcount has three states:
108 // -1: leaked, one reference, no ref-copies allowed, non-const.
109 // 0: one reference, non-const.
110 // n>0: n + 1 references, operations require a lock, const.
111 // 4. All fields == 0 is an empty string, given the extra storage
112 // beyond-the-end for a null terminator; thus, the shared
113 // empty string representation needs no constructor.
121 size_type _M_capacity;
122 _Atomic_word _M_refcount;
125 // Only for alignment purposes.
129 typedef typename _Alloc::template rebind<_Rep>::other _Rep_alloc_type;
133 { return reinterpret_cast<_CharT*>(this + 1); }
138 __atomic_add_dispatch(&_M_info._M_refcount, 1);
143 _M_set_length(size_type __n)
145 _M_info._M_refcount = 0; // One reference.
146 _M_info._M_length = __n;
147 // grrr. (per 21.3.4)
148 // You cannot leave those LWG people alone for a second.
149 traits_type::assign(_M_refdata()[__n], _CharT());
154 _S_create(size_type, size_type, const _Alloc&);
157 _M_destroy(const _Alloc&) throw();
160 _M_clone(const _Alloc&, size_type __res = 0);
169 static _Rep_empty _S_empty_rep;
171 // The maximum number of individual char_type elements of an
172 // individual string is determined by _S_max_size. This is the
173 // value that will be returned by max_size(). (Whereas npos
174 // is the maximum number of bytes the allocator can allocate.)
175 // If one was to divvy up the theoretical largest size string,
176 // with a terminating character and m _CharT elements, it'd
178 // npos = sizeof(_Rep) + (m * sizeof(_CharT)) + sizeof(_CharT)
179 // + sizeof(_Rep) - 1
180 // (NB: last two terms for rounding reasons, see _M_create below)
182 // m = ((npos - 2 * sizeof(_Rep) + 1) / sizeof(_CharT)) - 1
183 // In addition, this implementation halfs this amount.
184 enum { _S_max_size = (((static_cast<size_type>(-1) - 2 * sizeof(_Rep)
185 + 1) / sizeof(_CharT)) - 1) / 2 };
187 // Data Member (private):
188 mutable typename _Util_Base::template _Alloc_hider<_Alloc> _M_dataplus;
192 { _M_dataplus._M_p = __p; }
196 { return &((reinterpret_cast<_Rep*>(_M_data()))[-1]); }
199 _M_grab(const _Alloc& __alloc) const
201 return (!_M_is_leaked() && _M_get_allocator() == __alloc)
202 ? _M_rep()->_M_refcopy() : _M_rep()->_M_clone(__alloc);
208 if (__exchange_and_add_dispatch(&_M_rep()->_M_info._M_refcount,
210 _M_rep()->_M_destroy(_M_get_allocator());
215 { return _M_rep()->_M_info._M_refcount < 0; }
219 { _M_rep()->_M_info._M_refcount = 0; }
224 // _S_construct_aux is used to implement the 21.3.1 para 15 which
225 // requires special behaviour if _InIterator is an integral type
226 template<typename _InIterator>
228 _S_construct_aux(_InIterator __beg, _InIterator __end,
229 const _Alloc& __a, std::__false_type)
231 typedef typename iterator_traits<_InIterator>::iterator_category _Tag;
232 return _S_construct(__beg, __end, __a, _Tag());
235 // _GLIBCXX_RESOLVE_LIB_DEFECTS
236 // 438. Ambiguity in the "do the right thing" clause
237 template<typename _Integer>
239 _S_construct_aux(_Integer __beg, _Integer __end,
240 const _Alloc& __a, std::__true_type)
241 { return _S_construct(static_cast<size_type>(__beg), __end, __a); }
243 template<typename _InIterator>
245 _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a)
247 typedef typename std::__is_integer<_InIterator>::__type _Integral;
248 return _S_construct_aux(__beg, __end, __a, _Integral());
251 // For Input Iterators, used in istreambuf_iterators, etc.
252 template<typename _InIterator>
254 _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a,
255 std::input_iterator_tag);
257 // For forward_iterators up to random_access_iterators, used for
258 // string::iterator, _CharT*, etc.
259 template<typename _FwdIterator>
261 _S_construct(_FwdIterator __beg, _FwdIterator __end, const _Alloc& __a,
262 std::forward_iterator_tag);
265 _S_construct(size_type __req, _CharT __c, const _Alloc& __a);
270 { return size_type(_S_max_size); }
274 { return _M_dataplus._M_p; }
278 { return _M_rep()->_M_info._M_length; }
282 { return _M_rep()->_M_info._M_capacity; }
286 { return _M_rep()->_M_info._M_refcount > 0; }
290 { _M_rep()->_M_info._M_refcount = -1; }
293 _M_leak() // for use in begin() & non-const op[]
300 _M_set_length(size_type __n)
301 { _M_rep()->_M_set_length(__n); }
304 : _M_dataplus(_S_empty_rep._M_refcopy()) { }
306 __rc_string_base(const _Alloc& __a);
308 __rc_string_base(const __rc_string_base& __rcs);
310 #ifdef __GXX_EXPERIMENTAL_CXX0X__
311 __rc_string_base(__rc_string_base&& __rcs)
312 : _M_dataplus(__rcs._M_get_allocator(), __rcs._M_data())
313 { __rcs._M_data(_S_empty_rep._M_refcopy()); }
316 __rc_string_base(size_type __n, _CharT __c, const _Alloc& __a);
318 template<typename _InputIterator>
319 __rc_string_base(_InputIterator __beg, _InputIterator __end,
327 { return _M_dataplus; }
329 const allocator_type&
330 _M_get_allocator() const
331 { return _M_dataplus; }
334 _M_swap(__rc_string_base& __rcs);
337 _M_assign(const __rc_string_base& __rcs);
340 _M_reserve(size_type __res);
343 _M_mutate(size_type __pos, size_type __len1, const _CharT* __s,
347 _M_erase(size_type __pos, size_type __n);
351 { _M_erase(size_type(0), _M_length()); }
354 _M_compare(const __rc_string_base&) const
358 template<typename _CharT, typename _Traits, typename _Alloc>
359 typename __rc_string_base<_CharT, _Traits, _Alloc>::_Rep_empty
360 __rc_string_base<_CharT, _Traits, _Alloc>::_S_empty_rep;
362 template<typename _CharT, typename _Traits, typename _Alloc>
363 typename __rc_string_base<_CharT, _Traits, _Alloc>::_Rep*
364 __rc_string_base<_CharT, _Traits, _Alloc>::_Rep::
365 _S_create(size_type __capacity, size_type __old_capacity,
366 const _Alloc& __alloc)
368 // _GLIBCXX_RESOLVE_LIB_DEFECTS
369 // 83. String::npos vs. string::max_size()
370 if (__capacity > size_type(_S_max_size))
371 std::__throw_length_error(__N("__rc_string_base::_Rep::_S_create"));
373 // The standard places no restriction on allocating more memory
374 // than is strictly needed within this layer at the moment or as
375 // requested by an explicit application call to reserve().
377 // Many malloc implementations perform quite poorly when an
378 // application attempts to allocate memory in a stepwise fashion
379 // growing each allocation size by only 1 char. Additionally,
380 // it makes little sense to allocate less linear memory than the
381 // natural blocking size of the malloc implementation.
382 // Unfortunately, we would need a somewhat low-level calculation
383 // with tuned parameters to get this perfect for any particular
384 // malloc implementation. Fortunately, generalizations about
385 // common features seen among implementations seems to suffice.
387 // __pagesize need not match the actual VM page size for good
388 // results in practice, thus we pick a common value on the low
389 // side. __malloc_header_size is an estimate of the amount of
390 // overhead per memory allocation (in practice seen N * sizeof
391 // (void*) where N is 0, 2 or 4). According to folklore,
392 // picking this value on the high side is better than
393 // low-balling it (especially when this algorithm is used with
394 // malloc implementations that allocate memory blocks rounded up
395 // to a size which is a power of 2).
396 const size_type __pagesize = 4096;
397 const size_type __malloc_header_size = 4 * sizeof(void*);
399 // The below implements an exponential growth policy, necessary to
400 // meet amortized linear time requirements of the library: see
401 // http://gcc.gnu.org/ml/libstdc++/2001-07/msg00085.html.
402 if (__capacity > __old_capacity && __capacity < 2 * __old_capacity)
404 __capacity = 2 * __old_capacity;
405 // Never allocate a string bigger than _S_max_size.
406 if (__capacity > size_type(_S_max_size))
407 __capacity = size_type(_S_max_size);
410 // NB: Need an array of char_type[__capacity], plus a terminating
411 // null char_type() element, plus enough for the _Rep data structure,
412 // plus sizeof(_Rep) - 1 to upper round to a size multiple of
414 // Whew. Seemingly so needy, yet so elemental.
415 size_type __size = ((__capacity + 1) * sizeof(_CharT)
416 + 2 * sizeof(_Rep) - 1);
418 const size_type __adj_size = __size + __malloc_header_size;
419 if (__adj_size > __pagesize && __capacity > __old_capacity)
421 const size_type __extra = __pagesize - __adj_size % __pagesize;
422 __capacity += __extra / sizeof(_CharT);
423 if (__capacity > size_type(_S_max_size))
424 __capacity = size_type(_S_max_size);
425 __size = (__capacity + 1) * sizeof(_CharT) + 2 * sizeof(_Rep) - 1;
428 // NB: Might throw, but no worries about a leak, mate: _Rep()
430 _Rep* __place = _Rep_alloc_type(__alloc).allocate(__size / sizeof(_Rep));
431 _Rep* __p = new (__place) _Rep;
432 __p->_M_info._M_capacity = __capacity;
436 template<typename _CharT, typename _Traits, typename _Alloc>
438 __rc_string_base<_CharT, _Traits, _Alloc>::_Rep::
439 _M_destroy(const _Alloc& __a) throw ()
441 const size_type __size = ((_M_info._M_capacity + 1) * sizeof(_CharT)
442 + 2 * sizeof(_Rep) - 1);
443 _Rep_alloc_type(__a).deallocate(this, __size / sizeof(_Rep));
446 template<typename _CharT, typename _Traits, typename _Alloc>
448 __rc_string_base<_CharT, _Traits, _Alloc>::_Rep::
449 _M_clone(const _Alloc& __alloc, size_type __res)
451 // Requested capacity of the clone.
452 const size_type __requested_cap = _M_info._M_length + __res;
453 _Rep* __r = _Rep::_S_create(__requested_cap, _M_info._M_capacity,
456 if (_M_info._M_length)
457 _S_copy(__r->_M_refdata(), _M_refdata(), _M_info._M_length);
459 __r->_M_set_length(_M_info._M_length);
460 return __r->_M_refdata();
463 template<typename _CharT, typename _Traits, typename _Alloc>
464 __rc_string_base<_CharT, _Traits, _Alloc>::
465 __rc_string_base(const _Alloc& __a)
466 : _M_dataplus(__a, _S_construct(size_type(), _CharT(), __a)) { }
468 template<typename _CharT, typename _Traits, typename _Alloc>
469 __rc_string_base<_CharT, _Traits, _Alloc>::
470 __rc_string_base(const __rc_string_base& __rcs)
471 : _M_dataplus(__rcs._M_get_allocator(),
472 __rcs._M_grab(__rcs._M_get_allocator())) { }
474 template<typename _CharT, typename _Traits, typename _Alloc>
475 __rc_string_base<_CharT, _Traits, _Alloc>::
476 __rc_string_base(size_type __n, _CharT __c, const _Alloc& __a)
477 : _M_dataplus(__a, _S_construct(__n, __c, __a)) { }
479 template<typename _CharT, typename _Traits, typename _Alloc>
480 template<typename _InputIterator>
481 __rc_string_base<_CharT, _Traits, _Alloc>::
482 __rc_string_base(_InputIterator __beg, _InputIterator __end,
484 : _M_dataplus(__a, _S_construct(__beg, __end, __a)) { }
486 template<typename _CharT, typename _Traits, typename _Alloc>
488 __rc_string_base<_CharT, _Traits, _Alloc>::
496 // NB: This is the special case for Input Iterators, used in
497 // istreambuf_iterators, etc.
498 // Input Iterators have a cost structure very different from
499 // pointers, calling for a different coding style.
500 template<typename _CharT, typename _Traits, typename _Alloc>
501 template<typename _InIterator>
503 __rc_string_base<_CharT, _Traits, _Alloc>::
504 _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a,
505 std::input_iterator_tag)
507 if (__beg == __end && __a == _Alloc())
508 return _S_empty_rep._M_refcopy();
510 // Avoid reallocation for common case.
513 while (__beg != __end && __len < sizeof(__buf) / sizeof(_CharT))
515 __buf[__len++] = *__beg;
518 _Rep* __r = _Rep::_S_create(__len, size_type(0), __a);
519 _S_copy(__r->_M_refdata(), __buf, __len);
522 while (__beg != __end)
524 if (__len == __r->_M_info._M_capacity)
526 // Allocate more space.
527 _Rep* __another = _Rep::_S_create(__len + 1, __len, __a);
528 _S_copy(__another->_M_refdata(), __r->_M_refdata(), __len);
529 __r->_M_destroy(__a);
532 __r->_M_refdata()[__len++] = *__beg;
538 __r->_M_destroy(__a);
539 __throw_exception_again;
541 __r->_M_set_length(__len);
542 return __r->_M_refdata();
545 template<typename _CharT, typename _Traits, typename _Alloc>
546 template<typename _InIterator>
548 __rc_string_base<_CharT, _Traits, _Alloc>::
549 _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a,
550 std::forward_iterator_tag)
552 if (__beg == __end && __a == _Alloc())
553 return _S_empty_rep._M_refcopy();
555 // NB: Not required, but considered best practice.
556 if (__builtin_expect(__is_null_pointer(__beg) && __beg != __end, 0))
557 std::__throw_logic_error(__N("__rc_string_base::"
558 "_S_construct NULL not valid"));
560 const size_type __dnew = static_cast<size_type>(std::distance(__beg,
562 // Check for out_of_range and length_error exceptions.
563 _Rep* __r = _Rep::_S_create(__dnew, size_type(0), __a);
565 { _S_copy_chars(__r->_M_refdata(), __beg, __end); }
568 __r->_M_destroy(__a);
569 __throw_exception_again;
571 __r->_M_set_length(__dnew);
572 return __r->_M_refdata();
575 template<typename _CharT, typename _Traits, typename _Alloc>
577 __rc_string_base<_CharT, _Traits, _Alloc>::
578 _S_construct(size_type __n, _CharT __c, const _Alloc& __a)
580 if (__n == 0 && __a == _Alloc())
581 return _S_empty_rep._M_refcopy();
583 // Check for out_of_range and length_error exceptions.
584 _Rep* __r = _Rep::_S_create(__n, size_type(0), __a);
586 _S_assign(__r->_M_refdata(), __n, __c);
588 __r->_M_set_length(__n);
589 return __r->_M_refdata();
592 template<typename _CharT, typename _Traits, typename _Alloc>
594 __rc_string_base<_CharT, _Traits, _Alloc>::
595 _M_swap(__rc_string_base& __rcs)
599 if (__rcs._M_is_leaked())
600 __rcs._M_set_sharable();
602 _CharT* __tmp = _M_data();
603 _M_data(__rcs._M_data());
604 __rcs._M_data(__tmp);
606 // _GLIBCXX_RESOLVE_LIB_DEFECTS
607 // 431. Swapping containers with unequal allocators.
608 std::__alloc_swap<allocator_type>::_S_do_it(_M_get_allocator(),
609 __rcs._M_get_allocator());
612 template<typename _CharT, typename _Traits, typename _Alloc>
614 __rc_string_base<_CharT, _Traits, _Alloc>::
615 _M_assign(const __rc_string_base& __rcs)
617 if (_M_rep() != __rcs._M_rep())
619 _CharT* __tmp = __rcs._M_grab(_M_get_allocator());
625 template<typename _CharT, typename _Traits, typename _Alloc>
627 __rc_string_base<_CharT, _Traits, _Alloc>::
628 _M_reserve(size_type __res)
630 // Make sure we don't shrink below the current size.
631 if (__res < _M_length())
634 if (__res != _M_capacity() || _M_is_shared())
636 _CharT* __tmp = _M_rep()->_M_clone(_M_get_allocator(),
637 __res - _M_length());
643 template<typename _CharT, typename _Traits, typename _Alloc>
645 __rc_string_base<_CharT, _Traits, _Alloc>::
646 _M_mutate(size_type __pos, size_type __len1, const _CharT* __s,
649 const size_type __how_much = _M_length() - __pos - __len1;
651 _Rep* __r = _Rep::_S_create(_M_length() + __len2 - __len1,
652 _M_capacity(), _M_get_allocator());
655 _S_copy(__r->_M_refdata(), _M_data(), __pos);
657 _S_copy(__r->_M_refdata() + __pos, __s, __len2);
659 _S_copy(__r->_M_refdata() + __pos + __len2,
660 _M_data() + __pos + __len1, __how_much);
663 _M_data(__r->_M_refdata());
666 template<typename _CharT, typename _Traits, typename _Alloc>
668 __rc_string_base<_CharT, _Traits, _Alloc>::
669 _M_erase(size_type __pos, size_type __n)
671 const size_type __new_size = _M_length() - __n;
672 const size_type __how_much = _M_length() - __pos - __n;
677 _Rep* __r = _Rep::_S_create(__new_size, _M_capacity(),
681 _S_copy(__r->_M_refdata(), _M_data(), __pos);
683 _S_copy(__r->_M_refdata() + __pos,
684 _M_data() + __pos + __n, __how_much);
687 _M_data(__r->_M_refdata());
689 else if (__how_much && __n)
692 _S_move(_M_data() + __pos,
693 _M_data() + __pos + __n, __how_much);
696 _M_rep()->_M_set_length(__new_size);
701 __rc_string_base<char, std::char_traits<char>,
702 std::allocator<char> >::
703 _M_compare(const __rc_string_base& __rcs) const
705 if (_M_rep() == __rcs._M_rep())
710 #ifdef _GLIBCXX_USE_WCHAR_T
713 __rc_string_base<wchar_t, std::char_traits<wchar_t>,
714 std::allocator<wchar_t> >::
715 _M_compare(const __rc_string_base& __rcs) const
717 if (_M_rep() == __rcs._M_rep())
723 _GLIBCXX_END_NAMESPACE
725 #endif /* _RC_STRING_BASE_H */