1 // Reference-counted versatile string base -*- C++ -*-
3 // Copyright (C) 2005-2018 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 3, 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 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 // <http://www.gnu.org/licenses/>.
25 /** @file ext/rc_string_base.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{ext/vstring.h}
30 #ifndef _RC_STRING_BASE_H
31 #define _RC_STRING_BASE_H 1
33 #include <ext/atomicity.h>
34 #include <bits/stl_iterator_base_funcs.h>
36 namespace __gnu_cxx
_GLIBCXX_VISIBILITY(default)
38 _GLIBCXX_BEGIN_NAMESPACE_VERSION
41 * Documentation? What's that?
42 * Nathan Myers <ncm@cantrip.org>.
44 * A string looks like this:
49 * [__rc_string_base<char_type>] _M_capacity
50 * _M_dataplus _M_refcount
51 * _M_p ----------------> unnamed array of char_type
54 * Where the _M_p points to the first character in the string, and
55 * you cast it to a pointer-to-_Rep and subtract 1 to get a
56 * pointer to the header.
58 * This approach has the enormous advantage that a string object
59 * requires only one allocation. All the ugliness is confined
60 * within a single pair of inline functions, which each compile to
61 * a single @a add instruction: _Rep::_M_refdata(), and
62 * __rc_string_base::_M_rep(); and the allocation function which gets a
63 * block of raw bytes and with room enough and constructs a _Rep
64 * object at the front.
66 * The reason you want _M_data pointing to the character array and
67 * not the _Rep is so that the debugger can see the string
68 * contents. (Probably we should add a non-inline member to get
69 * the _Rep for the debugger to use, so users can check the actual
72 * Note that the _Rep object is a POD so that you can have a
73 * static <em>empty string</em> _Rep object already @a constructed before
74 * static constructors have run. The reference-count encoding is
75 * chosen so that a 0 indicates one reference, so you never try to
76 * destroy the empty-string _Rep object.
78 * All but the last paragraph is considered pretty conventional
79 * for a C++ string implementation.
81 template<typename _CharT
, typename _Traits
, typename _Alloc
>
82 class __rc_string_base
83 : protected __vstring_utility
<_CharT
, _Traits
, _Alloc
>
86 typedef _Traits traits_type
;
87 typedef typename
_Traits::char_type value_type
;
88 typedef _Alloc allocator_type
;
90 typedef __vstring_utility
<_CharT
, _Traits
, _Alloc
> _Util_Base
;
91 typedef typename
_Util_Base::_CharT_alloc_type _CharT_alloc_type
;
92 typedef typename
_CharT_alloc_type::size_type size_type
;
95 // _Rep: string representation
97 // 1. String really contains _M_length + 1 characters: due to 21.3.4
98 // must be kept null-terminated.
99 // 2. _M_capacity >= _M_length
100 // Allocated memory is always (_M_capacity + 1) * sizeof(_CharT).
101 // 3. _M_refcount has three states:
102 // -1: leaked, one reference, no ref-copies allowed, non-const.
103 // 0: one reference, non-const.
104 // n>0: n + 1 references, operations require a lock, const.
105 // 4. All fields == 0 is an empty string, given the extra storage
106 // beyond-the-end for a null terminator; thus, the shared
107 // empty string representation needs no constructor.
115 size_type _M_capacity
;
116 _Atomic_word _M_refcount
;
119 // Only for alignment purposes.
123 typedef typename
_Alloc::template rebind
<_Rep
>::other _Rep_alloc_type
;
127 { return reinterpret_cast<_CharT
*>(this + 1); }
132 __atomic_add_dispatch(&_M_info
._M_refcount
, 1);
137 _M_set_length(size_type __n
)
139 _M_info
._M_refcount
= 0; // One reference.
140 _M_info
._M_length
= __n
;
141 // grrr. (per 21.3.4)
142 // You cannot leave those LWG people alone for a second.
143 traits_type::assign(_M_refdata()[__n
], _CharT());
148 _S_create(size_type
, size_type
, const _Alloc
&);
151 _M_destroy(const _Alloc
&) throw();
154 _M_clone(const _Alloc
&, size_type __res
= 0);
163 static _Rep_empty _S_empty_rep
;
165 // The maximum number of individual char_type elements of an
166 // individual string is determined by _S_max_size. This is the
167 // value that will be returned by max_size(). (Whereas npos
168 // is the maximum number of bytes the allocator can allocate.)
169 // If one was to divvy up the theoretical largest size string,
170 // with a terminating character and m _CharT elements, it'd
172 // npos = sizeof(_Rep) + (m * sizeof(_CharT)) + sizeof(_CharT)
173 // + sizeof(_Rep) - 1
174 // (NB: last two terms for rounding reasons, see _M_create below)
176 // m = ((npos - 2 * sizeof(_Rep) + 1) / sizeof(_CharT)) - 1
177 // In addition, this implementation halves this amount.
178 enum { _S_max_size
= (((static_cast<size_type
>(-1) - 2 * sizeof(_Rep
)
179 + 1) / sizeof(_CharT
)) - 1) / 2 };
181 // Data Member (private):
182 mutable typename
_Util_Base::template _Alloc_hider
<_Alloc
> _M_dataplus
;
186 { _M_dataplus
._M_p
= __p
; }
190 { return &((reinterpret_cast<_Rep
*>(_M_data()))[-1]); }
193 _M_grab(const _Alloc
& __alloc
) const
195 return (!_M_is_leaked() && _M_get_allocator() == __alloc
)
196 ? _M_rep()->_M_refcopy() : _M_rep()->_M_clone(__alloc
);
202 // Be race-detector-friendly. For more info see bits/c++config.
203 _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_rep()->_M_info
.
205 if (__exchange_and_add_dispatch(&_M_rep()->_M_info
._M_refcount
,
208 _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_rep()->_M_info
.
210 _M_rep()->_M_destroy(_M_get_allocator());
216 { return _M_rep()->_M_info
._M_refcount
< 0; }
220 { _M_rep()->_M_info
._M_refcount
= 0; }
225 // _S_construct_aux is used to implement the 21.3.1 para 15 which
226 // requires special behaviour if _InIterator is an integral type
227 template<typename _InIterator
>
229 _S_construct_aux(_InIterator __beg
, _InIterator __end
,
230 const _Alloc
& __a
, std::__false_type
)
232 typedef typename iterator_traits
<_InIterator
>::iterator_category _Tag
;
233 return _S_construct(__beg
, __end
, __a
, _Tag());
236 // _GLIBCXX_RESOLVE_LIB_DEFECTS
237 // 438. Ambiguity in the "do the right thing" clause
238 template<typename _Integer
>
240 _S_construct_aux(_Integer __beg
, _Integer __end
,
241 const _Alloc
& __a
, std::__true_type
)
242 { return _S_construct_aux_2(static_cast<size_type
>(__beg
),
246 _S_construct_aux_2(size_type __req
, _CharT __c
, const _Alloc
& __a
)
247 { return _S_construct(__req
, __c
, __a
); }
249 template<typename _InIterator
>
251 _S_construct(_InIterator __beg
, _InIterator __end
, const _Alloc
& __a
)
253 typedef typename
std::__is_integer
<_InIterator
>::__type _Integral
;
254 return _S_construct_aux(__beg
, __end
, __a
, _Integral());
257 // For Input Iterators, used in istreambuf_iterators, etc.
258 template<typename _InIterator
>
260 _S_construct(_InIterator __beg
, _InIterator __end
, const _Alloc
& __a
,
261 std::input_iterator_tag
);
263 // For forward_iterators up to random_access_iterators, used for
264 // string::iterator, _CharT*, etc.
265 template<typename _FwdIterator
>
267 _S_construct(_FwdIterator __beg
, _FwdIterator __end
, const _Alloc
& __a
,
268 std::forward_iterator_tag
);
271 _S_construct(size_type __req
, _CharT __c
, const _Alloc
& __a
);
276 { return size_type(_S_max_size
); }
280 { return _M_dataplus
._M_p
; }
284 { return _M_rep()->_M_info
._M_length
; }
288 { return _M_rep()->_M_info
._M_capacity
; }
292 { return _M_rep()->_M_info
._M_refcount
> 0; }
296 { _M_rep()->_M_info
._M_refcount
= -1; }
299 _M_leak() // for use in begin() & non-const op[]
306 _M_set_length(size_type __n
)
307 { _M_rep()->_M_set_length(__n
); }
310 : _M_dataplus(_S_empty_rep
._M_refcopy()) { }
312 __rc_string_base(const _Alloc
& __a
);
314 __rc_string_base(const __rc_string_base
& __rcs
);
316 #if __cplusplus >= 201103L
317 __rc_string_base(__rc_string_base
&& __rcs
)
318 : _M_dataplus(__rcs
._M_dataplus
)
319 { __rcs
._M_data(_S_empty_rep
._M_refcopy()); }
322 __rc_string_base(size_type __n
, _CharT __c
, const _Alloc
& __a
);
324 template<typename _InputIterator
>
325 __rc_string_base(_InputIterator __beg
, _InputIterator __end
,
333 { return _M_dataplus
; }
335 const allocator_type
&
336 _M_get_allocator() const
337 { return _M_dataplus
; }
340 _M_swap(__rc_string_base
& __rcs
);
343 _M_assign(const __rc_string_base
& __rcs
);
346 _M_reserve(size_type __res
);
349 _M_mutate(size_type __pos
, size_type __len1
, const _CharT
* __s
,
353 _M_erase(size_type __pos
, size_type __n
);
359 _M_data(_S_empty_rep
._M_refcopy());
363 _M_compare(const __rc_string_base
&) const
367 template<typename _CharT
, typename _Traits
, typename _Alloc
>
368 typename __rc_string_base
<_CharT
, _Traits
, _Alloc
>::_Rep_empty
369 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::_S_empty_rep
;
371 template<typename _CharT
, typename _Traits
, typename _Alloc
>
372 typename __rc_string_base
<_CharT
, _Traits
, _Alloc
>::_Rep
*
373 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::_Rep::
374 _S_create(size_type __capacity
, size_type __old_capacity
,
375 const _Alloc
& __alloc
)
377 // _GLIBCXX_RESOLVE_LIB_DEFECTS
378 // 83. String::npos vs. string::max_size()
379 if (__capacity
> size_type(_S_max_size
))
380 std::__throw_length_error(__N("__rc_string_base::_Rep::_S_create"));
382 // The standard places no restriction on allocating more memory
383 // than is strictly needed within this layer at the moment or as
384 // requested by an explicit application call to reserve().
386 // Many malloc implementations perform quite poorly when an
387 // application attempts to allocate memory in a stepwise fashion
388 // growing each allocation size by only 1 char. Additionally,
389 // it makes little sense to allocate less linear memory than the
390 // natural blocking size of the malloc implementation.
391 // Unfortunately, we would need a somewhat low-level calculation
392 // with tuned parameters to get this perfect for any particular
393 // malloc implementation. Fortunately, generalizations about
394 // common features seen among implementations seems to suffice.
396 // __pagesize need not match the actual VM page size for good
397 // results in practice, thus we pick a common value on the low
398 // side. __malloc_header_size is an estimate of the amount of
399 // overhead per memory allocation (in practice seen N * sizeof
400 // (void*) where N is 0, 2 or 4). According to folklore,
401 // picking this value on the high side is better than
402 // low-balling it (especially when this algorithm is used with
403 // malloc implementations that allocate memory blocks rounded up
404 // to a size which is a power of 2).
405 const size_type __pagesize
= 4096;
406 const size_type __malloc_header_size
= 4 * sizeof(void*);
408 // The below implements an exponential growth policy, necessary to
409 // meet amortized linear time requirements of the library: see
410 // http://gcc.gnu.org/ml/libstdc++/2001-07/msg00085.html.
411 if (__capacity
> __old_capacity
&& __capacity
< 2 * __old_capacity
)
413 __capacity
= 2 * __old_capacity
;
414 // Never allocate a string bigger than _S_max_size.
415 if (__capacity
> size_type(_S_max_size
))
416 __capacity
= size_type(_S_max_size
);
419 // NB: Need an array of char_type[__capacity], plus a terminating
420 // null char_type() element, plus enough for the _Rep data structure,
421 // plus sizeof(_Rep) - 1 to upper round to a size multiple of
423 // Whew. Seemingly so needy, yet so elemental.
424 size_type __size
= ((__capacity
+ 1) * sizeof(_CharT
)
425 + 2 * sizeof(_Rep
) - 1);
427 const size_type __adj_size
= __size
+ __malloc_header_size
;
428 if (__adj_size
> __pagesize
&& __capacity
> __old_capacity
)
430 const size_type __extra
= __pagesize
- __adj_size
% __pagesize
;
431 __capacity
+= __extra
/ sizeof(_CharT
);
432 if (__capacity
> size_type(_S_max_size
))
433 __capacity
= size_type(_S_max_size
);
434 __size
= (__capacity
+ 1) * sizeof(_CharT
) + 2 * sizeof(_Rep
) - 1;
437 // NB: Might throw, but no worries about a leak, mate: _Rep()
439 _Rep
* __place
= _Rep_alloc_type(__alloc
).allocate(__size
/ sizeof(_Rep
));
440 _Rep
* __p
= new (__place
) _Rep
;
441 __p
->_M_info
._M_capacity
= __capacity
;
445 template<typename _CharT
, typename _Traits
, typename _Alloc
>
447 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::_Rep::
448 _M_destroy(const _Alloc
& __a
) throw ()
450 const size_type __size
= ((_M_info
._M_capacity
+ 1) * sizeof(_CharT
)
451 + 2 * sizeof(_Rep
) - 1);
452 _Rep_alloc_type(__a
).deallocate(this, __size
/ sizeof(_Rep
));
455 template<typename _CharT
, typename _Traits
, typename _Alloc
>
457 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::_Rep::
458 _M_clone(const _Alloc
& __alloc
, size_type __res
)
460 // Requested capacity of the clone.
461 const size_type __requested_cap
= _M_info
._M_length
+ __res
;
462 _Rep
* __r
= _Rep::_S_create(__requested_cap
, _M_info
._M_capacity
,
465 if (_M_info
._M_length
)
466 __rc_string_base::_S_copy(__r
->_M_refdata(), _M_refdata(), _M_info
._M_length
);
468 __r
->_M_set_length(_M_info
._M_length
);
469 return __r
->_M_refdata();
472 template<typename _CharT
, typename _Traits
, typename _Alloc
>
473 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
474 __rc_string_base(const _Alloc
& __a
)
475 : _M_dataplus(__a
, _S_construct(size_type(), _CharT(), __a
)) { }
477 template<typename _CharT
, typename _Traits
, typename _Alloc
>
478 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
479 __rc_string_base(const __rc_string_base
& __rcs
)
480 : _M_dataplus(__rcs
._M_get_allocator(),
481 __rcs
._M_grab(__rcs
._M_get_allocator())) { }
483 template<typename _CharT
, typename _Traits
, typename _Alloc
>
484 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
485 __rc_string_base(size_type __n
, _CharT __c
, const _Alloc
& __a
)
486 : _M_dataplus(__a
, _S_construct(__n
, __c
, __a
)) { }
488 template<typename _CharT
, typename _Traits
, typename _Alloc
>
489 template<typename _InputIterator
>
490 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
491 __rc_string_base(_InputIterator __beg
, _InputIterator __end
,
493 : _M_dataplus(__a
, _S_construct(__beg
, __end
, __a
)) { }
495 template<typename _CharT
, typename _Traits
, typename _Alloc
>
497 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
505 // NB: This is the special case for Input Iterators, used in
506 // istreambuf_iterators, etc.
507 // Input Iterators have a cost structure very different from
508 // pointers, calling for a different coding style.
509 template<typename _CharT
, typename _Traits
, typename _Alloc
>
510 template<typename _InIterator
>
512 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
513 _S_construct(_InIterator __beg
, _InIterator __end
, const _Alloc
& __a
,
514 std::input_iterator_tag
)
516 if (__beg
== __end
&& __a
== _Alloc())
517 return _S_empty_rep
._M_refcopy();
519 // Avoid reallocation for common case.
522 while (__beg
!= __end
&& __len
< sizeof(__buf
) / sizeof(_CharT
))
524 __buf
[__len
++] = *__beg
;
527 _Rep
* __r
= _Rep::_S_create(__len
, size_type(0), __a
);
528 _S_copy(__r
->_M_refdata(), __buf
, __len
);
531 while (__beg
!= __end
)
533 if (__len
== __r
->_M_info
._M_capacity
)
535 // Allocate more space.
536 _Rep
* __another
= _Rep::_S_create(__len
+ 1, __len
, __a
);
537 _S_copy(__another
->_M_refdata(), __r
->_M_refdata(), __len
);
538 __r
->_M_destroy(__a
);
541 __r
->_M_refdata()[__len
++] = *__beg
;
547 __r
->_M_destroy(__a
);
548 __throw_exception_again
;
550 __r
->_M_set_length(__len
);
551 return __r
->_M_refdata();
554 template<typename _CharT
, typename _Traits
, typename _Alloc
>
555 template<typename _InIterator
>
557 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
558 _S_construct(_InIterator __beg
, _InIterator __end
, const _Alloc
& __a
,
559 std::forward_iterator_tag
)
561 if (__beg
== __end
&& __a
== _Alloc())
562 return _S_empty_rep
._M_refcopy();
564 // NB: Not required, but considered best practice.
565 if (__is_null_pointer(__beg
) && __beg
!= __end
)
566 std::__throw_logic_error(__N("__rc_string_base::"
567 "_S_construct null not valid"));
569 const size_type __dnew
= static_cast<size_type
>(std::distance(__beg
,
571 // Check for out_of_range and length_error exceptions.
572 _Rep
* __r
= _Rep::_S_create(__dnew
, size_type(0), __a
);
574 { __rc_string_base::_S_copy_chars(__r
->_M_refdata(), __beg
, __end
); }
577 __r
->_M_destroy(__a
);
578 __throw_exception_again
;
580 __r
->_M_set_length(__dnew
);
581 return __r
->_M_refdata();
584 template<typename _CharT
, typename _Traits
, typename _Alloc
>
586 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
587 _S_construct(size_type __n
, _CharT __c
, const _Alloc
& __a
)
589 if (__n
== 0 && __a
== _Alloc())
590 return _S_empty_rep
._M_refcopy();
592 // Check for out_of_range and length_error exceptions.
593 _Rep
* __r
= _Rep::_S_create(__n
, size_type(0), __a
);
595 __rc_string_base::_S_assign(__r
->_M_refdata(), __n
, __c
);
597 __r
->_M_set_length(__n
);
598 return __r
->_M_refdata();
601 template<typename _CharT
, typename _Traits
, typename _Alloc
>
603 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
604 _M_swap(__rc_string_base
& __rcs
)
608 if (__rcs
._M_is_leaked())
609 __rcs
._M_set_sharable();
611 _CharT
* __tmp
= _M_data();
612 _M_data(__rcs
._M_data());
613 __rcs
._M_data(__tmp
);
615 // _GLIBCXX_RESOLVE_LIB_DEFECTS
616 // 431. Swapping containers with unequal allocators.
617 std::__alloc_swap
<allocator_type
>::_S_do_it(_M_get_allocator(),
618 __rcs
._M_get_allocator());
621 template<typename _CharT
, typename _Traits
, typename _Alloc
>
623 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
624 _M_assign(const __rc_string_base
& __rcs
)
626 if (_M_rep() != __rcs
._M_rep())
628 _CharT
* __tmp
= __rcs
._M_grab(_M_get_allocator());
634 template<typename _CharT
, typename _Traits
, typename _Alloc
>
636 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
637 _M_reserve(size_type __res
)
639 // Make sure we don't shrink below the current size.
640 if (__res
< _M_length())
643 if (__res
!= _M_capacity() || _M_is_shared())
645 _CharT
* __tmp
= _M_rep()->_M_clone(_M_get_allocator(),
646 __res
- _M_length());
652 template<typename _CharT
, typename _Traits
, typename _Alloc
>
654 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
655 _M_mutate(size_type __pos
, size_type __len1
, const _CharT
* __s
,
658 const size_type __how_much
= _M_length() - __pos
- __len1
;
660 _Rep
* __r
= _Rep::_S_create(_M_length() + __len2
- __len1
,
661 _M_capacity(), _M_get_allocator());
664 this->_S_copy(__r
->_M_refdata(), _M_data(), __pos
);
666 this->_S_copy(__r
->_M_refdata() + __pos
, __s
, __len2
);
668 this->_S_copy(__r
->_M_refdata() + __pos
+ __len2
,
669 _M_data() + __pos
+ __len1
, __how_much
);
672 _M_data(__r
->_M_refdata());
675 template<typename _CharT
, typename _Traits
, typename _Alloc
>
677 __rc_string_base
<_CharT
, _Traits
, _Alloc
>::
678 _M_erase(size_type __pos
, size_type __n
)
680 const size_type __new_size
= _M_length() - __n
;
681 const size_type __how_much
= _M_length() - __pos
- __n
;
686 _Rep
* __r
= _Rep::_S_create(__new_size
, _M_capacity(),
690 this->_S_copy(__r
->_M_refdata(), _M_data(), __pos
);
692 this->_S_copy(__r
->_M_refdata() + __pos
,
693 _M_data() + __pos
+ __n
, __how_much
);
696 _M_data(__r
->_M_refdata());
698 else if (__how_much
&& __n
)
701 this->_S_move(_M_data() + __pos
,
702 _M_data() + __pos
+ __n
, __how_much
);
705 _M_rep()->_M_set_length(__new_size
);
710 __rc_string_base
<char, std::char_traits
<char>,
711 std::allocator
<char> >::
712 _M_compare(const __rc_string_base
& __rcs
) const
714 if (_M_rep() == __rcs
._M_rep())
719 #ifdef _GLIBCXX_USE_WCHAR_T
722 __rc_string_base
<wchar_t, std::char_traits
<wchar_t>,
723 std::allocator
<wchar_t> >::
724 _M_compare(const __rc_string_base
& __rcs
) const
726 if (_M_rep() == __rcs
._M_rep())
732 _GLIBCXX_END_NAMESPACE_VERSION
735 #endif /* _RC_STRING_BASE_H */