1 // Reference-counted versatile string base -*- C++ -*-
3 // Copyright (C) 2005, 2006 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 <bits/atomicity.h>
41 _GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx
)
45 * Documentation? What's that?
46 * Nathan Myers <ncm@cantrip.org>.
48 * A string looks like this:
53 * [__rc_string_base<char_type>] _M_capacity
54 * _M_dataplus _M_refcount
55 * _M_p ----------------> unnamed array of char_type
58 * Where the _M_p points to the first character in the string, and
59 * you cast it to a pointer-to-_Rep and subtract 1 to get a
60 * pointer to the header.
62 * This approach has the enormous advantage that a string object
63 * requires only one allocation. All the ugliness is confined
64 * within a single pair of inline functions, which each compile to
65 * a single "add" instruction: _Rep::_M_refdata(), and
66 * __rc_string_base::_M_rep(); and the allocation function which gets a
67 * block of raw bytes and with room enough and constructs a _Rep
68 * object at the front.
70 * The reason you want _M_data pointing to the character array and
71 * not the _Rep is so that the debugger can see the string
72 * contents. (Probably we should add a non-inline member to get
73 * the _Rep for the debugger to use, so users can check the actual
76 * Note that the _Rep object is a POD so that you can have a
77 * static "empty string" _Rep object already "constructed" before
78 * static constructors have run. The reference-count encoding is
79 * chosen so that a 0 indicates one reference, so you never try to
80 * destroy the empty-string _Rep object.
82 * All but the last paragraph is considered pretty conventional
83 * for a C++ string implementation.
86 template<typename _CharT
, typename _Traits
, typename _Alloc
>
87 class __rc_string_base
88 : protected __vstring_utility
<_CharT
, _Traits
, _Alloc
>
91 typedef _Traits traits_type
;
92 typedef typename
_Traits::char_type value_type
;
93 typedef _Alloc allocator_type
;
95 typedef __vstring_utility
<_CharT
, _Traits
, _Alloc
> _Util_Base
;
96 typedef typename
_Util_Base::_CharT_alloc_type _CharT_alloc_type
;
97 typedef typename
_CharT_alloc_type::size_type size_type
;
100 // _Rep: string representation
102 // 1. String really contains _M_length + 1 characters: due to 21.3.4
103 // must be kept null-terminated.
104 // 2. _M_capacity >= _M_length
105 // Allocated memory is always (_M_capacity + 1) * sizeof(_CharT).
106 // 3. _M_refcount has three states:
107 // -1: leaked, one reference, no ref-copies allowed, non-const.
108 // 0: one reference, non-const.
109 // n>0: n + 1 references, operations require a lock, const.
110 // 4. All fields == 0 is an empty string, given the extra storage
111 // beyond-the-end for a null terminator; thus, the shared
112 // empty string representation needs no constructor.
120 size_type _M_capacity
;
121 _Atomic_word _M_refcount
;
124 // Only for alignment purposes.
128 typedef typename
_Alloc::template rebind
<_Rep
>::other _Rep_alloc_type
;
132 { return reinterpret_cast<_CharT
*>(this + 1); }
137 __atomic_add_dispatch(&_M_info
._M_refcount
, 1);
142 _M_set_length(size_type __n
)
144 _M_info
._M_refcount
= 0; // One reference.
145 _M_info
._M_length
= __n
;
146 // grrr. (per 21.3.4)
147 // You cannot leave those LWG people alone for a second.
148 traits_type::assign(_M_refdata()[__n
], _CharT());
153 _S_create(size_type
, size_type
, const _Alloc
&);
156 _M_destroy(const _Alloc
&) throw();
159 _M_clone(const _Alloc
&, size_type __res
= 0);
168 static _Rep_empty _S_empty_rep
;
170 // The maximum number of individual char_type elements of an
171 // individual string is determined by _S_max_size. This is the
172 // value that will be returned by max_size(). (Whereas npos
173 // is the maximum number of bytes the allocator can allocate.)
174 // If one was to divvy up the theoretical largest size string,
175 // with a terminating character and m _CharT elements, it'd
177 // npos = sizeof(_Rep) + (m * sizeof(_CharT)) + sizeof(_CharT)
179 // m = ((npos - sizeof(_Rep)) / sizeof(_CharT)) - 1
180 // In addition, this implementation quarters this amount.
181 enum { _S_max_size
= (((static_cast<size_type
>(-1) - sizeof(_Rep
))
182 / sizeof(_CharT
)) - 1) / 4 };
184 // Data Member (private):
185 mutable typename
_Util_Base::template _Alloc_hider
<_Alloc
> _M_dataplus
;
189 { _M_dataplus
._M_p
= __p
; }
193 { return &((reinterpret_cast<_Rep
*>(_M_data()))[-1]); }
196 _M_grab(const _Alloc
& __alloc
) const
198 return (!_M_is_leaked() && _M_get_allocator() == __alloc
)
199 ? _M_rep()->_M_refcopy() : _M_rep()->_M_clone(__alloc
);
205 if (__exchange_and_add_dispatch(&_M_rep()->_M_info
._M_refcount
,
207 _M_rep()->_M_destroy(_M_get_allocator());
212 { return _M_rep()->_M_info
._M_refcount
< 0; }
216 { _M_rep()->_M_info
._M_refcount
= 0; }
221 // _S_construct_aux is used to implement the 21.3.1 para 15 which
222 // requires special behaviour if _InIterator is an integral type
223 template<typename _InIterator
>
225 _S_construct_aux(_InIterator __beg
, _InIterator __end
,
226 const _Alloc
& __a
, __false_type
)
228 typedef typename iterator_traits
<_InIterator
>::iterator_category _Tag
;
229 return _S_construct(__beg
, __end
, __a
, _Tag());
232 template<typename _InIterator
>
234 _S_construct_aux(_InIterator __beg
, _InIterator __end
,
235 const _Alloc
& __a
, __true_type
)
236 { return _S_construct(static_cast<size_type
>(__beg
),
237 static_cast<value_type
>(__end
), __a
); }
239 template<typename _InIterator
>
241 _S_construct(_InIterator __beg
, _InIterator __end
, const _Alloc
& __a
)
243 typedef typename
std::__is_integer
<_InIterator
>::__type _Integral
;
244 return _S_construct_aux(__beg
, __end
, __a
, _Integral());
247 // For Input Iterators, used in istreambuf_iterators, etc.
248 template<typename _InIterator
>
250 _S_construct(_InIterator __beg
, _InIterator __end
, const _Alloc
& __a
,
251 std::input_iterator_tag
);
253 // For forward_iterators up to random_access_iterators, used for
254 // string::iterator, _CharT*, etc.
255 template<typename _FwdIterator
>
257 _S_construct(_FwdIterator __beg
, _FwdIterator __end
, const _Alloc
& __a
,
258 std::forward_iterator_tag
);
261 _S_construct(size_type __req
, _CharT __c
, const _Alloc
& __a
);
266 { return size_type(_S_max_size
); }
270 { return _M_dataplus
._M_p
; }
274 { return _M_rep()->_M_info
._M_length
; }
278 { return _M_rep()->_M_info
._M_capacity
; }
282 { return _M_rep()->_M_info
._M_refcount
> 0; }
286 { _M_rep()->_M_info
._M_refcount
= -1; }
289 _M_leak() // for use in begin() & non-const op[]
296 _M_set_length(size_type __n
)
297 { _M_rep()->_M_set_length(__n
); }
300 : _M_dataplus(_Alloc(), _S_empty_rep
._M_refcopy()) { }
302 __rc_string_base(const _Alloc
& __a
);
304 __rc_string_base(const __rc_string_base
& __rcs
);
306 __rc_string_base(size_type __n
, _CharT __c
, const _Alloc
& __a
);
308 template<typename _InputIterator
>
309 __rc_string_base(_InputIterator __beg
, _InputIterator __end
,
317 { return _M_dataplus
; }
319 const allocator_type
&
320 _M_get_allocator() const
321 { return _M_dataplus
; }
324 _M_swap(__rc_string_base
& __rcs
);
327 _M_assign(const __rc_string_base
& __rcs
);
330 _M_reserve(size_type __res
);
333 _M_mutate(size_type __pos
, size_type __len1
, const _CharT
* __s
,
337 _M_erase(size_type __pos
, size_type __n
);
340 _M_compare(const __rc_string_base
&) const
344 template<typename _CharT
, typename _Traits
, typename _Alloc
>
345 typename __rc_string_base
<_CharT
, _Traits
, _Alloc
>::_Rep_empty
346 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::_S_empty_rep
;
348 template<typename _CharT
, typename _Traits
, typename _Alloc
>
349 typename __rc_string_base
<_CharT
, _Traits
, _Alloc
>::_Rep
*
350 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::_Rep::
351 _S_create(size_type __capacity
, size_type __old_capacity
,
352 const _Alloc
& __alloc
)
354 // _GLIBCXX_RESOLVE_LIB_DEFECTS
355 // 83. String::npos vs. string::max_size()
356 if (__capacity
> size_type(_S_max_size
))
357 std::__throw_length_error(__N("__rc_string_base::_Rep::_S_create"));
359 // The standard places no restriction on allocating more memory
360 // than is strictly needed within this layer at the moment or as
361 // requested by an explicit application call to reserve().
363 // Many malloc implementations perform quite poorly when an
364 // application attempts to allocate memory in a stepwise fashion
365 // growing each allocation size by only 1 char. Additionally,
366 // it makes little sense to allocate less linear memory than the
367 // natural blocking size of the malloc implementation.
368 // Unfortunately, we would need a somewhat low-level calculation
369 // with tuned parameters to get this perfect for any particular
370 // malloc implementation. Fortunately, generalizations about
371 // common features seen among implementations seems to suffice.
373 // __pagesize need not match the actual VM page size for good
374 // results in practice, thus we pick a common value on the low
375 // side. __malloc_header_size is an estimate of the amount of
376 // overhead per memory allocation (in practice seen N * sizeof
377 // (void*) where N is 0, 2 or 4). According to folklore,
378 // picking this value on the high side is better than
379 // low-balling it (especially when this algorithm is used with
380 // malloc implementations that allocate memory blocks rounded up
381 // to a size which is a power of 2).
382 const size_type __pagesize
= 4096;
383 const size_type __malloc_header_size
= 4 * sizeof(void*);
385 // The below implements an exponential growth policy, necessary to
386 // meet amortized linear time requirements of the library: see
387 // http://gcc.gnu.org/ml/libstdc++/2001-07/msg00085.html.
388 if (__capacity
> __old_capacity
&& __capacity
< 2 * __old_capacity
)
389 __capacity
= 2 * __old_capacity
;
391 // NB: Need an array of char_type[__capacity], plus a terminating
392 // null char_type() element, plus enough for the _Rep data structure,
393 // plus sizeof(_Rep) - 1 to upper round to a size multiple of
395 // Whew. Seemingly so needy, yet so elemental.
396 size_type __size
= ((__capacity
+ 1) * sizeof(_CharT
)
397 + 2 * sizeof(_Rep
) - 1);
399 const size_type __adj_size
= __size
+ __malloc_header_size
;
400 if (__adj_size
> __pagesize
&& __capacity
> __old_capacity
)
402 const size_type __extra
= __pagesize
- __adj_size
% __pagesize
;
403 __capacity
+= __extra
/ sizeof(_CharT
);
404 // Never allocate a string bigger than _S_max_size.
405 if (__capacity
> size_type(_S_max_size
))
406 __capacity
= size_type(_S_max_size
);
407 __size
= (__capacity
+ 1) * sizeof(_CharT
) + 2 * sizeof(_Rep
) - 1;
410 // NB: Might throw, but no worries about a leak, mate: _Rep()
412 _Rep
* __place
= _Rep_alloc_type(__alloc
).allocate(__size
/ sizeof(_Rep
));
413 _Rep
* __p
= new (__place
) _Rep
;
414 __p
->_M_info
._M_capacity
= __capacity
;
418 template<typename _CharT
, typename _Traits
, typename _Alloc
>
420 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::_Rep::
421 _M_destroy(const _Alloc
& __a
) throw ()
423 const size_type __size
= ((_M_info
._M_capacity
+ 1) * sizeof(_CharT
)
424 + 2 * sizeof(_Rep
) - 1);
425 _Rep_alloc_type(__a
).deallocate(this, __size
/ sizeof(_Rep
));
428 template<typename _CharT
, typename _Traits
, typename _Alloc
>
430 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::_Rep::
431 _M_clone(const _Alloc
& __alloc
, size_type __res
)
433 // Requested capacity of the clone.
434 const size_type __requested_cap
= _M_info
._M_length
+ __res
;
435 _Rep
* __r
= _Rep::_S_create(__requested_cap
, _M_info
._M_capacity
,
438 if (_M_info
._M_length
)
439 _S_copy(__r
->_M_refdata(), _M_refdata(), _M_info
._M_length
);
441 __r
->_M_set_length(_M_info
._M_length
);
442 return __r
->_M_refdata();
445 template<typename _CharT
, typename _Traits
, typename _Alloc
>
446 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
447 __rc_string_base(const _Alloc
& __a
)
448 : _M_dataplus(__a
, _S_construct(size_type(), _CharT(), __a
)) { }
450 template<typename _CharT
, typename _Traits
, typename _Alloc
>
451 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
452 __rc_string_base(const __rc_string_base
& __rcs
)
453 : _M_dataplus(__rcs
._M_get_allocator(),
454 __rcs
._M_grab(__rcs
._M_get_allocator())) { }
456 template<typename _CharT
, typename _Traits
, typename _Alloc
>
457 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
458 __rc_string_base(size_type __n
, _CharT __c
, const _Alloc
& __a
)
459 : _M_dataplus(__a
, _S_construct(__n
, __c
, __a
)) { }
461 template<typename _CharT
, typename _Traits
, typename _Alloc
>
462 template<typename _InputIterator
>
463 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
464 __rc_string_base(_InputIterator __beg
, _InputIterator __end
,
466 : _M_dataplus(__a
, _S_construct(__beg
, __end
, __a
)) { }
468 template<typename _CharT
, typename _Traits
, typename _Alloc
>
470 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
478 // NB: This is the special case for Input Iterators, used in
479 // istreambuf_iterators, etc.
480 // Input Iterators have a cost structure very different from
481 // pointers, calling for a different coding style.
482 template<typename _CharT
, typename _Traits
, typename _Alloc
>
483 template<typename _InIterator
>
485 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
486 _S_construct(_InIterator __beg
, _InIterator __end
, const _Alloc
& __a
,
487 std::input_iterator_tag
)
489 if (__beg
== __end
&& __a
== _Alloc())
490 return _S_empty_rep
._M_refcopy();
492 // Avoid reallocation for common case.
495 while (__beg
!= __end
&& __len
< sizeof(__buf
) / sizeof(_CharT
))
497 __buf
[__len
++] = *__beg
;
500 _Rep
* __r
= _Rep::_S_create(__len
, size_type(0), __a
);
501 _S_copy(__r
->_M_refdata(), __buf
, __len
);
504 while (__beg
!= __end
)
506 if (__len
== __r
->_M_info
._M_capacity
)
508 // Allocate more space.
509 _Rep
* __another
= _Rep::_S_create(__len
+ 1, __len
, __a
);
510 _S_copy(__another
->_M_refdata(), __r
->_M_refdata(), __len
);
511 __r
->_M_destroy(__a
);
514 __r
->_M_refdata()[__len
++] = *__beg
;
520 __r
->_M_destroy(__a
);
521 __throw_exception_again
;
523 __r
->_M_set_length(__len
);
524 return __r
->_M_refdata();
527 template<typename _CharT
, typename _Traits
, typename _Alloc
>
528 template<typename _InIterator
>
530 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
531 _S_construct(_InIterator __beg
, _InIterator __end
, const _Alloc
& __a
,
532 std::forward_iterator_tag
)
534 if (__beg
== __end
&& __a
== _Alloc())
535 return _S_empty_rep
._M_refcopy();
537 // NB: Not required, but considered best practice.
538 if (__builtin_expect(_S_is_null_pointer(__beg
) && __beg
!= __end
, 0))
539 std::__throw_logic_error(__N("__rc_string_base::"
540 "_S_construct NULL not valid"));
542 const size_type __dnew
= static_cast<size_type
>(std::distance(__beg
,
544 // Check for out_of_range and length_error exceptions.
545 _Rep
* __r
= _Rep::_S_create(__dnew
, size_type(0), __a
);
547 { _S_copy_chars(__r
->_M_refdata(), __beg
, __end
); }
550 __r
->_M_destroy(__a
);
551 __throw_exception_again
;
553 __r
->_M_set_length(__dnew
);
554 return __r
->_M_refdata();
557 template<typename _CharT
, typename _Traits
, typename _Alloc
>
559 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
560 _S_construct(size_type __n
, _CharT __c
, const _Alloc
& __a
)
562 if (__n
== 0 && __a
== _Alloc())
563 return _S_empty_rep
._M_refcopy();
565 // Check for out_of_range and length_error exceptions.
566 _Rep
* __r
= _Rep::_S_create(__n
, size_type(0), __a
);
568 _S_assign(__r
->_M_refdata(), __n
, __c
);
570 __r
->_M_set_length(__n
);
571 return __r
->_M_refdata();
574 template<typename _CharT
, typename _Traits
, typename _Alloc
>
576 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
577 _M_swap(__rc_string_base
& __rcs
)
581 if (__rcs
._M_is_leaked())
582 __rcs
._M_set_sharable();
584 _CharT
* __tmp
= _M_data();
585 _M_data(__rcs
._M_data());
586 __rcs
._M_data(__tmp
);
588 // _GLIBCXX_RESOLVE_LIB_DEFECTS
589 // 431. Swapping containers with unequal allocators.
590 std::__alloc_swap
<allocator_type
>::_S_do_it(_M_get_allocator(),
591 __rcs
._M_get_allocator());
594 template<typename _CharT
, typename _Traits
, typename _Alloc
>
596 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
597 _M_assign(const __rc_string_base
& __rcs
)
599 if (_M_rep() != __rcs
._M_rep())
601 _CharT
* __tmp
= __rcs
._M_grab(_M_get_allocator());
607 template<typename _CharT
, typename _Traits
, typename _Alloc
>
609 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
610 _M_reserve(size_type __res
)
612 // Make sure we don't shrink below the current size.
613 if (__res
< _M_length())
616 if (__res
!= _M_capacity() || _M_is_shared())
618 _CharT
* __tmp
= _M_rep()->_M_clone(_M_get_allocator(),
619 __res
- _M_length());
625 template<typename _CharT
, typename _Traits
, typename _Alloc
>
627 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
628 _M_mutate(size_type __pos
, size_type __len1
, const _CharT
* __s
,
631 const size_type __how_much
= _M_length() - __pos
- __len1
;
633 _Rep
* __r
= _Rep::_S_create(_M_length() + __len2
- __len1
,
634 _M_capacity(), _M_get_allocator());
637 _S_copy(__r
->_M_refdata(), _M_data(), __pos
);
639 _S_copy(__r
->_M_refdata() + __pos
, __s
, __len2
);
641 _S_copy(__r
->_M_refdata() + __pos
+ __len2
,
642 _M_data() + __pos
+ __len1
, __how_much
);
645 _M_data(__r
->_M_refdata());
648 template<typename _CharT
, typename _Traits
, typename _Alloc
>
650 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
651 _M_erase(size_type __pos
, size_type __n
)
653 const size_type __new_size
= _M_length() - __n
;
654 const size_type __how_much
= _M_length() - __pos
- __n
;
659 _Rep
* __r
= _Rep::_S_create(__new_size
, _M_capacity(),
663 _S_copy(__r
->_M_refdata(), _M_data(), __pos
);
665 _S_copy(__r
->_M_refdata() + __pos
,
666 _M_data() + __pos
+ __n
, __how_much
);
669 _M_data(__r
->_M_refdata());
671 else if (__how_much
&& __n
)
674 _S_move(_M_data() + __pos
,
675 _M_data() + __pos
+ __n
, __how_much
);
678 _M_rep()->_M_set_length(__new_size
);
683 __rc_string_base
<char, std::char_traits
<char>,
684 std::allocator
<char> >::
685 _M_compare(const __rc_string_base
& __rcs
) const
687 if (_M_rep() == __rcs
._M_rep())
694 __rc_string_base
<wchar_t, std::char_traits
<wchar_t>,
695 std::allocator
<wchar_t> >::
696 _M_compare(const __rc_string_base
& __rcs
) const
698 if (_M_rep() == __rcs
._M_rep())
703 _GLIBCXX_END_NAMESPACE
705 #endif /* _RC_STRING_BASE_H */