PK!4*4*8/backward/auto_ptr.hnu[// auto_ptr implementation -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file backward/auto_ptr.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _BACKWARD_AUTO_PTR_H #define _BACKWARD_AUTO_PTR_H 1 #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * A wrapper class to provide auto_ptr with reference semantics. * For example, an auto_ptr can be assigned (or constructed from) * the result of a function which returns an auto_ptr by value. * * All the auto_ptr_ref stuff should happen behind the scenes. */ template struct auto_ptr_ref { _Tp1* _M_ptr; explicit auto_ptr_ref(_Tp1* __p): _M_ptr(__p) { } } _GLIBCXX_DEPRECATED; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" /** * @brief A simple smart pointer providing strict ownership semantics. * * The Standard says: *
   *  An @c auto_ptr owns the object it holds a pointer to.  Copying
   *  an @c auto_ptr copies the pointer and transfers ownership to the
   *  destination.  If more than one @c auto_ptr owns the same object
   *  at the same time the behavior of the program is undefined.
   *
   *  The uses of @c auto_ptr include providing temporary
   *  exception-safety for dynamically allocated memory, passing
   *  ownership of dynamically allocated memory to a function, and
   *  returning dynamically allocated memory from a function.  @c
   *  auto_ptr does not meet the CopyConstructible and Assignable
   *  requirements for Standard Library container elements and thus
   *  instantiating a Standard Library container with an @c auto_ptr
   *  results in undefined behavior.
   *  
* Quoted from [20.4.5]/3. * * Good examples of what can and cannot be done with auto_ptr can * be found in the libstdc++ testsuite. * * _GLIBCXX_RESOLVE_LIB_DEFECTS * 127. auto_ptr<> conversion issues * These resolutions have all been incorporated. */ template class auto_ptr { private: _Tp* _M_ptr; public: /// The pointed-to type. typedef _Tp element_type; /** * @brief An %auto_ptr is usually constructed from a raw pointer. * @param __p A pointer (defaults to NULL). * * This object now @e owns the object pointed to by @a __p. */ explicit auto_ptr(element_type* __p = 0) throw() : _M_ptr(__p) { } /** * @brief An %auto_ptr can be constructed from another %auto_ptr. * @param __a Another %auto_ptr of the same type. * * This object now @e owns the object previously owned by @a __a, * which has given up ownership. */ auto_ptr(auto_ptr& __a) throw() : _M_ptr(__a.release()) { } /** * @brief An %auto_ptr can be constructed from another %auto_ptr. * @param __a Another %auto_ptr of a different but related type. * * A pointer-to-Tp1 must be convertible to a * pointer-to-Tp/element_type. * * This object now @e owns the object previously owned by @a __a, * which has given up ownership. */ template auto_ptr(auto_ptr<_Tp1>& __a) throw() : _M_ptr(__a.release()) { } /** * @brief %auto_ptr assignment operator. * @param __a Another %auto_ptr of the same type. * * This object now @e owns the object previously owned by @a __a, * which has given up ownership. The object that this one @e * used to own and track has been deleted. */ auto_ptr& operator=(auto_ptr& __a) throw() { reset(__a.release()); return *this; } /** * @brief %auto_ptr assignment operator. * @param __a Another %auto_ptr of a different but related type. * * A pointer-to-Tp1 must be convertible to a pointer-to-Tp/element_type. * * This object now @e owns the object previously owned by @a __a, * which has given up ownership. The object that this one @e * used to own and track has been deleted. */ template auto_ptr& operator=(auto_ptr<_Tp1>& __a) throw() { reset(__a.release()); return *this; } /** * When the %auto_ptr goes out of scope, the object it owns is * deleted. If it no longer owns anything (i.e., @c get() is * @c NULL), then this has no effect. * * The C++ standard says there is supposed to be an empty throw * specification here, but omitting it is standard conforming. Its * presence can be detected only if _Tp::~_Tp() throws, but this is * prohibited. [17.4.3.6]/2 */ ~auto_ptr() { delete _M_ptr; } /** * @brief Smart pointer dereferencing. * * If this %auto_ptr no longer owns anything, then this * operation will crash. (For a smart pointer, no longer owns * anything is the same as being a null pointer, and you know * what happens when you dereference one of those...) */ element_type& operator*() const throw() { __glibcxx_assert(_M_ptr != 0); return *_M_ptr; } /** * @brief Smart pointer dereferencing. * * This returns the pointer itself, which the language then will * automatically cause to be dereferenced. */ element_type* operator->() const throw() { __glibcxx_assert(_M_ptr != 0); return _M_ptr; } /** * @brief Bypassing the smart pointer. * @return The raw pointer being managed. * * You can get a copy of the pointer that this object owns, for * situations such as passing to a function which only accepts * a raw pointer. * * @note This %auto_ptr still owns the memory. */ element_type* get() const throw() { return _M_ptr; } /** * @brief Bypassing the smart pointer. * @return The raw pointer being managed. * * You can get a copy of the pointer that this object owns, for * situations such as passing to a function which only accepts * a raw pointer. * * @note This %auto_ptr no longer owns the memory. When this object * goes out of scope, nothing will happen. */ element_type* release() throw() { element_type* __tmp = _M_ptr; _M_ptr = 0; return __tmp; } /** * @brief Forcibly deletes the managed object. * @param __p A pointer (defaults to NULL). * * This object now @e owns the object pointed to by @a __p. The * previous object has been deleted. */ void reset(element_type* __p = 0) throw() { if (__p != _M_ptr) { delete _M_ptr; _M_ptr = __p; } } /** * @brief Automatic conversions * * These operations are supposed to convert an %auto_ptr into and from * an auto_ptr_ref automatically as needed. This would allow * constructs such as * @code * auto_ptr func_returning_auto_ptr(.....); * ... * auto_ptr ptr = func_returning_auto_ptr(.....); * @endcode * * But it doesn't work, and won't be fixed. For further details see * http://cplusplus.github.io/LWG/lwg-closed.html#463 */ auto_ptr(auto_ptr_ref __ref) throw() : _M_ptr(__ref._M_ptr) { } auto_ptr& operator=(auto_ptr_ref __ref) throw() { if (__ref._M_ptr != this->get()) { delete _M_ptr; _M_ptr = __ref._M_ptr; } return *this; } template operator auto_ptr_ref<_Tp1>() throw() { return auto_ptr_ref<_Tp1>(this->release()); } template operator auto_ptr<_Tp1>() throw() { return auto_ptr<_Tp1>(this->release()); } } _GLIBCXX_DEPRECATED; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 541. shared_ptr template assignment and void template<> class auto_ptr { public: typedef void element_type; } _GLIBCXX_DEPRECATED; #if __cplusplus >= 201103L template<_Lock_policy _Lp> template inline __shared_count<_Lp>::__shared_count(std::auto_ptr<_Tp>&& __r) : _M_pi(new _Sp_counted_ptr<_Tp*, _Lp>(__r.get())) { __r.release(); } template template inline __shared_ptr<_Tp, _Lp>::__shared_ptr(std::auto_ptr<_Tp1>&& __r) : _M_ptr(__r.get()), _M_refcount() { __glibcxx_function_requires(_ConvertibleConcept<_Tp1*, _Tp*>) static_assert( sizeof(_Tp1) > 0, "incomplete type" ); _Tp1* __tmp = __r.get(); _M_refcount = __shared_count<_Lp>(std::move(__r)); _M_enable_shared_from_this_with(__tmp); } template template inline shared_ptr<_Tp>::shared_ptr(std::auto_ptr<_Tp1>&& __r) : __shared_ptr<_Tp>(std::move(__r)) { } template template inline unique_ptr<_Tp, _Dp>::unique_ptr(auto_ptr<_Up>&& __u) noexcept : _M_t(__u.release(), deleter_type()) { } #endif #pragma GCC diagnostic pop _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _BACKWARD_AUTO_PTR_H */ PK!&A 8/backward/backward_warning.hnu[// Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file backward/backward_warning.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iosfwd} */ #ifndef _BACKWARD_BACKWARD_WARNING_H #define _BACKWARD_BACKWARD_WARNING_H 1 #ifdef __DEPRECATED #warning \ This file includes at least one deprecated or antiquated header which \ may be removed without further notice at a future date. Please use a \ non-deprecated interface with equivalent functionality instead. For a \ listing of replacement headers and interfaces, consult the file \ backward_warning.h. To disable this warning use -Wno-deprecated. /* A list of valid replacements is as follows: Use: Instead of: , basic_stringbuf , strstreambuf , basic_istringstream , istrstream , basic_ostringstream , ostrstream , basic_stringstream , strstream , unordered_set , hash_set , unordered_multiset , hash_multiset , unordered_map , hash_map , unordered_multimap , hash_multimap , bind , binder1st , bind , binder2nd , bind , bind1st , bind , bind2nd , unique_ptr , auto_ptr */ #endif #endif PK!Ioξ8/backward/binders.hnu[// Functor implementations -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996-1998 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file backward/binders.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{functional} */ #ifndef _BACKWARD_BINDERS_H #define _BACKWARD_BINDERS_H 1 // Suppress deprecated warning for this file. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // 20.3.6 binders /** @defgroup binders Binder Classes * @ingroup functors * * Binders turn functions/functors with two arguments into functors * with a single argument, storing an argument to be applied later. * For example, a variable @c B of type @c binder1st is constructed * from a functor @c f and an argument @c x. Later, B's @c * operator() is called with a single argument @c y. The return * value is the value of @c f(x,y). @c B can be @a called with * various arguments (y1, y2, ...) and will in turn call @c * f(x,y1), @c f(x,y2), ... * * The function @c bind1st is provided to save some typing. It takes the * function and an argument as parameters, and returns an instance of * @c binder1st. * * The type @c binder2nd and its creator function @c bind2nd do the same * thing, but the stored argument is passed as the second parameter instead * of the first, e.g., @c bind2nd(std::minus(),1.3) will create a * functor whose @c operator() accepts a floating-point number, subtracts * 1.3 from it, and returns the result. (If @c bind1st had been used, * the functor would perform 1.3 - x instead. * * Creator-wrapper functions like @c bind1st are intended to be used in * calling algorithms. Their return values will be temporary objects. * (The goal is to not require you to type names like * @c std::binder1st> for declaring a variable to hold the * return value from @c bind1st(std::plus(),5). * * These become more useful when combined with the composition functions. * * These functions are deprecated in C++11 and can be replaced by * @c std::bind (or @c std::tr1::bind) which is more powerful and flexible, * supporting functions with any number of arguments. Uses of @c bind1st * can be replaced by @c std::bind(f, x, std::placeholders::_1) and * @c bind2nd by @c std::bind(f, std::placeholders::_1, x). * @{ */ /// One of the @link binders binder functors@endlink. template class binder1st : public unary_function { protected: _Operation op; typename _Operation::first_argument_type value; public: binder1st(const _Operation& __x, const typename _Operation::first_argument_type& __y) : op(__x), value(__y) { } typename _Operation::result_type operator()(const typename _Operation::second_argument_type& __x) const { return op(value, __x); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 109. Missing binders for non-const sequence elements typename _Operation::result_type operator()(typename _Operation::second_argument_type& __x) const { return op(value, __x); } } _GLIBCXX_DEPRECATED; /// One of the @link binders binder functors@endlink. template inline binder1st<_Operation> bind1st(const _Operation& __fn, const _Tp& __x) { typedef typename _Operation::first_argument_type _Arg1_type; return binder1st<_Operation>(__fn, _Arg1_type(__x)); } /// One of the @link binders binder functors@endlink. template class binder2nd : public unary_function { protected: _Operation op; typename _Operation::second_argument_type value; public: binder2nd(const _Operation& __x, const typename _Operation::second_argument_type& __y) : op(__x), value(__y) { } typename _Operation::result_type operator()(const typename _Operation::first_argument_type& __x) const { return op(__x, value); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 109. Missing binders for non-const sequence elements typename _Operation::result_type operator()(typename _Operation::first_argument_type& __x) const { return op(__x, value); } } _GLIBCXX_DEPRECATED; /// One of the @link binders binder functors@endlink. template inline binder2nd<_Operation> bind2nd(const _Operation& __fn, const _Tp& __x) { typedef typename _Operation::second_argument_type _Arg2_type; return binder2nd<_Operation>(__fn, _Arg2_type(__x)); } /** @} */ _GLIBCXX_END_NAMESPACE_VERSION } // namespace #pragma GCC diagnostic pop #endif /* _BACKWARD_BINDERS_H */ PK!4q$8/backward/hash_fun.hnu[// 'struct hash' from SGI -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * Copyright (c) 1996-1998 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * */ /** @file backward/hash_fun.h * This file is a GNU extension to the Standard C++ Library (possibly * containing extensions from the HP/SGI STL subset). */ #ifndef _BACKWARD_HASH_FUN_H #define _BACKWARD_HASH_FUN_H 1 #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using std::size_t; template struct hash { }; inline size_t __stl_hash_string(const char* __s) { unsigned long __h = 0; for ( ; *__s; ++__s) __h = 5 * __h + *__s; return size_t(__h); } template<> struct hash { size_t operator()(const char* __s) const { return __stl_hash_string(__s); } }; template<> struct hash { size_t operator()(const char* __s) const { return __stl_hash_string(__s); } }; template<> struct hash { size_t operator()(char __x) const { return __x; } }; template<> struct hash { size_t operator()(unsigned char __x) const { return __x; } }; template<> struct hash { size_t operator()(unsigned char __x) const { return __x; } }; template<> struct hash { size_t operator()(short __x) const { return __x; } }; template<> struct hash { size_t operator()(unsigned short __x) const { return __x; } }; template<> struct hash { size_t operator()(int __x) const { return __x; } }; template<> struct hash { size_t operator()(unsigned int __x) const { return __x; } }; template<> struct hash { size_t operator()(long __x) const { return __x; } }; template<> struct hash { size_t operator()(unsigned long __x) const { return __x; } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!oEoE8/backward/hash_mapnu[// Hashing map implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * */ /** @file backward/hash_map * This file is a GNU extension to the Standard C++ Library (possibly * containing extensions from the HP/SGI STL subset). */ #ifndef _BACKWARD_HASH_MAP #define _BACKWARD_HASH_MAP 1 #ifndef _GLIBCXX_PERMIT_BACKWARD_HASH #include "backward_warning.h" #endif #include #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using std::equal_to; using std::allocator; using std::pair; using std::_Select1st; /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template, class _EqualKey = equal_to<_Key>, class _Alloc = allocator<_Tp> > class hash_map { private: typedef hashtable,_Key, _HashFn, _Select1st >, _EqualKey, _Alloc> _Ht; _Ht _M_ht; public: typedef typename _Ht::key_type key_type; typedef _Tp data_type; typedef _Tp mapped_type; typedef typename _Ht::value_type value_type; typedef typename _Ht::hasher hasher; typedef typename _Ht::key_equal key_equal; typedef typename _Ht::size_type size_type; typedef typename _Ht::difference_type difference_type; typedef typename _Ht::pointer pointer; typedef typename _Ht::const_pointer const_pointer; typedef typename _Ht::reference reference; typedef typename _Ht::const_reference const_reference; typedef typename _Ht::iterator iterator; typedef typename _Ht::const_iterator const_iterator; typedef typename _Ht::allocator_type allocator_type; hasher hash_funct() const { return _M_ht.hash_funct(); } key_equal key_eq() const { return _M_ht.key_eq(); } allocator_type get_allocator() const { return _M_ht.get_allocator(); } hash_map() : _M_ht(100, hasher(), key_equal(), allocator_type()) {} explicit hash_map(size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) {} hash_map(size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) {} hash_map(size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) {} template hash_map(_InputIterator __f, _InputIterator __l) : _M_ht(100, hasher(), key_equal(), allocator_type()) { _M_ht.insert_unique(__f, __l); } template hash_map(_InputIterator __f, _InputIterator __l, size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) { _M_ht.insert_unique(__f, __l); } template hash_map(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) { _M_ht.insert_unique(__f, __l); } template hash_map(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) { _M_ht.insert_unique(__f, __l); } size_type size() const { return _M_ht.size(); } size_type max_size() const { return _M_ht.max_size(); } bool empty() const { return _M_ht.empty(); } void swap(hash_map& __hs) { _M_ht.swap(__hs._M_ht); } template friend bool operator== (const hash_map<_K1, _T1, _HF, _EqK, _Al>&, const hash_map<_K1, _T1, _HF, _EqK, _Al>&); iterator begin() { return _M_ht.begin(); } iterator end() { return _M_ht.end(); } const_iterator begin() const { return _M_ht.begin(); } const_iterator end() const { return _M_ht.end(); } pair insert(const value_type& __obj) { return _M_ht.insert_unique(__obj); } template void insert(_InputIterator __f, _InputIterator __l) { _M_ht.insert_unique(__f, __l); } pair insert_noresize(const value_type& __obj) { return _M_ht.insert_unique_noresize(__obj); } iterator find(const key_type& __key) { return _M_ht.find(__key); } const_iterator find(const key_type& __key) const { return _M_ht.find(__key); } _Tp& operator[](const key_type& __key) { return _M_ht.find_or_insert(value_type(__key, _Tp())).second; } size_type count(const key_type& __key) const { return _M_ht.count(__key); } pair equal_range(const key_type& __key) { return _M_ht.equal_range(__key); } pair equal_range(const key_type& __key) const { return _M_ht.equal_range(__key); } size_type erase(const key_type& __key) {return _M_ht.erase(__key); } void erase(iterator __it) { _M_ht.erase(__it); } void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); } void clear() { _M_ht.clear(); } void resize(size_type __hint) { _M_ht.resize(__hint); } size_type bucket_count() const { return _M_ht.bucket_count(); } size_type max_bucket_count() const { return _M_ht.max_bucket_count(); } size_type elems_in_bucket(size_type __n) const { return _M_ht.elems_in_bucket(__n); } }; template inline bool operator==(const hash_map<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm1, const hash_map<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm2) { return __hm1._M_ht == __hm2._M_ht; } template inline bool operator!=(const hash_map<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm1, const hash_map<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm2) { return !(__hm1 == __hm2); } template inline void swap(hash_map<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm1, hash_map<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm2) { __hm1.swap(__hm2); } /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template, class _EqualKey = equal_to<_Key>, class _Alloc = allocator<_Tp> > class hash_multimap { // concept requirements __glibcxx_class_requires(_Key, _SGIAssignableConcept) __glibcxx_class_requires(_Tp, _SGIAssignableConcept) __glibcxx_class_requires3(_HashFn, size_t, _Key, _UnaryFunctionConcept) __glibcxx_class_requires3(_EqualKey, _Key, _Key, _BinaryPredicateConcept) private: typedef hashtable, _Key, _HashFn, _Select1st >, _EqualKey, _Alloc> _Ht; _Ht _M_ht; public: typedef typename _Ht::key_type key_type; typedef _Tp data_type; typedef _Tp mapped_type; typedef typename _Ht::value_type value_type; typedef typename _Ht::hasher hasher; typedef typename _Ht::key_equal key_equal; typedef typename _Ht::size_type size_type; typedef typename _Ht::difference_type difference_type; typedef typename _Ht::pointer pointer; typedef typename _Ht::const_pointer const_pointer; typedef typename _Ht::reference reference; typedef typename _Ht::const_reference const_reference; typedef typename _Ht::iterator iterator; typedef typename _Ht::const_iterator const_iterator; typedef typename _Ht::allocator_type allocator_type; hasher hash_funct() const { return _M_ht.hash_funct(); } key_equal key_eq() const { return _M_ht.key_eq(); } allocator_type get_allocator() const { return _M_ht.get_allocator(); } hash_multimap() : _M_ht(100, hasher(), key_equal(), allocator_type()) {} explicit hash_multimap(size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) {} hash_multimap(size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) {} hash_multimap(size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) {} template hash_multimap(_InputIterator __f, _InputIterator __l) : _M_ht(100, hasher(), key_equal(), allocator_type()) { _M_ht.insert_equal(__f, __l); } template hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) { _M_ht.insert_equal(__f, __l); } template hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) { _M_ht.insert_equal(__f, __l); } template hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) { _M_ht.insert_equal(__f, __l); } size_type size() const { return _M_ht.size(); } size_type max_size() const { return _M_ht.max_size(); } bool empty() const { return _M_ht.empty(); } void swap(hash_multimap& __hs) { _M_ht.swap(__hs._M_ht); } template friend bool operator==(const hash_multimap<_K1, _T1, _HF, _EqK, _Al>&, const hash_multimap<_K1, _T1, _HF, _EqK, _Al>&); iterator begin() { return _M_ht.begin(); } iterator end() { return _M_ht.end(); } const_iterator begin() const { return _M_ht.begin(); } const_iterator end() const { return _M_ht.end(); } iterator insert(const value_type& __obj) { return _M_ht.insert_equal(__obj); } template void insert(_InputIterator __f, _InputIterator __l) { _M_ht.insert_equal(__f,__l); } iterator insert_noresize(const value_type& __obj) { return _M_ht.insert_equal_noresize(__obj); } iterator find(const key_type& __key) { return _M_ht.find(__key); } const_iterator find(const key_type& __key) const { return _M_ht.find(__key); } size_type count(const key_type& __key) const { return _M_ht.count(__key); } pair equal_range(const key_type& __key) { return _M_ht.equal_range(__key); } pair equal_range(const key_type& __key) const { return _M_ht.equal_range(__key); } size_type erase(const key_type& __key) { return _M_ht.erase(__key); } void erase(iterator __it) { _M_ht.erase(__it); } void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); } void clear() { _M_ht.clear(); } void resize(size_type __hint) { _M_ht.resize(__hint); } size_type bucket_count() const { return _M_ht.bucket_count(); } size_type max_bucket_count() const { return _M_ht.max_bucket_count(); } size_type elems_in_bucket(size_type __n) const { return _M_ht.elems_in_bucket(__n); } }; template inline bool operator==(const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm1, const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm2) { return __hm1._M_ht == __hm2._M_ht; } template inline bool operator!=(const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm1, const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm2) { return !(__hm1 == __hm2); } template inline void swap(hash_multimap<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm1, hash_multimap<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm2) { __hm1.swap(__hm2); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Specialization of insert_iterator so that it will work for hash_map // and hash_multimap. template class insert_iterator<__gnu_cxx::hash_map<_Key, _Tp, _HashFn, _EqKey, _Alloc> > { protected: typedef __gnu_cxx::hash_map<_Key, _Tp, _HashFn, _EqKey, _Alloc> _Container; _Container* container; public: typedef _Container container_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; insert_iterator(_Container& __x) : container(&__x) {} insert_iterator(_Container& __x, typename _Container::iterator) : container(&__x) {} insert_iterator<_Container>& operator=(const typename _Container::value_type& __value) { container->insert(__value); return *this; } insert_iterator<_Container>& operator*() { return *this; } insert_iterator<_Container>& operator++() { return *this; } insert_iterator<_Container>& operator++(int) { return *this; } }; template class insert_iterator<__gnu_cxx::hash_multimap<_Key, _Tp, _HashFn, _EqKey, _Alloc> > { protected: typedef __gnu_cxx::hash_multimap<_Key, _Tp, _HashFn, _EqKey, _Alloc> _Container; _Container* container; typename _Container::iterator iter; public: typedef _Container container_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; insert_iterator(_Container& __x) : container(&__x) {} insert_iterator(_Container& __x, typename _Container::iterator) : container(&__x) {} insert_iterator<_Container>& operator=(const typename _Container::value_type& __value) { container->insert(__value); return *this; } insert_iterator<_Container>& operator*() { return *this; } insert_iterator<_Container>& operator++() { return *this; } insert_iterator<_Container>& operator++(int) { return *this; } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!+C+C8/backward/hash_setnu[// Hashing set implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * */ /** @file backward/hash_set * This file is a GNU extension to the Standard C++ Library (possibly * containing extensions from the HP/SGI STL subset). */ #ifndef _BACKWARD_HASH_SET #define _BACKWARD_HASH_SET 1 #ifndef _GLIBCXX_PERMIT_BACKWARD_HASH #include "backward_warning.h" #endif #include #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using std::equal_to; using std::allocator; using std::pair; using std::_Identity; /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template, class _EqualKey = equal_to<_Value>, class _Alloc = allocator<_Value> > class hash_set { // concept requirements __glibcxx_class_requires(_Value, _SGIAssignableConcept) __glibcxx_class_requires3(_HashFcn, size_t, _Value, _UnaryFunctionConcept) __glibcxx_class_requires3(_EqualKey, _Value, _Value, _BinaryPredicateConcept) private: typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>, _EqualKey, _Alloc> _Ht; _Ht _M_ht; public: typedef typename _Ht::key_type key_type; typedef typename _Ht::value_type value_type; typedef typename _Ht::hasher hasher; typedef typename _Ht::key_equal key_equal; typedef typename _Ht::size_type size_type; typedef typename _Ht::difference_type difference_type; typedef typename _Alloc::pointer pointer; typedef typename _Alloc::const_pointer const_pointer; typedef typename _Alloc::reference reference; typedef typename _Alloc::const_reference const_reference; typedef typename _Ht::const_iterator iterator; typedef typename _Ht::const_iterator const_iterator; typedef typename _Ht::allocator_type allocator_type; hasher hash_funct() const { return _M_ht.hash_funct(); } key_equal key_eq() const { return _M_ht.key_eq(); } allocator_type get_allocator() const { return _M_ht.get_allocator(); } hash_set() : _M_ht(100, hasher(), key_equal(), allocator_type()) {} explicit hash_set(size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) {} hash_set(size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) {} hash_set(size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) {} template hash_set(_InputIterator __f, _InputIterator __l) : _M_ht(100, hasher(), key_equal(), allocator_type()) { _M_ht.insert_unique(__f, __l); } template hash_set(_InputIterator __f, _InputIterator __l, size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) { _M_ht.insert_unique(__f, __l); } template hash_set(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) { _M_ht.insert_unique(__f, __l); } template hash_set(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) { _M_ht.insert_unique(__f, __l); } size_type size() const { return _M_ht.size(); } size_type max_size() const { return _M_ht.max_size(); } bool empty() const { return _M_ht.empty(); } void swap(hash_set& __hs) { _M_ht.swap(__hs._M_ht); } template friend bool operator==(const hash_set<_Val, _HF, _EqK, _Al>&, const hash_set<_Val, _HF, _EqK, _Al>&); iterator begin() const { return _M_ht.begin(); } iterator end() const { return _M_ht.end(); } pair insert(const value_type& __obj) { pair __p = _M_ht.insert_unique(__obj); return pair(__p.first, __p.second); } template void insert(_InputIterator __f, _InputIterator __l) { _M_ht.insert_unique(__f, __l); } pair insert_noresize(const value_type& __obj) { pair __p = _M_ht.insert_unique_noresize(__obj); return pair(__p.first, __p.second); } iterator find(const key_type& __key) const { return _M_ht.find(__key); } size_type count(const key_type& __key) const { return _M_ht.count(__key); } pair equal_range(const key_type& __key) const { return _M_ht.equal_range(__key); } size_type erase(const key_type& __key) {return _M_ht.erase(__key); } void erase(iterator __it) { _M_ht.erase(__it); } void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); } void clear() { _M_ht.clear(); } void resize(size_type __hint) { _M_ht.resize(__hint); } size_type bucket_count() const { return _M_ht.bucket_count(); } size_type max_bucket_count() const { return _M_ht.max_bucket_count(); } size_type elems_in_bucket(size_type __n) const { return _M_ht.elems_in_bucket(__n); } }; template inline bool operator==(const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs1, const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs2) { return __hs1._M_ht == __hs2._M_ht; } template inline bool operator!=(const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs1, const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs2) { return !(__hs1 == __hs2); } template inline void swap(hash_set<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1, hash_set<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2) { __hs1.swap(__hs2); } /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template, class _EqualKey = equal_to<_Value>, class _Alloc = allocator<_Value> > class hash_multiset { // concept requirements __glibcxx_class_requires(_Value, _SGIAssignableConcept) __glibcxx_class_requires3(_HashFcn, size_t, _Value, _UnaryFunctionConcept) __glibcxx_class_requires3(_EqualKey, _Value, _Value, _BinaryPredicateConcept) private: typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>, _EqualKey, _Alloc> _Ht; _Ht _M_ht; public: typedef typename _Ht::key_type key_type; typedef typename _Ht::value_type value_type; typedef typename _Ht::hasher hasher; typedef typename _Ht::key_equal key_equal; typedef typename _Ht::size_type size_type; typedef typename _Ht::difference_type difference_type; typedef typename _Alloc::pointer pointer; typedef typename _Alloc::const_pointer const_pointer; typedef typename _Alloc::reference reference; typedef typename _Alloc::const_reference const_reference; typedef typename _Ht::const_iterator iterator; typedef typename _Ht::const_iterator const_iterator; typedef typename _Ht::allocator_type allocator_type; hasher hash_funct() const { return _M_ht.hash_funct(); } key_equal key_eq() const { return _M_ht.key_eq(); } allocator_type get_allocator() const { return _M_ht.get_allocator(); } hash_multiset() : _M_ht(100, hasher(), key_equal(), allocator_type()) {} explicit hash_multiset(size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) {} hash_multiset(size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) {} hash_multiset(size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) {} template hash_multiset(_InputIterator __f, _InputIterator __l) : _M_ht(100, hasher(), key_equal(), allocator_type()) { _M_ht.insert_equal(__f, __l); } template hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) { _M_ht.insert_equal(__f, __l); } template hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) { _M_ht.insert_equal(__f, __l); } template hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) { _M_ht.insert_equal(__f, __l); } size_type size() const { return _M_ht.size(); } size_type max_size() const { return _M_ht.max_size(); } bool empty() const { return _M_ht.empty(); } void swap(hash_multiset& hs) { _M_ht.swap(hs._M_ht); } template friend bool operator==(const hash_multiset<_Val, _HF, _EqK, _Al>&, const hash_multiset<_Val, _HF, _EqK, _Al>&); iterator begin() const { return _M_ht.begin(); } iterator end() const { return _M_ht.end(); } iterator insert(const value_type& __obj) { return _M_ht.insert_equal(__obj); } template void insert(_InputIterator __f, _InputIterator __l) { _M_ht.insert_equal(__f,__l); } iterator insert_noresize(const value_type& __obj) { return _M_ht.insert_equal_noresize(__obj); } iterator find(const key_type& __key) const { return _M_ht.find(__key); } size_type count(const key_type& __key) const { return _M_ht.count(__key); } pair equal_range(const key_type& __key) const { return _M_ht.equal_range(__key); } size_type erase(const key_type& __key) { return _M_ht.erase(__key); } void erase(iterator __it) { _M_ht.erase(__it); } void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); } void clear() { _M_ht.clear(); } void resize(size_type __hint) { _M_ht.resize(__hint); } size_type bucket_count() const { return _M_ht.bucket_count(); } size_type max_bucket_count() const { return _M_ht.max_bucket_count(); } size_type elems_in_bucket(size_type __n) const { return _M_ht.elems_in_bucket(__n); } }; template inline bool operator==(const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1, const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2) { return __hs1._M_ht == __hs2._M_ht; } template inline bool operator!=(const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1, const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2) { return !(__hs1 == __hs2); } template inline void swap(hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1, hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2) { __hs1.swap(__hs2); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Specialization of insert_iterator so that it will work for hash_set // and hash_multiset. template class insert_iterator<__gnu_cxx::hash_set<_Value, _HashFcn, _EqualKey, _Alloc> > { protected: typedef __gnu_cxx::hash_set<_Value, _HashFcn, _EqualKey, _Alloc> _Container; _Container* container; public: typedef _Container container_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; insert_iterator(_Container& __x) : container(&__x) {} insert_iterator(_Container& __x, typename _Container::iterator) : container(&__x) {} insert_iterator<_Container>& operator=(const typename _Container::value_type& __value) { container->insert(__value); return *this; } insert_iterator<_Container>& operator*() { return *this; } insert_iterator<_Container>& operator++() { return *this; } insert_iterator<_Container>& operator++(int) { return *this; } }; template class insert_iterator<__gnu_cxx::hash_multiset<_Value, _HashFcn, _EqualKey, _Alloc> > { protected: typedef __gnu_cxx::hash_multiset<_Value, _HashFcn, _EqualKey, _Alloc> _Container; _Container* container; typename _Container::iterator iter; public: typedef _Container container_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; insert_iterator(_Container& __x) : container(&__x) {} insert_iterator(_Container& __x, typename _Container::iterator) : container(&__x) {} insert_iterator<_Container>& operator=(const typename _Container::value_type& __value) { container->insert(__value); return *this; } insert_iterator<_Container>& operator*() { return *this; } insert_iterator<_Container>& operator++() { return *this; } insert_iterator<_Container>& operator++(int) { return *this; } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!qL̺8/backward/hashtable.hnu[// Hashtable implementation used by containers -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * */ /** @file backward/hashtable.h * This file is a GNU extension to the Standard C++ Library (possibly * containing extensions from the HP/SGI STL subset). */ #ifndef _BACKWARD_HASHTABLE_H #define _BACKWARD_HASHTABLE_H 1 // Hashtable class, used to implement the hashed associative containers // hash_set, hash_map, hash_multiset, and hash_multimap. #include #include #include #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using std::size_t; using std::ptrdiff_t; using std::forward_iterator_tag; using std::input_iterator_tag; using std::_Construct; using std::_Destroy; using std::distance; using std::vector; using std::pair; using std::__iterator_category; template struct _Hashtable_node { _Hashtable_node* _M_next; _Val _M_val; }; template > class hashtable; template struct _Hashtable_iterator; template struct _Hashtable_const_iterator; template struct _Hashtable_iterator { typedef hashtable<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc> _Hashtable; typedef _Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc> iterator; typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc> const_iterator; typedef _Hashtable_node<_Val> _Node; typedef forward_iterator_tag iterator_category; typedef _Val value_type; typedef ptrdiff_t difference_type; typedef size_t size_type; typedef _Val& reference; typedef _Val* pointer; _Node* _M_cur; _Hashtable* _M_ht; _Hashtable_iterator(_Node* __n, _Hashtable* __tab) : _M_cur(__n), _M_ht(__tab) { } _Hashtable_iterator() { } reference operator*() const { return _M_cur->_M_val; } pointer operator->() const { return &(operator*()); } iterator& operator++(); iterator operator++(int); bool operator==(const iterator& __it) const { return _M_cur == __it._M_cur; } bool operator!=(const iterator& __it) const { return _M_cur != __it._M_cur; } }; template struct _Hashtable_const_iterator { typedef hashtable<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc> _Hashtable; typedef _Hashtable_iterator<_Val,_Key,_HashFcn, _ExtractKey,_EqualKey,_Alloc> iterator; typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc> const_iterator; typedef _Hashtable_node<_Val> _Node; typedef forward_iterator_tag iterator_category; typedef _Val value_type; typedef ptrdiff_t difference_type; typedef size_t size_type; typedef const _Val& reference; typedef const _Val* pointer; const _Node* _M_cur; const _Hashtable* _M_ht; _Hashtable_const_iterator(const _Node* __n, const _Hashtable* __tab) : _M_cur(__n), _M_ht(__tab) { } _Hashtable_const_iterator() { } _Hashtable_const_iterator(const iterator& __it) : _M_cur(__it._M_cur), _M_ht(__it._M_ht) { } reference operator*() const { return _M_cur->_M_val; } pointer operator->() const { return &(operator*()); } const_iterator& operator++(); const_iterator operator++(int); bool operator==(const const_iterator& __it) const { return _M_cur == __it._M_cur; } bool operator!=(const const_iterator& __it) const { return _M_cur != __it._M_cur; } }; // Note: assumes long is at least 32 bits. enum { _S_num_primes = 29 }; template struct _Hashtable_prime_list { static const _PrimeType __stl_prime_list[_S_num_primes]; static const _PrimeType* _S_get_prime_list(); }; template const _PrimeType _Hashtable_prime_list<_PrimeType>::__stl_prime_list[_S_num_primes] = { 5ul, 53ul, 97ul, 193ul, 389ul, 769ul, 1543ul, 3079ul, 6151ul, 12289ul, 24593ul, 49157ul, 98317ul, 196613ul, 393241ul, 786433ul, 1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul, 50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul, 1610612741ul, 3221225473ul, 4294967291ul }; template inline const _PrimeType* _Hashtable_prime_list<_PrimeType>::_S_get_prime_list() { return __stl_prime_list; } inline unsigned long __stl_next_prime(unsigned long __n) { const unsigned long* __first = _Hashtable_prime_list::_S_get_prime_list(); const unsigned long* __last = __first + (int)_S_num_primes; const unsigned long* pos = std::lower_bound(__first, __last, __n); return pos == __last ? *(__last - 1) : *pos; } // Forward declaration of operator==. template class hashtable; template bool operator==(const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht1, const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht2); // Hashtables handle allocators a bit differently than other // containers do. If we're using standard-conforming allocators, then // a hashtable unconditionally has a member variable to hold its // allocator, even if it so happens that all instances of the // allocator type are identical. This is because, for hashtables, // this extra storage is negligible. Additionally, a base class // wouldn't serve any other purposes; it wouldn't, for example, // simplify the exception-handling code. template class hashtable { public: typedef _Key key_type; typedef _Val value_type; typedef _HashFcn hasher; typedef _EqualKey key_equal; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; hasher hash_funct() const { return _M_hash; } key_equal key_eq() const { return _M_equals; } private: typedef _Hashtable_node<_Val> _Node; public: typedef typename _Alloc::template rebind::other allocator_type; allocator_type get_allocator() const { return _M_node_allocator; } private: typedef typename _Alloc::template rebind<_Node>::other _Node_Alloc; typedef typename _Alloc::template rebind<_Node*>::other _Nodeptr_Alloc; typedef vector<_Node*, _Nodeptr_Alloc> _Vector_type; _Node_Alloc _M_node_allocator; _Node* _M_get_node() { return _M_node_allocator.allocate(1); } void _M_put_node(_Node* __p) { _M_node_allocator.deallocate(__p, 1); } private: hasher _M_hash; key_equal _M_equals; _ExtractKey _M_get_key; _Vector_type _M_buckets; size_type _M_num_elements; public: typedef _Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc> iterator; typedef _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc> const_iterator; friend struct _Hashtable_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc>; friend struct _Hashtable_const_iterator<_Val, _Key, _HashFcn, _ExtractKey, _EqualKey, _Alloc>; public: hashtable(size_type __n, const _HashFcn& __hf, const _EqualKey& __eql, const _ExtractKey& __ext, const allocator_type& __a = allocator_type()) : _M_node_allocator(__a), _M_hash(__hf), _M_equals(__eql), _M_get_key(__ext), _M_buckets(__a), _M_num_elements(0) { _M_initialize_buckets(__n); } hashtable(size_type __n, const _HashFcn& __hf, const _EqualKey& __eql, const allocator_type& __a = allocator_type()) : _M_node_allocator(__a), _M_hash(__hf), _M_equals(__eql), _M_get_key(_ExtractKey()), _M_buckets(__a), _M_num_elements(0) { _M_initialize_buckets(__n); } hashtable(const hashtable& __ht) : _M_node_allocator(__ht.get_allocator()), _M_hash(__ht._M_hash), _M_equals(__ht._M_equals), _M_get_key(__ht._M_get_key), _M_buckets(__ht.get_allocator()), _M_num_elements(0) { _M_copy_from(__ht); } hashtable& operator= (const hashtable& __ht) { if (&__ht != this) { clear(); _M_hash = __ht._M_hash; _M_equals = __ht._M_equals; _M_get_key = __ht._M_get_key; _M_copy_from(__ht); } return *this; } ~hashtable() { clear(); } size_type size() const { return _M_num_elements; } size_type max_size() const { return size_type(-1); } bool empty() const { return size() == 0; } void swap(hashtable& __ht) { std::swap(_M_hash, __ht._M_hash); std::swap(_M_equals, __ht._M_equals); std::swap(_M_get_key, __ht._M_get_key); _M_buckets.swap(__ht._M_buckets); std::swap(_M_num_elements, __ht._M_num_elements); } iterator begin() { for (size_type __n = 0; __n < _M_buckets.size(); ++__n) if (_M_buckets[__n]) return iterator(_M_buckets[__n], this); return end(); } iterator end() { return iterator(0, this); } const_iterator begin() const { for (size_type __n = 0; __n < _M_buckets.size(); ++__n) if (_M_buckets[__n]) return const_iterator(_M_buckets[__n], this); return end(); } const_iterator end() const { return const_iterator(0, this); } template friend bool operator==(const hashtable<_Vl, _Ky, _HF, _Ex, _Eq, _Al>&, const hashtable<_Vl, _Ky, _HF, _Ex, _Eq, _Al>&); public: size_type bucket_count() const { return _M_buckets.size(); } size_type max_bucket_count() const { return _Hashtable_prime_list:: _S_get_prime_list()[(int)_S_num_primes - 1]; } size_type elems_in_bucket(size_type __bucket) const { size_type __result = 0; for (_Node* __n = _M_buckets[__bucket]; __n; __n = __n->_M_next) __result += 1; return __result; } pair insert_unique(const value_type& __obj) { resize(_M_num_elements + 1); return insert_unique_noresize(__obj); } iterator insert_equal(const value_type& __obj) { resize(_M_num_elements + 1); return insert_equal_noresize(__obj); } pair insert_unique_noresize(const value_type& __obj); iterator insert_equal_noresize(const value_type& __obj); template void insert_unique(_InputIterator __f, _InputIterator __l) { insert_unique(__f, __l, __iterator_category(__f)); } template void insert_equal(_InputIterator __f, _InputIterator __l) { insert_equal(__f, __l, __iterator_category(__f)); } template void insert_unique(_InputIterator __f, _InputIterator __l, input_iterator_tag) { for ( ; __f != __l; ++__f) insert_unique(*__f); } template void insert_equal(_InputIterator __f, _InputIterator __l, input_iterator_tag) { for ( ; __f != __l; ++__f) insert_equal(*__f); } template void insert_unique(_ForwardIterator __f, _ForwardIterator __l, forward_iterator_tag) { size_type __n = distance(__f, __l); resize(_M_num_elements + __n); for ( ; __n > 0; --__n, ++__f) insert_unique_noresize(*__f); } template void insert_equal(_ForwardIterator __f, _ForwardIterator __l, forward_iterator_tag) { size_type __n = distance(__f, __l); resize(_M_num_elements + __n); for ( ; __n > 0; --__n, ++__f) insert_equal_noresize(*__f); } reference find_or_insert(const value_type& __obj); iterator find(const key_type& __key) { size_type __n = _M_bkt_num_key(__key); _Node* __first; for (__first = _M_buckets[__n]; __first && !_M_equals(_M_get_key(__first->_M_val), __key); __first = __first->_M_next) { } return iterator(__first, this); } const_iterator find(const key_type& __key) const { size_type __n = _M_bkt_num_key(__key); const _Node* __first; for (__first = _M_buckets[__n]; __first && !_M_equals(_M_get_key(__first->_M_val), __key); __first = __first->_M_next) { } return const_iterator(__first, this); } size_type count(const key_type& __key) const { const size_type __n = _M_bkt_num_key(__key); size_type __result = 0; for (const _Node* __cur = _M_buckets[__n]; __cur; __cur = __cur->_M_next) if (_M_equals(_M_get_key(__cur->_M_val), __key)) ++__result; return __result; } pair equal_range(const key_type& __key); pair equal_range(const key_type& __key) const; size_type erase(const key_type& __key); void erase(const iterator& __it); void erase(iterator __first, iterator __last); void erase(const const_iterator& __it); void erase(const_iterator __first, const_iterator __last); void resize(size_type __num_elements_hint); void clear(); private: size_type _M_next_size(size_type __n) const { return __stl_next_prime(__n); } void _M_initialize_buckets(size_type __n) { const size_type __n_buckets = _M_next_size(__n); _M_buckets.reserve(__n_buckets); _M_buckets.insert(_M_buckets.end(), __n_buckets, (_Node*) 0); _M_num_elements = 0; } size_type _M_bkt_num_key(const key_type& __key) const { return _M_bkt_num_key(__key, _M_buckets.size()); } size_type _M_bkt_num(const value_type& __obj) const { return _M_bkt_num_key(_M_get_key(__obj)); } size_type _M_bkt_num_key(const key_type& __key, size_t __n) const { return _M_hash(__key) % __n; } size_type _M_bkt_num(const value_type& __obj, size_t __n) const { return _M_bkt_num_key(_M_get_key(__obj), __n); } _Node* _M_new_node(const value_type& __obj) { _Node* __n = _M_get_node(); __n->_M_next = 0; __try { this->get_allocator().construct(&__n->_M_val, __obj); return __n; } __catch(...) { _M_put_node(__n); __throw_exception_again; } } void _M_delete_node(_Node* __n) { this->get_allocator().destroy(&__n->_M_val); _M_put_node(__n); } void _M_erase_bucket(const size_type __n, _Node* __first, _Node* __last); void _M_erase_bucket(const size_type __n, _Node* __last); void _M_copy_from(const hashtable& __ht); }; template _Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>& _Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>:: operator++() { const _Node* __old = _M_cur; _M_cur = _M_cur->_M_next; if (!_M_cur) { size_type __bucket = _M_ht->_M_bkt_num(__old->_M_val); while (!_M_cur && ++__bucket < _M_ht->_M_buckets.size()) _M_cur = _M_ht->_M_buckets[__bucket]; } return *this; } template inline _Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All> _Hashtable_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>:: operator++(int) { iterator __tmp = *this; ++*this; return __tmp; } template _Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>& _Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>:: operator++() { const _Node* __old = _M_cur; _M_cur = _M_cur->_M_next; if (!_M_cur) { size_type __bucket = _M_ht->_M_bkt_num(__old->_M_val); while (!_M_cur && ++__bucket < _M_ht->_M_buckets.size()) _M_cur = _M_ht->_M_buckets[__bucket]; } return *this; } template inline _Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All> _Hashtable_const_iterator<_Val, _Key, _HF, _ExK, _EqK, _All>:: operator++(int) { const_iterator __tmp = *this; ++*this; return __tmp; } template bool operator==(const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht1, const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht2) { typedef typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::_Node _Node; if (__ht1._M_buckets.size() != __ht2._M_buckets.size()) return false; for (size_t __n = 0; __n < __ht1._M_buckets.size(); ++__n) { _Node* __cur1 = __ht1._M_buckets[__n]; _Node* __cur2 = __ht2._M_buckets[__n]; // Check same length of lists for (; __cur1 && __cur2; __cur1 = __cur1->_M_next, __cur2 = __cur2->_M_next) { } if (__cur1 || __cur2) return false; // Now check one's elements are in the other for (__cur1 = __ht1._M_buckets[__n] ; __cur1; __cur1 = __cur1->_M_next) { bool _found__cur1 = false; for (__cur2 = __ht2._M_buckets[__n]; __cur2; __cur2 = __cur2->_M_next) { if (__cur1->_M_val == __cur2->_M_val) { _found__cur1 = true; break; } } if (!_found__cur1) return false; } } return true; } template inline bool operator!=(const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht1, const hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>& __ht2) { return !(__ht1 == __ht2); } template inline void swap(hashtable<_Val, _Key, _HF, _Extract, _EqKey, _All>& __ht1, hashtable<_Val, _Key, _HF, _Extract, _EqKey, _All>& __ht2) { __ht1.swap(__ht2); } template pair::iterator, bool> hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>:: insert_unique_noresize(const value_type& __obj) { const size_type __n = _M_bkt_num(__obj); _Node* __first = _M_buckets[__n]; for (_Node* __cur = __first; __cur; __cur = __cur->_M_next) if (_M_equals(_M_get_key(__cur->_M_val), _M_get_key(__obj))) return pair(iterator(__cur, this), false); _Node* __tmp = _M_new_node(__obj); __tmp->_M_next = __first; _M_buckets[__n] = __tmp; ++_M_num_elements; return pair(iterator(__tmp, this), true); } template typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::iterator hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>:: insert_equal_noresize(const value_type& __obj) { const size_type __n = _M_bkt_num(__obj); _Node* __first = _M_buckets[__n]; for (_Node* __cur = __first; __cur; __cur = __cur->_M_next) if (_M_equals(_M_get_key(__cur->_M_val), _M_get_key(__obj))) { _Node* __tmp = _M_new_node(__obj); __tmp->_M_next = __cur->_M_next; __cur->_M_next = __tmp; ++_M_num_elements; return iterator(__tmp, this); } _Node* __tmp = _M_new_node(__obj); __tmp->_M_next = __first; _M_buckets[__n] = __tmp; ++_M_num_elements; return iterator(__tmp, this); } template typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::reference hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>:: find_or_insert(const value_type& __obj) { resize(_M_num_elements + 1); size_type __n = _M_bkt_num(__obj); _Node* __first = _M_buckets[__n]; for (_Node* __cur = __first; __cur; __cur = __cur->_M_next) if (_M_equals(_M_get_key(__cur->_M_val), _M_get_key(__obj))) return __cur->_M_val; _Node* __tmp = _M_new_node(__obj); __tmp->_M_next = __first; _M_buckets[__n] = __tmp; ++_M_num_elements; return __tmp->_M_val; } template pair::iterator, typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::iterator> hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>:: equal_range(const key_type& __key) { typedef pair _Pii; const size_type __n = _M_bkt_num_key(__key); for (_Node* __first = _M_buckets[__n]; __first; __first = __first->_M_next) if (_M_equals(_M_get_key(__first->_M_val), __key)) { for (_Node* __cur = __first->_M_next; __cur; __cur = __cur->_M_next) if (!_M_equals(_M_get_key(__cur->_M_val), __key)) return _Pii(iterator(__first, this), iterator(__cur, this)); for (size_type __m = __n + 1; __m < _M_buckets.size(); ++__m) if (_M_buckets[__m]) return _Pii(iterator(__first, this), iterator(_M_buckets[__m], this)); return _Pii(iterator(__first, this), end()); } return _Pii(end(), end()); } template pair::const_iterator, typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::const_iterator> hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>:: equal_range(const key_type& __key) const { typedef pair _Pii; const size_type __n = _M_bkt_num_key(__key); for (const _Node* __first = _M_buckets[__n]; __first; __first = __first->_M_next) { if (_M_equals(_M_get_key(__first->_M_val), __key)) { for (const _Node* __cur = __first->_M_next; __cur; __cur = __cur->_M_next) if (!_M_equals(_M_get_key(__cur->_M_val), __key)) return _Pii(const_iterator(__first, this), const_iterator(__cur, this)); for (size_type __m = __n + 1; __m < _M_buckets.size(); ++__m) if (_M_buckets[__m]) return _Pii(const_iterator(__first, this), const_iterator(_M_buckets[__m], this)); return _Pii(const_iterator(__first, this), end()); } } return _Pii(end(), end()); } template typename hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>::size_type hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>:: erase(const key_type& __key) { const size_type __n = _M_bkt_num_key(__key); _Node* __first = _M_buckets[__n]; _Node* __saved_slot = 0; size_type __erased = 0; if (__first) { _Node* __cur = __first; _Node* __next = __cur->_M_next; while (__next) { if (_M_equals(_M_get_key(__next->_M_val), __key)) { if (&_M_get_key(__next->_M_val) != &__key) { __cur->_M_next = __next->_M_next; _M_delete_node(__next); __next = __cur->_M_next; ++__erased; --_M_num_elements; } else { __saved_slot = __cur; __cur = __next; __next = __cur->_M_next; } } else { __cur = __next; __next = __cur->_M_next; } } bool __delete_first = _M_equals(_M_get_key(__first->_M_val), __key); if (__saved_slot) { __next = __saved_slot->_M_next; __saved_slot->_M_next = __next->_M_next; _M_delete_node(__next); ++__erased; --_M_num_elements; } if (__delete_first) { _M_buckets[__n] = __first->_M_next; _M_delete_node(__first); ++__erased; --_M_num_elements; } } return __erased; } template void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>:: erase(const iterator& __it) { _Node* __p = __it._M_cur; if (__p) { const size_type __n = _M_bkt_num(__p->_M_val); _Node* __cur = _M_buckets[__n]; if (__cur == __p) { _M_buckets[__n] = __cur->_M_next; _M_delete_node(__cur); --_M_num_elements; } else { _Node* __next = __cur->_M_next; while (__next) { if (__next == __p) { __cur->_M_next = __next->_M_next; _M_delete_node(__next); --_M_num_elements; break; } else { __cur = __next; __next = __cur->_M_next; } } } } } template void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>:: erase(iterator __first, iterator __last) { size_type __f_bucket = __first._M_cur ? _M_bkt_num(__first._M_cur->_M_val) : _M_buckets.size(); size_type __l_bucket = __last._M_cur ? _M_bkt_num(__last._M_cur->_M_val) : _M_buckets.size(); if (__first._M_cur == __last._M_cur) return; else if (__f_bucket == __l_bucket) _M_erase_bucket(__f_bucket, __first._M_cur, __last._M_cur); else { _M_erase_bucket(__f_bucket, __first._M_cur, 0); for (size_type __n = __f_bucket + 1; __n < __l_bucket; ++__n) _M_erase_bucket(__n, 0); if (__l_bucket != _M_buckets.size()) _M_erase_bucket(__l_bucket, __last._M_cur); } } template inline void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>:: erase(const_iterator __first, const_iterator __last) { erase(iterator(const_cast<_Node*>(__first._M_cur), const_cast(__first._M_ht)), iterator(const_cast<_Node*>(__last._M_cur), const_cast(__last._M_ht))); } template inline void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>:: erase(const const_iterator& __it) { erase(iterator(const_cast<_Node*>(__it._M_cur), const_cast(__it._M_ht))); } template void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>:: resize(size_type __num_elements_hint) { const size_type __old_n = _M_buckets.size(); if (__num_elements_hint > __old_n) { const size_type __n = _M_next_size(__num_elements_hint); if (__n > __old_n) { _Vector_type __tmp(__n, (_Node*)(0), _M_buckets.get_allocator()); __try { for (size_type __bucket = 0; __bucket < __old_n; ++__bucket) { _Node* __first = _M_buckets[__bucket]; while (__first) { size_type __new_bucket = _M_bkt_num(__first->_M_val, __n); _M_buckets[__bucket] = __first->_M_next; __first->_M_next = __tmp[__new_bucket]; __tmp[__new_bucket] = __first; __first = _M_buckets[__bucket]; } } _M_buckets.swap(__tmp); } __catch(...) { for (size_type __bucket = 0; __bucket < __tmp.size(); ++__bucket) { while (__tmp[__bucket]) { _Node* __next = __tmp[__bucket]->_M_next; _M_delete_node(__tmp[__bucket]); __tmp[__bucket] = __next; } } __throw_exception_again; } } } } template void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>:: _M_erase_bucket(const size_type __n, _Node* __first, _Node* __last) { _Node* __cur = _M_buckets[__n]; if (__cur == __first) _M_erase_bucket(__n, __last); else { _Node* __next; for (__next = __cur->_M_next; __next != __first; __cur = __next, __next = __cur->_M_next) ; while (__next != __last) { __cur->_M_next = __next->_M_next; _M_delete_node(__next); __next = __cur->_M_next; --_M_num_elements; } } } template void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>:: _M_erase_bucket(const size_type __n, _Node* __last) { _Node* __cur = _M_buckets[__n]; while (__cur != __last) { _Node* __next = __cur->_M_next; _M_delete_node(__cur); __cur = __next; _M_buckets[__n] = __cur; --_M_num_elements; } } template void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>:: clear() { if (_M_num_elements == 0) return; for (size_type __i = 0; __i < _M_buckets.size(); ++__i) { _Node* __cur = _M_buckets[__i]; while (__cur != 0) { _Node* __next = __cur->_M_next; _M_delete_node(__cur); __cur = __next; } _M_buckets[__i] = 0; } _M_num_elements = 0; } template void hashtable<_Val, _Key, _HF, _Ex, _Eq, _All>:: _M_copy_from(const hashtable& __ht) { _M_buckets.clear(); _M_buckets.reserve(__ht._M_buckets.size()); _M_buckets.insert(_M_buckets.end(), __ht._M_buckets.size(), (_Node*) 0); __try { for (size_type __i = 0; __i < __ht._M_buckets.size(); ++__i) { const _Node* __cur = __ht._M_buckets[__i]; if (__cur) { _Node* __local_copy = _M_new_node(__cur->_M_val); _M_buckets[__i] = __local_copy; for (_Node* __next = __cur->_M_next; __next; __cur = __next, __next = __cur->_M_next) { __local_copy->_M_next = _M_new_node(__next->_M_val); __local_copy = __local_copy->_M_next; } } } _M_num_elements = __ht._M_num_elements; } __catch(...) { clear(); __throw_exception_again; } } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!T8/backward/strstreamnu[// Backward-compat support -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * Copyright (c) 1998 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ // WARNING: The classes defined in this header are DEPRECATED. This // header is defined in section D.7.1 of the C++ standard, and it // MAY BE REMOVED in a future standard revision. One should use the // header instead. /** @file strstream * This is a Standard C++ Library header. */ #ifndef _BACKWARD_STRSTREAM #define _BACKWARD_STRSTREAM #include "backward_warning.h" #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Class strstreambuf, a streambuf class that manages an array of char. // Note that this class is not a template. class strstreambuf : public basic_streambuf > { public: // Types. typedef char_traits _Traits; typedef basic_streambuf _Base; public: // Constructor, destructor explicit strstreambuf(streamsize __initial_capacity = 0); strstreambuf(void* (*__alloc)(size_t), void (*__free)(void*)); strstreambuf(char* __get, streamsize __n, char* __put = 0) throw (); strstreambuf(signed char* __get, streamsize __n, signed char* __put = 0) throw (); strstreambuf(unsigned char* __get, streamsize __n, unsigned char* __put=0) throw (); strstreambuf(const char* __get, streamsize __n) throw (); strstreambuf(const signed char* __get, streamsize __n) throw (); strstreambuf(const unsigned char* __get, streamsize __n) throw (); virtual ~strstreambuf(); public: void freeze(bool = true) throw (); char* str() throw (); _GLIBCXX_PURE int pcount() const throw (); protected: virtual int_type overflow(int_type __c = _Traits::eof()); virtual int_type pbackfail(int_type __c = _Traits::eof()); virtual int_type underflow(); virtual _Base* setbuf(char* __buf, streamsize __n); virtual pos_type seekoff(off_type __off, ios_base::seekdir __dir, ios_base::openmode __mode = ios_base::in | ios_base::out); virtual pos_type seekpos(pos_type __pos, ios_base::openmode __mode = ios_base::in | ios_base::out); private: strstreambuf& operator=(const strstreambuf&); strstreambuf(const strstreambuf&); // Dynamic allocation, possibly using _M_alloc_fun and _M_free_fun. char* _M_alloc(size_t); void _M_free(char*); // Helper function used in constructors. void _M_setup(char* __get, char* __put, streamsize __n) throw (); private: // Data members. void* (*_M_alloc_fun)(size_t); void (*_M_free_fun)(void*); bool _M_dynamic : 1; bool _M_frozen : 1; bool _M_constant : 1; }; // Class istrstream, an istream that manages a strstreambuf. class istrstream : public basic_istream { public: explicit istrstream(char*); explicit istrstream(const char*); istrstream(char* , streamsize); istrstream(const char*, streamsize); virtual ~istrstream(); _GLIBCXX_CONST strstreambuf* rdbuf() const throw (); char* str() throw (); private: strstreambuf _M_buf; }; // Class ostrstream class ostrstream : public basic_ostream { public: ostrstream(); ostrstream(char*, int, ios_base::openmode = ios_base::out); virtual ~ostrstream(); _GLIBCXX_CONST strstreambuf* rdbuf() const throw (); void freeze(bool = true) throw(); char* str() throw (); _GLIBCXX_PURE int pcount() const throw (); private: strstreambuf _M_buf; }; // Class strstream class strstream : public basic_iostream { public: typedef char char_type; typedef char_traits::int_type int_type; typedef char_traits::pos_type pos_type; typedef char_traits::off_type off_type; strstream(); strstream(char*, int, ios_base::openmode = ios_base::in | ios_base::out); virtual ~strstream(); _GLIBCXX_CONST strstreambuf* rdbuf() const throw (); void freeze(bool = true) throw (); _GLIBCXX_PURE int pcount() const throw (); char* str() throw (); private: strstreambuf _M_buf; }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!bNbN8/bits/alloc_traits.hnu[// Allocator traits -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/alloc_traits.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _ALLOC_TRAITS_H #define _ALLOC_TRAITS_H 1 #if __cplusplus >= 201103L #include #include #include #define __cpp_lib_allocator_traits_is_always_equal 201411 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION struct __allocator_traits_base { template struct __rebind : __replace_first_arg<_Tp, _Up> { }; template struct __rebind<_Tp, _Up, __void_t::other>> { using type = typename _Tp::template rebind<_Up>::other; }; protected: template using __pointer = typename _Tp::pointer; template using __c_pointer = typename _Tp::const_pointer; template using __v_pointer = typename _Tp::void_pointer; template using __cv_pointer = typename _Tp::const_void_pointer; template using __pocca = typename _Tp::propagate_on_container_copy_assignment; template using __pocma = typename _Tp::propagate_on_container_move_assignment; template using __pocs = typename _Tp::propagate_on_container_swap; template using __equal = typename _Tp::is_always_equal; }; template using __alloc_rebind = typename __allocator_traits_base::template __rebind<_Alloc, _Up>::type; /** * @brief Uniform interface to all allocator types. * @ingroup allocators */ template struct allocator_traits : __allocator_traits_base { /// The allocator type typedef _Alloc allocator_type; /// The allocated type typedef typename _Alloc::value_type value_type; /** * @brief The allocator's pointer type. * * @c Alloc::pointer if that type exists, otherwise @c value_type* */ using pointer = __detected_or_t; private: // Select _Func<_Alloc> or pointer_traits::rebind<_Tp> template class _Func, typename _Tp, typename = void> struct _Ptr { using type = typename pointer_traits::template rebind<_Tp>; }; template class _Func, typename _Tp> struct _Ptr<_Func, _Tp, __void_t<_Func<_Alloc>>> { using type = _Func<_Alloc>; }; // Select _A2::difference_type or pointer_traits<_Ptr>::difference_type template struct _Diff { using type = typename pointer_traits<_PtrT>::difference_type; }; template struct _Diff<_A2, _PtrT, __void_t> { using type = typename _A2::difference_type; }; // Select _A2::size_type or make_unsigned<_DiffT>::type template struct _Size : make_unsigned<_DiffT> { }; template struct _Size<_A2, _DiffT, __void_t> { using type = typename _A2::size_type; }; public: /** * @brief The allocator's const pointer type. * * @c Alloc::const_pointer if that type exists, otherwise * pointer_traits::rebind */ using const_pointer = typename _Ptr<__c_pointer, const value_type>::type; /** * @brief The allocator's void pointer type. * * @c Alloc::void_pointer if that type exists, otherwise * pointer_traits::rebind */ using void_pointer = typename _Ptr<__v_pointer, void>::type; /** * @brief The allocator's const void pointer type. * * @c Alloc::const_void_pointer if that type exists, otherwise * pointer_traits::rebind */ using const_void_pointer = typename _Ptr<__cv_pointer, const void>::type; /** * @brief The allocator's difference type * * @c Alloc::difference_type if that type exists, otherwise * pointer_traits::difference_type */ using difference_type = typename _Diff<_Alloc, pointer>::type; /** * @brief The allocator's size type * * @c Alloc::size_type if that type exists, otherwise * make_unsigned::type */ using size_type = typename _Size<_Alloc, difference_type>::type; /** * @brief How the allocator is propagated on copy assignment * * @c Alloc::propagate_on_container_copy_assignment if that type exists, * otherwise @c false_type */ using propagate_on_container_copy_assignment = __detected_or_t; /** * @brief How the allocator is propagated on move assignment * * @c Alloc::propagate_on_container_move_assignment if that type exists, * otherwise @c false_type */ using propagate_on_container_move_assignment = __detected_or_t; /** * @brief How the allocator is propagated on swap * * @c Alloc::propagate_on_container_swap if that type exists, * otherwise @c false_type */ using propagate_on_container_swap = __detected_or_t; /** * @brief Whether all instances of the allocator type compare equal. * * @c Alloc::is_always_equal if that type exists, * otherwise @c is_empty::type */ using is_always_equal = __detected_or_t::type, __equal, _Alloc>; template using rebind_alloc = __alloc_rebind<_Alloc, _Tp>; template using rebind_traits = allocator_traits>; private: template static auto _S_allocate(_Alloc2& __a, size_type __n, const_void_pointer __hint, int) -> decltype(__a.allocate(__n, __hint)) { return __a.allocate(__n, __hint); } template static pointer _S_allocate(_Alloc2& __a, size_type __n, const_void_pointer, ...) { return __a.allocate(__n); } template struct __construct_helper { template()->construct( std::declval<_Tp*>(), std::declval<_Args>()...))> static true_type __test(int); template static false_type __test(...); using type = decltype(__test<_Alloc>(0)); }; template using __has_construct = typename __construct_helper<_Tp, _Args...>::type; template static _Require<__has_construct<_Tp, _Args...>> _S_construct(_Alloc& __a, _Tp* __p, _Args&&... __args) { __a.construct(__p, std::forward<_Args>(__args)...); } template static _Require<__and_<__not_<__has_construct<_Tp, _Args...>>, is_constructible<_Tp, _Args...>>> _S_construct(_Alloc&, _Tp* __p, _Args&&... __args) { ::new((void*)__p) _Tp(std::forward<_Args>(__args)...); } template static auto _S_destroy(_Alloc2& __a, _Tp* __p, int) -> decltype(__a.destroy(__p)) { __a.destroy(__p); } template static void _S_destroy(_Alloc2&, _Tp* __p, ...) { __p->~_Tp(); } template static auto _S_max_size(_Alloc2& __a, int) -> decltype(__a.max_size()) { return __a.max_size(); } template static size_type _S_max_size(_Alloc2&, ...) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2466. allocator_traits::max_size() default behavior is incorrect return __gnu_cxx::__numeric_traits::__max / sizeof(value_type); } template static auto _S_select(_Alloc2& __a, int) -> decltype(__a.select_on_container_copy_construction()) { return __a.select_on_container_copy_construction(); } template static _Alloc2 _S_select(_Alloc2& __a, ...) { return __a; } public: /** * @brief Allocate memory. * @param __a An allocator. * @param __n The number of objects to allocate space for. * * Calls @c a.allocate(n) */ static pointer allocate(_Alloc& __a, size_type __n) { return __a.allocate(__n); } /** * @brief Allocate memory. * @param __a An allocator. * @param __n The number of objects to allocate space for. * @param __hint Aid to locality. * @return Memory of suitable size and alignment for @a n objects * of type @c value_type * * Returns a.allocate(n, hint) if that expression is * well-formed, otherwise returns @c a.allocate(n) */ static pointer allocate(_Alloc& __a, size_type __n, const_void_pointer __hint) { return _S_allocate(__a, __n, __hint, 0); } /** * @brief Deallocate memory. * @param __a An allocator. * @param __p Pointer to the memory to deallocate. * @param __n The number of objects space was allocated for. * * Calls a.deallocate(p, n) */ static void deallocate(_Alloc& __a, pointer __p, size_type __n) { __a.deallocate(__p, __n); } /** * @brief Construct an object of type @a _Tp * @param __a An allocator. * @param __p Pointer to memory of suitable size and alignment for Tp * @param __args Constructor arguments. * * Calls __a.construct(__p, std::forward(__args)...) * if that expression is well-formed, otherwise uses placement-new * to construct an object of type @a _Tp at location @a __p from the * arguments @a __args... */ template static auto construct(_Alloc& __a, _Tp* __p, _Args&&... __args) -> decltype(_S_construct(__a, __p, std::forward<_Args>(__args)...)) { _S_construct(__a, __p, std::forward<_Args>(__args)...); } /** * @brief Destroy an object of type @a _Tp * @param __a An allocator. * @param __p Pointer to the object to destroy * * Calls @c __a.destroy(__p) if that expression is well-formed, * otherwise calls @c __p->~_Tp() */ template static void destroy(_Alloc& __a, _Tp* __p) { _S_destroy(__a, __p, 0); } /** * @brief The maximum supported allocation size * @param __a An allocator. * @return @c __a.max_size() or @c numeric_limits::max() * * Returns @c __a.max_size() if that expression is well-formed, * otherwise returns @c numeric_limits::max() */ static size_type max_size(const _Alloc& __a) noexcept { return _S_max_size(__a, 0); } /** * @brief Obtain an allocator to use when copying a container. * @param __rhs An allocator. * @return @c __rhs.select_on_container_copy_construction() or @a __rhs * * Returns @c __rhs.select_on_container_copy_construction() if that * expression is well-formed, otherwise returns @a __rhs */ static _Alloc select_on_container_copy_construction(const _Alloc& __rhs) { return _S_select(__rhs, 0); } }; /// Partial specialization for std::allocator. template struct allocator_traits> { /// The allocator type using allocator_type = allocator<_Tp>; /// The allocated type using value_type = _Tp; /// The allocator's pointer type. using pointer = _Tp*; /// The allocator's const pointer type. using const_pointer = const _Tp*; /// The allocator's void pointer type. using void_pointer = void*; /// The allocator's const void pointer type. using const_void_pointer = const void*; /// The allocator's difference type using difference_type = std::ptrdiff_t; /// The allocator's size type using size_type = std::size_t; /// How the allocator is propagated on copy assignment using propagate_on_container_copy_assignment = false_type; /// How the allocator is propagated on move assignment using propagate_on_container_move_assignment = true_type; /// How the allocator is propagated on swap using propagate_on_container_swap = false_type; /// Whether all instances of the allocator type compare equal. using is_always_equal = true_type; template using rebind_alloc = allocator<_Up>; template using rebind_traits = allocator_traits>; /** * @brief Allocate memory. * @param __a An allocator. * @param __n The number of objects to allocate space for. * * Calls @c a.allocate(n) */ static pointer allocate(allocator_type& __a, size_type __n) { return __a.allocate(__n); } /** * @brief Allocate memory. * @param __a An allocator. * @param __n The number of objects to allocate space for. * @param __hint Aid to locality. * @return Memory of suitable size and alignment for @a n objects * of type @c value_type * * Returns a.allocate(n, hint) */ static pointer allocate(allocator_type& __a, size_type __n, const_void_pointer __hint) { return __a.allocate(__n, __hint); } /** * @brief Deallocate memory. * @param __a An allocator. * @param __p Pointer to the memory to deallocate. * @param __n The number of objects space was allocated for. * * Calls a.deallocate(p, n) */ static void deallocate(allocator_type& __a, pointer __p, size_type __n) { __a.deallocate(__p, __n); } /** * @brief Construct an object of type @a _Up * @param __a An allocator. * @param __p Pointer to memory of suitable size and alignment for Tp * @param __args Constructor arguments. * * Calls __a.construct(__p, std::forward(__args)...) */ template static void construct(allocator_type& __a, _Up* __p, _Args&&... __args) { __a.construct(__p, std::forward<_Args>(__args)...); } /** * @brief Destroy an object of type @a _Up * @param __a An allocator. * @param __p Pointer to the object to destroy * * Calls @c __a.destroy(__p). */ template static void destroy(allocator_type& __a, _Up* __p) { __a.destroy(__p); } /** * @brief The maximum supported allocation size * @param __a An allocator. * @return @c __a.max_size() */ static size_type max_size(const allocator_type& __a) noexcept { return __a.max_size(); } /** * @brief Obtain an allocator to use when copying a container. * @param __rhs An allocator. * @return @c __rhs */ static allocator_type select_on_container_copy_construction(const allocator_type& __rhs) { return __rhs; } }; template inline void __do_alloc_on_copy(_Alloc& __one, const _Alloc& __two, true_type) { __one = __two; } template inline void __do_alloc_on_copy(_Alloc&, const _Alloc&, false_type) { } template inline void __alloc_on_copy(_Alloc& __one, const _Alloc& __two) { typedef allocator_traits<_Alloc> __traits; typedef typename __traits::propagate_on_container_copy_assignment __pocca; __do_alloc_on_copy(__one, __two, __pocca()); } template inline _Alloc __alloc_on_copy(const _Alloc& __a) { typedef allocator_traits<_Alloc> __traits; return __traits::select_on_container_copy_construction(__a); } template inline void __do_alloc_on_move(_Alloc& __one, _Alloc& __two, true_type) { __one = std::move(__two); } template inline void __do_alloc_on_move(_Alloc&, _Alloc&, false_type) { } template inline void __alloc_on_move(_Alloc& __one, _Alloc& __two) { typedef allocator_traits<_Alloc> __traits; typedef typename __traits::propagate_on_container_move_assignment __pocma; __do_alloc_on_move(__one, __two, __pocma()); } template inline void __do_alloc_on_swap(_Alloc& __one, _Alloc& __two, true_type) { using std::swap; swap(__one, __two); } template inline void __do_alloc_on_swap(_Alloc&, _Alloc&, false_type) { } template inline void __alloc_on_swap(_Alloc& __one, _Alloc& __two) { typedef allocator_traits<_Alloc> __traits; typedef typename __traits::propagate_on_container_swap __pocs; __do_alloc_on_swap(__one, __two, __pocs()); } template class __is_copy_insertable_impl { typedef allocator_traits<_Alloc> _Traits; template(), std::declval<_Up*>(), std::declval()))> static true_type _M_select(int); template static false_type _M_select(...); public: typedef decltype(_M_select(0)) type; }; // true if _Alloc::value_type is CopyInsertable into containers using _Alloc template struct __is_copy_insertable : __is_copy_insertable_impl<_Alloc>::type { }; // std::allocator<_Tp> just requires CopyConstructible template struct __is_copy_insertable> : is_copy_constructible<_Tp> { }; // Trait to detect Allocator-like types. template struct __is_allocator : false_type { }; template struct __is_allocator<_Alloc, __void_t().allocate(size_t{}))>> : true_type { }; template using _RequireAllocator = typename enable_if<__is_allocator<_Alloc>::value, _Alloc>::type; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif // _ALLOC_TRAITS_H PK!+ʕ 8/bits/allocated_ptr.hnu[// Guarded Allocation -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/allocated_ptr.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _ALLOCATED_PTR_H #define _ALLOCATED_PTR_H 1 #if __cplusplus < 201103L # include #else # include # include # include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /// Non-standard RAII type for managing pointers obtained from allocators. template struct __allocated_ptr { using pointer = typename allocator_traits<_Alloc>::pointer; using value_type = typename allocator_traits<_Alloc>::value_type; /// Take ownership of __ptr __allocated_ptr(_Alloc& __a, pointer __ptr) noexcept : _M_alloc(std::__addressof(__a)), _M_ptr(__ptr) { } /// Convert __ptr to allocator's pointer type and take ownership of it template>> __allocated_ptr(_Alloc& __a, _Ptr __ptr) : _M_alloc(std::__addressof(__a)), _M_ptr(pointer_traits::pointer_to(*__ptr)) { } /// Transfer ownership of the owned pointer __allocated_ptr(__allocated_ptr&& __gd) noexcept : _M_alloc(__gd._M_alloc), _M_ptr(__gd._M_ptr) { __gd._M_ptr = nullptr; } /// Deallocate the owned pointer ~__allocated_ptr() { if (_M_ptr != nullptr) std::allocator_traits<_Alloc>::deallocate(*_M_alloc, _M_ptr, 1); } /// Release ownership of the owned pointer __allocated_ptr& operator=(std::nullptr_t) noexcept { _M_ptr = nullptr; return *this; } /// Get the address that the owned pointer refers to. value_type* get() { return std::__to_address(_M_ptr); } private: _Alloc* _M_alloc; pointer _M_ptr; }; /// Allocate space for a single object using __a template __allocated_ptr<_Alloc> __allocate_guarded(_Alloc& __a) { return { __a, std::allocator_traits<_Alloc>::allocate(__a, 1) }; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif #endif PK!XN8/bits/allocator.hnu[// Allocators -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * Copyright (c) 1996-1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/allocator.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _ALLOCATOR_H #define _ALLOCATOR_H 1 #include // Define the base class to std::allocator. #include #if __cplusplus >= 201103L #include #endif #define __cpp_lib_incomplete_container_elements 201505 #if __cplusplus >= 201103L # define __cpp_lib_allocator_is_always_equal 201411 #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup allocators * @{ */ /// allocator specialization. template<> class allocator { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef void* pointer; typedef const void* const_pointer; typedef void value_type; template struct rebind { typedef allocator<_Tp1> other; }; #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2103. std::allocator propagate_on_container_move_assignment typedef true_type propagate_on_container_move_assignment; typedef true_type is_always_equal; template void construct(_Up* __p, _Args&&... __args) { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); } template void destroy(_Up* __p) { __p->~_Up(); } #endif }; /** * @brief The @a standard allocator, as per [20.4]. * * See https://gcc.gnu.org/onlinedocs/libstdc++/manual/memory.html#std.util.memory.allocator * for further details. * * @tparam _Tp Type of allocated object. */ template class allocator : public __allocator_base<_Tp> { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Tp* pointer; typedef const _Tp* const_pointer; typedef _Tp& reference; typedef const _Tp& const_reference; typedef _Tp value_type; template struct rebind { typedef allocator<_Tp1> other; }; #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2103. std::allocator propagate_on_container_move_assignment typedef true_type propagate_on_container_move_assignment; typedef true_type is_always_equal; #endif allocator() throw() { } allocator(const allocator& __a) throw() : __allocator_base<_Tp>(__a) { } template allocator(const allocator<_Tp1>&) throw() { } ~allocator() throw() { } // Inherit everything else. }; template inline bool operator==(const allocator<_T1>&, const allocator<_T2>&) _GLIBCXX_USE_NOEXCEPT { return true; } template inline bool operator==(const allocator<_Tp>&, const allocator<_Tp>&) _GLIBCXX_USE_NOEXCEPT { return true; } template inline bool operator!=(const allocator<_T1>&, const allocator<_T2>&) _GLIBCXX_USE_NOEXCEPT { return false; } template inline bool operator!=(const allocator<_Tp>&, const allocator<_Tp>&) _GLIBCXX_USE_NOEXCEPT { return false; } // Invalid allocator partial specializations. // allocator_traits::rebind_alloc can be used to form a valid allocator type. template class allocator { public: typedef _Tp value_type; template allocator(const allocator<_Up>&) { } }; template class allocator { public: typedef _Tp value_type; template allocator(const allocator<_Up>&) { } }; template class allocator { public: typedef _Tp value_type; template allocator(const allocator<_Up>&) { } }; /// @} group allocator // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class allocator; extern template class allocator; #endif // Undefine. #undef __allocator_base // To implement Option 3 of DR 431. template struct __alloc_swap { static void _S_do_it(_Alloc&, _Alloc&) _GLIBCXX_NOEXCEPT { } }; template struct __alloc_swap<_Alloc, false> { static void _S_do_it(_Alloc& __one, _Alloc& __two) _GLIBCXX_NOEXCEPT { // Precondition: swappable allocators. if (__one != __two) swap(__one, __two); } }; // Optimize for stateless allocators. template struct __alloc_neq { static bool _S_do_it(const _Alloc&, const _Alloc&) { return false; } }; template struct __alloc_neq<_Alloc, false> { static bool _S_do_it(const _Alloc& __one, const _Alloc& __two) { return __one != __two; } }; #if __cplusplus >= 201103L template, is_nothrow_move_constructible>::value> struct __shrink_to_fit_aux { static bool _S_do_it(_Tp&) noexcept { return false; } }; template struct __shrink_to_fit_aux<_Tp, true> { static bool _S_do_it(_Tp& __c) noexcept { #if __cpp_exceptions try { _Tp(__make_move_if_noexcept_iterator(__c.begin()), __make_move_if_noexcept_iterator(__c.end()), __c.get_allocator()).swap(__c); return true; } catch(...) { return false; } #else return false; #endif } }; #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!==8"]"]8/bits/atomic_base.hnu[// -*- C++ -*- header. // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/atomic_base.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{atomic} */ #ifndef _GLIBCXX_ATOMIC_BASE_H #define _GLIBCXX_ATOMIC_BASE_H 1 #pragma GCC system_header #include #include #include #ifndef _GLIBCXX_ALWAYS_INLINE #define _GLIBCXX_ALWAYS_INLINE inline __attribute__((__always_inline__)) #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup atomics Atomics * * Components for performing atomic operations. * @{ */ /// Enumeration for memory_order typedef enum memory_order { memory_order_relaxed, memory_order_consume, memory_order_acquire, memory_order_release, memory_order_acq_rel, memory_order_seq_cst } memory_order; enum __memory_order_modifier { __memory_order_mask = 0x0ffff, __memory_order_modifier_mask = 0xffff0000, __memory_order_hle_acquire = 0x10000, __memory_order_hle_release = 0x20000 }; constexpr memory_order operator|(memory_order __m, __memory_order_modifier __mod) { return memory_order(__m | int(__mod)); } constexpr memory_order operator&(memory_order __m, __memory_order_modifier __mod) { return memory_order(__m & int(__mod)); } // Drop release ordering as per [atomics.types.operations.req]/21 constexpr memory_order __cmpexch_failure_order2(memory_order __m) noexcept { return __m == memory_order_acq_rel ? memory_order_acquire : __m == memory_order_release ? memory_order_relaxed : __m; } constexpr memory_order __cmpexch_failure_order(memory_order __m) noexcept { return memory_order(__cmpexch_failure_order2(__m & __memory_order_mask) | (__m & __memory_order_modifier_mask)); } _GLIBCXX_ALWAYS_INLINE void atomic_thread_fence(memory_order __m) noexcept { __atomic_thread_fence(__m); } _GLIBCXX_ALWAYS_INLINE void atomic_signal_fence(memory_order __m) noexcept { __atomic_signal_fence(__m); } /// kill_dependency template inline _Tp kill_dependency(_Tp __y) noexcept { _Tp __ret(__y); return __ret; } // Base types for atomics. template struct __atomic_base; #define ATOMIC_VAR_INIT(_VI) { _VI } template struct atomic; template struct atomic<_Tp*>; /* The target's "set" value for test-and-set may not be exactly 1. */ #if __GCC_ATOMIC_TEST_AND_SET_TRUEVAL == 1 typedef bool __atomic_flag_data_type; #else typedef unsigned char __atomic_flag_data_type; #endif /** * @brief Base type for atomic_flag. * * Base type is POD with data, allowing atomic_flag to derive from * it and meet the standard layout type requirement. In addition to * compatibility with a C interface, this allows different * implementations of atomic_flag to use the same atomic operation * functions, via a standard conversion to the __atomic_flag_base * argument. */ _GLIBCXX_BEGIN_EXTERN_C struct __atomic_flag_base { __atomic_flag_data_type _M_i; }; _GLIBCXX_END_EXTERN_C #define ATOMIC_FLAG_INIT { 0 } /// atomic_flag struct atomic_flag : public __atomic_flag_base { atomic_flag() noexcept = default; ~atomic_flag() noexcept = default; atomic_flag(const atomic_flag&) = delete; atomic_flag& operator=(const atomic_flag&) = delete; atomic_flag& operator=(const atomic_flag&) volatile = delete; // Conversion to ATOMIC_FLAG_INIT. constexpr atomic_flag(bool __i) noexcept : __atomic_flag_base{ _S_init(__i) } { } _GLIBCXX_ALWAYS_INLINE bool test_and_set(memory_order __m = memory_order_seq_cst) noexcept { return __atomic_test_and_set (&_M_i, __m); } _GLIBCXX_ALWAYS_INLINE bool test_and_set(memory_order __m = memory_order_seq_cst) volatile noexcept { return __atomic_test_and_set (&_M_i, __m); } _GLIBCXX_ALWAYS_INLINE void clear(memory_order __m = memory_order_seq_cst) noexcept { memory_order __b = __m & __memory_order_mask; __glibcxx_assert(__b != memory_order_consume); __glibcxx_assert(__b != memory_order_acquire); __glibcxx_assert(__b != memory_order_acq_rel); __atomic_clear (&_M_i, __m); } _GLIBCXX_ALWAYS_INLINE void clear(memory_order __m = memory_order_seq_cst) volatile noexcept { memory_order __b = __m & __memory_order_mask; __glibcxx_assert(__b != memory_order_consume); __glibcxx_assert(__b != memory_order_acquire); __glibcxx_assert(__b != memory_order_acq_rel); __atomic_clear (&_M_i, __m); } private: static constexpr __atomic_flag_data_type _S_init(bool __i) { return __i ? __GCC_ATOMIC_TEST_AND_SET_TRUEVAL : 0; } }; /// Base class for atomic integrals. // // For each of the integral types, define atomic_[integral type] struct // // atomic_bool bool // atomic_char char // atomic_schar signed char // atomic_uchar unsigned char // atomic_short short // atomic_ushort unsigned short // atomic_int int // atomic_uint unsigned int // atomic_long long // atomic_ulong unsigned long // atomic_llong long long // atomic_ullong unsigned long long // atomic_char16_t char16_t // atomic_char32_t char32_t // atomic_wchar_t wchar_t // // NB: Assuming _ITp is an integral scalar type that is 1, 2, 4, or // 8 bytes, since that is what GCC built-in functions for atomic // memory access expect. template struct __atomic_base { private: typedef _ITp __int_type; static constexpr int _S_alignment = sizeof(_ITp) > alignof(_ITp) ? sizeof(_ITp) : alignof(_ITp); alignas(_S_alignment) __int_type _M_i; public: __atomic_base() noexcept = default; ~__atomic_base() noexcept = default; __atomic_base(const __atomic_base&) = delete; __atomic_base& operator=(const __atomic_base&) = delete; __atomic_base& operator=(const __atomic_base&) volatile = delete; // Requires __int_type convertible to _M_i. constexpr __atomic_base(__int_type __i) noexcept : _M_i (__i) { } operator __int_type() const noexcept { return load(); } operator __int_type() const volatile noexcept { return load(); } __int_type operator=(__int_type __i) noexcept { store(__i); return __i; } __int_type operator=(__int_type __i) volatile noexcept { store(__i); return __i; } __int_type operator++(int) noexcept { return fetch_add(1); } __int_type operator++(int) volatile noexcept { return fetch_add(1); } __int_type operator--(int) noexcept { return fetch_sub(1); } __int_type operator--(int) volatile noexcept { return fetch_sub(1); } __int_type operator++() noexcept { return __atomic_add_fetch(&_M_i, 1, memory_order_seq_cst); } __int_type operator++() volatile noexcept { return __atomic_add_fetch(&_M_i, 1, memory_order_seq_cst); } __int_type operator--() noexcept { return __atomic_sub_fetch(&_M_i, 1, memory_order_seq_cst); } __int_type operator--() volatile noexcept { return __atomic_sub_fetch(&_M_i, 1, memory_order_seq_cst); } __int_type operator+=(__int_type __i) noexcept { return __atomic_add_fetch(&_M_i, __i, memory_order_seq_cst); } __int_type operator+=(__int_type __i) volatile noexcept { return __atomic_add_fetch(&_M_i, __i, memory_order_seq_cst); } __int_type operator-=(__int_type __i) noexcept { return __atomic_sub_fetch(&_M_i, __i, memory_order_seq_cst); } __int_type operator-=(__int_type __i) volatile noexcept { return __atomic_sub_fetch(&_M_i, __i, memory_order_seq_cst); } __int_type operator&=(__int_type __i) noexcept { return __atomic_and_fetch(&_M_i, __i, memory_order_seq_cst); } __int_type operator&=(__int_type __i) volatile noexcept { return __atomic_and_fetch(&_M_i, __i, memory_order_seq_cst); } __int_type operator|=(__int_type __i) noexcept { return __atomic_or_fetch(&_M_i, __i, memory_order_seq_cst); } __int_type operator|=(__int_type __i) volatile noexcept { return __atomic_or_fetch(&_M_i, __i, memory_order_seq_cst); } __int_type operator^=(__int_type __i) noexcept { return __atomic_xor_fetch(&_M_i, __i, memory_order_seq_cst); } __int_type operator^=(__int_type __i) volatile noexcept { return __atomic_xor_fetch(&_M_i, __i, memory_order_seq_cst); } bool is_lock_free() const noexcept { // Use a fake, minimally aligned pointer. return __atomic_is_lock_free(sizeof(_M_i), reinterpret_cast(-__alignof(_M_i))); } bool is_lock_free() const volatile noexcept { // Use a fake, minimally aligned pointer. return __atomic_is_lock_free(sizeof(_M_i), reinterpret_cast(-__alignof(_M_i))); } _GLIBCXX_ALWAYS_INLINE void store(__int_type __i, memory_order __m = memory_order_seq_cst) noexcept { memory_order __b = __m & __memory_order_mask; __glibcxx_assert(__b != memory_order_acquire); __glibcxx_assert(__b != memory_order_acq_rel); __glibcxx_assert(__b != memory_order_consume); __atomic_store_n(&_M_i, __i, __m); } _GLIBCXX_ALWAYS_INLINE void store(__int_type __i, memory_order __m = memory_order_seq_cst) volatile noexcept { memory_order __b = __m & __memory_order_mask; __glibcxx_assert(__b != memory_order_acquire); __glibcxx_assert(__b != memory_order_acq_rel); __glibcxx_assert(__b != memory_order_consume); __atomic_store_n(&_M_i, __i, __m); } _GLIBCXX_ALWAYS_INLINE __int_type load(memory_order __m = memory_order_seq_cst) const noexcept { memory_order __b = __m & __memory_order_mask; __glibcxx_assert(__b != memory_order_release); __glibcxx_assert(__b != memory_order_acq_rel); return __atomic_load_n(&_M_i, __m); } _GLIBCXX_ALWAYS_INLINE __int_type load(memory_order __m = memory_order_seq_cst) const volatile noexcept { memory_order __b = __m & __memory_order_mask; __glibcxx_assert(__b != memory_order_release); __glibcxx_assert(__b != memory_order_acq_rel); return __atomic_load_n(&_M_i, __m); } _GLIBCXX_ALWAYS_INLINE __int_type exchange(__int_type __i, memory_order __m = memory_order_seq_cst) noexcept { return __atomic_exchange_n(&_M_i, __i, __m); } _GLIBCXX_ALWAYS_INLINE __int_type exchange(__int_type __i, memory_order __m = memory_order_seq_cst) volatile noexcept { return __atomic_exchange_n(&_M_i, __i, __m); } _GLIBCXX_ALWAYS_INLINE bool compare_exchange_weak(__int_type& __i1, __int_type __i2, memory_order __m1, memory_order __m2) noexcept { memory_order __b2 = __m2 & __memory_order_mask; memory_order __b1 = __m1 & __memory_order_mask; __glibcxx_assert(__b2 != memory_order_release); __glibcxx_assert(__b2 != memory_order_acq_rel); __glibcxx_assert(__b2 <= __b1); return __atomic_compare_exchange_n(&_M_i, &__i1, __i2, 1, __m1, __m2); } _GLIBCXX_ALWAYS_INLINE bool compare_exchange_weak(__int_type& __i1, __int_type __i2, memory_order __m1, memory_order __m2) volatile noexcept { memory_order __b2 = __m2 & __memory_order_mask; memory_order __b1 = __m1 & __memory_order_mask; __glibcxx_assert(__b2 != memory_order_release); __glibcxx_assert(__b2 != memory_order_acq_rel); __glibcxx_assert(__b2 <= __b1); return __atomic_compare_exchange_n(&_M_i, &__i1, __i2, 1, __m1, __m2); } _GLIBCXX_ALWAYS_INLINE bool compare_exchange_weak(__int_type& __i1, __int_type __i2, memory_order __m = memory_order_seq_cst) noexcept { return compare_exchange_weak(__i1, __i2, __m, __cmpexch_failure_order(__m)); } _GLIBCXX_ALWAYS_INLINE bool compare_exchange_weak(__int_type& __i1, __int_type __i2, memory_order __m = memory_order_seq_cst) volatile noexcept { return compare_exchange_weak(__i1, __i2, __m, __cmpexch_failure_order(__m)); } _GLIBCXX_ALWAYS_INLINE bool compare_exchange_strong(__int_type& __i1, __int_type __i2, memory_order __m1, memory_order __m2) noexcept { memory_order __b2 = __m2 & __memory_order_mask; memory_order __b1 = __m1 & __memory_order_mask; __glibcxx_assert(__b2 != memory_order_release); __glibcxx_assert(__b2 != memory_order_acq_rel); __glibcxx_assert(__b2 <= __b1); return __atomic_compare_exchange_n(&_M_i, &__i1, __i2, 0, __m1, __m2); } _GLIBCXX_ALWAYS_INLINE bool compare_exchange_strong(__int_type& __i1, __int_type __i2, memory_order __m1, memory_order __m2) volatile noexcept { memory_order __b2 = __m2 & __memory_order_mask; memory_order __b1 = __m1 & __memory_order_mask; __glibcxx_assert(__b2 != memory_order_release); __glibcxx_assert(__b2 != memory_order_acq_rel); __glibcxx_assert(__b2 <= __b1); return __atomic_compare_exchange_n(&_M_i, &__i1, __i2, 0, __m1, __m2); } _GLIBCXX_ALWAYS_INLINE bool compare_exchange_strong(__int_type& __i1, __int_type __i2, memory_order __m = memory_order_seq_cst) noexcept { return compare_exchange_strong(__i1, __i2, __m, __cmpexch_failure_order(__m)); } _GLIBCXX_ALWAYS_INLINE bool compare_exchange_strong(__int_type& __i1, __int_type __i2, memory_order __m = memory_order_seq_cst) volatile noexcept { return compare_exchange_strong(__i1, __i2, __m, __cmpexch_failure_order(__m)); } _GLIBCXX_ALWAYS_INLINE __int_type fetch_add(__int_type __i, memory_order __m = memory_order_seq_cst) noexcept { return __atomic_fetch_add(&_M_i, __i, __m); } _GLIBCXX_ALWAYS_INLINE __int_type fetch_add(__int_type __i, memory_order __m = memory_order_seq_cst) volatile noexcept { return __atomic_fetch_add(&_M_i, __i, __m); } _GLIBCXX_ALWAYS_INLINE __int_type fetch_sub(__int_type __i, memory_order __m = memory_order_seq_cst) noexcept { return __atomic_fetch_sub(&_M_i, __i, __m); } _GLIBCXX_ALWAYS_INLINE __int_type fetch_sub(__int_type __i, memory_order __m = memory_order_seq_cst) volatile noexcept { return __atomic_fetch_sub(&_M_i, __i, __m); } _GLIBCXX_ALWAYS_INLINE __int_type fetch_and(__int_type __i, memory_order __m = memory_order_seq_cst) noexcept { return __atomic_fetch_and(&_M_i, __i, __m); } _GLIBCXX_ALWAYS_INLINE __int_type fetch_and(__int_type __i, memory_order __m = memory_order_seq_cst) volatile noexcept { return __atomic_fetch_and(&_M_i, __i, __m); } _GLIBCXX_ALWAYS_INLINE __int_type fetch_or(__int_type __i, memory_order __m = memory_order_seq_cst) noexcept { return __atomic_fetch_or(&_M_i, __i, __m); } _GLIBCXX_ALWAYS_INLINE __int_type fetch_or(__int_type __i, memory_order __m = memory_order_seq_cst) volatile noexcept { return __atomic_fetch_or(&_M_i, __i, __m); } _GLIBCXX_ALWAYS_INLINE __int_type fetch_xor(__int_type __i, memory_order __m = memory_order_seq_cst) noexcept { return __atomic_fetch_xor(&_M_i, __i, __m); } _GLIBCXX_ALWAYS_INLINE __int_type fetch_xor(__int_type __i, memory_order __m = memory_order_seq_cst) volatile noexcept { return __atomic_fetch_xor(&_M_i, __i, __m); } }; /// Partial specialization for pointer types. template struct __atomic_base<_PTp*> { private: typedef _PTp* __pointer_type; __pointer_type _M_p; // Factored out to facilitate explicit specialization. constexpr ptrdiff_t _M_type_size(ptrdiff_t __d) const { return __d * sizeof(_PTp); } constexpr ptrdiff_t _M_type_size(ptrdiff_t __d) const volatile { return __d * sizeof(_PTp); } public: __atomic_base() noexcept = default; ~__atomic_base() noexcept = default; __atomic_base(const __atomic_base&) = delete; __atomic_base& operator=(const __atomic_base&) = delete; __atomic_base& operator=(const __atomic_base&) volatile = delete; // Requires __pointer_type convertible to _M_p. constexpr __atomic_base(__pointer_type __p) noexcept : _M_p (__p) { } operator __pointer_type() const noexcept { return load(); } operator __pointer_type() const volatile noexcept { return load(); } __pointer_type operator=(__pointer_type __p) noexcept { store(__p); return __p; } __pointer_type operator=(__pointer_type __p) volatile noexcept { store(__p); return __p; } __pointer_type operator++(int) noexcept { return fetch_add(1); } __pointer_type operator++(int) volatile noexcept { return fetch_add(1); } __pointer_type operator--(int) noexcept { return fetch_sub(1); } __pointer_type operator--(int) volatile noexcept { return fetch_sub(1); } __pointer_type operator++() noexcept { return __atomic_add_fetch(&_M_p, _M_type_size(1), memory_order_seq_cst); } __pointer_type operator++() volatile noexcept { return __atomic_add_fetch(&_M_p, _M_type_size(1), memory_order_seq_cst); } __pointer_type operator--() noexcept { return __atomic_sub_fetch(&_M_p, _M_type_size(1), memory_order_seq_cst); } __pointer_type operator--() volatile noexcept { return __atomic_sub_fetch(&_M_p, _M_type_size(1), memory_order_seq_cst); } __pointer_type operator+=(ptrdiff_t __d) noexcept { return __atomic_add_fetch(&_M_p, _M_type_size(__d), memory_order_seq_cst); } __pointer_type operator+=(ptrdiff_t __d) volatile noexcept { return __atomic_add_fetch(&_M_p, _M_type_size(__d), memory_order_seq_cst); } __pointer_type operator-=(ptrdiff_t __d) noexcept { return __atomic_sub_fetch(&_M_p, _M_type_size(__d), memory_order_seq_cst); } __pointer_type operator-=(ptrdiff_t __d) volatile noexcept { return __atomic_sub_fetch(&_M_p, _M_type_size(__d), memory_order_seq_cst); } bool is_lock_free() const noexcept { // Produce a fake, minimally aligned pointer. return __atomic_is_lock_free(sizeof(_M_p), reinterpret_cast(-__alignof(_M_p))); } bool is_lock_free() const volatile noexcept { // Produce a fake, minimally aligned pointer. return __atomic_is_lock_free(sizeof(_M_p), reinterpret_cast(-__alignof(_M_p))); } _GLIBCXX_ALWAYS_INLINE void store(__pointer_type __p, memory_order __m = memory_order_seq_cst) noexcept { memory_order __b = __m & __memory_order_mask; __glibcxx_assert(__b != memory_order_acquire); __glibcxx_assert(__b != memory_order_acq_rel); __glibcxx_assert(__b != memory_order_consume); __atomic_store_n(&_M_p, __p, __m); } _GLIBCXX_ALWAYS_INLINE void store(__pointer_type __p, memory_order __m = memory_order_seq_cst) volatile noexcept { memory_order __b = __m & __memory_order_mask; __glibcxx_assert(__b != memory_order_acquire); __glibcxx_assert(__b != memory_order_acq_rel); __glibcxx_assert(__b != memory_order_consume); __atomic_store_n(&_M_p, __p, __m); } _GLIBCXX_ALWAYS_INLINE __pointer_type load(memory_order __m = memory_order_seq_cst) const noexcept { memory_order __b = __m & __memory_order_mask; __glibcxx_assert(__b != memory_order_release); __glibcxx_assert(__b != memory_order_acq_rel); return __atomic_load_n(&_M_p, __m); } _GLIBCXX_ALWAYS_INLINE __pointer_type load(memory_order __m = memory_order_seq_cst) const volatile noexcept { memory_order __b = __m & __memory_order_mask; __glibcxx_assert(__b != memory_order_release); __glibcxx_assert(__b != memory_order_acq_rel); return __atomic_load_n(&_M_p, __m); } _GLIBCXX_ALWAYS_INLINE __pointer_type exchange(__pointer_type __p, memory_order __m = memory_order_seq_cst) noexcept { return __atomic_exchange_n(&_M_p, __p, __m); } _GLIBCXX_ALWAYS_INLINE __pointer_type exchange(__pointer_type __p, memory_order __m = memory_order_seq_cst) volatile noexcept { return __atomic_exchange_n(&_M_p, __p, __m); } _GLIBCXX_ALWAYS_INLINE bool compare_exchange_strong(__pointer_type& __p1, __pointer_type __p2, memory_order __m1, memory_order __m2) noexcept { memory_order __b2 = __m2 & __memory_order_mask; memory_order __b1 = __m1 & __memory_order_mask; __glibcxx_assert(__b2 != memory_order_release); __glibcxx_assert(__b2 != memory_order_acq_rel); __glibcxx_assert(__b2 <= __b1); return __atomic_compare_exchange_n(&_M_p, &__p1, __p2, 0, __m1, __m2); } _GLIBCXX_ALWAYS_INLINE bool compare_exchange_strong(__pointer_type& __p1, __pointer_type __p2, memory_order __m1, memory_order __m2) volatile noexcept { memory_order __b2 = __m2 & __memory_order_mask; memory_order __b1 = __m1 & __memory_order_mask; __glibcxx_assert(__b2 != memory_order_release); __glibcxx_assert(__b2 != memory_order_acq_rel); __glibcxx_assert(__b2 <= __b1); return __atomic_compare_exchange_n(&_M_p, &__p1, __p2, 0, __m1, __m2); } _GLIBCXX_ALWAYS_INLINE __pointer_type fetch_add(ptrdiff_t __d, memory_order __m = memory_order_seq_cst) noexcept { return __atomic_fetch_add(&_M_p, _M_type_size(__d), __m); } _GLIBCXX_ALWAYS_INLINE __pointer_type fetch_add(ptrdiff_t __d, memory_order __m = memory_order_seq_cst) volatile noexcept { return __atomic_fetch_add(&_M_p, _M_type_size(__d), __m); } _GLIBCXX_ALWAYS_INLINE __pointer_type fetch_sub(ptrdiff_t __d, memory_order __m = memory_order_seq_cst) noexcept { return __atomic_fetch_sub(&_M_p, _M_type_size(__d), __m); } _GLIBCXX_ALWAYS_INLINE __pointer_type fetch_sub(ptrdiff_t __d, memory_order __m = memory_order_seq_cst) volatile noexcept { return __atomic_fetch_sub(&_M_p, _M_type_size(__d), __m); } }; // @} group atomics _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!'. /** @file bits/atomic_futex.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. */ #ifndef _GLIBCXX_ATOMIC_FUTEX_H #define _GLIBCXX_ATOMIC_FUTEX_H 1 #pragma GCC system_header #include #include #include #if ! (defined(_GLIBCXX_HAVE_LINUX_FUTEX) && ATOMIC_INT_LOCK_FREE > 1) #include #include #endif #ifndef _GLIBCXX_ALWAYS_INLINE #define _GLIBCXX_ALWAYS_INLINE inline __attribute__((__always_inline__)) #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1) #if defined(_GLIBCXX_HAVE_LINUX_FUTEX) && ATOMIC_INT_LOCK_FREE > 1 struct __atomic_futex_unsigned_base { // Returns false iff a timeout occurred. bool _M_futex_wait_until(unsigned *__addr, unsigned __val, bool __has_timeout, chrono::seconds __s, chrono::nanoseconds __ns); // This can be executed after the object has been destroyed. static void _M_futex_notify_all(unsigned* __addr); }; template class __atomic_futex_unsigned : __atomic_futex_unsigned_base { typedef chrono::system_clock __clock_t; // This must be lock-free and at offset 0. atomic _M_data; public: explicit __atomic_futex_unsigned(unsigned __data) : _M_data(__data) { } _GLIBCXX_ALWAYS_INLINE unsigned _M_load(memory_order __mo) { return _M_data.load(__mo) & ~_Waiter_bit; } private: // If a timeout occurs, returns a current value after the timeout; // otherwise, returns the operand's value if equal is true or a different // value if equal is false. // The assumed value is the caller's assumption about the current value // when making the call. unsigned _M_load_and_test_until(unsigned __assumed, unsigned __operand, bool __equal, memory_order __mo, bool __has_timeout, chrono::seconds __s, chrono::nanoseconds __ns) { for (;;) { // Don't bother checking the value again because we expect the caller // to have done it recently. // memory_order_relaxed is sufficient because we can rely on just the // modification order (store_notify uses an atomic RMW operation too), // and the futex syscalls synchronize between themselves. _M_data.fetch_or(_Waiter_bit, memory_order_relaxed); bool __ret = _M_futex_wait_until((unsigned*)(void*)&_M_data, __assumed | _Waiter_bit, __has_timeout, __s, __ns); // Fetch the current value after waiting (clears _Waiter_bit). __assumed = _M_load(__mo); if (!__ret || ((__operand == __assumed) == __equal)) return __assumed; // TODO adapt wait time } } // Returns the operand's value if equal is true or a different value if // equal is false. // The assumed value is the caller's assumption about the current value // when making the call. unsigned _M_load_and_test(unsigned __assumed, unsigned __operand, bool __equal, memory_order __mo) { return _M_load_and_test_until(__assumed, __operand, __equal, __mo, false, {}, {}); } // If a timeout occurs, returns a current value after the timeout; // otherwise, returns the operand's value if equal is true or a different // value if equal is false. // The assumed value is the caller's assumption about the current value // when making the call. template unsigned _M_load_and_test_until_impl(unsigned __assumed, unsigned __operand, bool __equal, memory_order __mo, const chrono::time_point<__clock_t, _Dur>& __atime) { auto __s = chrono::time_point_cast(__atime); auto __ns = chrono::duration_cast(__atime - __s); // XXX correct? return _M_load_and_test_until(__assumed, __operand, __equal, __mo, true, __s.time_since_epoch(), __ns); } public: _GLIBCXX_ALWAYS_INLINE unsigned _M_load_when_not_equal(unsigned __val, memory_order __mo) { unsigned __i = _M_load(__mo); if ((__i & ~_Waiter_bit) != __val) return (__i & ~_Waiter_bit); // TODO Spin-wait first. return _M_load_and_test(__i, __val, false, __mo); } _GLIBCXX_ALWAYS_INLINE void _M_load_when_equal(unsigned __val, memory_order __mo) { unsigned __i = _M_load(__mo); if ((__i & ~_Waiter_bit) == __val) return; // TODO Spin-wait first. _M_load_and_test(__i, __val, true, __mo); } // Returns false iff a timeout occurred. template _GLIBCXX_ALWAYS_INLINE bool _M_load_when_equal_for(unsigned __val, memory_order __mo, const chrono::duration<_Rep, _Period>& __rtime) { return _M_load_when_equal_until(__val, __mo, __clock_t::now() + __rtime); } // Returns false iff a timeout occurred. template _GLIBCXX_ALWAYS_INLINE bool _M_load_when_equal_until(unsigned __val, memory_order __mo, const chrono::time_point<_Clock, _Duration>& __atime) { // DR 887 - Sync unknown clock to known clock. const typename _Clock::time_point __c_entry = _Clock::now(); const __clock_t::time_point __s_entry = __clock_t::now(); const auto __delta = __atime - __c_entry; const auto __s_atime = __s_entry + __delta; return _M_load_when_equal_until(__val, __mo, __s_atime); } // Returns false iff a timeout occurred. template _GLIBCXX_ALWAYS_INLINE bool _M_load_when_equal_until(unsigned __val, memory_order __mo, const chrono::time_point<__clock_t, _Duration>& __atime) { unsigned __i = _M_load(__mo); if ((__i & ~_Waiter_bit) == __val) return true; // TODO Spin-wait first. Ignore effect on timeout. __i = _M_load_and_test_until_impl(__i, __val, true, __mo, __atime); return (__i & ~_Waiter_bit) == __val; } _GLIBCXX_ALWAYS_INLINE void _M_store_notify_all(unsigned __val, memory_order __mo) { unsigned* __futex = (unsigned *)(void *)&_M_data; if (_M_data.exchange(__val, __mo) & _Waiter_bit) _M_futex_notify_all(__futex); } }; #else // ! (_GLIBCXX_HAVE_LINUX_FUTEX && ATOMIC_INT_LOCK_FREE > 1) // If futexes are not available, use a mutex and a condvar to wait. // Because we access the data only within critical sections, all accesses // are sequentially consistent; thus, we satisfy any provided memory_order. template class __atomic_futex_unsigned { typedef chrono::system_clock __clock_t; unsigned _M_data; mutex _M_mutex; condition_variable _M_condvar; public: explicit __atomic_futex_unsigned(unsigned __data) : _M_data(__data) { } _GLIBCXX_ALWAYS_INLINE unsigned _M_load(memory_order __mo) { unique_lock __lock(_M_mutex); return _M_data; } _GLIBCXX_ALWAYS_INLINE unsigned _M_load_when_not_equal(unsigned __val, memory_order __mo) { unique_lock __lock(_M_mutex); while (_M_data == __val) _M_condvar.wait(__lock); return _M_data; } _GLIBCXX_ALWAYS_INLINE void _M_load_when_equal(unsigned __val, memory_order __mo) { unique_lock __lock(_M_mutex); while (_M_data != __val) _M_condvar.wait(__lock); } template _GLIBCXX_ALWAYS_INLINE bool _M_load_when_equal_for(unsigned __val, memory_order __mo, const chrono::duration<_Rep, _Period>& __rtime) { unique_lock __lock(_M_mutex); return _M_condvar.wait_for(__lock, __rtime, [&] { return _M_data == __val;}); } template _GLIBCXX_ALWAYS_INLINE bool _M_load_when_equal_until(unsigned __val, memory_order __mo, const chrono::time_point<_Clock, _Duration>& __atime) { unique_lock __lock(_M_mutex); return _M_condvar.wait_until(__lock, __atime, [&] { return _M_data == __val;}); } _GLIBCXX_ALWAYS_INLINE void _M_store_notify_all(unsigned __val, memory_order __mo) { unique_lock __lock(_M_mutex); _M_data = __val; _M_condvar.notify_all(); } }; #endif // _GLIBCXX_HAVE_LINUX_FUTEX && ATOMIC_INT_LOCK_FREE > 1 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!/l 8/bits/atomic_lockfree_defines.hnu[// -*- C++ -*- header. // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/atomic_lockfree_defines.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{atomic} */ #ifndef _GLIBCXX_ATOMIC_LOCK_FREE_H #define _GLIBCXX_ATOMIC_LOCK_FREE_H 1 #pragma GCC system_header /** * @addtogroup atomics * @{ */ /** * Lock-free property. * * 0 indicates that the types are never lock-free. * 1 indicates that the types are sometimes lock-free. * 2 indicates that the types are always lock-free. */ #if __cplusplus >= 201103L #define ATOMIC_BOOL_LOCK_FREE __GCC_ATOMIC_BOOL_LOCK_FREE #define ATOMIC_CHAR_LOCK_FREE __GCC_ATOMIC_CHAR_LOCK_FREE #define ATOMIC_WCHAR_T_LOCK_FREE __GCC_ATOMIC_WCHAR_T_LOCK_FREE #define ATOMIC_CHAR16_T_LOCK_FREE __GCC_ATOMIC_CHAR16_T_LOCK_FREE #define ATOMIC_CHAR32_T_LOCK_FREE __GCC_ATOMIC_CHAR32_T_LOCK_FREE #define ATOMIC_SHORT_LOCK_FREE __GCC_ATOMIC_SHORT_LOCK_FREE #define ATOMIC_INT_LOCK_FREE __GCC_ATOMIC_INT_LOCK_FREE #define ATOMIC_LONG_LOCK_FREE __GCC_ATOMIC_LONG_LOCK_FREE #define ATOMIC_LLONG_LOCK_FREE __GCC_ATOMIC_LLONG_LOCK_FREE #define ATOMIC_POINTER_LOCK_FREE __GCC_ATOMIC_POINTER_LOCK_FREE #endif // @} group atomics #endif PK!0>>8/bits/basic_ios.hnu[// Iostreams base classes -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/basic_ios.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ios} */ #ifndef _BASIC_IOS_H #define _BASIC_IOS_H 1 #pragma GCC system_header #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template inline const _Facet& __check_facet(const _Facet* __f) { if (!__f) __throw_bad_cast(); return *__f; } /** * @brief Template class basic_ios, virtual base class for all * stream classes. * @ingroup io * * @tparam _CharT Type of character stream. * @tparam _Traits Traits for character type, defaults to * char_traits<_CharT>. * * Most of the member functions called dispatched on stream objects * (e.g., @c std::cout.foo(bar);) are consolidated in this class. */ template class basic_ios : public ios_base { public: //@{ /** * These are standard types. They permit a standardized way of * referring to names of (or names dependent on) the template * parameters, which are specific to the implementation. */ typedef _CharT char_type; typedef typename _Traits::int_type int_type; typedef typename _Traits::pos_type pos_type; typedef typename _Traits::off_type off_type; typedef _Traits traits_type; //@} //@{ /** * These are non-standard types. */ typedef ctype<_CharT> __ctype_type; typedef num_put<_CharT, ostreambuf_iterator<_CharT, _Traits> > __num_put_type; typedef num_get<_CharT, istreambuf_iterator<_CharT, _Traits> > __num_get_type; //@} // Data members: protected: basic_ostream<_CharT, _Traits>* _M_tie; mutable char_type _M_fill; mutable bool _M_fill_init; basic_streambuf<_CharT, _Traits>* _M_streambuf; // Cached use_facet, which is based on the current locale info. const __ctype_type* _M_ctype; // For ostream. const __num_put_type* _M_num_put; // For istream. const __num_get_type* _M_num_get; public: //@{ /** * @brief The quick-and-easy status check. * * This allows you to write constructs such as * if (!a_stream) ... and while (a_stream) ... */ #if __cplusplus >= 201103L explicit operator bool() const { return !this->fail(); } #else operator void*() const { return this->fail() ? 0 : const_cast(this); } #endif bool operator!() const { return this->fail(); } //@} /** * @brief Returns the error state of the stream buffer. * @return A bit pattern (well, isn't everything?) * * See std::ios_base::iostate for the possible bit values. Most * users will call one of the interpreting wrappers, e.g., good(). */ iostate rdstate() const { return _M_streambuf_state; } /** * @brief [Re]sets the error state. * @param __state The new state flag(s) to set. * * See std::ios_base::iostate for the possible bit values. Most * users will not need to pass an argument. */ void clear(iostate __state = goodbit); /** * @brief Sets additional flags in the error state. * @param __state The additional state flag(s) to set. * * See std::ios_base::iostate for the possible bit values. */ void setstate(iostate __state) { this->clear(this->rdstate() | __state); } // Flip the internal state on for the proper state bits, then // rethrows the propagated exception if bit also set in // exceptions(). void _M_setstate(iostate __state) { // 27.6.1.2.1 Common requirements. // Turn this on without causing an ios::failure to be thrown. _M_streambuf_state |= __state; if (this->exceptions() & __state) __throw_exception_again; } /** * @brief Fast error checking. * @return True if no error flags are set. * * A wrapper around rdstate. */ bool good() const { return this->rdstate() == 0; } /** * @brief Fast error checking. * @return True if the eofbit is set. * * Note that other iostate flags may also be set. */ bool eof() const { return (this->rdstate() & eofbit) != 0; } /** * @brief Fast error checking. * @return True if either the badbit or the failbit is set. * * Checking the badbit in fail() is historical practice. * Note that other iostate flags may also be set. */ bool fail() const { return (this->rdstate() & (badbit | failbit)) != 0; } /** * @brief Fast error checking. * @return True if the badbit is set. * * Note that other iostate flags may also be set. */ bool bad() const { return (this->rdstate() & badbit) != 0; } /** * @brief Throwing exceptions on errors. * @return The current exceptions mask. * * This changes nothing in the stream. See the one-argument version * of exceptions(iostate) for the meaning of the return value. */ iostate exceptions() const { return _M_exception; } /** * @brief Throwing exceptions on errors. * @param __except The new exceptions mask. * * By default, error flags are set silently. You can set an * exceptions mask for each stream; if a bit in the mask becomes set * in the error flags, then an exception of type * std::ios_base::failure is thrown. * * If the error flag is already set when the exceptions mask is * added, the exception is immediately thrown. Try running the * following under GCC 3.1 or later: * @code * #include * #include * #include * * int main() * { * std::set_terminate (__gnu_cxx::__verbose_terminate_handler); * * std::ifstream f ("/etc/motd"); * * std::cerr << "Setting badbit\n"; * f.setstate (std::ios_base::badbit); * * std::cerr << "Setting exception mask\n"; * f.exceptions (std::ios_base::badbit); * } * @endcode */ void exceptions(iostate __except) { _M_exception = __except; this->clear(_M_streambuf_state); } // Constructor/destructor: /** * @brief Constructor performs initialization. * * The parameter is passed by derived streams. */ explicit basic_ios(basic_streambuf<_CharT, _Traits>* __sb) : ios_base(), _M_tie(0), _M_fill(), _M_fill_init(false), _M_streambuf(0), _M_ctype(0), _M_num_put(0), _M_num_get(0) { this->init(__sb); } /** * @brief Empty. * * The destructor does nothing. More specifically, it does not * destroy the streambuf held by rdbuf(). */ virtual ~basic_ios() { } // Members: /** * @brief Fetches the current @e tied stream. * @return A pointer to the tied stream, or NULL if the stream is * not tied. * * A stream may be @e tied (or synchronized) to a second output * stream. When this stream performs any I/O, the tied stream is * first flushed. For example, @c std::cin is tied to @c std::cout. */ basic_ostream<_CharT, _Traits>* tie() const { return _M_tie; } /** * @brief Ties this stream to an output stream. * @param __tiestr The output stream. * @return The previously tied output stream, or NULL if the stream * was not tied. * * This sets up a new tie; see tie() for more. */ basic_ostream<_CharT, _Traits>* tie(basic_ostream<_CharT, _Traits>* __tiestr) { basic_ostream<_CharT, _Traits>* __old = _M_tie; _M_tie = __tiestr; return __old; } /** * @brief Accessing the underlying buffer. * @return The current stream buffer. * * This does not change the state of the stream. */ basic_streambuf<_CharT, _Traits>* rdbuf() const { return _M_streambuf; } /** * @brief Changing the underlying buffer. * @param __sb The new stream buffer. * @return The previous stream buffer. * * Associates a new buffer with the current stream, and clears the * error state. * * Due to historical accidents which the LWG refuses to correct, the * I/O library suffers from a design error: this function is hidden * in derived classes by overrides of the zero-argument @c rdbuf(), * which is non-virtual for hysterical raisins. As a result, you * must use explicit qualifications to access this function via any * derived class. For example: * * @code * std::fstream foo; // or some other derived type * std::streambuf* p = .....; * * foo.ios::rdbuf(p); // ios == basic_ios * @endcode */ basic_streambuf<_CharT, _Traits>* rdbuf(basic_streambuf<_CharT, _Traits>* __sb); /** * @brief Copies fields of __rhs into this. * @param __rhs The source values for the copies. * @return Reference to this object. * * All fields of __rhs are copied into this object except that rdbuf() * and rdstate() remain unchanged. All values in the pword and iword * arrays are copied. Before copying, each callback is invoked with * erase_event. After copying, each (new) callback is invoked with * copyfmt_event. The final step is to copy exceptions(). */ basic_ios& copyfmt(const basic_ios& __rhs); /** * @brief Retrieves the @a empty character. * @return The current fill character. * * It defaults to a space (' ') in the current locale. */ char_type fill() const { if (!_M_fill_init) { _M_fill = this->widen(' '); _M_fill_init = true; } return _M_fill; } /** * @brief Sets a new @a empty character. * @param __ch The new character. * @return The previous fill character. * * The fill character is used to fill out space when P+ characters * have been requested (e.g., via setw), Q characters are actually * used, and Qfill(); _M_fill = __ch; return __old; } // Locales: /** * @brief Moves to a new locale. * @param __loc The new locale. * @return The previous locale. * * Calls @c ios_base::imbue(loc), and if a stream buffer is associated * with this stream, calls that buffer's @c pubimbue(loc). * * Additional l10n notes are at * http://gcc.gnu.org/onlinedocs/libstdc++/manual/localization.html */ locale imbue(const locale& __loc); /** * @brief Squeezes characters. * @param __c The character to narrow. * @param __dfault The character to narrow. * @return The narrowed character. * * Maps a character of @c char_type to a character of @c char, * if possible. * * Returns the result of * @code * std::use_facet >(getloc()).narrow(c,dfault) * @endcode * * Additional l10n notes are at * http://gcc.gnu.org/onlinedocs/libstdc++/manual/localization.html */ char narrow(char_type __c, char __dfault) const { return __check_facet(_M_ctype).narrow(__c, __dfault); } /** * @brief Widens characters. * @param __c The character to widen. * @return The widened character. * * Maps a character of @c char to a character of @c char_type. * * Returns the result of * @code * std::use_facet >(getloc()).widen(c) * @endcode * * Additional l10n notes are at * http://gcc.gnu.org/onlinedocs/libstdc++/manual/localization.html */ char_type widen(char __c) const { return __check_facet(_M_ctype).widen(__c); } protected: // 27.4.5.1 basic_ios constructors /** * @brief Empty. * * The default constructor does nothing and is not normally * accessible to users. */ basic_ios() : ios_base(), _M_tie(0), _M_fill(char_type()), _M_fill_init(false), _M_streambuf(0), _M_ctype(0), _M_num_put(0), _M_num_get(0) { } /** * @brief All setup is performed here. * * This is called from the public constructor. It is not virtual and * cannot be redefined. */ void init(basic_streambuf<_CharT, _Traits>* __sb); #if __cplusplus >= 201103L basic_ios(const basic_ios&) = delete; basic_ios& operator=(const basic_ios&) = delete; void move(basic_ios& __rhs) { ios_base::_M_move(__rhs); _M_cache_locale(_M_ios_locale); this->tie(__rhs.tie(nullptr)); _M_fill = __rhs._M_fill; _M_fill_init = __rhs._M_fill_init; _M_streambuf = nullptr; } void move(basic_ios&& __rhs) { this->move(__rhs); } void swap(basic_ios& __rhs) noexcept { ios_base::_M_swap(__rhs); _M_cache_locale(_M_ios_locale); __rhs._M_cache_locale(__rhs._M_ios_locale); std::swap(_M_tie, __rhs._M_tie); std::swap(_M_fill, __rhs._M_fill); std::swap(_M_fill_init, __rhs._M_fill_init); } void set_rdbuf(basic_streambuf<_CharT, _Traits>* __sb) { _M_streambuf = __sb; } #endif void _M_cache_locale(const locale& __loc); }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #include #endif /* _BASIC_IOS_H */ PK!7Q8/bits/basic_ios.tccnu[// basic_ios member functions -*- C++ -*- // Copyright (C) 1999-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/basic_ios.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ios} */ #ifndef _BASIC_IOS_TCC #define _BASIC_IOS_TCC 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template void basic_ios<_CharT, _Traits>::clear(iostate __state) { if (this->rdbuf()) _M_streambuf_state = __state; else _M_streambuf_state = __state | badbit; if (this->exceptions() & this->rdstate()) __throw_ios_failure(__N("basic_ios::clear")); } template basic_streambuf<_CharT, _Traits>* basic_ios<_CharT, _Traits>::rdbuf(basic_streambuf<_CharT, _Traits>* __sb) { basic_streambuf<_CharT, _Traits>* __old = _M_streambuf; _M_streambuf = __sb; this->clear(); return __old; } template basic_ios<_CharT, _Traits>& basic_ios<_CharT, _Traits>::copyfmt(const basic_ios& __rhs) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 292. effects of a.copyfmt (a) if (this != &__rhs) { // Per 27.1.1, do not call imbue, yet must trash all caches // associated with imbue() // Alloc any new word array first, so if it fails we have "rollback". _Words* __words = (__rhs._M_word_size <= _S_local_word_size) ? _M_local_word : new _Words[__rhs._M_word_size]; // Bump refs before doing callbacks, for safety. _Callback_list* __cb = __rhs._M_callbacks; if (__cb) __cb->_M_add_reference(); _M_call_callbacks(erase_event); if (_M_word != _M_local_word) { delete [] _M_word; _M_word = 0; } _M_dispose_callbacks(); // NB: Don't want any added during above. _M_callbacks = __cb; for (int __i = 0; __i < __rhs._M_word_size; ++__i) __words[__i] = __rhs._M_word[__i]; _M_word = __words; _M_word_size = __rhs._M_word_size; this->flags(__rhs.flags()); this->width(__rhs.width()); this->precision(__rhs.precision()); this->tie(__rhs.tie()); this->fill(__rhs.fill()); _M_ios_locale = __rhs.getloc(); _M_cache_locale(_M_ios_locale); _M_call_callbacks(copyfmt_event); // The next is required to be the last assignment. this->exceptions(__rhs.exceptions()); } return *this; } // Locales: template locale basic_ios<_CharT, _Traits>::imbue(const locale& __loc) { locale __old(this->getloc()); ios_base::imbue(__loc); _M_cache_locale(__loc); if (this->rdbuf() != 0) this->rdbuf()->pubimbue(__loc); return __old; } template void basic_ios<_CharT, _Traits>::init(basic_streambuf<_CharT, _Traits>* __sb) { // NB: This may be called more than once on the same object. ios_base::_M_init(); // Cache locale data and specific facets used by iostreams. _M_cache_locale(_M_ios_locale); // NB: The 27.4.4.1 Postconditions Table specifies requirements // after basic_ios::init() has been called. As part of this, // fill() must return widen(' ') any time after init() has been // called, which needs an imbued ctype facet of char_type to // return without throwing an exception. Unfortunately, // ctype is not necessarily a required facet, so // streams with char_type != [char, wchar_t] will not have it by // default. Because of this, the correct value for _M_fill is // constructed on the first call of fill(). That way, // unformatted input and output with non-required basic_ios // instantiations is possible even without imbuing the expected // ctype facet. _M_fill = _CharT(); _M_fill_init = false; _M_tie = 0; _M_exception = goodbit; _M_streambuf = __sb; _M_streambuf_state = __sb ? goodbit : badbit; } template void basic_ios<_CharT, _Traits>::_M_cache_locale(const locale& __loc) { if (__builtin_expect(has_facet<__ctype_type>(__loc), true)) _M_ctype = std::__addressof(use_facet<__ctype_type>(__loc)); else _M_ctype = 0; if (__builtin_expect(has_facet<__num_put_type>(__loc), true)) _M_num_put = std::__addressof(use_facet<__num_put_type>(__loc)); else _M_num_put = 0; if (__builtin_expect(has_facet<__num_get_type>(__loc), true)) _M_num_get = std::__addressof(use_facet<__num_get_type>(__loc)); else _M_num_get = 0; } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class basic_ios; #ifdef _GLIBCXX_USE_WCHAR_T extern template class basic_ios; #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!  8/bits/basic_string.hnu[// Components for manipulating sequences of characters -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/basic_string.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{string} */ // // ISO C++ 14882: 21 Strings library // #ifndef _BASIC_STRING_H #define _BASIC_STRING_H 1 #pragma GCC system_header #include #include #include #if __cplusplus >= 201103L #include #endif #if __cplusplus > 201402L # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if __cplusplus >= 201703L // Support P0426R1 changes to char_traits in C++17. # define __cpp_lib_constexpr_string 201611L #endif #if _GLIBCXX_USE_CXX11_ABI _GLIBCXX_BEGIN_NAMESPACE_CXX11 /** * @class basic_string basic_string.h * @brief Managing sequences of characters and character-like objects. * * @ingroup strings * @ingroup sequences * * @tparam _CharT Type of character * @tparam _Traits Traits for character type, defaults to * char_traits<_CharT>. * @tparam _Alloc Allocator type, defaults to allocator<_CharT>. * * Meets the requirements of a container, a * reversible container, and a * sequence. Of the * optional sequence requirements, only * @c push_back, @c at, and @c %array access are supported. */ template class basic_string { typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_CharT>::other _Char_alloc_type; typedef __gnu_cxx::__alloc_traits<_Char_alloc_type> _Alloc_traits; // Types: public: typedef _Traits traits_type; typedef typename _Traits::char_type value_type; typedef _Char_alloc_type allocator_type; typedef typename _Alloc_traits::size_type size_type; typedef typename _Alloc_traits::difference_type difference_type; typedef typename _Alloc_traits::reference reference; typedef typename _Alloc_traits::const_reference const_reference; typedef typename _Alloc_traits::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef __gnu_cxx::__normal_iterator iterator; typedef __gnu_cxx::__normal_iterator const_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; /// Value returned by various member functions when they fail. static const size_type npos = static_cast(-1); private: // type used for positions in insert, erase etc. #if __cplusplus < 201103L typedef iterator __const_iterator; #else typedef const_iterator __const_iterator; #endif #if __cplusplus > 201402L // A helper type for avoiding boiler-plate. typedef basic_string_view<_CharT, _Traits> __sv_type; template using _If_sv = enable_if_t< __and_, __not_>, __not_>>::value, _Res>; // Allows an implicit conversion to __sv_type. static __sv_type _S_to_string_view(__sv_type __svt) noexcept { return __svt; } // Wraps a string_view by explicit conversion and thus // allows to add an internal constructor that does not // participate in overload resolution when a string_view // is provided. struct __sv_wrapper { explicit __sv_wrapper(__sv_type __sv) noexcept : _M_sv(__sv) { } __sv_type _M_sv; }; #endif // Use empty-base optimization: http://www.cantrip.org/emptyopt.html struct _Alloc_hider : allocator_type // TODO check __is_final { #if __cplusplus < 201103L _Alloc_hider(pointer __dat, const _Alloc& __a = _Alloc()) : allocator_type(__a), _M_p(__dat) { } #else _Alloc_hider(pointer __dat, const _Alloc& __a) : allocator_type(__a), _M_p(__dat) { } _Alloc_hider(pointer __dat, _Alloc&& __a = _Alloc()) : allocator_type(std::move(__a)), _M_p(__dat) { } #endif pointer _M_p; // The actual data. }; _Alloc_hider _M_dataplus; size_type _M_string_length; enum { _S_local_capacity = 15 / sizeof(_CharT) }; union { _CharT _M_local_buf[_S_local_capacity + 1]; size_type _M_allocated_capacity; }; void _M_data(pointer __p) { _M_dataplus._M_p = __p; } void _M_length(size_type __length) { _M_string_length = __length; } pointer _M_data() const { return _M_dataplus._M_p; } pointer _M_local_data() { #if __cplusplus >= 201103L return std::pointer_traits::pointer_to(*_M_local_buf); #else return pointer(_M_local_buf); #endif } const_pointer _M_local_data() const { #if __cplusplus >= 201103L return std::pointer_traits::pointer_to(*_M_local_buf); #else return const_pointer(_M_local_buf); #endif } void _M_capacity(size_type __capacity) { _M_allocated_capacity = __capacity; } void _M_set_length(size_type __n) { _M_length(__n); traits_type::assign(_M_data()[__n], _CharT()); } bool _M_is_local() const { return _M_data() == _M_local_data(); } // Create & Destroy pointer _M_create(size_type&, size_type); void _M_dispose() { if (!_M_is_local()) _M_destroy(_M_allocated_capacity); } void _M_destroy(size_type __size) throw() { _Alloc_traits::deallocate(_M_get_allocator(), _M_data(), __size + 1); } // _M_construct_aux is used to implement the 21.3.1 para 15 which // requires special behaviour if _InIterator is an integral type template void _M_construct_aux(_InIterator __beg, _InIterator __end, std::__false_type) { typedef typename iterator_traits<_InIterator>::iterator_category _Tag; _M_construct(__beg, __end, _Tag()); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_construct_aux(_Integer __beg, _Integer __end, std::__true_type) { _M_construct_aux_2(static_cast(__beg), __end); } void _M_construct_aux_2(size_type __req, _CharT __c) { _M_construct(__req, __c); } template void _M_construct(_InIterator __beg, _InIterator __end) { typedef typename std::__is_integer<_InIterator>::__type _Integral; _M_construct_aux(__beg, __end, _Integral()); } // For Input Iterators, used in istreambuf_iterators, etc. template void _M_construct(_InIterator __beg, _InIterator __end, std::input_iterator_tag); // For forward_iterators up to random_access_iterators, used for // string::iterator, _CharT*, etc. template void _M_construct(_FwdIterator __beg, _FwdIterator __end, std::forward_iterator_tag); void _M_construct(size_type __req, _CharT __c); allocator_type& _M_get_allocator() { return _M_dataplus; } const allocator_type& _M_get_allocator() const { return _M_dataplus; } private: #ifdef _GLIBCXX_DISAMBIGUATE_REPLACE_INST // The explicit instantiations in misc-inst.cc require this due to // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64063 template::__value && !__are_same<_Tp, const _CharT*>::__value && !__are_same<_Tp, iterator>::__value && !__are_same<_Tp, const_iterator>::__value> struct __enable_if_not_native_iterator { typedef basic_string& __type; }; template struct __enable_if_not_native_iterator<_Tp, false> { }; #endif size_type _M_check(size_type __pos, const char* __s) const { if (__pos > this->size()) __throw_out_of_range_fmt(__N("%s: __pos (which is %zu) > " "this->size() (which is %zu)"), __s, __pos, this->size()); return __pos; } void _M_check_length(size_type __n1, size_type __n2, const char* __s) const { if (this->max_size() - (this->size() - __n1) < __n2) __throw_length_error(__N(__s)); } // NB: _M_limit doesn't check for a bad __pos value. size_type _M_limit(size_type __pos, size_type __off) const _GLIBCXX_NOEXCEPT { const bool __testoff = __off < this->size() - __pos; return __testoff ? __off : this->size() - __pos; } // True if _Rep and source do not overlap. bool _M_disjunct(const _CharT* __s) const _GLIBCXX_NOEXCEPT { return (less()(__s, _M_data()) || less()(_M_data() + this->size(), __s)); } // When __n = 1 way faster than the general multichar // traits_type::copy/move/assign. static void _S_copy(_CharT* __d, const _CharT* __s, size_type __n) { if (__n == 1) traits_type::assign(*__d, *__s); else traits_type::copy(__d, __s, __n); } static void _S_move(_CharT* __d, const _CharT* __s, size_type __n) { if (__n == 1) traits_type::assign(*__d, *__s); else traits_type::move(__d, __s, __n); } static void _S_assign(_CharT* __d, size_type __n, _CharT __c) { if (__n == 1) traits_type::assign(*__d, __c); else traits_type::assign(__d, __n, __c); } // _S_copy_chars is a separate template to permit specialization // to optimize for the common case of pointers as iterators. template static void _S_copy_chars(_CharT* __p, _Iterator __k1, _Iterator __k2) { for (; __k1 != __k2; ++__k1, (void)++__p) traits_type::assign(*__p, *__k1); // These types are off. } static void _S_copy_chars(_CharT* __p, iterator __k1, iterator __k2) _GLIBCXX_NOEXCEPT { _S_copy_chars(__p, __k1.base(), __k2.base()); } static void _S_copy_chars(_CharT* __p, const_iterator __k1, const_iterator __k2) _GLIBCXX_NOEXCEPT { _S_copy_chars(__p, __k1.base(), __k2.base()); } static void _S_copy_chars(_CharT* __p, _CharT* __k1, _CharT* __k2) _GLIBCXX_NOEXCEPT { _S_copy(__p, __k1, __k2 - __k1); } static void _S_copy_chars(_CharT* __p, const _CharT* __k1, const _CharT* __k2) _GLIBCXX_NOEXCEPT { _S_copy(__p, __k1, __k2 - __k1); } static int _S_compare(size_type __n1, size_type __n2) _GLIBCXX_NOEXCEPT { const difference_type __d = difference_type(__n1 - __n2); if (__d > __gnu_cxx::__numeric_traits::__max) return __gnu_cxx::__numeric_traits::__max; else if (__d < __gnu_cxx::__numeric_traits::__min) return __gnu_cxx::__numeric_traits::__min; else return int(__d); } void _M_assign(const basic_string&); void _M_mutate(size_type __pos, size_type __len1, const _CharT* __s, size_type __len2); void _M_erase(size_type __pos, size_type __n); public: // Construct/copy/destroy: // NB: We overload ctors in some cases instead of using default // arguments, per 17.4.4.4 para. 2 item 2. /** * @brief Default constructor creates an empty string. */ basic_string() _GLIBCXX_NOEXCEPT_IF(is_nothrow_default_constructible<_Alloc>::value) : _M_dataplus(_M_local_data()) { _M_set_length(0); } /** * @brief Construct an empty string using allocator @a a. */ explicit basic_string(const _Alloc& __a) _GLIBCXX_NOEXCEPT : _M_dataplus(_M_local_data(), __a) { _M_set_length(0); } /** * @brief Construct string with copy of value of @a __str. * @param __str Source string. */ basic_string(const basic_string& __str) : _M_dataplus(_M_local_data(), _Alloc_traits::_S_select_on_copy(__str._M_get_allocator())) { _M_construct(__str._M_data(), __str._M_data() + __str.length()); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2583. no way to supply an allocator for basic_string(str, pos) /** * @brief Construct string as copy of a substring. * @param __str Source string. * @param __pos Index of first character to copy from. * @param __a Allocator to use. */ basic_string(const basic_string& __str, size_type __pos, const _Alloc& __a = _Alloc()) : _M_dataplus(_M_local_data(), __a) { const _CharT* __start = __str._M_data() + __str._M_check(__pos, "basic_string::basic_string"); _M_construct(__start, __start + __str._M_limit(__pos, npos)); } /** * @brief Construct string as copy of a substring. * @param __str Source string. * @param __pos Index of first character to copy from. * @param __n Number of characters to copy. */ basic_string(const basic_string& __str, size_type __pos, size_type __n) : _M_dataplus(_M_local_data()) { const _CharT* __start = __str._M_data() + __str._M_check(__pos, "basic_string::basic_string"); _M_construct(__start, __start + __str._M_limit(__pos, __n)); } /** * @brief Construct string as copy of a substring. * @param __str Source string. * @param __pos Index of first character to copy from. * @param __n Number of characters to copy. * @param __a Allocator to use. */ basic_string(const basic_string& __str, size_type __pos, size_type __n, const _Alloc& __a) : _M_dataplus(_M_local_data(), __a) { const _CharT* __start = __str._M_data() + __str._M_check(__pos, "string::string"); _M_construct(__start, __start + __str._M_limit(__pos, __n)); } /** * @brief Construct string initialized by a character %array. * @param __s Source character %array. * @param __n Number of characters to copy. * @param __a Allocator to use (default is default allocator). * * NB: @a __s must have at least @a __n characters, '\\0' * has no special meaning. */ basic_string(const _CharT* __s, size_type __n, const _Alloc& __a = _Alloc()) : _M_dataplus(_M_local_data(), __a) { _M_construct(__s, __s + __n); } /** * @brief Construct string as copy of a C string. * @param __s Source C string. * @param __a Allocator to use (default is default allocator). */ #if __cpp_deduction_guides && ! defined _GLIBCXX_DEFINING_STRING_INSTANTIATIONS // _GLIBCXX_RESOLVE_LIB_DEFECTS // 3076. basic_string CTAD ambiguity template> #endif basic_string(const _CharT* __s, const _Alloc& __a = _Alloc()) : _M_dataplus(_M_local_data(), __a) { _M_construct(__s, __s ? __s + traits_type::length(__s) : __s+npos); } /** * @brief Construct string as multiple characters. * @param __n Number of characters. * @param __c Character to use. * @param __a Allocator to use (default is default allocator). */ #if __cpp_deduction_guides && ! defined _GLIBCXX_DEFINING_STRING_INSTANTIATIONS // _GLIBCXX_RESOLVE_LIB_DEFECTS // 3076. basic_string CTAD ambiguity template> #endif basic_string(size_type __n, _CharT __c, const _Alloc& __a = _Alloc()) : _M_dataplus(_M_local_data(), __a) { _M_construct(__n, __c); } #if __cplusplus >= 201103L /** * @brief Move construct string. * @param __str Source string. * * The newly-created string contains the exact contents of @a __str. * @a __str is a valid, but unspecified string. **/ basic_string(basic_string&& __str) noexcept : _M_dataplus(_M_local_data(), std::move(__str._M_get_allocator())) { if (__str._M_is_local()) { traits_type::copy(_M_local_buf, __str._M_local_buf, _S_local_capacity + 1); } else { _M_data(__str._M_data()); _M_capacity(__str._M_allocated_capacity); } // Must use _M_length() here not _M_set_length() because // basic_stringbuf relies on writing into unallocated capacity so // we mess up the contents if we put a '\0' in the string. _M_length(__str.length()); __str._M_data(__str._M_local_data()); __str._M_set_length(0); } /** * @brief Construct string from an initializer %list. * @param __l std::initializer_list of characters. * @param __a Allocator to use (default is default allocator). */ basic_string(initializer_list<_CharT> __l, const _Alloc& __a = _Alloc()) : _M_dataplus(_M_local_data(), __a) { _M_construct(__l.begin(), __l.end()); } basic_string(const basic_string& __str, const _Alloc& __a) : _M_dataplus(_M_local_data(), __a) { _M_construct(__str.begin(), __str.end()); } basic_string(basic_string&& __str, const _Alloc& __a) noexcept(_Alloc_traits::_S_always_equal()) : _M_dataplus(_M_local_data(), __a) { if (__str._M_is_local()) { traits_type::copy(_M_local_buf, __str._M_local_buf, _S_local_capacity + 1); _M_length(__str.length()); __str._M_set_length(0); } else if (_Alloc_traits::_S_always_equal() || __str.get_allocator() == __a) { _M_data(__str._M_data()); _M_length(__str.length()); _M_capacity(__str._M_allocated_capacity); __str._M_data(__str._M_local_buf); __str._M_set_length(0); } else _M_construct(__str.begin(), __str.end()); } #endif // C++11 /** * @brief Construct string as copy of a range. * @param __beg Start of range. * @param __end End of range. * @param __a Allocator to use (default is default allocator). */ #if __cplusplus >= 201103L template> #else template #endif basic_string(_InputIterator __beg, _InputIterator __end, const _Alloc& __a = _Alloc()) : _M_dataplus(_M_local_data(), __a) { _M_construct(__beg, __end); } #if __cplusplus > 201402L /** * @brief Construct string from a substring of a string_view. * @param __t Source object convertible to string view. * @param __pos The index of the first character to copy from __t. * @param __n The number of characters to copy from __t. * @param __a Allocator to use. */ template> basic_string(const _Tp& __t, size_type __pos, size_type __n, const _Alloc& __a = _Alloc()) : basic_string(_S_to_string_view(__t).substr(__pos, __n), __a) { } /** * @brief Construct string from a string_view. * @param __t Source object convertible to string view. * @param __a Allocator to use (default is default allocator). */ template> explicit basic_string(const _Tp& __t, const _Alloc& __a = _Alloc()) : basic_string(__sv_wrapper(_S_to_string_view(__t)), __a) { } /** * @brief Only internally used: Construct string from a string view * wrapper. * @param __svw string view wrapper. * @param __a Allocator to use. */ explicit basic_string(__sv_wrapper __svw, const _Alloc& __a) : basic_string(__svw._M_sv.data(), __svw._M_sv.size(), __a) { } #endif // C++17 /** * @brief Destroy the string instance. */ ~basic_string() { _M_dispose(); } /** * @brief Assign the value of @a str to this string. * @param __str Source string. */ basic_string& operator=(const basic_string& __str) { #if __cplusplus >= 201103L if (_Alloc_traits::_S_propagate_on_copy_assign()) { if (!_Alloc_traits::_S_always_equal() && !_M_is_local() && _M_get_allocator() != __str._M_get_allocator()) { // Propagating allocator cannot free existing storage so must // deallocate it before replacing current allocator. if (__str.size() <= _S_local_capacity) { _M_destroy(_M_allocated_capacity); _M_data(_M_local_data()); _M_set_length(0); } else { const auto __len = __str.size(); auto __alloc = __str._M_get_allocator(); // If this allocation throws there are no effects: auto __ptr = _Alloc_traits::allocate(__alloc, __len + 1); _M_destroy(_M_allocated_capacity); _M_data(__ptr); _M_capacity(__len); _M_set_length(__len); } } std::__alloc_on_copy(_M_get_allocator(), __str._M_get_allocator()); } #endif return this->assign(__str); } /** * @brief Copy contents of @a s into this string. * @param __s Source null-terminated string. */ basic_string& operator=(const _CharT* __s) { return this->assign(__s); } /** * @brief Set value to string of length 1. * @param __c Source character. * * Assigning to a character makes this string length 1 and * (*this)[0] == @a c. */ basic_string& operator=(_CharT __c) { this->assign(1, __c); return *this; } #if __cplusplus >= 201103L /** * @brief Move assign the value of @a str to this string. * @param __str Source string. * * The contents of @a str are moved into this string (without copying). * @a str is a valid, but unspecified string. **/ // PR 58265, this should be noexcept. // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2063. Contradictory requirements for string move assignment basic_string& operator=(basic_string&& __str) noexcept(_Alloc_traits::_S_nothrow_move()) { if (!_M_is_local() && _Alloc_traits::_S_propagate_on_move_assign() && !_Alloc_traits::_S_always_equal() && _M_get_allocator() != __str._M_get_allocator()) { // Destroy existing storage before replacing allocator. _M_destroy(_M_allocated_capacity); _M_data(_M_local_data()); _M_set_length(0); } // Replace allocator if POCMA is true. std::__alloc_on_move(_M_get_allocator(), __str._M_get_allocator()); if (__str._M_is_local()) { // We've always got room for a short string, just copy it. if (__str.size()) this->_S_copy(_M_data(), __str._M_data(), __str.size()); _M_set_length(__str.size()); } else if (_Alloc_traits::_S_propagate_on_move_assign() || _Alloc_traits::_S_always_equal() || _M_get_allocator() == __str._M_get_allocator()) { // Just move the allocated pointer, our allocator can free it. pointer __data = nullptr; size_type __capacity; if (!_M_is_local()) { if (_Alloc_traits::_S_always_equal()) { // __str can reuse our existing storage. __data = _M_data(); __capacity = _M_allocated_capacity; } else // __str can't use it, so free it. _M_destroy(_M_allocated_capacity); } _M_data(__str._M_data()); _M_length(__str.length()); _M_capacity(__str._M_allocated_capacity); if (__data) { __str._M_data(__data); __str._M_capacity(__capacity); } else __str._M_data(__str._M_local_buf); } else // Need to do a deep copy assign(__str); __str.clear(); return *this; } /** * @brief Set value to string constructed from initializer %list. * @param __l std::initializer_list. */ basic_string& operator=(initializer_list<_CharT> __l) { this->assign(__l.begin(), __l.size()); return *this; } #endif // C++11 #if __cplusplus > 201402L /** * @brief Set value to string constructed from a string_view. * @param __svt An object convertible to string_view. */ template _If_sv<_Tp, basic_string&> operator=(const _Tp& __svt) { return this->assign(__svt); } /** * @brief Convert to a string_view. * @return A string_view. */ operator __sv_type() const noexcept { return __sv_type(data(), size()); } #endif // C++17 // Iterators: /** * Returns a read/write iterator that points to the first character in * the %string. */ iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_M_data()); } /** * Returns a read-only (constant) iterator that points to the first * character in the %string. */ const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_M_data()); } /** * Returns a read/write iterator that points one past the last * character in the %string. */ iterator end() _GLIBCXX_NOEXCEPT { return iterator(_M_data() + this->size()); } /** * Returns a read-only (constant) iterator that points one past the * last character in the %string. */ const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_M_data() + this->size()); } /** * Returns a read/write reverse iterator that points to the last * character in the %string. Iteration is done in reverse element * order. */ reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(this->end()); } /** * Returns a read-only (constant) reverse iterator that points * to the last character in the %string. Iteration is done in * reverse element order. */ const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(this->end()); } /** * Returns a read/write reverse iterator that points to one before the * first character in the %string. Iteration is done in reverse * element order. */ reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(this->begin()); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first character in the %string. Iteration * is done in reverse element order. */ const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(this->begin()); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the first * character in the %string. */ const_iterator cbegin() const noexcept { return const_iterator(this->_M_data()); } /** * Returns a read-only (constant) iterator that points one past the * last character in the %string. */ const_iterator cend() const noexcept { return const_iterator(this->_M_data() + this->size()); } /** * Returns a read-only (constant) reverse iterator that points * to the last character in the %string. Iteration is done in * reverse element order. */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(this->end()); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first character in the %string. Iteration * is done in reverse element order. */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(this->begin()); } #endif public: // Capacity: /// Returns the number of characters in the string, not including any /// null-termination. size_type size() const _GLIBCXX_NOEXCEPT { return _M_string_length; } /// Returns the number of characters in the string, not including any /// null-termination. size_type length() const _GLIBCXX_NOEXCEPT { return _M_string_length; } /// Returns the size() of the largest possible %string. size_type max_size() const _GLIBCXX_NOEXCEPT { return (_Alloc_traits::max_size(_M_get_allocator()) - 1) / 2; } /** * @brief Resizes the %string to the specified number of characters. * @param __n Number of characters the %string should contain. * @param __c Character to fill any new elements. * * This function will %resize the %string to the specified * number of characters. If the number is smaller than the * %string's current size the %string is truncated, otherwise * the %string is extended and new elements are %set to @a __c. */ void resize(size_type __n, _CharT __c); /** * @brief Resizes the %string to the specified number of characters. * @param __n Number of characters the %string should contain. * * This function will resize the %string to the specified length. If * the new size is smaller than the %string's current size the %string * is truncated, otherwise the %string is extended and new characters * are default-constructed. For basic types such as char, this means * setting them to 0. */ void resize(size_type __n) { this->resize(__n, _CharT()); } #if __cplusplus >= 201103L /// A non-binding request to reduce capacity() to size(). void shrink_to_fit() noexcept { #if __cpp_exceptions if (capacity() > size()) { try { reserve(0); } catch(...) { } } #endif } #endif /** * Returns the total number of characters that the %string can hold * before needing to allocate more memory. */ size_type capacity() const _GLIBCXX_NOEXCEPT { return _M_is_local() ? size_type(_S_local_capacity) : _M_allocated_capacity; } /** * @brief Attempt to preallocate enough memory for specified number of * characters. * @param __res_arg Number of characters required. * @throw std::length_error If @a __res_arg exceeds @c max_size(). * * This function attempts to reserve enough memory for the * %string to hold the specified number of characters. If the * number requested is more than max_size(), length_error is * thrown. * * The advantage of this function is that if optimal code is a * necessity and the user can determine the string length that will be * required, the user can reserve the memory in %advance, and thus * prevent a possible reallocation of memory and copying of %string * data. */ void reserve(size_type __res_arg = 0); /** * Erases the string, making it empty. */ void clear() _GLIBCXX_NOEXCEPT { _M_set_length(0); } /** * Returns true if the %string is empty. Equivalent to * *this == "". */ bool empty() const _GLIBCXX_NOEXCEPT { return this->size() == 0; } // Element access: /** * @brief Subscript access to the data contained in the %string. * @param __pos The index of the character to access. * @return Read-only (constant) reference to the character. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ const_reference operator[] (size_type __pos) const _GLIBCXX_NOEXCEPT { __glibcxx_assert(__pos <= size()); return _M_data()[__pos]; } /** * @brief Subscript access to the data contained in the %string. * @param __pos The index of the character to access. * @return Read/write reference to the character. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ reference operator[](size_type __pos) { // Allow pos == size() both in C++98 mode, as v3 extension, // and in C++11 mode. __glibcxx_assert(__pos <= size()); // In pedantic mode be strict in C++98 mode. _GLIBCXX_DEBUG_PEDASSERT(__cplusplus >= 201103L || __pos < size()); return _M_data()[__pos]; } /** * @brief Provides access to the data contained in the %string. * @param __n The index of the character to access. * @return Read-only (const) reference to the character. * @throw std::out_of_range If @a n is an invalid index. * * This function provides for safer data access. The parameter is * first checked that it is in the range of the string. The function * throws out_of_range if the check fails. */ const_reference at(size_type __n) const { if (__n >= this->size()) __throw_out_of_range_fmt(__N("basic_string::at: __n " "(which is %zu) >= this->size() " "(which is %zu)"), __n, this->size()); return _M_data()[__n]; } /** * @brief Provides access to the data contained in the %string. * @param __n The index of the character to access. * @return Read/write reference to the character. * @throw std::out_of_range If @a n is an invalid index. * * This function provides for safer data access. The parameter is * first checked that it is in the range of the string. The function * throws out_of_range if the check fails. */ reference at(size_type __n) { if (__n >= size()) __throw_out_of_range_fmt(__N("basic_string::at: __n " "(which is %zu) >= this->size() " "(which is %zu)"), __n, this->size()); return _M_data()[__n]; } #if __cplusplus >= 201103L /** * Returns a read/write reference to the data at the first * element of the %string. */ reference front() noexcept { __glibcxx_assert(!empty()); return operator[](0); } /** * Returns a read-only (constant) reference to the data at the first * element of the %string. */ const_reference front() const noexcept { __glibcxx_assert(!empty()); return operator[](0); } /** * Returns a read/write reference to the data at the last * element of the %string. */ reference back() noexcept { __glibcxx_assert(!empty()); return operator[](this->size() - 1); } /** * Returns a read-only (constant) reference to the data at the * last element of the %string. */ const_reference back() const noexcept { __glibcxx_assert(!empty()); return operator[](this->size() - 1); } #endif // Modifiers: /** * @brief Append a string to this string. * @param __str The string to append. * @return Reference to this string. */ basic_string& operator+=(const basic_string& __str) { return this->append(__str); } /** * @brief Append a C string. * @param __s The C string to append. * @return Reference to this string. */ basic_string& operator+=(const _CharT* __s) { return this->append(__s); } /** * @brief Append a character. * @param __c The character to append. * @return Reference to this string. */ basic_string& operator+=(_CharT __c) { this->push_back(__c); return *this; } #if __cplusplus >= 201103L /** * @brief Append an initializer_list of characters. * @param __l The initializer_list of characters to be appended. * @return Reference to this string. */ basic_string& operator+=(initializer_list<_CharT> __l) { return this->append(__l.begin(), __l.size()); } #endif // C++11 #if __cplusplus > 201402L /** * @brief Append a string_view. * @param __svt An object convertible to string_view to be appended. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> operator+=(const _Tp& __svt) { return this->append(__svt); } #endif // C++17 /** * @brief Append a string to this string. * @param __str The string to append. * @return Reference to this string. */ basic_string& append(const basic_string& __str) { return _M_append(__str._M_data(), __str.size()); } /** * @brief Append a substring. * @param __str The string to append. * @param __pos Index of the first character of str to append. * @param __n The number of characters to append. * @return Reference to this string. * @throw std::out_of_range if @a __pos is not a valid index. * * This function appends @a __n characters from @a __str * starting at @a __pos to this string. If @a __n is is larger * than the number of available characters in @a __str, the * remainder of @a __str is appended. */ basic_string& append(const basic_string& __str, size_type __pos, size_type __n = npos) { return _M_append(__str._M_data() + __str._M_check(__pos, "basic_string::append"), __str._M_limit(__pos, __n)); } /** * @brief Append a C substring. * @param __s The C string to append. * @param __n The number of characters to append. * @return Reference to this string. */ basic_string& append(const _CharT* __s, size_type __n) { __glibcxx_requires_string_len(__s, __n); _M_check_length(size_type(0), __n, "basic_string::append"); return _M_append(__s, __n); } /** * @brief Append a C string. * @param __s The C string to append. * @return Reference to this string. */ basic_string& append(const _CharT* __s) { __glibcxx_requires_string(__s); const size_type __n = traits_type::length(__s); _M_check_length(size_type(0), __n, "basic_string::append"); return _M_append(__s, __n); } /** * @brief Append multiple characters. * @param __n The number of characters to append. * @param __c The character to use. * @return Reference to this string. * * Appends __n copies of __c to this string. */ basic_string& append(size_type __n, _CharT __c) { return _M_replace_aux(this->size(), size_type(0), __n, __c); } #if __cplusplus >= 201103L /** * @brief Append an initializer_list of characters. * @param __l The initializer_list of characters to append. * @return Reference to this string. */ basic_string& append(initializer_list<_CharT> __l) { return this->append(__l.begin(), __l.size()); } #endif // C++11 /** * @brief Append a range of characters. * @param __first Iterator referencing the first character to append. * @param __last Iterator marking the end of the range. * @return Reference to this string. * * Appends characters in the range [__first,__last) to this string. */ #if __cplusplus >= 201103L template> #else template #endif basic_string& append(_InputIterator __first, _InputIterator __last) { return this->replace(end(), end(), __first, __last); } #if __cplusplus > 201402L /** * @brief Append a string_view. * @param __svt An object convertible to string_view to be appended. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> append(const _Tp& __svt) { __sv_type __sv = __svt; return this->append(__sv.data(), __sv.size()); } /** * @brief Append a range of characters from a string_view. * @param __svt An object convertible to string_view to be appended from. * @param __pos The position in the string_view to append from. * @param __n The number of characters to append from the string_view. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> append(const _Tp& __svt, size_type __pos, size_type __n = npos) { __sv_type __sv = __svt; return _M_append(__sv.data() + __sv._M_check(__pos, "basic_string::append"), __sv._M_limit(__pos, __n)); } #endif // C++17 /** * @brief Append a single character. * @param __c Character to append. */ void push_back(_CharT __c) { const size_type __size = this->size(); if (__size + 1 > this->capacity()) this->_M_mutate(__size, size_type(0), 0, size_type(1)); traits_type::assign(this->_M_data()[__size], __c); this->_M_set_length(__size + 1); } /** * @brief Set value to contents of another string. * @param __str Source string to use. * @return Reference to this string. */ basic_string& assign(const basic_string& __str) { this->_M_assign(__str); return *this; } #if __cplusplus >= 201103L /** * @brief Set value to contents of another string. * @param __str Source string to use. * @return Reference to this string. * * This function sets this string to the exact contents of @a __str. * @a __str is a valid, but unspecified string. */ basic_string& assign(basic_string&& __str) noexcept(_Alloc_traits::_S_nothrow_move()) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2063. Contradictory requirements for string move assignment return *this = std::move(__str); } #endif // C++11 /** * @brief Set value to a substring of a string. * @param __str The string to use. * @param __pos Index of the first character of str. * @param __n Number of characters to use. * @return Reference to this string. * @throw std::out_of_range if @a pos is not a valid index. * * This function sets this string to the substring of @a __str * consisting of @a __n characters at @a __pos. If @a __n is * is larger than the number of available characters in @a * __str, the remainder of @a __str is used. */ basic_string& assign(const basic_string& __str, size_type __pos, size_type __n = npos) { return _M_replace(size_type(0), this->size(), __str._M_data() + __str._M_check(__pos, "basic_string::assign"), __str._M_limit(__pos, __n)); } /** * @brief Set value to a C substring. * @param __s The C string to use. * @param __n Number of characters to use. * @return Reference to this string. * * This function sets the value of this string to the first @a __n * characters of @a __s. If @a __n is is larger than the number of * available characters in @a __s, the remainder of @a __s is used. */ basic_string& assign(const _CharT* __s, size_type __n) { __glibcxx_requires_string_len(__s, __n); return _M_replace(size_type(0), this->size(), __s, __n); } /** * @brief Set value to contents of a C string. * @param __s The C string to use. * @return Reference to this string. * * This function sets the value of this string to the value of @a __s. * The data is copied, so there is no dependence on @a __s once the * function returns. */ basic_string& assign(const _CharT* __s) { __glibcxx_requires_string(__s); return _M_replace(size_type(0), this->size(), __s, traits_type::length(__s)); } /** * @brief Set value to multiple characters. * @param __n Length of the resulting string. * @param __c The character to use. * @return Reference to this string. * * This function sets the value of this string to @a __n copies of * character @a __c. */ basic_string& assign(size_type __n, _CharT __c) { return _M_replace_aux(size_type(0), this->size(), __n, __c); } /** * @brief Set value to a range of characters. * @param __first Iterator referencing the first character to append. * @param __last Iterator marking the end of the range. * @return Reference to this string. * * Sets value of string to characters in the range [__first,__last). */ #if __cplusplus >= 201103L template> #else template #endif basic_string& assign(_InputIterator __first, _InputIterator __last) { return this->replace(begin(), end(), __first, __last); } #if __cplusplus >= 201103L /** * @brief Set value to an initializer_list of characters. * @param __l The initializer_list of characters to assign. * @return Reference to this string. */ basic_string& assign(initializer_list<_CharT> __l) { return this->assign(__l.begin(), __l.size()); } #endif // C++11 #if __cplusplus > 201402L /** * @brief Set value from a string_view. * @param __svt The source object convertible to string_view. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> assign(const _Tp& __svt) { __sv_type __sv = __svt; return this->assign(__sv.data(), __sv.size()); } /** * @brief Set value from a range of characters in a string_view. * @param __svt The source object convertible to string_view. * @param __pos The position in the string_view to assign from. * @param __n The number of characters to assign. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> assign(const _Tp& __svt, size_type __pos, size_type __n = npos) { __sv_type __sv = __svt; return _M_replace(size_type(0), this->size(), __sv.data() + __sv._M_check(__pos, "basic_string::assign"), __sv._M_limit(__pos, __n)); } #endif // C++17 #if __cplusplus >= 201103L /** * @brief Insert multiple characters. * @param __p Const_iterator referencing location in string to * insert at. * @param __n Number of characters to insert * @param __c The character to insert. * @return Iterator referencing the first inserted char. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts @a __n copies of character @a __c starting at the * position referenced by iterator @a __p. If adding * characters causes the length to exceed max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ iterator insert(const_iterator __p, size_type __n, _CharT __c) { _GLIBCXX_DEBUG_PEDASSERT(__p >= begin() && __p <= end()); const size_type __pos = __p - begin(); this->replace(__p, __p, __n, __c); return iterator(this->_M_data() + __pos); } #else /** * @brief Insert multiple characters. * @param __p Iterator referencing location in string to insert at. * @param __n Number of characters to insert * @param __c The character to insert. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts @a __n copies of character @a __c starting at the * position referenced by iterator @a __p. If adding * characters causes the length to exceed max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ void insert(iterator __p, size_type __n, _CharT __c) { this->replace(__p, __p, __n, __c); } #endif #if __cplusplus >= 201103L /** * @brief Insert a range of characters. * @param __p Const_iterator referencing location in string to * insert at. * @param __beg Start of range. * @param __end End of range. * @return Iterator referencing the first inserted char. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts characters in range [beg,end). If adding characters * causes the length to exceed max_size(), length_error is * thrown. The value of the string doesn't change if an error * is thrown. */ template> iterator insert(const_iterator __p, _InputIterator __beg, _InputIterator __end) { _GLIBCXX_DEBUG_PEDASSERT(__p >= begin() && __p <= end()); const size_type __pos = __p - begin(); this->replace(__p, __p, __beg, __end); return iterator(this->_M_data() + __pos); } #else /** * @brief Insert a range of characters. * @param __p Iterator referencing location in string to insert at. * @param __beg Start of range. * @param __end End of range. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts characters in range [__beg,__end). If adding * characters causes the length to exceed max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ template void insert(iterator __p, _InputIterator __beg, _InputIterator __end) { this->replace(__p, __p, __beg, __end); } #endif #if __cplusplus >= 201103L /** * @brief Insert an initializer_list of characters. * @param __p Iterator referencing location in string to insert at. * @param __l The initializer_list of characters to insert. * @throw std::length_error If new length exceeds @c max_size(). */ void insert(iterator __p, initializer_list<_CharT> __l) { _GLIBCXX_DEBUG_PEDASSERT(__p >= begin() && __p <= end()); this->insert(__p - begin(), __l.begin(), __l.size()); } #endif // C++11 /** * @brief Insert value of a string. * @param __pos1 Iterator referencing location in string to insert at. * @param __str The string to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts value of @a __str starting at @a __pos1. If adding * characters causes the length to exceed max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& insert(size_type __pos1, const basic_string& __str) { return this->replace(__pos1, size_type(0), __str._M_data(), __str.size()); } /** * @brief Insert a substring. * @param __pos1 Iterator referencing location in string to insert at. * @param __str The string to insert. * @param __pos2 Start of characters in str to insert. * @param __n Number of characters to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a pos1 > size() or * @a __pos2 > @a str.size(). * * Starting at @a pos1, insert @a __n character of @a __str * beginning with @a __pos2. If adding characters causes the * length to exceed max_size(), length_error is thrown. If @a * __pos1 is beyond the end of this string or @a __pos2 is * beyond the end of @a __str, out_of_range is thrown. The * value of the string doesn't change if an error is thrown. */ basic_string& insert(size_type __pos1, const basic_string& __str, size_type __pos2, size_type __n = npos) { return this->replace(__pos1, size_type(0), __str._M_data() + __str._M_check(__pos2, "basic_string::insert"), __str._M_limit(__pos2, __n)); } /** * @brief Insert a C substring. * @param __pos Iterator referencing location in string to insert at. * @param __s The C string to insert. * @param __n The number of characters to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a __pos is beyond the end of this * string. * * Inserts the first @a __n characters of @a __s starting at @a * __pos. If adding characters causes the length to exceed * max_size(), length_error is thrown. If @a __pos is beyond * end(), out_of_range is thrown. The value of the string * doesn't change if an error is thrown. */ basic_string& insert(size_type __pos, const _CharT* __s, size_type __n) { return this->replace(__pos, size_type(0), __s, __n); } /** * @brief Insert a C string. * @param __pos Iterator referencing location in string to insert at. * @param __s The C string to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a pos is beyond the end of this * string. * * Inserts the first @a n characters of @a __s starting at @a __pos. If * adding characters causes the length to exceed max_size(), * length_error is thrown. If @a __pos is beyond end(), out_of_range is * thrown. The value of the string doesn't change if an error is * thrown. */ basic_string& insert(size_type __pos, const _CharT* __s) { __glibcxx_requires_string(__s); return this->replace(__pos, size_type(0), __s, traits_type::length(__s)); } /** * @brief Insert multiple characters. * @param __pos Index in string to insert at. * @param __n Number of characters to insert * @param __c The character to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a __pos is beyond the end of this * string. * * Inserts @a __n copies of character @a __c starting at index * @a __pos. If adding characters causes the length to exceed * max_size(), length_error is thrown. If @a __pos > length(), * out_of_range is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& insert(size_type __pos, size_type __n, _CharT __c) { return _M_replace_aux(_M_check(__pos, "basic_string::insert"), size_type(0), __n, __c); } /** * @brief Insert one character. * @param __p Iterator referencing position in string to insert at. * @param __c The character to insert. * @return Iterator referencing newly inserted char. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts character @a __c at position referenced by @a __p. * If adding character causes the length to exceed max_size(), * length_error is thrown. If @a __p is beyond end of string, * out_of_range is thrown. The value of the string doesn't * change if an error is thrown. */ iterator insert(__const_iterator __p, _CharT __c) { _GLIBCXX_DEBUG_PEDASSERT(__p >= begin() && __p <= end()); const size_type __pos = __p - begin(); _M_replace_aux(__pos, size_type(0), size_type(1), __c); return iterator(_M_data() + __pos); } #if __cplusplus > 201402L /** * @brief Insert a string_view. * @param __pos Iterator referencing position in string to insert at. * @param __svt The object convertible to string_view to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> insert(size_type __pos, const _Tp& __svt) { __sv_type __sv = __svt; return this->insert(__pos, __sv.data(), __sv.size()); } /** * @brief Insert a string_view. * @param __pos Iterator referencing position in string to insert at. * @param __svt The object convertible to string_view to insert from. * @param __pos Iterator referencing position in string_view to insert * from. * @param __n The number of characters to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> insert(size_type __pos1, const _Tp& __svt, size_type __pos2, size_type __n = npos) { __sv_type __sv = __svt; return this->replace(__pos1, size_type(0), __sv.data() + __sv._M_check(__pos2, "basic_string::insert"), __sv._M_limit(__pos2, __n)); } #endif // C++17 /** * @brief Remove characters. * @param __pos Index of first character to remove (default 0). * @param __n Number of characters to remove (default remainder). * @return Reference to this string. * @throw std::out_of_range If @a pos is beyond the end of this * string. * * Removes @a __n characters from this string starting at @a * __pos. The length of the string is reduced by @a __n. If * there are < @a __n characters to remove, the remainder of * the string is truncated. If @a __p is beyond end of string, * out_of_range is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& erase(size_type __pos = 0, size_type __n = npos) { _M_check(__pos, "basic_string::erase"); if (__n == npos) this->_M_set_length(__pos); else if (__n != 0) this->_M_erase(__pos, _M_limit(__pos, __n)); return *this; } /** * @brief Remove one character. * @param __position Iterator referencing the character to remove. * @return iterator referencing same location after removal. * * Removes the character at @a __position from this string. The value * of the string doesn't change if an error is thrown. */ iterator erase(__const_iterator __position) { _GLIBCXX_DEBUG_PEDASSERT(__position >= begin() && __position < end()); const size_type __pos = __position - begin(); this->_M_erase(__pos, size_type(1)); return iterator(_M_data() + __pos); } /** * @brief Remove a range of characters. * @param __first Iterator referencing the first character to remove. * @param __last Iterator referencing the end of the range. * @return Iterator referencing location of first after removal. * * Removes the characters in the range [first,last) from this string. * The value of the string doesn't change if an error is thrown. */ iterator erase(__const_iterator __first, __const_iterator __last) { _GLIBCXX_DEBUG_PEDASSERT(__first >= begin() && __first <= __last && __last <= end()); const size_type __pos = __first - begin(); if (__last == end()) this->_M_set_length(__pos); else this->_M_erase(__pos, __last - __first); return iterator(this->_M_data() + __pos); } #if __cplusplus >= 201103L /** * @brief Remove the last character. * * The string must be non-empty. */ void pop_back() noexcept { __glibcxx_assert(!empty()); _M_erase(size() - 1, 1); } #endif // C++11 /** * @brief Replace characters with value from another string. * @param __pos Index of first character to replace. * @param __n Number of characters to be replaced. * @param __str String to insert. * @return Reference to this string. * @throw std::out_of_range If @a pos is beyond the end of this * string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos,__pos+__n) from * this string. In place, the value of @a __str is inserted. * If @a __pos is beyond end of string, out_of_range is thrown. * If the length of the result exceeds max_size(), length_error * is thrown. The value of the string doesn't change if an * error is thrown. */ basic_string& replace(size_type __pos, size_type __n, const basic_string& __str) { return this->replace(__pos, __n, __str._M_data(), __str.size()); } /** * @brief Replace characters with value from another string. * @param __pos1 Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __str String to insert. * @param __pos2 Index of first character of str to use. * @param __n2 Number of characters from str to use. * @return Reference to this string. * @throw std::out_of_range If @a __pos1 > size() or @a __pos2 > * __str.size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos1,__pos1 + n) from this * string. In place, the value of @a __str is inserted. If @a __pos is * beyond end of string, out_of_range is thrown. If the length of the * result exceeds max_size(), length_error is thrown. The value of the * string doesn't change if an error is thrown. */ basic_string& replace(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2 = npos) { return this->replace(__pos1, __n1, __str._M_data() + __str._M_check(__pos2, "basic_string::replace"), __str._M_limit(__pos2, __n2)); } /** * @brief Replace characters with value of a C substring. * @param __pos Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __s C string to insert. * @param __n2 Number of characters from @a s to use. * @return Reference to this string. * @throw std::out_of_range If @a pos1 > size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos,__pos + __n1) * from this string. In place, the first @a __n2 characters of * @a __s are inserted, or all of @a __s if @a __n2 is too large. If * @a __pos is beyond end of string, out_of_range is thrown. If * the length of result exceeds max_size(), length_error is * thrown. The value of the string doesn't change if an error * is thrown. */ basic_string& replace(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2) { __glibcxx_requires_string_len(__s, __n2); return _M_replace(_M_check(__pos, "basic_string::replace"), _M_limit(__pos, __n1), __s, __n2); } /** * @brief Replace characters with value of a C string. * @param __pos Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __s C string to insert. * @return Reference to this string. * @throw std::out_of_range If @a pos > size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos,__pos + __n1) * from this string. In place, the characters of @a __s are * inserted. If @a __pos is beyond end of string, out_of_range * is thrown. If the length of result exceeds max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& replace(size_type __pos, size_type __n1, const _CharT* __s) { __glibcxx_requires_string(__s); return this->replace(__pos, __n1, __s, traits_type::length(__s)); } /** * @brief Replace characters with multiple characters. * @param __pos Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __n2 Number of characters to insert. * @param __c Character to insert. * @return Reference to this string. * @throw std::out_of_range If @a __pos > size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [pos,pos + n1) from this * string. In place, @a __n2 copies of @a __c are inserted. * If @a __pos is beyond end of string, out_of_range is thrown. * If the length of result exceeds max_size(), length_error is * thrown. The value of the string doesn't change if an error * is thrown. */ basic_string& replace(size_type __pos, size_type __n1, size_type __n2, _CharT __c) { return _M_replace_aux(_M_check(__pos, "basic_string::replace"), _M_limit(__pos, __n1), __n2, __c); } /** * @brief Replace range of characters with string. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __str String value to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * the value of @a __str is inserted. If the length of result * exceeds max_size(), length_error is thrown. The value of * the string doesn't change if an error is thrown. */ basic_string& replace(__const_iterator __i1, __const_iterator __i2, const basic_string& __str) { return this->replace(__i1, __i2, __str._M_data(), __str.size()); } /** * @brief Replace range of characters with C substring. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __s C string value to insert. * @param __n Number of characters from s to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * the first @a __n characters of @a __s are inserted. If the * length of result exceeds max_size(), length_error is thrown. * The value of the string doesn't change if an error is * thrown. */ basic_string& replace(__const_iterator __i1, __const_iterator __i2, const _CharT* __s, size_type __n) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); return this->replace(__i1 - begin(), __i2 - __i1, __s, __n); } /** * @brief Replace range of characters with C string. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __s C string value to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * the characters of @a __s are inserted. If the length of * result exceeds max_size(), length_error is thrown. The * value of the string doesn't change if an error is thrown. */ basic_string& replace(__const_iterator __i1, __const_iterator __i2, const _CharT* __s) { __glibcxx_requires_string(__s); return this->replace(__i1, __i2, __s, traits_type::length(__s)); } /** * @brief Replace range of characters with multiple characters * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __n Number of characters to insert. * @param __c Character to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * @a __n copies of @a __c are inserted. If the length of * result exceeds max_size(), length_error is thrown. The * value of the string doesn't change if an error is thrown. */ basic_string& replace(__const_iterator __i1, __const_iterator __i2, size_type __n, _CharT __c) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); return _M_replace_aux(__i1 - begin(), __i2 - __i1, __n, __c); } /** * @brief Replace range of characters with range. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __k1 Iterator referencing start of range to insert. * @param __k2 Iterator referencing end of range to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * characters in the range [__k1,__k2) are inserted. If the * length of result exceeds max_size(), length_error is thrown. * The value of the string doesn't change if an error is * thrown. */ #if __cplusplus >= 201103L template> basic_string& replace(const_iterator __i1, const_iterator __i2, _InputIterator __k1, _InputIterator __k2) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); __glibcxx_requires_valid_range(__k1, __k2); return this->_M_replace_dispatch(__i1, __i2, __k1, __k2, std::__false_type()); } #else template #ifdef _GLIBCXX_DISAMBIGUATE_REPLACE_INST typename __enable_if_not_native_iterator<_InputIterator>::__type #else basic_string& #endif replace(iterator __i1, iterator __i2, _InputIterator __k1, _InputIterator __k2) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); __glibcxx_requires_valid_range(__k1, __k2); typedef typename std::__is_integer<_InputIterator>::__type _Integral; return _M_replace_dispatch(__i1, __i2, __k1, __k2, _Integral()); } #endif // Specializations for the common case of pointer and iterator: // useful to avoid the overhead of temporary buffering in _M_replace. basic_string& replace(__const_iterator __i1, __const_iterator __i2, _CharT* __k1, _CharT* __k2) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - begin(), __i2 - __i1, __k1, __k2 - __k1); } basic_string& replace(__const_iterator __i1, __const_iterator __i2, const _CharT* __k1, const _CharT* __k2) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - begin(), __i2 - __i1, __k1, __k2 - __k1); } basic_string& replace(__const_iterator __i1, __const_iterator __i2, iterator __k1, iterator __k2) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - begin(), __i2 - __i1, __k1.base(), __k2 - __k1); } basic_string& replace(__const_iterator __i1, __const_iterator __i2, const_iterator __k1, const_iterator __k2) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - begin(), __i2 - __i1, __k1.base(), __k2 - __k1); } #if __cplusplus >= 201103L /** * @brief Replace range of characters with initializer_list. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __l The initializer_list of characters to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * characters in the range [__k1,__k2) are inserted. If the * length of result exceeds max_size(), length_error is thrown. * The value of the string doesn't change if an error is * thrown. */ basic_string& replace(const_iterator __i1, const_iterator __i2, initializer_list<_CharT> __l) { return this->replace(__i1, __i2, __l.begin(), __l.size()); } #endif // C++11 #if __cplusplus > 201402L /** * @brief Replace range of characters with string_view. * @param __pos The position to replace at. * @param __n The number of characters to replace. * @param __svt The object convertible to string_view to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> replace(size_type __pos, size_type __n, const _Tp& __svt) { __sv_type __sv = __svt; return this->replace(__pos, __n, __sv.data(), __sv.size()); } /** * @brief Replace range of characters with string_view. * @param __pos1 The position to replace at. * @param __n1 The number of characters to replace. * @param __svt The object convertible to string_view to insert from. * @param __pos2 The position in the string_view to insert from. * @param __n2 The number of characters to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> replace(size_type __pos1, size_type __n1, const _Tp& __svt, size_type __pos2, size_type __n2 = npos) { __sv_type __sv = __svt; return this->replace(__pos1, __n1, __sv.data() + __sv._M_check(__pos2, "basic_string::replace"), __sv._M_limit(__pos2, __n2)); } /** * @brief Replace range of characters with string_view. * @param __i1 An iterator referencing the start position to replace at. * @param __i2 An iterator referencing the end position for the replace. * @param __svt The object convertible to string_view to insert from. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> replace(const_iterator __i1, const_iterator __i2, const _Tp& __svt) { __sv_type __sv = __svt; return this->replace(__i1 - begin(), __i2 - __i1, __sv); } #endif // C++17 private: template basic_string& _M_replace_dispatch(const_iterator __i1, const_iterator __i2, _Integer __n, _Integer __val, __true_type) { return _M_replace_aux(__i1 - begin(), __i2 - __i1, __n, __val); } template basic_string& _M_replace_dispatch(const_iterator __i1, const_iterator __i2, _InputIterator __k1, _InputIterator __k2, __false_type); basic_string& _M_replace_aux(size_type __pos1, size_type __n1, size_type __n2, _CharT __c); basic_string& _M_replace(size_type __pos, size_type __len1, const _CharT* __s, const size_type __len2); basic_string& _M_append(const _CharT* __s, size_type __n); public: /** * @brief Copy substring into C string. * @param __s C string to copy value into. * @param __n Number of characters to copy. * @param __pos Index of first character to copy. * @return Number of characters actually copied * @throw std::out_of_range If __pos > size(). * * Copies up to @a __n characters starting at @a __pos into the * C string @a __s. If @a __pos is %greater than size(), * out_of_range is thrown. */ size_type copy(_CharT* __s, size_type __n, size_type __pos = 0) const; /** * @brief Swap contents with another string. * @param __s String to swap with. * * Exchanges the contents of this string with that of @a __s in constant * time. */ void swap(basic_string& __s) _GLIBCXX_NOEXCEPT; // String operations: /** * @brief Return const pointer to null-terminated contents. * * This is a handle to internal data. Do not modify or dire things may * happen. */ const _CharT* c_str() const _GLIBCXX_NOEXCEPT { return _M_data(); } /** * @brief Return const pointer to contents. * * This is a pointer to internal data. It is undefined to modify * the contents through the returned pointer. To get a pointer that * allows modifying the contents use @c &str[0] instead, * (or in C++17 the non-const @c str.data() overload). */ const _CharT* data() const _GLIBCXX_NOEXCEPT { return _M_data(); } #if __cplusplus > 201402L /** * @brief Return non-const pointer to contents. * * This is a pointer to the character sequence held by the string. * Modifying the characters in the sequence is allowed. */ _CharT* data() noexcept { return _M_data(); } #endif /** * @brief Return copy of allocator used to construct this string. */ allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return _M_get_allocator(); } /** * @brief Find position of a C substring. * @param __s C string to locate. * @param __pos Index of character to search from. * @param __n Number of characters from @a s to search for. * @return Index of start of first occurrence. * * Starting from @a __pos, searches forward for the first @a * __n characters in @a __s within this string. If found, * returns the index where it begins. If not found, returns * npos. */ size_type find(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find position of a string. * @param __str String to locate. * @param __pos Index of character to search from (default 0). * @return Index of start of first occurrence. * * Starting from @a __pos, searches forward for value of @a __str within * this string. If found, returns the index where it begins. If not * found, returns npos. */ size_type find(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find(__str.data(), __pos, __str.size()); } #if __cplusplus > 201402L /** * @brief Find position of a string_view. * @param __svt The object convertible to string_view to locate. * @param __pos Index of character to search from (default 0). * @return Index of start of first occurrence. */ template _If_sv<_Tp, size_type> find(const _Tp& __svt, size_type __pos = 0) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find position of a C string. * @param __s C string to locate. * @param __pos Index of character to search from (default 0). * @return Index of start of first occurrence. * * Starting from @a __pos, searches forward for the value of @a * __s within this string. If found, returns the index where * it begins. If not found, returns npos. */ size_type find(const _CharT* __s, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find(__s, __pos, traits_type::length(__s)); } /** * @brief Find position of a character. * @param __c Character to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for @a __c within * this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type find(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a string. * @param __str String to locate. * @param __pos Index of character to search back from (default end). * @return Index of start of last occurrence. * * Starting from @a __pos, searches backward for value of @a * __str within this string. If found, returns the index where * it begins. If not found, returns npos. */ size_type rfind(const basic_string& __str, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->rfind(__str.data(), __pos, __str.size()); } #if __cplusplus > 201402L /** * @brief Find last position of a string_view. * @param __svt The object convertible to string_view to locate. * @param __pos Index of character to search back from (default end). * @return Index of start of last occurrence. */ template _If_sv<_Tp, size_type> rfind(const _Tp& __svt, size_type __pos = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->rfind(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find last position of a C substring. * @param __s C string to locate. * @param __pos Index of character to search back from. * @param __n Number of characters from s to search for. * @return Index of start of last occurrence. * * Starting from @a __pos, searches backward for the first @a * __n characters in @a __s within this string. If found, * returns the index where it begins. If not found, returns * npos. */ size_type rfind(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a C string. * @param __s C string to locate. * @param __pos Index of character to start search at (default end). * @return Index of start of last occurrence. * * Starting from @a __pos, searches backward for the value of * @a __s within this string. If found, returns the index * where it begins. If not found, returns npos. */ size_type rfind(const _CharT* __s, size_type __pos = npos) const { __glibcxx_requires_string(__s); return this->rfind(__s, __pos, traits_type::length(__s)); } /** * @brief Find last position of a character. * @param __c Character to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for @a __c within * this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type rfind(_CharT __c, size_type __pos = npos) const _GLIBCXX_NOEXCEPT; /** * @brief Find position of a character of string. * @param __str String containing characters to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for one of the * characters of @a __str within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_first_of(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find_first_of(__str.data(), __pos, __str.size()); } #if __cplusplus > 201402L /** * @brief Find position of a character of a string_view. * @param __svt An object convertible to string_view containing * characters to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. */ template _If_sv<_Tp, size_type> find_first_of(const _Tp& __svt, size_type __pos = 0) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_first_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find position of a character of C substring. * @param __s String containing characters to locate. * @param __pos Index of character to search from. * @param __n Number of characters from s to search for. * @return Index of first occurrence. * * Starting from @a __pos, searches forward for one of the * first @a __n characters of @a __s within this string. If * found, returns the index where it was found. If not found, * returns npos. */ size_type find_first_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find position of a character of C string. * @param __s String containing characters to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for one of the * characters of @a __s within this string. If found, returns * the index where it was found. If not found, returns npos. */ size_type find_first_of(const _CharT* __s, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_first_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find position of a character. * @param __c Character to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for the character * @a __c within this string. If found, returns the index * where it was found. If not found, returns npos. * * Note: equivalent to find(__c, __pos). */ size_type find_first_of(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find(__c, __pos); } /** * @brief Find last position of a character of string. * @param __str String containing characters to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for one of the * characters of @a __str within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_last_of(const basic_string& __str, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->find_last_of(__str.data(), __pos, __str.size()); } #if __cplusplus > 201402L /** * @brief Find last position of a character of string. * @param __svt An object convertible to string_view containing * characters to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. */ template _If_sv<_Tp, size_type> find_last_of(const _Tp& __svt, size_type __pos = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_last_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find last position of a character of C substring. * @param __s C string containing characters to locate. * @param __pos Index of character to search back from. * @param __n Number of characters from s to search for. * @return Index of last occurrence. * * Starting from @a __pos, searches backward for one of the * first @a __n characters of @a __s within this string. If * found, returns the index where it was found. If not found, * returns npos. */ size_type find_last_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a character of C string. * @param __s C string containing characters to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for one of the * characters of @a __s within this string. If found, returns * the index where it was found. If not found, returns npos. */ size_type find_last_of(const _CharT* __s, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_last_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find last position of a character. * @param __c Character to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for @a __c within * this string. If found, returns the index where it was * found. If not found, returns npos. * * Note: equivalent to rfind(__c, __pos). */ size_type find_last_of(_CharT __c, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->rfind(__c, __pos); } /** * @brief Find position of a character not in string. * @param __str String containing characters to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character not contained * in @a __str within this string. If found, returns the index where it * was found. If not found, returns npos. */ size_type find_first_not_of(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find_first_not_of(__str.data(), __pos, __str.size()); } #if __cplusplus > 201402L /** * @brief Find position of a character not in a string_view. * @param __svt A object convertible to string_view containing * characters to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. */ template _If_sv<_Tp, size_type> find_first_not_of(const _Tp& __svt, size_type __pos = 0) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_first_not_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find position of a character not in C substring. * @param __s C string containing characters to avoid. * @param __pos Index of character to search from. * @param __n Number of characters from __s to consider. * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character not * contained in the first @a __n characters of @a __s within * this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find position of a character not in C string. * @param __s C string containing characters to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character not * contained in @a __s within this string. If found, returns * the index where it was found. If not found, returns npos. */ size_type find_first_not_of(const _CharT* __s, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_first_not_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find position of a different character. * @param __c Character to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character * other than @a __c within this string. If found, returns the * index where it was found. If not found, returns npos. */ size_type find_first_not_of(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a character not in string. * @param __str String containing characters to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character * not contained in @a __str within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_last_not_of(const basic_string& __str, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->find_last_not_of(__str.data(), __pos, __str.size()); } #if __cplusplus > 201402L /** * @brief Find last position of a character not in a string_view. * @param __svt An object convertible to string_view containing * characters to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. */ template _If_sv<_Tp, size_type> find_last_not_of(const _Tp& __svt, size_type __pos = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_last_not_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find last position of a character not in C substring. * @param __s C string containing characters to avoid. * @param __pos Index of character to search back from. * @param __n Number of characters from s to consider. * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character not * contained in the first @a __n characters of @a __s within this string. * If found, returns the index where it was found. If not found, * returns npos. */ size_type find_last_not_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a character not in C string. * @param __s C string containing characters to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character * not contained in @a __s within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_last_not_of(const _CharT* __s, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_last_not_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find last position of a different character. * @param __c Character to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character other than * @a __c within this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type find_last_not_of(_CharT __c, size_type __pos = npos) const _GLIBCXX_NOEXCEPT; /** * @brief Get a substring. * @param __pos Index of first character (default 0). * @param __n Number of characters in substring (default remainder). * @return The new string. * @throw std::out_of_range If __pos > size(). * * Construct and return a new string using the @a __n * characters starting at @a __pos. If the string is too * short, use the remainder of the characters. If @a __pos is * beyond the end of the string, out_of_range is thrown. */ basic_string substr(size_type __pos = 0, size_type __n = npos) const { return basic_string(*this, _M_check(__pos, "basic_string::substr"), __n); } /** * @brief Compare to a string. * @param __str String to compare against. * @return Integer < 0, 0, or > 0. * * Returns an integer < 0 if this string is ordered before @a * __str, 0 if their values are equivalent, or > 0 if this * string is ordered after @a __str. Determines the effective * length rlen of the strings to compare as the smallest of * size() and str.size(). The function then compares the two * strings by calling traits::compare(data(), str.data(),rlen). * If the result of the comparison is nonzero returns it, * otherwise the shorter one is ordered first. */ int compare(const basic_string& __str) const { const size_type __size = this->size(); const size_type __osize = __str.size(); const size_type __len = std::min(__size, __osize); int __r = traits_type::compare(_M_data(), __str.data(), __len); if (!__r) __r = _S_compare(__size, __osize); return __r; } #if __cplusplus > 201402L /** * @brief Compare to a string_view. * @param __svt An object convertible to string_view to compare against. * @return Integer < 0, 0, or > 0. */ template _If_sv<_Tp, int> compare(const _Tp& __svt) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; const size_type __size = this->size(); const size_type __osize = __sv.size(); const size_type __len = std::min(__size, __osize); int __r = traits_type::compare(_M_data(), __sv.data(), __len); if (!__r) __r = _S_compare(__size, __osize); return __r; } /** * @brief Compare to a string_view. * @param __pos A position in the string to start comparing from. * @param __n The number of characters to compare. * @param __svt An object convertible to string_view to compare * against. * @return Integer < 0, 0, or > 0. */ template _If_sv<_Tp, int> compare(size_type __pos, size_type __n, const _Tp& __svt) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return __sv_type(*this).substr(__pos, __n).compare(__sv); } /** * @brief Compare to a string_view. * @param __pos1 A position in the string to start comparing from. * @param __n1 The number of characters to compare. * @param __svt An object convertible to string_view to compare * against. * @param __pos2 A position in the string_view to start comparing from. * @param __n2 The number of characters to compare. * @return Integer < 0, 0, or > 0. */ template _If_sv<_Tp, int> compare(size_type __pos1, size_type __n1, const _Tp& __svt, size_type __pos2, size_type __n2 = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return __sv_type(*this) .substr(__pos1, __n1).compare(__sv.substr(__pos2, __n2)); } #endif // C++17 /** * @brief Compare substring to a string. * @param __pos Index of first character of substring. * @param __n Number of characters in substring. * @param __str String to compare against. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n characters * starting at @a __pos. Returns an integer < 0 if the * substring is ordered before @a __str, 0 if their values are * equivalent, or > 0 if the substring is ordered after @a * __str. Determines the effective length rlen of the strings * to compare as the smallest of the length of the substring * and @a __str.size(). The function then compares the two * strings by calling * traits::compare(substring.data(),str.data(),rlen). If the * result of the comparison is nonzero returns it, otherwise * the shorter one is ordered first. */ int compare(size_type __pos, size_type __n, const basic_string& __str) const; /** * @brief Compare substring to a substring. * @param __pos1 Index of first character of substring. * @param __n1 Number of characters in substring. * @param __str String to compare against. * @param __pos2 Index of first character of substring of str. * @param __n2 Number of characters in substring of str. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n1 * characters starting at @a __pos1. Form the substring of @a * __str from the @a __n2 characters starting at @a __pos2. * Returns an integer < 0 if this substring is ordered before * the substring of @a __str, 0 if their values are equivalent, * or > 0 if this substring is ordered after the substring of * @a __str. Determines the effective length rlen of the * strings to compare as the smallest of the lengths of the * substrings. The function then compares the two strings by * calling * traits::compare(substring.data(),str.substr(pos2,n2).data(),rlen). * If the result of the comparison is nonzero returns it, * otherwise the shorter one is ordered first. */ int compare(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2 = npos) const; /** * @brief Compare to a C string. * @param __s C string to compare against. * @return Integer < 0, 0, or > 0. * * Returns an integer < 0 if this string is ordered before @a __s, 0 if * their values are equivalent, or > 0 if this string is ordered after * @a __s. Determines the effective length rlen of the strings to * compare as the smallest of size() and the length of a string * constructed from @a __s. The function then compares the two strings * by calling traits::compare(data(),s,rlen). If the result of the * comparison is nonzero returns it, otherwise the shorter one is * ordered first. */ int compare(const _CharT* __s) const _GLIBCXX_NOEXCEPT; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 5 String::compare specification questionable /** * @brief Compare substring to a C string. * @param __pos Index of first character of substring. * @param __n1 Number of characters in substring. * @param __s C string to compare against. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n1 * characters starting at @a pos. Returns an integer < 0 if * the substring is ordered before @a __s, 0 if their values * are equivalent, or > 0 if the substring is ordered after @a * __s. Determines the effective length rlen of the strings to * compare as the smallest of the length of the substring and * the length of a string constructed from @a __s. The * function then compares the two string by calling * traits::compare(substring.data(),__s,rlen). If the result of * the comparison is nonzero returns it, otherwise the shorter * one is ordered first. */ int compare(size_type __pos, size_type __n1, const _CharT* __s) const; /** * @brief Compare substring against a character %array. * @param __pos Index of first character of substring. * @param __n1 Number of characters in substring. * @param __s character %array to compare against. * @param __n2 Number of characters of s. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n1 * characters starting at @a __pos. Form a string from the * first @a __n2 characters of @a __s. Returns an integer < 0 * if this substring is ordered before the string from @a __s, * 0 if their values are equivalent, or > 0 if this substring * is ordered after the string from @a __s. Determines the * effective length rlen of the strings to compare as the * smallest of the length of the substring and @a __n2. The * function then compares the two strings by calling * traits::compare(substring.data(),s,rlen). If the result of * the comparison is nonzero returns it, otherwise the shorter * one is ordered first. * * NB: s must have at least n2 characters, '\\0' has * no special meaning. */ int compare(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2) const; // Allow basic_stringbuf::__xfer_bufptrs to call _M_length: template friend class basic_stringbuf; }; _GLIBCXX_END_NAMESPACE_CXX11 #else // !_GLIBCXX_USE_CXX11_ABI // Reference-counted COW string implentation /** * @class basic_string basic_string.h * @brief Managing sequences of characters and character-like objects. * * @ingroup strings * @ingroup sequences * * @tparam _CharT Type of character * @tparam _Traits Traits for character type, defaults to * char_traits<_CharT>. * @tparam _Alloc Allocator type, defaults to allocator<_CharT>. * * Meets the requirements of a container, a * reversible container, and a * sequence. Of the * optional sequence requirements, only * @c push_back, @c at, and @c %array access are supported. * * @doctodo * * * Documentation? What's that? * Nathan Myers . * * A string looks like this: * * @code * [_Rep] * _M_length * [basic_string] _M_capacity * _M_dataplus _M_refcount * _M_p ----------------> unnamed array of char_type * @endcode * * Where the _M_p points to the first character in the string, and * you cast it to a pointer-to-_Rep and subtract 1 to get a * pointer to the header. * * This approach has the enormous advantage that a string object * requires only one allocation. All the ugliness is confined * within a single %pair of inline functions, which each compile to * a single @a add instruction: _Rep::_M_data(), and * string::_M_rep(); and the allocation function which gets a * block of raw bytes and with room enough and constructs a _Rep * object at the front. * * The reason you want _M_data pointing to the character %array and * not the _Rep is so that the debugger can see the string * contents. (Probably we should add a non-inline member to get * the _Rep for the debugger to use, so users can check the actual * string length.) * * Note that the _Rep object is a POD so that you can have a * static empty string _Rep object already @a constructed before * static constructors have run. The reference-count encoding is * chosen so that a 0 indicates one reference, so you never try to * destroy the empty-string _Rep object. * * All but the last paragraph is considered pretty conventional * for a C++ string implementation. */ // 21.3 Template class basic_string template class basic_string { typedef typename _Alloc::template rebind<_CharT>::other _CharT_alloc_type; // Types: public: typedef _Traits traits_type; typedef typename _Traits::char_type value_type; typedef _Alloc allocator_type; typedef typename _CharT_alloc_type::size_type size_type; typedef typename _CharT_alloc_type::difference_type difference_type; typedef typename _CharT_alloc_type::reference reference; typedef typename _CharT_alloc_type::const_reference const_reference; typedef typename _CharT_alloc_type::pointer pointer; typedef typename _CharT_alloc_type::const_pointer const_pointer; typedef __gnu_cxx::__normal_iterator iterator; typedef __gnu_cxx::__normal_iterator const_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; private: // _Rep: string representation // Invariants: // 1. String really contains _M_length + 1 characters: due to 21.3.4 // must be kept null-terminated. // 2. _M_capacity >= _M_length // Allocated memory is always (_M_capacity + 1) * sizeof(_CharT). // 3. _M_refcount has three states: // -1: leaked, one reference, no ref-copies allowed, non-const. // 0: one reference, non-const. // n>0: n + 1 references, operations require a lock, const. // 4. All fields==0 is an empty string, given the extra storage // beyond-the-end for a null terminator; thus, the shared // empty string representation needs no constructor. struct _Rep_base { size_type _M_length; size_type _M_capacity; _Atomic_word _M_refcount; }; struct _Rep : _Rep_base { // Types: typedef typename _Alloc::template rebind::other _Raw_bytes_alloc; // (Public) Data members: // The maximum number of individual char_type elements of an // individual string is determined by _S_max_size. This is the // value that will be returned by max_size(). (Whereas npos // is the maximum number of bytes the allocator can allocate.) // If one was to divvy up the theoretical largest size string, // with a terminating character and m _CharT elements, it'd // look like this: // npos = sizeof(_Rep) + (m * sizeof(_CharT)) + sizeof(_CharT) // Solving for m: // m = ((npos - sizeof(_Rep))/sizeof(CharT)) - 1 // In addition, this implementation quarters this amount. static const size_type _S_max_size; static const _CharT _S_terminal; // The following storage is init'd to 0 by the linker, resulting // (carefully) in an empty string with one reference. static size_type _S_empty_rep_storage[]; static _Rep& _S_empty_rep() _GLIBCXX_NOEXCEPT { // NB: Mild hack to avoid strict-aliasing warnings. Note that // _S_empty_rep_storage is never modified and the punning should // be reasonably safe in this case. void* __p = reinterpret_cast(&_S_empty_rep_storage); return *reinterpret_cast<_Rep*>(__p); } bool _M_is_leaked() const _GLIBCXX_NOEXCEPT { #if defined(__GTHREADS) // _M_refcount is mutated concurrently by _M_refcopy/_M_dispose, // so we need to use an atomic load. However, _M_is_leaked // predicate does not change concurrently (i.e. the string is either // leaked or not), so a relaxed load is enough. return __atomic_load_n(&this->_M_refcount, __ATOMIC_RELAXED) < 0; #else return this->_M_refcount < 0; #endif } bool _M_is_shared() const _GLIBCXX_NOEXCEPT { #if defined(__GTHREADS) // _M_refcount is mutated concurrently by _M_refcopy/_M_dispose, // so we need to use an atomic load. Another thread can drop last // but one reference concurrently with this check, so we need this // load to be acquire to synchronize with release fetch_and_add in // _M_dispose. return __atomic_load_n(&this->_M_refcount, __ATOMIC_ACQUIRE) > 0; #else return this->_M_refcount > 0; #endif } void _M_set_leaked() _GLIBCXX_NOEXCEPT { this->_M_refcount = -1; } void _M_set_sharable() _GLIBCXX_NOEXCEPT { this->_M_refcount = 0; } void _M_set_length_and_sharable(size_type __n) _GLIBCXX_NOEXCEPT { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 if (__builtin_expect(this != &_S_empty_rep(), false)) #endif { this->_M_set_sharable(); // One reference. this->_M_length = __n; traits_type::assign(this->_M_refdata()[__n], _S_terminal); // grrr. (per 21.3.4) // You cannot leave those LWG people alone for a second. } } _CharT* _M_refdata() throw() { return reinterpret_cast<_CharT*>(this + 1); } _CharT* _M_grab(const _Alloc& __alloc1, const _Alloc& __alloc2) { return (!_M_is_leaked() && __alloc1 == __alloc2) ? _M_refcopy() : _M_clone(__alloc1); } // Create & Destroy static _Rep* _S_create(size_type, size_type, const _Alloc&); void _M_dispose(const _Alloc& __a) _GLIBCXX_NOEXCEPT { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 if (__builtin_expect(this != &_S_empty_rep(), false)) #endif { // Be race-detector-friendly. For more info see bits/c++config. _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&this->_M_refcount); // Decrement of _M_refcount is acq_rel, because: // - all but last decrements need to release to synchronize with // the last decrement that will delete the object. // - the last decrement needs to acquire to synchronize with // all the previous decrements. // - last but one decrement needs to release to synchronize with // the acquire load in _M_is_shared that will conclude that // the object is not shared anymore. if (__gnu_cxx::__exchange_and_add_dispatch(&this->_M_refcount, -1) <= 0) { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&this->_M_refcount); _M_destroy(__a); } } } // XXX MT void _M_destroy(const _Alloc&) throw(); _CharT* _M_refcopy() throw() { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 if (__builtin_expect(this != &_S_empty_rep(), false)) #endif __gnu_cxx::__atomic_add_dispatch(&this->_M_refcount, 1); return _M_refdata(); } // XXX MT _CharT* _M_clone(const _Alloc&, size_type __res = 0); }; // Use empty-base optimization: http://www.cantrip.org/emptyopt.html struct _Alloc_hider : _Alloc { _Alloc_hider(_CharT* __dat, const _Alloc& __a) _GLIBCXX_NOEXCEPT : _Alloc(__a), _M_p(__dat) { } _CharT* _M_p; // The actual data. }; public: // Data Members (public): // NB: This is an unsigned type, and thus represents the maximum // size that the allocator can hold. /// Value returned by various member functions when they fail. static const size_type npos = static_cast(-1); private: // Data Members (private): mutable _Alloc_hider _M_dataplus; _CharT* _M_data() const _GLIBCXX_NOEXCEPT { return _M_dataplus._M_p; } _CharT* _M_data(_CharT* __p) _GLIBCXX_NOEXCEPT { return (_M_dataplus._M_p = __p); } _Rep* _M_rep() const _GLIBCXX_NOEXCEPT { return &((reinterpret_cast<_Rep*> (_M_data()))[-1]); } // For the internal use we have functions similar to `begin'/`end' // but they do not call _M_leak. iterator _M_ibegin() const _GLIBCXX_NOEXCEPT { return iterator(_M_data()); } iterator _M_iend() const _GLIBCXX_NOEXCEPT { return iterator(_M_data() + this->size()); } void _M_leak() // for use in begin() & non-const op[] { if (!_M_rep()->_M_is_leaked()) _M_leak_hard(); } size_type _M_check(size_type __pos, const char* __s) const { if (__pos > this->size()) __throw_out_of_range_fmt(__N("%s: __pos (which is %zu) > " "this->size() (which is %zu)"), __s, __pos, this->size()); return __pos; } void _M_check_length(size_type __n1, size_type __n2, const char* __s) const { if (this->max_size() - (this->size() - __n1) < __n2) __throw_length_error(__N(__s)); } // NB: _M_limit doesn't check for a bad __pos value. size_type _M_limit(size_type __pos, size_type __off) const _GLIBCXX_NOEXCEPT { const bool __testoff = __off < this->size() - __pos; return __testoff ? __off : this->size() - __pos; } // True if _Rep and source do not overlap. bool _M_disjunct(const _CharT* __s) const _GLIBCXX_NOEXCEPT { return (less()(__s, _M_data()) || less()(_M_data() + this->size(), __s)); } // When __n = 1 way faster than the general multichar // traits_type::copy/move/assign. static void _M_copy(_CharT* __d, const _CharT* __s, size_type __n) _GLIBCXX_NOEXCEPT { if (__n == 1) traits_type::assign(*__d, *__s); else traits_type::copy(__d, __s, __n); } static void _M_move(_CharT* __d, const _CharT* __s, size_type __n) _GLIBCXX_NOEXCEPT { if (__n == 1) traits_type::assign(*__d, *__s); else traits_type::move(__d, __s, __n); } static void _M_assign(_CharT* __d, size_type __n, _CharT __c) _GLIBCXX_NOEXCEPT { if (__n == 1) traits_type::assign(*__d, __c); else traits_type::assign(__d, __n, __c); } // _S_copy_chars is a separate template to permit specialization // to optimize for the common case of pointers as iterators. template static void _S_copy_chars(_CharT* __p, _Iterator __k1, _Iterator __k2) { for (; __k1 != __k2; ++__k1, (void)++__p) traits_type::assign(*__p, *__k1); // These types are off. } static void _S_copy_chars(_CharT* __p, iterator __k1, iterator __k2) _GLIBCXX_NOEXCEPT { _S_copy_chars(__p, __k1.base(), __k2.base()); } static void _S_copy_chars(_CharT* __p, const_iterator __k1, const_iterator __k2) _GLIBCXX_NOEXCEPT { _S_copy_chars(__p, __k1.base(), __k2.base()); } static void _S_copy_chars(_CharT* __p, _CharT* __k1, _CharT* __k2) _GLIBCXX_NOEXCEPT { _M_copy(__p, __k1, __k2 - __k1); } static void _S_copy_chars(_CharT* __p, const _CharT* __k1, const _CharT* __k2) _GLIBCXX_NOEXCEPT { _M_copy(__p, __k1, __k2 - __k1); } static int _S_compare(size_type __n1, size_type __n2) _GLIBCXX_NOEXCEPT { const difference_type __d = difference_type(__n1 - __n2); if (__d > __gnu_cxx::__numeric_traits::__max) return __gnu_cxx::__numeric_traits::__max; else if (__d < __gnu_cxx::__numeric_traits::__min) return __gnu_cxx::__numeric_traits::__min; else return int(__d); } void _M_mutate(size_type __pos, size_type __len1, size_type __len2); void _M_leak_hard(); static _Rep& _S_empty_rep() _GLIBCXX_NOEXCEPT { return _Rep::_S_empty_rep(); } #if __cplusplus > 201402L // A helper type for avoiding boiler-plate. typedef basic_string_view<_CharT, _Traits> __sv_type; template using _If_sv = enable_if_t< __and_, __not_>, __not_>>::value, _Res>; // Allows an implicit conversion to __sv_type. static __sv_type _S_to_string_view(__sv_type __svt) noexcept { return __svt; } // Wraps a string_view by explicit conversion and thus // allows to add an internal constructor that does not // participate in overload resolution when a string_view // is provided. struct __sv_wrapper { explicit __sv_wrapper(__sv_type __sv) noexcept : _M_sv(__sv) { } __sv_type _M_sv; }; #endif public: // Construct/copy/destroy: // NB: We overload ctors in some cases instead of using default // arguments, per 17.4.4.4 para. 2 item 2. /** * @brief Default constructor creates an empty string. */ basic_string() #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 : _M_dataplus(_S_empty_rep()._M_refdata(), _Alloc()) { } #else : _M_dataplus(_S_construct(size_type(), _CharT(), _Alloc()), _Alloc()){ } #endif /** * @brief Construct an empty string using allocator @a a. */ explicit basic_string(const _Alloc& __a); // NB: per LWG issue 42, semantics different from IS: /** * @brief Construct string with copy of value of @a str. * @param __str Source string. */ basic_string(const basic_string& __str); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2583. no way to supply an allocator for basic_string(str, pos) /** * @brief Construct string as copy of a substring. * @param __str Source string. * @param __pos Index of first character to copy from. * @param __a Allocator to use. */ basic_string(const basic_string& __str, size_type __pos, const _Alloc& __a = _Alloc()); /** * @brief Construct string as copy of a substring. * @param __str Source string. * @param __pos Index of first character to copy from. * @param __n Number of characters to copy. */ basic_string(const basic_string& __str, size_type __pos, size_type __n); /** * @brief Construct string as copy of a substring. * @param __str Source string. * @param __pos Index of first character to copy from. * @param __n Number of characters to copy. * @param __a Allocator to use. */ basic_string(const basic_string& __str, size_type __pos, size_type __n, const _Alloc& __a); /** * @brief Construct string initialized by a character %array. * @param __s Source character %array. * @param __n Number of characters to copy. * @param __a Allocator to use (default is default allocator). * * NB: @a __s must have at least @a __n characters, '\\0' * has no special meaning. */ basic_string(const _CharT* __s, size_type __n, const _Alloc& __a = _Alloc()); /** * @brief Construct string as copy of a C string. * @param __s Source C string. * @param __a Allocator to use (default is default allocator). */ basic_string(const _CharT* __s, const _Alloc& __a = _Alloc()); /** * @brief Construct string as multiple characters. * @param __n Number of characters. * @param __c Character to use. * @param __a Allocator to use (default is default allocator). */ basic_string(size_type __n, _CharT __c, const _Alloc& __a = _Alloc()); #if __cplusplus >= 201103L /** * @brief Move construct string. * @param __str Source string. * * The newly-created string contains the exact contents of @a __str. * @a __str is a valid, but unspecified string. **/ basic_string(basic_string&& __str) #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 noexcept // FIXME C++11: should always be noexcept. #endif : _M_dataplus(__str._M_dataplus) { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 __str._M_data(_S_empty_rep()._M_refdata()); #else __str._M_data(_S_construct(size_type(), _CharT(), get_allocator())); #endif } /** * @brief Construct string from an initializer %list. * @param __l std::initializer_list of characters. * @param __a Allocator to use (default is default allocator). */ basic_string(initializer_list<_CharT> __l, const _Alloc& __a = _Alloc()); #endif // C++11 /** * @brief Construct string as copy of a range. * @param __beg Start of range. * @param __end End of range. * @param __a Allocator to use (default is default allocator). */ template basic_string(_InputIterator __beg, _InputIterator __end, const _Alloc& __a = _Alloc()); #if __cplusplus > 201402L /** * @brief Construct string from a substring of a string_view. * @param __t Source object convertible to string view. * @param __pos The index of the first character to copy from __t. * @param __n The number of characters to copy from __t. * @param __a Allocator to use. */ template> basic_string(const _Tp& __t, size_type __pos, size_type __n, const _Alloc& __a = _Alloc()) : basic_string(_S_to_string_view(__t).substr(__pos, __n), __a) { } /** * @brief Construct string from a string_view. * @param __t Source object convertible to string view. * @param __a Allocator to use (default is default allocator). */ template> explicit basic_string(const _Tp& __t, const _Alloc& __a = _Alloc()) : basic_string(__sv_wrapper(_S_to_string_view(__t)), __a) { } /** * @brief Only internally used: Construct string from a string view * wrapper. * @param __svw string view wrapper. * @param __a Allocator to use. */ explicit basic_string(__sv_wrapper __svw, const _Alloc& __a) : basic_string(__svw._M_sv.data(), __svw._M_sv.size(), __a) { } #endif // C++17 /** * @brief Destroy the string instance. */ ~basic_string() _GLIBCXX_NOEXCEPT { _M_rep()->_M_dispose(this->get_allocator()); } /** * @brief Assign the value of @a str to this string. * @param __str Source string. */ basic_string& operator=(const basic_string& __str) { return this->assign(__str); } /** * @brief Copy contents of @a s into this string. * @param __s Source null-terminated string. */ basic_string& operator=(const _CharT* __s) { return this->assign(__s); } /** * @brief Set value to string of length 1. * @param __c Source character. * * Assigning to a character makes this string length 1 and * (*this)[0] == @a c. */ basic_string& operator=(_CharT __c) { this->assign(1, __c); return *this; } #if __cplusplus >= 201103L /** * @brief Move assign the value of @a str to this string. * @param __str Source string. * * The contents of @a str are moved into this string (without copying). * @a str is a valid, but unspecified string. **/ // PR 58265, this should be noexcept. basic_string& operator=(basic_string&& __str) { // NB: DR 1204. this->swap(__str); return *this; } /** * @brief Set value to string constructed from initializer %list. * @param __l std::initializer_list. */ basic_string& operator=(initializer_list<_CharT> __l) { this->assign(__l.begin(), __l.size()); return *this; } #endif // C++11 #if __cplusplus > 201402L /** * @brief Set value to string constructed from a string_view. * @param __svt An object convertible to string_view. */ template _If_sv<_Tp, basic_string&> operator=(const _Tp& __svt) { return this->assign(__svt); } /** * @brief Convert to a string_view. * @return A string_view. */ operator __sv_type() const noexcept { return __sv_type(data(), size()); } #endif // C++17 // Iterators: /** * Returns a read/write iterator that points to the first character in * the %string. Unshares the string. */ iterator begin() // FIXME C++11: should be noexcept. { _M_leak(); return iterator(_M_data()); } /** * Returns a read-only (constant) iterator that points to the first * character in the %string. */ const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_M_data()); } /** * Returns a read/write iterator that points one past the last * character in the %string. Unshares the string. */ iterator end() // FIXME C++11: should be noexcept. { _M_leak(); return iterator(_M_data() + this->size()); } /** * Returns a read-only (constant) iterator that points one past the * last character in the %string. */ const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_M_data() + this->size()); } /** * Returns a read/write reverse iterator that points to the last * character in the %string. Iteration is done in reverse element * order. Unshares the string. */ reverse_iterator rbegin() // FIXME C++11: should be noexcept. { return reverse_iterator(this->end()); } /** * Returns a read-only (constant) reverse iterator that points * to the last character in the %string. Iteration is done in * reverse element order. */ const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(this->end()); } /** * Returns a read/write reverse iterator that points to one before the * first character in the %string. Iteration is done in reverse * element order. Unshares the string. */ reverse_iterator rend() // FIXME C++11: should be noexcept. { return reverse_iterator(this->begin()); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first character in the %string. Iteration * is done in reverse element order. */ const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(this->begin()); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the first * character in the %string. */ const_iterator cbegin() const noexcept { return const_iterator(this->_M_data()); } /** * Returns a read-only (constant) iterator that points one past the * last character in the %string. */ const_iterator cend() const noexcept { return const_iterator(this->_M_data() + this->size()); } /** * Returns a read-only (constant) reverse iterator that points * to the last character in the %string. Iteration is done in * reverse element order. */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(this->end()); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first character in the %string. Iteration * is done in reverse element order. */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(this->begin()); } #endif public: // Capacity: /// Returns the number of characters in the string, not including any /// null-termination. size_type size() const _GLIBCXX_NOEXCEPT { return _M_rep()->_M_length; } /// Returns the number of characters in the string, not including any /// null-termination. size_type length() const _GLIBCXX_NOEXCEPT { return _M_rep()->_M_length; } /// Returns the size() of the largest possible %string. size_type max_size() const _GLIBCXX_NOEXCEPT { return _Rep::_S_max_size; } /** * @brief Resizes the %string to the specified number of characters. * @param __n Number of characters the %string should contain. * @param __c Character to fill any new elements. * * This function will %resize the %string to the specified * number of characters. If the number is smaller than the * %string's current size the %string is truncated, otherwise * the %string is extended and new elements are %set to @a __c. */ void resize(size_type __n, _CharT __c); /** * @brief Resizes the %string to the specified number of characters. * @param __n Number of characters the %string should contain. * * This function will resize the %string to the specified length. If * the new size is smaller than the %string's current size the %string * is truncated, otherwise the %string is extended and new characters * are default-constructed. For basic types such as char, this means * setting them to 0. */ void resize(size_type __n) { this->resize(__n, _CharT()); } #if __cplusplus >= 201103L /// A non-binding request to reduce capacity() to size(). void shrink_to_fit() _GLIBCXX_NOEXCEPT { #if __cpp_exceptions if (capacity() > size()) { try { reserve(0); } catch(...) { } } #endif } #endif /** * Returns the total number of characters that the %string can hold * before needing to allocate more memory. */ size_type capacity() const _GLIBCXX_NOEXCEPT { return _M_rep()->_M_capacity; } /** * @brief Attempt to preallocate enough memory for specified number of * characters. * @param __res_arg Number of characters required. * @throw std::length_error If @a __res_arg exceeds @c max_size(). * * This function attempts to reserve enough memory for the * %string to hold the specified number of characters. If the * number requested is more than max_size(), length_error is * thrown. * * The advantage of this function is that if optimal code is a * necessity and the user can determine the string length that will be * required, the user can reserve the memory in %advance, and thus * prevent a possible reallocation of memory and copying of %string * data. */ void reserve(size_type __res_arg = 0); /** * Erases the string, making it empty. */ #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 void clear() _GLIBCXX_NOEXCEPT { if (_M_rep()->_M_is_shared()) { _M_rep()->_M_dispose(this->get_allocator()); _M_data(_S_empty_rep()._M_refdata()); } else _M_rep()->_M_set_length_and_sharable(0); } #else // PR 56166: this should not throw. void clear() { _M_mutate(0, this->size(), 0); } #endif /** * Returns true if the %string is empty. Equivalent to * *this == "". */ bool empty() const _GLIBCXX_NOEXCEPT { return this->size() == 0; } // Element access: /** * @brief Subscript access to the data contained in the %string. * @param __pos The index of the character to access. * @return Read-only (constant) reference to the character. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ const_reference operator[] (size_type __pos) const _GLIBCXX_NOEXCEPT { __glibcxx_assert(__pos <= size()); return _M_data()[__pos]; } /** * @brief Subscript access to the data contained in the %string. * @param __pos The index of the character to access. * @return Read/write reference to the character. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) Unshares the string. */ reference operator[](size_type __pos) { // Allow pos == size() both in C++98 mode, as v3 extension, // and in C++11 mode. __glibcxx_assert(__pos <= size()); // In pedantic mode be strict in C++98 mode. _GLIBCXX_DEBUG_PEDASSERT(__cplusplus >= 201103L || __pos < size()); _M_leak(); return _M_data()[__pos]; } /** * @brief Provides access to the data contained in the %string. * @param __n The index of the character to access. * @return Read-only (const) reference to the character. * @throw std::out_of_range If @a n is an invalid index. * * This function provides for safer data access. The parameter is * first checked that it is in the range of the string. The function * throws out_of_range if the check fails. */ const_reference at(size_type __n) const { if (__n >= this->size()) __throw_out_of_range_fmt(__N("basic_string::at: __n " "(which is %zu) >= this->size() " "(which is %zu)"), __n, this->size()); return _M_data()[__n]; } /** * @brief Provides access to the data contained in the %string. * @param __n The index of the character to access. * @return Read/write reference to the character. * @throw std::out_of_range If @a n is an invalid index. * * This function provides for safer data access. The parameter is * first checked that it is in the range of the string. The function * throws out_of_range if the check fails. Success results in * unsharing the string. */ reference at(size_type __n) { if (__n >= size()) __throw_out_of_range_fmt(__N("basic_string::at: __n " "(which is %zu) >= this->size() " "(which is %zu)"), __n, this->size()); _M_leak(); return _M_data()[__n]; } #if __cplusplus >= 201103L /** * Returns a read/write reference to the data at the first * element of the %string. */ reference front() { __glibcxx_assert(!empty()); return operator[](0); } /** * Returns a read-only (constant) reference to the data at the first * element of the %string. */ const_reference front() const noexcept { __glibcxx_assert(!empty()); return operator[](0); } /** * Returns a read/write reference to the data at the last * element of the %string. */ reference back() { __glibcxx_assert(!empty()); return operator[](this->size() - 1); } /** * Returns a read-only (constant) reference to the data at the * last element of the %string. */ const_reference back() const noexcept { __glibcxx_assert(!empty()); return operator[](this->size() - 1); } #endif // Modifiers: /** * @brief Append a string to this string. * @param __str The string to append. * @return Reference to this string. */ basic_string& operator+=(const basic_string& __str) { return this->append(__str); } /** * @brief Append a C string. * @param __s The C string to append. * @return Reference to this string. */ basic_string& operator+=(const _CharT* __s) { return this->append(__s); } /** * @brief Append a character. * @param __c The character to append. * @return Reference to this string. */ basic_string& operator+=(_CharT __c) { this->push_back(__c); return *this; } #if __cplusplus >= 201103L /** * @brief Append an initializer_list of characters. * @param __l The initializer_list of characters to be appended. * @return Reference to this string. */ basic_string& operator+=(initializer_list<_CharT> __l) { return this->append(__l.begin(), __l.size()); } #endif // C++11 #if __cplusplus > 201402L /** * @brief Append a string_view. * @param __svt The object convertible to string_view to be appended. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> operator+=(const _Tp& __svt) { return this->append(__svt); } #endif // C++17 /** * @brief Append a string to this string. * @param __str The string to append. * @return Reference to this string. */ basic_string& append(const basic_string& __str); /** * @brief Append a substring. * @param __str The string to append. * @param __pos Index of the first character of str to append. * @param __n The number of characters to append. * @return Reference to this string. * @throw std::out_of_range if @a __pos is not a valid index. * * This function appends @a __n characters from @a __str * starting at @a __pos to this string. If @a __n is is larger * than the number of available characters in @a __str, the * remainder of @a __str is appended. */ basic_string& append(const basic_string& __str, size_type __pos, size_type __n = npos); /** * @brief Append a C substring. * @param __s The C string to append. * @param __n The number of characters to append. * @return Reference to this string. */ basic_string& append(const _CharT* __s, size_type __n); /** * @brief Append a C string. * @param __s The C string to append. * @return Reference to this string. */ basic_string& append(const _CharT* __s) { __glibcxx_requires_string(__s); return this->append(__s, traits_type::length(__s)); } /** * @brief Append multiple characters. * @param __n The number of characters to append. * @param __c The character to use. * @return Reference to this string. * * Appends __n copies of __c to this string. */ basic_string& append(size_type __n, _CharT __c); #if __cplusplus >= 201103L /** * @brief Append an initializer_list of characters. * @param __l The initializer_list of characters to append. * @return Reference to this string. */ basic_string& append(initializer_list<_CharT> __l) { return this->append(__l.begin(), __l.size()); } #endif // C++11 /** * @brief Append a range of characters. * @param __first Iterator referencing the first character to append. * @param __last Iterator marking the end of the range. * @return Reference to this string. * * Appends characters in the range [__first,__last) to this string. */ template basic_string& append(_InputIterator __first, _InputIterator __last) { return this->replace(_M_iend(), _M_iend(), __first, __last); } #if __cplusplus > 201402L /** * @brief Append a string_view. * @param __svt The object convertible to string_view to be appended. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> append(const _Tp& __svt) { __sv_type __sv = __svt; return this->append(__sv.data(), __sv.size()); } /** * @brief Append a range of characters from a string_view. * @param __svt The object convertible to string_view to be appended * from. * @param __pos The position in the string_view to append from. * @param __n The number of characters to append from the string_view. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> append(const _Tp& __svt, size_type __pos, size_type __n = npos) { __sv_type __sv = __svt; return append(__sv.data() + __sv._M_check(__pos, "basic_string::append"), __sv._M_limit(__pos, __n)); } #endif // C++17 /** * @brief Append a single character. * @param __c Character to append. */ void push_back(_CharT __c) { const size_type __len = 1 + this->size(); if (__len > this->capacity() || _M_rep()->_M_is_shared()) this->reserve(__len); traits_type::assign(_M_data()[this->size()], __c); _M_rep()->_M_set_length_and_sharable(__len); } /** * @brief Set value to contents of another string. * @param __str Source string to use. * @return Reference to this string. */ basic_string& assign(const basic_string& __str); #if __cplusplus >= 201103L /** * @brief Set value to contents of another string. * @param __str Source string to use. * @return Reference to this string. * * This function sets this string to the exact contents of @a __str. * @a __str is a valid, but unspecified string. */ // PR 58265, this should be noexcept. basic_string& assign(basic_string&& __str) { this->swap(__str); return *this; } #endif // C++11 /** * @brief Set value to a substring of a string. * @param __str The string to use. * @param __pos Index of the first character of str. * @param __n Number of characters to use. * @return Reference to this string. * @throw std::out_of_range if @a pos is not a valid index. * * This function sets this string to the substring of @a __str * consisting of @a __n characters at @a __pos. If @a __n is * is larger than the number of available characters in @a * __str, the remainder of @a __str is used. */ basic_string& assign(const basic_string& __str, size_type __pos, size_type __n = npos) { return this->assign(__str._M_data() + __str._M_check(__pos, "basic_string::assign"), __str._M_limit(__pos, __n)); } /** * @brief Set value to a C substring. * @param __s The C string to use. * @param __n Number of characters to use. * @return Reference to this string. * * This function sets the value of this string to the first @a __n * characters of @a __s. If @a __n is is larger than the number of * available characters in @a __s, the remainder of @a __s is used. */ basic_string& assign(const _CharT* __s, size_type __n); /** * @brief Set value to contents of a C string. * @param __s The C string to use. * @return Reference to this string. * * This function sets the value of this string to the value of @a __s. * The data is copied, so there is no dependence on @a __s once the * function returns. */ basic_string& assign(const _CharT* __s) { __glibcxx_requires_string(__s); return this->assign(__s, traits_type::length(__s)); } /** * @brief Set value to multiple characters. * @param __n Length of the resulting string. * @param __c The character to use. * @return Reference to this string. * * This function sets the value of this string to @a __n copies of * character @a __c. */ basic_string& assign(size_type __n, _CharT __c) { return _M_replace_aux(size_type(0), this->size(), __n, __c); } /** * @brief Set value to a range of characters. * @param __first Iterator referencing the first character to append. * @param __last Iterator marking the end of the range. * @return Reference to this string. * * Sets value of string to characters in the range [__first,__last). */ template basic_string& assign(_InputIterator __first, _InputIterator __last) { return this->replace(_M_ibegin(), _M_iend(), __first, __last); } #if __cplusplus >= 201103L /** * @brief Set value to an initializer_list of characters. * @param __l The initializer_list of characters to assign. * @return Reference to this string. */ basic_string& assign(initializer_list<_CharT> __l) { return this->assign(__l.begin(), __l.size()); } #endif // C++11 #if __cplusplus > 201402L /** * @brief Set value from a string_view. * @param __svt The source object convertible to string_view. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> assign(const _Tp& __svt) { __sv_type __sv = __svt; return this->assign(__sv.data(), __sv.size()); } /** * @brief Set value from a range of characters in a string_view. * @param __svt The source object convertible to string_view. * @param __pos The position in the string_view to assign from. * @param __n The number of characters to assign. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> assign(const _Tp& __svt, size_type __pos, size_type __n = npos) { __sv_type __sv = __svt; return assign(__sv.data() + __sv._M_check(__pos, "basic_string::assign"), __sv._M_limit(__pos, __n)); } #endif // C++17 /** * @brief Insert multiple characters. * @param __p Iterator referencing location in string to insert at. * @param __n Number of characters to insert * @param __c The character to insert. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts @a __n copies of character @a __c starting at the * position referenced by iterator @a __p. If adding * characters causes the length to exceed max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ void insert(iterator __p, size_type __n, _CharT __c) { this->replace(__p, __p, __n, __c); } /** * @brief Insert a range of characters. * @param __p Iterator referencing location in string to insert at. * @param __beg Start of range. * @param __end End of range. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts characters in range [__beg,__end). If adding * characters causes the length to exceed max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ template void insert(iterator __p, _InputIterator __beg, _InputIterator __end) { this->replace(__p, __p, __beg, __end); } #if __cplusplus >= 201103L /** * @brief Insert an initializer_list of characters. * @param __p Iterator referencing location in string to insert at. * @param __l The initializer_list of characters to insert. * @throw std::length_error If new length exceeds @c max_size(). */ void insert(iterator __p, initializer_list<_CharT> __l) { _GLIBCXX_DEBUG_PEDASSERT(__p >= _M_ibegin() && __p <= _M_iend()); this->insert(__p - _M_ibegin(), __l.begin(), __l.size()); } #endif // C++11 /** * @brief Insert value of a string. * @param __pos1 Iterator referencing location in string to insert at. * @param __str The string to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts value of @a __str starting at @a __pos1. If adding * characters causes the length to exceed max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& insert(size_type __pos1, const basic_string& __str) { return this->insert(__pos1, __str, size_type(0), __str.size()); } /** * @brief Insert a substring. * @param __pos1 Iterator referencing location in string to insert at. * @param __str The string to insert. * @param __pos2 Start of characters in str to insert. * @param __n Number of characters to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a pos1 > size() or * @a __pos2 > @a str.size(). * * Starting at @a pos1, insert @a __n character of @a __str * beginning with @a __pos2. If adding characters causes the * length to exceed max_size(), length_error is thrown. If @a * __pos1 is beyond the end of this string or @a __pos2 is * beyond the end of @a __str, out_of_range is thrown. The * value of the string doesn't change if an error is thrown. */ basic_string& insert(size_type __pos1, const basic_string& __str, size_type __pos2, size_type __n = npos) { return this->insert(__pos1, __str._M_data() + __str._M_check(__pos2, "basic_string::insert"), __str._M_limit(__pos2, __n)); } /** * @brief Insert a C substring. * @param __pos Iterator referencing location in string to insert at. * @param __s The C string to insert. * @param __n The number of characters to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a __pos is beyond the end of this * string. * * Inserts the first @a __n characters of @a __s starting at @a * __pos. If adding characters causes the length to exceed * max_size(), length_error is thrown. If @a __pos is beyond * end(), out_of_range is thrown. The value of the string * doesn't change if an error is thrown. */ basic_string& insert(size_type __pos, const _CharT* __s, size_type __n); /** * @brief Insert a C string. * @param __pos Iterator referencing location in string to insert at. * @param __s The C string to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a pos is beyond the end of this * string. * * Inserts the first @a n characters of @a __s starting at @a __pos. If * adding characters causes the length to exceed max_size(), * length_error is thrown. If @a __pos is beyond end(), out_of_range is * thrown. The value of the string doesn't change if an error is * thrown. */ basic_string& insert(size_type __pos, const _CharT* __s) { __glibcxx_requires_string(__s); return this->insert(__pos, __s, traits_type::length(__s)); } /** * @brief Insert multiple characters. * @param __pos Index in string to insert at. * @param __n Number of characters to insert * @param __c The character to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a __pos is beyond the end of this * string. * * Inserts @a __n copies of character @a __c starting at index * @a __pos. If adding characters causes the length to exceed * max_size(), length_error is thrown. If @a __pos > length(), * out_of_range is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& insert(size_type __pos, size_type __n, _CharT __c) { return _M_replace_aux(_M_check(__pos, "basic_string::insert"), size_type(0), __n, __c); } /** * @brief Insert one character. * @param __p Iterator referencing position in string to insert at. * @param __c The character to insert. * @return Iterator referencing newly inserted char. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts character @a __c at position referenced by @a __p. * If adding character causes the length to exceed max_size(), * length_error is thrown. If @a __p is beyond end of string, * out_of_range is thrown. The value of the string doesn't * change if an error is thrown. */ iterator insert(iterator __p, _CharT __c) { _GLIBCXX_DEBUG_PEDASSERT(__p >= _M_ibegin() && __p <= _M_iend()); const size_type __pos = __p - _M_ibegin(); _M_replace_aux(__pos, size_type(0), size_type(1), __c); _M_rep()->_M_set_leaked(); return iterator(_M_data() + __pos); } #if __cplusplus > 201402L /** * @brief Insert a string_view. * @param __pos Iterator referencing position in string to insert at. * @param __svt The object convertible to string_view to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> insert(size_type __pos, const _Tp& __svt) { __sv_type __sv = __svt; return this->insert(__pos, __sv.data(), __sv.size()); } /** * @brief Insert a string_view. * @param __pos Iterator referencing position in string to insert at. * @param __svt The object convertible to string_view to insert from. * @param __pos Iterator referencing position in string_view to insert * from. * @param __n The number of characters to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> insert(size_type __pos1, const _Tp& __svt, size_type __pos2, size_type __n = npos) { __sv_type __sv = __svt; return this->replace(__pos1, size_type(0), __sv.data() + __sv._M_check(__pos2, "basic_string::insert"), __sv._M_limit(__pos2, __n)); } #endif // C++17 /** * @brief Remove characters. * @param __pos Index of first character to remove (default 0). * @param __n Number of characters to remove (default remainder). * @return Reference to this string. * @throw std::out_of_range If @a pos is beyond the end of this * string. * * Removes @a __n characters from this string starting at @a * __pos. The length of the string is reduced by @a __n. If * there are < @a __n characters to remove, the remainder of * the string is truncated. If @a __p is beyond end of string, * out_of_range is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& erase(size_type __pos = 0, size_type __n = npos) { _M_mutate(_M_check(__pos, "basic_string::erase"), _M_limit(__pos, __n), size_type(0)); return *this; } /** * @brief Remove one character. * @param __position Iterator referencing the character to remove. * @return iterator referencing same location after removal. * * Removes the character at @a __position from this string. The value * of the string doesn't change if an error is thrown. */ iterator erase(iterator __position) { _GLIBCXX_DEBUG_PEDASSERT(__position >= _M_ibegin() && __position < _M_iend()); const size_type __pos = __position - _M_ibegin(); _M_mutate(__pos, size_type(1), size_type(0)); _M_rep()->_M_set_leaked(); return iterator(_M_data() + __pos); } /** * @brief Remove a range of characters. * @param __first Iterator referencing the first character to remove. * @param __last Iterator referencing the end of the range. * @return Iterator referencing location of first after removal. * * Removes the characters in the range [first,last) from this string. * The value of the string doesn't change if an error is thrown. */ iterator erase(iterator __first, iterator __last); #if __cplusplus >= 201103L /** * @brief Remove the last character. * * The string must be non-empty. */ void pop_back() // FIXME C++11: should be noexcept. { __glibcxx_assert(!empty()); erase(size() - 1, 1); } #endif // C++11 /** * @brief Replace characters with value from another string. * @param __pos Index of first character to replace. * @param __n Number of characters to be replaced. * @param __str String to insert. * @return Reference to this string. * @throw std::out_of_range If @a pos is beyond the end of this * string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos,__pos+__n) from * this string. In place, the value of @a __str is inserted. * If @a __pos is beyond end of string, out_of_range is thrown. * If the length of the result exceeds max_size(), length_error * is thrown. The value of the string doesn't change if an * error is thrown. */ basic_string& replace(size_type __pos, size_type __n, const basic_string& __str) { return this->replace(__pos, __n, __str._M_data(), __str.size()); } /** * @brief Replace characters with value from another string. * @param __pos1 Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __str String to insert. * @param __pos2 Index of first character of str to use. * @param __n2 Number of characters from str to use. * @return Reference to this string. * @throw std::out_of_range If @a __pos1 > size() or @a __pos2 > * __str.size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos1,__pos1 + n) from this * string. In place, the value of @a __str is inserted. If @a __pos is * beyond end of string, out_of_range is thrown. If the length of the * result exceeds max_size(), length_error is thrown. The value of the * string doesn't change if an error is thrown. */ basic_string& replace(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2 = npos) { return this->replace(__pos1, __n1, __str._M_data() + __str._M_check(__pos2, "basic_string::replace"), __str._M_limit(__pos2, __n2)); } /** * @brief Replace characters with value of a C substring. * @param __pos Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __s C string to insert. * @param __n2 Number of characters from @a s to use. * @return Reference to this string. * @throw std::out_of_range If @a pos1 > size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos,__pos + __n1) * from this string. In place, the first @a __n2 characters of * @a __s are inserted, or all of @a __s if @a __n2 is too large. If * @a __pos is beyond end of string, out_of_range is thrown. If * the length of result exceeds max_size(), length_error is * thrown. The value of the string doesn't change if an error * is thrown. */ basic_string& replace(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2); /** * @brief Replace characters with value of a C string. * @param __pos Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __s C string to insert. * @return Reference to this string. * @throw std::out_of_range If @a pos > size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos,__pos + __n1) * from this string. In place, the characters of @a __s are * inserted. If @a __pos is beyond end of string, out_of_range * is thrown. If the length of result exceeds max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& replace(size_type __pos, size_type __n1, const _CharT* __s) { __glibcxx_requires_string(__s); return this->replace(__pos, __n1, __s, traits_type::length(__s)); } /** * @brief Replace characters with multiple characters. * @param __pos Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __n2 Number of characters to insert. * @param __c Character to insert. * @return Reference to this string. * @throw std::out_of_range If @a __pos > size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [pos,pos + n1) from this * string. In place, @a __n2 copies of @a __c are inserted. * If @a __pos is beyond end of string, out_of_range is thrown. * If the length of result exceeds max_size(), length_error is * thrown. The value of the string doesn't change if an error * is thrown. */ basic_string& replace(size_type __pos, size_type __n1, size_type __n2, _CharT __c) { return _M_replace_aux(_M_check(__pos, "basic_string::replace"), _M_limit(__pos, __n1), __n2, __c); } /** * @brief Replace range of characters with string. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __str String value to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * the value of @a __str is inserted. If the length of result * exceeds max_size(), length_error is thrown. The value of * the string doesn't change if an error is thrown. */ basic_string& replace(iterator __i1, iterator __i2, const basic_string& __str) { return this->replace(__i1, __i2, __str._M_data(), __str.size()); } /** * @brief Replace range of characters with C substring. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __s C string value to insert. * @param __n Number of characters from s to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * the first @a __n characters of @a __s are inserted. If the * length of result exceeds max_size(), length_error is thrown. * The value of the string doesn't change if an error is * thrown. */ basic_string& replace(iterator __i1, iterator __i2, const _CharT* __s, size_type __n) { _GLIBCXX_DEBUG_PEDASSERT(_M_ibegin() <= __i1 && __i1 <= __i2 && __i2 <= _M_iend()); return this->replace(__i1 - _M_ibegin(), __i2 - __i1, __s, __n); } /** * @brief Replace range of characters with C string. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __s C string value to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * the characters of @a __s are inserted. If the length of * result exceeds max_size(), length_error is thrown. The * value of the string doesn't change if an error is thrown. */ basic_string& replace(iterator __i1, iterator __i2, const _CharT* __s) { __glibcxx_requires_string(__s); return this->replace(__i1, __i2, __s, traits_type::length(__s)); } /** * @brief Replace range of characters with multiple characters * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __n Number of characters to insert. * @param __c Character to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * @a __n copies of @a __c are inserted. If the length of * result exceeds max_size(), length_error is thrown. The * value of the string doesn't change if an error is thrown. */ basic_string& replace(iterator __i1, iterator __i2, size_type __n, _CharT __c) { _GLIBCXX_DEBUG_PEDASSERT(_M_ibegin() <= __i1 && __i1 <= __i2 && __i2 <= _M_iend()); return _M_replace_aux(__i1 - _M_ibegin(), __i2 - __i1, __n, __c); } /** * @brief Replace range of characters with range. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __k1 Iterator referencing start of range to insert. * @param __k2 Iterator referencing end of range to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * characters in the range [__k1,__k2) are inserted. If the * length of result exceeds max_size(), length_error is thrown. * The value of the string doesn't change if an error is * thrown. */ template basic_string& replace(iterator __i1, iterator __i2, _InputIterator __k1, _InputIterator __k2) { _GLIBCXX_DEBUG_PEDASSERT(_M_ibegin() <= __i1 && __i1 <= __i2 && __i2 <= _M_iend()); __glibcxx_requires_valid_range(__k1, __k2); typedef typename std::__is_integer<_InputIterator>::__type _Integral; return _M_replace_dispatch(__i1, __i2, __k1, __k2, _Integral()); } // Specializations for the common case of pointer and iterator: // useful to avoid the overhead of temporary buffering in _M_replace. basic_string& replace(iterator __i1, iterator __i2, _CharT* __k1, _CharT* __k2) { _GLIBCXX_DEBUG_PEDASSERT(_M_ibegin() <= __i1 && __i1 <= __i2 && __i2 <= _M_iend()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - _M_ibegin(), __i2 - __i1, __k1, __k2 - __k1); } basic_string& replace(iterator __i1, iterator __i2, const _CharT* __k1, const _CharT* __k2) { _GLIBCXX_DEBUG_PEDASSERT(_M_ibegin() <= __i1 && __i1 <= __i2 && __i2 <= _M_iend()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - _M_ibegin(), __i2 - __i1, __k1, __k2 - __k1); } basic_string& replace(iterator __i1, iterator __i2, iterator __k1, iterator __k2) { _GLIBCXX_DEBUG_PEDASSERT(_M_ibegin() <= __i1 && __i1 <= __i2 && __i2 <= _M_iend()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - _M_ibegin(), __i2 - __i1, __k1.base(), __k2 - __k1); } basic_string& replace(iterator __i1, iterator __i2, const_iterator __k1, const_iterator __k2) { _GLIBCXX_DEBUG_PEDASSERT(_M_ibegin() <= __i1 && __i1 <= __i2 && __i2 <= _M_iend()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - _M_ibegin(), __i2 - __i1, __k1.base(), __k2 - __k1); } #if __cplusplus >= 201103L /** * @brief Replace range of characters with initializer_list. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __l The initializer_list of characters to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * characters in the range [__k1,__k2) are inserted. If the * length of result exceeds max_size(), length_error is thrown. * The value of the string doesn't change if an error is * thrown. */ basic_string& replace(iterator __i1, iterator __i2, initializer_list<_CharT> __l) { return this->replace(__i1, __i2, __l.begin(), __l.end()); } #endif // C++11 #if __cplusplus > 201402L /** * @brief Replace range of characters with string_view. * @param __pos The position to replace at. * @param __n The number of characters to replace. * @param __svt The object convertible to string_view to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> replace(size_type __pos, size_type __n, const _Tp& __svt) { __sv_type __sv = __svt; return this->replace(__pos, __n, __sv.data(), __sv.size()); } /** * @brief Replace range of characters with string_view. * @param __pos1 The position to replace at. * @param __n1 The number of characters to replace. * @param __svt The object convertible to string_view to insert from. * @param __pos2 The position in the string_view to insert from. * @param __n2 The number of characters to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> replace(size_type __pos1, size_type __n1, const _Tp& __svt, size_type __pos2, size_type __n2 = npos) { __sv_type __sv = __svt; return this->replace(__pos1, __n1, __sv.data() + __sv._M_check(__pos2, "basic_string::replace"), __sv._M_limit(__pos2, __n2)); } /** * @brief Replace range of characters with string_view. * @param __i1 An iterator referencing the start position to replace at. * @param __i2 An iterator referencing the end position for the replace. * @param __svt The object convertible to string_view to insert from. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> replace(const_iterator __i1, const_iterator __i2, const _Tp& __svt) { __sv_type __sv = __svt; return this->replace(__i1 - begin(), __i2 - __i1, __sv); } #endif // C++17 private: template basic_string& _M_replace_dispatch(iterator __i1, iterator __i2, _Integer __n, _Integer __val, __true_type) { return _M_replace_aux(__i1 - _M_ibegin(), __i2 - __i1, __n, __val); } template basic_string& _M_replace_dispatch(iterator __i1, iterator __i2, _InputIterator __k1, _InputIterator __k2, __false_type); basic_string& _M_replace_aux(size_type __pos1, size_type __n1, size_type __n2, _CharT __c); basic_string& _M_replace_safe(size_type __pos1, size_type __n1, const _CharT* __s, size_type __n2); // _S_construct_aux is used to implement the 21.3.1 para 15 which // requires special behaviour if _InIter is an integral type template static _CharT* _S_construct_aux(_InIterator __beg, _InIterator __end, const _Alloc& __a, __false_type) { typedef typename iterator_traits<_InIterator>::iterator_category _Tag; return _S_construct(__beg, __end, __a, _Tag()); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template static _CharT* _S_construct_aux(_Integer __beg, _Integer __end, const _Alloc& __a, __true_type) { return _S_construct_aux_2(static_cast(__beg), __end, __a); } static _CharT* _S_construct_aux_2(size_type __req, _CharT __c, const _Alloc& __a) { return _S_construct(__req, __c, __a); } template static _CharT* _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a) { typedef typename std::__is_integer<_InIterator>::__type _Integral; return _S_construct_aux(__beg, __end, __a, _Integral()); } // For Input Iterators, used in istreambuf_iterators, etc. template static _CharT* _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a, input_iterator_tag); // For forward_iterators up to random_access_iterators, used for // string::iterator, _CharT*, etc. template static _CharT* _S_construct(_FwdIterator __beg, _FwdIterator __end, const _Alloc& __a, forward_iterator_tag); static _CharT* _S_construct(size_type __req, _CharT __c, const _Alloc& __a); public: /** * @brief Copy substring into C string. * @param __s C string to copy value into. * @param __n Number of characters to copy. * @param __pos Index of first character to copy. * @return Number of characters actually copied * @throw std::out_of_range If __pos > size(). * * Copies up to @a __n characters starting at @a __pos into the * C string @a __s. If @a __pos is %greater than size(), * out_of_range is thrown. */ size_type copy(_CharT* __s, size_type __n, size_type __pos = 0) const; /** * @brief Swap contents with another string. * @param __s String to swap with. * * Exchanges the contents of this string with that of @a __s in constant * time. */ // PR 58265, this should be noexcept. void swap(basic_string& __s); // String operations: /** * @brief Return const pointer to null-terminated contents. * * This is a handle to internal data. Do not modify or dire things may * happen. */ const _CharT* c_str() const _GLIBCXX_NOEXCEPT { return _M_data(); } /** * @brief Return const pointer to contents. * * This is a pointer to internal data. It is undefined to modify * the contents through the returned pointer. To get a pointer that * allows modifying the contents use @c &str[0] instead, * (or in C++17 the non-const @c str.data() overload). */ const _CharT* data() const _GLIBCXX_NOEXCEPT { return _M_data(); } #if __cplusplus > 201402L /** * @brief Return non-const pointer to contents. * * This is a pointer to the character sequence held by the string. * Modifying the characters in the sequence is allowed. */ _CharT* data() noexcept { _M_leak(); return _M_data(); } #endif /** * @brief Return copy of allocator used to construct this string. */ allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return _M_dataplus; } /** * @brief Find position of a C substring. * @param __s C string to locate. * @param __pos Index of character to search from. * @param __n Number of characters from @a s to search for. * @return Index of start of first occurrence. * * Starting from @a __pos, searches forward for the first @a * __n characters in @a __s within this string. If found, * returns the index where it begins. If not found, returns * npos. */ size_type find(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find position of a string. * @param __str String to locate. * @param __pos Index of character to search from (default 0). * @return Index of start of first occurrence. * * Starting from @a __pos, searches forward for value of @a __str within * this string. If found, returns the index where it begins. If not * found, returns npos. */ size_type find(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find(__str.data(), __pos, __str.size()); } /** * @brief Find position of a C string. * @param __s C string to locate. * @param __pos Index of character to search from (default 0). * @return Index of start of first occurrence. * * Starting from @a __pos, searches forward for the value of @a * __s within this string. If found, returns the index where * it begins. If not found, returns npos. */ size_type find(const _CharT* __s, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find(__s, __pos, traits_type::length(__s)); } /** * @brief Find position of a character. * @param __c Character to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for @a __c within * this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type find(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT; #if __cplusplus > 201402L /** * @brief Find position of a string_view. * @param __svt The object convertible to string_view to locate. * @param __pos Index of character to search from (default 0). * @return Index of start of first occurrence. */ template _If_sv<_Tp, size_type> find(const _Tp& __svt, size_type __pos = 0) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find last position of a string. * @param __str String to locate. * @param __pos Index of character to search back from (default end). * @return Index of start of last occurrence. * * Starting from @a __pos, searches backward for value of @a * __str within this string. If found, returns the index where * it begins. If not found, returns npos. */ size_type rfind(const basic_string& __str, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->rfind(__str.data(), __pos, __str.size()); } /** * @brief Find last position of a C substring. * @param __s C string to locate. * @param __pos Index of character to search back from. * @param __n Number of characters from s to search for. * @return Index of start of last occurrence. * * Starting from @a __pos, searches backward for the first @a * __n characters in @a __s within this string. If found, * returns the index where it begins. If not found, returns * npos. */ size_type rfind(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a C string. * @param __s C string to locate. * @param __pos Index of character to start search at (default end). * @return Index of start of last occurrence. * * Starting from @a __pos, searches backward for the value of * @a __s within this string. If found, returns the index * where it begins. If not found, returns npos. */ size_type rfind(const _CharT* __s, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->rfind(__s, __pos, traits_type::length(__s)); } /** * @brief Find last position of a character. * @param __c Character to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for @a __c within * this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type rfind(_CharT __c, size_type __pos = npos) const _GLIBCXX_NOEXCEPT; #if __cplusplus > 201402L /** * @brief Find last position of a string_view. * @param __svt The object convertible to string_view to locate. * @param __pos Index of character to search back from (default end). * @return Index of start of last occurrence. */ template _If_sv<_Tp, size_type> rfind(const _Tp& __svt, size_type __pos = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->rfind(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find position of a character of string. * @param __str String containing characters to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for one of the * characters of @a __str within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_first_of(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find_first_of(__str.data(), __pos, __str.size()); } /** * @brief Find position of a character of C substring. * @param __s String containing characters to locate. * @param __pos Index of character to search from. * @param __n Number of characters from s to search for. * @return Index of first occurrence. * * Starting from @a __pos, searches forward for one of the * first @a __n characters of @a __s within this string. If * found, returns the index where it was found. If not found, * returns npos. */ size_type find_first_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find position of a character of C string. * @param __s String containing characters to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for one of the * characters of @a __s within this string. If found, returns * the index where it was found. If not found, returns npos. */ size_type find_first_of(const _CharT* __s, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_first_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find position of a character. * @param __c Character to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for the character * @a __c within this string. If found, returns the index * where it was found. If not found, returns npos. * * Note: equivalent to find(__c, __pos). */ size_type find_first_of(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find(__c, __pos); } #if __cplusplus > 201402L /** * @brief Find position of a character of a string_view. * @param __svt An object convertible to string_view containing * characters to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. */ template _If_sv<_Tp, size_type> find_first_of(const _Tp& __svt, size_type __pos = 0) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_first_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find last position of a character of string. * @param __str String containing characters to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for one of the * characters of @a __str within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_last_of(const basic_string& __str, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->find_last_of(__str.data(), __pos, __str.size()); } /** * @brief Find last position of a character of C substring. * @param __s C string containing characters to locate. * @param __pos Index of character to search back from. * @param __n Number of characters from s to search for. * @return Index of last occurrence. * * Starting from @a __pos, searches backward for one of the * first @a __n characters of @a __s within this string. If * found, returns the index where it was found. If not found, * returns npos. */ size_type find_last_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a character of C string. * @param __s C string containing characters to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for one of the * characters of @a __s within this string. If found, returns * the index where it was found. If not found, returns npos. */ size_type find_last_of(const _CharT* __s, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_last_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find last position of a character. * @param __c Character to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for @a __c within * this string. If found, returns the index where it was * found. If not found, returns npos. * * Note: equivalent to rfind(__c, __pos). */ size_type find_last_of(_CharT __c, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->rfind(__c, __pos); } #if __cplusplus > 201402L /** * @brief Find last position of a character of string. * @param __svt An object convertible to string_view containing * characters to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. */ template _If_sv<_Tp, size_type> find_last_of(const _Tp& __svt, size_type __pos = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_last_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find position of a character not in string. * @param __str String containing characters to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character not contained * in @a __str within this string. If found, returns the index where it * was found. If not found, returns npos. */ size_type find_first_not_of(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find_first_not_of(__str.data(), __pos, __str.size()); } /** * @brief Find position of a character not in C substring. * @param __s C string containing characters to avoid. * @param __pos Index of character to search from. * @param __n Number of characters from __s to consider. * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character not * contained in the first @a __n characters of @a __s within * this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find position of a character not in C string. * @param __s C string containing characters to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character not * contained in @a __s within this string. If found, returns * the index where it was found. If not found, returns npos. */ size_type find_first_not_of(const _CharT* __s, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_first_not_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find position of a different character. * @param __c Character to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character * other than @a __c within this string. If found, returns the * index where it was found. If not found, returns npos. */ size_type find_first_not_of(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT; #if __cplusplus > 201402L /** * @brief Find position of a character not in a string_view. * @param __svt An object convertible to string_view containing * characters to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. */ template _If_sv<_Tp, size_type> find_first_not_of(const _Tp& __svt, size_type __pos = 0) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_first_not_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find last position of a character not in string. * @param __str String containing characters to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character * not contained in @a __str within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_last_not_of(const basic_string& __str, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->find_last_not_of(__str.data(), __pos, __str.size()); } /** * @brief Find last position of a character not in C substring. * @param __s C string containing characters to avoid. * @param __pos Index of character to search back from. * @param __n Number of characters from s to consider. * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character not * contained in the first @a __n characters of @a __s within this string. * If found, returns the index where it was found. If not found, * returns npos. */ size_type find_last_not_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a character not in C string. * @param __s C string containing characters to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character * not contained in @a __s within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_last_not_of(const _CharT* __s, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_last_not_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find last position of a different character. * @param __c Character to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character other than * @a __c within this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type find_last_not_of(_CharT __c, size_type __pos = npos) const _GLIBCXX_NOEXCEPT; #if __cplusplus > 201402L /** * @brief Find last position of a character not in a string_view. * @param __svt An object convertible to string_view containing * characters to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. */ template _If_sv<_Tp, size_type> find_last_not_of(const _Tp& __svt, size_type __pos = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_last_not_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Get a substring. * @param __pos Index of first character (default 0). * @param __n Number of characters in substring (default remainder). * @return The new string. * @throw std::out_of_range If __pos > size(). * * Construct and return a new string using the @a __n * characters starting at @a __pos. If the string is too * short, use the remainder of the characters. If @a __pos is * beyond the end of the string, out_of_range is thrown. */ basic_string substr(size_type __pos = 0, size_type __n = npos) const { return basic_string(*this, _M_check(__pos, "basic_string::substr"), __n); } /** * @brief Compare to a string. * @param __str String to compare against. * @return Integer < 0, 0, or > 0. * * Returns an integer < 0 if this string is ordered before @a * __str, 0 if their values are equivalent, or > 0 if this * string is ordered after @a __str. Determines the effective * length rlen of the strings to compare as the smallest of * size() and str.size(). The function then compares the two * strings by calling traits::compare(data(), str.data(),rlen). * If the result of the comparison is nonzero returns it, * otherwise the shorter one is ordered first. */ int compare(const basic_string& __str) const { const size_type __size = this->size(); const size_type __osize = __str.size(); const size_type __len = std::min(__size, __osize); int __r = traits_type::compare(_M_data(), __str.data(), __len); if (!__r) __r = _S_compare(__size, __osize); return __r; } #if __cplusplus > 201402L /** * @brief Compare to a string_view. * @param __svt An object convertible to string_view to compare against. * @return Integer < 0, 0, or > 0. */ template _If_sv<_Tp, int> compare(const _Tp& __svt) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; const size_type __size = this->size(); const size_type __osize = __sv.size(); const size_type __len = std::min(__size, __osize); int __r = traits_type::compare(_M_data(), __sv.data(), __len); if (!__r) __r = _S_compare(__size, __osize); return __r; } /** * @brief Compare to a string_view. * @param __pos A position in the string to start comparing from. * @param __n The number of characters to compare. * @param __svt An object convertible to string_view to compare * against. * @return Integer < 0, 0, or > 0. */ template _If_sv<_Tp, int> compare(size_type __pos, size_type __n, const _Tp& __svt) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return __sv_type(*this).substr(__pos, __n).compare(__sv); } /** * @brief Compare to a string_view. * @param __pos1 A position in the string to start comparing from. * @param __n1 The number of characters to compare. * @param __svt An object convertible to string_view to compare * against. * @param __pos2 A position in the string_view to start comparing from. * @param __n2 The number of characters to compare. * @return Integer < 0, 0, or > 0. */ template _If_sv<_Tp, int> compare(size_type __pos1, size_type __n1, const _Tp& __svt, size_type __pos2, size_type __n2 = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return __sv_type(*this) .substr(__pos1, __n1).compare(__sv.substr(__pos2, __n2)); } #endif // C++17 /** * @brief Compare substring to a string. * @param __pos Index of first character of substring. * @param __n Number of characters in substring. * @param __str String to compare against. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n characters * starting at @a __pos. Returns an integer < 0 if the * substring is ordered before @a __str, 0 if their values are * equivalent, or > 0 if the substring is ordered after @a * __str. Determines the effective length rlen of the strings * to compare as the smallest of the length of the substring * and @a __str.size(). The function then compares the two * strings by calling * traits::compare(substring.data(),str.data(),rlen). If the * result of the comparison is nonzero returns it, otherwise * the shorter one is ordered first. */ int compare(size_type __pos, size_type __n, const basic_string& __str) const; /** * @brief Compare substring to a substring. * @param __pos1 Index of first character of substring. * @param __n1 Number of characters in substring. * @param __str String to compare against. * @param __pos2 Index of first character of substring of str. * @param __n2 Number of characters in substring of str. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n1 * characters starting at @a __pos1. Form the substring of @a * __str from the @a __n2 characters starting at @a __pos2. * Returns an integer < 0 if this substring is ordered before * the substring of @a __str, 0 if their values are equivalent, * or > 0 if this substring is ordered after the substring of * @a __str. Determines the effective length rlen of the * strings to compare as the smallest of the lengths of the * substrings. The function then compares the two strings by * calling * traits::compare(substring.data(),str.substr(pos2,n2).data(),rlen). * If the result of the comparison is nonzero returns it, * otherwise the shorter one is ordered first. */ int compare(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2 = npos) const; /** * @brief Compare to a C string. * @param __s C string to compare against. * @return Integer < 0, 0, or > 0. * * Returns an integer < 0 if this string is ordered before @a __s, 0 if * their values are equivalent, or > 0 if this string is ordered after * @a __s. Determines the effective length rlen of the strings to * compare as the smallest of size() and the length of a string * constructed from @a __s. The function then compares the two strings * by calling traits::compare(data(),s,rlen). If the result of the * comparison is nonzero returns it, otherwise the shorter one is * ordered first. */ int compare(const _CharT* __s) const _GLIBCXX_NOEXCEPT; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 5 String::compare specification questionable /** * @brief Compare substring to a C string. * @param __pos Index of first character of substring. * @param __n1 Number of characters in substring. * @param __s C string to compare against. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n1 * characters starting at @a pos. Returns an integer < 0 if * the substring is ordered before @a __s, 0 if their values * are equivalent, or > 0 if the substring is ordered after @a * __s. Determines the effective length rlen of the strings to * compare as the smallest of the length of the substring and * the length of a string constructed from @a __s. The * function then compares the two string by calling * traits::compare(substring.data(),__s,rlen). If the result of * the comparison is nonzero returns it, otherwise the shorter * one is ordered first. */ int compare(size_type __pos, size_type __n1, const _CharT* __s) const; /** * @brief Compare substring against a character %array. * @param __pos Index of first character of substring. * @param __n1 Number of characters in substring. * @param __s character %array to compare against. * @param __n2 Number of characters of s. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n1 * characters starting at @a __pos. Form a string from the * first @a __n2 characters of @a __s. Returns an integer < 0 * if this substring is ordered before the string from @a __s, * 0 if their values are equivalent, or > 0 if this substring * is ordered after the string from @a __s. Determines the * effective length rlen of the strings to compare as the * smallest of the length of the substring and @a __n2. The * function then compares the two strings by calling * traits::compare(substring.data(),s,rlen). If the result of * the comparison is nonzero returns it, otherwise the shorter * one is ordered first. * * NB: s must have at least n2 characters, '\\0' has * no special meaning. */ int compare(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2) const; # ifdef _GLIBCXX_TM_TS_INTERNAL friend void ::_txnal_cow_string_C1_for_exceptions(void* that, const char* s, void* exc); friend const char* ::_txnal_cow_string_c_str(const void *that); friend void ::_txnal_cow_string_D1(void *that); friend void ::_txnal_cow_string_D1_commit(void *that); # endif }; #endif // !_GLIBCXX_USE_CXX11_ABI #if __cpp_deduction_guides >= 201606 _GLIBCXX_BEGIN_NAMESPACE_CXX11 template::value_type, typename _Allocator = allocator<_CharT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> basic_string(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> basic_string<_CharT, char_traits<_CharT>, _Allocator>; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 3075. basic_string needs deduction guides from basic_string_view template, typename = _RequireAllocator<_Allocator>> basic_string(basic_string_view<_CharT, _Traits>, const _Allocator& = _Allocator()) -> basic_string<_CharT, _Traits, _Allocator>; template, typename = _RequireAllocator<_Allocator>> basic_string(basic_string_view<_CharT, _Traits>, typename basic_string<_CharT, _Traits, _Allocator>::size_type, typename basic_string<_CharT, _Traits, _Allocator>::size_type, const _Allocator& = _Allocator()) -> basic_string<_CharT, _Traits, _Allocator>; _GLIBCXX_END_NAMESPACE_CXX11 #endif // operator+ /** * @brief Concatenate two strings. * @param __lhs First string. * @param __rhs Last string. * @return New string with value of @a __lhs followed by @a __rhs. */ template basic_string<_CharT, _Traits, _Alloc> operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { basic_string<_CharT, _Traits, _Alloc> __str(__lhs); __str.append(__rhs); return __str; } /** * @brief Concatenate C string and string. * @param __lhs First string. * @param __rhs Last string. * @return New string with value of @a __lhs followed by @a __rhs. */ template basic_string<_CharT,_Traits,_Alloc> operator+(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Alloc>& __rhs); /** * @brief Concatenate character and string. * @param __lhs First string. * @param __rhs Last string. * @return New string with @a __lhs followed by @a __rhs. */ template basic_string<_CharT,_Traits,_Alloc> operator+(_CharT __lhs, const basic_string<_CharT,_Traits,_Alloc>& __rhs); /** * @brief Concatenate string and C string. * @param __lhs First string. * @param __rhs Last string. * @return New string with @a __lhs followed by @a __rhs. */ template inline basic_string<_CharT, _Traits, _Alloc> operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const _CharT* __rhs) { basic_string<_CharT, _Traits, _Alloc> __str(__lhs); __str.append(__rhs); return __str; } /** * @brief Concatenate string and character. * @param __lhs First string. * @param __rhs Last string. * @return New string with @a __lhs followed by @a __rhs. */ template inline basic_string<_CharT, _Traits, _Alloc> operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs, _CharT __rhs) { typedef basic_string<_CharT, _Traits, _Alloc> __string_type; typedef typename __string_type::size_type __size_type; __string_type __str(__lhs); __str.append(__size_type(1), __rhs); return __str; } #if __cplusplus >= 201103L template inline basic_string<_CharT, _Traits, _Alloc> operator+(basic_string<_CharT, _Traits, _Alloc>&& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { return std::move(__lhs.append(__rhs)); } template inline basic_string<_CharT, _Traits, _Alloc> operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs, basic_string<_CharT, _Traits, _Alloc>&& __rhs) { return std::move(__rhs.insert(0, __lhs)); } template inline basic_string<_CharT, _Traits, _Alloc> operator+(basic_string<_CharT, _Traits, _Alloc>&& __lhs, basic_string<_CharT, _Traits, _Alloc>&& __rhs) { const auto __size = __lhs.size() + __rhs.size(); const bool __cond = (__size > __lhs.capacity() && __size <= __rhs.capacity()); return __cond ? std::move(__rhs.insert(0, __lhs)) : std::move(__lhs.append(__rhs)); } template inline basic_string<_CharT, _Traits, _Alloc> operator+(const _CharT* __lhs, basic_string<_CharT, _Traits, _Alloc>&& __rhs) { return std::move(__rhs.insert(0, __lhs)); } template inline basic_string<_CharT, _Traits, _Alloc> operator+(_CharT __lhs, basic_string<_CharT, _Traits, _Alloc>&& __rhs) { return std::move(__rhs.insert(0, 1, __lhs)); } template inline basic_string<_CharT, _Traits, _Alloc> operator+(basic_string<_CharT, _Traits, _Alloc>&& __lhs, const _CharT* __rhs) { return std::move(__lhs.append(__rhs)); } template inline basic_string<_CharT, _Traits, _Alloc> operator+(basic_string<_CharT, _Traits, _Alloc>&& __lhs, _CharT __rhs) { return std::move(__lhs.append(1, __rhs)); } #endif // operator == /** * @brief Test equivalence of two strings. * @param __lhs First string. * @param __rhs Second string. * @return True if @a __lhs.compare(@a __rhs) == 0. False otherwise. */ template inline bool operator==(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.compare(__rhs) == 0; } template inline typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, bool>::__type operator==(const basic_string<_CharT>& __lhs, const basic_string<_CharT>& __rhs) _GLIBCXX_NOEXCEPT { return (__lhs.size() == __rhs.size() && !std::char_traits<_CharT>::compare(__lhs.data(), __rhs.data(), __lhs.size())); } /** * @brief Test equivalence of C string and string. * @param __lhs C string. * @param __rhs String. * @return True if @a __rhs.compare(@a __lhs) == 0. False otherwise. */ template inline bool operator==(const _CharT* __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { return __rhs.compare(__lhs) == 0; } /** * @brief Test equivalence of string and C string. * @param __lhs String. * @param __rhs C string. * @return True if @a __lhs.compare(@a __rhs) == 0. False otherwise. */ template inline bool operator==(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const _CharT* __rhs) { return __lhs.compare(__rhs) == 0; } // operator != /** * @brief Test difference of two strings. * @param __lhs First string. * @param __rhs Second string. * @return True if @a __lhs.compare(@a __rhs) != 0. False otherwise. */ template inline bool operator!=(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT { return !(__lhs == __rhs); } /** * @brief Test difference of C string and string. * @param __lhs C string. * @param __rhs String. * @return True if @a __rhs.compare(@a __lhs) != 0. False otherwise. */ template inline bool operator!=(const _CharT* __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { return !(__lhs == __rhs); } /** * @brief Test difference of string and C string. * @param __lhs String. * @param __rhs C string. * @return True if @a __lhs.compare(@a __rhs) != 0. False otherwise. */ template inline bool operator!=(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const _CharT* __rhs) { return !(__lhs == __rhs); } // operator < /** * @brief Test if string precedes string. * @param __lhs First string. * @param __rhs Second string. * @return True if @a __lhs precedes @a __rhs. False otherwise. */ template inline bool operator<(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.compare(__rhs) < 0; } /** * @brief Test if string precedes C string. * @param __lhs String. * @param __rhs C string. * @return True if @a __lhs precedes @a __rhs. False otherwise. */ template inline bool operator<(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const _CharT* __rhs) { return __lhs.compare(__rhs) < 0; } /** * @brief Test if C string precedes string. * @param __lhs C string. * @param __rhs String. * @return True if @a __lhs precedes @a __rhs. False otherwise. */ template inline bool operator<(const _CharT* __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { return __rhs.compare(__lhs) > 0; } // operator > /** * @brief Test if string follows string. * @param __lhs First string. * @param __rhs Second string. * @return True if @a __lhs follows @a __rhs. False otherwise. */ template inline bool operator>(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.compare(__rhs) > 0; } /** * @brief Test if string follows C string. * @param __lhs String. * @param __rhs C string. * @return True if @a __lhs follows @a __rhs. False otherwise. */ template inline bool operator>(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const _CharT* __rhs) { return __lhs.compare(__rhs) > 0; } /** * @brief Test if C string follows string. * @param __lhs C string. * @param __rhs String. * @return True if @a __lhs follows @a __rhs. False otherwise. */ template inline bool operator>(const _CharT* __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { return __rhs.compare(__lhs) < 0; } // operator <= /** * @brief Test if string doesn't follow string. * @param __lhs First string. * @param __rhs Second string. * @return True if @a __lhs doesn't follow @a __rhs. False otherwise. */ template inline bool operator<=(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.compare(__rhs) <= 0; } /** * @brief Test if string doesn't follow C string. * @param __lhs String. * @param __rhs C string. * @return True if @a __lhs doesn't follow @a __rhs. False otherwise. */ template inline bool operator<=(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const _CharT* __rhs) { return __lhs.compare(__rhs) <= 0; } /** * @brief Test if C string doesn't follow string. * @param __lhs C string. * @param __rhs String. * @return True if @a __lhs doesn't follow @a __rhs. False otherwise. */ template inline bool operator<=(const _CharT* __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { return __rhs.compare(__lhs) >= 0; } // operator >= /** * @brief Test if string doesn't precede string. * @param __lhs First string. * @param __rhs Second string. * @return True if @a __lhs doesn't precede @a __rhs. False otherwise. */ template inline bool operator>=(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.compare(__rhs) >= 0; } /** * @brief Test if string doesn't precede C string. * @param __lhs String. * @param __rhs C string. * @return True if @a __lhs doesn't precede @a __rhs. False otherwise. */ template inline bool operator>=(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const _CharT* __rhs) { return __lhs.compare(__rhs) >= 0; } /** * @brief Test if C string doesn't precede string. * @param __lhs C string. * @param __rhs String. * @return True if @a __lhs doesn't precede @a __rhs. False otherwise. */ template inline bool operator>=(const _CharT* __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { return __rhs.compare(__lhs) <= 0; } /** * @brief Swap contents of two strings. * @param __lhs First string. * @param __rhs Second string. * * Exchanges the contents of @a __lhs and @a __rhs in constant time. */ template inline void swap(basic_string<_CharT, _Traits, _Alloc>& __lhs, basic_string<_CharT, _Traits, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT_IF(noexcept(__lhs.swap(__rhs))) { __lhs.swap(__rhs); } /** * @brief Read stream into a string. * @param __is Input stream. * @param __str Buffer to store into. * @return Reference to the input stream. * * Stores characters from @a __is into @a __str until whitespace is * found, the end of the stream is encountered, or str.max_size() * is reached. If is.width() is non-zero, that is the limit on the * number of characters stored into @a __str. Any previous * contents of @a __str are erased. */ template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __is, basic_string<_CharT, _Traits, _Alloc>& __str); template<> basic_istream& operator>>(basic_istream& __is, basic_string& __str); /** * @brief Write string to a stream. * @param __os Output stream. * @param __str String to write out. * @return Reference to the output stream. * * Output characters of @a __str into os following the same rules as for * writing a C string. */ template inline basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, const basic_string<_CharT, _Traits, _Alloc>& __str) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 586. string inserter not a formatted function return __ostream_insert(__os, __str.data(), __str.size()); } /** * @brief Read a line from stream into a string. * @param __is Input stream. * @param __str Buffer to store into. * @param __delim Character marking end of line. * @return Reference to the input stream. * * Stores characters from @a __is into @a __str until @a __delim is * found, the end of the stream is encountered, or str.max_size() * is reached. Any previous contents of @a __str are erased. If * @a __delim is encountered, it is extracted but not stored into * @a __str. */ template basic_istream<_CharT, _Traits>& getline(basic_istream<_CharT, _Traits>& __is, basic_string<_CharT, _Traits, _Alloc>& __str, _CharT __delim); /** * @brief Read a line from stream into a string. * @param __is Input stream. * @param __str Buffer to store into. * @return Reference to the input stream. * * Stores characters from is into @a __str until '\n' is * found, the end of the stream is encountered, or str.max_size() * is reached. Any previous contents of @a __str are erased. If * end of line is encountered, it is extracted but not stored into * @a __str. */ template inline basic_istream<_CharT, _Traits>& getline(basic_istream<_CharT, _Traits>& __is, basic_string<_CharT, _Traits, _Alloc>& __str) { return std::getline(__is, __str, __is.widen('\n')); } #if __cplusplus >= 201103L /// Read a line from an rvalue stream into a string. template inline basic_istream<_CharT, _Traits>& getline(basic_istream<_CharT, _Traits>&& __is, basic_string<_CharT, _Traits, _Alloc>& __str, _CharT __delim) { return std::getline(__is, __str, __delim); } /// Read a line from an rvalue stream into a string. template inline basic_istream<_CharT, _Traits>& getline(basic_istream<_CharT, _Traits>&& __is, basic_string<_CharT, _Traits, _Alloc>& __str) { return std::getline(__is, __str); } #endif template<> basic_istream& getline(basic_istream& __in, basic_string& __str, char __delim); #ifdef _GLIBCXX_USE_WCHAR_T template<> basic_istream& getline(basic_istream& __in, basic_string& __str, wchar_t __delim); #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #if __cplusplus >= 201103L #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CXX11 #if _GLIBCXX_USE_C99_STDLIB // 21.4 Numeric Conversions [string.conversions]. inline int stoi(const string& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::strtol, "stoi", __str.c_str(), __idx, __base); } inline long stol(const string& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::strtol, "stol", __str.c_str(), __idx, __base); } inline unsigned long stoul(const string& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::strtoul, "stoul", __str.c_str(), __idx, __base); } inline long long stoll(const string& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::strtoll, "stoll", __str.c_str(), __idx, __base); } inline unsigned long long stoull(const string& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::strtoull, "stoull", __str.c_str(), __idx, __base); } // NB: strtof vs strtod. inline float stof(const string& __str, size_t* __idx = 0) { return __gnu_cxx::__stoa(&std::strtof, "stof", __str.c_str(), __idx); } inline double stod(const string& __str, size_t* __idx = 0) { return __gnu_cxx::__stoa(&std::strtod, "stod", __str.c_str(), __idx); } inline long double stold(const string& __str, size_t* __idx = 0) { return __gnu_cxx::__stoa(&std::strtold, "stold", __str.c_str(), __idx); } #endif // _GLIBCXX_USE_C99_STDLIB #if _GLIBCXX_USE_C99_STDIO // NB: (v)snprintf vs sprintf. // DR 1261. inline string to_string(int __val) { return __gnu_cxx::__to_xstring(&std::vsnprintf, 4 * sizeof(int), "%d", __val); } inline string to_string(unsigned __val) { return __gnu_cxx::__to_xstring(&std::vsnprintf, 4 * sizeof(unsigned), "%u", __val); } inline string to_string(long __val) { return __gnu_cxx::__to_xstring(&std::vsnprintf, 4 * sizeof(long), "%ld", __val); } inline string to_string(unsigned long __val) { return __gnu_cxx::__to_xstring(&std::vsnprintf, 4 * sizeof(unsigned long), "%lu", __val); } inline string to_string(long long __val) { return __gnu_cxx::__to_xstring(&std::vsnprintf, 4 * sizeof(long long), "%lld", __val); } inline string to_string(unsigned long long __val) { return __gnu_cxx::__to_xstring(&std::vsnprintf, 4 * sizeof(unsigned long long), "%llu", __val); } inline string to_string(float __val) { const int __n = __gnu_cxx::__numeric_traits::__max_exponent10 + 20; return __gnu_cxx::__to_xstring(&std::vsnprintf, __n, "%f", __val); } inline string to_string(double __val) { const int __n = __gnu_cxx::__numeric_traits::__max_exponent10 + 20; return __gnu_cxx::__to_xstring(&std::vsnprintf, __n, "%f", __val); } inline string to_string(long double __val) { const int __n = __gnu_cxx::__numeric_traits::__max_exponent10 + 20; return __gnu_cxx::__to_xstring(&std::vsnprintf, __n, "%Lf", __val); } #endif // _GLIBCXX_USE_C99_STDIO #if defined(_GLIBCXX_USE_WCHAR_T) && _GLIBCXX_USE_C99_WCHAR inline int stoi(const wstring& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::wcstol, "stoi", __str.c_str(), __idx, __base); } inline long stol(const wstring& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::wcstol, "stol", __str.c_str(), __idx, __base); } inline unsigned long stoul(const wstring& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::wcstoul, "stoul", __str.c_str(), __idx, __base); } inline long long stoll(const wstring& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::wcstoll, "stoll", __str.c_str(), __idx, __base); } inline unsigned long long stoull(const wstring& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::wcstoull, "stoull", __str.c_str(), __idx, __base); } // NB: wcstof vs wcstod. inline float stof(const wstring& __str, size_t* __idx = 0) { return __gnu_cxx::__stoa(&std::wcstof, "stof", __str.c_str(), __idx); } inline double stod(const wstring& __str, size_t* __idx = 0) { return __gnu_cxx::__stoa(&std::wcstod, "stod", __str.c_str(), __idx); } inline long double stold(const wstring& __str, size_t* __idx = 0) { return __gnu_cxx::__stoa(&std::wcstold, "stold", __str.c_str(), __idx); } #ifndef _GLIBCXX_HAVE_BROKEN_VSWPRINTF // DR 1261. inline wstring to_wstring(int __val) { return __gnu_cxx::__to_xstring(&std::vswprintf, 4 * sizeof(int), L"%d", __val); } inline wstring to_wstring(unsigned __val) { return __gnu_cxx::__to_xstring(&std::vswprintf, 4 * sizeof(unsigned), L"%u", __val); } inline wstring to_wstring(long __val) { return __gnu_cxx::__to_xstring(&std::vswprintf, 4 * sizeof(long), L"%ld", __val); } inline wstring to_wstring(unsigned long __val) { return __gnu_cxx::__to_xstring(&std::vswprintf, 4 * sizeof(unsigned long), L"%lu", __val); } inline wstring to_wstring(long long __val) { return __gnu_cxx::__to_xstring(&std::vswprintf, 4 * sizeof(long long), L"%lld", __val); } inline wstring to_wstring(unsigned long long __val) { return __gnu_cxx::__to_xstring(&std::vswprintf, 4 * sizeof(unsigned long long), L"%llu", __val); } inline wstring to_wstring(float __val) { const int __n = __gnu_cxx::__numeric_traits::__max_exponent10 + 20; return __gnu_cxx::__to_xstring(&std::vswprintf, __n, L"%f", __val); } inline wstring to_wstring(double __val) { const int __n = __gnu_cxx::__numeric_traits::__max_exponent10 + 20; return __gnu_cxx::__to_xstring(&std::vswprintf, __n, L"%f", __val); } inline wstring to_wstring(long double __val) { const int __n = __gnu_cxx::__numeric_traits::__max_exponent10 + 20; return __gnu_cxx::__to_xstring(&std::vswprintf, __n, L"%Lf", __val); } #endif // _GLIBCXX_HAVE_BROKEN_VSWPRINTF #endif // _GLIBCXX_USE_WCHAR_T && _GLIBCXX_USE_C99_WCHAR _GLIBCXX_END_NAMESPACE_CXX11 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* C++11 */ #if __cplusplus >= 201103L #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // DR 1182. #ifndef _GLIBCXX_COMPATIBILITY_CXX0X /// std::hash specialization for string. template<> struct hash : public __hash_base { size_t operator()(const string& __s) const noexcept { return std::_Hash_impl::hash(__s.data(), __s.length()); } }; template<> struct __is_fast_hash> : std::false_type { }; #ifdef _GLIBCXX_USE_WCHAR_T /// std::hash specialization for wstring. template<> struct hash : public __hash_base { size_t operator()(const wstring& __s) const noexcept { return std::_Hash_impl::hash(__s.data(), __s.length() * sizeof(wchar_t)); } }; template<> struct __is_fast_hash> : std::false_type { }; #endif #endif /* _GLIBCXX_COMPATIBILITY_CXX0X */ #ifdef _GLIBCXX_USE_C99_STDINT_TR1 /// std::hash specialization for u16string. template<> struct hash : public __hash_base { size_t operator()(const u16string& __s) const noexcept { return std::_Hash_impl::hash(__s.data(), __s.length() * sizeof(char16_t)); } }; template<> struct __is_fast_hash> : std::false_type { }; /// std::hash specialization for u32string. template<> struct hash : public __hash_base { size_t operator()(const u32string& __s) const noexcept { return std::_Hash_impl::hash(__s.data(), __s.length() * sizeof(char32_t)); } }; template<> struct __is_fast_hash> : std::false_type { }; #endif #if __cplusplus > 201103L #define __cpp_lib_string_udls 201304 inline namespace literals { inline namespace string_literals { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wliteral-suffix" _GLIBCXX_DEFAULT_ABI_TAG inline basic_string operator""s(const char* __str, size_t __len) { return basic_string{__str, __len}; } #ifdef _GLIBCXX_USE_WCHAR_T _GLIBCXX_DEFAULT_ABI_TAG inline basic_string operator""s(const wchar_t* __str, size_t __len) { return basic_string{__str, __len}; } #endif #ifdef _GLIBCXX_USE_C99_STDINT_TR1 _GLIBCXX_DEFAULT_ABI_TAG inline basic_string operator""s(const char16_t* __str, size_t __len) { return basic_string{__str, __len}; } _GLIBCXX_DEFAULT_ABI_TAG inline basic_string operator""s(const char32_t* __str, size_t __len) { return basic_string{__str, __len}; } #endif #pragma GCC diagnostic pop } // inline namespace string_literals } // inline namespace literals #endif // __cplusplus > 201103L _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif /* _BASIC_STRING_H */ PK!u8/bits/basic_string.tccnu[// Components for manipulating sequences of characters -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/basic_string.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{string} */ // // ISO C++ 14882: 21 Strings library // // Written by Jason Merrill based upon the specification by Takanori Adachi // in ANSI X3J16/94-0013R2. Rewritten by Nathan Myers to ISO-14882. // Non-reference-counted implementation written by Paolo Carlini and // updated by Jonathan Wakely for ISO-14882-2011. #ifndef _BASIC_STRING_TCC #define _BASIC_STRING_TCC 1 #pragma GCC system_header #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if _GLIBCXX_USE_CXX11_ABI template const typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>::npos; template void basic_string<_CharT, _Traits, _Alloc>:: swap(basic_string& __s) _GLIBCXX_NOEXCEPT { if (this == &__s) return; _Alloc_traits::_S_on_swap(_M_get_allocator(), __s._M_get_allocator()); if (_M_is_local()) if (__s._M_is_local()) { if (length() && __s.length()) { _CharT __tmp_data[_S_local_capacity + 1]; traits_type::copy(__tmp_data, __s._M_local_buf, _S_local_capacity + 1); traits_type::copy(__s._M_local_buf, _M_local_buf, _S_local_capacity + 1); traits_type::copy(_M_local_buf, __tmp_data, _S_local_capacity + 1); } else if (__s.length()) { traits_type::copy(_M_local_buf, __s._M_local_buf, _S_local_capacity + 1); _M_length(__s.length()); __s._M_set_length(0); return; } else if (length()) { traits_type::copy(__s._M_local_buf, _M_local_buf, _S_local_capacity + 1); __s._M_length(length()); _M_set_length(0); return; } } else { const size_type __tmp_capacity = __s._M_allocated_capacity; traits_type::copy(__s._M_local_buf, _M_local_buf, _S_local_capacity + 1); _M_data(__s._M_data()); __s._M_data(__s._M_local_buf); _M_capacity(__tmp_capacity); } else { const size_type __tmp_capacity = _M_allocated_capacity; if (__s._M_is_local()) { traits_type::copy(_M_local_buf, __s._M_local_buf, _S_local_capacity + 1); __s._M_data(_M_data()); _M_data(_M_local_buf); } else { pointer __tmp_ptr = _M_data(); _M_data(__s._M_data()); __s._M_data(__tmp_ptr); _M_capacity(__s._M_allocated_capacity); } __s._M_capacity(__tmp_capacity); } const size_type __tmp_length = length(); _M_length(__s.length()); __s._M_length(__tmp_length); } template typename basic_string<_CharT, _Traits, _Alloc>::pointer basic_string<_CharT, _Traits, _Alloc>:: _M_create(size_type& __capacity, size_type __old_capacity) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 83. String::npos vs. string::max_size() if (__capacity > max_size()) std::__throw_length_error(__N("basic_string::_M_create")); // The below implements an exponential growth policy, necessary to // meet amortized linear time requirements of the library: see // http://gcc.gnu.org/ml/libstdc++/2001-07/msg00085.html. if (__capacity > __old_capacity && __capacity < 2 * __old_capacity) { __capacity = 2 * __old_capacity; // Never allocate a string bigger than max_size. if (__capacity > max_size()) __capacity = max_size(); } // NB: Need an array of char_type[__capacity], plus a terminating // null char_type() element. return _Alloc_traits::allocate(_M_get_allocator(), __capacity + 1); } // NB: This is the special case for Input Iterators, used in // istreambuf_iterators, etc. // Input Iterators have a cost structure very different from // pointers, calling for a different coding style. template template void basic_string<_CharT, _Traits, _Alloc>:: _M_construct(_InIterator __beg, _InIterator __end, std::input_iterator_tag) { size_type __len = 0; size_type __capacity = size_type(_S_local_capacity); while (__beg != __end && __len < __capacity) { _M_data()[__len++] = *__beg; ++__beg; } __try { while (__beg != __end) { if (__len == __capacity) { // Allocate more space. __capacity = __len + 1; pointer __another = _M_create(__capacity, __len); this->_S_copy(__another, _M_data(), __len); _M_dispose(); _M_data(__another); _M_capacity(__capacity); } _M_data()[__len++] = *__beg; ++__beg; } } __catch(...) { _M_dispose(); __throw_exception_again; } _M_set_length(__len); } template template void basic_string<_CharT, _Traits, _Alloc>:: _M_construct(_InIterator __beg, _InIterator __end, std::forward_iterator_tag) { // NB: Not required, but considered best practice. if (__gnu_cxx::__is_null_pointer(__beg) && __beg != __end) std::__throw_logic_error(__N("basic_string::" "_M_construct null not valid")); size_type __dnew = static_cast(std::distance(__beg, __end)); if (__dnew > size_type(_S_local_capacity)) { _M_data(_M_create(__dnew, size_type(0))); _M_capacity(__dnew); } // Check for out_of_range and length_error exceptions. __try { this->_S_copy_chars(_M_data(), __beg, __end); } __catch(...) { _M_dispose(); __throw_exception_again; } _M_set_length(__dnew); } template void basic_string<_CharT, _Traits, _Alloc>:: _M_construct(size_type __n, _CharT __c) { if (__n > size_type(_S_local_capacity)) { _M_data(_M_create(__n, size_type(0))); _M_capacity(__n); } if (__n) this->_S_assign(_M_data(), __n, __c); _M_set_length(__n); } template void basic_string<_CharT, _Traits, _Alloc>:: _M_assign(const basic_string& __str) { if (this != &__str) { const size_type __rsize = __str.length(); const size_type __capacity = capacity(); if (__rsize > __capacity) { size_type __new_capacity = __rsize; pointer __tmp = _M_create(__new_capacity, __capacity); _M_dispose(); _M_data(__tmp); _M_capacity(__new_capacity); } if (__rsize) this->_S_copy(_M_data(), __str._M_data(), __rsize); _M_set_length(__rsize); } } template void basic_string<_CharT, _Traits, _Alloc>:: reserve(size_type __res) { // Make sure we don't shrink below the current size. if (__res < length()) __res = length(); const size_type __capacity = capacity(); if (__res != __capacity) { if (__res > __capacity || __res > size_type(_S_local_capacity)) { pointer __tmp = _M_create(__res, __capacity); this->_S_copy(__tmp, _M_data(), length() + 1); _M_dispose(); _M_data(__tmp); _M_capacity(__res); } else if (!_M_is_local()) { this->_S_copy(_M_local_data(), _M_data(), length() + 1); _M_destroy(__capacity); _M_data(_M_local_data()); } } } template void basic_string<_CharT, _Traits, _Alloc>:: _M_mutate(size_type __pos, size_type __len1, const _CharT* __s, size_type __len2) { const size_type __how_much = length() - __pos - __len1; size_type __new_capacity = length() + __len2 - __len1; pointer __r = _M_create(__new_capacity, capacity()); if (__pos) this->_S_copy(__r, _M_data(), __pos); if (__s && __len2) this->_S_copy(__r + __pos, __s, __len2); if (__how_much) this->_S_copy(__r + __pos + __len2, _M_data() + __pos + __len1, __how_much); _M_dispose(); _M_data(__r); _M_capacity(__new_capacity); } template void basic_string<_CharT, _Traits, _Alloc>:: _M_erase(size_type __pos, size_type __n) { const size_type __how_much = length() - __pos - __n; if (__how_much && __n) this->_S_move(_M_data() + __pos, _M_data() + __pos + __n, __how_much); _M_set_length(length() - __n); } template void basic_string<_CharT, _Traits, _Alloc>:: resize(size_type __n, _CharT __c) { const size_type __size = this->size(); if (__size < __n) this->append(__n - __size, __c); else if (__n < __size) this->_M_set_length(__n); } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: _M_append(const _CharT* __s, size_type __n) { const size_type __len = __n + this->size(); if (__len <= this->capacity()) { if (__n) this->_S_copy(this->_M_data() + this->size(), __s, __n); } else this->_M_mutate(this->size(), size_type(0), __s, __n); this->_M_set_length(__len); return *this; } template template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: _M_replace_dispatch(const_iterator __i1, const_iterator __i2, _InputIterator __k1, _InputIterator __k2, std::__false_type) { const basic_string __s(__k1, __k2); const size_type __n1 = __i2 - __i1; return _M_replace(__i1 - begin(), __n1, __s._M_data(), __s.size()); } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: _M_replace_aux(size_type __pos1, size_type __n1, size_type __n2, _CharT __c) { _M_check_length(__n1, __n2, "basic_string::_M_replace_aux"); const size_type __old_size = this->size(); const size_type __new_size = __old_size + __n2 - __n1; if (__new_size <= this->capacity()) { pointer __p = this->_M_data() + __pos1; const size_type __how_much = __old_size - __pos1 - __n1; if (__how_much && __n1 != __n2) this->_S_move(__p + __n2, __p + __n1, __how_much); } else this->_M_mutate(__pos1, __n1, 0, __n2); if (__n2) this->_S_assign(this->_M_data() + __pos1, __n2, __c); this->_M_set_length(__new_size); return *this; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: _M_replace(size_type __pos, size_type __len1, const _CharT* __s, const size_type __len2) { _M_check_length(__len1, __len2, "basic_string::_M_replace"); const size_type __old_size = this->size(); const size_type __new_size = __old_size + __len2 - __len1; if (__new_size <= this->capacity()) { pointer __p = this->_M_data() + __pos; const size_type __how_much = __old_size - __pos - __len1; if (_M_disjunct(__s)) { if (__how_much && __len1 != __len2) this->_S_move(__p + __len2, __p + __len1, __how_much); if (__len2) this->_S_copy(__p, __s, __len2); } else { // Work in-place. if (__len2 && __len2 <= __len1) this->_S_move(__p, __s, __len2); if (__how_much && __len1 != __len2) this->_S_move(__p + __len2, __p + __len1, __how_much); if (__len2 > __len1) { if (__s + __len2 <= __p + __len1) this->_S_move(__p, __s, __len2); else if (__s >= __p + __len1) this->_S_copy(__p, __s + __len2 - __len1, __len2); else { const size_type __nleft = (__p + __len1) - __s; this->_S_move(__p, __s, __nleft); this->_S_copy(__p + __nleft, __p + __len2, __len2 - __nleft); } } } } else this->_M_mutate(__pos, __len1, __s, __len2); this->_M_set_length(__new_size); return *this; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: copy(_CharT* __s, size_type __n, size_type __pos) const { _M_check(__pos, "basic_string::copy"); __n = _M_limit(__pos, __n); __glibcxx_requires_string_len(__s, __n); if (__n) _S_copy(__s, _M_data() + __pos, __n); // 21.3.5.7 par 3: do not append null. (good.) return __n; } #else // !_GLIBCXX_USE_CXX11_ABI template const typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: _Rep::_S_max_size = (((npos - sizeof(_Rep_base))/sizeof(_CharT)) - 1) / 4; template const _CharT basic_string<_CharT, _Traits, _Alloc>:: _Rep::_S_terminal = _CharT(); template const typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>::npos; // Linker sets _S_empty_rep_storage to all 0s (one reference, empty string) // at static init time (before static ctors are run). template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>::_Rep::_S_empty_rep_storage[ (sizeof(_Rep_base) + sizeof(_CharT) + sizeof(size_type) - 1) / sizeof(size_type)]; // NB: This is the special case for Input Iterators, used in // istreambuf_iterators, etc. // Input Iterators have a cost structure very different from // pointers, calling for a different coding style. template template _CharT* basic_string<_CharT, _Traits, _Alloc>:: _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a, input_iterator_tag) { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 if (__beg == __end && __a == _Alloc()) return _S_empty_rep()._M_refdata(); #endif // Avoid reallocation for common case. _CharT __buf[128]; size_type __len = 0; while (__beg != __end && __len < sizeof(__buf) / sizeof(_CharT)) { __buf[__len++] = *__beg; ++__beg; } _Rep* __r = _Rep::_S_create(__len, size_type(0), __a); _M_copy(__r->_M_refdata(), __buf, __len); __try { while (__beg != __end) { if (__len == __r->_M_capacity) { // Allocate more space. _Rep* __another = _Rep::_S_create(__len + 1, __len, __a); _M_copy(__another->_M_refdata(), __r->_M_refdata(), __len); __r->_M_destroy(__a); __r = __another; } __r->_M_refdata()[__len++] = *__beg; ++__beg; } } __catch(...) { __r->_M_destroy(__a); __throw_exception_again; } __r->_M_set_length_and_sharable(__len); return __r->_M_refdata(); } template template _CharT* basic_string<_CharT, _Traits, _Alloc>:: _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a, forward_iterator_tag) { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 if (__beg == __end && __a == _Alloc()) return _S_empty_rep()._M_refdata(); #endif // NB: Not required, but considered best practice. if (__gnu_cxx::__is_null_pointer(__beg) && __beg != __end) __throw_logic_error(__N("basic_string::_S_construct null not valid")); const size_type __dnew = static_cast(std::distance(__beg, __end)); // Check for out_of_range and length_error exceptions. _Rep* __r = _Rep::_S_create(__dnew, size_type(0), __a); __try { _S_copy_chars(__r->_M_refdata(), __beg, __end); } __catch(...) { __r->_M_destroy(__a); __throw_exception_again; } __r->_M_set_length_and_sharable(__dnew); return __r->_M_refdata(); } template _CharT* basic_string<_CharT, _Traits, _Alloc>:: _S_construct(size_type __n, _CharT __c, const _Alloc& __a) { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 if (__n == 0 && __a == _Alloc()) return _S_empty_rep()._M_refdata(); #endif // Check for out_of_range and length_error exceptions. _Rep* __r = _Rep::_S_create(__n, size_type(0), __a); if (__n) _M_assign(__r->_M_refdata(), __n, __c); __r->_M_set_length_and_sharable(__n); return __r->_M_refdata(); } template basic_string<_CharT, _Traits, _Alloc>:: basic_string(const basic_string& __str) : _M_dataplus(__str._M_rep()->_M_grab(_Alloc(__str.get_allocator()), __str.get_allocator()), __str.get_allocator()) { } template basic_string<_CharT, _Traits, _Alloc>:: basic_string(const _Alloc& __a) : _M_dataplus(_S_construct(size_type(), _CharT(), __a), __a) { } template basic_string<_CharT, _Traits, _Alloc>:: basic_string(const basic_string& __str, size_type __pos, const _Alloc& __a) : _M_dataplus(_S_construct(__str._M_data() + __str._M_check(__pos, "basic_string::basic_string"), __str._M_data() + __str._M_limit(__pos, npos) + __pos, __a), __a) { } template basic_string<_CharT, _Traits, _Alloc>:: basic_string(const basic_string& __str, size_type __pos, size_type __n) : _M_dataplus(_S_construct(__str._M_data() + __str._M_check(__pos, "basic_string::basic_string"), __str._M_data() + __str._M_limit(__pos, __n) + __pos, _Alloc()), _Alloc()) { } template basic_string<_CharT, _Traits, _Alloc>:: basic_string(const basic_string& __str, size_type __pos, size_type __n, const _Alloc& __a) : _M_dataplus(_S_construct(__str._M_data() + __str._M_check(__pos, "basic_string::basic_string"), __str._M_data() + __str._M_limit(__pos, __n) + __pos, __a), __a) { } // TBD: DPG annotate template basic_string<_CharT, _Traits, _Alloc>:: basic_string(const _CharT* __s, size_type __n, const _Alloc& __a) : _M_dataplus(_S_construct(__s, __s + __n, __a), __a) { } // TBD: DPG annotate template basic_string<_CharT, _Traits, _Alloc>:: basic_string(const _CharT* __s, const _Alloc& __a) : _M_dataplus(_S_construct(__s, __s ? __s + traits_type::length(__s) : __s + npos, __a), __a) { } template basic_string<_CharT, _Traits, _Alloc>:: basic_string(size_type __n, _CharT __c, const _Alloc& __a) : _M_dataplus(_S_construct(__n, __c, __a), __a) { } // TBD: DPG annotate template template basic_string<_CharT, _Traits, _Alloc>:: basic_string(_InputIterator __beg, _InputIterator __end, const _Alloc& __a) : _M_dataplus(_S_construct(__beg, __end, __a), __a) { } #if __cplusplus >= 201103L template basic_string<_CharT, _Traits, _Alloc>:: basic_string(initializer_list<_CharT> __l, const _Alloc& __a) : _M_dataplus(_S_construct(__l.begin(), __l.end(), __a), __a) { } #endif template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: assign(const basic_string& __str) { if (_M_rep() != __str._M_rep()) { // XXX MT const allocator_type __a = this->get_allocator(); _CharT* __tmp = __str._M_rep()->_M_grab(__a, __str.get_allocator()); _M_rep()->_M_dispose(__a); _M_data(__tmp); } return *this; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: assign(const _CharT* __s, size_type __n) { __glibcxx_requires_string_len(__s, __n); _M_check_length(this->size(), __n, "basic_string::assign"); if (_M_disjunct(__s) || _M_rep()->_M_is_shared()) return _M_replace_safe(size_type(0), this->size(), __s, __n); else { // Work in-place. const size_type __pos = __s - _M_data(); if (__pos >= __n) _M_copy(_M_data(), __s, __n); else if (__pos) _M_move(_M_data(), __s, __n); _M_rep()->_M_set_length_and_sharable(__n); return *this; } } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: append(size_type __n, _CharT __c) { if (__n) { _M_check_length(size_type(0), __n, "basic_string::append"); const size_type __len = __n + this->size(); if (__len > this->capacity() || _M_rep()->_M_is_shared()) this->reserve(__len); _M_assign(_M_data() + this->size(), __n, __c); _M_rep()->_M_set_length_and_sharable(__len); } return *this; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: append(const _CharT* __s, size_type __n) { __glibcxx_requires_string_len(__s, __n); if (__n) { _M_check_length(size_type(0), __n, "basic_string::append"); const size_type __len = __n + this->size(); if (__len > this->capacity() || _M_rep()->_M_is_shared()) { if (_M_disjunct(__s)) this->reserve(__len); else { const size_type __off = __s - _M_data(); this->reserve(__len); __s = _M_data() + __off; } } _M_copy(_M_data() + this->size(), __s, __n); _M_rep()->_M_set_length_and_sharable(__len); } return *this; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: append(const basic_string& __str) { const size_type __size = __str.size(); if (__size) { const size_type __len = __size + this->size(); if (__len > this->capacity() || _M_rep()->_M_is_shared()) this->reserve(__len); _M_copy(_M_data() + this->size(), __str._M_data(), __size); _M_rep()->_M_set_length_and_sharable(__len); } return *this; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: append(const basic_string& __str, size_type __pos, size_type __n) { __str._M_check(__pos, "basic_string::append"); __n = __str._M_limit(__pos, __n); if (__n) { const size_type __len = __n + this->size(); if (__len > this->capacity() || _M_rep()->_M_is_shared()) this->reserve(__len); _M_copy(_M_data() + this->size(), __str._M_data() + __pos, __n); _M_rep()->_M_set_length_and_sharable(__len); } return *this; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: insert(size_type __pos, const _CharT* __s, size_type __n) { __glibcxx_requires_string_len(__s, __n); _M_check(__pos, "basic_string::insert"); _M_check_length(size_type(0), __n, "basic_string::insert"); if (_M_disjunct(__s) || _M_rep()->_M_is_shared()) return _M_replace_safe(__pos, size_type(0), __s, __n); else { // Work in-place. const size_type __off = __s - _M_data(); _M_mutate(__pos, 0, __n); __s = _M_data() + __off; _CharT* __p = _M_data() + __pos; if (__s + __n <= __p) _M_copy(__p, __s, __n); else if (__s >= __p) _M_copy(__p, __s + __n, __n); else { const size_type __nleft = __p - __s; _M_copy(__p, __s, __nleft); _M_copy(__p + __nleft, __p + __n, __n - __nleft); } return *this; } } template typename basic_string<_CharT, _Traits, _Alloc>::iterator basic_string<_CharT, _Traits, _Alloc>:: erase(iterator __first, iterator __last) { _GLIBCXX_DEBUG_PEDASSERT(__first >= _M_ibegin() && __first <= __last && __last <= _M_iend()); // NB: This isn't just an optimization (bail out early when // there is nothing to do, really), it's also a correctness // issue vs MT, see libstdc++/40518. const size_type __size = __last - __first; if (__size) { const size_type __pos = __first - _M_ibegin(); _M_mutate(__pos, __size, size_type(0)); _M_rep()->_M_set_leaked(); return iterator(_M_data() + __pos); } else return __first; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: replace(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2) { __glibcxx_requires_string_len(__s, __n2); _M_check(__pos, "basic_string::replace"); __n1 = _M_limit(__pos, __n1); _M_check_length(__n1, __n2, "basic_string::replace"); bool __left; if (_M_disjunct(__s) || _M_rep()->_M_is_shared()) return _M_replace_safe(__pos, __n1, __s, __n2); else if ((__left = __s + __n2 <= _M_data() + __pos) || _M_data() + __pos + __n1 <= __s) { // Work in-place: non-overlapping case. size_type __off = __s - _M_data(); __left ? __off : (__off += __n2 - __n1); _M_mutate(__pos, __n1, __n2); _M_copy(_M_data() + __pos, _M_data() + __off, __n2); return *this; } else { // Todo: overlapping case. const basic_string __tmp(__s, __n2); return _M_replace_safe(__pos, __n1, __tmp._M_data(), __n2); } } template void basic_string<_CharT, _Traits, _Alloc>::_Rep:: _M_destroy(const _Alloc& __a) throw () { const size_type __size = sizeof(_Rep_base) + (this->_M_capacity + 1) * sizeof(_CharT); _Raw_bytes_alloc(__a).deallocate(reinterpret_cast(this), __size); } template void basic_string<_CharT, _Traits, _Alloc>:: _M_leak_hard() { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 if (_M_rep() == &_S_empty_rep()) return; #endif if (_M_rep()->_M_is_shared()) _M_mutate(0, 0, 0); _M_rep()->_M_set_leaked(); } template void basic_string<_CharT, _Traits, _Alloc>:: _M_mutate(size_type __pos, size_type __len1, size_type __len2) { const size_type __old_size = this->size(); const size_type __new_size = __old_size + __len2 - __len1; const size_type __how_much = __old_size - __pos - __len1; if (__new_size > this->capacity() || _M_rep()->_M_is_shared()) { // Must reallocate. const allocator_type __a = get_allocator(); _Rep* __r = _Rep::_S_create(__new_size, this->capacity(), __a); if (__pos) _M_copy(__r->_M_refdata(), _M_data(), __pos); if (__how_much) _M_copy(__r->_M_refdata() + __pos + __len2, _M_data() + __pos + __len1, __how_much); _M_rep()->_M_dispose(__a); _M_data(__r->_M_refdata()); } else if (__how_much && __len1 != __len2) { // Work in-place. _M_move(_M_data() + __pos + __len2, _M_data() + __pos + __len1, __how_much); } _M_rep()->_M_set_length_and_sharable(__new_size); } template void basic_string<_CharT, _Traits, _Alloc>:: reserve(size_type __res) { if (__res != this->capacity() || _M_rep()->_M_is_shared()) { // Make sure we don't shrink below the current size if (__res < this->size()) __res = this->size(); const allocator_type __a = get_allocator(); _CharT* __tmp = _M_rep()->_M_clone(__a, __res - this->size()); _M_rep()->_M_dispose(__a); _M_data(__tmp); } } template void basic_string<_CharT, _Traits, _Alloc>:: swap(basic_string& __s) { if (_M_rep()->_M_is_leaked()) _M_rep()->_M_set_sharable(); if (__s._M_rep()->_M_is_leaked()) __s._M_rep()->_M_set_sharable(); if (this->get_allocator() == __s.get_allocator()) { _CharT* __tmp = _M_data(); _M_data(__s._M_data()); __s._M_data(__tmp); } // The code below can usually be optimized away. else { const basic_string __tmp1(_M_ibegin(), _M_iend(), __s.get_allocator()); const basic_string __tmp2(__s._M_ibegin(), __s._M_iend(), this->get_allocator()); *this = __tmp2; __s = __tmp1; } } template typename basic_string<_CharT, _Traits, _Alloc>::_Rep* basic_string<_CharT, _Traits, _Alloc>::_Rep:: _S_create(size_type __capacity, size_type __old_capacity, const _Alloc& __alloc) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 83. String::npos vs. string::max_size() if (__capacity > _S_max_size) __throw_length_error(__N("basic_string::_S_create")); // The standard places no restriction on allocating more memory // than is strictly needed within this layer at the moment or as // requested by an explicit application call to reserve(). // Many malloc implementations perform quite poorly when an // application attempts to allocate memory in a stepwise fashion // growing each allocation size by only 1 char. Additionally, // it makes little sense to allocate less linear memory than the // natural blocking size of the malloc implementation. // Unfortunately, we would need a somewhat low-level calculation // with tuned parameters to get this perfect for any particular // malloc implementation. Fortunately, generalizations about // common features seen among implementations seems to suffice. // __pagesize need not match the actual VM page size for good // results in practice, thus we pick a common value on the low // side. __malloc_header_size is an estimate of the amount of // overhead per memory allocation (in practice seen N * sizeof // (void*) where N is 0, 2 or 4). According to folklore, // picking this value on the high side is better than // low-balling it (especially when this algorithm is used with // malloc implementations that allocate memory blocks rounded up // to a size which is a power of 2). const size_type __pagesize = 4096; const size_type __malloc_header_size = 4 * sizeof(void*); // The below implements an exponential growth policy, necessary to // meet amortized linear time requirements of the library: see // http://gcc.gnu.org/ml/libstdc++/2001-07/msg00085.html. // It's active for allocations requiring an amount of memory above // system pagesize. This is consistent with the requirements of the // standard: http://gcc.gnu.org/ml/libstdc++/2001-07/msg00130.html if (__capacity > __old_capacity && __capacity < 2 * __old_capacity) __capacity = 2 * __old_capacity; // NB: Need an array of char_type[__capacity], plus a terminating // null char_type() element, plus enough for the _Rep data structure. // Whew. Seemingly so needy, yet so elemental. size_type __size = (__capacity + 1) * sizeof(_CharT) + sizeof(_Rep); const size_type __adj_size = __size + __malloc_header_size; if (__adj_size > __pagesize && __capacity > __old_capacity) { const size_type __extra = __pagesize - __adj_size % __pagesize; __capacity += __extra / sizeof(_CharT); // Never allocate a string bigger than _S_max_size. if (__capacity > _S_max_size) __capacity = _S_max_size; __size = (__capacity + 1) * sizeof(_CharT) + sizeof(_Rep); } // NB: Might throw, but no worries about a leak, mate: _Rep() // does not throw. void* __place = _Raw_bytes_alloc(__alloc).allocate(__size); _Rep *__p = new (__place) _Rep; __p->_M_capacity = __capacity; // ABI compatibility - 3.4.x set in _S_create both // _M_refcount and _M_length. All callers of _S_create // in basic_string.tcc then set just _M_length. // In 4.0.x and later both _M_refcount and _M_length // are initialized in the callers, unfortunately we can // have 3.4.x compiled code with _S_create callers inlined // calling 4.0.x+ _S_create. __p->_M_set_sharable(); return __p; } template _CharT* basic_string<_CharT, _Traits, _Alloc>::_Rep:: _M_clone(const _Alloc& __alloc, size_type __res) { // Requested capacity of the clone. const size_type __requested_cap = this->_M_length + __res; _Rep* __r = _Rep::_S_create(__requested_cap, this->_M_capacity, __alloc); if (this->_M_length) _M_copy(__r->_M_refdata(), _M_refdata(), this->_M_length); __r->_M_set_length_and_sharable(this->_M_length); return __r->_M_refdata(); } template void basic_string<_CharT, _Traits, _Alloc>:: resize(size_type __n, _CharT __c) { const size_type __size = this->size(); _M_check_length(__size, __n, "basic_string::resize"); if (__size < __n) this->append(__n - __size, __c); else if (__n < __size) this->erase(__n); // else nothing (in particular, avoid calling _M_mutate() unnecessarily.) } template template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: _M_replace_dispatch(iterator __i1, iterator __i2, _InputIterator __k1, _InputIterator __k2, __false_type) { const basic_string __s(__k1, __k2); const size_type __n1 = __i2 - __i1; _M_check_length(__n1, __s.size(), "basic_string::_M_replace_dispatch"); return _M_replace_safe(__i1 - _M_ibegin(), __n1, __s._M_data(), __s.size()); } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: _M_replace_aux(size_type __pos1, size_type __n1, size_type __n2, _CharT __c) { _M_check_length(__n1, __n2, "basic_string::_M_replace_aux"); _M_mutate(__pos1, __n1, __n2); if (__n2) _M_assign(_M_data() + __pos1, __n2, __c); return *this; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: _M_replace_safe(size_type __pos1, size_type __n1, const _CharT* __s, size_type __n2) { _M_mutate(__pos1, __n1, __n2); if (__n2) _M_copy(_M_data() + __pos1, __s, __n2); return *this; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: copy(_CharT* __s, size_type __n, size_type __pos) const { _M_check(__pos, "basic_string::copy"); __n = _M_limit(__pos, __n); __glibcxx_requires_string_len(__s, __n); if (__n) _M_copy(__s, _M_data() + __pos, __n); // 21.3.5.7 par 3: do not append null. (good.) return __n; } #endif // !_GLIBCXX_USE_CXX11_ABI template basic_string<_CharT, _Traits, _Alloc> operator+(const _CharT* __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { __glibcxx_requires_string(__lhs); typedef basic_string<_CharT, _Traits, _Alloc> __string_type; typedef typename __string_type::size_type __size_type; const __size_type __len = _Traits::length(__lhs); __string_type __str; __str.reserve(__len + __rhs.size()); __str.append(__lhs, __len); __str.append(__rhs); return __str; } template basic_string<_CharT, _Traits, _Alloc> operator+(_CharT __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { typedef basic_string<_CharT, _Traits, _Alloc> __string_type; typedef typename __string_type::size_type __size_type; __string_type __str; const __size_type __len = __rhs.size(); __str.reserve(__len + 1); __str.append(__size_type(1), __lhs); __str.append(__rhs); return __str; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string_len(__s, __n); const size_type __size = this->size(); if (__n == 0) return __pos <= __size ? __pos : npos; if (__pos >= __size) return npos; const _CharT __elem0 = __s[0]; const _CharT* const __data = data(); const _CharT* __first = __data + __pos; const _CharT* const __last = __data + __size; size_type __len = __size - __pos; while (__len >= __n) { // Find the first occurrence of __elem0: __first = traits_type::find(__first, __len - __n + 1, __elem0); if (!__first) return npos; // Compare the full strings from the first occurrence of __elem0. // We already know that __first[0] == __s[0] but compare them again // anyway because __s is probably aligned, which helps memcmp. if (traits_type::compare(__first, __s, __n) == 0) return __first - __data; __len = __last - ++__first; } return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { size_type __ret = npos; const size_type __size = this->size(); if (__pos < __size) { const _CharT* __data = _M_data(); const size_type __n = __size - __pos; const _CharT* __p = traits_type::find(__data + __pos, __n, __c); if (__p) __ret = __p - __data; } return __ret; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: rfind(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string_len(__s, __n); const size_type __size = this->size(); if (__n <= __size) { __pos = std::min(size_type(__size - __n), __pos); const _CharT* __data = _M_data(); do { if (traits_type::compare(__data + __pos, __s, __n) == 0) return __pos; } while (__pos-- > 0); } return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: rfind(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { size_type __size = this->size(); if (__size) { if (--__size > __pos) __size = __pos; for (++__size; __size-- > 0; ) if (traits_type::eq(_M_data()[__size], __c)) return __size; } return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find_first_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string_len(__s, __n); for (; __n && __pos < this->size(); ++__pos) { const _CharT* __p = traits_type::find(__s, __n, _M_data()[__pos]); if (__p) return __pos; } return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find_last_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string_len(__s, __n); size_type __size = this->size(); if (__size && __n) { if (--__size > __pos) __size = __pos; do { if (traits_type::find(__s, __n, _M_data()[__size])) return __size; } while (__size-- != 0); } return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string_len(__s, __n); for (; __pos < this->size(); ++__pos) if (!traits_type::find(__s, __n, _M_data()[__pos])) return __pos; return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find_first_not_of(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { for (; __pos < this->size(); ++__pos) if (!traits_type::eq(_M_data()[__pos], __c)) return __pos; return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find_last_not_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string_len(__s, __n); size_type __size = this->size(); if (__size) { if (--__size > __pos) __size = __pos; do { if (!traits_type::find(__s, __n, _M_data()[__size])) return __size; } while (__size--); } return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find_last_not_of(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { size_type __size = this->size(); if (__size) { if (--__size > __pos) __size = __pos; do { if (!traits_type::eq(_M_data()[__size], __c)) return __size; } while (__size--); } return npos; } template int basic_string<_CharT, _Traits, _Alloc>:: compare(size_type __pos, size_type __n, const basic_string& __str) const { _M_check(__pos, "basic_string::compare"); __n = _M_limit(__pos, __n); const size_type __osize = __str.size(); const size_type __len = std::min(__n, __osize); int __r = traits_type::compare(_M_data() + __pos, __str.data(), __len); if (!__r) __r = _S_compare(__n, __osize); return __r; } template int basic_string<_CharT, _Traits, _Alloc>:: compare(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2) const { _M_check(__pos1, "basic_string::compare"); __str._M_check(__pos2, "basic_string::compare"); __n1 = _M_limit(__pos1, __n1); __n2 = __str._M_limit(__pos2, __n2); const size_type __len = std::min(__n1, __n2); int __r = traits_type::compare(_M_data() + __pos1, __str.data() + __pos2, __len); if (!__r) __r = _S_compare(__n1, __n2); return __r; } template int basic_string<_CharT, _Traits, _Alloc>:: compare(const _CharT* __s) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); const size_type __size = this->size(); const size_type __osize = traits_type::length(__s); const size_type __len = std::min(__size, __osize); int __r = traits_type::compare(_M_data(), __s, __len); if (!__r) __r = _S_compare(__size, __osize); return __r; } template int basic_string <_CharT, _Traits, _Alloc>:: compare(size_type __pos, size_type __n1, const _CharT* __s) const { __glibcxx_requires_string(__s); _M_check(__pos, "basic_string::compare"); __n1 = _M_limit(__pos, __n1); const size_type __osize = traits_type::length(__s); const size_type __len = std::min(__n1, __osize); int __r = traits_type::compare(_M_data() + __pos, __s, __len); if (!__r) __r = _S_compare(__n1, __osize); return __r; } template int basic_string <_CharT, _Traits, _Alloc>:: compare(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2) const { __glibcxx_requires_string_len(__s, __n2); _M_check(__pos, "basic_string::compare"); __n1 = _M_limit(__pos, __n1); const size_type __len = std::min(__n1, __n2); int __r = traits_type::compare(_M_data() + __pos, __s, __len); if (!__r) __r = _S_compare(__n1, __n2); return __r; } // 21.3.7.9 basic_string::getline and operators template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __in, basic_string<_CharT, _Traits, _Alloc>& __str) { typedef basic_istream<_CharT, _Traits> __istream_type; typedef basic_string<_CharT, _Traits, _Alloc> __string_type; typedef typename __istream_type::ios_base __ios_base; typedef typename __istream_type::int_type __int_type; typedef typename __string_type::size_type __size_type; typedef ctype<_CharT> __ctype_type; typedef typename __ctype_type::ctype_base __ctype_base; __size_type __extracted = 0; typename __ios_base::iostate __err = __ios_base::goodbit; typename __istream_type::sentry __cerb(__in, false); if (__cerb) { __try { // Avoid reallocation for common case. __str.erase(); _CharT __buf[128]; __size_type __len = 0; const streamsize __w = __in.width(); const __size_type __n = __w > 0 ? static_cast<__size_type>(__w) : __str.max_size(); const __ctype_type& __ct = use_facet<__ctype_type>(__in.getloc()); const __int_type __eof = _Traits::eof(); __int_type __c = __in.rdbuf()->sgetc(); while (__extracted < __n && !_Traits::eq_int_type(__c, __eof) && !__ct.is(__ctype_base::space, _Traits::to_char_type(__c))) { if (__len == sizeof(__buf) / sizeof(_CharT)) { __str.append(__buf, sizeof(__buf) / sizeof(_CharT)); __len = 0; } __buf[__len++] = _Traits::to_char_type(__c); ++__extracted; __c = __in.rdbuf()->snextc(); } __str.append(__buf, __len); if (_Traits::eq_int_type(__c, __eof)) __err |= __ios_base::eofbit; __in.width(0); } __catch(__cxxabiv1::__forced_unwind&) { __in._M_setstate(__ios_base::badbit); __throw_exception_again; } __catch(...) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 91. Description of operator>> and getline() for string<> // might cause endless loop __in._M_setstate(__ios_base::badbit); } } // 211. operator>>(istream&, string&) doesn't set failbit if (!__extracted) __err |= __ios_base::failbit; if (__err) __in.setstate(__err); return __in; } template basic_istream<_CharT, _Traits>& getline(basic_istream<_CharT, _Traits>& __in, basic_string<_CharT, _Traits, _Alloc>& __str, _CharT __delim) { typedef basic_istream<_CharT, _Traits> __istream_type; typedef basic_string<_CharT, _Traits, _Alloc> __string_type; typedef typename __istream_type::ios_base __ios_base; typedef typename __istream_type::int_type __int_type; typedef typename __string_type::size_type __size_type; __size_type __extracted = 0; const __size_type __n = __str.max_size(); typename __ios_base::iostate __err = __ios_base::goodbit; typename __istream_type::sentry __cerb(__in, true); if (__cerb) { __try { __str.erase(); const __int_type __idelim = _Traits::to_int_type(__delim); const __int_type __eof = _Traits::eof(); __int_type __c = __in.rdbuf()->sgetc(); while (__extracted < __n && !_Traits::eq_int_type(__c, __eof) && !_Traits::eq_int_type(__c, __idelim)) { __str += _Traits::to_char_type(__c); ++__extracted; __c = __in.rdbuf()->snextc(); } if (_Traits::eq_int_type(__c, __eof)) __err |= __ios_base::eofbit; else if (_Traits::eq_int_type(__c, __idelim)) { ++__extracted; __in.rdbuf()->sbumpc(); } else __err |= __ios_base::failbit; } __catch(__cxxabiv1::__forced_unwind&) { __in._M_setstate(__ios_base::badbit); __throw_exception_again; } __catch(...) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 91. Description of operator>> and getline() for string<> // might cause endless loop __in._M_setstate(__ios_base::badbit); } } if (!__extracted) __err |= __ios_base::failbit; if (__err) __in.setstate(__err); return __in; } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE // The explicit instantiations definitions in src/c++11/string-inst.cc // are compiled as C++14, so the new C++17 members aren't instantiated. // Until those definitions are compiled as C++17 suppress the declaration, // so C++17 code will implicitly instantiate std::string and std::wstring // as needed. # if __cplusplus <= 201402L && _GLIBCXX_EXTERN_TEMPLATE > 0 extern template class basic_string; # elif ! _GLIBCXX_USE_CXX11_ABI // Still need to prevent implicit instantiation of the COW empty rep, // to ensure the definition in libstdc++.so is unique (PR 86138). extern template basic_string::size_type basic_string::_Rep::_S_empty_rep_storage[]; # endif extern template basic_istream& operator>>(basic_istream&, string&); extern template basic_ostream& operator<<(basic_ostream&, const string&); extern template basic_istream& getline(basic_istream&, string&, char); extern template basic_istream& getline(basic_istream&, string&); #ifdef _GLIBCXX_USE_WCHAR_T # if __cplusplus <= 201402L && _GLIBCXX_EXTERN_TEMPLATE > 0 extern template class basic_string; # elif ! _GLIBCXX_USE_CXX11_ABI extern template basic_string::size_type basic_string::_Rep::_S_empty_rep_storage[]; # endif extern template basic_istream& operator>>(basic_istream&, wstring&); extern template basic_ostream& operator<<(basic_ostream&, const wstring&); extern template basic_istream& getline(basic_istream&, wstring&, wchar_t); extern template basic_istream& getline(basic_istream&, wstring&); #endif // _GLIBCXX_USE_WCHAR_T #endif // _GLIBCXX_EXTERN_TEMPLATE _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!Bjj8/bits/boost_concept_check.hnu[// -*- C++ -*- // Copyright (C) 2004-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // (C) Copyright Jeremy Siek 2000. Permission to copy, use, modify, // sell and distribute this software is granted provided this // copyright notice appears in all copies. This software is provided // "as is" without express or implied warranty, and with no claim as // to its suitability for any purpose. // /** @file bits/boost_concept_check.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iterator} */ // GCC Note: based on version 1.12.0 of the Boost library. #ifndef _BOOST_CONCEPT_CHECK_H #define _BOOST_CONCEPT_CHECK_H 1 #pragma GCC system_header #include #include // for traits and tags namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-local-typedefs" #define _IsUnused __attribute__ ((__unused__)) // When the C-C code is in use, we would like this function to do as little // as possible at runtime, use as few resources as possible, and hopefully // be elided out of existence... hmmm. template inline void __function_requires() { void (_Concept::*__x)() _IsUnused = &_Concept::__constraints; } // No definition: if this is referenced, there's a problem with // the instantiating type not being one of the required integer types. // Unfortunately, this results in a link-time error, not a compile-time error. void __error_type_must_be_an_integer_type(); void __error_type_must_be_an_unsigned_integer_type(); void __error_type_must_be_a_signed_integer_type(); // ??? Should the "concept_checking*" structs begin with more than _ ? #define _GLIBCXX_CLASS_REQUIRES(_type_var, _ns, _concept) \ typedef void (_ns::_concept <_type_var>::* _func##_type_var##_concept)(); \ template <_func##_type_var##_concept _Tp1> \ struct _concept_checking##_type_var##_concept { }; \ typedef _concept_checking##_type_var##_concept< \ &_ns::_concept <_type_var>::__constraints> \ _concept_checking_typedef##_type_var##_concept #define _GLIBCXX_CLASS_REQUIRES2(_type_var1, _type_var2, _ns, _concept) \ typedef void (_ns::_concept <_type_var1,_type_var2>::* _func##_type_var1##_type_var2##_concept)(); \ template <_func##_type_var1##_type_var2##_concept _Tp1> \ struct _concept_checking##_type_var1##_type_var2##_concept { }; \ typedef _concept_checking##_type_var1##_type_var2##_concept< \ &_ns::_concept <_type_var1,_type_var2>::__constraints> \ _concept_checking_typedef##_type_var1##_type_var2##_concept #define _GLIBCXX_CLASS_REQUIRES3(_type_var1, _type_var2, _type_var3, _ns, _concept) \ typedef void (_ns::_concept <_type_var1,_type_var2,_type_var3>::* _func##_type_var1##_type_var2##_type_var3##_concept)(); \ template <_func##_type_var1##_type_var2##_type_var3##_concept _Tp1> \ struct _concept_checking##_type_var1##_type_var2##_type_var3##_concept { }; \ typedef _concept_checking##_type_var1##_type_var2##_type_var3##_concept< \ &_ns::_concept <_type_var1,_type_var2,_type_var3>::__constraints> \ _concept_checking_typedef##_type_var1##_type_var2##_type_var3##_concept #define _GLIBCXX_CLASS_REQUIRES4(_type_var1, _type_var2, _type_var3, _type_var4, _ns, _concept) \ typedef void (_ns::_concept <_type_var1,_type_var2,_type_var3,_type_var4>::* _func##_type_var1##_type_var2##_type_var3##_type_var4##_concept)(); \ template <_func##_type_var1##_type_var2##_type_var3##_type_var4##_concept _Tp1> \ struct _concept_checking##_type_var1##_type_var2##_type_var3##_type_var4##_concept { }; \ typedef _concept_checking##_type_var1##_type_var2##_type_var3##_type_var4##_concept< \ &_ns::_concept <_type_var1,_type_var2,_type_var3,_type_var4>::__constraints> \ _concept_checking_typedef##_type_var1##_type_var2##_type_var3##_type_var4##_concept template struct _Aux_require_same { }; template struct _Aux_require_same<_Tp,_Tp> { typedef _Tp _Type; }; template struct _SameTypeConcept { void __constraints() { typedef typename _Aux_require_same<_Tp1, _Tp2>::_Type _Required; } }; template struct _IntegerConcept { void __constraints() { __error_type_must_be_an_integer_type(); } }; template <> struct _IntegerConcept { void __constraints() {} }; template <> struct _IntegerConcept { void __constraints(){} }; template <> struct _IntegerConcept { void __constraints() {} }; template <> struct _IntegerConcept { void __constraints() {} }; template <> struct _IntegerConcept { void __constraints() {} }; template <> struct _IntegerConcept { void __constraints() {} }; template <> struct _IntegerConcept { void __constraints() {} }; template <> struct _IntegerConcept { void __constraints() {} }; template struct _SignedIntegerConcept { void __constraints() { __error_type_must_be_a_signed_integer_type(); } }; template <> struct _SignedIntegerConcept { void __constraints() {} }; template <> struct _SignedIntegerConcept { void __constraints() {} }; template <> struct _SignedIntegerConcept { void __constraints() {} }; template <> struct _SignedIntegerConcept { void __constraints(){}}; template struct _UnsignedIntegerConcept { void __constraints() { __error_type_must_be_an_unsigned_integer_type(); } }; template <> struct _UnsignedIntegerConcept { void __constraints() {} }; template <> struct _UnsignedIntegerConcept { void __constraints() {} }; template <> struct _UnsignedIntegerConcept { void __constraints() {} }; template <> struct _UnsignedIntegerConcept { void __constraints() {} }; //=========================================================================== // Basic Concepts template struct _DefaultConstructibleConcept { void __constraints() { _Tp __a _IsUnused; // require default constructor } }; template struct _AssignableConcept { void __constraints() { __a = __a; // require assignment operator __const_constraints(__a); } void __const_constraints(const _Tp& __b) { __a = __b; // const required for argument to assignment } _Tp __a; // possibly should be "Tp* a;" and then dereference "a" in constraint // functions? present way would require a default ctor, i think... }; template struct _CopyConstructibleConcept { void __constraints() { _Tp __a(__b); // require copy constructor _Tp* __ptr _IsUnused = &__a; // require address of operator __const_constraints(__a); } void __const_constraints(const _Tp& __a) { _Tp __c _IsUnused(__a); // require const copy constructor const _Tp* __ptr _IsUnused = &__a; // require const address of operator } _Tp __b; }; // The SGI STL version of Assignable requires copy constructor and operator= template struct _SGIAssignableConcept { void __constraints() { _Tp __b _IsUnused(__a); __a = __a; // require assignment operator __const_constraints(__a); } void __const_constraints(const _Tp& __b) { _Tp __c _IsUnused(__b); __a = __b; // const required for argument to assignment } _Tp __a; }; template struct _ConvertibleConcept { void __constraints() { _To __y _IsUnused = __x; } _From __x; }; // The C++ standard requirements for many concepts talk about return // types that must be "convertible to bool". The problem with this // requirement is that it leaves the door open for evil proxies that // define things like operator|| with strange return types. Two // possible solutions are: // 1) require the return type to be exactly bool // 2) stay with convertible to bool, and also // specify stuff about all the logical operators. // For now we just test for convertible to bool. template void __aux_require_boolean_expr(const _Tp& __t) { bool __x _IsUnused = __t; } // FIXME template struct _EqualityComparableConcept { void __constraints() { __aux_require_boolean_expr(__a == __b); } _Tp __a, __b; }; template struct _LessThanComparableConcept { void __constraints() { __aux_require_boolean_expr(__a < __b); } _Tp __a, __b; }; // This is equivalent to SGI STL's LessThanComparable. template struct _ComparableConcept { void __constraints() { __aux_require_boolean_expr(__a < __b); __aux_require_boolean_expr(__a > __b); __aux_require_boolean_expr(__a <= __b); __aux_require_boolean_expr(__a >= __b); } _Tp __a, __b; }; #define _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(_OP,_NAME) \ template \ struct _NAME { \ void __constraints() { (void)__constraints_(); } \ bool __constraints_() { \ return __a _OP __b; \ } \ _First __a; \ _Second __b; \ } #define _GLIBCXX_DEFINE_BINARY_OPERATOR_CONSTRAINT(_OP,_NAME) \ template \ struct _NAME { \ void __constraints() { (void)__constraints_(); } \ _Ret __constraints_() { \ return __a _OP __b; \ } \ _First __a; \ _Second __b; \ } _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(==, _EqualOpConcept); _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(!=, _NotEqualOpConcept); _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(<, _LessThanOpConcept); _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(<=, _LessEqualOpConcept); _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(>, _GreaterThanOpConcept); _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(>=, _GreaterEqualOpConcept); _GLIBCXX_DEFINE_BINARY_OPERATOR_CONSTRAINT(+, _PlusOpConcept); _GLIBCXX_DEFINE_BINARY_OPERATOR_CONSTRAINT(*, _TimesOpConcept); _GLIBCXX_DEFINE_BINARY_OPERATOR_CONSTRAINT(/, _DivideOpConcept); _GLIBCXX_DEFINE_BINARY_OPERATOR_CONSTRAINT(-, _SubtractOpConcept); _GLIBCXX_DEFINE_BINARY_OPERATOR_CONSTRAINT(%, _ModOpConcept); #undef _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT #undef _GLIBCXX_DEFINE_BINARY_OPERATOR_CONSTRAINT //=========================================================================== // Function Object Concepts template struct _GeneratorConcept { void __constraints() { const _Return& __r _IsUnused = __f();// require operator() member function } _Func __f; }; template struct _GeneratorConcept<_Func,void> { void __constraints() { __f(); // require operator() member function } _Func __f; }; template struct _UnaryFunctionConcept { void __constraints() { __r = __f(__arg); // require operator() } _Func __f; _Arg __arg; _Return __r; }; template struct _UnaryFunctionConcept<_Func, void, _Arg> { void __constraints() { __f(__arg); // require operator() } _Func __f; _Arg __arg; }; template struct _BinaryFunctionConcept { void __constraints() { __r = __f(__first, __second); // require operator() } _Func __f; _First __first; _Second __second; _Return __r; }; template struct _BinaryFunctionConcept<_Func, void, _First, _Second> { void __constraints() { __f(__first, __second); // require operator() } _Func __f; _First __first; _Second __second; }; template struct _UnaryPredicateConcept { void __constraints() { __aux_require_boolean_expr(__f(__arg)); // require op() returning bool } _Func __f; _Arg __arg; }; template struct _BinaryPredicateConcept { void __constraints() { __aux_require_boolean_expr(__f(__a, __b)); // require op() returning bool } _Func __f; _First __a; _Second __b; }; // use this when functor is used inside a container class like std::set template struct _Const_BinaryPredicateConcept { void __constraints() { __const_constraints(__f); } void __const_constraints(const _Func& __fun) { __function_requires<_BinaryPredicateConcept<_Func, _First, _Second> >(); // operator() must be a const member function __aux_require_boolean_expr(__fun(__a, __b)); } _Func __f; _First __a; _Second __b; }; //=========================================================================== // Iterator Concepts template struct _TrivialIteratorConcept { void __constraints() { // __function_requires< _DefaultConstructibleConcept<_Tp> >(); __function_requires< _AssignableConcept<_Tp> >(); __function_requires< _EqualityComparableConcept<_Tp> >(); // typedef typename std::iterator_traits<_Tp>::value_type _V; (void)*__i; // require dereference operator } _Tp __i; }; template struct _Mutable_TrivialIteratorConcept { void __constraints() { __function_requires< _TrivialIteratorConcept<_Tp> >(); *__i = *__j; // require dereference and assignment } _Tp __i, __j; }; template struct _InputIteratorConcept { void __constraints() { __function_requires< _TrivialIteratorConcept<_Tp> >(); // require iterator_traits typedef's typedef typename std::iterator_traits<_Tp>::difference_type _Diff; // __function_requires< _SignedIntegerConcept<_Diff> >(); typedef typename std::iterator_traits<_Tp>::reference _Ref; typedef typename std::iterator_traits<_Tp>::pointer _Pt; typedef typename std::iterator_traits<_Tp>::iterator_category _Cat; __function_requires< _ConvertibleConcept< typename std::iterator_traits<_Tp>::iterator_category, std::input_iterator_tag> >(); ++__i; // require preincrement operator __i++; // require postincrement operator } _Tp __i; }; template struct _OutputIteratorConcept { void __constraints() { __function_requires< _AssignableConcept<_Tp> >(); ++__i; // require preincrement operator __i++; // require postincrement operator *__i++ = __t; // require postincrement and assignment } _Tp __i; _ValueT __t; }; template struct _ForwardIteratorConcept { void __constraints() { __function_requires< _InputIteratorConcept<_Tp> >(); __function_requires< _DefaultConstructibleConcept<_Tp> >(); __function_requires< _ConvertibleConcept< typename std::iterator_traits<_Tp>::iterator_category, std::forward_iterator_tag> >(); typedef typename std::iterator_traits<_Tp>::reference _Ref; _Ref __r _IsUnused = *__i; } _Tp __i; }; template struct _Mutable_ForwardIteratorConcept { void __constraints() { __function_requires< _ForwardIteratorConcept<_Tp> >(); *__i++ = *__i; // require postincrement and assignment } _Tp __i; }; template struct _BidirectionalIteratorConcept { void __constraints() { __function_requires< _ForwardIteratorConcept<_Tp> >(); __function_requires< _ConvertibleConcept< typename std::iterator_traits<_Tp>::iterator_category, std::bidirectional_iterator_tag> >(); --__i; // require predecrement operator __i--; // require postdecrement operator } _Tp __i; }; template struct _Mutable_BidirectionalIteratorConcept { void __constraints() { __function_requires< _BidirectionalIteratorConcept<_Tp> >(); __function_requires< _Mutable_ForwardIteratorConcept<_Tp> >(); *__i-- = *__i; // require postdecrement and assignment } _Tp __i; }; template struct _RandomAccessIteratorConcept { void __constraints() { __function_requires< _BidirectionalIteratorConcept<_Tp> >(); __function_requires< _ComparableConcept<_Tp> >(); __function_requires< _ConvertibleConcept< typename std::iterator_traits<_Tp>::iterator_category, std::random_access_iterator_tag> >(); // ??? We don't use _Ref, are we just checking for "referenceability"? typedef typename std::iterator_traits<_Tp>::reference _Ref; __i += __n; // require assignment addition operator __i = __i + __n; __i = __n + __i; // require addition with difference type __i -= __n; // require assignment subtraction op __i = __i - __n; // require subtraction with // difference type __n = __i - __j; // require difference operator (void)__i[__n]; // require element access operator } _Tp __a, __b; _Tp __i, __j; typename std::iterator_traits<_Tp>::difference_type __n; }; template struct _Mutable_RandomAccessIteratorConcept { void __constraints() { __function_requires< _RandomAccessIteratorConcept<_Tp> >(); __function_requires< _Mutable_BidirectionalIteratorConcept<_Tp> >(); __i[__n] = *__i; // require element access and assignment } _Tp __i; typename std::iterator_traits<_Tp>::difference_type __n; }; //=========================================================================== // Container Concepts template struct _ContainerConcept { typedef typename _Container::value_type _Value_type; typedef typename _Container::difference_type _Difference_type; typedef typename _Container::size_type _Size_type; typedef typename _Container::const_reference _Const_reference; typedef typename _Container::const_pointer _Const_pointer; typedef typename _Container::const_iterator _Const_iterator; void __constraints() { __function_requires< _InputIteratorConcept<_Const_iterator> >(); __function_requires< _AssignableConcept<_Container> >(); const _Container __c; __i = __c.begin(); __i = __c.end(); __n = __c.size(); __n = __c.max_size(); __b = __c.empty(); } bool __b; _Const_iterator __i; _Size_type __n; }; template struct _Mutable_ContainerConcept { typedef typename _Container::value_type _Value_type; typedef typename _Container::reference _Reference; typedef typename _Container::iterator _Iterator; typedef typename _Container::pointer _Pointer; void __constraints() { __function_requires< _ContainerConcept<_Container> >(); __function_requires< _AssignableConcept<_Value_type> >(); __function_requires< _InputIteratorConcept<_Iterator> >(); __i = __c.begin(); __i = __c.end(); __c.swap(__c2); } _Iterator __i; _Container __c, __c2; }; template struct _ForwardContainerConcept { void __constraints() { __function_requires< _ContainerConcept<_ForwardContainer> >(); typedef typename _ForwardContainer::const_iterator _Const_iterator; __function_requires< _ForwardIteratorConcept<_Const_iterator> >(); } }; template struct _Mutable_ForwardContainerConcept { void __constraints() { __function_requires< _ForwardContainerConcept<_ForwardContainer> >(); __function_requires< _Mutable_ContainerConcept<_ForwardContainer> >(); typedef typename _ForwardContainer::iterator _Iterator; __function_requires< _Mutable_ForwardIteratorConcept<_Iterator> >(); } }; template struct _ReversibleContainerConcept { typedef typename _ReversibleContainer::const_iterator _Const_iterator; typedef typename _ReversibleContainer::const_reverse_iterator _Const_reverse_iterator; void __constraints() { __function_requires< _ForwardContainerConcept<_ReversibleContainer> >(); __function_requires< _BidirectionalIteratorConcept<_Const_iterator> >(); __function_requires< _BidirectionalIteratorConcept<_Const_reverse_iterator> >(); const _ReversibleContainer __c; _Const_reverse_iterator __i = __c.rbegin(); __i = __c.rend(); } }; template struct _Mutable_ReversibleContainerConcept { typedef typename _ReversibleContainer::iterator _Iterator; typedef typename _ReversibleContainer::reverse_iterator _Reverse_iterator; void __constraints() { __function_requires<_ReversibleContainerConcept<_ReversibleContainer> >(); __function_requires< _Mutable_ForwardContainerConcept<_ReversibleContainer> >(); __function_requires<_Mutable_BidirectionalIteratorConcept<_Iterator> >(); __function_requires< _Mutable_BidirectionalIteratorConcept<_Reverse_iterator> >(); _Reverse_iterator __i = __c.rbegin(); __i = __c.rend(); } _ReversibleContainer __c; }; template struct _RandomAccessContainerConcept { typedef typename _RandomAccessContainer::size_type _Size_type; typedef typename _RandomAccessContainer::const_reference _Const_reference; typedef typename _RandomAccessContainer::const_iterator _Const_iterator; typedef typename _RandomAccessContainer::const_reverse_iterator _Const_reverse_iterator; void __constraints() { __function_requires< _ReversibleContainerConcept<_RandomAccessContainer> >(); __function_requires< _RandomAccessIteratorConcept<_Const_iterator> >(); __function_requires< _RandomAccessIteratorConcept<_Const_reverse_iterator> >(); const _RandomAccessContainer __c; _Const_reference __r _IsUnused = __c[__n]; } _Size_type __n; }; template struct _Mutable_RandomAccessContainerConcept { typedef typename _RandomAccessContainer::size_type _Size_type; typedef typename _RandomAccessContainer::reference _Reference; typedef typename _RandomAccessContainer::iterator _Iterator; typedef typename _RandomAccessContainer::reverse_iterator _Reverse_iterator; void __constraints() { __function_requires< _RandomAccessContainerConcept<_RandomAccessContainer> >(); __function_requires< _Mutable_ReversibleContainerConcept<_RandomAccessContainer> >(); __function_requires< _Mutable_RandomAccessIteratorConcept<_Iterator> >(); __function_requires< _Mutable_RandomAccessIteratorConcept<_Reverse_iterator> >(); _Reference __r _IsUnused = __c[__i]; } _Size_type __i; _RandomAccessContainer __c; }; // A Sequence is inherently mutable template struct _SequenceConcept { typedef typename _Sequence::reference _Reference; typedef typename _Sequence::const_reference _Const_reference; void __constraints() { // Matt Austern's book puts DefaultConstructible here, the C++ // standard places it in Container // function_requires< DefaultConstructible >(); __function_requires< _Mutable_ForwardContainerConcept<_Sequence> >(); __function_requires< _DefaultConstructibleConcept<_Sequence> >(); _Sequence __c _IsUnused(__n, __t), __c2 _IsUnused(__first, __last); __c.insert(__p, __t); __c.insert(__p, __n, __t); __c.insert(__p, __first, __last); __c.erase(__p); __c.erase(__p, __q); _Reference __r _IsUnused = __c.front(); __const_constraints(__c); } void __const_constraints(const _Sequence& __c) { _Const_reference __r _IsUnused = __c.front(); } typename _Sequence::value_type __t; typename _Sequence::size_type __n; typename _Sequence::value_type *__first, *__last; typename _Sequence::iterator __p, __q; }; template struct _FrontInsertionSequenceConcept { void __constraints() { __function_requires< _SequenceConcept<_FrontInsertionSequence> >(); __c.push_front(__t); __c.pop_front(); } _FrontInsertionSequence __c; typename _FrontInsertionSequence::value_type __t; }; template struct _BackInsertionSequenceConcept { typedef typename _BackInsertionSequence::reference _Reference; typedef typename _BackInsertionSequence::const_reference _Const_reference; void __constraints() { __function_requires< _SequenceConcept<_BackInsertionSequence> >(); __c.push_back(__t); __c.pop_back(); _Reference __r _IsUnused = __c.back(); } void __const_constraints(const _BackInsertionSequence& __c) { _Const_reference __r _IsUnused = __c.back(); }; _BackInsertionSequence __c; typename _BackInsertionSequence::value_type __t; }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #pragma GCC diagnostic pop #undef _IsUnused #endif // _GLIBCXX_BOOST_CONCEPT_CHECK PK!L+J8/bits/c++0x_warning.hnu[// Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/c++0x_warning.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iosfwd} */ #ifndef _CXX0X_WARNING_H #define _CXX0X_WARNING_H 1 #if __cplusplus < 201103L #error This file requires compiler and library support \ for the ISO C++ 2011 standard. This support must be enabled \ with the -std=c++11 or -std=gnu++11 compiler options. #endif #endif PK!8QQ8/bits/char_traits.hnu[// Character Traits for use by standard string and iostream -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/char_traits.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{string} */ // // ISO C++ 14882: 21 Strings library // #ifndef _CHAR_TRAITS_H #define _CHAR_TRAITS_H 1 #pragma GCC system_header #include // std::copy, std::fill_n #include // For streampos #include // For WEOF, wmemmove, wmemset, etc. #ifndef _GLIBCXX_ALWAYS_INLINE #define _GLIBCXX_ALWAYS_INLINE inline __attribute__((__always_inline__)) #endif namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief Mapping from character type to associated types. * * @note This is an implementation class for the generic version * of char_traits. It defines int_type, off_type, pos_type, and * state_type. By default these are unsigned long, streamoff, * streampos, and mbstate_t. Users who need a different set of * types, but who don't need to change the definitions of any function * defined in char_traits, can specialize __gnu_cxx::_Char_types * while leaving __gnu_cxx::char_traits alone. */ template struct _Char_types { typedef unsigned long int_type; typedef std::streampos pos_type; typedef std::streamoff off_type; typedef std::mbstate_t state_type; }; /** * @brief Base class used to implement std::char_traits. * * @note For any given actual character type, this definition is * probably wrong. (Most of the member functions are likely to be * right, but the int_type and state_type typedefs, and the eof() * member function, are likely to be wrong.) The reason this class * exists is so users can specialize it. Classes in namespace std * may not be specialized for fundamental types, but classes in * namespace __gnu_cxx may be. * * See https://gcc.gnu.org/onlinedocs/libstdc++/manual/strings.html#strings.string.character_types * for advice on how to make use of this class for @a unusual character * types. Also, check out include/ext/pod_char_traits.h. */ template struct char_traits { typedef _CharT char_type; typedef typename _Char_types<_CharT>::int_type int_type; typedef typename _Char_types<_CharT>::pos_type pos_type; typedef typename _Char_types<_CharT>::off_type off_type; typedef typename _Char_types<_CharT>::state_type state_type; static _GLIBCXX14_CONSTEXPR void assign(char_type& __c1, const char_type& __c2) { __c1 = __c2; } static _GLIBCXX_CONSTEXPR bool eq(const char_type& __c1, const char_type& __c2) { return __c1 == __c2; } static _GLIBCXX_CONSTEXPR bool lt(const char_type& __c1, const char_type& __c2) { return __c1 < __c2; } static _GLIBCXX14_CONSTEXPR int compare(const char_type* __s1, const char_type* __s2, std::size_t __n); static _GLIBCXX14_CONSTEXPR std::size_t length(const char_type* __s); static _GLIBCXX14_CONSTEXPR const char_type* find(const char_type* __s, std::size_t __n, const char_type& __a); static char_type* move(char_type* __s1, const char_type* __s2, std::size_t __n); static char_type* copy(char_type* __s1, const char_type* __s2, std::size_t __n); static char_type* assign(char_type* __s, std::size_t __n, char_type __a); static _GLIBCXX_CONSTEXPR char_type to_char_type(const int_type& __c) { return static_cast(__c); } static _GLIBCXX_CONSTEXPR int_type to_int_type(const char_type& __c) { return static_cast(__c); } static _GLIBCXX_CONSTEXPR bool eq_int_type(const int_type& __c1, const int_type& __c2) { return __c1 == __c2; } static _GLIBCXX_CONSTEXPR int_type eof() { return static_cast(_GLIBCXX_STDIO_EOF); } static _GLIBCXX_CONSTEXPR int_type not_eof(const int_type& __c) { return !eq_int_type(__c, eof()) ? __c : to_int_type(char_type()); } }; template _GLIBCXX14_CONSTEXPR int char_traits<_CharT>:: compare(const char_type* __s1, const char_type* __s2, std::size_t __n) { for (std::size_t __i = 0; __i < __n; ++__i) if (lt(__s1[__i], __s2[__i])) return -1; else if (lt(__s2[__i], __s1[__i])) return 1; return 0; } template _GLIBCXX14_CONSTEXPR std::size_t char_traits<_CharT>:: length(const char_type* __p) { std::size_t __i = 0; while (!eq(__p[__i], char_type())) ++__i; return __i; } template _GLIBCXX14_CONSTEXPR const typename char_traits<_CharT>::char_type* char_traits<_CharT>:: find(const char_type* __s, std::size_t __n, const char_type& __a) { for (std::size_t __i = 0; __i < __n; ++__i) if (eq(__s[__i], __a)) return __s + __i; return 0; } template typename char_traits<_CharT>::char_type* char_traits<_CharT>:: move(char_type* __s1, const char_type* __s2, std::size_t __n) { if (__n == 0) return __s1; return static_cast<_CharT*>(__builtin_memmove(__s1, __s2, __n * sizeof(char_type))); } template typename char_traits<_CharT>::char_type* char_traits<_CharT>:: copy(char_type* __s1, const char_type* __s2, std::size_t __n) { // NB: Inline std::copy so no recursive dependencies. std::copy(__s2, __s2 + __n, __s1); return __s1; } template typename char_traits<_CharT>::char_type* char_traits<_CharT>:: assign(char_type* __s, std::size_t __n, char_type __a) { // NB: Inline std::fill_n so no recursive dependencies. std::fill_n(__s, __n, __a); return __s; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if __cplusplus > 201402 #define __cpp_lib_constexpr_char_traits 201611 /** * @brief Determine whether the characters of a NULL-terminated * string are known at compile time. * @param __s The string. * * Assumes that _CharT is a built-in character type. */ template static _GLIBCXX_ALWAYS_INLINE constexpr bool __constant_string_p(const _CharT* __s) { while (__builtin_constant_p(*__s) && *__s) __s++; return __builtin_constant_p(*__s); } /** * @brief Determine whether the characters of a character array are * known at compile time. * @param __a The character array. * @param __n Number of characters. * * Assumes that _CharT is a built-in character type. */ template static _GLIBCXX_ALWAYS_INLINE constexpr bool __constant_char_array_p(const _CharT* __a, size_t __n) { size_t __i = 0; while (__i < __n && __builtin_constant_p(__a[__i])) __i++; return __i == __n; } #endif // 21.1 /** * @brief Basis for explicit traits specializations. * * @note For any given actual character type, this definition is * probably wrong. Since this is just a thin wrapper around * __gnu_cxx::char_traits, it is possible to achieve a more * appropriate definition by specializing __gnu_cxx::char_traits. * * See https://gcc.gnu.org/onlinedocs/libstdc++/manual/strings.html#strings.string.character_types * for advice on how to make use of this class for @a unusual character * types. Also, check out include/ext/pod_char_traits.h. */ template struct char_traits : public __gnu_cxx::char_traits<_CharT> { }; /// 21.1.3.1 char_traits specializations template<> struct char_traits { typedef char char_type; typedef int int_type; typedef streampos pos_type; typedef streamoff off_type; typedef mbstate_t state_type; static _GLIBCXX17_CONSTEXPR void assign(char_type& __c1, const char_type& __c2) _GLIBCXX_NOEXCEPT { __c1 = __c2; } static _GLIBCXX_CONSTEXPR bool eq(const char_type& __c1, const char_type& __c2) _GLIBCXX_NOEXCEPT { return __c1 == __c2; } static _GLIBCXX_CONSTEXPR bool lt(const char_type& __c1, const char_type& __c2) _GLIBCXX_NOEXCEPT { // LWG 467. return (static_cast(__c1) < static_cast(__c2)); } static _GLIBCXX17_CONSTEXPR int compare(const char_type* __s1, const char_type* __s2, size_t __n) { #if __cplusplus > 201402 if (__builtin_constant_p(__n) && __constant_char_array_p(__s1, __n) && __constant_char_array_p(__s2, __n)) { for (size_t __i = 0; __i < __n; ++__i) if (lt(__s1[__i], __s2[__i])) return -1; else if (lt(__s2[__i], __s1[__i])) return 1; return 0; } #endif if (__n == 0) return 0; return __builtin_memcmp(__s1, __s2, __n); } static _GLIBCXX17_CONSTEXPR size_t length(const char_type* __s) { #if __cplusplus > 201402 if (__constant_string_p(__s)) return __gnu_cxx::char_traits::length(__s); #endif return __builtin_strlen(__s); } static _GLIBCXX17_CONSTEXPR const char_type* find(const char_type* __s, size_t __n, const char_type& __a) { #if __cplusplus > 201402 if (__builtin_constant_p(__n) && __builtin_constant_p(__a) && __constant_char_array_p(__s, __n)) return __gnu_cxx::char_traits::find(__s, __n, __a); #endif if (__n == 0) return 0; return static_cast(__builtin_memchr(__s, __a, __n)); } static char_type* move(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return static_cast(__builtin_memmove(__s1, __s2, __n)); } static char_type* copy(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return static_cast(__builtin_memcpy(__s1, __s2, __n)); } static char_type* assign(char_type* __s, size_t __n, char_type __a) { if (__n == 0) return __s; return static_cast(__builtin_memset(__s, __a, __n)); } static _GLIBCXX_CONSTEXPR char_type to_char_type(const int_type& __c) _GLIBCXX_NOEXCEPT { return static_cast(__c); } // To keep both the byte 0xff and the eof symbol 0xffffffff // from ending up as 0xffffffff. static _GLIBCXX_CONSTEXPR int_type to_int_type(const char_type& __c) _GLIBCXX_NOEXCEPT { return static_cast(static_cast(__c)); } static _GLIBCXX_CONSTEXPR bool eq_int_type(const int_type& __c1, const int_type& __c2) _GLIBCXX_NOEXCEPT { return __c1 == __c2; } static _GLIBCXX_CONSTEXPR int_type eof() _GLIBCXX_NOEXCEPT { return static_cast(_GLIBCXX_STDIO_EOF); } static _GLIBCXX_CONSTEXPR int_type not_eof(const int_type& __c) _GLIBCXX_NOEXCEPT { return (__c == eof()) ? 0 : __c; } }; #ifdef _GLIBCXX_USE_WCHAR_T /// 21.1.3.2 char_traits specializations template<> struct char_traits { typedef wchar_t char_type; typedef wint_t int_type; typedef streamoff off_type; typedef wstreampos pos_type; typedef mbstate_t state_type; static _GLIBCXX17_CONSTEXPR void assign(char_type& __c1, const char_type& __c2) _GLIBCXX_NOEXCEPT { __c1 = __c2; } static _GLIBCXX_CONSTEXPR bool eq(const char_type& __c1, const char_type& __c2) _GLIBCXX_NOEXCEPT { return __c1 == __c2; } static _GLIBCXX_CONSTEXPR bool lt(const char_type& __c1, const char_type& __c2) _GLIBCXX_NOEXCEPT { return __c1 < __c2; } static _GLIBCXX17_CONSTEXPR int compare(const char_type* __s1, const char_type* __s2, size_t __n) { #if __cplusplus > 201402 if (__builtin_constant_p(__n) && __constant_char_array_p(__s1, __n) && __constant_char_array_p(__s2, __n)) return __gnu_cxx::char_traits::compare(__s1, __s2, __n); #endif if (__n == 0) return 0; else return wmemcmp(__s1, __s2, __n); } static _GLIBCXX17_CONSTEXPR size_t length(const char_type* __s) { #if __cplusplus > 201402 if (__constant_string_p(__s)) return __gnu_cxx::char_traits::length(__s); else #endif return wcslen(__s); } static _GLIBCXX17_CONSTEXPR const char_type* find(const char_type* __s, size_t __n, const char_type& __a) { #if __cplusplus > 201402 if (__builtin_constant_p(__n) && __builtin_constant_p(__a) && __constant_char_array_p(__s, __n)) return __gnu_cxx::char_traits::find(__s, __n, __a); #endif if (__n == 0) return 0; else return wmemchr(__s, __a, __n); } static char_type* move(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return wmemmove(__s1, __s2, __n); } static char_type* copy(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return wmemcpy(__s1, __s2, __n); } static char_type* assign(char_type* __s, size_t __n, char_type __a) { if (__n == 0) return __s; return wmemset(__s, __a, __n); } static _GLIBCXX_CONSTEXPR char_type to_char_type(const int_type& __c) _GLIBCXX_NOEXCEPT { return char_type(__c); } static _GLIBCXX_CONSTEXPR int_type to_int_type(const char_type& __c) _GLIBCXX_NOEXCEPT { return int_type(__c); } static _GLIBCXX_CONSTEXPR bool eq_int_type(const int_type& __c1, const int_type& __c2) _GLIBCXX_NOEXCEPT { return __c1 == __c2; } static _GLIBCXX_CONSTEXPR int_type eof() _GLIBCXX_NOEXCEPT { return static_cast(WEOF); } static _GLIBCXX_CONSTEXPR int_type not_eof(const int_type& __c) _GLIBCXX_NOEXCEPT { return eq_int_type(__c, eof()) ? 0 : __c; } }; #endif //_GLIBCXX_USE_WCHAR_T _GLIBCXX_END_NAMESPACE_VERSION } // namespace #if ((__cplusplus >= 201103L) \ && defined(_GLIBCXX_USE_C99_STDINT_TR1)) #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template<> struct char_traits { typedef char16_t char_type; typedef uint_least16_t int_type; typedef streamoff off_type; typedef u16streampos pos_type; typedef mbstate_t state_type; static _GLIBCXX17_CONSTEXPR void assign(char_type& __c1, const char_type& __c2) noexcept { __c1 = __c2; } static constexpr bool eq(const char_type& __c1, const char_type& __c2) noexcept { return __c1 == __c2; } static constexpr bool lt(const char_type& __c1, const char_type& __c2) noexcept { return __c1 < __c2; } static _GLIBCXX17_CONSTEXPR int compare(const char_type* __s1, const char_type* __s2, size_t __n) { for (size_t __i = 0; __i < __n; ++__i) if (lt(__s1[__i], __s2[__i])) return -1; else if (lt(__s2[__i], __s1[__i])) return 1; return 0; } static _GLIBCXX17_CONSTEXPR size_t length(const char_type* __s) { size_t __i = 0; while (!eq(__s[__i], char_type())) ++__i; return __i; } static _GLIBCXX17_CONSTEXPR const char_type* find(const char_type* __s, size_t __n, const char_type& __a) { for (size_t __i = 0; __i < __n; ++__i) if (eq(__s[__i], __a)) return __s + __i; return 0; } static char_type* move(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return (static_cast (__builtin_memmove(__s1, __s2, __n * sizeof(char_type)))); } static char_type* copy(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return (static_cast (__builtin_memcpy(__s1, __s2, __n * sizeof(char_type)))); } static char_type* assign(char_type* __s, size_t __n, char_type __a) { for (size_t __i = 0; __i < __n; ++__i) assign(__s[__i], __a); return __s; } static constexpr char_type to_char_type(const int_type& __c) noexcept { return char_type(__c); } static constexpr int_type to_int_type(const char_type& __c) noexcept { return __c == eof() ? int_type(0xfffd) : int_type(__c); } static constexpr bool eq_int_type(const int_type& __c1, const int_type& __c2) noexcept { return __c1 == __c2; } static constexpr int_type eof() noexcept { return static_cast(-1); } static constexpr int_type not_eof(const int_type& __c) noexcept { return eq_int_type(__c, eof()) ? 0 : __c; } }; template<> struct char_traits { typedef char32_t char_type; typedef uint_least32_t int_type; typedef streamoff off_type; typedef u32streampos pos_type; typedef mbstate_t state_type; static _GLIBCXX17_CONSTEXPR void assign(char_type& __c1, const char_type& __c2) noexcept { __c1 = __c2; } static constexpr bool eq(const char_type& __c1, const char_type& __c2) noexcept { return __c1 == __c2; } static constexpr bool lt(const char_type& __c1, const char_type& __c2) noexcept { return __c1 < __c2; } static _GLIBCXX17_CONSTEXPR int compare(const char_type* __s1, const char_type* __s2, size_t __n) { for (size_t __i = 0; __i < __n; ++__i) if (lt(__s1[__i], __s2[__i])) return -1; else if (lt(__s2[__i], __s1[__i])) return 1; return 0; } static _GLIBCXX17_CONSTEXPR size_t length(const char_type* __s) { size_t __i = 0; while (!eq(__s[__i], char_type())) ++__i; return __i; } static _GLIBCXX17_CONSTEXPR const char_type* find(const char_type* __s, size_t __n, const char_type& __a) { for (size_t __i = 0; __i < __n; ++__i) if (eq(__s[__i], __a)) return __s + __i; return 0; } static char_type* move(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return (static_cast (__builtin_memmove(__s1, __s2, __n * sizeof(char_type)))); } static char_type* copy(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return (static_cast (__builtin_memcpy(__s1, __s2, __n * sizeof(char_type)))); } static char_type* assign(char_type* __s, size_t __n, char_type __a) { for (size_t __i = 0; __i < __n; ++__i) assign(__s[__i], __a); return __s; } static constexpr char_type to_char_type(const int_type& __c) noexcept { return char_type(__c); } static constexpr int_type to_int_type(const char_type& __c) noexcept { return int_type(__c); } static constexpr bool eq_int_type(const int_type& __c1, const int_type& __c2) noexcept { return __c1 == __c2; } static constexpr int_type eof() noexcept { return static_cast(-1); } static constexpr int_type not_eof(const int_type& __c) noexcept { return eq_int_type(__c, eof()) ? 0 : __c; } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif #endif // _CHAR_TRAITS_H PK!])S)S8/bits/codecvt.hnu[// Locale support (codecvt) -*- C++ -*- // Copyright (C) 2000-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/codecvt.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.2.1.5 Template class codecvt // // Written by Benjamin Kosnik #ifndef _CODECVT_H #define _CODECVT_H 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /// Empty base class for codecvt facet [22.2.1.5]. class codecvt_base { public: enum result { ok, partial, error, noconv }; }; /** * @brief Common base for codecvt functions. * * This template class provides implementations of the public functions * that forward to the protected virtual functions. * * This template also provides abstract stubs for the protected virtual * functions. */ template class __codecvt_abstract_base : public locale::facet, public codecvt_base { public: // Types: typedef codecvt_base::result result; typedef _InternT intern_type; typedef _ExternT extern_type; typedef _StateT state_type; // 22.2.1.5.1 codecvt members /** * @brief Convert from internal to external character set. * * Converts input string of intern_type to output string of * extern_type. This is analogous to wcsrtombs. It does this by * calling codecvt::do_out. * * The source and destination character sets are determined by the * facet's locale, internal and external types. * * The characters in [from,from_end) are converted and written to * [to,to_end). from_next and to_next are set to point to the * character following the last successfully converted character, * respectively. If the result needed no conversion, from_next and * to_next are not affected. * * The @a state argument should be initialized if the input is at the * beginning and carried from a previous call if continuing * conversion. There are no guarantees about how @a state is used. * * The result returned is a member of codecvt_base::result. If * all the input is converted, returns codecvt_base::ok. If no * conversion is necessary, returns codecvt_base::noconv. If * the input ends early or there is insufficient space in the * output, returns codecvt_base::partial. Otherwise the * conversion failed and codecvt_base::error is returned. * * @param __state Persistent conversion state data. * @param __from Start of input. * @param __from_end End of input. * @param __from_next Returns start of unconverted data. * @param __to Start of output buffer. * @param __to_end End of output buffer. * @param __to_next Returns start of unused output area. * @return codecvt_base::result. */ result out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { return this->do_out(__state, __from, __from_end, __from_next, __to, __to_end, __to_next); } /** * @brief Reset conversion state. * * Writes characters to output that would restore @a state to initial * conditions. The idea is that if a partial conversion occurs, then * the converting the characters written by this function would leave * the state in initial conditions, rather than partial conversion * state. It does this by calling codecvt::do_unshift(). * * For example, if 4 external characters always converted to 1 internal * character, and input to in() had 6 external characters with state * saved, this function would write two characters to the output and * set the state to initialized conditions. * * The source and destination character sets are determined by the * facet's locale, internal and external types. * * The result returned is a member of codecvt_base::result. If the * state could be reset and data written, returns codecvt_base::ok. If * no conversion is necessary, returns codecvt_base::noconv. If the * output has insufficient space, returns codecvt_base::partial. * Otherwise the reset failed and codecvt_base::error is returned. * * @param __state Persistent conversion state data. * @param __to Start of output buffer. * @param __to_end End of output buffer. * @param __to_next Returns start of unused output area. * @return codecvt_base::result. */ result unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { return this->do_unshift(__state, __to,__to_end,__to_next); } /** * @brief Convert from external to internal character set. * * Converts input string of extern_type to output string of * intern_type. This is analogous to mbsrtowcs. It does this by * calling codecvt::do_in. * * The source and destination character sets are determined by the * facet's locale, internal and external types. * * The characters in [from,from_end) are converted and written to * [to,to_end). from_next and to_next are set to point to the * character following the last successfully converted character, * respectively. If the result needed no conversion, from_next and * to_next are not affected. * * The @a state argument should be initialized if the input is at the * beginning and carried from a previous call if continuing * conversion. There are no guarantees about how @a state is used. * * The result returned is a member of codecvt_base::result. If * all the input is converted, returns codecvt_base::ok. If no * conversion is necessary, returns codecvt_base::noconv. If * the input ends early or there is insufficient space in the * output, returns codecvt_base::partial. Otherwise the * conversion failed and codecvt_base::error is returned. * * @param __state Persistent conversion state data. * @param __from Start of input. * @param __from_end End of input. * @param __from_next Returns start of unconverted data. * @param __to Start of output buffer. * @param __to_end End of output buffer. * @param __to_next Returns start of unused output area. * @return codecvt_base::result. */ result in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { return this->do_in(__state, __from, __from_end, __from_next, __to, __to_end, __to_next); } int encoding() const throw() { return this->do_encoding(); } bool always_noconv() const throw() { return this->do_always_noconv(); } int length(state_type& __state, const extern_type* __from, const extern_type* __end, size_t __max) const { return this->do_length(__state, __from, __end, __max); } int max_length() const throw() { return this->do_max_length(); } protected: explicit __codecvt_abstract_base(size_t __refs = 0) : locale::facet(__refs) { } virtual ~__codecvt_abstract_base() { } /** * @brief Convert from internal to external character set. * * Converts input string of intern_type to output string of * extern_type. This function is a hook for derived classes to change * the value returned. @see out for more information. */ virtual result do_out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const = 0; virtual result do_unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const = 0; virtual result do_in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const = 0; virtual int do_encoding() const throw() = 0; virtual bool do_always_noconv() const throw() = 0; virtual int do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const = 0; virtual int do_max_length() const throw() = 0; }; /** * @brief Primary class template codecvt. * @ingroup locales * * NB: Generic, mostly useless implementation. * */ template class codecvt : public __codecvt_abstract_base<_InternT, _ExternT, _StateT> { public: // Types: typedef codecvt_base::result result; typedef _InternT intern_type; typedef _ExternT extern_type; typedef _StateT state_type; protected: __c_locale _M_c_locale_codecvt; public: static locale::id id; explicit codecvt(size_t __refs = 0) : __codecvt_abstract_base<_InternT, _ExternT, _StateT> (__refs), _M_c_locale_codecvt(0) { } explicit codecvt(__c_locale __cloc, size_t __refs = 0); protected: virtual ~codecvt() { } virtual result do_out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const; virtual int do_encoding() const throw(); virtual bool do_always_noconv() const throw(); virtual int do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const; virtual int do_max_length() const throw(); }; template locale::id codecvt<_InternT, _ExternT, _StateT>::id; /// class codecvt specialization. template<> class codecvt : public __codecvt_abstract_base { friend class messages; public: // Types: typedef char intern_type; typedef char extern_type; typedef mbstate_t state_type; protected: __c_locale _M_c_locale_codecvt; public: static locale::id id; explicit codecvt(size_t __refs = 0); explicit codecvt(__c_locale __cloc, size_t __refs = 0); protected: virtual ~codecvt(); virtual result do_out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const; virtual int do_encoding() const throw(); virtual bool do_always_noconv() const throw(); virtual int do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const; virtual int do_max_length() const throw(); }; #ifdef _GLIBCXX_USE_WCHAR_T /** @brief Class codecvt specialization. * * Converts between narrow and wide characters in the native character set */ template<> class codecvt : public __codecvt_abstract_base { friend class messages; public: // Types: typedef wchar_t intern_type; typedef char extern_type; typedef mbstate_t state_type; protected: __c_locale _M_c_locale_codecvt; public: static locale::id id; explicit codecvt(size_t __refs = 0); explicit codecvt(__c_locale __cloc, size_t __refs = 0); protected: virtual ~codecvt(); virtual result do_out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const; virtual int do_encoding() const throw(); virtual bool do_always_noconv() const throw(); virtual int do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const; virtual int do_max_length() const throw(); }; #endif //_GLIBCXX_USE_WCHAR_T #if __cplusplus >= 201103L #ifdef _GLIBCXX_USE_C99_STDINT_TR1 /** @brief Class codecvt specialization. * * Converts between UTF-16 and UTF-8. */ template<> class codecvt : public __codecvt_abstract_base { public: // Types: typedef char16_t intern_type; typedef char extern_type; typedef mbstate_t state_type; public: static locale::id id; explicit codecvt(size_t __refs = 0) : __codecvt_abstract_base(__refs) { } protected: virtual ~codecvt(); virtual result do_out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const; virtual int do_encoding() const throw(); virtual bool do_always_noconv() const throw(); virtual int do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const; virtual int do_max_length() const throw(); }; /** @brief Class codecvt specialization. * * Converts between UTF-32 and UTF-8. */ template<> class codecvt : public __codecvt_abstract_base { public: // Types: typedef char32_t intern_type; typedef char extern_type; typedef mbstate_t state_type; public: static locale::id id; explicit codecvt(size_t __refs = 0) : __codecvt_abstract_base(__refs) { } protected: virtual ~codecvt(); virtual result do_out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const; virtual int do_encoding() const throw(); virtual bool do_always_noconv() const throw(); virtual int do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const; virtual int do_max_length() const throw(); }; #endif // _GLIBCXX_USE_C99_STDINT_TR1 #endif // C++11 /// class codecvt_byname [22.2.1.6]. template class codecvt_byname : public codecvt<_InternT, _ExternT, _StateT> { public: explicit codecvt_byname(const char* __s, size_t __refs = 0) : codecvt<_InternT, _ExternT, _StateT>(__refs) { if (__builtin_strcmp(__s, "C") != 0 && __builtin_strcmp(__s, "POSIX") != 0) { this->_S_destroy_c_locale(this->_M_c_locale_codecvt); this->_S_create_c_locale(this->_M_c_locale_codecvt, __s); } } #if __cplusplus >= 201103L explicit codecvt_byname(const string& __s, size_t __refs = 0) : codecvt_byname(__s.c_str(), __refs) { } #endif protected: virtual ~codecvt_byname() { } }; #if __cplusplus >= 201103L && defined(_GLIBCXX_USE_C99_STDINT_TR1) template<> class codecvt_byname : public codecvt { public: explicit codecvt_byname(const char*, size_t __refs = 0) : codecvt(__refs) { } explicit codecvt_byname(const string& __s, size_t __refs = 0) : codecvt_byname(__s.c_str(), __refs) { } protected: virtual ~codecvt_byname() { } }; template<> class codecvt_byname : public codecvt { public: explicit codecvt_byname(const char*, size_t __refs = 0) : codecvt(__refs) { } explicit codecvt_byname(const string& __s, size_t __refs = 0) : codecvt_byname(__s.c_str(), __refs) { } protected: virtual ~codecvt_byname() { } }; #endif // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class codecvt_byname; extern template const codecvt& use_facet >(const locale&); extern template bool has_facet >(const locale&); #ifdef _GLIBCXX_USE_WCHAR_T extern template class codecvt_byname; extern template const codecvt& use_facet >(const locale&); extern template bool has_facet >(const locale&); #endif #if __cplusplus >= 201103L && defined(_GLIBCXX_USE_C99_STDINT_TR1) extern template class codecvt_byname; extern template class codecvt_byname; #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _CODECVT_H PK! *^_ _ 8/bits/concept_check.hnu[// Concept-checking control -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/concept_check.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iterator} */ #ifndef _CONCEPT_CHECK_H #define _CONCEPT_CHECK_H 1 #pragma GCC system_header #include // All places in libstdc++-v3 where these are used, or /might/ be used, or // don't need to be used, or perhaps /should/ be used, are commented with // "concept requirements" (and maybe some more text). So grep like crazy // if you're looking for additional places to use these. // Concept-checking code is off by default unless users turn it on via // configure options or editing c++config.h. // It is not supported for freestanding implementations. #if !defined(_GLIBCXX_CONCEPT_CHECKS) || !_GLIBCXX_HOSTED #define __glibcxx_function_requires(...) #define __glibcxx_class_requires(_a,_b) #define __glibcxx_class_requires2(_a,_b,_c) #define __glibcxx_class_requires3(_a,_b,_c,_d) #define __glibcxx_class_requires4(_a,_b,_c,_d,_e) #else // the checks are on #include // Note that the obvious and elegant approach of // //#define glibcxx_function_requires(C) debug::function_requires< debug::C >() // // won't work due to concept templates with more than one parameter, e.g., // BinaryPredicateConcept. The preprocessor tries to split things up on // the commas in the template argument list. We can't use an inner pair of // parenthesis to hide the commas, because "debug::(Temp)" isn't // a valid instantiation pattern. Thus, we steal a feature from C99. #define __glibcxx_function_requires(...) \ __gnu_cxx::__function_requires< __gnu_cxx::__VA_ARGS__ >(); #define __glibcxx_class_requires(_a,_C) \ _GLIBCXX_CLASS_REQUIRES(_a, __gnu_cxx, _C); #define __glibcxx_class_requires2(_a,_b,_C) \ _GLIBCXX_CLASS_REQUIRES2(_a, _b, __gnu_cxx, _C); #define __glibcxx_class_requires3(_a,_b,_c,_C) \ _GLIBCXX_CLASS_REQUIRES3(_a, _b, _c, __gnu_cxx, _C); #define __glibcxx_class_requires4(_a,_b,_c,_d,_C) \ _GLIBCXX_CLASS_REQUIRES4(_a, _b, _c, _d, __gnu_cxx, _C); #endif // enable/disable #endif // _GLIBCXX_CONCEPT_CHECK PK!ƀ=&=&8/bits/cpp_type_traits.hnu[// The -*- C++ -*- type traits classes for internal use in libstdc++ // Copyright (C) 2000-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/cpp_type_traits.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ext/type_traits} */ // Written by Gabriel Dos Reis #ifndef _CPP_TYPE_TRAITS_H #define _CPP_TYPE_TRAITS_H 1 #pragma GCC system_header #include // // This file provides some compile-time information about various types. // These representations were designed, on purpose, to be constant-expressions // and not types as found in . In particular, they // can be used in control structures and the optimizer hopefully will do // the obvious thing. // // Why integral expressions, and not functions nor types? // Firstly, these compile-time entities are used as template-arguments // so function return values won't work: We need compile-time entities. // We're left with types and constant integral expressions. // Secondly, from the point of view of ease of use, type-based compile-time // information is -not- *that* convenient. On has to write lots of // overloaded functions and to hope that the compiler will select the right // one. As a net effect, the overall structure isn't very clear at first // glance. // Thirdly, partial ordering and overload resolution (of function templates) // is highly costly in terms of compiler-resource. It is a Good Thing to // keep these resource consumption as least as possible. // // See valarray_array.h for a case use. // // -- Gaby (dosreis@cmla.ens-cachan.fr) 2000-03-06. // // Update 2005: types are also provided and has been // removed. // extern "C++" { namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION struct __true_type { }; struct __false_type { }; template struct __truth_type { typedef __false_type __type; }; template<> struct __truth_type { typedef __true_type __type; }; // N.B. The conversions to bool are needed due to the issue // explained in c++/19404. template struct __traitor { enum { __value = bool(_Sp::__value) || bool(_Tp::__value) }; typedef typename __truth_type<__value>::__type __type; }; // Compare for equality of types. template struct __are_same { enum { __value = 0 }; typedef __false_type __type; }; template struct __are_same<_Tp, _Tp> { enum { __value = 1 }; typedef __true_type __type; }; // Holds if the template-argument is a void type. template struct __is_void { enum { __value = 0 }; typedef __false_type __type; }; template<> struct __is_void { enum { __value = 1 }; typedef __true_type __type; }; // // Integer types // template struct __is_integer { enum { __value = 0 }; typedef __false_type __type; }; // Thirteen specializations (yes there are eleven standard integer // types; long long and unsigned long long are // supported as extensions). Up to four target-specific __int // types are supported as well. template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; # ifdef _GLIBCXX_USE_WCHAR_T template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; # endif #if __cplusplus >= 201103L template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; #endif template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; #define __INT_N(TYPE) \ template<> \ struct __is_integer \ { \ enum { __value = 1 }; \ typedef __true_type __type; \ }; \ template<> \ struct __is_integer \ { \ enum { __value = 1 }; \ typedef __true_type __type; \ }; #ifdef __GLIBCXX_TYPE_INT_N_0 __INT_N(__GLIBCXX_TYPE_INT_N_0) #endif #ifdef __GLIBCXX_TYPE_INT_N_1 __INT_N(__GLIBCXX_TYPE_INT_N_1) #endif #ifdef __GLIBCXX_TYPE_INT_N_2 __INT_N(__GLIBCXX_TYPE_INT_N_2) #endif #ifdef __GLIBCXX_TYPE_INT_N_3 __INT_N(__GLIBCXX_TYPE_INT_N_3) #endif #undef __INT_N // // Floating point types // template struct __is_floating { enum { __value = 0 }; typedef __false_type __type; }; // three specializations (float, double and 'long double') template<> struct __is_floating { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_floating { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_floating { enum { __value = 1 }; typedef __true_type __type; }; // // Pointer types // template struct __is_pointer { enum { __value = 0 }; typedef __false_type __type; }; template struct __is_pointer<_Tp*> { enum { __value = 1 }; typedef __true_type __type; }; // // An arithmetic type is an integer type or a floating point type // template struct __is_arithmetic : public __traitor<__is_integer<_Tp>, __is_floating<_Tp> > { }; // // A scalar type is an arithmetic type or a pointer type // template struct __is_scalar : public __traitor<__is_arithmetic<_Tp>, __is_pointer<_Tp> > { }; // // For use in std::copy and std::find overloads for streambuf iterators. // template struct __is_char { enum { __value = 0 }; typedef __false_type __type; }; template<> struct __is_char { enum { __value = 1 }; typedef __true_type __type; }; #ifdef _GLIBCXX_USE_WCHAR_T template<> struct __is_char { enum { __value = 1 }; typedef __true_type __type; }; #endif template struct __is_byte { enum { __value = 0 }; typedef __false_type __type; }; template<> struct __is_byte { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_byte { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_byte { enum { __value = 1 }; typedef __true_type __type; }; #if __cplusplus >= 201703L enum class byte : unsigned char; template<> struct __is_byte { enum { __value = 1 }; typedef __true_type __type; }; #endif // C++17 // // Move iterator type // template struct __is_move_iterator { enum { __value = 0 }; typedef __false_type __type; }; // Fallback implementation of the function in bits/stl_iterator.h used to // remove the move_iterator wrapper. template inline _Iterator __miter_base(_Iterator __it) { return __it; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace } // extern "C++" #endif //_CPP_TYPE_TRAITS_H PK!X8/bits/cxxabi_forced.hnu[// cxxabi.h subset for cancellation -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of GCC. // // GCC is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3, or (at your option) // any later version. // // GCC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/cxxabi_forced.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{cxxabi.h} */ #ifndef _CXXABI_FORCED_H #define _CXXABI_FORCED_H 1 #pragma GCC system_header #pragma GCC visibility push(default) #ifdef __cplusplus namespace __cxxabiv1 { /** * @brief Thrown as part of forced unwinding. * @ingroup exceptions * * A magic placeholder class that can be caught by reference to * recognize forced unwinding. */ class __forced_unwind { virtual ~__forced_unwind() throw(); // Prevent catch by value. virtual void __pure_dummy() = 0; }; } #endif // __cplusplus #pragma GCC visibility pop #endif // __CXXABI_FORCED_H PK!Pq8/bits/cxxabi_init_exception.hnu[// ABI Support -*- C++ -*- // Copyright (C) 2016-2018 Free Software Foundation, Inc. // // This file is part of GCC. // // GCC is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3, or (at your option) // any later version. // // GCC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/cxxabi_init_exception.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. */ #ifndef _CXXABI_INIT_EXCEPTION_H #define _CXXABI_INIT_EXCEPTION_H 1 #pragma GCC system_header #pragma GCC visibility push(default) #include #include #ifndef _GLIBCXX_CDTOR_CALLABI #define _GLIBCXX_CDTOR_CALLABI #define _GLIBCXX_HAVE_CDTOR_CALLABI 0 #else #define _GLIBCXX_HAVE_CDTOR_CALLABI 1 #endif #ifdef __cplusplus namespace std { class type_info; } namespace __cxxabiv1 { struct __cxa_refcounted_exception; extern "C" { // Allocate memory for the primary exception plus the thrown object. void* __cxa_allocate_exception(size_t) _GLIBCXX_NOTHROW; void __cxa_free_exception(void*) _GLIBCXX_NOTHROW; // Initialize exception (this is a GNU extension) __cxa_refcounted_exception* __cxa_init_primary_exception(void *object, std::type_info *tinfo, void (_GLIBCXX_CDTOR_CALLABI *dest) (void *)) _GLIBCXX_NOTHROW; } } // namespace __cxxabiv1 #endif #pragma GCC visibility pop #endif // _CXXABI_INIT_EXCEPTION_H PK!|EJJ8/bits/deque.tccnu[// Deque implementation (out of line) -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/deque.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{deque} */ #ifndef _DEQUE_TCC #define _DEQUE_TCC 1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER #if __cplusplus >= 201103L template void deque<_Tp, _Alloc>:: _M_default_initialize() { _Map_pointer __cur; __try { for (__cur = this->_M_impl._M_start._M_node; __cur < this->_M_impl._M_finish._M_node; ++__cur) std::__uninitialized_default_a(*__cur, *__cur + _S_buffer_size(), _M_get_Tp_allocator()); std::__uninitialized_default_a(this->_M_impl._M_finish._M_first, this->_M_impl._M_finish._M_cur, _M_get_Tp_allocator()); } __catch(...) { std::_Destroy(this->_M_impl._M_start, iterator(*__cur, __cur), _M_get_Tp_allocator()); __throw_exception_again; } } #endif template deque<_Tp, _Alloc>& deque<_Tp, _Alloc>:: operator=(const deque& __x) { if (&__x != this) { #if __cplusplus >= 201103L if (_Alloc_traits::_S_propagate_on_copy_assign()) { if (!_Alloc_traits::_S_always_equal() && _M_get_Tp_allocator() != __x._M_get_Tp_allocator()) { // Replacement allocator cannot free existing storage, // so deallocate everything and take copy of __x's data. _M_replace_map(__x, __x.get_allocator()); std::__alloc_on_copy(_M_get_Tp_allocator(), __x._M_get_Tp_allocator()); return *this; } std::__alloc_on_copy(_M_get_Tp_allocator(), __x._M_get_Tp_allocator()); } #endif const size_type __len = size(); if (__len >= __x.size()) _M_erase_at_end(std::copy(__x.begin(), __x.end(), this->_M_impl._M_start)); else { const_iterator __mid = __x.begin() + difference_type(__len); std::copy(__x.begin(), __mid, this->_M_impl._M_start); _M_range_insert_aux(this->_M_impl._M_finish, __mid, __x.end(), std::random_access_iterator_tag()); } } return *this; } #if __cplusplus >= 201103L template template #if __cplusplus > 201402L typename deque<_Tp, _Alloc>::reference #else void #endif deque<_Tp, _Alloc>:: emplace_front(_Args&&... __args) { if (this->_M_impl._M_start._M_cur != this->_M_impl._M_start._M_first) { _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_start._M_cur - 1, std::forward<_Args>(__args)...); --this->_M_impl._M_start._M_cur; } else _M_push_front_aux(std::forward<_Args>(__args)...); #if __cplusplus > 201402L return front(); #endif } template template #if __cplusplus > 201402L typename deque<_Tp, _Alloc>::reference #else void #endif deque<_Tp, _Alloc>:: emplace_back(_Args&&... __args) { if (this->_M_impl._M_finish._M_cur != this->_M_impl._M_finish._M_last - 1) { _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish._M_cur, std::forward<_Args>(__args)...); ++this->_M_impl._M_finish._M_cur; } else _M_push_back_aux(std::forward<_Args>(__args)...); #if __cplusplus > 201402L return back(); #endif } #endif #if __cplusplus >= 201103L template template typename deque<_Tp, _Alloc>::iterator deque<_Tp, _Alloc>:: emplace(const_iterator __position, _Args&&... __args) { if (__position._M_cur == this->_M_impl._M_start._M_cur) { emplace_front(std::forward<_Args>(__args)...); return this->_M_impl._M_start; } else if (__position._M_cur == this->_M_impl._M_finish._M_cur) { emplace_back(std::forward<_Args>(__args)...); iterator __tmp = this->_M_impl._M_finish; --__tmp; return __tmp; } else return _M_insert_aux(__position._M_const_cast(), std::forward<_Args>(__args)...); } #endif template typename deque<_Tp, _Alloc>::iterator deque<_Tp, _Alloc>:: #if __cplusplus >= 201103L insert(const_iterator __position, const value_type& __x) #else insert(iterator __position, const value_type& __x) #endif { if (__position._M_cur == this->_M_impl._M_start._M_cur) { push_front(__x); return this->_M_impl._M_start; } else if (__position._M_cur == this->_M_impl._M_finish._M_cur) { push_back(__x); iterator __tmp = this->_M_impl._M_finish; --__tmp; return __tmp; } else return _M_insert_aux(__position._M_const_cast(), __x); } template typename deque<_Tp, _Alloc>::iterator deque<_Tp, _Alloc>:: _M_erase(iterator __position) { iterator __next = __position; ++__next; const difference_type __index = __position - begin(); if (static_cast(__index) < (size() >> 1)) { if (__position != begin()) _GLIBCXX_MOVE_BACKWARD3(begin(), __position, __next); pop_front(); } else { if (__next != end()) _GLIBCXX_MOVE3(__next, end(), __position); pop_back(); } return begin() + __index; } template typename deque<_Tp, _Alloc>::iterator deque<_Tp, _Alloc>:: _M_erase(iterator __first, iterator __last) { if (__first == __last) return __first; else if (__first == begin() && __last == end()) { clear(); return end(); } else { const difference_type __n = __last - __first; const difference_type __elems_before = __first - begin(); if (static_cast(__elems_before) <= (size() - __n) / 2) { if (__first != begin()) _GLIBCXX_MOVE_BACKWARD3(begin(), __first, __last); _M_erase_at_begin(begin() + __n); } else { if (__last != end()) _GLIBCXX_MOVE3(__last, end(), __first); _M_erase_at_end(end() - __n); } return begin() + __elems_before; } } template template void deque<_Tp, _Alloc>:: _M_assign_aux(_InputIterator __first, _InputIterator __last, std::input_iterator_tag) { iterator __cur = begin(); for (; __first != __last && __cur != end(); ++__cur, ++__first) *__cur = *__first; if (__first == __last) _M_erase_at_end(__cur); else _M_range_insert_aux(end(), __first, __last, std::__iterator_category(__first)); } template void deque<_Tp, _Alloc>:: _M_fill_insert(iterator __pos, size_type __n, const value_type& __x) { if (__pos._M_cur == this->_M_impl._M_start._M_cur) { iterator __new_start = _M_reserve_elements_at_front(__n); __try { std::__uninitialized_fill_a(__new_start, this->_M_impl._M_start, __x, _M_get_Tp_allocator()); this->_M_impl._M_start = __new_start; } __catch(...) { _M_destroy_nodes(__new_start._M_node, this->_M_impl._M_start._M_node); __throw_exception_again; } } else if (__pos._M_cur == this->_M_impl._M_finish._M_cur) { iterator __new_finish = _M_reserve_elements_at_back(__n); __try { std::__uninitialized_fill_a(this->_M_impl._M_finish, __new_finish, __x, _M_get_Tp_allocator()); this->_M_impl._M_finish = __new_finish; } __catch(...) { _M_destroy_nodes(this->_M_impl._M_finish._M_node + 1, __new_finish._M_node + 1); __throw_exception_again; } } else _M_insert_aux(__pos, __n, __x); } #if __cplusplus >= 201103L template void deque<_Tp, _Alloc>:: _M_default_append(size_type __n) { if (__n) { iterator __new_finish = _M_reserve_elements_at_back(__n); __try { std::__uninitialized_default_a(this->_M_impl._M_finish, __new_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish = __new_finish; } __catch(...) { _M_destroy_nodes(this->_M_impl._M_finish._M_node + 1, __new_finish._M_node + 1); __throw_exception_again; } } } template bool deque<_Tp, _Alloc>:: _M_shrink_to_fit() { const difference_type __front_capacity = (this->_M_impl._M_start._M_cur - this->_M_impl._M_start._M_first); if (__front_capacity == 0) return false; const difference_type __back_capacity = (this->_M_impl._M_finish._M_last - this->_M_impl._M_finish._M_cur); if (__front_capacity + __back_capacity < _S_buffer_size()) return false; return std::__shrink_to_fit_aux::_S_do_it(*this); } #endif template void deque<_Tp, _Alloc>:: _M_fill_initialize(const value_type& __value) { _Map_pointer __cur; __try { for (__cur = this->_M_impl._M_start._M_node; __cur < this->_M_impl._M_finish._M_node; ++__cur) std::__uninitialized_fill_a(*__cur, *__cur + _S_buffer_size(), __value, _M_get_Tp_allocator()); std::__uninitialized_fill_a(this->_M_impl._M_finish._M_first, this->_M_impl._M_finish._M_cur, __value, _M_get_Tp_allocator()); } __catch(...) { std::_Destroy(this->_M_impl._M_start, iterator(*__cur, __cur), _M_get_Tp_allocator()); __throw_exception_again; } } template template void deque<_Tp, _Alloc>:: _M_range_initialize(_InputIterator __first, _InputIterator __last, std::input_iterator_tag) { this->_M_initialize_map(0); __try { for (; __first != __last; ++__first) #if __cplusplus >= 201103L emplace_back(*__first); #else push_back(*__first); #endif } __catch(...) { clear(); __throw_exception_again; } } template template void deque<_Tp, _Alloc>:: _M_range_initialize(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { const size_type __n = std::distance(__first, __last); this->_M_initialize_map(__n); _Map_pointer __cur_node; __try { for (__cur_node = this->_M_impl._M_start._M_node; __cur_node < this->_M_impl._M_finish._M_node; ++__cur_node) { _ForwardIterator __mid = __first; std::advance(__mid, _S_buffer_size()); std::__uninitialized_copy_a(__first, __mid, *__cur_node, _M_get_Tp_allocator()); __first = __mid; } std::__uninitialized_copy_a(__first, __last, this->_M_impl._M_finish._M_first, _M_get_Tp_allocator()); } __catch(...) { std::_Destroy(this->_M_impl._M_start, iterator(*__cur_node, __cur_node), _M_get_Tp_allocator()); __throw_exception_again; } } // Called only if _M_impl._M_finish._M_cur == _M_impl._M_finish._M_last - 1. template #if __cplusplus >= 201103L template void deque<_Tp, _Alloc>:: _M_push_back_aux(_Args&&... __args) #else void deque<_Tp, _Alloc>:: _M_push_back_aux(const value_type& __t) #endif { _M_reserve_map_at_back(); *(this->_M_impl._M_finish._M_node + 1) = this->_M_allocate_node(); __try { #if __cplusplus >= 201103L _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish._M_cur, std::forward<_Args>(__args)...); #else this->_M_impl.construct(this->_M_impl._M_finish._M_cur, __t); #endif this->_M_impl._M_finish._M_set_node(this->_M_impl._M_finish._M_node + 1); this->_M_impl._M_finish._M_cur = this->_M_impl._M_finish._M_first; } __catch(...) { _M_deallocate_node(*(this->_M_impl._M_finish._M_node + 1)); __throw_exception_again; } } // Called only if _M_impl._M_start._M_cur == _M_impl._M_start._M_first. template #if __cplusplus >= 201103L template void deque<_Tp, _Alloc>:: _M_push_front_aux(_Args&&... __args) #else void deque<_Tp, _Alloc>:: _M_push_front_aux(const value_type& __t) #endif { _M_reserve_map_at_front(); *(this->_M_impl._M_start._M_node - 1) = this->_M_allocate_node(); __try { this->_M_impl._M_start._M_set_node(this->_M_impl._M_start._M_node - 1); this->_M_impl._M_start._M_cur = this->_M_impl._M_start._M_last - 1; #if __cplusplus >= 201103L _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_start._M_cur, std::forward<_Args>(__args)...); #else this->_M_impl.construct(this->_M_impl._M_start._M_cur, __t); #endif } __catch(...) { ++this->_M_impl._M_start; _M_deallocate_node(*(this->_M_impl._M_start._M_node - 1)); __throw_exception_again; } } // Called only if _M_impl._M_finish._M_cur == _M_impl._M_finish._M_first. template void deque<_Tp, _Alloc>:: _M_pop_back_aux() { _M_deallocate_node(this->_M_impl._M_finish._M_first); this->_M_impl._M_finish._M_set_node(this->_M_impl._M_finish._M_node - 1); this->_M_impl._M_finish._M_cur = this->_M_impl._M_finish._M_last - 1; _Alloc_traits::destroy(_M_get_Tp_allocator(), this->_M_impl._M_finish._M_cur); } // Called only if _M_impl._M_start._M_cur == _M_impl._M_start._M_last - 1. // Note that if the deque has at least one element (a precondition for this // member function), and if // _M_impl._M_start._M_cur == _M_impl._M_start._M_last, // then the deque must have at least two nodes. template void deque<_Tp, _Alloc>:: _M_pop_front_aux() { _Alloc_traits::destroy(_M_get_Tp_allocator(), this->_M_impl._M_start._M_cur); _M_deallocate_node(this->_M_impl._M_start._M_first); this->_M_impl._M_start._M_set_node(this->_M_impl._M_start._M_node + 1); this->_M_impl._M_start._M_cur = this->_M_impl._M_start._M_first; } template template void deque<_Tp, _Alloc>:: _M_range_insert_aux(iterator __pos, _InputIterator __first, _InputIterator __last, std::input_iterator_tag) { std::copy(__first, __last, std::inserter(*this, __pos)); } template template void deque<_Tp, _Alloc>:: _M_range_insert_aux(iterator __pos, _ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { const size_type __n = std::distance(__first, __last); if (__pos._M_cur == this->_M_impl._M_start._M_cur) { iterator __new_start = _M_reserve_elements_at_front(__n); __try { std::__uninitialized_copy_a(__first, __last, __new_start, _M_get_Tp_allocator()); this->_M_impl._M_start = __new_start; } __catch(...) { _M_destroy_nodes(__new_start._M_node, this->_M_impl._M_start._M_node); __throw_exception_again; } } else if (__pos._M_cur == this->_M_impl._M_finish._M_cur) { iterator __new_finish = _M_reserve_elements_at_back(__n); __try { std::__uninitialized_copy_a(__first, __last, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish = __new_finish; } __catch(...) { _M_destroy_nodes(this->_M_impl._M_finish._M_node + 1, __new_finish._M_node + 1); __throw_exception_again; } } else _M_insert_aux(__pos, __first, __last, __n); } template #if __cplusplus >= 201103L template typename deque<_Tp, _Alloc>::iterator deque<_Tp, _Alloc>:: _M_insert_aux(iterator __pos, _Args&&... __args) { value_type __x_copy(std::forward<_Args>(__args)...); // XXX copy #else typename deque<_Tp, _Alloc>::iterator deque<_Tp, _Alloc>:: _M_insert_aux(iterator __pos, const value_type& __x) { value_type __x_copy = __x; // XXX copy #endif difference_type __index = __pos - this->_M_impl._M_start; if (static_cast(__index) < size() / 2) { push_front(_GLIBCXX_MOVE(front())); iterator __front1 = this->_M_impl._M_start; ++__front1; iterator __front2 = __front1; ++__front2; __pos = this->_M_impl._M_start + __index; iterator __pos1 = __pos; ++__pos1; _GLIBCXX_MOVE3(__front2, __pos1, __front1); } else { push_back(_GLIBCXX_MOVE(back())); iterator __back1 = this->_M_impl._M_finish; --__back1; iterator __back2 = __back1; --__back2; __pos = this->_M_impl._M_start + __index; _GLIBCXX_MOVE_BACKWARD3(__pos, __back2, __back1); } *__pos = _GLIBCXX_MOVE(__x_copy); return __pos; } template void deque<_Tp, _Alloc>:: _M_insert_aux(iterator __pos, size_type __n, const value_type& __x) { const difference_type __elems_before = __pos - this->_M_impl._M_start; const size_type __length = this->size(); value_type __x_copy = __x; if (__elems_before < difference_type(__length / 2)) { iterator __new_start = _M_reserve_elements_at_front(__n); iterator __old_start = this->_M_impl._M_start; __pos = this->_M_impl._M_start + __elems_before; __try { if (__elems_before >= difference_type(__n)) { iterator __start_n = (this->_M_impl._M_start + difference_type(__n)); std::__uninitialized_move_a(this->_M_impl._M_start, __start_n, __new_start, _M_get_Tp_allocator()); this->_M_impl._M_start = __new_start; _GLIBCXX_MOVE3(__start_n, __pos, __old_start); std::fill(__pos - difference_type(__n), __pos, __x_copy); } else { std::__uninitialized_move_fill(this->_M_impl._M_start, __pos, __new_start, this->_M_impl._M_start, __x_copy, _M_get_Tp_allocator()); this->_M_impl._M_start = __new_start; std::fill(__old_start, __pos, __x_copy); } } __catch(...) { _M_destroy_nodes(__new_start._M_node, this->_M_impl._M_start._M_node); __throw_exception_again; } } else { iterator __new_finish = _M_reserve_elements_at_back(__n); iterator __old_finish = this->_M_impl._M_finish; const difference_type __elems_after = difference_type(__length) - __elems_before; __pos = this->_M_impl._M_finish - __elems_after; __try { if (__elems_after > difference_type(__n)) { iterator __finish_n = (this->_M_impl._M_finish - difference_type(__n)); std::__uninitialized_move_a(__finish_n, this->_M_impl._M_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish = __new_finish; _GLIBCXX_MOVE_BACKWARD3(__pos, __finish_n, __old_finish); std::fill(__pos, __pos + difference_type(__n), __x_copy); } else { std::__uninitialized_fill_move(this->_M_impl._M_finish, __pos + difference_type(__n), __x_copy, __pos, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish = __new_finish; std::fill(__pos, __old_finish, __x_copy); } } __catch(...) { _M_destroy_nodes(this->_M_impl._M_finish._M_node + 1, __new_finish._M_node + 1); __throw_exception_again; } } } template template void deque<_Tp, _Alloc>:: _M_insert_aux(iterator __pos, _ForwardIterator __first, _ForwardIterator __last, size_type __n) { const difference_type __elemsbefore = __pos - this->_M_impl._M_start; const size_type __length = size(); if (static_cast(__elemsbefore) < __length / 2) { iterator __new_start = _M_reserve_elements_at_front(__n); iterator __old_start = this->_M_impl._M_start; __pos = this->_M_impl._M_start + __elemsbefore; __try { if (__elemsbefore >= difference_type(__n)) { iterator __start_n = (this->_M_impl._M_start + difference_type(__n)); std::__uninitialized_move_a(this->_M_impl._M_start, __start_n, __new_start, _M_get_Tp_allocator()); this->_M_impl._M_start = __new_start; _GLIBCXX_MOVE3(__start_n, __pos, __old_start); std::copy(__first, __last, __pos - difference_type(__n)); } else { _ForwardIterator __mid = __first; std::advance(__mid, difference_type(__n) - __elemsbefore); std::__uninitialized_move_copy(this->_M_impl._M_start, __pos, __first, __mid, __new_start, _M_get_Tp_allocator()); this->_M_impl._M_start = __new_start; std::copy(__mid, __last, __old_start); } } __catch(...) { _M_destroy_nodes(__new_start._M_node, this->_M_impl._M_start._M_node); __throw_exception_again; } } else { iterator __new_finish = _M_reserve_elements_at_back(__n); iterator __old_finish = this->_M_impl._M_finish; const difference_type __elemsafter = difference_type(__length) - __elemsbefore; __pos = this->_M_impl._M_finish - __elemsafter; __try { if (__elemsafter > difference_type(__n)) { iterator __finish_n = (this->_M_impl._M_finish - difference_type(__n)); std::__uninitialized_move_a(__finish_n, this->_M_impl._M_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish = __new_finish; _GLIBCXX_MOVE_BACKWARD3(__pos, __finish_n, __old_finish); std::copy(__first, __last, __pos); } else { _ForwardIterator __mid = __first; std::advance(__mid, __elemsafter); std::__uninitialized_copy_move(__mid, __last, __pos, this->_M_impl._M_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish = __new_finish; std::copy(__first, __mid, __pos); } } __catch(...) { _M_destroy_nodes(this->_M_impl._M_finish._M_node + 1, __new_finish._M_node + 1); __throw_exception_again; } } } template void deque<_Tp, _Alloc>:: _M_destroy_data_aux(iterator __first, iterator __last) { for (_Map_pointer __node = __first._M_node + 1; __node < __last._M_node; ++__node) std::_Destroy(*__node, *__node + _S_buffer_size(), _M_get_Tp_allocator()); if (__first._M_node != __last._M_node) { std::_Destroy(__first._M_cur, __first._M_last, _M_get_Tp_allocator()); std::_Destroy(__last._M_first, __last._M_cur, _M_get_Tp_allocator()); } else std::_Destroy(__first._M_cur, __last._M_cur, _M_get_Tp_allocator()); } template void deque<_Tp, _Alloc>:: _M_new_elements_at_front(size_type __new_elems) { if (this->max_size() - this->size() < __new_elems) __throw_length_error(__N("deque::_M_new_elements_at_front")); const size_type __new_nodes = ((__new_elems + _S_buffer_size() - 1) / _S_buffer_size()); _M_reserve_map_at_front(__new_nodes); size_type __i; __try { for (__i = 1; __i <= __new_nodes; ++__i) *(this->_M_impl._M_start._M_node - __i) = this->_M_allocate_node(); } __catch(...) { for (size_type __j = 1; __j < __i; ++__j) _M_deallocate_node(*(this->_M_impl._M_start._M_node - __j)); __throw_exception_again; } } template void deque<_Tp, _Alloc>:: _M_new_elements_at_back(size_type __new_elems) { if (this->max_size() - this->size() < __new_elems) __throw_length_error(__N("deque::_M_new_elements_at_back")); const size_type __new_nodes = ((__new_elems + _S_buffer_size() - 1) / _S_buffer_size()); _M_reserve_map_at_back(__new_nodes); size_type __i; __try { for (__i = 1; __i <= __new_nodes; ++__i) *(this->_M_impl._M_finish._M_node + __i) = this->_M_allocate_node(); } __catch(...) { for (size_type __j = 1; __j < __i; ++__j) _M_deallocate_node(*(this->_M_impl._M_finish._M_node + __j)); __throw_exception_again; } } template void deque<_Tp, _Alloc>:: _M_reallocate_map(size_type __nodes_to_add, bool __add_at_front) { const size_type __old_num_nodes = this->_M_impl._M_finish._M_node - this->_M_impl._M_start._M_node + 1; const size_type __new_num_nodes = __old_num_nodes + __nodes_to_add; _Map_pointer __new_nstart; if (this->_M_impl._M_map_size > 2 * __new_num_nodes) { __new_nstart = this->_M_impl._M_map + (this->_M_impl._M_map_size - __new_num_nodes) / 2 + (__add_at_front ? __nodes_to_add : 0); if (__new_nstart < this->_M_impl._M_start._M_node) std::copy(this->_M_impl._M_start._M_node, this->_M_impl._M_finish._M_node + 1, __new_nstart); else std::copy_backward(this->_M_impl._M_start._M_node, this->_M_impl._M_finish._M_node + 1, __new_nstart + __old_num_nodes); } else { size_type __new_map_size = this->_M_impl._M_map_size + std::max(this->_M_impl._M_map_size, __nodes_to_add) + 2; _Map_pointer __new_map = this->_M_allocate_map(__new_map_size); __new_nstart = __new_map + (__new_map_size - __new_num_nodes) / 2 + (__add_at_front ? __nodes_to_add : 0); std::copy(this->_M_impl._M_start._M_node, this->_M_impl._M_finish._M_node + 1, __new_nstart); _M_deallocate_map(this->_M_impl._M_map, this->_M_impl._M_map_size); this->_M_impl._M_map = __new_map; this->_M_impl._M_map_size = __new_map_size; } this->_M_impl._M_start._M_set_node(__new_nstart); this->_M_impl._M_finish._M_set_node(__new_nstart + __old_num_nodes - 1); } // Overload for deque::iterators, exploiting the "segmented-iterator // optimization". template void fill(const _Deque_iterator<_Tp, _Tp&, _Tp*>& __first, const _Deque_iterator<_Tp, _Tp&, _Tp*>& __last, const _Tp& __value) { typedef typename _Deque_iterator<_Tp, _Tp&, _Tp*>::_Self _Self; for (typename _Self::_Map_pointer __node = __first._M_node + 1; __node < __last._M_node; ++__node) std::fill(*__node, *__node + _Self::_S_buffer_size(), __value); if (__first._M_node != __last._M_node) { std::fill(__first._M_cur, __first._M_last, __value); std::fill(__last._M_first, __last._M_cur, __value); } else std::fill(__first._M_cur, __last._M_cur, __value); } template _Deque_iterator<_Tp, _Tp&, _Tp*> copy(_Deque_iterator<_Tp, const _Tp&, const _Tp*> __first, _Deque_iterator<_Tp, const _Tp&, const _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { typedef typename _Deque_iterator<_Tp, _Tp&, _Tp*>::_Self _Self; typedef typename _Self::difference_type difference_type; difference_type __len = __last - __first; while (__len > 0) { const difference_type __clen = std::min(__len, std::min(__first._M_last - __first._M_cur, __result._M_last - __result._M_cur)); std::copy(__first._M_cur, __first._M_cur + __clen, __result._M_cur); __first += __clen; __result += __clen; __len -= __clen; } return __result; } template _Deque_iterator<_Tp, _Tp&, _Tp*> copy_backward(_Deque_iterator<_Tp, const _Tp&, const _Tp*> __first, _Deque_iterator<_Tp, const _Tp&, const _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { typedef typename _Deque_iterator<_Tp, _Tp&, _Tp*>::_Self _Self; typedef typename _Self::difference_type difference_type; difference_type __len = __last - __first; while (__len > 0) { difference_type __llen = __last._M_cur - __last._M_first; _Tp* __lend = __last._M_cur; difference_type __rlen = __result._M_cur - __result._M_first; _Tp* __rend = __result._M_cur; if (!__llen) { __llen = _Self::_S_buffer_size(); __lend = *(__last._M_node - 1) + __llen; } if (!__rlen) { __rlen = _Self::_S_buffer_size(); __rend = *(__result._M_node - 1) + __rlen; } const difference_type __clen = std::min(__len, std::min(__llen, __rlen)); std::copy_backward(__lend - __clen, __lend, __rend); __last -= __clen; __result -= __clen; __len -= __clen; } return __result; } #if __cplusplus >= 201103L template _Deque_iterator<_Tp, _Tp&, _Tp*> move(_Deque_iterator<_Tp, const _Tp&, const _Tp*> __first, _Deque_iterator<_Tp, const _Tp&, const _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { typedef typename _Deque_iterator<_Tp, _Tp&, _Tp*>::_Self _Self; typedef typename _Self::difference_type difference_type; difference_type __len = __last - __first; while (__len > 0) { const difference_type __clen = std::min(__len, std::min(__first._M_last - __first._M_cur, __result._M_last - __result._M_cur)); std::move(__first._M_cur, __first._M_cur + __clen, __result._M_cur); __first += __clen; __result += __clen; __len -= __clen; } return __result; } template _Deque_iterator<_Tp, _Tp&, _Tp*> move_backward(_Deque_iterator<_Tp, const _Tp&, const _Tp*> __first, _Deque_iterator<_Tp, const _Tp&, const _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { typedef typename _Deque_iterator<_Tp, _Tp&, _Tp*>::_Self _Self; typedef typename _Self::difference_type difference_type; difference_type __len = __last - __first; while (__len > 0) { difference_type __llen = __last._M_cur - __last._M_first; _Tp* __lend = __last._M_cur; difference_type __rlen = __result._M_cur - __result._M_first; _Tp* __rend = __result._M_cur; if (!__llen) { __llen = _Self::_S_buffer_size(); __lend = *(__last._M_node - 1) + __llen; } if (!__rlen) { __rlen = _Self::_S_buffer_size(); __rend = *(__result._M_node - 1) + __rlen; } const difference_type __clen = std::min(__len, std::min(__llen, __rlen)); std::move_backward(__lend - __clen, __lend, __rend); __last -= __clen; __result -= __clen; __len -= __clen; } return __result; } #endif _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!FMPc0c08/bits/enable_special_members.hnu[// -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/enable_special_members.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. */ #ifndef _ENABLE_SPECIAL_MEMBERS_H #define _ENABLE_SPECIAL_MEMBERS_H 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION struct _Enable_default_constructor_tag { explicit constexpr _Enable_default_constructor_tag() = default; }; /** * @brief A mixin helper to conditionally enable or disable the default * constructor. * @sa _Enable_special_members */ template struct _Enable_default_constructor { constexpr _Enable_default_constructor() noexcept = default; constexpr _Enable_default_constructor(_Enable_default_constructor const&) noexcept = default; constexpr _Enable_default_constructor(_Enable_default_constructor&&) noexcept = default; _Enable_default_constructor& operator=(_Enable_default_constructor const&) noexcept = default; _Enable_default_constructor& operator=(_Enable_default_constructor&&) noexcept = default; // Can be used in other ctors. constexpr explicit _Enable_default_constructor(_Enable_default_constructor_tag) { } }; /** * @brief A mixin helper to conditionally enable or disable the default * destructor. * @sa _Enable_special_members */ template struct _Enable_destructor { }; /** * @brief A mixin helper to conditionally enable or disable the copy/move * special members. * @sa _Enable_special_members */ template struct _Enable_copy_move { }; /** * @brief A mixin helper to conditionally enable or disable the special * members. * * The @c _Tag type parameter is to make mixin bases unique and thus avoid * ambiguities. */ template struct _Enable_special_members : private _Enable_default_constructor<_Default, _Tag>, private _Enable_destructor<_Destructor, _Tag>, private _Enable_copy_move<_Copy, _CopyAssignment, _Move, _MoveAssignment, _Tag> { }; // Boilerplate follows. template struct _Enable_default_constructor { constexpr _Enable_default_constructor() noexcept = delete; constexpr _Enable_default_constructor(_Enable_default_constructor const&) noexcept = default; constexpr _Enable_default_constructor(_Enable_default_constructor&&) noexcept = default; _Enable_default_constructor& operator=(_Enable_default_constructor const&) noexcept = default; _Enable_default_constructor& operator=(_Enable_default_constructor&&) noexcept = default; // Can be used in other ctors. constexpr explicit _Enable_default_constructor(_Enable_default_constructor_tag) { } }; template struct _Enable_destructor { ~_Enable_destructor() noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = default; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = default; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = default; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = default; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = default; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = default; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = default; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _ENABLE_SPECIAL_MEMBERS_H PK!@ 8/bits/exception.hnu[// Exception Handling support header for -*- C++ -*- // Copyright (C) 2016-2018 Free Software Foundation, Inc. // // This file is part of GCC. // // GCC is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3, or (at your option) // any later version. // // GCC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/exception.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. */ #ifndef __EXCEPTION_H #define __EXCEPTION_H 1 #pragma GCC system_header #pragma GCC visibility push(default) #include extern "C++" { namespace std { /** * @defgroup exceptions Exceptions * @ingroup diagnostics * * Classes and functions for reporting errors via exception classes. * @{ */ /** * @brief Base class for all library exceptions. * * This is the base class for all exceptions thrown by the standard * library, and by certain language expressions. You are free to derive * your own %exception classes, or use a different hierarchy, or to * throw non-class data (e.g., fundamental types). */ class exception { public: exception() _GLIBCXX_USE_NOEXCEPT { } virtual ~exception() _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT; /** Returns a C-style character string describing the general cause * of the current error. */ virtual const char* what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT; }; } // namespace std } #pragma GCC visibility pop #endif PK! _mm8/bits/exception_defines.hnu[// -fno-exceptions Support -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/exception_defines.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{exception} */ #ifndef _EXCEPTION_DEFINES_H #define _EXCEPTION_DEFINES_H 1 #if ! __cpp_exceptions // Iff -fno-exceptions, transform error handling code to work without it. # define __try if (true) # define __catch(X) if (false) # define __throw_exception_again #else // Else proceed normally. # define __try try # define __catch(X) catch(X) # define __throw_exception_again throw #endif #endif PK!yGw]]8/bits/exception_ptr.hnu[// Exception Handling support header (exception_ptr class) for -*- C++ -*- // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of GCC. // // GCC is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3, or (at your option) // any later version. // // GCC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/exception_ptr.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{exception} */ #ifndef _EXCEPTION_PTR_H #define _EXCEPTION_PTR_H #pragma GCC visibility push(default) #include #include #include #include #include extern "C++" { namespace std { class type_info; /** * @addtogroup exceptions * @{ */ namespace __exception_ptr { class exception_ptr; } using __exception_ptr::exception_ptr; /** Obtain an exception_ptr to the currently handled exception. If there * is none, or the currently handled exception is foreign, return the null * value. */ exception_ptr current_exception() _GLIBCXX_USE_NOEXCEPT; template exception_ptr make_exception_ptr(_Ex) _GLIBCXX_USE_NOEXCEPT; /// Throw the object pointed to by the exception_ptr. void rethrow_exception(exception_ptr) __attribute__ ((__noreturn__)); namespace __exception_ptr { using std::rethrow_exception; /** * @brief An opaque pointer to an arbitrary exception. * @ingroup exceptions */ class exception_ptr { void* _M_exception_object; explicit exception_ptr(void* __e) _GLIBCXX_USE_NOEXCEPT; void _M_addref() _GLIBCXX_USE_NOEXCEPT; void _M_release() _GLIBCXX_USE_NOEXCEPT; void *_M_get() const _GLIBCXX_NOEXCEPT __attribute__ ((__pure__)); friend exception_ptr std::current_exception() _GLIBCXX_USE_NOEXCEPT; friend void std::rethrow_exception(exception_ptr); template friend exception_ptr std::make_exception_ptr(_Ex) _GLIBCXX_USE_NOEXCEPT; public: exception_ptr() _GLIBCXX_USE_NOEXCEPT; exception_ptr(const exception_ptr&) _GLIBCXX_USE_NOEXCEPT; #if __cplusplus >= 201103L exception_ptr(nullptr_t) noexcept : _M_exception_object(0) { } exception_ptr(exception_ptr&& __o) noexcept : _M_exception_object(__o._M_exception_object) { __o._M_exception_object = 0; } #endif #if (__cplusplus < 201103L) || defined (_GLIBCXX_EH_PTR_COMPAT) typedef void (exception_ptr::*__safe_bool)(); // For construction from nullptr or 0. exception_ptr(__safe_bool) _GLIBCXX_USE_NOEXCEPT; #endif exception_ptr& operator=(const exception_ptr&) _GLIBCXX_USE_NOEXCEPT; #if __cplusplus >= 201103L exception_ptr& operator=(exception_ptr&& __o) noexcept { exception_ptr(static_cast(__o)).swap(*this); return *this; } #endif ~exception_ptr() _GLIBCXX_USE_NOEXCEPT; void swap(exception_ptr&) _GLIBCXX_USE_NOEXCEPT; #ifdef _GLIBCXX_EH_PTR_COMPAT // Retained for compatibility with CXXABI_1.3. void _M_safe_bool_dummy() _GLIBCXX_USE_NOEXCEPT __attribute__ ((__const__)); bool operator!() const _GLIBCXX_USE_NOEXCEPT __attribute__ ((__pure__)); operator __safe_bool() const _GLIBCXX_USE_NOEXCEPT; #endif #if __cplusplus >= 201103L explicit operator bool() const { return _M_exception_object; } #endif friend bool operator==(const exception_ptr&, const exception_ptr&) _GLIBCXX_USE_NOEXCEPT __attribute__ ((__pure__)); const class std::type_info* __cxa_exception_type() const _GLIBCXX_USE_NOEXCEPT __attribute__ ((__pure__)); }; bool operator==(const exception_ptr&, const exception_ptr&) _GLIBCXX_USE_NOEXCEPT __attribute__ ((__pure__)); bool operator!=(const exception_ptr&, const exception_ptr&) _GLIBCXX_USE_NOEXCEPT __attribute__ ((__pure__)); inline void swap(exception_ptr& __lhs, exception_ptr& __rhs) { __lhs.swap(__rhs); } template inline void __dest_thunk(void* __x) { static_cast<_Ex*>(__x)->~_Ex(); } } // namespace __exception_ptr /// Obtain an exception_ptr pointing to a copy of the supplied object. template exception_ptr make_exception_ptr(_Ex __ex) _GLIBCXX_USE_NOEXCEPT { #if __cpp_exceptions && __cpp_rtti && !_GLIBCXX_HAVE_CDTOR_CALLABI void* __e = __cxxabiv1::__cxa_allocate_exception(sizeof(_Ex)); (void) __cxxabiv1::__cxa_init_primary_exception( __e, const_cast(&typeid(__ex)), __exception_ptr::__dest_thunk<_Ex>); try { ::new (__e) _Ex(__ex); return exception_ptr(__e); } catch(...) { __cxxabiv1::__cxa_free_exception(__e); return current_exception(); } #elif __cpp_exceptions try { throw __ex; } catch(...) { return current_exception(); } #else // no RTTI and no exceptions return exception_ptr(); #endif } // @} group exceptions } // namespace std } // extern "C++" #pragma GCC visibility pop #endif PK!pg8/bits/forward_list.hnu[// -*- C++ -*- // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/forward_list.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{forward_list} */ #ifndef _FORWARD_LIST_H #define _FORWARD_LIST_H 1 #pragma GCC system_header #include #include #include #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER /** * @brief A helper basic node class for %forward_list. * This is just a linked list with nothing inside it. * There are purely list shuffling utility methods here. */ struct _Fwd_list_node_base { _Fwd_list_node_base() = default; _Fwd_list_node_base(_Fwd_list_node_base&& __x) noexcept : _M_next(__x._M_next) { __x._M_next = nullptr; } _Fwd_list_node_base(const _Fwd_list_node_base&) = delete; _Fwd_list_node_base& operator=(const _Fwd_list_node_base&) = delete; _Fwd_list_node_base& operator=(_Fwd_list_node_base&& __x) noexcept { _M_next = __x._M_next; __x._M_next = nullptr; return *this; } _Fwd_list_node_base* _M_next = nullptr; _Fwd_list_node_base* _M_transfer_after(_Fwd_list_node_base* __begin, _Fwd_list_node_base* __end) noexcept { _Fwd_list_node_base* __keep = __begin->_M_next; if (__end) { __begin->_M_next = __end->_M_next; __end->_M_next = _M_next; } else __begin->_M_next = nullptr; _M_next = __keep; return __end; } void _M_reverse_after() noexcept { _Fwd_list_node_base* __tail = _M_next; if (!__tail) return; while (_Fwd_list_node_base* __temp = __tail->_M_next) { _Fwd_list_node_base* __keep = _M_next; _M_next = __temp; __tail->_M_next = __temp->_M_next; _M_next->_M_next = __keep; } } }; /** * @brief A helper node class for %forward_list. * This is just a linked list with uninitialized storage for a * data value in each node. * There is a sorting utility method. */ template struct _Fwd_list_node : public _Fwd_list_node_base { _Fwd_list_node() = default; __gnu_cxx::__aligned_buffer<_Tp> _M_storage; _Tp* _M_valptr() noexcept { return _M_storage._M_ptr(); } const _Tp* _M_valptr() const noexcept { return _M_storage._M_ptr(); } }; /** * @brief A forward_list::iterator. * * All the functions are op overloads. */ template struct _Fwd_list_iterator { typedef _Fwd_list_iterator<_Tp> _Self; typedef _Fwd_list_node<_Tp> _Node; typedef _Tp value_type; typedef _Tp* pointer; typedef _Tp& reference; typedef ptrdiff_t difference_type; typedef std::forward_iterator_tag iterator_category; _Fwd_list_iterator() noexcept : _M_node() { } explicit _Fwd_list_iterator(_Fwd_list_node_base* __n) noexcept : _M_node(__n) { } reference operator*() const noexcept { return *static_cast<_Node*>(this->_M_node)->_M_valptr(); } pointer operator->() const noexcept { return static_cast<_Node*>(this->_M_node)->_M_valptr(); } _Self& operator++() noexcept { _M_node = _M_node->_M_next; return *this; } _Self operator++(int) noexcept { _Self __tmp(*this); _M_node = _M_node->_M_next; return __tmp; } bool operator==(const _Self& __x) const noexcept { return _M_node == __x._M_node; } bool operator!=(const _Self& __x) const noexcept { return _M_node != __x._M_node; } _Self _M_next() const noexcept { if (_M_node) return _Fwd_list_iterator(_M_node->_M_next); else return _Fwd_list_iterator(nullptr); } _Fwd_list_node_base* _M_node; }; /** * @brief A forward_list::const_iterator. * * All the functions are op overloads. */ template struct _Fwd_list_const_iterator { typedef _Fwd_list_const_iterator<_Tp> _Self; typedef const _Fwd_list_node<_Tp> _Node; typedef _Fwd_list_iterator<_Tp> iterator; typedef _Tp value_type; typedef const _Tp* pointer; typedef const _Tp& reference; typedef ptrdiff_t difference_type; typedef std::forward_iterator_tag iterator_category; _Fwd_list_const_iterator() noexcept : _M_node() { } explicit _Fwd_list_const_iterator(const _Fwd_list_node_base* __n) noexcept : _M_node(__n) { } _Fwd_list_const_iterator(const iterator& __iter) noexcept : _M_node(__iter._M_node) { } reference operator*() const noexcept { return *static_cast<_Node*>(this->_M_node)->_M_valptr(); } pointer operator->() const noexcept { return static_cast<_Node*>(this->_M_node)->_M_valptr(); } _Self& operator++() noexcept { _M_node = _M_node->_M_next; return *this; } _Self operator++(int) noexcept { _Self __tmp(*this); _M_node = _M_node->_M_next; return __tmp; } bool operator==(const _Self& __x) const noexcept { return _M_node == __x._M_node; } bool operator!=(const _Self& __x) const noexcept { return _M_node != __x._M_node; } _Self _M_next() const noexcept { if (this->_M_node) return _Fwd_list_const_iterator(_M_node->_M_next); else return _Fwd_list_const_iterator(nullptr); } const _Fwd_list_node_base* _M_node; }; /** * @brief Forward list iterator equality comparison. */ template inline bool operator==(const _Fwd_list_iterator<_Tp>& __x, const _Fwd_list_const_iterator<_Tp>& __y) noexcept { return __x._M_node == __y._M_node; } /** * @brief Forward list iterator inequality comparison. */ template inline bool operator!=(const _Fwd_list_iterator<_Tp>& __x, const _Fwd_list_const_iterator<_Tp>& __y) noexcept { return __x._M_node != __y._M_node; } /** * @brief Base class for %forward_list. */ template struct _Fwd_list_base { protected: typedef __alloc_rebind<_Alloc, _Fwd_list_node<_Tp>> _Node_alloc_type; typedef __gnu_cxx::__alloc_traits<_Node_alloc_type> _Node_alloc_traits; struct _Fwd_list_impl : public _Node_alloc_type { _Fwd_list_node_base _M_head; _Fwd_list_impl() noexcept(is_nothrow_default_constructible<_Node_alloc_type>::value) : _Node_alloc_type(), _M_head() { } _Fwd_list_impl(_Fwd_list_impl&&) = default; _Fwd_list_impl(_Fwd_list_impl&& __fl, _Node_alloc_type&& __a) : _Node_alloc_type(std::move(__a)), _M_head(std::move(__fl._M_head)) { } _Fwd_list_impl(_Node_alloc_type&& __a) : _Node_alloc_type(std::move(__a)), _M_head() { } }; _Fwd_list_impl _M_impl; public: typedef _Fwd_list_iterator<_Tp> iterator; typedef _Fwd_list_const_iterator<_Tp> const_iterator; typedef _Fwd_list_node<_Tp> _Node; _Node_alloc_type& _M_get_Node_allocator() noexcept { return this->_M_impl; } const _Node_alloc_type& _M_get_Node_allocator() const noexcept { return this->_M_impl; } _Fwd_list_base() = default; _Fwd_list_base(_Node_alloc_type&& __a) : _M_impl(std::move(__a)) { } // When allocators are always equal. _Fwd_list_base(_Fwd_list_base&& __lst, _Node_alloc_type&& __a, std::true_type) : _M_impl(std::move(__lst._M_impl), std::move(__a)) { } // When allocators are not always equal. _Fwd_list_base(_Fwd_list_base&& __lst, _Node_alloc_type&& __a); _Fwd_list_base(_Fwd_list_base&&) = default; ~_Fwd_list_base() { _M_erase_after(&_M_impl._M_head, nullptr); } protected: _Node* _M_get_node() { auto __ptr = _Node_alloc_traits::allocate(_M_get_Node_allocator(), 1); return std::__to_address(__ptr); } template _Node* _M_create_node(_Args&&... __args) { _Node* __node = this->_M_get_node(); __try { ::new ((void*)__node) _Node; _Node_alloc_traits::construct(_M_get_Node_allocator(), __node->_M_valptr(), std::forward<_Args>(__args)...); } __catch(...) { this->_M_put_node(__node); __throw_exception_again; } return __node; } template _Fwd_list_node_base* _M_insert_after(const_iterator __pos, _Args&&... __args); void _M_put_node(_Node* __p) { typedef typename _Node_alloc_traits::pointer _Ptr; auto __ptr = std::pointer_traits<_Ptr>::pointer_to(*__p); _Node_alloc_traits::deallocate(_M_get_Node_allocator(), __ptr, 1); } _Fwd_list_node_base* _M_erase_after(_Fwd_list_node_base* __pos); _Fwd_list_node_base* _M_erase_after(_Fwd_list_node_base* __pos, _Fwd_list_node_base* __last); }; /** * @brief A standard container with linear time access to elements, * and fixed time insertion/deletion at any point in the sequence. * * @ingroup sequences * * @tparam _Tp Type of element. * @tparam _Alloc Allocator type, defaults to allocator<_Tp>. * * Meets the requirements of a container, a * sequence, including the * optional sequence requirements with the * %exception of @c at and @c operator[]. * * This is a @e singly @e linked %list. Traversal up the * %list requires linear time, but adding and removing elements (or * @e nodes) is done in constant time, regardless of where the * change takes place. Unlike std::vector and std::deque, * random-access iterators are not provided, so subscripting ( @c * [] ) access is not allowed. For algorithms which only need * sequential access, this lack makes no difference. * * Also unlike the other standard containers, std::forward_list provides * specialized algorithms %unique to linked lists, such as * splicing, sorting, and in-place reversal. */ template> class forward_list : private _Fwd_list_base<_Tp, _Alloc> { static_assert(is_same::type, _Tp>::value, "std::forward_list must have a non-const, non-volatile value_type"); #ifdef __STRICT_ANSI__ static_assert(is_same::value, "std::forward_list must have the same value_type as its allocator"); #endif private: typedef _Fwd_list_base<_Tp, _Alloc> _Base; typedef _Fwd_list_node<_Tp> _Node; typedef _Fwd_list_node_base _Node_base; typedef typename _Base::_Node_alloc_type _Node_alloc_type; typedef typename _Base::_Node_alloc_traits _Node_alloc_traits; typedef allocator_traits<__alloc_rebind<_Alloc, _Tp>> _Alloc_traits; public: // types: typedef _Tp value_type; typedef typename _Alloc_traits::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef _Fwd_list_iterator<_Tp> iterator; typedef _Fwd_list_const_iterator<_Tp> const_iterator; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef _Alloc allocator_type; // 23.3.4.2 construct/copy/destroy: /** * @brief Creates a %forward_list with no elements. */ forward_list() = default; /** * @brief Creates a %forward_list with no elements. * @param __al An allocator object. */ explicit forward_list(const _Alloc& __al) noexcept : _Base(_Node_alloc_type(__al)) { } /** * @brief Copy constructor with allocator argument. * @param __list Input list to copy. * @param __al An allocator object. */ forward_list(const forward_list& __list, const _Alloc& __al) : _Base(_Node_alloc_type(__al)) { _M_range_initialize(__list.begin(), __list.end()); } private: forward_list(forward_list&& __list, _Node_alloc_type&& __al, false_type) : _Base(std::move(__list), std::move(__al)) { // If __list is not empty it means its allocator is not equal to __a, // so we need to move from each element individually. insert_after(cbefore_begin(), std::__make_move_if_noexcept_iterator(__list.begin()), std::__make_move_if_noexcept_iterator(__list.end())); } forward_list(forward_list&& __list, _Node_alloc_type&& __al, true_type) noexcept : _Base(std::move(__list), _Node_alloc_type(__al), true_type{}) { } public: /** * @brief Move constructor with allocator argument. * @param __list Input list to move. * @param __al An allocator object. */ forward_list(forward_list&& __list, const _Alloc& __al) noexcept(_Node_alloc_traits::_S_always_equal()) : forward_list(std::move(__list), _Node_alloc_type(__al), typename _Node_alloc_traits::is_always_equal{}) { } /** * @brief Creates a %forward_list with default constructed elements. * @param __n The number of elements to initially create. * @param __al An allocator object. * * This constructor creates the %forward_list with @a __n default * constructed elements. */ explicit forward_list(size_type __n, const _Alloc& __al = _Alloc()) : _Base(_Node_alloc_type(__al)) { _M_default_initialize(__n); } /** * @brief Creates a %forward_list with copies of an exemplar element. * @param __n The number of elements to initially create. * @param __value An element to copy. * @param __al An allocator object. * * This constructor fills the %forward_list with @a __n copies of * @a __value. */ forward_list(size_type __n, const _Tp& __value, const _Alloc& __al = _Alloc()) : _Base(_Node_alloc_type(__al)) { _M_fill_initialize(__n, __value); } /** * @brief Builds a %forward_list from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __al An allocator object. * * Create a %forward_list consisting of copies of the elements from * [@a __first,@a __last). This is linear in N (where N is * distance(@a __first,@a __last)). */ template> forward_list(_InputIterator __first, _InputIterator __last, const _Alloc& __al = _Alloc()) : _Base(_Node_alloc_type(__al)) { _M_range_initialize(__first, __last); } /** * @brief The %forward_list copy constructor. * @param __list A %forward_list of identical element and allocator * types. */ forward_list(const forward_list& __list) : _Base(_Node_alloc_traits::_S_select_on_copy( __list._M_get_Node_allocator())) { _M_range_initialize(__list.begin(), __list.end()); } /** * @brief The %forward_list move constructor. * @param __list A %forward_list of identical element and allocator * types. * * The newly-created %forward_list contains the exact contents of the * moved instance. The contents of the moved instance are a valid, but * unspecified %forward_list. */ forward_list(forward_list&&) = default; /** * @brief Builds a %forward_list from an initializer_list * @param __il An initializer_list of value_type. * @param __al An allocator object. * * Create a %forward_list consisting of copies of the elements * in the initializer_list @a __il. This is linear in __il.size(). */ forward_list(std::initializer_list<_Tp> __il, const _Alloc& __al = _Alloc()) : _Base(_Node_alloc_type(__al)) { _M_range_initialize(__il.begin(), __il.end()); } /** * @brief The forward_list dtor. */ ~forward_list() noexcept { } /** * @brief The %forward_list assignment operator. * @param __list A %forward_list of identical element and allocator * types. * * All the elements of @a __list are copied. * * Whether the allocator is copied depends on the allocator traits. */ forward_list& operator=(const forward_list& __list); /** * @brief The %forward_list move assignment operator. * @param __list A %forward_list of identical element and allocator * types. * * The contents of @a __list are moved into this %forward_list * (without copying, if the allocators permit it). * * Afterwards @a __list is a valid, but unspecified %forward_list * * Whether the allocator is moved depends on the allocator traits. */ forward_list& operator=(forward_list&& __list) noexcept(_Node_alloc_traits::_S_nothrow_move()) { constexpr bool __move_storage = _Node_alloc_traits::_S_propagate_on_move_assign() || _Node_alloc_traits::_S_always_equal(); _M_move_assign(std::move(__list), __bool_constant<__move_storage>()); return *this; } /** * @brief The %forward_list initializer list assignment operator. * @param __il An initializer_list of value_type. * * Replace the contents of the %forward_list with copies of the * elements in the initializer_list @a __il. This is linear in * __il.size(). */ forward_list& operator=(std::initializer_list<_Tp> __il) { assign(__il); return *this; } /** * @brief Assigns a range to a %forward_list. * @param __first An input iterator. * @param __last An input iterator. * * This function fills a %forward_list with copies of the elements * in the range [@a __first,@a __last). * * Note that the assignment completely changes the %forward_list and * that the number of elements of the resulting %forward_list is the * same as the number of elements assigned. */ template> void assign(_InputIterator __first, _InputIterator __last) { typedef is_assignable<_Tp, decltype(*__first)> __assignable; _M_assign(__first, __last, __assignable()); } /** * @brief Assigns a given value to a %forward_list. * @param __n Number of elements to be assigned. * @param __val Value to be assigned. * * This function fills a %forward_list with @a __n copies of the * given value. Note that the assignment completely changes the * %forward_list, and that the resulting %forward_list has __n * elements. */ void assign(size_type __n, const _Tp& __val) { _M_assign_n(__n, __val, is_copy_assignable<_Tp>()); } /** * @brief Assigns an initializer_list to a %forward_list. * @param __il An initializer_list of value_type. * * Replace the contents of the %forward_list with copies of the * elements in the initializer_list @a __il. This is linear in * il.size(). */ void assign(std::initializer_list<_Tp> __il) { assign(__il.begin(), __il.end()); } /// Get a copy of the memory allocation object. allocator_type get_allocator() const noexcept { return allocator_type(this->_M_get_Node_allocator()); } // 23.3.4.3 iterators: /** * Returns a read/write iterator that points before the first element * in the %forward_list. Iteration is done in ordinary element order. */ iterator before_begin() noexcept { return iterator(&this->_M_impl._M_head); } /** * Returns a read-only (constant) iterator that points before the * first element in the %forward_list. Iteration is done in ordinary * element order. */ const_iterator before_begin() const noexcept { return const_iterator(&this->_M_impl._M_head); } /** * Returns a read/write iterator that points to the first element * in the %forward_list. Iteration is done in ordinary element order. */ iterator begin() noexcept { return iterator(this->_M_impl._M_head._M_next); } /** * Returns a read-only (constant) iterator that points to the first * element in the %forward_list. Iteration is done in ordinary * element order. */ const_iterator begin() const noexcept { return const_iterator(this->_M_impl._M_head._M_next); } /** * Returns a read/write iterator that points one past the last * element in the %forward_list. Iteration is done in ordinary * element order. */ iterator end() noexcept { return iterator(nullptr); } /** * Returns a read-only iterator that points one past the last * element in the %forward_list. Iteration is done in ordinary * element order. */ const_iterator end() const noexcept { return const_iterator(nullptr); } /** * Returns a read-only (constant) iterator that points to the * first element in the %forward_list. Iteration is done in ordinary * element order. */ const_iterator cbegin() const noexcept { return const_iterator(this->_M_impl._M_head._M_next); } /** * Returns a read-only (constant) iterator that points before the * first element in the %forward_list. Iteration is done in ordinary * element order. */ const_iterator cbefore_begin() const noexcept { return const_iterator(&this->_M_impl._M_head); } /** * Returns a read-only (constant) iterator that points one past * the last element in the %forward_list. Iteration is done in * ordinary element order. */ const_iterator cend() const noexcept { return const_iterator(nullptr); } /** * Returns true if the %forward_list is empty. (Thus begin() would * equal end().) */ bool empty() const noexcept { return this->_M_impl._M_head._M_next == nullptr; } /** * Returns the largest possible number of elements of %forward_list. */ size_type max_size() const noexcept { return _Node_alloc_traits::max_size(this->_M_get_Node_allocator()); } // 23.3.4.4 element access: /** * Returns a read/write reference to the data at the first * element of the %forward_list. */ reference front() { _Node* __front = static_cast<_Node*>(this->_M_impl._M_head._M_next); return *__front->_M_valptr(); } /** * Returns a read-only (constant) reference to the data at the first * element of the %forward_list. */ const_reference front() const { _Node* __front = static_cast<_Node*>(this->_M_impl._M_head._M_next); return *__front->_M_valptr(); } // 23.3.4.5 modifiers: /** * @brief Constructs object in %forward_list at the front of the * list. * @param __args Arguments. * * This function will insert an object of type Tp constructed * with Tp(std::forward(args)...) at the front of the list * Due to the nature of a %forward_list this operation can * be done in constant time, and does not invalidate iterators * and references. */ template #if __cplusplus > 201402L reference #else void #endif emplace_front(_Args&&... __args) { this->_M_insert_after(cbefore_begin(), std::forward<_Args>(__args)...); #if __cplusplus > 201402L return front(); #endif } /** * @brief Add data to the front of the %forward_list. * @param __val Data to be added. * * This is a typical stack operation. The function creates an * element at the front of the %forward_list and assigns the given * data to it. Due to the nature of a %forward_list this operation * can be done in constant time, and does not invalidate iterators * and references. */ void push_front(const _Tp& __val) { this->_M_insert_after(cbefore_begin(), __val); } /** * */ void push_front(_Tp&& __val) { this->_M_insert_after(cbefore_begin(), std::move(__val)); } /** * @brief Removes first element. * * This is a typical stack operation. It shrinks the %forward_list * by one. Due to the nature of a %forward_list this operation can * be done in constant time, and only invalidates iterators/references * to the element being removed. * * Note that no data is returned, and if the first element's data * is needed, it should be retrieved before pop_front() is * called. */ void pop_front() { this->_M_erase_after(&this->_M_impl._M_head); } /** * @brief Constructs object in %forward_list after the specified * iterator. * @param __pos A const_iterator into the %forward_list. * @param __args Arguments. * @return An iterator that points to the inserted data. * * This function will insert an object of type T constructed * with T(std::forward(args)...) after the specified * location. Due to the nature of a %forward_list this operation can * be done in constant time, and does not invalidate iterators * and references. */ template iterator emplace_after(const_iterator __pos, _Args&&... __args) { return iterator(this->_M_insert_after(__pos, std::forward<_Args>(__args)...)); } /** * @brief Inserts given value into %forward_list after specified * iterator. * @param __pos An iterator into the %forward_list. * @param __val Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value after * the specified location. Due to the nature of a %forward_list this * operation can be done in constant time, and does not * invalidate iterators and references. */ iterator insert_after(const_iterator __pos, const _Tp& __val) { return iterator(this->_M_insert_after(__pos, __val)); } /** * */ iterator insert_after(const_iterator __pos, _Tp&& __val) { return iterator(this->_M_insert_after(__pos, std::move(__val))); } /** * @brief Inserts a number of copies of given data into the * %forward_list. * @param __pos An iterator into the %forward_list. * @param __n Number of elements to be inserted. * @param __val Data to be inserted. * @return An iterator pointing to the last inserted copy of * @a val or @a pos if @a n == 0. * * This function will insert a specified number of copies of the * given data after the location specified by @a pos. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ iterator insert_after(const_iterator __pos, size_type __n, const _Tp& __val); /** * @brief Inserts a range into the %forward_list. * @param __pos An iterator into the %forward_list. * @param __first An input iterator. * @param __last An input iterator. * @return An iterator pointing to the last inserted element or * @a __pos if @a __first == @a __last. * * This function will insert copies of the data in the range * [@a __first,@a __last) into the %forward_list after the * location specified by @a __pos. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ template> iterator insert_after(const_iterator __pos, _InputIterator __first, _InputIterator __last); /** * @brief Inserts the contents of an initializer_list into * %forward_list after the specified iterator. * @param __pos An iterator into the %forward_list. * @param __il An initializer_list of value_type. * @return An iterator pointing to the last inserted element * or @a __pos if @a __il is empty. * * This function will insert copies of the data in the * initializer_list @a __il into the %forward_list before the location * specified by @a __pos. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ iterator insert_after(const_iterator __pos, std::initializer_list<_Tp> __il) { return insert_after(__pos, __il.begin(), __il.end()); } /** * @brief Removes the element pointed to by the iterator following * @c pos. * @param __pos Iterator pointing before element to be erased. * @return An iterator pointing to the element following the one * that was erased, or end() if no such element exists. * * This function will erase the element at the given position and * thus shorten the %forward_list by one. * * Due to the nature of a %forward_list this operation can be done * in constant time, and only invalidates iterators/references to * the element being removed. The user is also cautioned that * this function only erases the element, and that if the element * is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ iterator erase_after(const_iterator __pos) { return iterator(this->_M_erase_after(const_cast<_Node_base*> (__pos._M_node))); } /** * @brief Remove a range of elements. * @param __pos Iterator pointing before the first element to be * erased. * @param __last Iterator pointing to one past the last element to be * erased. * @return @ __last. * * This function will erase the elements in the range * @a (__pos,__last) and shorten the %forward_list accordingly. * * This operation is linear time in the size of the range and only * invalidates iterators/references to the element being removed. * The user is also cautioned that this function only erases the * elements, and that if the elements themselves are pointers, the * pointed-to memory is not touched in any way. Managing the pointer * is the user's responsibility. */ iterator erase_after(const_iterator __pos, const_iterator __last) { return iterator(this->_M_erase_after(const_cast<_Node_base*> (__pos._M_node), const_cast<_Node_base*> (__last._M_node))); } /** * @brief Swaps data with another %forward_list. * @param __list A %forward_list of the same element and allocator * types. * * This exchanges the elements between two lists in constant * time. Note that the global std::swap() function is * specialized such that std::swap(l1,l2) will feed to this * function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(forward_list& __list) noexcept { std::swap(this->_M_impl._M_head._M_next, __list._M_impl._M_head._M_next); _Node_alloc_traits::_S_on_swap(this->_M_get_Node_allocator(), __list._M_get_Node_allocator()); } /** * @brief Resizes the %forward_list to the specified number of * elements. * @param __sz Number of elements the %forward_list should contain. * * This function will %resize the %forward_list to the specified * number of elements. If the number is smaller than the * %forward_list's current number of elements the %forward_list * is truncated, otherwise the %forward_list is extended and the * new elements are default constructed. */ void resize(size_type __sz); /** * @brief Resizes the %forward_list to the specified number of * elements. * @param __sz Number of elements the %forward_list should contain. * @param __val Data with which new elements should be populated. * * This function will %resize the %forward_list to the specified * number of elements. If the number is smaller than the * %forward_list's current number of elements the %forward_list * is truncated, otherwise the %forward_list is extended and new * elements are populated with given data. */ void resize(size_type __sz, const value_type& __val); /** * @brief Erases all the elements. * * Note that this function only erases * the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibility. */ void clear() noexcept { this->_M_erase_after(&this->_M_impl._M_head, nullptr); } // 23.3.4.6 forward_list operations: /** * @brief Insert contents of another %forward_list. * @param __pos Iterator referencing the element to insert after. * @param __list Source list. * * The elements of @a list are inserted in constant time after * the element referenced by @a pos. @a list becomes an empty * list. * * Requires this != @a x. */ void splice_after(const_iterator __pos, forward_list&& __list) noexcept { if (!__list.empty()) _M_splice_after(__pos, __list.before_begin(), __list.end()); } void splice_after(const_iterator __pos, forward_list& __list) noexcept { splice_after(__pos, std::move(__list)); } /** * @brief Insert element from another %forward_list. * @param __pos Iterator referencing the element to insert after. * @param __list Source list. * @param __i Iterator referencing the element before the element * to move. * * Removes the element in list @a list referenced by @a i and * inserts it into the current list after @a pos. */ void splice_after(const_iterator __pos, forward_list&& __list, const_iterator __i) noexcept; void splice_after(const_iterator __pos, forward_list& __list, const_iterator __i) noexcept { splice_after(__pos, std::move(__list), __i); } /** * @brief Insert range from another %forward_list. * @param __pos Iterator referencing the element to insert after. * @param __list Source list. * @param __before Iterator referencing before the start of range * in list. * @param __last Iterator referencing the end of range in list. * * Removes elements in the range (__before,__last) and inserts them * after @a __pos in constant time. * * Undefined if @a __pos is in (__before,__last). * @{ */ void splice_after(const_iterator __pos, forward_list&&, const_iterator __before, const_iterator __last) noexcept { _M_splice_after(__pos, __before, __last); } void splice_after(const_iterator __pos, forward_list&, const_iterator __before, const_iterator __last) noexcept { _M_splice_after(__pos, __before, __last); } // @} /** * @brief Remove all elements equal to value. * @param __val The value to remove. * * Removes every element in the list equal to @a __val. * Remaining elements stay in list order. Note that this * function only erases the elements, and that if the elements * themselves are pointers, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ void remove(const _Tp& __val); /** * @brief Remove all elements satisfying a predicate. * @param __pred Unary predicate function or object. * * Removes every element in the list for which the predicate * returns true. Remaining elements stay in list order. Note * that this function only erases the elements, and that if the * elements themselves are pointers, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibility. */ template void remove_if(_Pred __pred); /** * @brief Remove consecutive duplicate elements. * * For each consecutive set of elements with the same value, * remove all but the first one. Remaining elements stay in * list order. Note that this function only erases the * elements, and that if the elements themselves are pointers, * the pointed-to memory is not touched in any way. Managing * the pointer is the user's responsibility. */ void unique() { unique(std::equal_to<_Tp>()); } /** * @brief Remove consecutive elements satisfying a predicate. * @param __binary_pred Binary predicate function or object. * * For each consecutive set of elements [first,last) that * satisfy predicate(first,i) where i is an iterator in * [first,last), remove all but the first one. Remaining * elements stay in list order. Note that this function only * erases the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibility. */ template void unique(_BinPred __binary_pred); /** * @brief Merge sorted lists. * @param __list Sorted list to merge. * * Assumes that both @a list and this list are sorted according to * operator<(). Merges elements of @a __list into this list in * sorted order, leaving @a __list empty when complete. Elements in * this list precede elements in @a __list that are equal. */ void merge(forward_list&& __list) { merge(std::move(__list), std::less<_Tp>()); } void merge(forward_list& __list) { merge(std::move(__list)); } /** * @brief Merge sorted lists according to comparison function. * @param __list Sorted list to merge. * @param __comp Comparison function defining sort order. * * Assumes that both @a __list and this list are sorted according to * comp. Merges elements of @a __list into this list * in sorted order, leaving @a __list empty when complete. Elements * in this list precede elements in @a __list that are equivalent * according to comp(). */ template void merge(forward_list&& __list, _Comp __comp); template void merge(forward_list& __list, _Comp __comp) { merge(std::move(__list), __comp); } /** * @brief Sort the elements of the list. * * Sorts the elements of this list in NlogN time. Equivalent * elements remain in list order. */ void sort() { sort(std::less<_Tp>()); } /** * @brief Sort the forward_list using a comparison function. * * Sorts the elements of this list in NlogN time. Equivalent * elements remain in list order. */ template void sort(_Comp __comp); /** * @brief Reverse the elements in list. * * Reverse the order of elements in the list in linear time. */ void reverse() noexcept { this->_M_impl._M_head._M_reverse_after(); } private: // Called by the range constructor to implement [23.3.4.2]/9 template void _M_range_initialize(_InputIterator __first, _InputIterator __last); // Called by forward_list(n,v,a), and the range constructor when it // turns out to be the same thing. void _M_fill_initialize(size_type __n, const value_type& __value); // Called by splice_after and insert_after. iterator _M_splice_after(const_iterator __pos, const_iterator __before, const_iterator __last); // Called by forward_list(n). void _M_default_initialize(size_type __n); // Called by resize(sz). void _M_default_insert_after(const_iterator __pos, size_type __n); // Called by operator=(forward_list&&) void _M_move_assign(forward_list&& __list, true_type) noexcept { clear(); this->_M_impl._M_head._M_next = __list._M_impl._M_head._M_next; __list._M_impl._M_head._M_next = nullptr; std::__alloc_on_move(this->_M_get_Node_allocator(), __list._M_get_Node_allocator()); } // Called by operator=(forward_list&&) void _M_move_assign(forward_list&& __list, false_type) { if (__list._M_get_Node_allocator() == this->_M_get_Node_allocator()) _M_move_assign(std::move(__list), true_type()); else // The rvalue's allocator cannot be moved, or is not equal, // so we need to individually move each element. this->assign(std::__make_move_if_noexcept_iterator(__list.begin()), std::__make_move_if_noexcept_iterator(__list.end())); } // Called by assign(_InputIterator, _InputIterator) if _Tp is // CopyAssignable. template void _M_assign(_InputIterator __first, _InputIterator __last, true_type) { auto __prev = before_begin(); auto __curr = begin(); auto __end = end(); while (__curr != __end && __first != __last) { *__curr = *__first; ++__prev; ++__curr; ++__first; } if (__first != __last) insert_after(__prev, __first, __last); else if (__curr != __end) erase_after(__prev, __end); } // Called by assign(_InputIterator, _InputIterator) if _Tp is not // CopyAssignable. template void _M_assign(_InputIterator __first, _InputIterator __last, false_type) { clear(); insert_after(cbefore_begin(), __first, __last); } // Called by assign(size_type, const _Tp&) if Tp is CopyAssignable void _M_assign_n(size_type __n, const _Tp& __val, true_type) { auto __prev = before_begin(); auto __curr = begin(); auto __end = end(); while (__curr != __end && __n > 0) { *__curr = __val; ++__prev; ++__curr; --__n; } if (__n > 0) insert_after(__prev, __n, __val); else if (__curr != __end) erase_after(__prev, __end); } // Called by assign(size_type, const _Tp&) if Tp is non-CopyAssignable void _M_assign_n(size_type __n, const _Tp& __val, false_type) { clear(); insert_after(cbefore_begin(), __n, __val); } }; #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> forward_list(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> forward_list<_ValT, _Allocator>; #endif /** * @brief Forward list equality comparison. * @param __lx A %forward_list * @param __ly A %forward_list of the same type as @a __lx. * @return True iff the elements of the forward lists are equal. * * This is an equivalence relation. It is linear in the number of * elements of the forward lists. Deques are considered equivalent * if corresponding elements compare equal. */ template bool operator==(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly); /** * @brief Forward list ordering relation. * @param __lx A %forward_list. * @param __ly A %forward_list of the same type as @a __lx. * @return True iff @a __lx is lexicographically less than @a __ly. * * This is a total ordering relation. It is linear in the number of * elements of the forward lists. The elements must be comparable * with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return std::lexicographical_compare(__lx.cbegin(), __lx.cend(), __ly.cbegin(), __ly.cend()); } /// Based on operator== template inline bool operator!=(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return !(__lx == __ly); } /// Based on operator< template inline bool operator>(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return (__ly < __lx); } /// Based on operator< template inline bool operator>=(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return !(__lx < __ly); } /// Based on operator< template inline bool operator<=(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return !(__ly < __lx); } /// See std::forward_list::swap(). template inline void swap(forward_list<_Tp, _Alloc>& __lx, forward_list<_Tp, _Alloc>& __ly) noexcept(noexcept(__lx.swap(__ly))) { __lx.swap(__ly); } _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _FORWARD_LIST_H PK!P^q3q38/bits/forward_list.tccnu[// -*- C++ -*- // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/forward_list.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{forward_list} */ #ifndef _FORWARD_LIST_TCC #define _FORWARD_LIST_TCC 1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER template _Fwd_list_base<_Tp, _Alloc>:: _Fwd_list_base(_Fwd_list_base&& __lst, _Node_alloc_type&& __a) : _M_impl(std::move(__a)) { if (__lst._M_get_Node_allocator() == _M_get_Node_allocator()) this->_M_impl._M_head = std::move(__lst._M_impl._M_head); } template template _Fwd_list_node_base* _Fwd_list_base<_Tp, _Alloc>:: _M_insert_after(const_iterator __pos, _Args&&... __args) { _Fwd_list_node_base* __to = const_cast<_Fwd_list_node_base*>(__pos._M_node); _Node* __thing = _M_create_node(std::forward<_Args>(__args)...); __thing->_M_next = __to->_M_next; __to->_M_next = __thing; return __to->_M_next; } template _Fwd_list_node_base* _Fwd_list_base<_Tp, _Alloc>:: _M_erase_after(_Fwd_list_node_base* __pos) { _Node* __curr = static_cast<_Node*>(__pos->_M_next); __pos->_M_next = __curr->_M_next; _Node_alloc_traits::destroy(_M_get_Node_allocator(), __curr->_M_valptr()); __curr->~_Node(); _M_put_node(__curr); return __pos->_M_next; } template _Fwd_list_node_base* _Fwd_list_base<_Tp, _Alloc>:: _M_erase_after(_Fwd_list_node_base* __pos, _Fwd_list_node_base* __last) { _Node* __curr = static_cast<_Node*>(__pos->_M_next); while (__curr != __last) { _Node* __temp = __curr; __curr = static_cast<_Node*>(__curr->_M_next); _Node_alloc_traits::destroy(_M_get_Node_allocator(), __temp->_M_valptr()); __temp->~_Node(); _M_put_node(__temp); } __pos->_M_next = __last; return __last; } // Called by the range constructor to implement [23.3.4.2]/9 template template void forward_list<_Tp, _Alloc>:: _M_range_initialize(_InputIterator __first, _InputIterator __last) { _Node_base* __to = &this->_M_impl._M_head; for (; __first != __last; ++__first) { __to->_M_next = this->_M_create_node(*__first); __to = __to->_M_next; } } // Called by forward_list(n,v,a). template void forward_list<_Tp, _Alloc>:: _M_fill_initialize(size_type __n, const value_type& __value) { _Node_base* __to = &this->_M_impl._M_head; for (; __n; --__n) { __to->_M_next = this->_M_create_node(__value); __to = __to->_M_next; } } template void forward_list<_Tp, _Alloc>:: _M_default_initialize(size_type __n) { _Node_base* __to = &this->_M_impl._M_head; for (; __n; --__n) { __to->_M_next = this->_M_create_node(); __to = __to->_M_next; } } template forward_list<_Tp, _Alloc>& forward_list<_Tp, _Alloc>:: operator=(const forward_list& __list) { if (std::__addressof(__list) != this) { if (_Node_alloc_traits::_S_propagate_on_copy_assign()) { auto& __this_alloc = this->_M_get_Node_allocator(); auto& __that_alloc = __list._M_get_Node_allocator(); if (!_Node_alloc_traits::_S_always_equal() && __this_alloc != __that_alloc) { // replacement allocator cannot free existing storage clear(); } std::__alloc_on_copy(__this_alloc, __that_alloc); } assign(__list.cbegin(), __list.cend()); } return *this; } template void forward_list<_Tp, _Alloc>:: _M_default_insert_after(const_iterator __pos, size_type __n) { const_iterator __saved_pos = __pos; __try { for (; __n; --__n) __pos = emplace_after(__pos); } __catch(...) { erase_after(__saved_pos, ++__pos); __throw_exception_again; } } template void forward_list<_Tp, _Alloc>:: resize(size_type __sz) { iterator __k = before_begin(); size_type __len = 0; while (__k._M_next() != end() && __len < __sz) { ++__k; ++__len; } if (__len == __sz) erase_after(__k, end()); else _M_default_insert_after(__k, __sz - __len); } template void forward_list<_Tp, _Alloc>:: resize(size_type __sz, const value_type& __val) { iterator __k = before_begin(); size_type __len = 0; while (__k._M_next() != end() && __len < __sz) { ++__k; ++__len; } if (__len == __sz) erase_after(__k, end()); else insert_after(__k, __sz - __len, __val); } template typename forward_list<_Tp, _Alloc>::iterator forward_list<_Tp, _Alloc>:: _M_splice_after(const_iterator __pos, const_iterator __before, const_iterator __last) { _Node_base* __tmp = const_cast<_Node_base*>(__pos._M_node); _Node_base* __b = const_cast<_Node_base*>(__before._M_node); _Node_base* __end = __b; while (__end && __end->_M_next != __last._M_node) __end = __end->_M_next; if (__b != __end) return iterator(__tmp->_M_transfer_after(__b, __end)); else return iterator(__tmp); } template void forward_list<_Tp, _Alloc>:: splice_after(const_iterator __pos, forward_list&&, const_iterator __i) noexcept { const_iterator __j = __i; ++__j; if (__pos == __i || __pos == __j) return; _Node_base* __tmp = const_cast<_Node_base*>(__pos._M_node); __tmp->_M_transfer_after(const_cast<_Node_base*>(__i._M_node), const_cast<_Node_base*>(__j._M_node)); } template typename forward_list<_Tp, _Alloc>::iterator forward_list<_Tp, _Alloc>:: insert_after(const_iterator __pos, size_type __n, const _Tp& __val) { if (__n) { forward_list __tmp(__n, __val, get_allocator()); return _M_splice_after(__pos, __tmp.before_begin(), __tmp.end()); } else return iterator(const_cast<_Node_base*>(__pos._M_node)); } template template typename forward_list<_Tp, _Alloc>::iterator forward_list<_Tp, _Alloc>:: insert_after(const_iterator __pos, _InputIterator __first, _InputIterator __last) { forward_list __tmp(__first, __last, get_allocator()); if (!__tmp.empty()) return _M_splice_after(__pos, __tmp.before_begin(), __tmp.end()); else return iterator(const_cast<_Node_base*>(__pos._M_node)); } template void forward_list<_Tp, _Alloc>:: remove(const _Tp& __val) { _Node_base* __curr = &this->_M_impl._M_head; _Node_base* __extra = nullptr; while (_Node* __tmp = static_cast<_Node*>(__curr->_M_next)) { if (*__tmp->_M_valptr() == __val) { if (__tmp->_M_valptr() != std::__addressof(__val)) { this->_M_erase_after(__curr); continue; } else __extra = __curr; } __curr = __curr->_M_next; } if (__extra) this->_M_erase_after(__extra); } template template void forward_list<_Tp, _Alloc>:: remove_if(_Pred __pred) { _Node_base* __curr = &this->_M_impl._M_head; while (_Node* __tmp = static_cast<_Node*>(__curr->_M_next)) { if (__pred(*__tmp->_M_valptr())) this->_M_erase_after(__curr); else __curr = __curr->_M_next; } } template template void forward_list<_Tp, _Alloc>:: unique(_BinPred __binary_pred) { iterator __first = begin(); iterator __last = end(); if (__first == __last) return; iterator __next = __first; while (++__next != __last) { if (__binary_pred(*__first, *__next)) erase_after(__first); else __first = __next; __next = __first; } } template template void forward_list<_Tp, _Alloc>:: merge(forward_list&& __list, _Comp __comp) { _Node_base* __node = &this->_M_impl._M_head; while (__node->_M_next && __list._M_impl._M_head._M_next) { if (__comp(*static_cast<_Node*> (__list._M_impl._M_head._M_next)->_M_valptr(), *static_cast<_Node*> (__node->_M_next)->_M_valptr())) __node->_M_transfer_after(&__list._M_impl._M_head, __list._M_impl._M_head._M_next); __node = __node->_M_next; } if (__list._M_impl._M_head._M_next) *__node = std::move(__list._M_impl._M_head); } template bool operator==(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { // We don't have size() so we need to walk through both lists // making sure both iterators are valid. auto __ix = __lx.cbegin(); auto __iy = __ly.cbegin(); while (__ix != __lx.cend() && __iy != __ly.cend()) { if (!(*__ix == *__iy)) return false; ++__ix; ++__iy; } if (__ix == __lx.cend() && __iy == __ly.cend()) return true; else return false; } template template void forward_list<_Tp, _Alloc>:: sort(_Comp __comp) { // If `next' is nullptr, return immediately. _Node* __list = static_cast<_Node*>(this->_M_impl._M_head._M_next); if (!__list) return; unsigned long __insize = 1; while (1) { _Node* __p = __list; __list = nullptr; _Node* __tail = nullptr; // Count number of merges we do in this pass. unsigned long __nmerges = 0; while (__p) { ++__nmerges; // There exists a merge to be done. // Step `insize' places along from p. _Node* __q = __p; unsigned long __psize = 0; for (unsigned long __i = 0; __i < __insize; ++__i) { ++__psize; __q = static_cast<_Node*>(__q->_M_next); if (!__q) break; } // If q hasn't fallen off end, we have two lists to merge. unsigned long __qsize = __insize; // Now we have two lists; merge them. while (__psize > 0 || (__qsize > 0 && __q)) { // Decide whether next node of merge comes from p or q. _Node* __e; if (__psize == 0) { // p is empty; e must come from q. __e = __q; __q = static_cast<_Node*>(__q->_M_next); --__qsize; } else if (__qsize == 0 || !__q) { // q is empty; e must come from p. __e = __p; __p = static_cast<_Node*>(__p->_M_next); --__psize; } else if (!__comp(*__q->_M_valptr(), *__p->_M_valptr())) { // First node of q is not lower; e must come from p. __e = __p; __p = static_cast<_Node*>(__p->_M_next); --__psize; } else { // First node of q is lower; e must come from q. __e = __q; __q = static_cast<_Node*>(__q->_M_next); --__qsize; } // Add the next node to the merged list. if (__tail) __tail->_M_next = __e; else __list = __e; __tail = __e; } // Now p has stepped `insize' places along, and q has too. __p = __q; } __tail->_M_next = nullptr; // If we have done only one merge, we're finished. // Allow for nmerges == 0, the empty list case. if (__nmerges <= 1) { this->_M_impl._M_head._M_next = __list; return; } // Otherwise repeat, merging lists twice the size. __insize *= 2; } } _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _FORWARD_LIST_TCC */ PK!V998/bits/fs_dir.hnu[// Filesystem directory utilities -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/fs_dir.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{filesystem} */ #ifndef _GLIBCXX_FS_DIR_H #define _GLIBCXX_FS_DIR_H 1 #if __cplusplus >= 201703L # include # include # include # include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace filesystem { /** * @ingroup filesystem * @{ */ class file_status { public: // constructors and destructor file_status() noexcept : file_status(file_type::none) {} explicit file_status(file_type __ft, perms __prms = perms::unknown) noexcept : _M_type(__ft), _M_perms(__prms) { } file_status(const file_status&) noexcept = default; file_status(file_status&&) noexcept = default; ~file_status() = default; file_status& operator=(const file_status&) noexcept = default; file_status& operator=(file_status&&) noexcept = default; // observers file_type type() const noexcept { return _M_type; } perms permissions() const noexcept { return _M_perms; } // modifiers void type(file_type __ft) noexcept { _M_type = __ft; } void permissions(perms __prms) noexcept { _M_perms = __prms; } private: file_type _M_type; perms _M_perms; }; _GLIBCXX_BEGIN_NAMESPACE_CXX11 struct _Dir; class directory_iterator; class recursive_directory_iterator; class directory_entry { public: // constructors and destructor directory_entry() noexcept = default; directory_entry(const directory_entry&) = default; directory_entry(directory_entry&&) noexcept = default; explicit directory_entry(const filesystem::path& __p) : _M_path(__p) { refresh(); } directory_entry(const filesystem::path& __p, error_code& __ec) : _M_path(__p) { refresh(__ec); if (__ec) _M_path.clear(); } ~directory_entry() = default; // modifiers directory_entry& operator=(const directory_entry&) = default; directory_entry& operator=(directory_entry&&) noexcept = default; void assign(const filesystem::path& __p) { _M_path = __p; refresh(); } void assign(const filesystem::path& __p, error_code& __ec) { _M_path = __p; refresh(__ec); } void replace_filename(const filesystem::path& __p) { _M_path.replace_filename(__p); refresh(); } void replace_filename(const filesystem::path& __p, error_code& __ec) { _M_path.replace_filename(__p); refresh(__ec); } void refresh() { _M_type = symlink_status().type(); } void refresh(error_code& __ec) noexcept { _M_type = symlink_status(__ec).type(); } // observers const filesystem::path& path() const noexcept { return _M_path; } operator const filesystem::path& () const noexcept { return _M_path; } bool exists() const { return filesystem::exists(file_status{_M_file_type()}); } bool exists(error_code& __ec) const noexcept { return filesystem::exists(file_status{_M_file_type(__ec)}); } bool is_block_file() const { return _M_file_type() == file_type::block; } bool is_block_file(error_code& __ec) const noexcept { return _M_file_type(__ec) == file_type::block; } bool is_character_file() const { return _M_file_type() == file_type::character; } bool is_character_file(error_code& __ec) const noexcept { return _M_file_type(__ec) == file_type::character; } bool is_directory() const { return _M_file_type() == file_type::directory; } bool is_directory(error_code& __ec) const noexcept { return _M_file_type(__ec) == file_type::directory; } bool is_fifo() const { return _M_file_type() == file_type::fifo; } bool is_fifo(error_code& __ec) const noexcept { return _M_file_type(__ec) == file_type::fifo; } bool is_other() const { return filesystem::is_other(file_status{_M_file_type()}); } bool is_other(error_code& __ec) const noexcept { return filesystem::is_other(file_status{_M_file_type(__ec)}); } bool is_regular_file() const { return _M_file_type() == file_type::regular; } bool is_regular_file(error_code& __ec) const noexcept { return _M_file_type(__ec) == file_type::regular; } bool is_socket() const { return _M_file_type() == file_type::socket; } bool is_socket(error_code& __ec) const noexcept { return _M_file_type(__ec) == file_type::socket; } bool is_symlink() const { if (_M_type != file_type::none) return _M_type == file_type::symlink; return symlink_status().type() == file_type::symlink; } bool is_symlink(error_code& __ec) const noexcept { if (_M_type != file_type::none) return _M_type == file_type::symlink; return symlink_status(__ec).type() == file_type::symlink; } uintmax_t file_size() const { return filesystem::file_size(_M_path); } uintmax_t file_size(error_code& __ec) const noexcept { return filesystem::file_size(_M_path, __ec); } uintmax_t hard_link_count() const { return filesystem::hard_link_count(_M_path); } uintmax_t hard_link_count(error_code& __ec) const noexcept { return filesystem::hard_link_count(_M_path, __ec); } file_time_type last_write_time() const { return filesystem::last_write_time(_M_path); } file_time_type last_write_time(error_code& __ec) const noexcept { return filesystem::last_write_time(_M_path, __ec); } file_status status() const { return filesystem::status(_M_path); } file_status status(error_code& __ec) const noexcept { return filesystem::status(_M_path, __ec); } file_status symlink_status() const { return filesystem::symlink_status(_M_path); } file_status symlink_status(error_code& __ec) const noexcept { return filesystem::symlink_status(_M_path, __ec); } bool operator< (const directory_entry& __rhs) const noexcept { return _M_path < __rhs._M_path; } bool operator==(const directory_entry& __rhs) const noexcept { return _M_path == __rhs._M_path; } bool operator!=(const directory_entry& __rhs) const noexcept { return _M_path != __rhs._M_path; } bool operator<=(const directory_entry& __rhs) const noexcept { return _M_path <= __rhs._M_path; } bool operator> (const directory_entry& __rhs) const noexcept { return _M_path > __rhs._M_path; } bool operator>=(const directory_entry& __rhs) const noexcept { return _M_path >= __rhs._M_path; } private: friend class _Dir; friend class directory_iterator; friend class recursive_directory_iterator; directory_entry(const filesystem::path& __p, file_type __t) : _M_path(__p), _M_type(__t) { } // Equivalent to status().type() but uses cached value, if any. file_type _M_file_type() const { if (_M_type != file_type::none && _M_type != file_type::symlink) return _M_type; return status().type(); } // Equivalent to status(__ec).type() but uses cached value, if any. file_type _M_file_type(error_code& __ec) const noexcept { if (_M_type != file_type::none && _M_type != file_type::symlink) { __ec.clear(); return _M_type; } return status(__ec).type(); } filesystem::path _M_path; file_type _M_type = file_type::none; }; struct __directory_iterator_proxy { const directory_entry& operator*() const& noexcept { return _M_entry; } directory_entry operator*() && noexcept { return std::move(_M_entry); } private: friend class directory_iterator; friend class recursive_directory_iterator; explicit __directory_iterator_proxy(const directory_entry& __e) : _M_entry(__e) { } directory_entry _M_entry; }; class directory_iterator { public: typedef directory_entry value_type; typedef ptrdiff_t difference_type; typedef const directory_entry* pointer; typedef const directory_entry& reference; typedef input_iterator_tag iterator_category; directory_iterator() = default; explicit directory_iterator(const path& __p) : directory_iterator(__p, directory_options::none, nullptr) { } directory_iterator(const path& __p, directory_options __options) : directory_iterator(__p, __options, nullptr) { } directory_iterator(const path& __p, error_code& __ec) : directory_iterator(__p, directory_options::none, __ec) { } directory_iterator(const path& __p, directory_options __options, error_code& __ec) : directory_iterator(__p, __options, &__ec) { } directory_iterator(const directory_iterator& __rhs) = default; directory_iterator(directory_iterator&& __rhs) noexcept = default; ~directory_iterator() = default; directory_iterator& operator=(const directory_iterator& __rhs) = default; directory_iterator& operator=(directory_iterator&& __rhs) noexcept = default; const directory_entry& operator*() const; const directory_entry* operator->() const { return &**this; } directory_iterator& operator++(); directory_iterator& increment(error_code& __ec); __directory_iterator_proxy operator++(int) { __directory_iterator_proxy __pr{**this}; ++*this; return __pr; } private: directory_iterator(const path&, directory_options, error_code*); friend bool operator==(const directory_iterator& __lhs, const directory_iterator& __rhs); friend class recursive_directory_iterator; std::shared_ptr<_Dir> _M_dir; }; inline directory_iterator begin(directory_iterator __iter) noexcept { return __iter; } inline directory_iterator end(directory_iterator) noexcept { return directory_iterator(); } inline bool operator==(const directory_iterator& __lhs, const directory_iterator& __rhs) { return !__rhs._M_dir.owner_before(__lhs._M_dir) && !__lhs._M_dir.owner_before(__rhs._M_dir); } inline bool operator!=(const directory_iterator& __lhs, const directory_iterator& __rhs) { return !(__lhs == __rhs); } class recursive_directory_iterator { public: typedef directory_entry value_type; typedef ptrdiff_t difference_type; typedef const directory_entry* pointer; typedef const directory_entry& reference; typedef input_iterator_tag iterator_category; recursive_directory_iterator() = default; explicit recursive_directory_iterator(const path& __p) : recursive_directory_iterator(__p, directory_options::none, nullptr) { } recursive_directory_iterator(const path& __p, directory_options __options) : recursive_directory_iterator(__p, __options, nullptr) { } recursive_directory_iterator(const path& __p, directory_options __options, error_code& __ec) : recursive_directory_iterator(__p, __options, &__ec) { } recursive_directory_iterator(const path& __p, error_code& __ec) : recursive_directory_iterator(__p, directory_options::none, &__ec) { } recursive_directory_iterator( const recursive_directory_iterator&) = default; recursive_directory_iterator(recursive_directory_iterator&&) = default; ~recursive_directory_iterator(); // observers directory_options options() const { return _M_options; } int depth() const; bool recursion_pending() const { return _M_pending; } const directory_entry& operator*() const; const directory_entry* operator->() const { return &**this; } // modifiers recursive_directory_iterator& operator=(const recursive_directory_iterator& __rhs) noexcept; recursive_directory_iterator& operator=(recursive_directory_iterator&& __rhs) noexcept; recursive_directory_iterator& operator++(); recursive_directory_iterator& increment(error_code& __ec); __directory_iterator_proxy operator++(int) { __directory_iterator_proxy __pr{**this}; ++*this; return __pr; } void pop(); void pop(error_code&); void disable_recursion_pending() { _M_pending = false; } private: recursive_directory_iterator(const path&, directory_options, error_code*); friend bool operator==(const recursive_directory_iterator& __lhs, const recursive_directory_iterator& __rhs); struct _Dir_stack; std::shared_ptr<_Dir_stack> _M_dirs; directory_options _M_options = {}; bool _M_pending = false; }; inline recursive_directory_iterator begin(recursive_directory_iterator __iter) noexcept { return __iter; } inline recursive_directory_iterator end(recursive_directory_iterator) noexcept { return recursive_directory_iterator(); } inline bool operator==(const recursive_directory_iterator& __lhs, const recursive_directory_iterator& __rhs) { return !__rhs._M_dirs.owner_before(__lhs._M_dirs) && !__lhs._M_dirs.owner_before(__rhs._M_dirs); } inline bool operator!=(const recursive_directory_iterator& __lhs, const recursive_directory_iterator& __rhs) { return !(__lhs == __rhs); } _GLIBCXX_END_NAMESPACE_CXX11 // @} group filesystem } // namespace filesystem _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++17 #endif // _GLIBCXX_FS_DIR_H PK!'('(8/bits/fs_fwd.hnu[// Filesystem declarations -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/fs_fwd.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{filesystem} */ #ifndef _GLIBCXX_FS_FWD_H #define _GLIBCXX_FS_FWD_H 1 #if __cplusplus >= 201703L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace filesystem { #if _GLIBCXX_USE_CXX11_ABI inline namespace __cxx11 __attribute__((__abi_tag__ ("cxx11"))) { } #endif /** * @defgroup filesystem Filesystem * * Utilities for performing operations on file systems and their components, * such as paths, regular files, and directories. * * @{ */ class file_status; _GLIBCXX_BEGIN_NAMESPACE_CXX11 class path; class filesystem_error; class directory_entry; class directory_iterator; class recursive_directory_iterator; _GLIBCXX_END_NAMESPACE_CXX11 struct space_info { uintmax_t capacity; uintmax_t free; uintmax_t available; }; enum class file_type : signed char { none = 0, not_found = -1, regular = 1, directory = 2, symlink = 3, block = 4, character = 5, fifo = 6, socket = 7, unknown = 8 }; /// Bitmask type enum class copy_options : unsigned short { none = 0, skip_existing = 1, overwrite_existing = 2, update_existing = 4, recursive = 8, copy_symlinks = 16, skip_symlinks = 32, directories_only = 64, create_symlinks = 128, create_hard_links = 256 }; constexpr copy_options operator&(copy_options __x, copy_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) & static_cast<__utype>(__y)); } constexpr copy_options operator|(copy_options __x, copy_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) | static_cast<__utype>(__y)); } constexpr copy_options operator^(copy_options __x, copy_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) ^ static_cast<__utype>(__y)); } constexpr copy_options operator~(copy_options __x) noexcept { using __utype = typename std::underlying_type::type; return static_cast(~static_cast<__utype>(__x)); } inline copy_options& operator&=(copy_options& __x, copy_options __y) noexcept { return __x = __x & __y; } inline copy_options& operator|=(copy_options& __x, copy_options __y) noexcept { return __x = __x | __y; } inline copy_options& operator^=(copy_options& __x, copy_options __y) noexcept { return __x = __x ^ __y; } /// Bitmask type enum class perms : unsigned { none = 0, owner_read = 0400, owner_write = 0200, owner_exec = 0100, owner_all = 0700, group_read = 040, group_write = 020, group_exec = 010, group_all = 070, others_read = 04, others_write = 02, others_exec = 01, others_all = 07, all = 0777, set_uid = 04000, set_gid = 02000, sticky_bit = 01000, mask = 07777, unknown = 0xFFFF, }; constexpr perms operator&(perms __x, perms __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) & static_cast<__utype>(__y)); } constexpr perms operator|(perms __x, perms __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) | static_cast<__utype>(__y)); } constexpr perms operator^(perms __x, perms __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) ^ static_cast<__utype>(__y)); } constexpr perms operator~(perms __x) noexcept { using __utype = typename std::underlying_type::type; return static_cast(~static_cast<__utype>(__x)); } inline perms& operator&=(perms& __x, perms __y) noexcept { return __x = __x & __y; } inline perms& operator|=(perms& __x, perms __y) noexcept { return __x = __x | __y; } inline perms& operator^=(perms& __x, perms __y) noexcept { return __x = __x ^ __y; } /// Bitmask type enum class perm_options : unsigned { replace = 0x1, add = 0x2, remove = 0x4, nofollow = 0x8 }; constexpr perm_options operator&(perm_options __x, perm_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) & static_cast<__utype>(__y)); } constexpr perm_options operator|(perm_options __x, perm_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) | static_cast<__utype>(__y)); } constexpr perm_options operator^(perm_options __x, perm_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) ^ static_cast<__utype>(__y)); } constexpr perm_options operator~(perm_options __x) noexcept { using __utype = typename std::underlying_type::type; return static_cast(~static_cast<__utype>(__x)); } inline perm_options& operator&=(perm_options& __x, perm_options __y) noexcept { return __x = __x & __y; } inline perm_options& operator|=(perm_options& __x, perm_options __y) noexcept { return __x = __x | __y; } inline perm_options& operator^=(perm_options& __x, perm_options __y) noexcept { return __x = __x ^ __y; } // Bitmask type enum class directory_options : unsigned char { none = 0, follow_directory_symlink = 1, skip_permission_denied = 2 }; constexpr directory_options operator&(directory_options __x, directory_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) & static_cast<__utype>(__y)); } constexpr directory_options operator|(directory_options __x, directory_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) | static_cast<__utype>(__y)); } constexpr directory_options operator^(directory_options __x, directory_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) ^ static_cast<__utype>(__y)); } constexpr directory_options operator~(directory_options __x) noexcept { using __utype = typename std::underlying_type::type; return static_cast(~static_cast<__utype>(__x)); } inline directory_options& operator&=(directory_options& __x, directory_options __y) noexcept { return __x = __x & __y; } inline directory_options& operator|=(directory_options& __x, directory_options __y) noexcept { return __x = __x | __y; } inline directory_options& operator^=(directory_options& __x, directory_options __y) noexcept { return __x = __x ^ __y; } using file_time_type = std::chrono::system_clock::time_point; // operational functions void copy(const path& __from, const path& __to, copy_options __options); void copy(const path& __from, const path& __to, copy_options __options, error_code&); bool copy_file(const path& __from, const path& __to, copy_options __option); bool copy_file(const path& __from, const path& __to, copy_options __option, error_code&); path current_path(); bool exists(file_status) noexcept; bool is_other(file_status) noexcept; uintmax_t file_size(const path&); uintmax_t file_size(const path&, error_code&) noexcept; uintmax_t hard_link_count(const path&); uintmax_t hard_link_count(const path&, error_code&) noexcept; file_time_type last_write_time(const path&); file_time_type last_write_time(const path&, error_code&) noexcept; void permissions(const path&, perms, perm_options, error_code&) noexcept; path proximate(const path& __p, const path& __base, error_code& __ec); path proximate(const path& __p, const path& __base, error_code& __ec); path relative(const path& __p, const path& __base, error_code& __ec); file_status status(const path&); file_status status(const path&, error_code&) noexcept; bool status_known(file_status) noexcept; file_status symlink_status(const path&); file_status symlink_status(const path&, error_code&) noexcept; bool is_regular_file(file_status) noexcept; bool is_symlink(file_status) noexcept; // @} group filesystem } // namespace filesystem _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++17 #endif // _GLIBCXX_FS_FWD_H PK!,Gf&&8/bits/fs_ops.hnu[// Filesystem operational functions -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your __option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/fs_fwd.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{filesystem} */ #ifndef _GLIBCXX_FS_OPS_H #define _GLIBCXX_FS_OPS_H 1 #if __cplusplus >= 201703L #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace filesystem { /** * @ingroup filesystem * @{ */ path absolute(const path& __p); path absolute(const path& __p, error_code& __ec); path canonical(const path& __p); path canonical(const path& __p, error_code& __ec); inline void copy(const path& __from, const path& __to) { copy(__from, __to, copy_options::none); } inline void copy(const path& __from, const path& __to, error_code& __ec) { copy(__from, __to, copy_options::none, __ec); } void copy(const path& __from, const path& __to, copy_options __options); void copy(const path& __from, const path& __to, copy_options __options, error_code& __ec); inline bool copy_file(const path& __from, const path& __to) { return copy_file(__from, __to, copy_options::none); } inline bool copy_file(const path& __from, const path& __to, error_code& __ec) { return copy_file(__from, __to, copy_options::none, __ec); } bool copy_file(const path& __from, const path& __to, copy_options __option); bool copy_file(const path& __from, const path& __to, copy_options __option, error_code& __ec); void copy_symlink(const path& __existing_symlink, const path& __new_symlink); void copy_symlink(const path& __existing_symlink, const path& __new_symlink, error_code& __ec) noexcept; bool create_directories(const path& __p); bool create_directories(const path& __p, error_code& __ec); bool create_directory(const path& __p); bool create_directory(const path& __p, error_code& __ec) noexcept; bool create_directory(const path& __p, const path& attributes); bool create_directory(const path& __p, const path& attributes, error_code& __ec) noexcept; void create_directory_symlink(const path& __to, const path& __new_symlink); void create_directory_symlink(const path& __to, const path& __new_symlink, error_code& __ec) noexcept; void create_hard_link(const path& __to, const path& __new_hard_link); void create_hard_link(const path& __to, const path& __new_hard_link, error_code& __ec) noexcept; void create_symlink(const path& __to, const path& __new_symlink); void create_symlink(const path& __to, const path& __new_symlink, error_code& __ec) noexcept; path current_path(); path current_path(error_code& __ec); void current_path(const path& __p); void current_path(const path& __p, error_code& __ec) noexcept; bool equivalent(const path& __p1, const path& __p2); bool equivalent(const path& __p1, const path& __p2, error_code& __ec) noexcept; inline bool exists(file_status __s) noexcept { return status_known(__s) && __s.type() != file_type::not_found; } inline bool exists(const path& __p) { return exists(status(__p)); } inline bool exists(const path& __p, error_code& __ec) noexcept { auto __s = status(__p, __ec); if (status_known(__s)) { __ec.clear(); return __s.type() != file_type::not_found; } return false; } uintmax_t file_size(const path& __p); uintmax_t file_size(const path& __p, error_code& __ec) noexcept; uintmax_t hard_link_count(const path& __p); uintmax_t hard_link_count(const path& __p, error_code& __ec) noexcept; inline bool is_block_file(file_status __s) noexcept { return __s.type() == file_type::block; } inline bool is_block_file(const path& __p) { return is_block_file(status(__p)); } inline bool is_block_file(const path& __p, error_code& __ec) noexcept { return is_block_file(status(__p, __ec)); } inline bool is_character_file(file_status __s) noexcept { return __s.type() == file_type::character; } inline bool is_character_file(const path& __p) { return is_character_file(status(__p)); } inline bool is_character_file(const path& __p, error_code& __ec) noexcept { return is_character_file(status(__p, __ec)); } inline bool is_directory(file_status __s) noexcept { return __s.type() == file_type::directory; } inline bool is_directory(const path& __p) { return is_directory(status(__p)); } inline bool is_directory(const path& __p, error_code& __ec) noexcept { return is_directory(status(__p, __ec)); } bool is_empty(const path& __p); bool is_empty(const path& __p, error_code& __ec); inline bool is_fifo(file_status __s) noexcept { return __s.type() == file_type::fifo; } inline bool is_fifo(const path& __p) { return is_fifo(status(__p)); } inline bool is_fifo(const path& __p, error_code& __ec) noexcept { return is_fifo(status(__p, __ec)); } inline bool is_other(file_status __s) noexcept { return exists(__s) && !is_regular_file(__s) && !is_directory(__s) && !is_symlink(__s); } inline bool is_other(const path& __p) { return is_other(status(__p)); } inline bool is_other(const path& __p, error_code& __ec) noexcept { return is_other(status(__p, __ec)); } inline bool is_regular_file(file_status __s) noexcept { return __s.type() == file_type::regular; } inline bool is_regular_file(const path& __p) { return is_regular_file(status(__p)); } inline bool is_regular_file(const path& __p, error_code& __ec) noexcept { return is_regular_file(status(__p, __ec)); } inline bool is_socket(file_status __s) noexcept { return __s.type() == file_type::socket; } inline bool is_socket(const path& __p) { return is_socket(status(__p)); } inline bool is_socket(const path& __p, error_code& __ec) noexcept { return is_socket(status(__p, __ec)); } inline bool is_symlink(file_status __s) noexcept { return __s.type() == file_type::symlink; } inline bool is_symlink(const path& __p) { return is_symlink(symlink_status(__p)); } inline bool is_symlink(const path& __p, error_code& __ec) noexcept { return is_symlink(symlink_status(__p, __ec)); } file_time_type last_write_time(const path& __p); file_time_type last_write_time(const path& __p, error_code& __ec) noexcept; void last_write_time(const path& __p, file_time_type __new_time); void last_write_time(const path& __p, file_time_type __new_time, error_code& __ec) noexcept; void permissions(const path& __p, perms __prms, perm_options __opts = perm_options::replace); inline void permissions(const path& __p, perms __prms, error_code& __ec) noexcept { permissions(__p, __prms, perm_options::replace, __ec); } void permissions(const path& __p, perms __prms, perm_options __opts, error_code& __ec) noexcept; inline path proximate(const path& __p, error_code& __ec) { return proximate(__p, current_path(), __ec); } path proximate(const path& __p, const path& __base = current_path()); path proximate(const path& __p, const path& __base, error_code& __ec); path read_symlink(const path& __p); path read_symlink(const path& __p, error_code& __ec); inline path relative(const path& __p, error_code& __ec) { return relative(__p, current_path(), __ec); } path relative(const path& __p, const path& __base = current_path()); path relative(const path& __p, const path& __base, error_code& __ec); bool remove(const path& __p); bool remove(const path& __p, error_code& __ec) noexcept; uintmax_t remove_all(const path& __p); uintmax_t remove_all(const path& __p, error_code& __ec); void rename(const path& __from, const path& __to); void rename(const path& __from, const path& __to, error_code& __ec) noexcept; void resize_file(const path& __p, uintmax_t __size); void resize_file(const path& __p, uintmax_t __size, error_code& __ec) noexcept; space_info space(const path& __p); space_info space(const path& __p, error_code& __ec) noexcept; file_status status(const path& __p); file_status status(const path& __p, error_code& __ec) noexcept; inline bool status_known(file_status __s) noexcept { return __s.type() != file_type::none; } file_status symlink_status(const path& __p); file_status symlink_status(const path& __p, error_code& __ec) noexcept; path temp_directory_path(); path temp_directory_path(error_code& __ec); path weakly_canonical(const path& __p); path weakly_canonical(const path& __p, error_code& __ec); // @} group filesystem } // namespace filesystem _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++17 #endif // _GLIBCXX_FS_OPS_H PK!?~~8/bits/fs_path.hnu[// Class filesystem::path -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/fs_path.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{filesystem} */ #ifndef _GLIBCXX_FS_PATH_H #define _GLIBCXX_FS_PATH_H 1 #if __cplusplus >= 201703L #include #include #include #include #include #include #include #include #include #include #include #if defined(_WIN32) && !defined(__CYGWIN__) # define _GLIBCXX_FILESYSTEM_IS_WINDOWS 1 # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace filesystem { _GLIBCXX_BEGIN_NAMESPACE_CXX11 /** * @ingroup filesystem * @{ */ /// A filesystem path. class path { template struct __is_encoded_char : std::false_type { }; template> using __is_path_iter_src = __and_<__is_encoded_char, std::is_base_of>; template static __is_path_iter_src<_Iter> __is_path_src(_Iter, int); template static __is_encoded_char<_CharT> __is_path_src(const basic_string<_CharT, _Traits, _Alloc>&, int); template static __is_encoded_char<_CharT> __is_path_src(const basic_string_view<_CharT, _Traits>&, int); template static std::false_type __is_path_src(const _Unknown&, ...); template struct __constructible_from; template struct __constructible_from<_Iter, _Iter> : __is_path_iter_src<_Iter> { }; template struct __constructible_from<_Source, void> : decltype(__is_path_src(std::declval<_Source>(), 0)) { }; template using _Path = typename std::enable_if<__and_<__not_, path>>, __not_>>, __constructible_from<_Tp1, _Tp2>>::value, path>::type; template static _Source _S_range_begin(_Source __begin) { return __begin; } struct __null_terminated { }; template static __null_terminated _S_range_end(_Source) { return {}; } template static const _CharT* _S_range_begin(const basic_string<_CharT, _Traits, _Alloc>& __str) { return __str.data(); } template static const _CharT* _S_range_end(const basic_string<_CharT, _Traits, _Alloc>& __str) { return __str.data() + __str.size(); } template static const _CharT* _S_range_begin(const basic_string_view<_CharT, _Traits>& __str) { return __str.data(); } template static const _CharT* _S_range_end(const basic_string_view<_CharT, _Traits>& __str) { return __str.data() + __str.size(); } template())), typename _Val = typename std::iterator_traits<_Iter>::value_type> using __value_type_is_char = typename std::enable_if::value>::type; public: #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS typedef wchar_t value_type; static constexpr value_type preferred_separator = L'\\'; #else typedef char value_type; static constexpr value_type preferred_separator = '/'; #endif typedef std::basic_string string_type; enum format { native_format, generic_format, auto_format }; // constructors and destructor path() noexcept { } path(const path& __p) = default; path(path&& __p) noexcept : _M_pathname(std::move(__p._M_pathname)), _M_type(__p._M_type) { if (_M_type == _Type::_Multi) _M_split_cmpts(); __p.clear(); } path(string_type&& __source, format = auto_format) : _M_pathname(std::move(__source)) { _M_split_cmpts(); } template> path(_Source const& __source, format = auto_format) : _M_pathname(_S_convert(_S_range_begin(__source), _S_range_end(__source))) { _M_split_cmpts(); } template> path(_InputIterator __first, _InputIterator __last, format = auto_format) : _M_pathname(_S_convert(__first, __last)) { _M_split_cmpts(); } template, typename _Require2 = __value_type_is_char<_Source>> path(_Source const& __source, const locale& __loc, format = auto_format) : _M_pathname(_S_convert_loc(_S_range_begin(__source), _S_range_end(__source), __loc)) { _M_split_cmpts(); } template, typename _Require2 = __value_type_is_char<_InputIterator>> path(_InputIterator __first, _InputIterator __last, const locale& __loc, format = auto_format) : _M_pathname(_S_convert_loc(__first, __last, __loc)) { _M_split_cmpts(); } ~path() = default; // assignments path& operator=(const path& __p) = default; path& operator=(path&& __p) noexcept; path& operator=(string_type&& __source); path& assign(string_type&& __source); template _Path<_Source>& operator=(_Source const& __source) { return *this = path(__source); } template _Path<_Source>& assign(_Source const& __source) { return *this = path(__source); } template _Path<_InputIterator, _InputIterator>& assign(_InputIterator __first, _InputIterator __last) { return *this = path(__first, __last); } // appends path& operator/=(const path& __p) { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS if (__p.is_absolute() || (__p.has_root_name() && __p.root_name() != root_name())) operator=(__p); else { string_type __pathname; if (__p.has_root_directory()) __pathname = root_name().native(); else if (has_filename() || (!has_root_directory() && is_absolute())) __pathname = _M_pathname + preferred_separator; __pathname += __p.relative_path().native(); // XXX is this right? _M_pathname.swap(__pathname); _M_split_cmpts(); } #else // Much simpler, as any path with root-name or root-dir is absolute. if (__p.is_absolute()) operator=(__p); else { if (has_filename() || (_M_type == _Type::_Root_name)) _M_pathname += preferred_separator; _M_pathname += __p.native(); _M_split_cmpts(); } #endif return *this; } template _Path<_Source>& operator/=(_Source const& __source) { return _M_append(path(__source)); } template _Path<_Source>& append(_Source const& __source) { return _M_append(path(__source)); } template _Path<_InputIterator, _InputIterator>& append(_InputIterator __first, _InputIterator __last) { return _M_append(path(__first, __last)); } // concatenation path& operator+=(const path& __x); path& operator+=(const string_type& __x); path& operator+=(const value_type* __x); path& operator+=(value_type __x); path& operator+=(basic_string_view __x); template _Path<_Source>& operator+=(_Source const& __x) { return concat(__x); } template _Path<_CharT*, _CharT*>& operator+=(_CharT __x); template _Path<_Source>& concat(_Source const& __x) { return *this += _S_convert(_S_range_begin(__x), _S_range_end(__x)); } template _Path<_InputIterator, _InputIterator>& concat(_InputIterator __first, _InputIterator __last) { return *this += _S_convert(__first, __last); } // modifiers void clear() noexcept { _M_pathname.clear(); _M_split_cmpts(); } path& make_preferred(); path& remove_filename(); path& replace_filename(const path& __replacement); path& replace_extension(const path& __replacement = path()); void swap(path& __rhs) noexcept; // native format observers const string_type& native() const noexcept { return _M_pathname; } const value_type* c_str() const noexcept { return _M_pathname.c_str(); } operator string_type() const { return _M_pathname; } template, typename _Allocator = std::allocator<_CharT>> std::basic_string<_CharT, _Traits, _Allocator> string(const _Allocator& __a = _Allocator()) const; std::string string() const; #if _GLIBCXX_USE_WCHAR_T std::wstring wstring() const; #endif std::string u8string() const; std::u16string u16string() const; std::u32string u32string() const; // generic format observers template, typename _Allocator = std::allocator<_CharT>> std::basic_string<_CharT, _Traits, _Allocator> generic_string(const _Allocator& __a = _Allocator()) const; std::string generic_string() const; #if _GLIBCXX_USE_WCHAR_T std::wstring generic_wstring() const; #endif std::string generic_u8string() const; std::u16string generic_u16string() const; std::u32string generic_u32string() const; // compare int compare(const path& __p) const noexcept; int compare(const string_type& __s) const; int compare(const value_type* __s) const; int compare(const basic_string_view __s) const; // decomposition path root_name() const; path root_directory() const; path root_path() const; path relative_path() const; path parent_path() const; path filename() const; path stem() const; path extension() const; // query [[nodiscard]] bool empty() const noexcept { return _M_pathname.empty(); } bool has_root_name() const; bool has_root_directory() const; bool has_root_path() const; bool has_relative_path() const; bool has_parent_path() const; bool has_filename() const; bool has_stem() const; bool has_extension() const; bool is_absolute() const { return has_root_directory(); } bool is_relative() const { return !is_absolute(); } // generation path lexically_normal() const; path lexically_relative(const path& base) const; path lexically_proximate(const path& base) const; // iterators class iterator; typedef iterator const_iterator; iterator begin() const; iterator end() const; private: enum class _Type : unsigned char { _Multi, _Root_name, _Root_dir, _Filename }; path(string_type __str, _Type __type) : _M_pathname(__str), _M_type(__type) { __glibcxx_assert(_M_type != _Type::_Multi); } enum class _Split { _Stem, _Extension }; path& _M_append(path __p) { if (__p.is_absolute()) operator=(std::move(__p)); #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS else if (__p.has_root_name() && __p.root_name() != root_name()) operator=(std::move(__p)); #endif else operator/=(const_cast(__p)); return *this; } pair _M_find_extension() const; template struct _Cvt; static string_type _S_convert(value_type* __src, __null_terminated) { return string_type(__src); } static string_type _S_convert(const value_type* __src, __null_terminated) { return string_type(__src); } template static string_type _S_convert(_Iter __first, _Iter __last) { using __value_type = typename std::iterator_traits<_Iter>::value_type; return _Cvt::type>:: _S_convert(__first, __last); } template static string_type _S_convert(_InputIterator __src, __null_terminated) { using _Tp = typename std::iterator_traits<_InputIterator>::value_type; std::basic_string::type> __tmp; for (; *__src != _Tp{}; ++__src) __tmp.push_back(*__src); return _S_convert(__tmp.c_str(), __tmp.c_str() + __tmp.size()); } static string_type _S_convert_loc(const char* __first, const char* __last, const std::locale& __loc); template static string_type _S_convert_loc(_Iter __first, _Iter __last, const std::locale& __loc) { const std::string __str(__first, __last); return _S_convert_loc(__str.data(), __str.data()+__str.size(), __loc); } template static string_type _S_convert_loc(_InputIterator __src, __null_terminated, const std::locale& __loc) { std::string __tmp; while (*__src != '\0') __tmp.push_back(*__src++); return _S_convert_loc(__tmp.data(), __tmp.data()+__tmp.size(), __loc); } template static basic_string<_CharT, _Traits, _Allocator> _S_str_convert(basic_string_view, const _Allocator&); static bool _S_is_dir_sep(value_type __ch) { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS return __ch == L'/' || __ch == preferred_separator; #else return __ch == '/'; #endif } void _M_split_cmpts(); void _M_trim(); void _M_add_root_name(size_t __n); void _M_add_root_dir(size_t __pos); void _M_add_filename(size_t __pos, size_t __n); string_type _M_pathname; struct _Cmpt; using _List = _GLIBCXX_STD_C::vector<_Cmpt>; _List _M_cmpts; // empty unless _M_type == _Type::_Multi _Type _M_type = _Type::_Filename; }; template<> struct path::__is_encoded_char : std::true_type { using value_type = char; }; template<> struct path::__is_encoded_char : std::true_type { using value_type = wchar_t; }; template<> struct path::__is_encoded_char : std::true_type { using value_type = char16_t; }; template<> struct path::__is_encoded_char : std::true_type { using value_type = char32_t; }; template struct path::__is_encoded_char : __is_encoded_char<_Tp> { }; inline void swap(path& __lhs, path& __rhs) noexcept { __lhs.swap(__rhs); } size_t hash_value(const path& __p) noexcept; /// Compare paths inline bool operator<(const path& __lhs, const path& __rhs) noexcept { return __lhs.compare(__rhs) < 0; } /// Compare paths inline bool operator<=(const path& __lhs, const path& __rhs) noexcept { return !(__rhs < __lhs); } /// Compare paths inline bool operator>(const path& __lhs, const path& __rhs) noexcept { return __rhs < __lhs; } /// Compare paths inline bool operator>=(const path& __lhs, const path& __rhs) noexcept { return !(__lhs < __rhs); } /// Compare paths inline bool operator==(const path& __lhs, const path& __rhs) noexcept { return __lhs.compare(__rhs) == 0; } /// Compare paths inline bool operator!=(const path& __lhs, const path& __rhs) noexcept { return !(__lhs == __rhs); } /// Append one path to another inline path operator/(const path& __lhs, const path& __rhs) { path __result(__lhs); __result /= __rhs; return __result; } /// Write a path to a stream template basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, const path& __p) { auto __tmp = __p.string<_CharT, _Traits>(); using __quoted_string = std::__detail::_Quoted_string; __os << __quoted_string{__tmp, '"', '\\'}; return __os; } /// Read a path from a stream template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __is, path& __p) { basic_string<_CharT, _Traits> __tmp; using __quoted_string = std::__detail::_Quoted_string; if (__is >> __quoted_string{ __tmp, '"', '\\' }) __p = std::move(__tmp); return __is; } template inline auto u8path(const _Source& __source) -> decltype(filesystem::path(__source, std::locale::classic())) { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS const std::string __u8str{__source}; return std::filesystem::u8path(__u8str.begin(), __u8str.end()); #else return path{ __source }; #endif } template inline auto u8path(_InputIterator __first, _InputIterator __last) -> decltype(filesystem::path(__first, __last, std::locale::classic())) { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS codecvt_utf8 __cvt; string_type __tmp; if (__str_codecvt_in(__first, __last, __tmp, __cvt)) return path{ __tmp }; else return {}; #else return path{ __first, __last }; #endif } class filesystem_error : public std::system_error { public: filesystem_error(const string& __what_arg, error_code __ec) : system_error(__ec, __what_arg) { } filesystem_error(const string& __what_arg, const path& __p1, error_code __ec) : system_error(__ec, __what_arg), _M_path1(__p1) { } filesystem_error(const string& __what_arg, const path& __p1, const path& __p2, error_code __ec) : system_error(__ec, __what_arg), _M_path1(__p1), _M_path2(__p2) { } ~filesystem_error(); const path& path1() const noexcept { return _M_path1; } const path& path2() const noexcept { return _M_path2; } const char* what() const noexcept { return _M_what.c_str(); } private: std::string _M_gen_what(); path _M_path1; path _M_path2; std::string _M_what = _M_gen_what(); }; struct path::_Cmpt : path { _Cmpt(string_type __s, _Type __t, size_t __pos) : path(std::move(__s), __t), _M_pos(__pos) { } _Cmpt() : _M_pos(-1) { } size_t _M_pos; }; // specialize _Cvt for degenerate 'noconv' case template<> struct path::_Cvt { template static string_type _S_convert(_Iter __first, _Iter __last) { return string_type{__first, __last}; } }; template struct path::_Cvt { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS static string_type _S_wconvert(const char* __f, const char* __l, true_type) { using _Cvt = std::codecvt; const auto& __cvt = std::use_facet<_Cvt>(std::locale{}); std::wstring __wstr; if (__str_codecvt_in(__f, __l, __wstr, __cvt)) return __wstr; _GLIBCXX_THROW_OR_ABORT(filesystem_error( "Cannot convert character sequence", std::make_error_code(errc::illegal_byte_sequence))); } static string_type _S_wconvert(const _CharT* __f, const _CharT* __l, false_type) { std::codecvt_utf8<_CharT> __cvt; std::string __str; if (__str_codecvt_out(__f, __l, __str, __cvt)) { const char* __f2 = __str.data(); const char* __l2 = __f2 + __str.size(); std::codecvt_utf8 __wcvt; std::wstring __wstr; if (__str_codecvt_in(__f2, __l2, __wstr, __wcvt)) return __wstr; } _GLIBCXX_THROW_OR_ABORT(filesystem_error( "Cannot convert character sequence", std::make_error_code(errc::illegal_byte_sequence))); } static string_type _S_convert(const _CharT* __f, const _CharT* __l) { return _S_wconvert(__f, __l, is_same<_CharT, char>{}); } #else static string_type _S_convert(const _CharT* __f, const _CharT* __l) { std::codecvt_utf8<_CharT> __cvt; std::string __str; if (__str_codecvt_out(__f, __l, __str, __cvt)) return __str; _GLIBCXX_THROW_OR_ABORT(filesystem_error( "Cannot convert character sequence", std::make_error_code(errc::illegal_byte_sequence))); } #endif static string_type _S_convert(_CharT* __f, _CharT* __l) { return _S_convert(const_cast(__f), const_cast(__l)); } template static string_type _S_convert(_Iter __first, _Iter __last) { const std::basic_string<_CharT> __str(__first, __last); return _S_convert(__str.data(), __str.data() + __str.size()); } template static string_type _S_convert(__gnu_cxx::__normal_iterator<_Iter, _Cont> __first, __gnu_cxx::__normal_iterator<_Iter, _Cont> __last) { return _S_convert(__first.base(), __last.base()); } }; /// An iterator for the components of a path class path::iterator { public: using difference_type = std::ptrdiff_t; using value_type = path; using reference = const path&; using pointer = const path*; using iterator_category = std::bidirectional_iterator_tag; iterator() : _M_path(nullptr), _M_cur(), _M_at_end() { } iterator(const iterator&) = default; iterator& operator=(const iterator&) = default; reference operator*() const; pointer operator->() const { return std::__addressof(**this); } iterator& operator++(); iterator operator++(int) { auto __tmp = *this; ++*this; return __tmp; } iterator& operator--(); iterator operator--(int) { auto __tmp = *this; --*this; return __tmp; } friend bool operator==(const iterator& __lhs, const iterator& __rhs) { return __lhs._M_equals(__rhs); } friend bool operator!=(const iterator& __lhs, const iterator& __rhs) { return !__lhs._M_equals(__rhs); } private: friend class path; iterator(const path* __path, path::_List::const_iterator __iter) : _M_path(__path), _M_cur(__iter), _M_at_end() { } iterator(const path* __path, bool __at_end) : _M_path(__path), _M_cur(), _M_at_end(__at_end) { } bool _M_equals(iterator) const; const path* _M_path; path::_List::const_iterator _M_cur; bool _M_at_end; // only used when type != _Multi }; inline path& path::operator=(path&& __p) noexcept { if (&__p == this) return *this; _M_pathname = std::move(__p._M_pathname); _M_cmpts = std::move(__p._M_cmpts); _M_type = __p._M_type; __p.clear(); return *this; } inline path& path::operator=(string_type&& __source) { return *this = path(std::move(__source)); } inline path& path::assign(string_type&& __source) { return *this = path(std::move(__source)); } inline path& path::operator+=(const path& __p) { return operator+=(__p.native()); } inline path& path::operator+=(const string_type& __x) { _M_pathname += __x; _M_split_cmpts(); return *this; } inline path& path::operator+=(const value_type* __x) { _M_pathname += __x; _M_split_cmpts(); return *this; } inline path& path::operator+=(value_type __x) { _M_pathname += __x; _M_split_cmpts(); return *this; } inline path& path::operator+=(basic_string_view __x) { _M_pathname.append(__x.data(), __x.size()); _M_split_cmpts(); return *this; } template inline path::_Path<_CharT*, _CharT*>& path::operator+=(_CharT __x) { auto* __addr = std::__addressof(__x); return concat(__addr, __addr + 1); } inline path& path::make_preferred() { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS std::replace(_M_pathname.begin(), _M_pathname.end(), L'/', preferred_separator); #endif return *this; } inline void path::swap(path& __rhs) noexcept { _M_pathname.swap(__rhs._M_pathname); _M_cmpts.swap(__rhs._M_cmpts); std::swap(_M_type, __rhs._M_type); } template std::basic_string<_CharT, _Traits, _Allocator> path::_S_str_convert(basic_string_view __str, const _Allocator& __a) { if (__str.size() == 0) return std::basic_string<_CharT, _Traits, _Allocator>(__a); const value_type* __first = __str.data(); const value_type* __last = __first + __str.size(); #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS using _CharAlloc = __alloc_rebind<_Allocator, char>; using _String = basic_string, _CharAlloc>; using _WString = basic_string<_CharT, _Traits, _Allocator>; // use codecvt_utf8 to convert native string to UTF-8 codecvt_utf8 __cvt; _String __u8str{_CharAlloc{__a}}; if (__str_codecvt_out(__first, __last, __u8str, __cvt)) { if constexpr (is_same_v<_CharT, char>) return __u8str; else { _WString __wstr; // use codecvt_utf8<_CharT> to convert UTF-8 to wide string codecvt_utf8<_CharT> __cvt; const char* __f = __u8str.data(); const char* __l = __f + __u8str.size(); if (__str_codecvt_in(__f, __l, __wstr, __cvt)) return __wstr; } } #else codecvt_utf8<_CharT> __cvt; basic_string<_CharT, _Traits, _Allocator> __wstr{__a}; if (__str_codecvt_in(__first, __last, __wstr, __cvt)) return __wstr; #endif _GLIBCXX_THROW_OR_ABORT(filesystem_error( "Cannot convert character sequence", std::make_error_code(errc::illegal_byte_sequence))); } template inline basic_string<_CharT, _Traits, _Allocator> path::string(const _Allocator& __a) const { if constexpr (is_same_v<_CharT, value_type>) #if _GLIBCXX_USE_CXX11_ABI return { _M_pathname, __a }; #else return { _M_pathname, string_type::size_type(0), __a }; #endif else return _S_str_convert<_CharT, _Traits>(_M_pathname, __a); } inline std::string path::string() const { return string(); } #if _GLIBCXX_USE_WCHAR_T inline std::wstring path::wstring() const { return string(); } #endif inline std::string path::u8string() const { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS std::string __str; // convert from native encoding to UTF-8 codecvt_utf8 __cvt; const value_type* __first = _M_pathname.data(); const value_type* __last = __first + _M_pathname.size(); if (__str_codecvt_out(__first, __last, __str, __cvt)) return __str; _GLIBCXX_THROW_OR_ABORT(filesystem_error( "Cannot convert character sequence", std::make_error_code(errc::illegal_byte_sequence))); #else return _M_pathname; #endif } inline std::u16string path::u16string() const { return string(); } inline std::u32string path::u32string() const { return string(); } template inline std::basic_string<_CharT, _Traits, _Allocator> path::generic_string(const _Allocator& __a) const { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS const value_type __slash = L'/'; #else const value_type __slash = '/'; #endif using _Alloc2 = typename allocator_traits<_Allocator>::template rebind_alloc; basic_string, _Alloc2> __str(__a); if (_M_type == _Type::_Root_dir) __str.assign(1, __slash); else { __str.reserve(_M_pathname.size()); bool __add_slash = false; for (auto& __elem : *this) { if (__add_slash) __str += __slash; __str += basic_string_view(__elem._M_pathname); __add_slash = __elem._M_type == _Type::_Filename; } } if constexpr (is_same_v<_CharT, value_type>) return __str; else return _S_str_convert<_CharT, _Traits>(__str, __a); } inline std::string path::generic_string() const { return generic_string(); } #if _GLIBCXX_USE_WCHAR_T inline std::wstring path::generic_wstring() const { return generic_string(); } #endif inline std::string path::generic_u8string() const { return generic_string(); } inline std::u16string path::generic_u16string() const { return generic_string(); } inline std::u32string path::generic_u32string() const { return generic_string(); } inline int path::compare(const string_type& __s) const { return compare(path(__s)); } inline int path::compare(const value_type* __s) const { return compare(path(__s)); } inline int path::compare(basic_string_view __s) const { return compare(path(__s)); } inline path path::filename() const { if (empty()) return {}; else if (_M_type == _Type::_Filename) return *this; else if (_M_type == _Type::_Multi) { if (_M_pathname.back() == preferred_separator) return {}; auto& __last = *--end(); if (__last._M_type == _Type::_Filename) return __last; } return {}; } inline path path::stem() const { auto ext = _M_find_extension(); if (ext.first && ext.second != 0) return path{ext.first->substr(0, ext.second)}; return {}; } inline path path::extension() const { auto ext = _M_find_extension(); if (ext.first && ext.second != string_type::npos) return path{ext.first->substr(ext.second)}; return {}; } inline bool path::has_stem() const { auto ext = _M_find_extension(); return ext.first && ext.second != 0; } inline bool path::has_extension() const { auto ext = _M_find_extension(); return ext.first && ext.second != string_type::npos; } inline path::iterator path::begin() const { if (_M_type == _Type::_Multi) return iterator(this, _M_cmpts.begin()); return iterator(this, empty()); } inline path::iterator path::end() const { if (_M_type == _Type::_Multi) return iterator(this, _M_cmpts.end()); return iterator(this, true); } inline path::iterator& path::iterator::operator++() { __glibcxx_assert(_M_path != nullptr); if (_M_path->_M_type == _Type::_Multi) { __glibcxx_assert(_M_cur != _M_path->_M_cmpts.end()); ++_M_cur; } else { __glibcxx_assert(!_M_at_end); _M_at_end = true; } return *this; } inline path::iterator& path::iterator::operator--() { __glibcxx_assert(_M_path != nullptr); if (_M_path->_M_type == _Type::_Multi) { __glibcxx_assert(_M_cur != _M_path->_M_cmpts.begin()); --_M_cur; } else { __glibcxx_assert(_M_at_end); _M_at_end = false; } return *this; } inline path::iterator::reference path::iterator::operator*() const { __glibcxx_assert(_M_path != nullptr); if (_M_path->_M_type == _Type::_Multi) { __glibcxx_assert(_M_cur != _M_path->_M_cmpts.end()); return *_M_cur; } return *_M_path; } inline bool path::iterator::_M_equals(iterator __rhs) const { if (_M_path != __rhs._M_path) return false; if (_M_path == nullptr) return true; if (_M_path->_M_type == path::_Type::_Multi) return _M_cur == __rhs._M_cur; return _M_at_end == __rhs._M_at_end; } // @} group filesystem _GLIBCXX_END_NAMESPACE_CXX11 } // namespace filesystem _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++17 #endif // _GLIBCXX_FS_PATH_H PK!W8/bits/fstream.tccnu[// File based streams -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/fstream.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{fstream} */ // // ISO C++ 14882: 27.8 File-based streams // #ifndef _FSTREAM_TCC #define _FSTREAM_TCC 1 #pragma GCC system_header #include #include // for swap namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template void basic_filebuf<_CharT, _Traits>:: _M_allocate_internal_buffer() { // Allocate internal buffer only if one doesn't already exist // (either allocated or provided by the user via setbuf). if (!_M_buf_allocated && !_M_buf) { _M_buf = new char_type[_M_buf_size]; _M_buf_allocated = true; } } template void basic_filebuf<_CharT, _Traits>:: _M_destroy_internal_buffer() throw() { if (_M_buf_allocated) { delete [] _M_buf; _M_buf = 0; _M_buf_allocated = false; } delete [] _M_ext_buf; _M_ext_buf = 0; _M_ext_buf_size = 0; _M_ext_next = 0; _M_ext_end = 0; } template basic_filebuf<_CharT, _Traits>:: basic_filebuf() : __streambuf_type(), _M_lock(), _M_file(&_M_lock), _M_mode(ios_base::openmode(0)), _M_state_beg(), _M_state_cur(), _M_state_last(), _M_buf(0), _M_buf_size(BUFSIZ), _M_buf_allocated(false), _M_reading(false), _M_writing(false), _M_pback(), _M_pback_cur_save(0), _M_pback_end_save(0), _M_pback_init(false), _M_codecvt(0), _M_ext_buf(0), _M_ext_buf_size(0), _M_ext_next(0), _M_ext_end(0) { if (has_facet<__codecvt_type>(this->_M_buf_locale)) _M_codecvt = &use_facet<__codecvt_type>(this->_M_buf_locale); } #if __cplusplus >= 201103L template basic_filebuf<_CharT, _Traits>:: basic_filebuf(basic_filebuf&& __rhs) : __streambuf_type(__rhs), _M_lock(), _M_file(std::move(__rhs._M_file), &_M_lock), _M_mode(std::__exchange(__rhs._M_mode, ios_base::openmode(0))), _M_state_beg(std::move(__rhs._M_state_beg)), _M_state_cur(std::move(__rhs._M_state_cur)), _M_state_last(std::move(__rhs._M_state_last)), _M_buf(std::__exchange(__rhs._M_buf, nullptr)), _M_buf_size(std::__exchange(__rhs._M_buf_size, 1)), _M_buf_allocated(std::__exchange(__rhs._M_buf_allocated, false)), _M_reading(std::__exchange(__rhs._M_reading, false)), _M_writing(std::__exchange(__rhs._M_writing, false)), _M_pback(__rhs._M_pback), _M_pback_cur_save(std::__exchange(__rhs._M_pback_cur_save, nullptr)), _M_pback_end_save(std::__exchange(__rhs._M_pback_end_save, nullptr)), _M_pback_init(std::__exchange(__rhs._M_pback_init, false)), _M_codecvt(__rhs._M_codecvt), _M_ext_buf(std::__exchange(__rhs._M_ext_buf, nullptr)), _M_ext_buf_size(std::__exchange(__rhs._M_ext_buf_size, 0)), _M_ext_next(std::__exchange(__rhs._M_ext_next, nullptr)), _M_ext_end(std::__exchange(__rhs._M_ext_end, nullptr)) { __rhs._M_set_buffer(-1); __rhs._M_state_last = __rhs._M_state_cur = __rhs._M_state_beg; } template basic_filebuf<_CharT, _Traits>& basic_filebuf<_CharT, _Traits>:: operator=(basic_filebuf&& __rhs) { this->close(); __streambuf_type::operator=(__rhs); _M_file.swap(__rhs._M_file); _M_mode = std::__exchange(__rhs._M_mode, ios_base::openmode(0)); _M_state_beg = std::move(__rhs._M_state_beg); _M_state_cur = std::move(__rhs._M_state_cur); _M_state_last = std::move(__rhs._M_state_last); _M_buf = std::__exchange(__rhs._M_buf, nullptr); _M_buf_size = std::__exchange(__rhs._M_buf_size, 1); _M_buf_allocated = std::__exchange(__rhs._M_buf_allocated, false); _M_ext_buf = std::__exchange(__rhs._M_ext_buf, nullptr); _M_ext_buf_size = std::__exchange(__rhs._M_ext_buf_size, 0); _M_ext_next = std::__exchange(__rhs._M_ext_next, nullptr); _M_ext_end = std::__exchange(__rhs._M_ext_end, nullptr); _M_reading = std::__exchange(__rhs._M_reading, false); _M_writing = std::__exchange(__rhs._M_writing, false); _M_pback_cur_save = std::__exchange(__rhs._M_pback_cur_save, nullptr); _M_pback_end_save = std::__exchange(__rhs._M_pback_end_save, nullptr); _M_pback_init = std::__exchange(__rhs._M_pback_init, false); __rhs._M_set_buffer(-1); __rhs._M_state_last = __rhs._M_state_cur = __rhs._M_state_beg; return *this; } template void basic_filebuf<_CharT, _Traits>:: swap(basic_filebuf& __rhs) { __streambuf_type::swap(__rhs); _M_file.swap(__rhs._M_file); std::swap(_M_mode, __rhs._M_mode); std::swap(_M_state_beg, __rhs._M_state_beg); std::swap(_M_state_cur, __rhs._M_state_cur); std::swap(_M_state_last, __rhs._M_state_last); std::swap(_M_buf, __rhs._M_buf); std::swap(_M_buf_size, __rhs._M_buf_size); std::swap(_M_buf_allocated, __rhs._M_buf_allocated); std::swap(_M_ext_buf, __rhs._M_ext_buf); std::swap(_M_ext_buf_size, __rhs._M_ext_buf_size); std::swap(_M_ext_next, __rhs._M_ext_next); std::swap(_M_ext_end, __rhs._M_ext_end); std::swap(_M_reading, __rhs._M_reading); std::swap(_M_writing, __rhs._M_writing); std::swap(_M_pback_cur_save, __rhs._M_pback_cur_save); std::swap(_M_pback_end_save, __rhs._M_pback_end_save); std::swap(_M_pback_init, __rhs._M_pback_init); } #endif template typename basic_filebuf<_CharT, _Traits>::__filebuf_type* basic_filebuf<_CharT, _Traits>:: open(const char* __s, ios_base::openmode __mode) { __filebuf_type *__ret = 0; if (!this->is_open()) { _M_file.open(__s, __mode); if (this->is_open()) { _M_allocate_internal_buffer(); _M_mode = __mode; // Setup initial buffer to 'uncommitted' mode. _M_reading = false; _M_writing = false; _M_set_buffer(-1); // Reset to initial state. _M_state_last = _M_state_cur = _M_state_beg; // 27.8.1.3,4 if ((__mode & ios_base::ate) && this->seekoff(0, ios_base::end, __mode) == pos_type(off_type(-1))) this->close(); else __ret = this; } } return __ret; } template typename basic_filebuf<_CharT, _Traits>::__filebuf_type* basic_filebuf<_CharT, _Traits>:: close() { if (!this->is_open()) return 0; bool __testfail = false; { // NB: Do this here so that re-opened filebufs will be cool... struct __close_sentry { basic_filebuf *__fb; __close_sentry (basic_filebuf *__fbi): __fb(__fbi) { } ~__close_sentry () { __fb->_M_mode = ios_base::openmode(0); __fb->_M_pback_init = false; __fb->_M_destroy_internal_buffer(); __fb->_M_reading = false; __fb->_M_writing = false; __fb->_M_set_buffer(-1); __fb->_M_state_last = __fb->_M_state_cur = __fb->_M_state_beg; } } __cs (this); __try { if (!_M_terminate_output()) __testfail = true; } __catch(__cxxabiv1::__forced_unwind&) { _M_file.close(); __throw_exception_again; } __catch(...) { __testfail = true; } } if (!_M_file.close()) __testfail = true; if (__testfail) return 0; else return this; } template streamsize basic_filebuf<_CharT, _Traits>:: showmanyc() { streamsize __ret = -1; const bool __testin = _M_mode & ios_base::in; if (__testin && this->is_open()) { // For a stateful encoding (-1) the pending sequence might be just // shift and unshift prefixes with no actual character. __ret = this->egptr() - this->gptr(); #if _GLIBCXX_HAVE_DOS_BASED_FILESYSTEM // About this workaround, see libstdc++/20806. const bool __testbinary = _M_mode & ios_base::binary; if (__check_facet(_M_codecvt).encoding() >= 0 && __testbinary) #else if (__check_facet(_M_codecvt).encoding() >= 0) #endif __ret += _M_file.showmanyc() / _M_codecvt->max_length(); } return __ret; } template typename basic_filebuf<_CharT, _Traits>::int_type basic_filebuf<_CharT, _Traits>:: underflow() { int_type __ret = traits_type::eof(); const bool __testin = _M_mode & ios_base::in; if (__testin) { if (_M_writing) { if (overflow() == traits_type::eof()) return __ret; _M_set_buffer(-1); _M_writing = false; } // Check for pback madness, and if so switch back to the // normal buffers and jet outta here before expensive // fileops happen... _M_destroy_pback(); if (this->gptr() < this->egptr()) return traits_type::to_int_type(*this->gptr()); // Get and convert input sequence. const size_t __buflen = _M_buf_size > 1 ? _M_buf_size - 1 : 1; // Will be set to true if ::read() returns 0 indicating EOF. bool __got_eof = false; // Number of internal characters produced. streamsize __ilen = 0; codecvt_base::result __r = codecvt_base::ok; if (__check_facet(_M_codecvt).always_noconv()) { __ilen = _M_file.xsgetn(reinterpret_cast(this->eback()), __buflen); if (__ilen == 0) __got_eof = true; } else { // Worst-case number of external bytes. // XXX Not done encoding() == -1. const int __enc = _M_codecvt->encoding(); streamsize __blen; // Minimum buffer size. streamsize __rlen; // Number of chars to read. if (__enc > 0) __blen = __rlen = __buflen * __enc; else { __blen = __buflen + _M_codecvt->max_length() - 1; __rlen = __buflen; } const streamsize __remainder = _M_ext_end - _M_ext_next; __rlen = __rlen > __remainder ? __rlen - __remainder : 0; // An imbue in 'read' mode implies first converting the external // chars already present. if (_M_reading && this->egptr() == this->eback() && __remainder) __rlen = 0; // Allocate buffer if necessary and move unconverted // bytes to front. if (_M_ext_buf_size < __blen) { char* __buf = new char[__blen]; if (__remainder) __builtin_memcpy(__buf, _M_ext_next, __remainder); delete [] _M_ext_buf; _M_ext_buf = __buf; _M_ext_buf_size = __blen; } else if (__remainder) __builtin_memmove(_M_ext_buf, _M_ext_next, __remainder); _M_ext_next = _M_ext_buf; _M_ext_end = _M_ext_buf + __remainder; _M_state_last = _M_state_cur; do { if (__rlen > 0) { // Sanity check! // This may fail if the return value of // codecvt::max_length() is bogus. if (_M_ext_end - _M_ext_buf + __rlen > _M_ext_buf_size) { __throw_ios_failure(__N("basic_filebuf::underflow " "codecvt::max_length() " "is not valid")); } streamsize __elen = _M_file.xsgetn(_M_ext_end, __rlen); if (__elen == 0) __got_eof = true; else if (__elen == -1) break; _M_ext_end += __elen; } char_type* __iend = this->eback(); if (_M_ext_next < _M_ext_end) __r = _M_codecvt->in(_M_state_cur, _M_ext_next, _M_ext_end, _M_ext_next, this->eback(), this->eback() + __buflen, __iend); if (__r == codecvt_base::noconv) { size_t __avail = _M_ext_end - _M_ext_buf; __ilen = std::min(__avail, __buflen); traits_type::copy(this->eback(), reinterpret_cast (_M_ext_buf), __ilen); _M_ext_next = _M_ext_buf + __ilen; } else __ilen = __iend - this->eback(); // _M_codecvt->in may return error while __ilen > 0: this is // ok, and actually occurs in case of mixed encodings (e.g., // XML files). if (__r == codecvt_base::error) break; __rlen = 1; } while (__ilen == 0 && !__got_eof); } if (__ilen > 0) { _M_set_buffer(__ilen); _M_reading = true; __ret = traits_type::to_int_type(*this->gptr()); } else if (__got_eof) { // If the actual end of file is reached, set 'uncommitted' // mode, thus allowing an immediate write without an // intervening seek. _M_set_buffer(-1); _M_reading = false; // However, reaching it while looping on partial means that // the file has got an incomplete character. if (__r == codecvt_base::partial) __throw_ios_failure(__N("basic_filebuf::underflow " "incomplete character in file")); } else if (__r == codecvt_base::error) __throw_ios_failure(__N("basic_filebuf::underflow " "invalid byte sequence in file")); else __throw_ios_failure(__N("basic_filebuf::underflow " "error reading the file")); } return __ret; } template typename basic_filebuf<_CharT, _Traits>::int_type basic_filebuf<_CharT, _Traits>:: pbackfail(int_type __i) { int_type __ret = traits_type::eof(); const bool __testin = _M_mode & ios_base::in; if (__testin) { if (_M_writing) { if (overflow() == traits_type::eof()) return __ret; _M_set_buffer(-1); _M_writing = false; } // Remember whether the pback buffer is active, otherwise below // we may try to store in it a second char (libstdc++/9761). const bool __testpb = _M_pback_init; const bool __testeof = traits_type::eq_int_type(__i, __ret); int_type __tmp; if (this->eback() < this->gptr()) { this->gbump(-1); __tmp = traits_type::to_int_type(*this->gptr()); } else if (this->seekoff(-1, ios_base::cur) != pos_type(off_type(-1))) { __tmp = this->underflow(); if (traits_type::eq_int_type(__tmp, __ret)) return __ret; } else { // At the beginning of the buffer, need to make a // putback position available. But the seek may fail // (f.i., at the beginning of a file, see // libstdc++/9439) and in that case we return // traits_type::eof(). return __ret; } // Try to put back __i into input sequence in one of three ways. // Order these tests done in is unspecified by the standard. if (!__testeof && traits_type::eq_int_type(__i, __tmp)) __ret = __i; else if (__testeof) __ret = traits_type::not_eof(__i); else if (!__testpb) { _M_create_pback(); _M_reading = true; *this->gptr() = traits_type::to_char_type(__i); __ret = __i; } } return __ret; } template typename basic_filebuf<_CharT, _Traits>::int_type basic_filebuf<_CharT, _Traits>:: overflow(int_type __c) { int_type __ret = traits_type::eof(); const bool __testeof = traits_type::eq_int_type(__c, __ret); const bool __testout = (_M_mode & ios_base::out || _M_mode & ios_base::app); if (__testout) { if (_M_reading) { _M_destroy_pback(); const int __gptr_off = _M_get_ext_pos(_M_state_last); if (_M_seek(__gptr_off, ios_base::cur, _M_state_last) == pos_type(off_type(-1))) return __ret; } if (this->pbase() < this->pptr()) { // If appropriate, append the overflow char. if (!__testeof) { *this->pptr() = traits_type::to_char_type(__c); this->pbump(1); } // Convert pending sequence to external representation, // and output. if (_M_convert_to_external(this->pbase(), this->pptr() - this->pbase())) { _M_set_buffer(0); __ret = traits_type::not_eof(__c); } } else if (_M_buf_size > 1) { // Overflow in 'uncommitted' mode: set _M_writing, set // the buffer to the initial 'write' mode, and put __c // into the buffer. _M_set_buffer(0); _M_writing = true; if (!__testeof) { *this->pptr() = traits_type::to_char_type(__c); this->pbump(1); } __ret = traits_type::not_eof(__c); } else { // Unbuffered. char_type __conv = traits_type::to_char_type(__c); if (__testeof || _M_convert_to_external(&__conv, 1)) { _M_writing = true; __ret = traits_type::not_eof(__c); } } } return __ret; } template bool basic_filebuf<_CharT, _Traits>:: _M_convert_to_external(_CharT* __ibuf, streamsize __ilen) { // Sizes of external and pending output. streamsize __elen; streamsize __plen; if (__check_facet(_M_codecvt).always_noconv()) { __elen = _M_file.xsputn(reinterpret_cast(__ibuf), __ilen); __plen = __ilen; } else { // Worst-case number of external bytes needed. // XXX Not done encoding() == -1. streamsize __blen = __ilen * _M_codecvt->max_length(); char* __buf = static_cast(__builtin_alloca(__blen)); char* __bend; const char_type* __iend; codecvt_base::result __r; __r = _M_codecvt->out(_M_state_cur, __ibuf, __ibuf + __ilen, __iend, __buf, __buf + __blen, __bend); if (__r == codecvt_base::ok || __r == codecvt_base::partial) __blen = __bend - __buf; else if (__r == codecvt_base::noconv) { // Same as the always_noconv case above. __buf = reinterpret_cast(__ibuf); __blen = __ilen; } else __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external " "conversion error")); __elen = _M_file.xsputn(__buf, __blen); __plen = __blen; // Try once more for partial conversions. if (__r == codecvt_base::partial && __elen == __plen) { const char_type* __iresume = __iend; streamsize __rlen = this->pptr() - __iend; __r = _M_codecvt->out(_M_state_cur, __iresume, __iresume + __rlen, __iend, __buf, __buf + __blen, __bend); if (__r != codecvt_base::error) { __rlen = __bend - __buf; __elen = _M_file.xsputn(__buf, __rlen); __plen = __rlen; } else __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external " "conversion error")); } } return __elen == __plen; } template streamsize basic_filebuf<_CharT, _Traits>:: xsgetn(_CharT* __s, streamsize __n) { // Clear out pback buffer before going on to the real deal... streamsize __ret = 0; if (_M_pback_init) { if (__n > 0 && this->gptr() == this->eback()) { *__s++ = *this->gptr(); // emulate non-underflowing sbumpc this->gbump(1); __ret = 1; --__n; } _M_destroy_pback(); } else if (_M_writing) { if (overflow() == traits_type::eof()) return __ret; _M_set_buffer(-1); _M_writing = false; } // Optimization in the always_noconv() case, to be generalized in the // future: when __n > __buflen we read directly instead of using the // buffer repeatedly. const bool __testin = _M_mode & ios_base::in; const streamsize __buflen = _M_buf_size > 1 ? _M_buf_size - 1 : 1; if (__n > __buflen && __check_facet(_M_codecvt).always_noconv() && __testin) { // First, copy the chars already present in the buffer. const streamsize __avail = this->egptr() - this->gptr(); if (__avail != 0) { traits_type::copy(__s, this->gptr(), __avail); __s += __avail; this->setg(this->eback(), this->gptr() + __avail, this->egptr()); __ret += __avail; __n -= __avail; } // Need to loop in case of short reads (relatively common // with pipes). streamsize __len; for (;;) { __len = _M_file.xsgetn(reinterpret_cast(__s), __n); if (__len == -1) __throw_ios_failure(__N("basic_filebuf::xsgetn " "error reading the file")); if (__len == 0) break; __n -= __len; __ret += __len; if (__n == 0) break; __s += __len; } if (__n == 0) { // Set _M_reading. Buffer is already in initial 'read' mode. _M_reading = true; } else if (__len == 0) { // If end of file is reached, set 'uncommitted' // mode, thus allowing an immediate write without // an intervening seek. _M_set_buffer(-1); _M_reading = false; } } else __ret += __streambuf_type::xsgetn(__s, __n); return __ret; } template streamsize basic_filebuf<_CharT, _Traits>:: xsputn(const _CharT* __s, streamsize __n) { streamsize __ret = 0; // Optimization in the always_noconv() case, to be generalized in the // future: when __n is sufficiently large we write directly instead of // using the buffer. const bool __testout = (_M_mode & ios_base::out || _M_mode & ios_base::app); if (__check_facet(_M_codecvt).always_noconv() && __testout && !_M_reading) { // Measurement would reveal the best choice. const streamsize __chunk = 1ul << 10; streamsize __bufavail = this->epptr() - this->pptr(); // Don't mistake 'uncommitted' mode buffered with unbuffered. if (!_M_writing && _M_buf_size > 1) __bufavail = _M_buf_size - 1; const streamsize __limit = std::min(__chunk, __bufavail); if (__n >= __limit) { const streamsize __buffill = this->pptr() - this->pbase(); const char* __buf = reinterpret_cast(this->pbase()); __ret = _M_file.xsputn_2(__buf, __buffill, reinterpret_cast(__s), __n); if (__ret == __buffill + __n) { _M_set_buffer(0); _M_writing = true; } if (__ret > __buffill) __ret -= __buffill; else __ret = 0; } else __ret = __streambuf_type::xsputn(__s, __n); } else __ret = __streambuf_type::xsputn(__s, __n); return __ret; } template typename basic_filebuf<_CharT, _Traits>::__streambuf_type* basic_filebuf<_CharT, _Traits>:: setbuf(char_type* __s, streamsize __n) { if (!this->is_open()) { if (__s == 0 && __n == 0) _M_buf_size = 1; else if (__s && __n > 0) { // This is implementation-defined behavior, and assumes that // an external char_type array of length __n exists and has // been pre-allocated. If this is not the case, things will // quickly blow up. When __n > 1, __n - 1 positions will be // used for the get area, __n - 1 for the put area and 1 // position to host the overflow char of a full put area. // When __n == 1, 1 position will be used for the get area // and 0 for the put area, as in the unbuffered case above. _M_buf = __s; _M_buf_size = __n; } } return this; } // According to 27.8.1.4 p11 - 13, seekoff should ignore the last // argument (of type openmode). template typename basic_filebuf<_CharT, _Traits>::pos_type basic_filebuf<_CharT, _Traits>:: seekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode) { int __width = 0; if (_M_codecvt) __width = _M_codecvt->encoding(); if (__width < 0) __width = 0; pos_type __ret = pos_type(off_type(-1)); const bool __testfail = __off != 0 && __width <= 0; if (this->is_open() && !__testfail) { // tellg and tellp queries do not affect any state, unless // ! always_noconv and the put sequence is not empty. // In that case, determining the position requires converting the // put sequence. That doesn't use ext_buf, so requires a flush. bool __no_movement = __way == ios_base::cur && __off == 0 && (!_M_writing || _M_codecvt->always_noconv()); // Ditch any pback buffers to avoid confusion. if (!__no_movement) _M_destroy_pback(); // Correct state at destination. Note that this is the correct // state for the current position during output, because // codecvt::unshift() returns the state to the initial state. // This is also the correct state at the end of the file because // an unshift sequence should have been written at the end. __state_type __state = _M_state_beg; off_type __computed_off = __off * __width; if (_M_reading && __way == ios_base::cur) { __state = _M_state_last; __computed_off += _M_get_ext_pos(__state); } if (!__no_movement) __ret = _M_seek(__computed_off, __way, __state); else { if (_M_writing) __computed_off = this->pptr() - this->pbase(); off_type __file_off = _M_file.seekoff(0, ios_base::cur); if (__file_off != off_type(-1)) { __ret = __file_off + __computed_off; __ret.state(__state); } } } return __ret; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 171. Strange seekpos() semantics due to joint position // According to the resolution of DR 171, seekpos should ignore the last // argument (of type openmode). template typename basic_filebuf<_CharT, _Traits>::pos_type basic_filebuf<_CharT, _Traits>:: seekpos(pos_type __pos, ios_base::openmode) { pos_type __ret = pos_type(off_type(-1)); if (this->is_open()) { // Ditch any pback buffers to avoid confusion. _M_destroy_pback(); __ret = _M_seek(off_type(__pos), ios_base::beg, __pos.state()); } return __ret; } template typename basic_filebuf<_CharT, _Traits>::pos_type basic_filebuf<_CharT, _Traits>:: _M_seek(off_type __off, ios_base::seekdir __way, __state_type __state) { pos_type __ret = pos_type(off_type(-1)); if (_M_terminate_output()) { off_type __file_off = _M_file.seekoff(__off, __way); if (__file_off != off_type(-1)) { _M_reading = false; _M_writing = false; _M_ext_next = _M_ext_end = _M_ext_buf; _M_set_buffer(-1); _M_state_cur = __state; __ret = __file_off; __ret.state(_M_state_cur); } } return __ret; } // Returns the distance from the end of the ext buffer to the point // corresponding to gptr(). This is a negative value. Updates __state // from eback() correspondence to gptr(). template int basic_filebuf<_CharT, _Traits>:: _M_get_ext_pos(__state_type& __state) { if (_M_codecvt->always_noconv()) return this->gptr() - this->egptr(); else { // Calculate offset from _M_ext_buf that corresponds to // gptr(). Precondition: __state == _M_state_last, which // corresponds to eback(). const int __gptr_off = _M_codecvt->length(__state, _M_ext_buf, _M_ext_next, this->gptr() - this->eback()); return _M_ext_buf + __gptr_off - _M_ext_end; } } template bool basic_filebuf<_CharT, _Traits>:: _M_terminate_output() { // Part one: update the output sequence. bool __testvalid = true; if (this->pbase() < this->pptr()) { const int_type __tmp = this->overflow(); if (traits_type::eq_int_type(__tmp, traits_type::eof())) __testvalid = false; } // Part two: output unshift sequence. if (_M_writing && !__check_facet(_M_codecvt).always_noconv() && __testvalid) { // Note: this value is arbitrary, since there is no way to // get the length of the unshift sequence from codecvt, // without calling unshift. const size_t __blen = 128; char __buf[__blen]; codecvt_base::result __r; streamsize __ilen = 0; do { char* __next; __r = _M_codecvt->unshift(_M_state_cur, __buf, __buf + __blen, __next); if (__r == codecvt_base::error) __testvalid = false; else if (__r == codecvt_base::ok || __r == codecvt_base::partial) { __ilen = __next - __buf; if (__ilen > 0) { const streamsize __elen = _M_file.xsputn(__buf, __ilen); if (__elen != __ilen) __testvalid = false; } } } while (__r == codecvt_base::partial && __ilen > 0 && __testvalid); if (__testvalid) { // This second call to overflow() is required by the standard, // but it's not clear why it's needed, since the output buffer // should be empty by this point (it should have been emptied // in the first call to overflow()). const int_type __tmp = this->overflow(); if (traits_type::eq_int_type(__tmp, traits_type::eof())) __testvalid = false; } } return __testvalid; } template int basic_filebuf<_CharT, _Traits>:: sync() { // Make sure that the internal buffer resyncs its idea of // the file position with the external file. int __ret = 0; if (this->pbase() < this->pptr()) { const int_type __tmp = this->overflow(); if (traits_type::eq_int_type(__tmp, traits_type::eof())) __ret = -1; } return __ret; } template void basic_filebuf<_CharT, _Traits>:: imbue(const locale& __loc) { bool __testvalid = true; const __codecvt_type* _M_codecvt_tmp = 0; if (__builtin_expect(has_facet<__codecvt_type>(__loc), true)) _M_codecvt_tmp = &use_facet<__codecvt_type>(__loc); if (this->is_open()) { // encoding() == -1 is ok only at the beginning. if ((_M_reading || _M_writing) && __check_facet(_M_codecvt).encoding() == -1) __testvalid = false; else { if (_M_reading) { if (__check_facet(_M_codecvt).always_noconv()) { if (_M_codecvt_tmp && !__check_facet(_M_codecvt_tmp).always_noconv()) __testvalid = this->seekoff(0, ios_base::cur, _M_mode) != pos_type(off_type(-1)); } else { // External position corresponding to gptr(). _M_ext_next = _M_ext_buf + _M_codecvt->length(_M_state_last, _M_ext_buf, _M_ext_next, this->gptr() - this->eback()); const streamsize __remainder = _M_ext_end - _M_ext_next; if (__remainder) __builtin_memmove(_M_ext_buf, _M_ext_next, __remainder); _M_ext_next = _M_ext_buf; _M_ext_end = _M_ext_buf + __remainder; _M_set_buffer(-1); _M_state_last = _M_state_cur = _M_state_beg; } } else if (_M_writing && (__testvalid = _M_terminate_output())) _M_set_buffer(-1); } } if (__testvalid) _M_codecvt = _M_codecvt_tmp; else _M_codecvt = 0; } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class basic_filebuf; extern template class basic_ifstream; extern template class basic_ofstream; extern template class basic_fstream; #ifdef _GLIBCXX_USE_WCHAR_T extern template class basic_filebuf; extern template class basic_ifstream; extern template class basic_ofstream; extern template class basic_fstream; #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!)$ 8/bits/functexcept.hnu[// Function-Based Exception Support -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/functexcept.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{exception} * * This header provides support for -fno-exceptions. */ // // ISO C++ 14882: 19.1 Exception classes // #ifndef _FUNCTEXCEPT_H #define _FUNCTEXCEPT_H 1 #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Helper for exception objects in void __throw_bad_exception(void) __attribute__((__noreturn__)); // Helper for exception objects in void __throw_bad_alloc(void) __attribute__((__noreturn__)); // Helper for exception objects in void __throw_bad_cast(void) __attribute__((__noreturn__)); void __throw_bad_typeid(void) __attribute__((__noreturn__)); // Helpers for exception objects in void __throw_logic_error(const char*) __attribute__((__noreturn__)); void __throw_domain_error(const char*) __attribute__((__noreturn__)); void __throw_invalid_argument(const char*) __attribute__((__noreturn__)); void __throw_length_error(const char*) __attribute__((__noreturn__)); void __throw_out_of_range(const char*) __attribute__((__noreturn__)); void __throw_out_of_range_fmt(const char*, ...) __attribute__((__noreturn__)) __attribute__((__format__(__gnu_printf__, 1, 2))); void __throw_runtime_error(const char*) __attribute__((__noreturn__)); void __throw_range_error(const char*) __attribute__((__noreturn__)); void __throw_overflow_error(const char*) __attribute__((__noreturn__)); void __throw_underflow_error(const char*) __attribute__((__noreturn__)); // Helpers for exception objects in void __throw_ios_failure(const char*) __attribute__((__noreturn__)); void __throw_system_error(int) __attribute__((__noreturn__)); void __throw_future_error(int) __attribute__((__noreturn__)); // Helpers for exception objects in void __throw_bad_function_call() __attribute__((__noreturn__)); _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!Ɲ{. . 8/bits/functional_hash.hnu[// functional_hash.h header -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/functional_hash.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{functional} */ #ifndef _FUNCTIONAL_HASH_H #define _FUNCTIONAL_HASH_H 1 #pragma GCC system_header #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** @defgroup hashes Hashes * @ingroup functors * * Hashing functors taking a variable type and returning a @c std::size_t. * * @{ */ template struct __hash_base { typedef _Result result_type _GLIBCXX17_DEPRECATED; typedef _Arg argument_type _GLIBCXX17_DEPRECATED; }; /// Primary class template hash. template struct hash; template struct __poison_hash { static constexpr bool __enable_hash_call = false; private: // Private rather than deleted to be non-trivially-copyable. __poison_hash(__poison_hash&&); ~__poison_hash(); }; template struct __poison_hash<_Tp, __void_t()(declval<_Tp>()))>> { static constexpr bool __enable_hash_call = true; }; // Helper struct for SFINAE-poisoning non-enum types. template::value> struct __hash_enum { private: // Private rather than deleted to be non-trivially-copyable. __hash_enum(__hash_enum&&); ~__hash_enum(); }; // Helper struct for hash with enum types. template struct __hash_enum<_Tp, true> : public __hash_base { size_t operator()(_Tp __val) const noexcept { using __type = typename underlying_type<_Tp>::type; return hash<__type>{}(static_cast<__type>(__val)); } }; /// Primary class template hash, usable for enum types only. // Use with non-enum types still SFINAES. template struct hash : __hash_enum<_Tp> { }; /// Partial specializations for pointer types. template struct hash<_Tp*> : public __hash_base { size_t operator()(_Tp* __p) const noexcept { return reinterpret_cast(__p); } }; // Explicit specializations for integer types. #define _Cxx_hashtable_define_trivial_hash(_Tp) \ template<> \ struct hash<_Tp> : public __hash_base \ { \ size_t \ operator()(_Tp __val) const noexcept \ { return static_cast(__val); } \ }; /// Explicit specialization for bool. _Cxx_hashtable_define_trivial_hash(bool) /// Explicit specialization for char. _Cxx_hashtable_define_trivial_hash(char) /// Explicit specialization for signed char. _Cxx_hashtable_define_trivial_hash(signed char) /// Explicit specialization for unsigned char. _Cxx_hashtable_define_trivial_hash(unsigned char) /// Explicit specialization for wchar_t. _Cxx_hashtable_define_trivial_hash(wchar_t) /// Explicit specialization for char16_t. _Cxx_hashtable_define_trivial_hash(char16_t) /// Explicit specialization for char32_t. _Cxx_hashtable_define_trivial_hash(char32_t) /// Explicit specialization for short. _Cxx_hashtable_define_trivial_hash(short) /// Explicit specialization for int. _Cxx_hashtable_define_trivial_hash(int) /// Explicit specialization for long. _Cxx_hashtable_define_trivial_hash(long) /// Explicit specialization for long long. _Cxx_hashtable_define_trivial_hash(long long) /// Explicit specialization for unsigned short. _Cxx_hashtable_define_trivial_hash(unsigned short) /// Explicit specialization for unsigned int. _Cxx_hashtable_define_trivial_hash(unsigned int) /// Explicit specialization for unsigned long. _Cxx_hashtable_define_trivial_hash(unsigned long) /// Explicit specialization for unsigned long long. _Cxx_hashtable_define_trivial_hash(unsigned long long) #ifdef __GLIBCXX_TYPE_INT_N_0 _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_0) _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_0 unsigned) #endif #ifdef __GLIBCXX_TYPE_INT_N_1 _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_1) _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_1 unsigned) #endif #ifdef __GLIBCXX_TYPE_INT_N_2 _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_2) _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_2 unsigned) #endif #ifdef __GLIBCXX_TYPE_INT_N_3 _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_3) _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_3 unsigned) #endif #undef _Cxx_hashtable_define_trivial_hash struct _Hash_impl { static size_t hash(const void* __ptr, size_t __clength, size_t __seed = static_cast(0xc70f6907UL)) { return _Hash_bytes(__ptr, __clength, __seed); } template static size_t hash(const _Tp& __val) { return hash(&__val, sizeof(__val)); } template static size_t __hash_combine(const _Tp& __val, size_t __hash) { return hash(&__val, sizeof(__val), __hash); } }; // A hash function similar to FNV-1a (see PR59406 for how it differs). struct _Fnv_hash_impl { static size_t hash(const void* __ptr, size_t __clength, size_t __seed = static_cast(2166136261UL)) { return _Fnv_hash_bytes(__ptr, __clength, __seed); } template static size_t hash(const _Tp& __val) { return hash(&__val, sizeof(__val)); } template static size_t __hash_combine(const _Tp& __val, size_t __hash) { return hash(&__val, sizeof(__val), __hash); } }; /// Specialization for float. template<> struct hash : public __hash_base { size_t operator()(float __val) const noexcept { // 0 and -0 both hash to zero. return __val != 0.0f ? std::_Hash_impl::hash(__val) : 0; } }; /// Specialization for double. template<> struct hash : public __hash_base { size_t operator()(double __val) const noexcept { // 0 and -0 both hash to zero. return __val != 0.0 ? std::_Hash_impl::hash(__val) : 0; } }; /// Specialization for long double. template<> struct hash : public __hash_base { _GLIBCXX_PURE size_t operator()(long double __val) const noexcept; }; // @} group hashes // Hint about performance of hash functor. If not fast the hash-based // containers will cache the hash code. // Default behavior is to consider that hashers are fast unless specified // otherwise. template struct __is_fast_hash : public std::true_type { }; template<> struct __is_fast_hash> : public std::false_type { }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _FUNCTIONAL_HASH_H PK!iN8/bits/gslice.hnu[// The template and inlines for the -*- C++ -*- gslice class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/gslice.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _GSLICE_H #define _GSLICE_H 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup numeric_arrays * @{ */ /** * @brief Class defining multi-dimensional subset of an array. * * The slice class represents a multi-dimensional subset of an array, * specified by three parameter sets: start offset, size array, and stride * array. The start offset is the index of the first element of the array * that is part of the subset. The size and stride array describe each * dimension of the slice. Size is the number of elements in that * dimension, and stride is the distance in the array between successive * elements in that dimension. Each dimension's size and stride is taken * to begin at an array element described by the previous dimension. The * size array and stride array must be the same size. * * For example, if you have offset==3, stride[0]==11, size[1]==3, * stride[1]==3, then slice[0,0]==array[3], slice[0,1]==array[6], * slice[0,2]==array[9], slice[1,0]==array[14], slice[1,1]==array[17], * slice[1,2]==array[20]. */ class gslice { public: /// Construct an empty slice. gslice(); /** * @brief Construct a slice. * * Constructs a slice with as many dimensions as the length of the @a l * and @a s arrays. * * @param __o Offset in array of first element. * @param __l Array of dimension lengths. * @param __s Array of dimension strides between array elements. */ gslice(size_t __o, const valarray& __l, const valarray& __s); // XXX: the IS says the copy-ctor and copy-assignment operators are // synthesized by the compiler but they are just unsuitable // for a ref-counted semantic /// Copy constructor. gslice(const gslice&); /// Destructor. ~gslice(); // XXX: See the note above. /// Assignment operator. gslice& operator=(const gslice&); /// Return array offset of first slice element. size_t start() const; /// Return array of sizes of slice dimensions. valarray size() const; /// Return array of array strides for each dimension. valarray stride() const; private: struct _Indexer { size_t _M_count; size_t _M_start; valarray _M_size; valarray _M_stride; valarray _M_index; // Linear array of referenced indices _Indexer() : _M_count(1), _M_start(0), _M_size(), _M_stride(), _M_index() {} _Indexer(size_t, const valarray&, const valarray&); void _M_increment_use() { ++_M_count; } size_t _M_decrement_use() { return --_M_count; } }; _Indexer* _M_index; template friend class valarray; }; inline size_t gslice::start() const { return _M_index ? _M_index->_M_start : 0; } inline valarray gslice::size() const { return _M_index ? _M_index->_M_size : valarray(); } inline valarray gslice::stride() const { return _M_index ? _M_index->_M_stride : valarray(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 543. valarray slice default constructor inline gslice::gslice() : _M_index(new gslice::_Indexer()) {} inline gslice::gslice(size_t __o, const valarray& __l, const valarray& __s) : _M_index(new gslice::_Indexer(__o, __l, __s)) {} inline gslice::gslice(const gslice& __g) : _M_index(__g._M_index) { if (_M_index) _M_index->_M_increment_use(); } inline gslice::~gslice() { if (_M_index && _M_index->_M_decrement_use() == 0) delete _M_index; } inline gslice& gslice::operator=(const gslice& __g) { if (__g._M_index) __g._M_index->_M_increment_use(); if (_M_index && _M_index->_M_decrement_use() == 0) delete _M_index; _M_index = __g._M_index; return *this; } // @} group numeric_arrays _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _GSLICE_H */ PK!.YY8/bits/gslice_array.hnu[// The template and inlines for the -*- C++ -*- gslice_array class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/gslice_array.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _GSLICE_ARRAY_H #define _GSLICE_ARRAY_H 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup numeric_arrays * @{ */ /** * @brief Reference to multi-dimensional subset of an array. * * A gslice_array is a reference to the actual elements of an array * specified by a gslice. The way to get a gslice_array is to call * operator[](gslice) on a valarray. The returned gslice_array then * permits carrying operations out on the referenced subset of elements in * the original valarray. For example, operator+=(valarray) will add * values to the subset of elements in the underlying valarray this * gslice_array refers to. * * @param Tp Element type. */ template class gslice_array { public: typedef _Tp value_type; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 253. valarray helper functions are almost entirely useless /// Copy constructor. Both slices refer to the same underlying array. gslice_array(const gslice_array&); /// Assignment operator. Assigns slice elements to corresponding /// elements of @a a. gslice_array& operator=(const gslice_array&); /// Assign slice elements to corresponding elements of @a v. void operator=(const valarray<_Tp>&) const; /// Multiply slice elements by corresponding elements of @a v. void operator*=(const valarray<_Tp>&) const; /// Divide slice elements by corresponding elements of @a v. void operator/=(const valarray<_Tp>&) const; /// Modulo slice elements by corresponding elements of @a v. void operator%=(const valarray<_Tp>&) const; /// Add corresponding elements of @a v to slice elements. void operator+=(const valarray<_Tp>&) const; /// Subtract corresponding elements of @a v from slice elements. void operator-=(const valarray<_Tp>&) const; /// Logical xor slice elements with corresponding elements of @a v. void operator^=(const valarray<_Tp>&) const; /// Logical and slice elements with corresponding elements of @a v. void operator&=(const valarray<_Tp>&) const; /// Logical or slice elements with corresponding elements of @a v. void operator|=(const valarray<_Tp>&) const; /// Left shift slice elements by corresponding elements of @a v. void operator<<=(const valarray<_Tp>&) const; /// Right shift slice elements by corresponding elements of @a v. void operator>>=(const valarray<_Tp>&) const; /// Assign all slice elements to @a t. void operator=(const _Tp&) const; template void operator=(const _Expr<_Dom, _Tp>&) const; template void operator*=(const _Expr<_Dom, _Tp>&) const; template void operator/=(const _Expr<_Dom, _Tp>&) const; template void operator%=(const _Expr<_Dom, _Tp>&) const; template void operator+=(const _Expr<_Dom, _Tp>&) const; template void operator-=(const _Expr<_Dom, _Tp>&) const; template void operator^=(const _Expr<_Dom, _Tp>&) const; template void operator&=(const _Expr<_Dom, _Tp>&) const; template void operator|=(const _Expr<_Dom, _Tp>&) const; template void operator<<=(const _Expr<_Dom, _Tp>&) const; template void operator>>=(const _Expr<_Dom, _Tp>&) const; private: _Array<_Tp> _M_array; const valarray& _M_index; friend class valarray<_Tp>; gslice_array(_Array<_Tp>, const valarray&); // not implemented gslice_array(); }; template inline gslice_array<_Tp>::gslice_array(_Array<_Tp> __a, const valarray& __i) : _M_array(__a), _M_index(__i) {} template inline gslice_array<_Tp>::gslice_array(const gslice_array<_Tp>& __a) : _M_array(__a._M_array), _M_index(__a._M_index) {} template inline gslice_array<_Tp>& gslice_array<_Tp>::operator=(const gslice_array<_Tp>& __a) { std::__valarray_copy(_Array<_Tp>(__a._M_array), _Array(__a._M_index), _M_index.size(), _M_array, _Array(_M_index)); return *this; } template inline void gslice_array<_Tp>::operator=(const _Tp& __t) const { std::__valarray_fill(_M_array, _Array(_M_index), _M_index.size(), __t); } template inline void gslice_array<_Tp>::operator=(const valarray<_Tp>& __v) const { std::__valarray_copy(_Array<_Tp>(__v), __v.size(), _M_array, _Array(_M_index)); } template template inline void gslice_array<_Tp>::operator=(const _Expr<_Dom, _Tp>& __e) const { std::__valarray_copy (__e, _M_index.size(), _M_array, _Array(_M_index)); } #undef _DEFINE_VALARRAY_OPERATOR #define _DEFINE_VALARRAY_OPERATOR(_Op, _Name) \ template \ inline void \ gslice_array<_Tp>::operator _Op##=(const valarray<_Tp>& __v) const \ { \ _Array_augmented_##_Name(_M_array, _Array(_M_index), \ _Array<_Tp>(__v), __v.size()); \ } \ \ template \ template \ inline void \ gslice_array<_Tp>::operator _Op##= (const _Expr<_Dom, _Tp>& __e) const\ { \ _Array_augmented_##_Name(_M_array, _Array(_M_index), __e,\ _M_index.size()); \ } _DEFINE_VALARRAY_OPERATOR(*, __multiplies) _DEFINE_VALARRAY_OPERATOR(/, __divides) _DEFINE_VALARRAY_OPERATOR(%, __modulus) _DEFINE_VALARRAY_OPERATOR(+, __plus) _DEFINE_VALARRAY_OPERATOR(-, __minus) _DEFINE_VALARRAY_OPERATOR(^, __bitwise_xor) _DEFINE_VALARRAY_OPERATOR(&, __bitwise_and) _DEFINE_VALARRAY_OPERATOR(|, __bitwise_or) _DEFINE_VALARRAY_OPERATOR(<<, __shift_left) _DEFINE_VALARRAY_OPERATOR(>>, __shift_right) #undef _DEFINE_VALARRAY_OPERATOR // @} group numeric_arrays _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _GSLICE_ARRAY_H */ PK!gybb8/bits/hash_bytes.hnu[// Declarations for hash functions. -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/hash_bytes.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{functional} */ #ifndef _HASH_BYTES_H #define _HASH_BYTES_H 1 #pragma GCC system_header #include namespace std { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Hash function implementation for the nontrivial specialization. // All of them are based on a primitive that hashes a pointer to a // byte array. The actual hash algorithm is not guaranteed to stay // the same from release to release -- it may be updated or tuned to // improve hash quality or speed. size_t _Hash_bytes(const void* __ptr, size_t __len, size_t __seed); // A similar hash primitive, using the FNV hash algorithm. This // algorithm is guaranteed to stay the same from release to release. // (although it might not produce the same values on different // machines.) size_t _Fnv_hash_bytes(const void* __ptr, size_t __len, size_t __seed); _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!9 9 8/bits/hashtable.hnu[// hashtable.h header -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/hashtable.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{unordered_map, unordered_set} */ #ifndef _HASHTABLE_H #define _HASHTABLE_H 1 #pragma GCC system_header #include #if __cplusplus > 201402L # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template using __cache_default = __not_<__and_, // Mandatory to have erase not throwing. __is_nothrow_invocable>>; /** * Primary class template _Hashtable. * * @ingroup hashtable-detail * * @tparam _Value CopyConstructible type. * * @tparam _Key CopyConstructible type. * * @tparam _Alloc An allocator type * ([lib.allocator.requirements]) whose _Alloc::value_type is * _Value. As a conforming extension, we allow for * _Alloc::value_type != _Value. * * @tparam _ExtractKey Function object that takes an object of type * _Value and returns a value of type _Key. * * @tparam _Equal Function object that takes two objects of type k * and returns a bool-like value that is true if the two objects * are considered equal. * * @tparam _H1 The hash function. A unary function object with * argument type _Key and result type size_t. Return values should * be distributed over the entire range [0, numeric_limits:::max()]. * * @tparam _H2 The range-hashing function (in the terminology of * Tavori and Dreizin). A binary function object whose argument * types and result type are all size_t. Given arguments r and N, * the return value is in the range [0, N). * * @tparam _Hash The ranged hash function (Tavori and Dreizin). A * binary function whose argument types are _Key and size_t and * whose result type is size_t. Given arguments k and N, the * return value is in the range [0, N). Default: hash(k, N) = * h2(h1(k), N). If _Hash is anything other than the default, _H1 * and _H2 are ignored. * * @tparam _RehashPolicy Policy class with three members, all of * which govern the bucket count. _M_next_bkt(n) returns a bucket * count no smaller than n. _M_bkt_for_elements(n) returns a * bucket count appropriate for an element count of n. * _M_need_rehash(n_bkt, n_elt, n_ins) determines whether, if the * current bucket count is n_bkt and the current element count is * n_elt, we need to increase the bucket count. If so, returns * make_pair(true, n), where n is the new bucket count. If not, * returns make_pair(false, ) * * @tparam _Traits Compile-time class with three boolean * std::integral_constant members: __cache_hash_code, __constant_iterators, * __unique_keys. * * Each _Hashtable data structure has: * * - _Bucket[] _M_buckets * - _Hash_node_base _M_before_begin * - size_type _M_bucket_count * - size_type _M_element_count * * with _Bucket being _Hash_node* and _Hash_node containing: * * - _Hash_node* _M_next * - Tp _M_value * - size_t _M_hash_code if cache_hash_code is true * * In terms of Standard containers the hashtable is like the aggregation of: * * - std::forward_list<_Node> containing the elements * - std::vector::iterator> representing the buckets * * The non-empty buckets contain the node before the first node in the * bucket. This design makes it possible to implement something like a * std::forward_list::insert_after on container insertion and * std::forward_list::erase_after on container erase * calls. _M_before_begin is equivalent to * std::forward_list::before_begin. Empty buckets contain * nullptr. Note that one of the non-empty buckets contains * &_M_before_begin which is not a dereferenceable node so the * node pointer in a bucket shall never be dereferenced, only its * next node can be. * * Walking through a bucket's nodes requires a check on the hash code to * see if each node is still in the bucket. Such a design assumes a * quite efficient hash functor and is one of the reasons it is * highly advisable to set __cache_hash_code to true. * * The container iterators are simply built from nodes. This way * incrementing the iterator is perfectly efficient independent of * how many empty buckets there are in the container. * * On insert we compute the element's hash code and use it to find the * bucket index. If the element must be inserted in an empty bucket * we add it at the beginning of the singly linked list and make the * bucket point to _M_before_begin. The bucket that used to point to * _M_before_begin, if any, is updated to point to its new before * begin node. * * On erase, the simple iterator design requires using the hash * functor to get the index of the bucket to update. For this * reason, when __cache_hash_code is set to false the hash functor must * not throw and this is enforced by a static assertion. * * Functionality is implemented by decomposition into base classes, * where the derived _Hashtable class is used in _Map_base, * _Insert, _Rehash_base, and _Equality base classes to access the * "this" pointer. _Hashtable_base is used in the base classes as a * non-recursive, fully-completed-type so that detailed nested type * information, such as iterator type and node type, can be * used. This is similar to the "Curiously Recurring Template * Pattern" (CRTP) technique, but uses a reconstructed, not * explicitly passed, template pattern. * * Base class templates are: * - __detail::_Hashtable_base * - __detail::_Map_base * - __detail::_Insert * - __detail::_Rehash_base * - __detail::_Equality */ template class _Hashtable : public __detail::_Hashtable_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, _Hash, _Traits>, public __detail::_Map_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>, public __detail::_Insert<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>, public __detail::_Rehash_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>, public __detail::_Equality<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>, private __detail::_Hashtable_alloc< __alloc_rebind<_Alloc, __detail::_Hash_node<_Value, _Traits::__hash_cached::value>>> { static_assert(is_same::type, _Value>::value, "unordered container must have a non-const, non-volatile value_type"); #ifdef __STRICT_ANSI__ static_assert(is_same{}, "unordered container must have the same value_type as its allocator"); #endif using __traits_type = _Traits; using __hash_cached = typename __traits_type::__hash_cached; using __node_type = __detail::_Hash_node<_Value, __hash_cached::value>; using __node_alloc_type = __alloc_rebind<_Alloc, __node_type>; using __hashtable_alloc = __detail::_Hashtable_alloc<__node_alloc_type>; using __value_alloc_traits = typename __hashtable_alloc::__value_alloc_traits; using __node_alloc_traits = typename __hashtable_alloc::__node_alloc_traits; using __node_base = typename __hashtable_alloc::__node_base; using __bucket_type = typename __hashtable_alloc::__bucket_type; public: typedef _Key key_type; typedef _Value value_type; typedef _Alloc allocator_type; typedef _Equal key_equal; // mapped_type, if present, comes from _Map_base. // hasher, if present, comes from _Hash_code_base/_Hashtable_base. typedef typename __value_alloc_traits::pointer pointer; typedef typename __value_alloc_traits::const_pointer const_pointer; typedef value_type& reference; typedef const value_type& const_reference; private: using __rehash_type = _RehashPolicy; using __rehash_state = typename __rehash_type::_State; using __constant_iterators = typename __traits_type::__constant_iterators; using __unique_keys = typename __traits_type::__unique_keys; using __key_extract = typename std::conditional< __constant_iterators::value, __detail::_Identity, __detail::_Select1st>::type; using __hashtable_base = __detail:: _Hashtable_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, _Hash, _Traits>; using __hash_code_base = typename __hashtable_base::__hash_code_base; using __hash_code = typename __hashtable_base::__hash_code; using __ireturn_type = typename __hashtable_base::__ireturn_type; using __map_base = __detail::_Map_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; using __rehash_base = __detail::_Rehash_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; using __eq_base = __detail::_Equality<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; using __reuse_or_alloc_node_type = __detail::_ReuseOrAllocNode<__node_alloc_type>; // Metaprogramming for picking apart hash caching. template using __if_hash_cached = __or_<__not_<__hash_cached>, _Cond>; template using __if_hash_not_cached = __or_<__hash_cached, _Cond>; // Compile-time diagnostics. // _Hash_code_base has everything protected, so use this derived type to // access it. struct __hash_code_base_access : __hash_code_base { using __hash_code_base::_M_bucket_index; }; // Getting a bucket index from a node shall not throw because it is used // in methods (erase, swap...) that shall not throw. static_assert(noexcept(declval() ._M_bucket_index((const __node_type*)nullptr, (std::size_t)0)), "Cache the hash code or qualify your functors involved" " in hash code and bucket index computation with noexcept"); // Following two static assertions are necessary to guarantee // that local_iterator will be default constructible. // When hash codes are cached local iterator inherits from H2 functor // which must then be default constructible. static_assert(__if_hash_cached>::value, "Functor used to map hash code to bucket index" " must be default constructible"); template friend struct __detail::_Map_base; template friend struct __detail::_Insert_base; template friend struct __detail::_Insert; public: using size_type = typename __hashtable_base::size_type; using difference_type = typename __hashtable_base::difference_type; using iterator = typename __hashtable_base::iterator; using const_iterator = typename __hashtable_base::const_iterator; using local_iterator = typename __hashtable_base::local_iterator; using const_local_iterator = typename __hashtable_base:: const_local_iterator; #if __cplusplus > 201402L using node_type = _Node_handle<_Key, _Value, __node_alloc_type>; using insert_return_type = _Node_insert_return; #endif private: __bucket_type* _M_buckets = &_M_single_bucket; size_type _M_bucket_count = 1; __node_base _M_before_begin; size_type _M_element_count = 0; _RehashPolicy _M_rehash_policy; // A single bucket used when only need for 1 bucket. Especially // interesting in move semantic to leave hashtable with only 1 buckets // which is not allocated so that we can have those operations noexcept // qualified. // Note that we can't leave hashtable with 0 bucket without adding // numerous checks in the code to avoid 0 modulus. __bucket_type _M_single_bucket = nullptr; bool _M_uses_single_bucket(__bucket_type* __bkts) const { return __builtin_expect(__bkts == &_M_single_bucket, false); } bool _M_uses_single_bucket() const { return _M_uses_single_bucket(_M_buckets); } __hashtable_alloc& _M_base_alloc() { return *this; } __bucket_type* _M_allocate_buckets(size_type __n) { if (__builtin_expect(__n == 1, false)) { _M_single_bucket = nullptr; return &_M_single_bucket; } return __hashtable_alloc::_M_allocate_buckets(__n); } void _M_deallocate_buckets(__bucket_type* __bkts, size_type __n) { if (_M_uses_single_bucket(__bkts)) return; __hashtable_alloc::_M_deallocate_buckets(__bkts, __n); } void _M_deallocate_buckets() { _M_deallocate_buckets(_M_buckets, _M_bucket_count); } // Gets bucket begin, deals with the fact that non-empty buckets contain // their before begin node. __node_type* _M_bucket_begin(size_type __bkt) const; __node_type* _M_begin() const { return static_cast<__node_type*>(_M_before_begin._M_nxt); } template void _M_assign(const _Hashtable&, const _NodeGenerator&); void _M_move_assign(_Hashtable&&, std::true_type); void _M_move_assign(_Hashtable&&, std::false_type); void _M_reset() noexcept; _Hashtable(const _H1& __h1, const _H2& __h2, const _Hash& __h, const _Equal& __eq, const _ExtractKey& __exk, const allocator_type& __a) : __hashtable_base(__exk, __h1, __h2, __h, __eq), __hashtable_alloc(__node_alloc_type(__a)) { } public: // Constructor, destructor, assignment, swap _Hashtable() = default; _Hashtable(size_type __bucket_hint, const _H1&, const _H2&, const _Hash&, const _Equal&, const _ExtractKey&, const allocator_type&); template _Hashtable(_InputIterator __first, _InputIterator __last, size_type __bucket_hint, const _H1&, const _H2&, const _Hash&, const _Equal&, const _ExtractKey&, const allocator_type&); _Hashtable(const _Hashtable&); _Hashtable(_Hashtable&&) noexcept; _Hashtable(const _Hashtable&, const allocator_type&); _Hashtable(_Hashtable&&, const allocator_type&); // Use delegating constructors. explicit _Hashtable(const allocator_type& __a) : __hashtable_alloc(__node_alloc_type(__a)) { } explicit _Hashtable(size_type __n, const _H1& __hf = _H1(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Hashtable(__n, __hf, _H2(), _Hash(), __eql, __key_extract(), __a) { } template _Hashtable(_InputIterator __f, _InputIterator __l, size_type __n = 0, const _H1& __hf = _H1(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Hashtable(__f, __l, __n, __hf, _H2(), _Hash(), __eql, __key_extract(), __a) { } _Hashtable(initializer_list __l, size_type __n = 0, const _H1& __hf = _H1(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Hashtable(__l.begin(), __l.end(), __n, __hf, _H2(), _Hash(), __eql, __key_extract(), __a) { } _Hashtable& operator=(const _Hashtable& __ht); _Hashtable& operator=(_Hashtable&& __ht) noexcept(__node_alloc_traits::_S_nothrow_move() && is_nothrow_move_assignable<_H1>::value && is_nothrow_move_assignable<_Equal>::value) { constexpr bool __move_storage = __node_alloc_traits::_S_propagate_on_move_assign() || __node_alloc_traits::_S_always_equal(); _M_move_assign(std::move(__ht), __bool_constant<__move_storage>()); return *this; } _Hashtable& operator=(initializer_list __l) { __reuse_or_alloc_node_type __roan(_M_begin(), *this); _M_before_begin._M_nxt = nullptr; clear(); this->_M_insert_range(__l.begin(), __l.end(), __roan, __unique_keys()); return *this; } ~_Hashtable() noexcept; void swap(_Hashtable&) noexcept(__and_<__is_nothrow_swappable<_H1>, __is_nothrow_swappable<_Equal>>::value); // Basic container operations iterator begin() noexcept { return iterator(_M_begin()); } const_iterator begin() const noexcept { return const_iterator(_M_begin()); } iterator end() noexcept { return iterator(nullptr); } const_iterator end() const noexcept { return const_iterator(nullptr); } const_iterator cbegin() const noexcept { return const_iterator(_M_begin()); } const_iterator cend() const noexcept { return const_iterator(nullptr); } size_type size() const noexcept { return _M_element_count; } bool empty() const noexcept { return size() == 0; } allocator_type get_allocator() const noexcept { return allocator_type(this->_M_node_allocator()); } size_type max_size() const noexcept { return __node_alloc_traits::max_size(this->_M_node_allocator()); } // Observers key_equal key_eq() const { return this->_M_eq(); } // hash_function, if present, comes from _Hash_code_base. // Bucket operations size_type bucket_count() const noexcept { return _M_bucket_count; } size_type max_bucket_count() const noexcept { return max_size(); } size_type bucket_size(size_type __n) const { return std::distance(begin(__n), end(__n)); } size_type bucket(const key_type& __k) const { return _M_bucket_index(__k, this->_M_hash_code(__k)); } local_iterator begin(size_type __n) { return local_iterator(*this, _M_bucket_begin(__n), __n, _M_bucket_count); } local_iterator end(size_type __n) { return local_iterator(*this, nullptr, __n, _M_bucket_count); } const_local_iterator begin(size_type __n) const { return const_local_iterator(*this, _M_bucket_begin(__n), __n, _M_bucket_count); } const_local_iterator end(size_type __n) const { return const_local_iterator(*this, nullptr, __n, _M_bucket_count); } // DR 691. const_local_iterator cbegin(size_type __n) const { return const_local_iterator(*this, _M_bucket_begin(__n), __n, _M_bucket_count); } const_local_iterator cend(size_type __n) const { return const_local_iterator(*this, nullptr, __n, _M_bucket_count); } float load_factor() const noexcept { return static_cast(size()) / static_cast(bucket_count()); } // max_load_factor, if present, comes from _Rehash_base. // Generalization of max_load_factor. Extension, not found in // TR1. Only useful if _RehashPolicy is something other than // the default. const _RehashPolicy& __rehash_policy() const { return _M_rehash_policy; } void __rehash_policy(const _RehashPolicy& __pol) { _M_rehash_policy = __pol; } // Lookup. iterator find(const key_type& __k); const_iterator find(const key_type& __k) const; size_type count(const key_type& __k) const; std::pair equal_range(const key_type& __k); std::pair equal_range(const key_type& __k) const; protected: // Bucket index computation helpers. size_type _M_bucket_index(__node_type* __n) const noexcept { return __hash_code_base::_M_bucket_index(__n, _M_bucket_count); } size_type _M_bucket_index(const key_type& __k, __hash_code __c) const { return __hash_code_base::_M_bucket_index(__k, __c, _M_bucket_count); } // Find and insert helper functions and types // Find the node before the one matching the criteria. __node_base* _M_find_before_node(size_type, const key_type&, __hash_code) const; __node_type* _M_find_node(size_type __bkt, const key_type& __key, __hash_code __c) const { __node_base* __before_n = _M_find_before_node(__bkt, __key, __c); if (__before_n) return static_cast<__node_type*>(__before_n->_M_nxt); return nullptr; } // Insert a node at the beginning of a bucket. void _M_insert_bucket_begin(size_type, __node_type*); // Remove the bucket first node void _M_remove_bucket_begin(size_type __bkt, __node_type* __next_n, size_type __next_bkt); // Get the node before __n in the bucket __bkt __node_base* _M_get_previous_node(size_type __bkt, __node_base* __n); // Insert node with hash code __code, in bucket bkt if no rehash (assumes // no element with its key already present). Take ownership of the node, // deallocate it on exception. iterator _M_insert_unique_node(size_type __bkt, __hash_code __code, __node_type* __n, size_type __n_elt = 1); // Insert node with hash code __code. Take ownership of the node, // deallocate it on exception. iterator _M_insert_multi_node(__node_type* __hint, __hash_code __code, __node_type* __n); template std::pair _M_emplace(std::true_type, _Args&&... __args); template iterator _M_emplace(std::false_type __uk, _Args&&... __args) { return _M_emplace(cend(), __uk, std::forward<_Args>(__args)...); } // Emplace with hint, useless when keys are unique. template iterator _M_emplace(const_iterator, std::true_type __uk, _Args&&... __args) { return _M_emplace(__uk, std::forward<_Args>(__args)...).first; } template iterator _M_emplace(const_iterator, std::false_type, _Args&&... __args); template std::pair _M_insert(_Arg&&, const _NodeGenerator&, true_type, size_type = 1); template iterator _M_insert(_Arg&& __arg, const _NodeGenerator& __node_gen, false_type __uk) { return _M_insert(cend(), std::forward<_Arg>(__arg), __node_gen, __uk); } // Insert with hint, not used when keys are unique. template iterator _M_insert(const_iterator, _Arg&& __arg, const _NodeGenerator& __node_gen, true_type __uk) { return _M_insert(std::forward<_Arg>(__arg), __node_gen, __uk).first; } // Insert with hint when keys are not unique. template iterator _M_insert(const_iterator, _Arg&&, const _NodeGenerator&, false_type); size_type _M_erase(std::true_type, const key_type&); size_type _M_erase(std::false_type, const key_type&); iterator _M_erase(size_type __bkt, __node_base* __prev_n, __node_type* __n); public: // Emplace template __ireturn_type emplace(_Args&&... __args) { return _M_emplace(__unique_keys(), std::forward<_Args>(__args)...); } template iterator emplace_hint(const_iterator __hint, _Args&&... __args) { return _M_emplace(__hint, __unique_keys(), std::forward<_Args>(__args)...); } // Insert member functions via inheritance. // Erase iterator erase(const_iterator); // LWG 2059. iterator erase(iterator __it) { return erase(const_iterator(__it)); } size_type erase(const key_type& __k) { return _M_erase(__unique_keys(), __k); } iterator erase(const_iterator, const_iterator); void clear() noexcept; // Set number of buckets to be appropriate for container of n element. void rehash(size_type __n); // DR 1189. // reserve, if present, comes from _Rehash_base. #if __cplusplus > 201402L /// Re-insert an extracted node into a container with unique keys. insert_return_type _M_reinsert_node(node_type&& __nh) { insert_return_type __ret; if (__nh.empty()) __ret.position = end(); else { __glibcxx_assert(get_allocator() == __nh.get_allocator()); const key_type& __k = __nh._M_key(); __hash_code __code = this->_M_hash_code(__k); size_type __bkt = _M_bucket_index(__k, __code); if (__node_type* __n = _M_find_node(__bkt, __k, __code)) { __ret.node = std::move(__nh); __ret.position = iterator(__n); __ret.inserted = false; } else { __ret.position = _M_insert_unique_node(__bkt, __code, __nh._M_ptr); __nh._M_ptr = nullptr; __ret.inserted = true; } } return __ret; } /// Re-insert an extracted node into a container with equivalent keys. iterator _M_reinsert_node_multi(const_iterator __hint, node_type&& __nh) { iterator __ret; if (__nh.empty()) __ret = end(); else { __glibcxx_assert(get_allocator() == __nh.get_allocator()); auto __code = this->_M_hash_code(__nh._M_key()); auto __node = std::exchange(__nh._M_ptr, nullptr); // FIXME: this deallocates the node on exception. __ret = _M_insert_multi_node(__hint._M_cur, __code, __node); } return __ret; } /// Extract a node. node_type extract(const_iterator __pos) { __node_type* __n = __pos._M_cur; size_t __bkt = _M_bucket_index(__n); // Look for previous node to unlink it from the erased one, this // is why we need buckets to contain the before begin to make // this search fast. __node_base* __prev_n = _M_get_previous_node(__bkt, __n); if (__prev_n == _M_buckets[__bkt]) _M_remove_bucket_begin(__bkt, __n->_M_next(), __n->_M_nxt ? _M_bucket_index(__n->_M_next()) : 0); else if (__n->_M_nxt) { size_type __next_bkt = _M_bucket_index(__n->_M_next()); if (__next_bkt != __bkt) _M_buckets[__next_bkt] = __prev_n; } __prev_n->_M_nxt = __n->_M_nxt; __n->_M_nxt = nullptr; --_M_element_count; return { __n, this->_M_node_allocator() }; } /// Extract a node. node_type extract(const _Key& __k) { node_type __nh; auto __pos = find(__k); if (__pos != end()) __nh = extract(const_iterator(__pos)); return __nh; } /// Merge from a compatible container into one with unique keys. template void _M_merge_unique(_Compatible_Hashtable& __src) noexcept { static_assert(is_same_v, "Node types are compatible"); __glibcxx_assert(get_allocator() == __src.get_allocator()); auto __n_elt = __src.size(); for (auto __i = __src.begin(), __end = __src.end(); __i != __end;) { auto __pos = __i++; const key_type& __k = this->_M_extract()(__pos._M_cur->_M_v()); __hash_code __code = this->_M_hash_code(__k); size_type __bkt = _M_bucket_index(__k, __code); if (_M_find_node(__bkt, __k, __code) == nullptr) { auto __nh = __src.extract(__pos); _M_insert_unique_node(__bkt, __code, __nh._M_ptr, __n_elt); __nh._M_ptr = nullptr; __n_elt = 1; } else if (__n_elt != 1) --__n_elt; } } /// Merge from a compatible container into one with equivalent keys. template void _M_merge_multi(_Compatible_Hashtable& __src) noexcept { static_assert(is_same_v, "Node types are compatible"); __glibcxx_assert(get_allocator() == __src.get_allocator()); this->reserve(size() + __src.size()); for (auto __i = __src.begin(), __end = __src.end(); __i != __end;) _M_reinsert_node_multi(cend(), __src.extract(__i++)); } #endif // C++17 private: // Helper rehash method used when keys are unique. void _M_rehash_aux(size_type __n, std::true_type); // Helper rehash method used when keys can be non-unique. void _M_rehash_aux(size_type __n, std::false_type); // Unconditionally change size of bucket array to n, restore // hash policy state to __state on exception. void _M_rehash(size_type __n, const __rehash_state& __state); }; // Definitions of class template _Hashtable's out-of-line member functions. template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_bucket_begin(size_type __bkt) const -> __node_type* { __node_base* __n = _M_buckets[__bkt]; return __n ? static_cast<__node_type*>(__n->_M_nxt) : nullptr; } template _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _Hashtable(size_type __bucket_hint, const _H1& __h1, const _H2& __h2, const _Hash& __h, const _Equal& __eq, const _ExtractKey& __exk, const allocator_type& __a) : _Hashtable(__h1, __h2, __h, __eq, __exk, __a) { auto __bkt = _M_rehash_policy._M_next_bkt(__bucket_hint); if (__bkt > _M_bucket_count) { _M_buckets = _M_allocate_buckets(__bkt); _M_bucket_count = __bkt; } } template template _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _Hashtable(_InputIterator __f, _InputIterator __l, size_type __bucket_hint, const _H1& __h1, const _H2& __h2, const _Hash& __h, const _Equal& __eq, const _ExtractKey& __exk, const allocator_type& __a) : _Hashtable(__h1, __h2, __h, __eq, __exk, __a) { auto __nb_elems = __detail::__distance_fw(__f, __l); auto __bkt_count = _M_rehash_policy._M_next_bkt( std::max(_M_rehash_policy._M_bkt_for_elements(__nb_elems), __bucket_hint)); if (__bkt_count > _M_bucket_count) { _M_buckets = _M_allocate_buckets(__bkt_count); _M_bucket_count = __bkt_count; } for (; __f != __l; ++__f) this->insert(*__f); } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: operator=(const _Hashtable& __ht) -> _Hashtable& { if (&__ht == this) return *this; if (__node_alloc_traits::_S_propagate_on_copy_assign()) { auto& __this_alloc = this->_M_node_allocator(); auto& __that_alloc = __ht._M_node_allocator(); if (!__node_alloc_traits::_S_always_equal() && __this_alloc != __that_alloc) { // Replacement allocator cannot free existing storage. this->_M_deallocate_nodes(_M_begin()); _M_before_begin._M_nxt = nullptr; _M_deallocate_buckets(); _M_buckets = nullptr; std::__alloc_on_copy(__this_alloc, __that_alloc); __hashtable_base::operator=(__ht); _M_bucket_count = __ht._M_bucket_count; _M_element_count = __ht._M_element_count; _M_rehash_policy = __ht._M_rehash_policy; __try { _M_assign(__ht, [this](const __node_type* __n) { return this->_M_allocate_node(__n->_M_v()); }); } __catch(...) { // _M_assign took care of deallocating all memory. Now we // must make sure this instance remains in a usable state. _M_reset(); __throw_exception_again; } return *this; } std::__alloc_on_copy(__this_alloc, __that_alloc); } // Reuse allocated buckets and nodes. __bucket_type* __former_buckets = nullptr; std::size_t __former_bucket_count = _M_bucket_count; const __rehash_state& __former_state = _M_rehash_policy._M_state(); if (_M_bucket_count != __ht._M_bucket_count) { __former_buckets = _M_buckets; _M_buckets = _M_allocate_buckets(__ht._M_bucket_count); _M_bucket_count = __ht._M_bucket_count; } else __builtin_memset(_M_buckets, 0, _M_bucket_count * sizeof(__bucket_type)); __try { __hashtable_base::operator=(__ht); _M_element_count = __ht._M_element_count; _M_rehash_policy = __ht._M_rehash_policy; __reuse_or_alloc_node_type __roan(_M_begin(), *this); _M_before_begin._M_nxt = nullptr; _M_assign(__ht, [&__roan](const __node_type* __n) { return __roan(__n->_M_v()); }); if (__former_buckets) _M_deallocate_buckets(__former_buckets, __former_bucket_count); } __catch(...) { if (__former_buckets) { // Restore previous buckets. _M_deallocate_buckets(); _M_rehash_policy._M_reset(__former_state); _M_buckets = __former_buckets; _M_bucket_count = __former_bucket_count; } __builtin_memset(_M_buckets, 0, _M_bucket_count * sizeof(__bucket_type)); __throw_exception_again; } return *this; } template template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_assign(const _Hashtable& __ht, const _NodeGenerator& __node_gen) { __bucket_type* __buckets = nullptr; if (!_M_buckets) _M_buckets = __buckets = _M_allocate_buckets(_M_bucket_count); __try { if (!__ht._M_before_begin._M_nxt) return; // First deal with the special first node pointed to by // _M_before_begin. __node_type* __ht_n = __ht._M_begin(); __node_type* __this_n = __node_gen(__ht_n); this->_M_copy_code(__this_n, __ht_n); _M_before_begin._M_nxt = __this_n; _M_buckets[_M_bucket_index(__this_n)] = &_M_before_begin; // Then deal with other nodes. __node_base* __prev_n = __this_n; for (__ht_n = __ht_n->_M_next(); __ht_n; __ht_n = __ht_n->_M_next()) { __this_n = __node_gen(__ht_n); __prev_n->_M_nxt = __this_n; this->_M_copy_code(__this_n, __ht_n); size_type __bkt = _M_bucket_index(__this_n); if (!_M_buckets[__bkt]) _M_buckets[__bkt] = __prev_n; __prev_n = __this_n; } } __catch(...) { clear(); if (__buckets) _M_deallocate_buckets(); __throw_exception_again; } } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_reset() noexcept { _M_rehash_policy._M_reset(); _M_bucket_count = 1; _M_single_bucket = nullptr; _M_buckets = &_M_single_bucket; _M_before_begin._M_nxt = nullptr; _M_element_count = 0; } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_move_assign(_Hashtable&& __ht, std::true_type) { this->_M_deallocate_nodes(_M_begin()); _M_deallocate_buckets(); __hashtable_base::operator=(std::move(__ht)); _M_rehash_policy = __ht._M_rehash_policy; if (!__ht._M_uses_single_bucket()) _M_buckets = __ht._M_buckets; else { _M_buckets = &_M_single_bucket; _M_single_bucket = __ht._M_single_bucket; } _M_bucket_count = __ht._M_bucket_count; _M_before_begin._M_nxt = __ht._M_before_begin._M_nxt; _M_element_count = __ht._M_element_count; std::__alloc_on_move(this->_M_node_allocator(), __ht._M_node_allocator()); // Fix buckets containing the _M_before_begin pointers that can't be // moved. if (_M_begin()) _M_buckets[_M_bucket_index(_M_begin())] = &_M_before_begin; __ht._M_reset(); } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_move_assign(_Hashtable&& __ht, std::false_type) { if (__ht._M_node_allocator() == this->_M_node_allocator()) _M_move_assign(std::move(__ht), std::true_type()); else { // Can't move memory, move elements then. __bucket_type* __former_buckets = nullptr; size_type __former_bucket_count = _M_bucket_count; const __rehash_state& __former_state = _M_rehash_policy._M_state(); if (_M_bucket_count != __ht._M_bucket_count) { __former_buckets = _M_buckets; _M_buckets = _M_allocate_buckets(__ht._M_bucket_count); _M_bucket_count = __ht._M_bucket_count; } else __builtin_memset(_M_buckets, 0, _M_bucket_count * sizeof(__bucket_type)); __try { __hashtable_base::operator=(std::move(__ht)); _M_element_count = __ht._M_element_count; _M_rehash_policy = __ht._M_rehash_policy; __reuse_or_alloc_node_type __roan(_M_begin(), *this); _M_before_begin._M_nxt = nullptr; _M_assign(__ht, [&__roan](__node_type* __n) { return __roan(std::move_if_noexcept(__n->_M_v())); }); if (__former_buckets) _M_deallocate_buckets(__former_buckets, __former_bucket_count); __ht.clear(); } __catch(...) { if (__former_buckets) { _M_deallocate_buckets(); _M_rehash_policy._M_reset(__former_state); _M_buckets = __former_buckets; _M_bucket_count = __former_bucket_count; } __builtin_memset(_M_buckets, 0, _M_bucket_count * sizeof(__bucket_type)); __throw_exception_again; } } } template _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _Hashtable(const _Hashtable& __ht) : __hashtable_base(__ht), __map_base(__ht), __rehash_base(__ht), __hashtable_alloc( __node_alloc_traits::_S_select_on_copy(__ht._M_node_allocator())), _M_buckets(nullptr), _M_bucket_count(__ht._M_bucket_count), _M_element_count(__ht._M_element_count), _M_rehash_policy(__ht._M_rehash_policy) { _M_assign(__ht, [this](const __node_type* __n) { return this->_M_allocate_node(__n->_M_v()); }); } template _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _Hashtable(_Hashtable&& __ht) noexcept : __hashtable_base(__ht), __map_base(__ht), __rehash_base(__ht), __hashtable_alloc(std::move(__ht._M_base_alloc())), _M_buckets(__ht._M_buckets), _M_bucket_count(__ht._M_bucket_count), _M_before_begin(__ht._M_before_begin._M_nxt), _M_element_count(__ht._M_element_count), _M_rehash_policy(__ht._M_rehash_policy) { // Update, if necessary, buckets if __ht is using its single bucket. if (__ht._M_uses_single_bucket()) { _M_buckets = &_M_single_bucket; _M_single_bucket = __ht._M_single_bucket; } // Update, if necessary, bucket pointing to before begin that hasn't // moved. if (_M_begin()) _M_buckets[_M_bucket_index(_M_begin())] = &_M_before_begin; __ht._M_reset(); } template _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _Hashtable(const _Hashtable& __ht, const allocator_type& __a) : __hashtable_base(__ht), __map_base(__ht), __rehash_base(__ht), __hashtable_alloc(__node_alloc_type(__a)), _M_buckets(), _M_bucket_count(__ht._M_bucket_count), _M_element_count(__ht._M_element_count), _M_rehash_policy(__ht._M_rehash_policy) { _M_assign(__ht, [this](const __node_type* __n) { return this->_M_allocate_node(__n->_M_v()); }); } template _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _Hashtable(_Hashtable&& __ht, const allocator_type& __a) : __hashtable_base(__ht), __map_base(__ht), __rehash_base(__ht), __hashtable_alloc(__node_alloc_type(__a)), _M_buckets(nullptr), _M_bucket_count(__ht._M_bucket_count), _M_element_count(__ht._M_element_count), _M_rehash_policy(__ht._M_rehash_policy) { if (__ht._M_node_allocator() == this->_M_node_allocator()) { if (__ht._M_uses_single_bucket()) { _M_buckets = &_M_single_bucket; _M_single_bucket = __ht._M_single_bucket; } else _M_buckets = __ht._M_buckets; _M_before_begin._M_nxt = __ht._M_before_begin._M_nxt; // Update, if necessary, bucket pointing to before begin that hasn't // moved. if (_M_begin()) _M_buckets[_M_bucket_index(_M_begin())] = &_M_before_begin; __ht._M_reset(); } else { _M_assign(__ht, [this](__node_type* __n) { return this->_M_allocate_node( std::move_if_noexcept(__n->_M_v())); }); __ht.clear(); } } template _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: ~_Hashtable() noexcept { clear(); _M_deallocate_buckets(); } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: swap(_Hashtable& __x) noexcept(__and_<__is_nothrow_swappable<_H1>, __is_nothrow_swappable<_Equal>>::value) { // The only base class with member variables is hash_code_base. // We define _Hash_code_base::_M_swap because different // specializations have different members. this->_M_swap(__x); std::__alloc_on_swap(this->_M_node_allocator(), __x._M_node_allocator()); std::swap(_M_rehash_policy, __x._M_rehash_policy); // Deal properly with potentially moved instances. if (this->_M_uses_single_bucket()) { if (!__x._M_uses_single_bucket()) { _M_buckets = __x._M_buckets; __x._M_buckets = &__x._M_single_bucket; } } else if (__x._M_uses_single_bucket()) { __x._M_buckets = _M_buckets; _M_buckets = &_M_single_bucket; } else std::swap(_M_buckets, __x._M_buckets); std::swap(_M_bucket_count, __x._M_bucket_count); std::swap(_M_before_begin._M_nxt, __x._M_before_begin._M_nxt); std::swap(_M_element_count, __x._M_element_count); std::swap(_M_single_bucket, __x._M_single_bucket); // Fix buckets containing the _M_before_begin pointers that can't be // swapped. if (_M_begin()) _M_buckets[_M_bucket_index(_M_begin())] = &_M_before_begin; if (__x._M_begin()) __x._M_buckets[__x._M_bucket_index(__x._M_begin())] = &__x._M_before_begin; } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: find(const key_type& __k) -> iterator { __hash_code __code = this->_M_hash_code(__k); std::size_t __n = _M_bucket_index(__k, __code); __node_type* __p = _M_find_node(__n, __k, __code); return __p ? iterator(__p) : end(); } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: find(const key_type& __k) const -> const_iterator { __hash_code __code = this->_M_hash_code(__k); std::size_t __n = _M_bucket_index(__k, __code); __node_type* __p = _M_find_node(__n, __k, __code); return __p ? const_iterator(__p) : end(); } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: count(const key_type& __k) const -> size_type { __hash_code __code = this->_M_hash_code(__k); std::size_t __n = _M_bucket_index(__k, __code); __node_type* __p = _M_bucket_begin(__n); if (!__p) return 0; std::size_t __result = 0; for (;; __p = __p->_M_next()) { if (this->_M_equals(__k, __code, __p)) ++__result; else if (__result) // All equivalent values are next to each other, if we // found a non-equivalent value after an equivalent one it // means that we won't find any new equivalent value. break; if (!__p->_M_nxt || _M_bucket_index(__p->_M_next()) != __n) break; } return __result; } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: equal_range(const key_type& __k) -> pair { __hash_code __code = this->_M_hash_code(__k); std::size_t __n = _M_bucket_index(__k, __code); __node_type* __p = _M_find_node(__n, __k, __code); if (__p) { __node_type* __p1 = __p->_M_next(); while (__p1 && _M_bucket_index(__p1) == __n && this->_M_equals(__k, __code, __p1)) __p1 = __p1->_M_next(); return std::make_pair(iterator(__p), iterator(__p1)); } else return std::make_pair(end(), end()); } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: equal_range(const key_type& __k) const -> pair { __hash_code __code = this->_M_hash_code(__k); std::size_t __n = _M_bucket_index(__k, __code); __node_type* __p = _M_find_node(__n, __k, __code); if (__p) { __node_type* __p1 = __p->_M_next(); while (__p1 && _M_bucket_index(__p1) == __n && this->_M_equals(__k, __code, __p1)) __p1 = __p1->_M_next(); return std::make_pair(const_iterator(__p), const_iterator(__p1)); } else return std::make_pair(end(), end()); } // Find the node whose key compares equal to k in the bucket n. // Return nullptr if no node is found. template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_find_before_node(size_type __n, const key_type& __k, __hash_code __code) const -> __node_base* { __node_base* __prev_p = _M_buckets[__n]; if (!__prev_p) return nullptr; for (__node_type* __p = static_cast<__node_type*>(__prev_p->_M_nxt);; __p = __p->_M_next()) { if (this->_M_equals(__k, __code, __p)) return __prev_p; if (!__p->_M_nxt || _M_bucket_index(__p->_M_next()) != __n) break; __prev_p = __p; } return nullptr; } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_insert_bucket_begin(size_type __bkt, __node_type* __node) { if (_M_buckets[__bkt]) { // Bucket is not empty, we just need to insert the new node // after the bucket before begin. __node->_M_nxt = _M_buckets[__bkt]->_M_nxt; _M_buckets[__bkt]->_M_nxt = __node; } else { // The bucket is empty, the new node is inserted at the // beginning of the singly-linked list and the bucket will // contain _M_before_begin pointer. __node->_M_nxt = _M_before_begin._M_nxt; _M_before_begin._M_nxt = __node; if (__node->_M_nxt) // We must update former begin bucket that is pointing to // _M_before_begin. _M_buckets[_M_bucket_index(__node->_M_next())] = __node; _M_buckets[__bkt] = &_M_before_begin; } } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_remove_bucket_begin(size_type __bkt, __node_type* __next, size_type __next_bkt) { if (!__next || __next_bkt != __bkt) { // Bucket is now empty // First update next bucket if any if (__next) _M_buckets[__next_bkt] = _M_buckets[__bkt]; // Second update before begin node if necessary if (&_M_before_begin == _M_buckets[__bkt]) _M_before_begin._M_nxt = __next; _M_buckets[__bkt] = nullptr; } } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_get_previous_node(size_type __bkt, __node_base* __n) -> __node_base* { __node_base* __prev_n = _M_buckets[__bkt]; while (__prev_n->_M_nxt != __n) __prev_n = __prev_n->_M_nxt; return __prev_n; } template template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_emplace(std::true_type, _Args&&... __args) -> pair { // First build the node to get access to the hash code __node_type* __node = this->_M_allocate_node(std::forward<_Args>(__args)...); const key_type& __k = this->_M_extract()(__node->_M_v()); __hash_code __code; __try { __code = this->_M_hash_code(__k); } __catch(...) { this->_M_deallocate_node(__node); __throw_exception_again; } size_type __bkt = _M_bucket_index(__k, __code); if (__node_type* __p = _M_find_node(__bkt, __k, __code)) { // There is already an equivalent node, no insertion this->_M_deallocate_node(__node); return std::make_pair(iterator(__p), false); } // Insert the node return std::make_pair(_M_insert_unique_node(__bkt, __code, __node), true); } template template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_emplace(const_iterator __hint, std::false_type, _Args&&... __args) -> iterator { // First build the node to get its hash code. __node_type* __node = this->_M_allocate_node(std::forward<_Args>(__args)...); __hash_code __code; __try { __code = this->_M_hash_code(this->_M_extract()(__node->_M_v())); } __catch(...) { this->_M_deallocate_node(__node); __throw_exception_again; } return _M_insert_multi_node(__hint._M_cur, __code, __node); } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_insert_unique_node(size_type __bkt, __hash_code __code, __node_type* __node, size_type __n_elt) -> iterator { const __rehash_state& __saved_state = _M_rehash_policy._M_state(); std::pair __do_rehash = _M_rehash_policy._M_need_rehash(_M_bucket_count, _M_element_count, __n_elt); __try { if (__do_rehash.first) { _M_rehash(__do_rehash.second, __saved_state); __bkt = _M_bucket_index(this->_M_extract()(__node->_M_v()), __code); } this->_M_store_code(__node, __code); // Always insert at the beginning of the bucket. _M_insert_bucket_begin(__bkt, __node); ++_M_element_count; return iterator(__node); } __catch(...) { this->_M_deallocate_node(__node); __throw_exception_again; } } // Insert node, in bucket bkt if no rehash (assumes no element with its key // already present). Take ownership of the node, deallocate it on exception. template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_insert_multi_node(__node_type* __hint, __hash_code __code, __node_type* __node) -> iterator { const __rehash_state& __saved_state = _M_rehash_policy._M_state(); std::pair __do_rehash = _M_rehash_policy._M_need_rehash(_M_bucket_count, _M_element_count, 1); __try { if (__do_rehash.first) _M_rehash(__do_rehash.second, __saved_state); this->_M_store_code(__node, __code); const key_type& __k = this->_M_extract()(__node->_M_v()); size_type __bkt = _M_bucket_index(__k, __code); // Find the node before an equivalent one or use hint if it exists and // if it is equivalent. __node_base* __prev = __builtin_expect(__hint != nullptr, false) && this->_M_equals(__k, __code, __hint) ? __hint : _M_find_before_node(__bkt, __k, __code); if (__prev) { // Insert after the node before the equivalent one. __node->_M_nxt = __prev->_M_nxt; __prev->_M_nxt = __node; if (__builtin_expect(__prev == __hint, false)) // hint might be the last bucket node, in this case we need to // update next bucket. if (__node->_M_nxt && !this->_M_equals(__k, __code, __node->_M_next())) { size_type __next_bkt = _M_bucket_index(__node->_M_next()); if (__next_bkt != __bkt) _M_buckets[__next_bkt] = __node; } } else // The inserted node has no equivalent in the // hashtable. We must insert the new node at the // beginning of the bucket to preserve equivalent // elements' relative positions. _M_insert_bucket_begin(__bkt, __node); ++_M_element_count; return iterator(__node); } __catch(...) { this->_M_deallocate_node(__node); __throw_exception_again; } } // Insert v if no element with its key is already present. template template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_insert(_Arg&& __v, const _NodeGenerator& __node_gen, true_type, size_type __n_elt) -> pair { const key_type& __k = this->_M_extract()(__v); __hash_code __code = this->_M_hash_code(__k); size_type __bkt = _M_bucket_index(__k, __code); __node_type* __n = _M_find_node(__bkt, __k, __code); if (__n) return std::make_pair(iterator(__n), false); __n = __node_gen(std::forward<_Arg>(__v)); return { _M_insert_unique_node(__bkt, __code, __n, __n_elt), true }; } // Insert v unconditionally. template template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_insert(const_iterator __hint, _Arg&& __v, const _NodeGenerator& __node_gen, false_type) -> iterator { // First compute the hash code so that we don't do anything if it // throws. __hash_code __code = this->_M_hash_code(this->_M_extract()(__v)); // Second allocate new node so that we don't rehash if it throws. __node_type* __node = __node_gen(std::forward<_Arg>(__v)); return _M_insert_multi_node(__hint._M_cur, __code, __node); } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: erase(const_iterator __it) -> iterator { __node_type* __n = __it._M_cur; std::size_t __bkt = _M_bucket_index(__n); // Look for previous node to unlink it from the erased one, this // is why we need buckets to contain the before begin to make // this search fast. __node_base* __prev_n = _M_get_previous_node(__bkt, __n); return _M_erase(__bkt, __prev_n, __n); } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_erase(size_type __bkt, __node_base* __prev_n, __node_type* __n) -> iterator { if (__prev_n == _M_buckets[__bkt]) _M_remove_bucket_begin(__bkt, __n->_M_next(), __n->_M_nxt ? _M_bucket_index(__n->_M_next()) : 0); else if (__n->_M_nxt) { size_type __next_bkt = _M_bucket_index(__n->_M_next()); if (__next_bkt != __bkt) _M_buckets[__next_bkt] = __prev_n; } __prev_n->_M_nxt = __n->_M_nxt; iterator __result(__n->_M_next()); this->_M_deallocate_node(__n); --_M_element_count; return __result; } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_erase(std::true_type, const key_type& __k) -> size_type { __hash_code __code = this->_M_hash_code(__k); std::size_t __bkt = _M_bucket_index(__k, __code); // Look for the node before the first matching node. __node_base* __prev_n = _M_find_before_node(__bkt, __k, __code); if (!__prev_n) return 0; // We found a matching node, erase it. __node_type* __n = static_cast<__node_type*>(__prev_n->_M_nxt); _M_erase(__bkt, __prev_n, __n); return 1; } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_erase(std::false_type, const key_type& __k) -> size_type { __hash_code __code = this->_M_hash_code(__k); std::size_t __bkt = _M_bucket_index(__k, __code); // Look for the node before the first matching node. __node_base* __prev_n = _M_find_before_node(__bkt, __k, __code); if (!__prev_n) return 0; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 526. Is it undefined if a function in the standard changes // in parameters? // We use one loop to find all matching nodes and another to deallocate // them so that the key stays valid during the first loop. It might be // invalidated indirectly when destroying nodes. __node_type* __n = static_cast<__node_type*>(__prev_n->_M_nxt); __node_type* __n_last = __n; std::size_t __n_last_bkt = __bkt; do { __n_last = __n_last->_M_next(); if (!__n_last) break; __n_last_bkt = _M_bucket_index(__n_last); } while (__n_last_bkt == __bkt && this->_M_equals(__k, __code, __n_last)); // Deallocate nodes. size_type __result = 0; do { __node_type* __p = __n->_M_next(); this->_M_deallocate_node(__n); __n = __p; ++__result; --_M_element_count; } while (__n != __n_last); if (__prev_n == _M_buckets[__bkt]) _M_remove_bucket_begin(__bkt, __n_last, __n_last_bkt); else if (__n_last && __n_last_bkt != __bkt) _M_buckets[__n_last_bkt] = __prev_n; __prev_n->_M_nxt = __n_last; return __result; } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: erase(const_iterator __first, const_iterator __last) -> iterator { __node_type* __n = __first._M_cur; __node_type* __last_n = __last._M_cur; if (__n == __last_n) return iterator(__n); std::size_t __bkt = _M_bucket_index(__n); __node_base* __prev_n = _M_get_previous_node(__bkt, __n); bool __is_bucket_begin = __n == _M_bucket_begin(__bkt); std::size_t __n_bkt = __bkt; for (;;) { do { __node_type* __tmp = __n; __n = __n->_M_next(); this->_M_deallocate_node(__tmp); --_M_element_count; if (!__n) break; __n_bkt = _M_bucket_index(__n); } while (__n != __last_n && __n_bkt == __bkt); if (__is_bucket_begin) _M_remove_bucket_begin(__bkt, __n, __n_bkt); if (__n == __last_n) break; __is_bucket_begin = true; __bkt = __n_bkt; } if (__n && (__n_bkt != __bkt || __is_bucket_begin)) _M_buckets[__n_bkt] = __prev_n; __prev_n->_M_nxt = __n; return iterator(__n); } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: clear() noexcept { this->_M_deallocate_nodes(_M_begin()); __builtin_memset(_M_buckets, 0, _M_bucket_count * sizeof(__bucket_type)); _M_element_count = 0; _M_before_begin._M_nxt = nullptr; } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: rehash(size_type __n) { const __rehash_state& __saved_state = _M_rehash_policy._M_state(); std::size_t __buckets = std::max(_M_rehash_policy._M_bkt_for_elements(_M_element_count + 1), __n); __buckets = _M_rehash_policy._M_next_bkt(__buckets); if (__buckets != _M_bucket_count) _M_rehash(__buckets, __saved_state); else // No rehash, restore previous state to keep a consistent state. _M_rehash_policy._M_reset(__saved_state); } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_rehash(size_type __n, const __rehash_state& __state) { __try { _M_rehash_aux(__n, __unique_keys()); } __catch(...) { // A failure here means that buckets allocation failed. We only // have to restore hash policy previous state. _M_rehash_policy._M_reset(__state); __throw_exception_again; } } // Rehash when there is no equivalent elements. template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_rehash_aux(size_type __n, std::true_type) { __bucket_type* __new_buckets = _M_allocate_buckets(__n); __node_type* __p = _M_begin(); _M_before_begin._M_nxt = nullptr; std::size_t __bbegin_bkt = 0; while (__p) { __node_type* __next = __p->_M_next(); std::size_t __bkt = __hash_code_base::_M_bucket_index(__p, __n); if (!__new_buckets[__bkt]) { __p->_M_nxt = _M_before_begin._M_nxt; _M_before_begin._M_nxt = __p; __new_buckets[__bkt] = &_M_before_begin; if (__p->_M_nxt) __new_buckets[__bbegin_bkt] = __p; __bbegin_bkt = __bkt; } else { __p->_M_nxt = __new_buckets[__bkt]->_M_nxt; __new_buckets[__bkt]->_M_nxt = __p; } __p = __next; } _M_deallocate_buckets(); _M_bucket_count = __n; _M_buckets = __new_buckets; } // Rehash when there can be equivalent elements, preserve their relative // order. template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_rehash_aux(size_type __n, std::false_type) { __bucket_type* __new_buckets = _M_allocate_buckets(__n); __node_type* __p = _M_begin(); _M_before_begin._M_nxt = nullptr; std::size_t __bbegin_bkt = 0; std::size_t __prev_bkt = 0; __node_type* __prev_p = nullptr; bool __check_bucket = false; while (__p) { __node_type* __next = __p->_M_next(); std::size_t __bkt = __hash_code_base::_M_bucket_index(__p, __n); if (__prev_p && __prev_bkt == __bkt) { // Previous insert was already in this bucket, we insert after // the previously inserted one to preserve equivalent elements // relative order. __p->_M_nxt = __prev_p->_M_nxt; __prev_p->_M_nxt = __p; // Inserting after a node in a bucket require to check that we // haven't change the bucket last node, in this case next // bucket containing its before begin node must be updated. We // schedule a check as soon as we move out of the sequence of // equivalent nodes to limit the number of checks. __check_bucket = true; } else { if (__check_bucket) { // Check if we shall update the next bucket because of // insertions into __prev_bkt bucket. if (__prev_p->_M_nxt) { std::size_t __next_bkt = __hash_code_base::_M_bucket_index(__prev_p->_M_next(), __n); if (__next_bkt != __prev_bkt) __new_buckets[__next_bkt] = __prev_p; } __check_bucket = false; } if (!__new_buckets[__bkt]) { __p->_M_nxt = _M_before_begin._M_nxt; _M_before_begin._M_nxt = __p; __new_buckets[__bkt] = &_M_before_begin; if (__p->_M_nxt) __new_buckets[__bbegin_bkt] = __p; __bbegin_bkt = __bkt; } else { __p->_M_nxt = __new_buckets[__bkt]->_M_nxt; __new_buckets[__bkt]->_M_nxt = __p; } } __prev_p = __p; __prev_bkt = __bkt; __p = __next; } if (__check_bucket && __prev_p->_M_nxt) { std::size_t __next_bkt = __hash_code_base::_M_bucket_index(__prev_p->_M_next(), __n); if (__next_bkt != __prev_bkt) __new_buckets[__next_bkt] = __prev_p; } _M_deallocate_buckets(); _M_bucket_count = __n; _M_buckets = __new_buckets; } #if __cplusplus > 201402L template class _Hash_merge_helper { }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _HASHTABLE_H PK!P&  8/bits/hashtable_policy.hnu[// Internal policy header for unordered_set and unordered_map -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/hashtable_policy.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. * @headername{unordered_map,unordered_set} */ #ifndef _HASHTABLE_POLICY_H #define _HASHTABLE_POLICY_H 1 #include // for std::tuple, std::forward_as_tuple #include // for std::uint_fast64_t #include // for std::min. namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template class _Hashtable; namespace __detail { /** * @defgroup hashtable-detail Base and Implementation Classes * @ingroup unordered_associative_containers * @{ */ template struct _Hashtable_base; // Helper function: return distance(first, last) for forward // iterators, or 0/1 for input iterators. template inline typename std::iterator_traits<_Iterator>::difference_type __distance_fw(_Iterator __first, _Iterator __last, std::input_iterator_tag) { return __first != __last ? 1 : 0; } template inline typename std::iterator_traits<_Iterator>::difference_type __distance_fw(_Iterator __first, _Iterator __last, std::forward_iterator_tag) { return std::distance(__first, __last); } template inline typename std::iterator_traits<_Iterator>::difference_type __distance_fw(_Iterator __first, _Iterator __last) { return __distance_fw(__first, __last, std::__iterator_category(__first)); } struct _Identity { template _Tp&& operator()(_Tp&& __x) const { return std::forward<_Tp>(__x); } }; struct _Select1st { template auto operator()(_Tp&& __x) const -> decltype(std::get<0>(std::forward<_Tp>(__x))) { return std::get<0>(std::forward<_Tp>(__x)); } }; template struct _Hashtable_alloc; // Functor recycling a pool of nodes and using allocation once the pool is // empty. template struct _ReuseOrAllocNode { private: using __node_alloc_type = _NodeAlloc; using __hashtable_alloc = _Hashtable_alloc<__node_alloc_type>; using __node_alloc_traits = typename __hashtable_alloc::__node_alloc_traits; using __node_type = typename __hashtable_alloc::__node_type; public: _ReuseOrAllocNode(__node_type* __nodes, __hashtable_alloc& __h) : _M_nodes(__nodes), _M_h(__h) { } _ReuseOrAllocNode(const _ReuseOrAllocNode&) = delete; ~_ReuseOrAllocNode() { _M_h._M_deallocate_nodes(_M_nodes); } template __node_type* operator()(_Arg&& __arg) const { if (_M_nodes) { __node_type* __node = _M_nodes; _M_nodes = _M_nodes->_M_next(); __node->_M_nxt = nullptr; auto& __a = _M_h._M_node_allocator(); __node_alloc_traits::destroy(__a, __node->_M_valptr()); __try { __node_alloc_traits::construct(__a, __node->_M_valptr(), std::forward<_Arg>(__arg)); } __catch(...) { __node->~__node_type(); __node_alloc_traits::deallocate(__a, __node, 1); __throw_exception_again; } return __node; } return _M_h._M_allocate_node(std::forward<_Arg>(__arg)); } private: mutable __node_type* _M_nodes; __hashtable_alloc& _M_h; }; // Functor similar to the previous one but without any pool of nodes to // recycle. template struct _AllocNode { private: using __hashtable_alloc = _Hashtable_alloc<_NodeAlloc>; using __node_type = typename __hashtable_alloc::__node_type; public: _AllocNode(__hashtable_alloc& __h) : _M_h(__h) { } template __node_type* operator()(_Arg&& __arg) const { return _M_h._M_allocate_node(std::forward<_Arg>(__arg)); } private: __hashtable_alloc& _M_h; }; // Auxiliary types used for all instantiations of _Hashtable nodes // and iterators. /** * struct _Hashtable_traits * * Important traits for hash tables. * * @tparam _Cache_hash_code Boolean value. True if the value of * the hash function is stored along with the value. This is a * time-space tradeoff. Storing it may improve lookup speed by * reducing the number of times we need to call the _Equal * function. * * @tparam _Constant_iterators Boolean value. True if iterator and * const_iterator are both constant iterator types. This is true * for unordered_set and unordered_multiset, false for * unordered_map and unordered_multimap. * * @tparam _Unique_keys Boolean value. True if the return value * of _Hashtable::count(k) is always at most one, false if it may * be an arbitrary number. This is true for unordered_set and * unordered_map, false for unordered_multiset and * unordered_multimap. */ template struct _Hashtable_traits { using __hash_cached = __bool_constant<_Cache_hash_code>; using __constant_iterators = __bool_constant<_Constant_iterators>; using __unique_keys = __bool_constant<_Unique_keys>; }; /** * struct _Hash_node_base * * Nodes, used to wrap elements stored in the hash table. A policy * template parameter of class template _Hashtable controls whether * nodes also store a hash code. In some cases (e.g. strings) this * may be a performance win. */ struct _Hash_node_base { _Hash_node_base* _M_nxt; _Hash_node_base() noexcept : _M_nxt() { } _Hash_node_base(_Hash_node_base* __next) noexcept : _M_nxt(__next) { } }; /** * struct _Hash_node_value_base * * Node type with the value to store. */ template struct _Hash_node_value_base : _Hash_node_base { typedef _Value value_type; __gnu_cxx::__aligned_buffer<_Value> _M_storage; _Value* _M_valptr() noexcept { return _M_storage._M_ptr(); } const _Value* _M_valptr() const noexcept { return _M_storage._M_ptr(); } _Value& _M_v() noexcept { return *_M_valptr(); } const _Value& _M_v() const noexcept { return *_M_valptr(); } }; /** * Primary template struct _Hash_node. */ template struct _Hash_node; /** * Specialization for nodes with caches, struct _Hash_node. * * Base class is __detail::_Hash_node_value_base. */ template struct _Hash_node<_Value, true> : _Hash_node_value_base<_Value> { std::size_t _M_hash_code; _Hash_node* _M_next() const noexcept { return static_cast<_Hash_node*>(this->_M_nxt); } }; /** * Specialization for nodes without caches, struct _Hash_node. * * Base class is __detail::_Hash_node_value_base. */ template struct _Hash_node<_Value, false> : _Hash_node_value_base<_Value> { _Hash_node* _M_next() const noexcept { return static_cast<_Hash_node*>(this->_M_nxt); } }; /// Base class for node iterators. template struct _Node_iterator_base { using __node_type = _Hash_node<_Value, _Cache_hash_code>; __node_type* _M_cur; _Node_iterator_base(__node_type* __p) noexcept : _M_cur(__p) { } void _M_incr() noexcept { _M_cur = _M_cur->_M_next(); } }; template inline bool operator==(const _Node_iterator_base<_Value, _Cache_hash_code>& __x, const _Node_iterator_base<_Value, _Cache_hash_code >& __y) noexcept { return __x._M_cur == __y._M_cur; } template inline bool operator!=(const _Node_iterator_base<_Value, _Cache_hash_code>& __x, const _Node_iterator_base<_Value, _Cache_hash_code>& __y) noexcept { return __x._M_cur != __y._M_cur; } /// Node iterators, used to iterate through all the hashtable. template struct _Node_iterator : public _Node_iterator_base<_Value, __cache> { private: using __base_type = _Node_iterator_base<_Value, __cache>; using __node_type = typename __base_type::__node_type; public: typedef _Value value_type; typedef std::ptrdiff_t difference_type; typedef std::forward_iterator_tag iterator_category; using pointer = typename std::conditional<__constant_iterators, const _Value*, _Value*>::type; using reference = typename std::conditional<__constant_iterators, const _Value&, _Value&>::type; _Node_iterator() noexcept : __base_type(0) { } explicit _Node_iterator(__node_type* __p) noexcept : __base_type(__p) { } reference operator*() const noexcept { return this->_M_cur->_M_v(); } pointer operator->() const noexcept { return this->_M_cur->_M_valptr(); } _Node_iterator& operator++() noexcept { this->_M_incr(); return *this; } _Node_iterator operator++(int) noexcept { _Node_iterator __tmp(*this); this->_M_incr(); return __tmp; } }; /// Node const_iterators, used to iterate through all the hashtable. template struct _Node_const_iterator : public _Node_iterator_base<_Value, __cache> { private: using __base_type = _Node_iterator_base<_Value, __cache>; using __node_type = typename __base_type::__node_type; public: typedef _Value value_type; typedef std::ptrdiff_t difference_type; typedef std::forward_iterator_tag iterator_category; typedef const _Value* pointer; typedef const _Value& reference; _Node_const_iterator() noexcept : __base_type(0) { } explicit _Node_const_iterator(__node_type* __p) noexcept : __base_type(__p) { } _Node_const_iterator(const _Node_iterator<_Value, __constant_iterators, __cache>& __x) noexcept : __base_type(__x._M_cur) { } reference operator*() const noexcept { return this->_M_cur->_M_v(); } pointer operator->() const noexcept { return this->_M_cur->_M_valptr(); } _Node_const_iterator& operator++() noexcept { this->_M_incr(); return *this; } _Node_const_iterator operator++(int) noexcept { _Node_const_iterator __tmp(*this); this->_M_incr(); return __tmp; } }; // Many of class template _Hashtable's template parameters are policy // classes. These are defaults for the policies. /// Default range hashing function: use division to fold a large number /// into the range [0, N). struct _Mod_range_hashing { typedef std::size_t first_argument_type; typedef std::size_t second_argument_type; typedef std::size_t result_type; result_type operator()(first_argument_type __num, second_argument_type __den) const noexcept { return __num % __den; } }; /// Default ranged hash function H. In principle it should be a /// function object composed from objects of type H1 and H2 such that /// h(k, N) = h2(h1(k), N), but that would mean making extra copies of /// h1 and h2. So instead we'll just use a tag to tell class template /// hashtable to do that composition. struct _Default_ranged_hash { }; /// Default value for rehash policy. Bucket size is (usually) the /// smallest prime that keeps the load factor small enough. struct _Prime_rehash_policy { using __has_load_factor = std::true_type; _Prime_rehash_policy(float __z = 1.0) noexcept : _M_max_load_factor(__z), _M_next_resize(0) { } float max_load_factor() const noexcept { return _M_max_load_factor; } // Return a bucket size no smaller than n. std::size_t _M_next_bkt(std::size_t __n) const; // Return a bucket count appropriate for n elements std::size_t _M_bkt_for_elements(std::size_t __n) const { return __builtin_ceil(__n / (long double)_M_max_load_factor); } // __n_bkt is current bucket count, __n_elt is current element count, // and __n_ins is number of elements to be inserted. Do we need to // increase bucket count? If so, return make_pair(true, n), where n // is the new bucket count. If not, return make_pair(false, 0). std::pair _M_need_rehash(std::size_t __n_bkt, std::size_t __n_elt, std::size_t __n_ins) const; typedef std::size_t _State; _State _M_state() const { return _M_next_resize; } void _M_reset() noexcept { _M_next_resize = 0; } void _M_reset(_State __state) { _M_next_resize = __state; } static const std::size_t _S_growth_factor = 2; float _M_max_load_factor; mutable std::size_t _M_next_resize; }; /// Range hashing function assuming that second arg is a power of 2. struct _Mask_range_hashing { typedef std::size_t first_argument_type; typedef std::size_t second_argument_type; typedef std::size_t result_type; result_type operator()(first_argument_type __num, second_argument_type __den) const noexcept { return __num & (__den - 1); } }; /// Compute closest power of 2. _GLIBCXX14_CONSTEXPR inline std::size_t __clp2(std::size_t __n) noexcept { #if __SIZEOF_SIZE_T__ >= 8 std::uint_fast64_t __x = __n; #else std::uint_fast32_t __x = __n; #endif // Algorithm from Hacker's Delight, Figure 3-3. __x = __x - 1; __x = __x | (__x >> 1); __x = __x | (__x >> 2); __x = __x | (__x >> 4); __x = __x | (__x >> 8); __x = __x | (__x >>16); #if __SIZEOF_SIZE_T__ >= 8 __x = __x | (__x >>32); #endif return __x + 1; } /// Rehash policy providing power of 2 bucket numbers. Avoids modulo /// operations. struct _Power2_rehash_policy { using __has_load_factor = std::true_type; _Power2_rehash_policy(float __z = 1.0) noexcept : _M_max_load_factor(__z), _M_next_resize(0) { } float max_load_factor() const noexcept { return _M_max_load_factor; } // Return a bucket size no smaller than n (as long as n is not above the // highest power of 2). std::size_t _M_next_bkt(std::size_t __n) noexcept { const auto __max_width = std::min(sizeof(size_t), 8); const auto __max_bkt = size_t(1) << (__max_width * __CHAR_BIT__ - 1); std::size_t __res = __clp2(__n); if (__res == __n) __res <<= 1; if (__res == 0) __res = __max_bkt; if (__res == __max_bkt) // Set next resize to the max value so that we never try to rehash again // as we already reach the biggest possible bucket number. // Note that it might result in max_load_factor not being respected. _M_next_resize = std::size_t(-1); else _M_next_resize = __builtin_ceil(__res * (long double)_M_max_load_factor); return __res; } // Return a bucket count appropriate for n elements std::size_t _M_bkt_for_elements(std::size_t __n) const noexcept { return __builtin_ceil(__n / (long double)_M_max_load_factor); } // __n_bkt is current bucket count, __n_elt is current element count, // and __n_ins is number of elements to be inserted. Do we need to // increase bucket count? If so, return make_pair(true, n), where n // is the new bucket count. If not, return make_pair(false, 0). std::pair _M_need_rehash(std::size_t __n_bkt, std::size_t __n_elt, std::size_t __n_ins) noexcept { if (__n_elt + __n_ins >= _M_next_resize) { long double __min_bkts = (__n_elt + __n_ins) / (long double)_M_max_load_factor; if (__min_bkts >= __n_bkt) return std::make_pair(true, _M_next_bkt(std::max(__builtin_floor(__min_bkts) + 1, __n_bkt * _S_growth_factor))); _M_next_resize = __builtin_floor(__n_bkt * (long double)_M_max_load_factor); return std::make_pair(false, 0); } else return std::make_pair(false, 0); } typedef std::size_t _State; _State _M_state() const noexcept { return _M_next_resize; } void _M_reset() noexcept { _M_next_resize = 0; } void _M_reset(_State __state) noexcept { _M_next_resize = __state; } static const std::size_t _S_growth_factor = 2; float _M_max_load_factor; std::size_t _M_next_resize; }; // Base classes for std::_Hashtable. We define these base classes // because in some cases we want to do different things depending on // the value of a policy class. In some cases the policy class // affects which member functions and nested typedefs are defined; // we handle that by specializing base class templates. Several of // the base class templates need to access other members of class // template _Hashtable, so we use a variant of the "Curiously // Recurring Template Pattern" (CRTP) technique. /** * Primary class template _Map_base. * * If the hashtable has a value type of the form pair and a * key extraction policy (_ExtractKey) that returns the first part * of the pair, the hashtable gets a mapped_type typedef. If it * satisfies those criteria and also has unique keys, then it also * gets an operator[]. */ template struct _Map_base { }; /// Partial specialization, __unique_keys set to false. template struct _Map_base<_Key, _Pair, _Alloc, _Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, false> { using mapped_type = typename std::tuple_element<1, _Pair>::type; }; /// Partial specialization, __unique_keys set to true. template struct _Map_base<_Key, _Pair, _Alloc, _Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true> { private: using __hashtable_base = __detail::_Hashtable_base<_Key, _Pair, _Select1st, _Equal, _H1, _H2, _Hash, _Traits>; using __hashtable = _Hashtable<_Key, _Pair, _Alloc, _Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; using __hash_code = typename __hashtable_base::__hash_code; using __node_type = typename __hashtable_base::__node_type; public: using key_type = typename __hashtable_base::key_type; using iterator = typename __hashtable_base::iterator; using mapped_type = typename std::tuple_element<1, _Pair>::type; mapped_type& operator[](const key_type& __k); mapped_type& operator[](key_type&& __k); // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 761. unordered_map needs an at() member function. mapped_type& at(const key_type& __k); const mapped_type& at(const key_type& __k) const; }; template auto _Map_base<_Key, _Pair, _Alloc, _Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true>:: operator[](const key_type& __k) -> mapped_type& { __hashtable* __h = static_cast<__hashtable*>(this); __hash_code __code = __h->_M_hash_code(__k); std::size_t __n = __h->_M_bucket_index(__k, __code); __node_type* __p = __h->_M_find_node(__n, __k, __code); if (!__p) { __p = __h->_M_allocate_node(std::piecewise_construct, std::tuple(__k), std::tuple<>()); return __h->_M_insert_unique_node(__n, __code, __p)->second; } return __p->_M_v().second; } template auto _Map_base<_Key, _Pair, _Alloc, _Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true>:: operator[](key_type&& __k) -> mapped_type& { __hashtable* __h = static_cast<__hashtable*>(this); __hash_code __code = __h->_M_hash_code(__k); std::size_t __n = __h->_M_bucket_index(__k, __code); __node_type* __p = __h->_M_find_node(__n, __k, __code); if (!__p) { __p = __h->_M_allocate_node(std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::tuple<>()); return __h->_M_insert_unique_node(__n, __code, __p)->second; } return __p->_M_v().second; } template auto _Map_base<_Key, _Pair, _Alloc, _Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true>:: at(const key_type& __k) -> mapped_type& { __hashtable* __h = static_cast<__hashtable*>(this); __hash_code __code = __h->_M_hash_code(__k); std::size_t __n = __h->_M_bucket_index(__k, __code); __node_type* __p = __h->_M_find_node(__n, __k, __code); if (!__p) __throw_out_of_range(__N("_Map_base::at")); return __p->_M_v().second; } template auto _Map_base<_Key, _Pair, _Alloc, _Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true>:: at(const key_type& __k) const -> const mapped_type& { const __hashtable* __h = static_cast(this); __hash_code __code = __h->_M_hash_code(__k); std::size_t __n = __h->_M_bucket_index(__k, __code); __node_type* __p = __h->_M_find_node(__n, __k, __code); if (!__p) __throw_out_of_range(__N("_Map_base::at")); return __p->_M_v().second; } /** * Primary class template _Insert_base. * * Defines @c insert member functions appropriate to all _Hashtables. */ template struct _Insert_base { protected: using __hashtable = _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; using __hashtable_base = _Hashtable_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, _Hash, _Traits>; using value_type = typename __hashtable_base::value_type; using iterator = typename __hashtable_base::iterator; using const_iterator = typename __hashtable_base::const_iterator; using size_type = typename __hashtable_base::size_type; using __unique_keys = typename __hashtable_base::__unique_keys; using __ireturn_type = typename __hashtable_base::__ireturn_type; using __node_type = _Hash_node<_Value, _Traits::__hash_cached::value>; using __node_alloc_type = __alloc_rebind<_Alloc, __node_type>; using __node_gen_type = _AllocNode<__node_alloc_type>; __hashtable& _M_conjure_hashtable() { return *(static_cast<__hashtable*>(this)); } template void _M_insert_range(_InputIterator __first, _InputIterator __last, const _NodeGetter&, true_type); template void _M_insert_range(_InputIterator __first, _InputIterator __last, const _NodeGetter&, false_type); public: __ireturn_type insert(const value_type& __v) { __hashtable& __h = _M_conjure_hashtable(); __node_gen_type __node_gen(__h); return __h._M_insert(__v, __node_gen, __unique_keys()); } iterator insert(const_iterator __hint, const value_type& __v) { __hashtable& __h = _M_conjure_hashtable(); __node_gen_type __node_gen(__h); return __h._M_insert(__hint, __v, __node_gen, __unique_keys()); } void insert(initializer_list __l) { this->insert(__l.begin(), __l.end()); } template void insert(_InputIterator __first, _InputIterator __last) { __hashtable& __h = _M_conjure_hashtable(); __node_gen_type __node_gen(__h); return _M_insert_range(__first, __last, __node_gen, __unique_keys()); } }; template template void _Insert_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_insert_range(_InputIterator __first, _InputIterator __last, const _NodeGetter& __node_gen, true_type) { size_type __n_elt = __detail::__distance_fw(__first, __last); if (__n_elt == 0) return; __hashtable& __h = _M_conjure_hashtable(); for (; __first != __last; ++__first) { if (__h._M_insert(*__first, __node_gen, __unique_keys(), __n_elt).second) __n_elt = 1; else if (__n_elt != 1) --__n_elt; } } template template void _Insert_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_insert_range(_InputIterator __first, _InputIterator __last, const _NodeGetter& __node_gen, false_type) { using __rehash_type = typename __hashtable::__rehash_type; using __rehash_state = typename __hashtable::__rehash_state; using pair_type = std::pair; size_type __n_elt = __detail::__distance_fw(__first, __last); if (__n_elt == 0) return; __hashtable& __h = _M_conjure_hashtable(); __rehash_type& __rehash = __h._M_rehash_policy; const __rehash_state& __saved_state = __rehash._M_state(); pair_type __do_rehash = __rehash._M_need_rehash(__h._M_bucket_count, __h._M_element_count, __n_elt); if (__do_rehash.first) __h._M_rehash(__do_rehash.second, __saved_state); for (; __first != __last; ++__first) __h._M_insert(*__first, __node_gen, __unique_keys()); } /** * Primary class template _Insert. * * Defines @c insert member functions that depend on _Hashtable policies, * via partial specializations. */ template struct _Insert; /// Specialization. template struct _Insert<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true> : public _Insert_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits> { using __base_type = _Insert_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; using __hashtable_base = _Hashtable_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, _Hash, _Traits>; using value_type = typename __base_type::value_type; using iterator = typename __base_type::iterator; using const_iterator = typename __base_type::const_iterator; using __unique_keys = typename __base_type::__unique_keys; using __ireturn_type = typename __hashtable_base::__ireturn_type; using __hashtable = typename __base_type::__hashtable; using __node_gen_type = typename __base_type::__node_gen_type; using __base_type::insert; __ireturn_type insert(value_type&& __v) { __hashtable& __h = this->_M_conjure_hashtable(); __node_gen_type __node_gen(__h); return __h._M_insert(std::move(__v), __node_gen, __unique_keys()); } iterator insert(const_iterator __hint, value_type&& __v) { __hashtable& __h = this->_M_conjure_hashtable(); __node_gen_type __node_gen(__h); return __h._M_insert(__hint, std::move(__v), __node_gen, __unique_keys()); } }; /// Specialization. template struct _Insert<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, false> : public _Insert_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits> { using __base_type = _Insert_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; using value_type = typename __base_type::value_type; using iterator = typename __base_type::iterator; using const_iterator = typename __base_type::const_iterator; using __unique_keys = typename __base_type::__unique_keys; using __hashtable = typename __base_type::__hashtable; using __ireturn_type = typename __base_type::__ireturn_type; using __base_type::insert; template using __is_cons = std::is_constructible; template using _IFcons = std::enable_if<__is_cons<_Pair>::value>; template using _IFconsp = typename _IFcons<_Pair>::type; template> __ireturn_type insert(_Pair&& __v) { __hashtable& __h = this->_M_conjure_hashtable(); return __h._M_emplace(__unique_keys(), std::forward<_Pair>(__v)); } template> iterator insert(const_iterator __hint, _Pair&& __v) { __hashtable& __h = this->_M_conjure_hashtable(); return __h._M_emplace(__hint, __unique_keys(), std::forward<_Pair>(__v)); } }; template using __has_load_factor = typename _Policy::__has_load_factor; /** * Primary class template _Rehash_base. * * Give hashtable the max_load_factor functions and reserve iff the * rehash policy supports it. */ template> struct _Rehash_base; /// Specialization when rehash policy doesn't provide load factor management. template struct _Rehash_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, std::false_type> { }; /// Specialization when rehash policy provide load factor management. template struct _Rehash_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, std::true_type> { using __hashtable = _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; float max_load_factor() const noexcept { const __hashtable* __this = static_cast(this); return __this->__rehash_policy().max_load_factor(); } void max_load_factor(float __z) { __hashtable* __this = static_cast<__hashtable*>(this); __this->__rehash_policy(_RehashPolicy(__z)); } void reserve(std::size_t __n) { __hashtable* __this = static_cast<__hashtable*>(this); __this->rehash(__builtin_ceil(__n / max_load_factor())); } }; /** * Primary class template _Hashtable_ebo_helper. * * Helper class using EBO when it is not forbidden (the type is not * final) and when it is worth it (the type is empty.) */ template struct _Hashtable_ebo_helper; /// Specialization using EBO. template struct _Hashtable_ebo_helper<_Nm, _Tp, true> : private _Tp { _Hashtable_ebo_helper() = default; template _Hashtable_ebo_helper(_OtherTp&& __tp) : _Tp(std::forward<_OtherTp>(__tp)) { } static const _Tp& _S_cget(const _Hashtable_ebo_helper& __eboh) { return static_cast(__eboh); } static _Tp& _S_get(_Hashtable_ebo_helper& __eboh) { return static_cast<_Tp&>(__eboh); } }; /// Specialization not using EBO. template struct _Hashtable_ebo_helper<_Nm, _Tp, false> { _Hashtable_ebo_helper() = default; template _Hashtable_ebo_helper(_OtherTp&& __tp) : _M_tp(std::forward<_OtherTp>(__tp)) { } static const _Tp& _S_cget(const _Hashtable_ebo_helper& __eboh) { return __eboh._M_tp; } static _Tp& _S_get(_Hashtable_ebo_helper& __eboh) { return __eboh._M_tp; } private: _Tp _M_tp; }; /** * Primary class template _Local_iterator_base. * * Base class for local iterators, used to iterate within a bucket * but not between buckets. */ template struct _Local_iterator_base; /** * Primary class template _Hash_code_base. * * Encapsulates two policy issues that aren't quite orthogonal. * (1) the difference between using a ranged hash function and using * the combination of a hash function and a range-hashing function. * In the former case we don't have such things as hash codes, so * we have a dummy type as placeholder. * (2) Whether or not we cache hash codes. Caching hash codes is * meaningless if we have a ranged hash function. * * We also put the key extraction objects here, for convenience. * Each specialization derives from one or more of the template * parameters to benefit from Ebo. This is important as this type * is inherited in some cases by the _Local_iterator_base type used * to implement local_iterator and const_local_iterator. As with * any iterator type we prefer to make it as small as possible. * * Primary template is unused except as a hook for specializations. */ template struct _Hash_code_base; /// Specialization: ranged hash function, no caching hash codes. H1 /// and H2 are provided but ignored. We define a dummy hash code type. template struct _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, false> : private _Hashtable_ebo_helper<0, _ExtractKey>, private _Hashtable_ebo_helper<1, _Hash> { private: using __ebo_extract_key = _Hashtable_ebo_helper<0, _ExtractKey>; using __ebo_hash = _Hashtable_ebo_helper<1, _Hash>; protected: typedef void* __hash_code; typedef _Hash_node<_Value, false> __node_type; // We need the default constructor for the local iterators and _Hashtable // default constructor. _Hash_code_base() = default; _Hash_code_base(const _ExtractKey& __ex, const _H1&, const _H2&, const _Hash& __h) : __ebo_extract_key(__ex), __ebo_hash(__h) { } __hash_code _M_hash_code(const _Key& __key) const { return 0; } std::size_t _M_bucket_index(const _Key& __k, __hash_code, std::size_t __n) const { return _M_ranged_hash()(__k, __n); } std::size_t _M_bucket_index(const __node_type* __p, std::size_t __n) const noexcept( noexcept(declval()(declval(), (std::size_t)0)) ) { return _M_ranged_hash()(_M_extract()(__p->_M_v()), __n); } void _M_store_code(__node_type*, __hash_code) const { } void _M_copy_code(__node_type*, const __node_type*) const { } void _M_swap(_Hash_code_base& __x) { std::swap(_M_extract(), __x._M_extract()); std::swap(_M_ranged_hash(), __x._M_ranged_hash()); } const _ExtractKey& _M_extract() const { return __ebo_extract_key::_S_cget(*this); } _ExtractKey& _M_extract() { return __ebo_extract_key::_S_get(*this); } const _Hash& _M_ranged_hash() const { return __ebo_hash::_S_cget(*this); } _Hash& _M_ranged_hash() { return __ebo_hash::_S_get(*this); } }; // No specialization for ranged hash function while caching hash codes. // That combination is meaningless, and trying to do it is an error. /// Specialization: ranged hash function, cache hash codes. This /// combination is meaningless, so we provide only a declaration /// and no definition. template struct _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, true>; /// Specialization: hash function and range-hashing function, no /// caching of hash codes. /// Provides typedef and accessor required by C++ 11. template struct _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Default_ranged_hash, false> : private _Hashtable_ebo_helper<0, _ExtractKey>, private _Hashtable_ebo_helper<1, _H1>, private _Hashtable_ebo_helper<2, _H2> { private: using __ebo_extract_key = _Hashtable_ebo_helper<0, _ExtractKey>; using __ebo_h1 = _Hashtable_ebo_helper<1, _H1>; using __ebo_h2 = _Hashtable_ebo_helper<2, _H2>; // Gives the local iterator implementation access to _M_bucket_index(). friend struct _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Default_ranged_hash, false>; public: typedef _H1 hasher; hasher hash_function() const { return _M_h1(); } protected: typedef std::size_t __hash_code; typedef _Hash_node<_Value, false> __node_type; // We need the default constructor for the local iterators and _Hashtable // default constructor. _Hash_code_base() = default; _Hash_code_base(const _ExtractKey& __ex, const _H1& __h1, const _H2& __h2, const _Default_ranged_hash&) : __ebo_extract_key(__ex), __ebo_h1(__h1), __ebo_h2(__h2) { } __hash_code _M_hash_code(const _Key& __k) const { static_assert(__is_invocable{}, "hash function must be invocable with an argument of key type"); return _M_h1()(__k); } std::size_t _M_bucket_index(const _Key&, __hash_code __c, std::size_t __n) const { return _M_h2()(__c, __n); } std::size_t _M_bucket_index(const __node_type* __p, std::size_t __n) const noexcept( noexcept(declval()(declval())) && noexcept(declval()((__hash_code)0, (std::size_t)0)) ) { return _M_h2()(_M_h1()(_M_extract()(__p->_M_v())), __n); } void _M_store_code(__node_type*, __hash_code) const { } void _M_copy_code(__node_type*, const __node_type*) const { } void _M_swap(_Hash_code_base& __x) { std::swap(_M_extract(), __x._M_extract()); std::swap(_M_h1(), __x._M_h1()); std::swap(_M_h2(), __x._M_h2()); } const _ExtractKey& _M_extract() const { return __ebo_extract_key::_S_cget(*this); } _ExtractKey& _M_extract() { return __ebo_extract_key::_S_get(*this); } const _H1& _M_h1() const { return __ebo_h1::_S_cget(*this); } _H1& _M_h1() { return __ebo_h1::_S_get(*this); } const _H2& _M_h2() const { return __ebo_h2::_S_cget(*this); } _H2& _M_h2() { return __ebo_h2::_S_get(*this); } }; /// Specialization: hash function and range-hashing function, /// caching hash codes. H is provided but ignored. Provides /// typedef and accessor required by C++ 11. template struct _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Default_ranged_hash, true> : private _Hashtable_ebo_helper<0, _ExtractKey>, private _Hashtable_ebo_helper<1, _H1>, private _Hashtable_ebo_helper<2, _H2> { private: // Gives the local iterator implementation access to _M_h2(). friend struct _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Default_ranged_hash, true>; using __ebo_extract_key = _Hashtable_ebo_helper<0, _ExtractKey>; using __ebo_h1 = _Hashtable_ebo_helper<1, _H1>; using __ebo_h2 = _Hashtable_ebo_helper<2, _H2>; public: typedef _H1 hasher; hasher hash_function() const { return _M_h1(); } protected: typedef std::size_t __hash_code; typedef _Hash_node<_Value, true> __node_type; // We need the default constructor for _Hashtable default constructor. _Hash_code_base() = default; _Hash_code_base(const _ExtractKey& __ex, const _H1& __h1, const _H2& __h2, const _Default_ranged_hash&) : __ebo_extract_key(__ex), __ebo_h1(__h1), __ebo_h2(__h2) { } __hash_code _M_hash_code(const _Key& __k) const { static_assert(__is_invocable{}, "hash function must be invocable with an argument of key type"); return _M_h1()(__k); } std::size_t _M_bucket_index(const _Key&, __hash_code __c, std::size_t __n) const { return _M_h2()(__c, __n); } std::size_t _M_bucket_index(const __node_type* __p, std::size_t __n) const noexcept( noexcept(declval()((__hash_code)0, (std::size_t)0)) ) { return _M_h2()(__p->_M_hash_code, __n); } void _M_store_code(__node_type* __n, __hash_code __c) const { __n->_M_hash_code = __c; } void _M_copy_code(__node_type* __to, const __node_type* __from) const { __to->_M_hash_code = __from->_M_hash_code; } void _M_swap(_Hash_code_base& __x) { std::swap(_M_extract(), __x._M_extract()); std::swap(_M_h1(), __x._M_h1()); std::swap(_M_h2(), __x._M_h2()); } const _ExtractKey& _M_extract() const { return __ebo_extract_key::_S_cget(*this); } _ExtractKey& _M_extract() { return __ebo_extract_key::_S_get(*this); } const _H1& _M_h1() const { return __ebo_h1::_S_cget(*this); } _H1& _M_h1() { return __ebo_h1::_S_get(*this); } const _H2& _M_h2() const { return __ebo_h2::_S_cget(*this); } _H2& _M_h2() { return __ebo_h2::_S_get(*this); } }; /** * Primary class template _Equal_helper. * */ template struct _Equal_helper; /// Specialization. template struct _Equal_helper<_Key, _Value, _ExtractKey, _Equal, _HashCodeType, true> { static bool _S_equals(const _Equal& __eq, const _ExtractKey& __extract, const _Key& __k, _HashCodeType __c, _Hash_node<_Value, true>* __n) { return __c == __n->_M_hash_code && __eq(__k, __extract(__n->_M_v())); } }; /// Specialization. template struct _Equal_helper<_Key, _Value, _ExtractKey, _Equal, _HashCodeType, false> { static bool _S_equals(const _Equal& __eq, const _ExtractKey& __extract, const _Key& __k, _HashCodeType, _Hash_node<_Value, false>* __n) { return __eq(__k, __extract(__n->_M_v())); } }; /// Partial specialization used when nodes contain a cached hash code. template struct _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, true> : private _Hashtable_ebo_helper<0, _H2> { protected: using __base_type = _Hashtable_ebo_helper<0, _H2>; using __hash_code_base = _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, true>; _Local_iterator_base() = default; _Local_iterator_base(const __hash_code_base& __base, _Hash_node<_Value, true>* __p, std::size_t __bkt, std::size_t __bkt_count) : __base_type(__base._M_h2()), _M_cur(__p), _M_bucket(__bkt), _M_bucket_count(__bkt_count) { } void _M_incr() { _M_cur = _M_cur->_M_next(); if (_M_cur) { std::size_t __bkt = __base_type::_S_get(*this)(_M_cur->_M_hash_code, _M_bucket_count); if (__bkt != _M_bucket) _M_cur = nullptr; } } _Hash_node<_Value, true>* _M_cur; std::size_t _M_bucket; std::size_t _M_bucket_count; public: const void* _M_curr() const { return _M_cur; } // for equality ops std::size_t _M_get_bucket() const { return _M_bucket; } // for debug mode }; // Uninitialized storage for a _Hash_code_base. // This type is DefaultConstructible and Assignable even if the // _Hash_code_base type isn't, so that _Local_iterator_base<..., false> // can be DefaultConstructible and Assignable. template::value> struct _Hash_code_storage { __gnu_cxx::__aligned_buffer<_Tp> _M_storage; _Tp* _M_h() { return _M_storage._M_ptr(); } const _Tp* _M_h() const { return _M_storage._M_ptr(); } }; // Empty partial specialization for empty _Hash_code_base types. template struct _Hash_code_storage<_Tp, true> { static_assert( std::is_empty<_Tp>::value, "Type must be empty" ); // As _Tp is an empty type there will be no bytes written/read through // the cast pointer, so no strict-aliasing violation. _Tp* _M_h() { return reinterpret_cast<_Tp*>(this); } const _Tp* _M_h() const { return reinterpret_cast(this); } }; template using __hash_code_for_local_iter = _Hash_code_storage<_Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, false>>; // Partial specialization used when hash codes are not cached template struct _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, false> : __hash_code_for_local_iter<_Key, _Value, _ExtractKey, _H1, _H2, _Hash> { protected: using __hash_code_base = _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, false>; _Local_iterator_base() : _M_bucket_count(-1) { } _Local_iterator_base(const __hash_code_base& __base, _Hash_node<_Value, false>* __p, std::size_t __bkt, std::size_t __bkt_count) : _M_cur(__p), _M_bucket(__bkt), _M_bucket_count(__bkt_count) { _M_init(__base); } ~_Local_iterator_base() { if (_M_bucket_count != -1) _M_destroy(); } _Local_iterator_base(const _Local_iterator_base& __iter) : _M_cur(__iter._M_cur), _M_bucket(__iter._M_bucket), _M_bucket_count(__iter._M_bucket_count) { if (_M_bucket_count != -1) _M_init(*__iter._M_h()); } _Local_iterator_base& operator=(const _Local_iterator_base& __iter) { if (_M_bucket_count != -1) _M_destroy(); _M_cur = __iter._M_cur; _M_bucket = __iter._M_bucket; _M_bucket_count = __iter._M_bucket_count; if (_M_bucket_count != -1) _M_init(*__iter._M_h()); return *this; } void _M_incr() { _M_cur = _M_cur->_M_next(); if (_M_cur) { std::size_t __bkt = this->_M_h()->_M_bucket_index(_M_cur, _M_bucket_count); if (__bkt != _M_bucket) _M_cur = nullptr; } } _Hash_node<_Value, false>* _M_cur; std::size_t _M_bucket; std::size_t _M_bucket_count; void _M_init(const __hash_code_base& __base) { ::new(this->_M_h()) __hash_code_base(__base); } void _M_destroy() { this->_M_h()->~__hash_code_base(); } public: const void* _M_curr() const { return _M_cur; } // for equality ops and debug mode std::size_t _M_get_bucket() const { return _M_bucket; } // for debug mode }; template inline bool operator==(const _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache>& __x, const _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache>& __y) { return __x._M_curr() == __y._M_curr(); } template inline bool operator!=(const _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache>& __x, const _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache>& __y) { return __x._M_curr() != __y._M_curr(); } /// local iterators template struct _Local_iterator : public _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache> { private: using __base_type = _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache>; using __hash_code_base = typename __base_type::__hash_code_base; public: typedef _Value value_type; typedef typename std::conditional<__constant_iterators, const _Value*, _Value*>::type pointer; typedef typename std::conditional<__constant_iterators, const _Value&, _Value&>::type reference; typedef std::ptrdiff_t difference_type; typedef std::forward_iterator_tag iterator_category; _Local_iterator() = default; _Local_iterator(const __hash_code_base& __base, _Hash_node<_Value, __cache>* __p, std::size_t __bkt, std::size_t __bkt_count) : __base_type(__base, __p, __bkt, __bkt_count) { } reference operator*() const { return this->_M_cur->_M_v(); } pointer operator->() const { return this->_M_cur->_M_valptr(); } _Local_iterator& operator++() { this->_M_incr(); return *this; } _Local_iterator operator++(int) { _Local_iterator __tmp(*this); this->_M_incr(); return __tmp; } }; /// local const_iterators template struct _Local_const_iterator : public _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache> { private: using __base_type = _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache>; using __hash_code_base = typename __base_type::__hash_code_base; public: typedef _Value value_type; typedef const _Value* pointer; typedef const _Value& reference; typedef std::ptrdiff_t difference_type; typedef std::forward_iterator_tag iterator_category; _Local_const_iterator() = default; _Local_const_iterator(const __hash_code_base& __base, _Hash_node<_Value, __cache>* __p, std::size_t __bkt, std::size_t __bkt_count) : __base_type(__base, __p, __bkt, __bkt_count) { } _Local_const_iterator(const _Local_iterator<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __constant_iterators, __cache>& __x) : __base_type(__x) { } reference operator*() const { return this->_M_cur->_M_v(); } pointer operator->() const { return this->_M_cur->_M_valptr(); } _Local_const_iterator& operator++() { this->_M_incr(); return *this; } _Local_const_iterator operator++(int) { _Local_const_iterator __tmp(*this); this->_M_incr(); return __tmp; } }; /** * Primary class template _Hashtable_base. * * Helper class adding management of _Equal functor to * _Hash_code_base type. * * Base class templates are: * - __detail::_Hash_code_base * - __detail::_Hashtable_ebo_helper */ template struct _Hashtable_base : public _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, _Traits::__hash_cached::value>, private _Hashtable_ebo_helper<0, _Equal> { public: typedef _Key key_type; typedef _Value value_type; typedef _Equal key_equal; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; using __traits_type = _Traits; using __hash_cached = typename __traits_type::__hash_cached; using __constant_iterators = typename __traits_type::__constant_iterators; using __unique_keys = typename __traits_type::__unique_keys; using __hash_code_base = _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __hash_cached::value>; using __hash_code = typename __hash_code_base::__hash_code; using __node_type = typename __hash_code_base::__node_type; using iterator = __detail::_Node_iterator; using const_iterator = __detail::_Node_const_iterator; using local_iterator = __detail::_Local_iterator; using const_local_iterator = __detail::_Local_const_iterator; using __ireturn_type = typename std::conditional<__unique_keys::value, std::pair, iterator>::type; private: using _EqualEBO = _Hashtable_ebo_helper<0, _Equal>; using _EqualHelper = _Equal_helper<_Key, _Value, _ExtractKey, _Equal, __hash_code, __hash_cached::value>; protected: _Hashtable_base() = default; _Hashtable_base(const _ExtractKey& __ex, const _H1& __h1, const _H2& __h2, const _Hash& __hash, const _Equal& __eq) : __hash_code_base(__ex, __h1, __h2, __hash), _EqualEBO(__eq) { } bool _M_equals(const _Key& __k, __hash_code __c, __node_type* __n) const { static_assert(__is_invocable{}, "key equality predicate must be invocable with two arguments of " "key type"); return _EqualHelper::_S_equals(_M_eq(), this->_M_extract(), __k, __c, __n); } void _M_swap(_Hashtable_base& __x) { __hash_code_base::_M_swap(__x); std::swap(_M_eq(), __x._M_eq()); } const _Equal& _M_eq() const { return _EqualEBO::_S_cget(*this); } _Equal& _M_eq() { return _EqualEBO::_S_get(*this); } }; /** * struct _Equality_base. * * Common types and functions for class _Equality. */ struct _Equality_base { protected: template static bool _S_is_permutation(_Uiterator, _Uiterator, _Uiterator); }; // See std::is_permutation in N3068. template bool _Equality_base:: _S_is_permutation(_Uiterator __first1, _Uiterator __last1, _Uiterator __first2) { for (; __first1 != __last1; ++__first1, ++__first2) if (!(*__first1 == *__first2)) break; if (__first1 == __last1) return true; _Uiterator __last2 = __first2; std::advance(__last2, std::distance(__first1, __last1)); for (_Uiterator __it1 = __first1; __it1 != __last1; ++__it1) { _Uiterator __tmp = __first1; while (__tmp != __it1 && !bool(*__tmp == *__it1)) ++__tmp; // We've seen this one before. if (__tmp != __it1) continue; std::ptrdiff_t __n2 = 0; for (__tmp = __first2; __tmp != __last2; ++__tmp) if (*__tmp == *__it1) ++__n2; if (!__n2) return false; std::ptrdiff_t __n1 = 0; for (__tmp = __it1; __tmp != __last1; ++__tmp) if (*__tmp == *__it1) ++__n1; if (__n1 != __n2) return false; } return true; } /** * Primary class template _Equality. * * This is for implementing equality comparison for unordered * containers, per N3068, by John Lakos and Pablo Halpern. * Algorithmically, we follow closely the reference implementations * therein. */ template struct _Equality; /// Specialization. template struct _Equality<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true> { using __hashtable = _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; bool _M_equal(const __hashtable&) const; }; template bool _Equality<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true>:: _M_equal(const __hashtable& __other) const { const __hashtable* __this = static_cast(this); if (__this->size() != __other.size()) return false; for (auto __itx = __this->begin(); __itx != __this->end(); ++__itx) { const auto __ity = __other.find(_ExtractKey()(*__itx)); if (__ity == __other.end() || !bool(*__ity == *__itx)) return false; } return true; } /// Specialization. template struct _Equality<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, false> : public _Equality_base { using __hashtable = _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; bool _M_equal(const __hashtable&) const; }; template bool _Equality<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, false>:: _M_equal(const __hashtable& __other) const { const __hashtable* __this = static_cast(this); if (__this->size() != __other.size()) return false; for (auto __itx = __this->begin(); __itx != __this->end();) { const auto __xrange = __this->equal_range(_ExtractKey()(*__itx)); const auto __yrange = __other.equal_range(_ExtractKey()(*__itx)); if (std::distance(__xrange.first, __xrange.second) != std::distance(__yrange.first, __yrange.second)) return false; if (!_S_is_permutation(__xrange.first, __xrange.second, __yrange.first)) return false; __itx = __xrange.second; } return true; } /** * This type deals with all allocation and keeps an allocator instance through * inheritance to benefit from EBO when possible. */ template struct _Hashtable_alloc : private _Hashtable_ebo_helper<0, _NodeAlloc> { private: using __ebo_node_alloc = _Hashtable_ebo_helper<0, _NodeAlloc>; public: using __node_type = typename _NodeAlloc::value_type; using __node_alloc_type = _NodeAlloc; // Use __gnu_cxx to benefit from _S_always_equal and al. using __node_alloc_traits = __gnu_cxx::__alloc_traits<__node_alloc_type>; using __value_alloc_traits = typename __node_alloc_traits::template rebind_traits; using __node_base = __detail::_Hash_node_base; using __bucket_type = __node_base*; using __bucket_alloc_type = __alloc_rebind<__node_alloc_type, __bucket_type>; using __bucket_alloc_traits = std::allocator_traits<__bucket_alloc_type>; _Hashtable_alloc() = default; _Hashtable_alloc(const _Hashtable_alloc&) = default; _Hashtable_alloc(_Hashtable_alloc&&) = default; template _Hashtable_alloc(_Alloc&& __a) : __ebo_node_alloc(std::forward<_Alloc>(__a)) { } __node_alloc_type& _M_node_allocator() { return __ebo_node_alloc::_S_get(*this); } const __node_alloc_type& _M_node_allocator() const { return __ebo_node_alloc::_S_cget(*this); } template __node_type* _M_allocate_node(_Args&&... __args); void _M_deallocate_node(__node_type* __n); // Deallocate the linked list of nodes pointed to by __n void _M_deallocate_nodes(__node_type* __n); __bucket_type* _M_allocate_buckets(std::size_t __n); void _M_deallocate_buckets(__bucket_type*, std::size_t __n); }; // Definitions of class template _Hashtable_alloc's out-of-line member // functions. template template typename _Hashtable_alloc<_NodeAlloc>::__node_type* _Hashtable_alloc<_NodeAlloc>::_M_allocate_node(_Args&&... __args) { auto __nptr = __node_alloc_traits::allocate(_M_node_allocator(), 1); __node_type* __n = std::__to_address(__nptr); __try { ::new ((void*)__n) __node_type; __node_alloc_traits::construct(_M_node_allocator(), __n->_M_valptr(), std::forward<_Args>(__args)...); return __n; } __catch(...) { __node_alloc_traits::deallocate(_M_node_allocator(), __nptr, 1); __throw_exception_again; } } template void _Hashtable_alloc<_NodeAlloc>::_M_deallocate_node(__node_type* __n) { typedef typename __node_alloc_traits::pointer _Ptr; auto __ptr = std::pointer_traits<_Ptr>::pointer_to(*__n); __node_alloc_traits::destroy(_M_node_allocator(), __n->_M_valptr()); __n->~__node_type(); __node_alloc_traits::deallocate(_M_node_allocator(), __ptr, 1); } template void _Hashtable_alloc<_NodeAlloc>::_M_deallocate_nodes(__node_type* __n) { while (__n) { __node_type* __tmp = __n; __n = __n->_M_next(); _M_deallocate_node(__tmp); } } template typename _Hashtable_alloc<_NodeAlloc>::__bucket_type* _Hashtable_alloc<_NodeAlloc>::_M_allocate_buckets(std::size_t __n) { __bucket_alloc_type __alloc(_M_node_allocator()); auto __ptr = __bucket_alloc_traits::allocate(__alloc, __n); __bucket_type* __p = std::__to_address(__ptr); __builtin_memset(__p, 0, __n * sizeof(__bucket_type)); return __p; } template void _Hashtable_alloc<_NodeAlloc>::_M_deallocate_buckets(__bucket_type* __bkts, std::size_t __n) { typedef typename __bucket_alloc_traits::pointer _Ptr; auto __ptr = std::pointer_traits<_Ptr>::pointer_to(*__bkts); __bucket_alloc_type __alloc(_M_node_allocator()); __bucket_alloc_traits::deallocate(__alloc, __ptr, __n); } //@} hashtable-detail } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _HASHTABLE_POLICY_H PK!] 8/bits/indirect_array.hnu[// The template and inlines for the -*- C++ -*- indirect_array class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/indirect_array.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _INDIRECT_ARRAY_H #define _INDIRECT_ARRAY_H 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup numeric_arrays * @{ */ /** * @brief Reference to arbitrary subset of an array. * * An indirect_array is a reference to the actual elements of an array * specified by an ordered array of indices. The way to get an * indirect_array is to call operator[](valarray) on a valarray. * The returned indirect_array then permits carrying operations out on the * referenced subset of elements in the original valarray. * * For example, if an indirect_array is obtained using the array (4,2,0) as * an argument, and then assigned to an array containing (1,2,3), then the * underlying array will have array[0]==3, array[2]==2, and array[4]==1. * * @param Tp Element type. */ template class indirect_array { public: typedef _Tp value_type; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 253. valarray helper functions are almost entirely useless /// Copy constructor. Both slices refer to the same underlying array. indirect_array(const indirect_array&); /// Assignment operator. Assigns elements to corresponding elements /// of @a a. indirect_array& operator=(const indirect_array&); /// Assign slice elements to corresponding elements of @a v. void operator=(const valarray<_Tp>&) const; /// Multiply slice elements by corresponding elements of @a v. void operator*=(const valarray<_Tp>&) const; /// Divide slice elements by corresponding elements of @a v. void operator/=(const valarray<_Tp>&) const; /// Modulo slice elements by corresponding elements of @a v. void operator%=(const valarray<_Tp>&) const; /// Add corresponding elements of @a v to slice elements. void operator+=(const valarray<_Tp>&) const; /// Subtract corresponding elements of @a v from slice elements. void operator-=(const valarray<_Tp>&) const; /// Logical xor slice elements with corresponding elements of @a v. void operator^=(const valarray<_Tp>&) const; /// Logical and slice elements with corresponding elements of @a v. void operator&=(const valarray<_Tp>&) const; /// Logical or slice elements with corresponding elements of @a v. void operator|=(const valarray<_Tp>&) const; /// Left shift slice elements by corresponding elements of @a v. void operator<<=(const valarray<_Tp>&) const; /// Right shift slice elements by corresponding elements of @a v. void operator>>=(const valarray<_Tp>&) const; /// Assign all slice elements to @a t. void operator= (const _Tp&) const; // ~indirect_array(); template void operator=(const _Expr<_Dom, _Tp>&) const; template void operator*=(const _Expr<_Dom, _Tp>&) const; template void operator/=(const _Expr<_Dom, _Tp>&) const; template void operator%=(const _Expr<_Dom, _Tp>&) const; template void operator+=(const _Expr<_Dom, _Tp>&) const; template void operator-=(const _Expr<_Dom, _Tp>&) const; template void operator^=(const _Expr<_Dom, _Tp>&) const; template void operator&=(const _Expr<_Dom, _Tp>&) const; template void operator|=(const _Expr<_Dom, _Tp>&) const; template void operator<<=(const _Expr<_Dom, _Tp>&) const; template void operator>>=(const _Expr<_Dom, _Tp>&) const; private: /// Copy constructor. Both slices refer to the same underlying array. indirect_array(_Array<_Tp>, size_t, _Array); friend class valarray<_Tp>; friend class gslice_array<_Tp>; const size_t _M_sz; const _Array _M_index; const _Array<_Tp> _M_array; // not implemented indirect_array(); }; template inline indirect_array<_Tp>::indirect_array(const indirect_array<_Tp>& __a) : _M_sz(__a._M_sz), _M_index(__a._M_index), _M_array(__a._M_array) {} template inline indirect_array<_Tp>::indirect_array(_Array<_Tp> __a, size_t __s, _Array __i) : _M_sz(__s), _M_index(__i), _M_array(__a) {} template inline indirect_array<_Tp>& indirect_array<_Tp>::operator=(const indirect_array<_Tp>& __a) { std::__valarray_copy(__a._M_array, _M_sz, __a._M_index, _M_array, _M_index); return *this; } template inline void indirect_array<_Tp>::operator=(const _Tp& __t) const { std::__valarray_fill(_M_array, _M_index, _M_sz, __t); } template inline void indirect_array<_Tp>::operator=(const valarray<_Tp>& __v) const { std::__valarray_copy(_Array<_Tp>(__v), _M_sz, _M_array, _M_index); } template template inline void indirect_array<_Tp>::operator=(const _Expr<_Dom, _Tp>& __e) const { std::__valarray_copy(__e, _M_sz, _M_array, _M_index); } #undef _DEFINE_VALARRAY_OPERATOR #define _DEFINE_VALARRAY_OPERATOR(_Op, _Name) \ template \ inline void \ indirect_array<_Tp>::operator _Op##=(const valarray<_Tp>& __v) const\ { \ _Array_augmented_##_Name(_M_array, _M_index, _Array<_Tp>(__v), _M_sz); \ } \ \ template \ template \ inline void \ indirect_array<_Tp>::operator _Op##=(const _Expr<_Dom,_Tp>& __e) const\ { \ _Array_augmented_##_Name(_M_array, _M_index, __e, _M_sz); \ } _DEFINE_VALARRAY_OPERATOR(*, __multiplies) _DEFINE_VALARRAY_OPERATOR(/, __divides) _DEFINE_VALARRAY_OPERATOR(%, __modulus) _DEFINE_VALARRAY_OPERATOR(+, __plus) _DEFINE_VALARRAY_OPERATOR(-, __minus) _DEFINE_VALARRAY_OPERATOR(^, __bitwise_xor) _DEFINE_VALARRAY_OPERATOR(&, __bitwise_and) _DEFINE_VALARRAY_OPERATOR(|, __bitwise_or) _DEFINE_VALARRAY_OPERATOR(<<, __shift_left) _DEFINE_VALARRAY_OPERATOR(>>, __shift_right) #undef _DEFINE_VALARRAY_OPERATOR // @} group numeric_arrays _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _INDIRECT_ARRAY_H */ PK!|޸II8/bits/invoke.hnu[// Implementation of INVOKE -*- C++ -*- // Copyright (C) 2016-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/invoke.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{functional} */ #ifndef _GLIBCXX_INVOKE_H #define _GLIBCXX_INVOKE_H 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup utilities * @{ */ // Used by __invoke_impl instead of std::forward<_Tp> so that a // reference_wrapper is converted to an lvalue-reference. template::type> constexpr _Up&& __invfwd(typename remove_reference<_Tp>::type& __t) noexcept { return static_cast<_Up&&>(__t); } template constexpr _Res __invoke_impl(__invoke_other, _Fn&& __f, _Args&&... __args) { return std::forward<_Fn>(__f)(std::forward<_Args>(__args)...); } template constexpr _Res __invoke_impl(__invoke_memfun_ref, _MemFun&& __f, _Tp&& __t, _Args&&... __args) { return (__invfwd<_Tp>(__t).*__f)(std::forward<_Args>(__args)...); } template constexpr _Res __invoke_impl(__invoke_memfun_deref, _MemFun&& __f, _Tp&& __t, _Args&&... __args) { return ((*std::forward<_Tp>(__t)).*__f)(std::forward<_Args>(__args)...); } template constexpr _Res __invoke_impl(__invoke_memobj_ref, _MemPtr&& __f, _Tp&& __t) { return __invfwd<_Tp>(__t).*__f; } template constexpr _Res __invoke_impl(__invoke_memobj_deref, _MemPtr&& __f, _Tp&& __t) { return (*std::forward<_Tp>(__t)).*__f; } /// Invoke a callable object. template constexpr typename __invoke_result<_Callable, _Args...>::type __invoke(_Callable&& __fn, _Args&&... __args) noexcept(__is_nothrow_invocable<_Callable, _Args...>::value) { using __result = __invoke_result<_Callable, _Args...>; using __type = typename __result::type; using __tag = typename __result::__invoke_type; return std::__invoke_impl<__type>(__tag{}, std::forward<_Callable>(__fn), std::forward<_Args>(__args)...); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif // _GLIBCXX_INVOKE_H PK!` ̐/y/y8/bits/ios_base.hnu[// Iostreams base classes -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/ios_base.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ios} */ // // ISO C++ 14882: 27.4 Iostreams base classes // #ifndef _IOS_BASE_H #define _IOS_BASE_H 1 #pragma GCC system_header #include #include #include #if __cplusplus < 201103L # include #else # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // The following definitions of bitmask types are enums, not ints, // as permitted (but not required) in the standard, in order to provide // better type safety in iostream calls. A side effect is that in C++98 // expressions involving them are not compile-time constants. enum _Ios_Fmtflags { _S_boolalpha = 1L << 0, _S_dec = 1L << 1, _S_fixed = 1L << 2, _S_hex = 1L << 3, _S_internal = 1L << 4, _S_left = 1L << 5, _S_oct = 1L << 6, _S_right = 1L << 7, _S_scientific = 1L << 8, _S_showbase = 1L << 9, _S_showpoint = 1L << 10, _S_showpos = 1L << 11, _S_skipws = 1L << 12, _S_unitbuf = 1L << 13, _S_uppercase = 1L << 14, _S_adjustfield = _S_left | _S_right | _S_internal, _S_basefield = _S_dec | _S_oct | _S_hex, _S_floatfield = _S_scientific | _S_fixed, _S_ios_fmtflags_end = 1L << 16, _S_ios_fmtflags_max = __INT_MAX__, _S_ios_fmtflags_min = ~__INT_MAX__ }; inline _GLIBCXX_CONSTEXPR _Ios_Fmtflags operator&(_Ios_Fmtflags __a, _Ios_Fmtflags __b) { return _Ios_Fmtflags(static_cast(__a) & static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Fmtflags operator|(_Ios_Fmtflags __a, _Ios_Fmtflags __b) { return _Ios_Fmtflags(static_cast(__a) | static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Fmtflags operator^(_Ios_Fmtflags __a, _Ios_Fmtflags __b) { return _Ios_Fmtflags(static_cast(__a) ^ static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Fmtflags operator~(_Ios_Fmtflags __a) { return _Ios_Fmtflags(~static_cast(__a)); } inline const _Ios_Fmtflags& operator|=(_Ios_Fmtflags& __a, _Ios_Fmtflags __b) { return __a = __a | __b; } inline const _Ios_Fmtflags& operator&=(_Ios_Fmtflags& __a, _Ios_Fmtflags __b) { return __a = __a & __b; } inline const _Ios_Fmtflags& operator^=(_Ios_Fmtflags& __a, _Ios_Fmtflags __b) { return __a = __a ^ __b; } enum _Ios_Openmode { _S_app = 1L << 0, _S_ate = 1L << 1, _S_bin = 1L << 2, _S_in = 1L << 3, _S_out = 1L << 4, _S_trunc = 1L << 5, _S_ios_openmode_end = 1L << 16, _S_ios_openmode_max = __INT_MAX__, _S_ios_openmode_min = ~__INT_MAX__ }; inline _GLIBCXX_CONSTEXPR _Ios_Openmode operator&(_Ios_Openmode __a, _Ios_Openmode __b) { return _Ios_Openmode(static_cast(__a) & static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Openmode operator|(_Ios_Openmode __a, _Ios_Openmode __b) { return _Ios_Openmode(static_cast(__a) | static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Openmode operator^(_Ios_Openmode __a, _Ios_Openmode __b) { return _Ios_Openmode(static_cast(__a) ^ static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Openmode operator~(_Ios_Openmode __a) { return _Ios_Openmode(~static_cast(__a)); } inline const _Ios_Openmode& operator|=(_Ios_Openmode& __a, _Ios_Openmode __b) { return __a = __a | __b; } inline const _Ios_Openmode& operator&=(_Ios_Openmode& __a, _Ios_Openmode __b) { return __a = __a & __b; } inline const _Ios_Openmode& operator^=(_Ios_Openmode& __a, _Ios_Openmode __b) { return __a = __a ^ __b; } enum _Ios_Iostate { _S_goodbit = 0, _S_badbit = 1L << 0, _S_eofbit = 1L << 1, _S_failbit = 1L << 2, _S_ios_iostate_end = 1L << 16, _S_ios_iostate_max = __INT_MAX__, _S_ios_iostate_min = ~__INT_MAX__ }; inline _GLIBCXX_CONSTEXPR _Ios_Iostate operator&(_Ios_Iostate __a, _Ios_Iostate __b) { return _Ios_Iostate(static_cast(__a) & static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Iostate operator|(_Ios_Iostate __a, _Ios_Iostate __b) { return _Ios_Iostate(static_cast(__a) | static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Iostate operator^(_Ios_Iostate __a, _Ios_Iostate __b) { return _Ios_Iostate(static_cast(__a) ^ static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Iostate operator~(_Ios_Iostate __a) { return _Ios_Iostate(~static_cast(__a)); } inline const _Ios_Iostate& operator|=(_Ios_Iostate& __a, _Ios_Iostate __b) { return __a = __a | __b; } inline const _Ios_Iostate& operator&=(_Ios_Iostate& __a, _Ios_Iostate __b) { return __a = __a & __b; } inline const _Ios_Iostate& operator^=(_Ios_Iostate& __a, _Ios_Iostate __b) { return __a = __a ^ __b; } enum _Ios_Seekdir { _S_beg = 0, _S_cur = _GLIBCXX_STDIO_SEEK_CUR, _S_end = _GLIBCXX_STDIO_SEEK_END, _S_ios_seekdir_end = 1L << 16 }; #if __cplusplus >= 201103L /// I/O error code enum class io_errc { stream = 1 }; template <> struct is_error_code_enum : public true_type { }; const error_category& iostream_category() noexcept; inline error_code make_error_code(io_errc __e) noexcept { return error_code(static_cast(__e), iostream_category()); } inline error_condition make_error_condition(io_errc __e) noexcept { return error_condition(static_cast(__e), iostream_category()); } #endif // 27.4.2 Class ios_base /** * @brief The base of the I/O class hierarchy. * @ingroup io * * This class defines everything that can be defined about I/O that does * not depend on the type of characters being input or output. Most * people will only see @c ios_base when they need to specify the full * name of the various I/O flags (e.g., the openmodes). */ class ios_base { #if _GLIBCXX_USE_CXX11_ABI #if __cplusplus < 201103L // Type that is layout-compatible with std::system_error struct system_error : std::runtime_error { // Type that is layout-compatible with std::error_code struct error_code { error_code() { } private: int _M_value; const void* _M_cat; } _M_code; }; #endif #endif public: /** * @brief These are thrown to indicate problems with io. * @ingroup exceptions * * 27.4.2.1.1 Class ios_base::failure */ #if _GLIBCXX_USE_CXX11_ABI class _GLIBCXX_ABI_TAG_CXX11 failure : public system_error { public: explicit failure(const string& __str); #if __cplusplus >= 201103L explicit failure(const string&, const error_code&); explicit failure(const char*, const error_code& = io_errc::stream); #endif virtual ~failure() throw(); virtual const char* what() const throw(); }; #else class failure : public exception { public: // _GLIBCXX_RESOLVE_LIB_DEFECTS // 48. Use of non-existent exception constructor explicit failure(const string& __str) throw(); // This declaration is not useless: // http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Vague-Linkage.html virtual ~failure() throw(); virtual const char* what() const throw(); private: string _M_msg; }; #endif // 27.4.2.1.2 Type ios_base::fmtflags /** * @brief This is a bitmask type. * * @c @a _Ios_Fmtflags is implementation-defined, but it is valid to * perform bitwise operations on these values and expect the Right * Thing to happen. Defined objects of type fmtflags are: * - boolalpha * - dec * - fixed * - hex * - internal * - left * - oct * - right * - scientific * - showbase * - showpoint * - showpos * - skipws * - unitbuf * - uppercase * - adjustfield * - basefield * - floatfield */ typedef _Ios_Fmtflags fmtflags; /// Insert/extract @c bool in alphabetic rather than numeric format. static const fmtflags boolalpha = _S_boolalpha; /// Converts integer input or generates integer output in decimal base. static const fmtflags dec = _S_dec; /// Generate floating-point output in fixed-point notation. static const fmtflags fixed = _S_fixed; /// Converts integer input or generates integer output in hexadecimal base. static const fmtflags hex = _S_hex; /// Adds fill characters at a designated internal point in certain /// generated output, or identical to @c right if no such point is /// designated. static const fmtflags internal = _S_internal; /// Adds fill characters on the right (final positions) of certain /// generated output. (I.e., the thing you print is flush left.) static const fmtflags left = _S_left; /// Converts integer input or generates integer output in octal base. static const fmtflags oct = _S_oct; /// Adds fill characters on the left (initial positions) of certain /// generated output. (I.e., the thing you print is flush right.) static const fmtflags right = _S_right; /// Generates floating-point output in scientific notation. static const fmtflags scientific = _S_scientific; /// Generates a prefix indicating the numeric base of generated integer /// output. static const fmtflags showbase = _S_showbase; /// Generates a decimal-point character unconditionally in generated /// floating-point output. static const fmtflags showpoint = _S_showpoint; /// Generates a + sign in non-negative generated numeric output. static const fmtflags showpos = _S_showpos; /// Skips leading white space before certain input operations. static const fmtflags skipws = _S_skipws; /// Flushes output after each output operation. static const fmtflags unitbuf = _S_unitbuf; /// Replaces certain lowercase letters with their uppercase equivalents /// in generated output. static const fmtflags uppercase = _S_uppercase; /// A mask of left|right|internal. Useful for the 2-arg form of @c setf. static const fmtflags adjustfield = _S_adjustfield; /// A mask of dec|oct|hex. Useful for the 2-arg form of @c setf. static const fmtflags basefield = _S_basefield; /// A mask of scientific|fixed. Useful for the 2-arg form of @c setf. static const fmtflags floatfield = _S_floatfield; // 27.4.2.1.3 Type ios_base::iostate /** * @brief This is a bitmask type. * * @c @a _Ios_Iostate is implementation-defined, but it is valid to * perform bitwise operations on these values and expect the Right * Thing to happen. Defined objects of type iostate are: * - badbit * - eofbit * - failbit * - goodbit */ typedef _Ios_Iostate iostate; /// Indicates a loss of integrity in an input or output sequence (such /// as an irrecoverable read error from a file). static const iostate badbit = _S_badbit; /// Indicates that an input operation reached the end of an input sequence. static const iostate eofbit = _S_eofbit; /// Indicates that an input operation failed to read the expected /// characters, or that an output operation failed to generate the /// desired characters. static const iostate failbit = _S_failbit; /// Indicates all is well. static const iostate goodbit = _S_goodbit; // 27.4.2.1.4 Type ios_base::openmode /** * @brief This is a bitmask type. * * @c @a _Ios_Openmode is implementation-defined, but it is valid to * perform bitwise operations on these values and expect the Right * Thing to happen. Defined objects of type openmode are: * - app * - ate * - binary * - in * - out * - trunc */ typedef _Ios_Openmode openmode; /// Seek to end before each write. static const openmode app = _S_app; /// Open and seek to end immediately after opening. static const openmode ate = _S_ate; /// Perform input and output in binary mode (as opposed to text mode). /// This is probably not what you think it is; see /// https://gcc.gnu.org/onlinedocs/libstdc++/manual/fstreams.html#std.io.filestreams.binary static const openmode binary = _S_bin; /// Open for input. Default for @c ifstream and fstream. static const openmode in = _S_in; /// Open for output. Default for @c ofstream and fstream. static const openmode out = _S_out; /// Truncate an existing stream when opening. Default for @c ofstream. static const openmode trunc = _S_trunc; // 27.4.2.1.5 Type ios_base::seekdir /** * @brief This is an enumerated type. * * @c @a _Ios_Seekdir is implementation-defined. Defined values * of type seekdir are: * - beg * - cur, equivalent to @c SEEK_CUR in the C standard library. * - end, equivalent to @c SEEK_END in the C standard library. */ typedef _Ios_Seekdir seekdir; /// Request a seek relative to the beginning of the stream. static const seekdir beg = _S_beg; /// Request a seek relative to the current position within the sequence. static const seekdir cur = _S_cur; /// Request a seek relative to the current end of the sequence. static const seekdir end = _S_end; #if __cplusplus <= 201402L // Annex D.6 (removed in C++17) typedef int io_state; typedef int open_mode; typedef int seek_dir; typedef std::streampos streampos; typedef std::streamoff streamoff; #endif // Callbacks; /** * @brief The set of events that may be passed to an event callback. * * erase_event is used during ~ios() and copyfmt(). imbue_event is used * during imbue(). copyfmt_event is used during copyfmt(). */ enum event { erase_event, imbue_event, copyfmt_event }; /** * @brief The type of an event callback function. * @param __e One of the members of the event enum. * @param __b Reference to the ios_base object. * @param __i The integer provided when the callback was registered. * * Event callbacks are user defined functions that get called during * several ios_base and basic_ios functions, specifically imbue(), * copyfmt(), and ~ios(). */ typedef void (*event_callback) (event __e, ios_base& __b, int __i); /** * @brief Add the callback __fn with parameter __index. * @param __fn The function to add. * @param __index The integer to pass to the function when invoked. * * Registers a function as an event callback with an integer parameter to * be passed to the function when invoked. Multiple copies of the * function are allowed. If there are multiple callbacks, they are * invoked in the order they were registered. */ void register_callback(event_callback __fn, int __index); protected: streamsize _M_precision; streamsize _M_width; fmtflags _M_flags; iostate _M_exception; iostate _M_streambuf_state; // 27.4.2.6 Members for callbacks // 27.4.2.6 ios_base callbacks struct _Callback_list { // Data Members _Callback_list* _M_next; ios_base::event_callback _M_fn; int _M_index; _Atomic_word _M_refcount; // 0 means one reference. _Callback_list(ios_base::event_callback __fn, int __index, _Callback_list* __cb) : _M_next(__cb), _M_fn(__fn), _M_index(__index), _M_refcount(0) { } void _M_add_reference() { __gnu_cxx::__atomic_add_dispatch(&_M_refcount, 1); } // 0 => OK to delete. int _M_remove_reference() { // Be race-detector-friendly. For more info see bits/c++config. _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_refcount); int __res = __gnu_cxx::__exchange_and_add_dispatch(&_M_refcount, -1); if (__res == 0) { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_refcount); } return __res; } }; _Callback_list* _M_callbacks; void _M_call_callbacks(event __ev) throw(); void _M_dispose_callbacks(void) throw(); // 27.4.2.5 Members for iword/pword storage struct _Words { void* _M_pword; long _M_iword; _Words() : _M_pword(0), _M_iword(0) { } }; // Only for failed iword/pword calls. _Words _M_word_zero; // Guaranteed storage. // The first 5 iword and pword slots are reserved for internal use. enum { _S_local_word_size = 8 }; _Words _M_local_word[_S_local_word_size]; // Allocated storage. int _M_word_size; _Words* _M_word; _Words& _M_grow_words(int __index, bool __iword); // Members for locale and locale caching. locale _M_ios_locale; void _M_init() throw(); public: // 27.4.2.1.6 Class ios_base::Init // Used to initialize standard streams. In theory, g++ could use // -finit-priority to order this stuff correctly without going // through these machinations. class Init { friend class ios_base; public: Init(); ~Init(); private: static _Atomic_word _S_refcount; static bool _S_synced_with_stdio; }; // [27.4.2.2] fmtflags state functions /** * @brief Access to format flags. * @return The format control flags for both input and output. */ fmtflags flags() const { return _M_flags; } /** * @brief Setting new format flags all at once. * @param __fmtfl The new flags to set. * @return The previous format control flags. * * This function overwrites all the format flags with @a __fmtfl. */ fmtflags flags(fmtflags __fmtfl) { fmtflags __old = _M_flags; _M_flags = __fmtfl; return __old; } /** * @brief Setting new format flags. * @param __fmtfl Additional flags to set. * @return The previous format control flags. * * This function sets additional flags in format control. Flags that * were previously set remain set. */ fmtflags setf(fmtflags __fmtfl) { fmtflags __old = _M_flags; _M_flags |= __fmtfl; return __old; } /** * @brief Setting new format flags. * @param __fmtfl Additional flags to set. * @param __mask The flags mask for @a fmtfl. * @return The previous format control flags. * * This function clears @a mask in the format flags, then sets * @a fmtfl @c & @a mask. An example mask is @c ios_base::adjustfield. */ fmtflags setf(fmtflags __fmtfl, fmtflags __mask) { fmtflags __old = _M_flags; _M_flags &= ~__mask; _M_flags |= (__fmtfl & __mask); return __old; } /** * @brief Clearing format flags. * @param __mask The flags to unset. * * This function clears @a __mask in the format flags. */ void unsetf(fmtflags __mask) { _M_flags &= ~__mask; } /** * @brief Flags access. * @return The precision to generate on certain output operations. * * Be careful if you try to give a definition of @a precision here; see * DR 189. */ streamsize precision() const { return _M_precision; } /** * @brief Changing flags. * @param __prec The new precision value. * @return The previous value of precision(). */ streamsize precision(streamsize __prec) { streamsize __old = _M_precision; _M_precision = __prec; return __old; } /** * @brief Flags access. * @return The minimum field width to generate on output operations. * * Minimum field width refers to the number of characters. */ streamsize width() const { return _M_width; } /** * @brief Changing flags. * @param __wide The new width value. * @return The previous value of width(). */ streamsize width(streamsize __wide) { streamsize __old = _M_width; _M_width = __wide; return __old; } // [27.4.2.4] ios_base static members /** * @brief Interaction with the standard C I/O objects. * @param __sync Whether to synchronize or not. * @return True if the standard streams were previously synchronized. * * The synchronization referred to is @e only that between the standard * C facilities (e.g., stdout) and the standard C++ objects (e.g., * cout). User-declared streams are unaffected. See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/fstreams.html#std.io.filestreams.binary */ static bool sync_with_stdio(bool __sync = true); // [27.4.2.3] ios_base locale functions /** * @brief Setting a new locale. * @param __loc The new locale. * @return The previous locale. * * Sets the new locale for this stream, and then invokes each callback * with imbue_event. */ locale imbue(const locale& __loc) throw(); /** * @brief Locale access * @return A copy of the current locale. * * If @c imbue(loc) has previously been called, then this function * returns @c loc. Otherwise, it returns a copy of @c std::locale(), * the global C++ locale. */ locale getloc() const { return _M_ios_locale; } /** * @brief Locale access * @return A reference to the current locale. * * Like getloc above, but returns a reference instead of * generating a copy. */ const locale& _M_getloc() const { return _M_ios_locale; } // [27.4.2.5] ios_base storage functions /** * @brief Access to unique indices. * @return An integer different from all previous calls. * * This function returns a unique integer every time it is called. It * can be used for any purpose, but is primarily intended to be a unique * index for the iword and pword functions. The expectation is that an * application calls xalloc in order to obtain an index in the iword and * pword arrays that can be used without fear of conflict. * * The implementation maintains a static variable that is incremented and * returned on each invocation. xalloc is guaranteed to return an index * that is safe to use in the iword and pword arrays. */ static int xalloc() throw(); /** * @brief Access to integer array. * @param __ix Index into the array. * @return A reference to an integer associated with the index. * * The iword function provides access to an array of integers that can be * used for any purpose. The array grows as required to hold the * supplied index. All integers in the array are initialized to 0. * * The implementation reserves several indices. You should use xalloc to * obtain an index that is safe to use. Also note that since the array * can grow dynamically, it is not safe to hold onto the reference. */ long& iword(int __ix) { _Words& __word = (__ix < _M_word_size) ? _M_word[__ix] : _M_grow_words(__ix, true); return __word._M_iword; } /** * @brief Access to void pointer array. * @param __ix Index into the array. * @return A reference to a void* associated with the index. * * The pword function provides access to an array of pointers that can be * used for any purpose. The array grows as required to hold the * supplied index. All pointers in the array are initialized to 0. * * The implementation reserves several indices. You should use xalloc to * obtain an index that is safe to use. Also note that since the array * can grow dynamically, it is not safe to hold onto the reference. */ void*& pword(int __ix) { _Words& __word = (__ix < _M_word_size) ? _M_word[__ix] : _M_grow_words(__ix, false); return __word._M_pword; } // Destructor /** * Invokes each callback with erase_event. Destroys local storage. * * Note that the ios_base object for the standard streams never gets * destroyed. As a result, any callbacks registered with the standard * streams will not get invoked with erase_event (unless copyfmt is * used). */ virtual ~ios_base(); protected: ios_base() throw (); #if __cplusplus < 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 50. Copy constructor and assignment operator of ios_base private: ios_base(const ios_base&); ios_base& operator=(const ios_base&); #else public: ios_base(const ios_base&) = delete; ios_base& operator=(const ios_base&) = delete; protected: void _M_move(ios_base&) noexcept; void _M_swap(ios_base& __rhs) noexcept; #endif }; // [27.4.5.1] fmtflags manipulators /// Calls base.setf(ios_base::boolalpha). inline ios_base& boolalpha(ios_base& __base) { __base.setf(ios_base::boolalpha); return __base; } /// Calls base.unsetf(ios_base::boolalpha). inline ios_base& noboolalpha(ios_base& __base) { __base.unsetf(ios_base::boolalpha); return __base; } /// Calls base.setf(ios_base::showbase). inline ios_base& showbase(ios_base& __base) { __base.setf(ios_base::showbase); return __base; } /// Calls base.unsetf(ios_base::showbase). inline ios_base& noshowbase(ios_base& __base) { __base.unsetf(ios_base::showbase); return __base; } /// Calls base.setf(ios_base::showpoint). inline ios_base& showpoint(ios_base& __base) { __base.setf(ios_base::showpoint); return __base; } /// Calls base.unsetf(ios_base::showpoint). inline ios_base& noshowpoint(ios_base& __base) { __base.unsetf(ios_base::showpoint); return __base; } /// Calls base.setf(ios_base::showpos). inline ios_base& showpos(ios_base& __base) { __base.setf(ios_base::showpos); return __base; } /// Calls base.unsetf(ios_base::showpos). inline ios_base& noshowpos(ios_base& __base) { __base.unsetf(ios_base::showpos); return __base; } /// Calls base.setf(ios_base::skipws). inline ios_base& skipws(ios_base& __base) { __base.setf(ios_base::skipws); return __base; } /// Calls base.unsetf(ios_base::skipws). inline ios_base& noskipws(ios_base& __base) { __base.unsetf(ios_base::skipws); return __base; } /// Calls base.setf(ios_base::uppercase). inline ios_base& uppercase(ios_base& __base) { __base.setf(ios_base::uppercase); return __base; } /// Calls base.unsetf(ios_base::uppercase). inline ios_base& nouppercase(ios_base& __base) { __base.unsetf(ios_base::uppercase); return __base; } /// Calls base.setf(ios_base::unitbuf). inline ios_base& unitbuf(ios_base& __base) { __base.setf(ios_base::unitbuf); return __base; } /// Calls base.unsetf(ios_base::unitbuf). inline ios_base& nounitbuf(ios_base& __base) { __base.unsetf(ios_base::unitbuf); return __base; } // [27.4.5.2] adjustfield manipulators /// Calls base.setf(ios_base::internal, ios_base::adjustfield). inline ios_base& internal(ios_base& __base) { __base.setf(ios_base::internal, ios_base::adjustfield); return __base; } /// Calls base.setf(ios_base::left, ios_base::adjustfield). inline ios_base& left(ios_base& __base) { __base.setf(ios_base::left, ios_base::adjustfield); return __base; } /// Calls base.setf(ios_base::right, ios_base::adjustfield). inline ios_base& right(ios_base& __base) { __base.setf(ios_base::right, ios_base::adjustfield); return __base; } // [27.4.5.3] basefield manipulators /// Calls base.setf(ios_base::dec, ios_base::basefield). inline ios_base& dec(ios_base& __base) { __base.setf(ios_base::dec, ios_base::basefield); return __base; } /// Calls base.setf(ios_base::hex, ios_base::basefield). inline ios_base& hex(ios_base& __base) { __base.setf(ios_base::hex, ios_base::basefield); return __base; } /// Calls base.setf(ios_base::oct, ios_base::basefield). inline ios_base& oct(ios_base& __base) { __base.setf(ios_base::oct, ios_base::basefield); return __base; } // [27.4.5.4] floatfield manipulators /// Calls base.setf(ios_base::fixed, ios_base::floatfield). inline ios_base& fixed(ios_base& __base) { __base.setf(ios_base::fixed, ios_base::floatfield); return __base; } /// Calls base.setf(ios_base::scientific, ios_base::floatfield). inline ios_base& scientific(ios_base& __base) { __base.setf(ios_base::scientific, ios_base::floatfield); return __base; } #if __cplusplus >= 201103L // New C++11 floatfield manipulators /// Calls /// base.setf(ios_base::fixed|ios_base::scientific, ios_base::floatfield) inline ios_base& hexfloat(ios_base& __base) { __base.setf(ios_base::fixed | ios_base::scientific, ios_base::floatfield); return __base; } /// Calls @c base.unsetf(ios_base::floatfield) inline ios_base& defaultfloat(ios_base& __base) { __base.unsetf(ios_base::floatfield); return __base; } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _IOS_BASE_H */ PK! Spuyuy8/bits/istream.tccnu[// istream classes -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/istream.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{istream} */ // // ISO C++ 14882: 27.6.1 Input streams // #ifndef _ISTREAM_TCC #define _ISTREAM_TCC 1 #pragma GCC system_header #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template basic_istream<_CharT, _Traits>::sentry:: sentry(basic_istream<_CharT, _Traits>& __in, bool __noskip) : _M_ok(false) { ios_base::iostate __err = ios_base::goodbit; if (__in.good()) __try { if (__in.tie()) __in.tie()->flush(); if (!__noskip && bool(__in.flags() & ios_base::skipws)) { const __int_type __eof = traits_type::eof(); __streambuf_type* __sb = __in.rdbuf(); __int_type __c = __sb->sgetc(); const __ctype_type& __ct = __check_facet(__in._M_ctype); while (!traits_type::eq_int_type(__c, __eof) && __ct.is(ctype_base::space, traits_type::to_char_type(__c))) __c = __sb->snextc(); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 195. Should basic_istream::sentry's constructor ever // set eofbit? if (traits_type::eq_int_type(__c, __eof)) __err |= ios_base::eofbit; } } __catch(__cxxabiv1::__forced_unwind&) { __in._M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { __in._M_setstate(ios_base::badbit); } if (__in.good() && __err == ios_base::goodbit) _M_ok = true; else { __err |= ios_base::failbit; __in.setstate(__err); } } template template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: _M_extract(_ValueT& __v) { sentry __cerb(*this, false); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { const __num_get_type& __ng = __check_facet(this->_M_num_get); __ng.get(*this, 0, *this, __err, __v); } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: operator>>(short& __n) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 118. basic_istream uses nonexistent num_get member functions. sentry __cerb(*this, false); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { long __l; const __num_get_type& __ng = __check_facet(this->_M_num_get); __ng.get(*this, 0, *this, __err, __l); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 696. istream::operator>>(int&) broken. if (__l < __gnu_cxx::__numeric_traits::__min) { __err |= ios_base::failbit; __n = __gnu_cxx::__numeric_traits::__min; } else if (__l > __gnu_cxx::__numeric_traits::__max) { __err |= ios_base::failbit; __n = __gnu_cxx::__numeric_traits::__max; } else __n = short(__l); } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: operator>>(int& __n) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 118. basic_istream uses nonexistent num_get member functions. sentry __cerb(*this, false); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { long __l; const __num_get_type& __ng = __check_facet(this->_M_num_get); __ng.get(*this, 0, *this, __err, __l); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 696. istream::operator>>(int&) broken. if (__l < __gnu_cxx::__numeric_traits::__min) { __err |= ios_base::failbit; __n = __gnu_cxx::__numeric_traits::__min; } else if (__l > __gnu_cxx::__numeric_traits::__max) { __err |= ios_base::failbit; __n = __gnu_cxx::__numeric_traits::__max; } else __n = int(__l); } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: operator>>(__streambuf_type* __sbout) { ios_base::iostate __err = ios_base::goodbit; sentry __cerb(*this, false); if (__cerb && __sbout) { __try { bool __ineof; if (!__copy_streambufs_eof(this->rdbuf(), __sbout, __ineof)) __err |= ios_base::failbit; if (__ineof) __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::failbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::failbit); } } else if (!__sbout) __err |= ios_base::failbit; if (__err) this->setstate(__err); return *this; } template typename basic_istream<_CharT, _Traits>::int_type basic_istream<_CharT, _Traits>:: get(void) { const int_type __eof = traits_type::eof(); int_type __c = __eof; _M_gcount = 0; ios_base::iostate __err = ios_base::goodbit; sentry __cerb(*this, true); if (__cerb) { __try { __c = this->rdbuf()->sbumpc(); // 27.6.1.1 paragraph 3 if (!traits_type::eq_int_type(__c, __eof)) _M_gcount = 1; else __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } } if (!_M_gcount) __err |= ios_base::failbit; if (__err) this->setstate(__err); return __c; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: get(char_type& __c) { _M_gcount = 0; ios_base::iostate __err = ios_base::goodbit; sentry __cerb(*this, true); if (__cerb) { __try { const int_type __cb = this->rdbuf()->sbumpc(); // 27.6.1.1 paragraph 3 if (!traits_type::eq_int_type(__cb, traits_type::eof())) { _M_gcount = 1; __c = traits_type::to_char_type(__cb); } else __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } } if (!_M_gcount) __err |= ios_base::failbit; if (__err) this->setstate(__err); return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: get(char_type* __s, streamsize __n, char_type __delim) { _M_gcount = 0; ios_base::iostate __err = ios_base::goodbit; sentry __cerb(*this, true); if (__cerb) { __try { const int_type __idelim = traits_type::to_int_type(__delim); const int_type __eof = traits_type::eof(); __streambuf_type* __sb = this->rdbuf(); int_type __c = __sb->sgetc(); while (_M_gcount + 1 < __n && !traits_type::eq_int_type(__c, __eof) && !traits_type::eq_int_type(__c, __idelim)) { *__s++ = traits_type::to_char_type(__c); ++_M_gcount; __c = __sb->snextc(); } if (traits_type::eq_int_type(__c, __eof)) __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 243. get and getline when sentry reports failure. if (__n > 0) *__s = char_type(); if (!_M_gcount) __err |= ios_base::failbit; if (__err) this->setstate(__err); return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: get(__streambuf_type& __sb, char_type __delim) { _M_gcount = 0; ios_base::iostate __err = ios_base::goodbit; sentry __cerb(*this, true); if (__cerb) { __try { const int_type __idelim = traits_type::to_int_type(__delim); const int_type __eof = traits_type::eof(); __streambuf_type* __this_sb = this->rdbuf(); int_type __c = __this_sb->sgetc(); char_type __c2 = traits_type::to_char_type(__c); while (!traits_type::eq_int_type(__c, __eof) && !traits_type::eq_int_type(__c, __idelim) && !traits_type::eq_int_type(__sb.sputc(__c2), __eof)) { ++_M_gcount; __c = __this_sb->snextc(); __c2 = traits_type::to_char_type(__c); } if (traits_type::eq_int_type(__c, __eof)) __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } } if (!_M_gcount) __err |= ios_base::failbit; if (__err) this->setstate(__err); return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: getline(char_type* __s, streamsize __n, char_type __delim) { _M_gcount = 0; ios_base::iostate __err = ios_base::goodbit; sentry __cerb(*this, true); if (__cerb) { __try { const int_type __idelim = traits_type::to_int_type(__delim); const int_type __eof = traits_type::eof(); __streambuf_type* __sb = this->rdbuf(); int_type __c = __sb->sgetc(); while (_M_gcount + 1 < __n && !traits_type::eq_int_type(__c, __eof) && !traits_type::eq_int_type(__c, __idelim)) { *__s++ = traits_type::to_char_type(__c); __c = __sb->snextc(); ++_M_gcount; } if (traits_type::eq_int_type(__c, __eof)) __err |= ios_base::eofbit; else { if (traits_type::eq_int_type(__c, __idelim)) { __sb->sbumpc(); ++_M_gcount; } else __err |= ios_base::failbit; } } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 243. get and getline when sentry reports failure. if (__n > 0) *__s = char_type(); if (!_M_gcount) __err |= ios_base::failbit; if (__err) this->setstate(__err); return *this; } // We provide three overloads, since the first two are much simpler // than the general case. Also, the latter two can thus adopt the // same "batchy" strategy used by getline above. template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: ignore(void) { _M_gcount = 0; sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { const int_type __eof = traits_type::eof(); __streambuf_type* __sb = this->rdbuf(); if (traits_type::eq_int_type(__sb->sbumpc(), __eof)) __err |= ios_base::eofbit; else _M_gcount = 1; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: ignore(streamsize __n) { _M_gcount = 0; sentry __cerb(*this, true); if (__cerb && __n > 0) { ios_base::iostate __err = ios_base::goodbit; __try { const int_type __eof = traits_type::eof(); __streambuf_type* __sb = this->rdbuf(); int_type __c = __sb->sgetc(); // N.B. On LFS-enabled platforms streamsize is still 32 bits // wide: if we want to implement the standard mandated behavior // for n == max() (see 27.6.1.3/24) we are at risk of signed // integer overflow: thus these contortions. Also note that, // by definition, when more than 2G chars are actually ignored, // _M_gcount (the return value of gcount, that is) cannot be // really correct, being unavoidably too small. bool __large_ignore = false; while (true) { while (_M_gcount < __n && !traits_type::eq_int_type(__c, __eof)) { ++_M_gcount; __c = __sb->snextc(); } if (__n == __gnu_cxx::__numeric_traits::__max && !traits_type::eq_int_type(__c, __eof)) { _M_gcount = __gnu_cxx::__numeric_traits::__min; __large_ignore = true; } else break; } if (__large_ignore) _M_gcount = __gnu_cxx::__numeric_traits::__max; if (traits_type::eq_int_type(__c, __eof)) __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: ignore(streamsize __n, int_type __delim) { _M_gcount = 0; sentry __cerb(*this, true); if (__cerb && __n > 0) { ios_base::iostate __err = ios_base::goodbit; __try { const int_type __eof = traits_type::eof(); __streambuf_type* __sb = this->rdbuf(); int_type __c = __sb->sgetc(); // See comment above. bool __large_ignore = false; while (true) { while (_M_gcount < __n && !traits_type::eq_int_type(__c, __eof) && !traits_type::eq_int_type(__c, __delim)) { ++_M_gcount; __c = __sb->snextc(); } if (__n == __gnu_cxx::__numeric_traits::__max && !traits_type::eq_int_type(__c, __eof) && !traits_type::eq_int_type(__c, __delim)) { _M_gcount = __gnu_cxx::__numeric_traits::__min; __large_ignore = true; } else break; } if (__large_ignore) _M_gcount = __gnu_cxx::__numeric_traits::__max; if (traits_type::eq_int_type(__c, __eof)) __err |= ios_base::eofbit; else if (traits_type::eq_int_type(__c, __delim)) { if (_M_gcount < __gnu_cxx::__numeric_traits::__max) ++_M_gcount; __sb->sbumpc(); } } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template typename basic_istream<_CharT, _Traits>::int_type basic_istream<_CharT, _Traits>:: peek(void) { int_type __c = traits_type::eof(); _M_gcount = 0; sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { __c = this->rdbuf()->sgetc(); if (traits_type::eq_int_type(__c, traits_type::eof())) __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return __c; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: read(char_type* __s, streamsize __n) { _M_gcount = 0; sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { _M_gcount = this->rdbuf()->sgetn(__s, __n); if (_M_gcount != __n) __err |= (ios_base::eofbit | ios_base::failbit); } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template streamsize basic_istream<_CharT, _Traits>:: readsome(char_type* __s, streamsize __n) { _M_gcount = 0; sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { // Cannot compare int_type with streamsize generically. const streamsize __num = this->rdbuf()->in_avail(); if (__num > 0) _M_gcount = this->rdbuf()->sgetn(__s, std::min(__num, __n)); else if (__num == -1) __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return _M_gcount; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: putback(char_type __c) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 60. What is a formatted input function? _M_gcount = 0; // Clear eofbit per N3168. this->clear(this->rdstate() & ~ios_base::eofbit); sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { const int_type __eof = traits_type::eof(); __streambuf_type* __sb = this->rdbuf(); if (!__sb || traits_type::eq_int_type(__sb->sputbackc(__c), __eof)) __err |= ios_base::badbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: unget(void) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 60. What is a formatted input function? _M_gcount = 0; // Clear eofbit per N3168. this->clear(this->rdstate() & ~ios_base::eofbit); sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { const int_type __eof = traits_type::eof(); __streambuf_type* __sb = this->rdbuf(); if (!__sb || traits_type::eq_int_type(__sb->sungetc(), __eof)) __err |= ios_base::badbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template int basic_istream<_CharT, _Traits>:: sync(void) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR60. Do not change _M_gcount. int __ret = -1; sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { __streambuf_type* __sb = this->rdbuf(); if (__sb) { if (__sb->pubsync() == -1) __err |= ios_base::badbit; else __ret = 0; } } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return __ret; } template typename basic_istream<_CharT, _Traits>::pos_type basic_istream<_CharT, _Traits>:: tellg(void) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR60. Do not change _M_gcount. pos_type __ret = pos_type(-1); sentry __cerb(*this, true); if (__cerb) { __try { if (!this->fail()) __ret = this->rdbuf()->pubseekoff(0, ios_base::cur, ios_base::in); } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } } return __ret; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: seekg(pos_type __pos) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR60. Do not change _M_gcount. // Clear eofbit per N3168. this->clear(this->rdstate() & ~ios_base::eofbit); sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { if (!this->fail()) { // 136. seekp, seekg setting wrong streams? const pos_type __p = this->rdbuf()->pubseekpos(__pos, ios_base::in); // 129. Need error indication from seekp() and seekg() if (__p == pos_type(off_type(-1))) __err |= ios_base::failbit; } } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: seekg(off_type __off, ios_base::seekdir __dir) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR60. Do not change _M_gcount. // Clear eofbit per N3168. this->clear(this->rdstate() & ~ios_base::eofbit); sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { if (!this->fail()) { // 136. seekp, seekg setting wrong streams? const pos_type __p = this->rdbuf()->pubseekoff(__off, __dir, ios_base::in); // 129. Need error indication from seekp() and seekg() if (__p == pos_type(off_type(-1))) __err |= ios_base::failbit; } } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } // 27.6.1.2.3 Character extraction templates template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __in, _CharT& __c) { typedef basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::int_type __int_type; typename __istream_type::sentry __cerb(__in, false); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { const __int_type __cb = __in.rdbuf()->sbumpc(); if (!_Traits::eq_int_type(__cb, _Traits::eof())) __c = _Traits::to_char_type(__cb); else __err |= (ios_base::eofbit | ios_base::failbit); } __catch(__cxxabiv1::__forced_unwind&) { __in._M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { __in._M_setstate(ios_base::badbit); } if (__err) __in.setstate(__err); } return __in; } template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __in, _CharT* __s) { typedef basic_istream<_CharT, _Traits> __istream_type; typedef basic_streambuf<_CharT, _Traits> __streambuf_type; typedef typename _Traits::int_type int_type; typedef _CharT char_type; typedef ctype<_CharT> __ctype_type; streamsize __extracted = 0; ios_base::iostate __err = ios_base::goodbit; typename __istream_type::sentry __cerb(__in, false); if (__cerb) { __try { // Figure out how many characters to extract. streamsize __num = __in.width(); if (__num <= 0) __num = __gnu_cxx::__numeric_traits::__max; const __ctype_type& __ct = use_facet<__ctype_type>(__in.getloc()); const int_type __eof = _Traits::eof(); __streambuf_type* __sb = __in.rdbuf(); int_type __c = __sb->sgetc(); while (__extracted < __num - 1 && !_Traits::eq_int_type(__c, __eof) && !__ct.is(ctype_base::space, _Traits::to_char_type(__c))) { *__s++ = _Traits::to_char_type(__c); ++__extracted; __c = __sb->snextc(); } if (_Traits::eq_int_type(__c, __eof)) __err |= ios_base::eofbit; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 68. Extractors for char* should store null at end *__s = char_type(); __in.width(0); } __catch(__cxxabiv1::__forced_unwind&) { __in._M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { __in._M_setstate(ios_base::badbit); } } if (!__extracted) __err |= ios_base::failbit; if (__err) __in.setstate(__err); return __in; } // 27.6.1.4 Standard basic_istream manipulators template basic_istream<_CharT, _Traits>& ws(basic_istream<_CharT, _Traits>& __in) { typedef basic_istream<_CharT, _Traits> __istream_type; typedef basic_streambuf<_CharT, _Traits> __streambuf_type; typedef typename __istream_type::int_type __int_type; typedef ctype<_CharT> __ctype_type; const __ctype_type& __ct = use_facet<__ctype_type>(__in.getloc()); const __int_type __eof = _Traits::eof(); __streambuf_type* __sb = __in.rdbuf(); __int_type __c = __sb->sgetc(); while (!_Traits::eq_int_type(__c, __eof) && __ct.is(ctype_base::space, _Traits::to_char_type(__c))) __c = __sb->snextc(); if (_Traits::eq_int_type(__c, __eof)) __in.setstate(ios_base::eofbit); return __in; } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class basic_istream; extern template istream& ws(istream&); extern template istream& operator>>(istream&, char&); extern template istream& operator>>(istream&, char*); extern template istream& operator>>(istream&, unsigned char&); extern template istream& operator>>(istream&, signed char&); extern template istream& operator>>(istream&, unsigned char*); extern template istream& operator>>(istream&, signed char*); extern template istream& istream::_M_extract(unsigned short&); extern template istream& istream::_M_extract(unsigned int&); extern template istream& istream::_M_extract(long&); extern template istream& istream::_M_extract(unsigned long&); extern template istream& istream::_M_extract(bool&); #ifdef _GLIBCXX_USE_LONG_LONG extern template istream& istream::_M_extract(long long&); extern template istream& istream::_M_extract(unsigned long long&); #endif extern template istream& istream::_M_extract(float&); extern template istream& istream::_M_extract(double&); extern template istream& istream::_M_extract(long double&); extern template istream& istream::_M_extract(void*&); extern template class basic_iostream; #ifdef _GLIBCXX_USE_WCHAR_T extern template class basic_istream; extern template wistream& ws(wistream&); extern template wistream& operator>>(wistream&, wchar_t&); extern template wistream& operator>>(wistream&, wchar_t*); extern template wistream& wistream::_M_extract(unsigned short&); extern template wistream& wistream::_M_extract(unsigned int&); extern template wistream& wistream::_M_extract(long&); extern template wistream& wistream::_M_extract(unsigned long&); extern template wistream& wistream::_M_extract(bool&); #ifdef _GLIBCXX_USE_LONG_LONG extern template wistream& wistream::_M_extract(long long&); extern template wistream& wistream::_M_extract(unsigned long long&); #endif extern template wistream& wistream::_M_extract(float&); extern template wistream& wistream::_M_extract(double&); extern template wistream& wistream::_M_extract(long double&); extern template wistream& wistream::_M_extract(void*&); extern template class basic_iostream; #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!y{h>h>8/bits/list.tccnu[// List implementation (out of line) -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/list.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{list} */ #ifndef _LIST_TCC #define _LIST_TCC 1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER template void _List_base<_Tp, _Alloc>:: _M_clear() _GLIBCXX_NOEXCEPT { typedef _List_node<_Tp> _Node; __detail::_List_node_base* __cur = _M_impl._M_node._M_next; while (__cur != &_M_impl._M_node) { _Node* __tmp = static_cast<_Node*>(__cur); __cur = __tmp->_M_next; _Tp* __val = __tmp->_M_valptr(); #if __cplusplus >= 201103L _Node_alloc_traits::destroy(_M_get_Node_allocator(), __val); #else _Tp_alloc_type(_M_get_Node_allocator()).destroy(__val); #endif _M_put_node(__tmp); } } #if __cplusplus >= 201103L template template typename list<_Tp, _Alloc>::iterator list<_Tp, _Alloc>:: emplace(const_iterator __position, _Args&&... __args) { _Node* __tmp = _M_create_node(std::forward<_Args>(__args)...); __tmp->_M_hook(__position._M_const_cast()._M_node); this->_M_inc_size(1); return iterator(__tmp); } #endif template typename list<_Tp, _Alloc>::iterator list<_Tp, _Alloc>:: #if __cplusplus >= 201103L insert(const_iterator __position, const value_type& __x) #else insert(iterator __position, const value_type& __x) #endif { _Node* __tmp = _M_create_node(__x); __tmp->_M_hook(__position._M_const_cast()._M_node); this->_M_inc_size(1); return iterator(__tmp); } #if __cplusplus >= 201103L template typename list<_Tp, _Alloc>::iterator list<_Tp, _Alloc>:: insert(const_iterator __position, size_type __n, const value_type& __x) { if (__n) { list __tmp(__n, __x, get_allocator()); iterator __it = __tmp.begin(); splice(__position, __tmp); return __it; } return __position._M_const_cast(); } template template typename list<_Tp, _Alloc>::iterator list<_Tp, _Alloc>:: insert(const_iterator __position, _InputIterator __first, _InputIterator __last) { list __tmp(__first, __last, get_allocator()); if (!__tmp.empty()) { iterator __it = __tmp.begin(); splice(__position, __tmp); return __it; } return __position._M_const_cast(); } #endif template typename list<_Tp, _Alloc>::iterator list<_Tp, _Alloc>:: #if __cplusplus >= 201103L erase(const_iterator __position) noexcept #else erase(iterator __position) #endif { iterator __ret = iterator(__position._M_node->_M_next); _M_erase(__position._M_const_cast()); return __ret; } // Return a const_iterator indicating the position to start inserting or // erasing elements (depending whether the list is growing or shrinking), // and set __new_size to the number of new elements that must be appended. // Equivalent to the following, but performed optimally: // if (__new_size < size()) { // __new_size = 0; // return std::next(begin(), __new_size); // } else { // __newsize -= size(); // return end(); // } template typename list<_Tp, _Alloc>::const_iterator list<_Tp, _Alloc>:: _M_resize_pos(size_type& __new_size) const { const_iterator __i; #if _GLIBCXX_USE_CXX11_ABI const size_type __len = size(); if (__new_size < __len) { if (__new_size <= __len / 2) { __i = begin(); std::advance(__i, __new_size); } else { __i = end(); ptrdiff_t __num_erase = __len - __new_size; std::advance(__i, -__num_erase); } __new_size = 0; return __i; } else __i = end(); #else size_type __len = 0; for (__i = begin(); __i != end() && __len < __new_size; ++__i, ++__len) ; #endif __new_size -= __len; return __i; } #if __cplusplus >= 201103L template void list<_Tp, _Alloc>:: _M_default_append(size_type __n) { size_type __i = 0; __try { for (; __i < __n; ++__i) emplace_back(); } __catch(...) { for (; __i; --__i) pop_back(); __throw_exception_again; } } template void list<_Tp, _Alloc>:: resize(size_type __new_size) { const_iterator __i = _M_resize_pos(__new_size); if (__new_size) _M_default_append(__new_size); else erase(__i, end()); } template void list<_Tp, _Alloc>:: resize(size_type __new_size, const value_type& __x) { const_iterator __i = _M_resize_pos(__new_size); if (__new_size) insert(end(), __new_size, __x); else erase(__i, end()); } #else template void list<_Tp, _Alloc>:: resize(size_type __new_size, value_type __x) { const_iterator __i = _M_resize_pos(__new_size); if (__new_size) insert(end(), __new_size, __x); else erase(__i._M_const_cast(), end()); } #endif template list<_Tp, _Alloc>& list<_Tp, _Alloc>:: operator=(const list& __x) { if (this != std::__addressof(__x)) { #if __cplusplus >= 201103L if (_Node_alloc_traits::_S_propagate_on_copy_assign()) { auto& __this_alloc = this->_M_get_Node_allocator(); auto& __that_alloc = __x._M_get_Node_allocator(); if (!_Node_alloc_traits::_S_always_equal() && __this_alloc != __that_alloc) { // replacement allocator cannot free existing storage clear(); } std::__alloc_on_copy(__this_alloc, __that_alloc); } #endif _M_assign_dispatch(__x.begin(), __x.end(), __false_type()); } return *this; } template void list<_Tp, _Alloc>:: _M_fill_assign(size_type __n, const value_type& __val) { iterator __i = begin(); for (; __i != end() && __n > 0; ++__i, --__n) *__i = __val; if (__n > 0) insert(end(), __n, __val); else erase(__i, end()); } template template void list<_Tp, _Alloc>:: _M_assign_dispatch(_InputIterator __first2, _InputIterator __last2, __false_type) { iterator __first1 = begin(); iterator __last1 = end(); for (; __first1 != __last1 && __first2 != __last2; ++__first1, ++__first2) *__first1 = *__first2; if (__first2 == __last2) erase(__first1, __last1); else insert(__last1, __first2, __last2); } template void list<_Tp, _Alloc>:: remove(const value_type& __value) { iterator __first = begin(); iterator __last = end(); iterator __extra = __last; while (__first != __last) { iterator __next = __first; ++__next; if (*__first == __value) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 526. Is it undefined if a function in the standard changes // in parameters? if (std::__addressof(*__first) != std::__addressof(__value)) _M_erase(__first); else __extra = __first; } __first = __next; } if (__extra != __last) _M_erase(__extra); } template void list<_Tp, _Alloc>:: unique() { iterator __first = begin(); iterator __last = end(); if (__first == __last) return; iterator __next = __first; while (++__next != __last) { if (*__first == *__next) _M_erase(__next); else __first = __next; __next = __first; } } template void list<_Tp, _Alloc>:: #if __cplusplus >= 201103L merge(list&& __x) #else merge(list& __x) #endif { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 300. list::merge() specification incomplete if (this != std::__addressof(__x)) { _M_check_equal_allocators(__x); iterator __first1 = begin(); iterator __last1 = end(); iterator __first2 = __x.begin(); iterator __last2 = __x.end(); const size_t __orig_size = __x.size(); __try { while (__first1 != __last1 && __first2 != __last2) if (*__first2 < *__first1) { iterator __next = __first2; _M_transfer(__first1, __first2, ++__next); __first2 = __next; } else ++__first1; if (__first2 != __last2) _M_transfer(__last1, __first2, __last2); this->_M_inc_size(__x._M_get_size()); __x._M_set_size(0); } __catch(...) { const size_t __dist = std::distance(__first2, __last2); this->_M_inc_size(__orig_size - __dist); __x._M_set_size(__dist); __throw_exception_again; } } } template template void list<_Tp, _Alloc>:: #if __cplusplus >= 201103L merge(list&& __x, _StrictWeakOrdering __comp) #else merge(list& __x, _StrictWeakOrdering __comp) #endif { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 300. list::merge() specification incomplete if (this != std::__addressof(__x)) { _M_check_equal_allocators(__x); iterator __first1 = begin(); iterator __last1 = end(); iterator __first2 = __x.begin(); iterator __last2 = __x.end(); const size_t __orig_size = __x.size(); __try { while (__first1 != __last1 && __first2 != __last2) if (__comp(*__first2, *__first1)) { iterator __next = __first2; _M_transfer(__first1, __first2, ++__next); __first2 = __next; } else ++__first1; if (__first2 != __last2) _M_transfer(__last1, __first2, __last2); this->_M_inc_size(__x._M_get_size()); __x._M_set_size(0); } __catch(...) { const size_t __dist = std::distance(__first2, __last2); this->_M_inc_size(__orig_size - __dist); __x._M_set_size(__dist); __throw_exception_again; } } } template void list<_Tp, _Alloc>:: sort() { // Do nothing if the list has length 0 or 1. if (this->_M_impl._M_node._M_next != &this->_M_impl._M_node && this->_M_impl._M_node._M_next->_M_next != &this->_M_impl._M_node) { list __carry; list __tmp[64]; list * __fill = __tmp; list * __counter; __try { do { __carry.splice(__carry.begin(), *this, begin()); for(__counter = __tmp; __counter != __fill && !__counter->empty(); ++__counter) { __counter->merge(__carry); __carry.swap(*__counter); } __carry.swap(*__counter); if (__counter == __fill) ++__fill; } while ( !empty() ); for (__counter = __tmp + 1; __counter != __fill; ++__counter) __counter->merge(*(__counter - 1)); swap( *(__fill - 1) ); } __catch(...) { this->splice(this->end(), __carry); for (int __i = 0; __i < sizeof(__tmp)/sizeof(__tmp[0]); ++__i) this->splice(this->end(), __tmp[__i]); __throw_exception_again; } } } template template void list<_Tp, _Alloc>:: remove_if(_Predicate __pred) { iterator __first = begin(); iterator __last = end(); while (__first != __last) { iterator __next = __first; ++__next; if (__pred(*__first)) _M_erase(__first); __first = __next; } } template template void list<_Tp, _Alloc>:: unique(_BinaryPredicate __binary_pred) { iterator __first = begin(); iterator __last = end(); if (__first == __last) return; iterator __next = __first; while (++__next != __last) { if (__binary_pred(*__first, *__next)) _M_erase(__next); else __first = __next; __next = __first; } } template template void list<_Tp, _Alloc>:: sort(_StrictWeakOrdering __comp) { // Do nothing if the list has length 0 or 1. if (this->_M_impl._M_node._M_next != &this->_M_impl._M_node && this->_M_impl._M_node._M_next->_M_next != &this->_M_impl._M_node) { list __carry; list __tmp[64]; list * __fill = __tmp; list * __counter; __try { do { __carry.splice(__carry.begin(), *this, begin()); for(__counter = __tmp; __counter != __fill && !__counter->empty(); ++__counter) { __counter->merge(__carry, __comp); __carry.swap(*__counter); } __carry.swap(*__counter); if (__counter == __fill) ++__fill; } while ( !empty() ); for (__counter = __tmp + 1; __counter != __fill; ++__counter) __counter->merge(*(__counter - 1), __comp); swap(*(__fill - 1)); } __catch(...) { this->splice(this->end(), __carry); for (int __i = 0; __i < sizeof(__tmp)/sizeof(__tmp[0]); ++__i) this->splice(this->end(), __tmp[__i]); __throw_exception_again; } } } _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _LIST_TCC */ PK!AaAa8/bits/locale_classes.hnu[// Locale support -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/locale_classes.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.1 Locales // #ifndef _LOCALE_CLASSES_H #define _LOCALE_CLASSES_H 1 #pragma GCC system_header #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // 22.1.1 Class locale /** * @brief Container class for localization functionality. * @ingroup locales * * The locale class is first a class wrapper for C library locales. It is * also an extensible container for user-defined localization. A locale is * a collection of facets that implement various localization features such * as money, time, and number printing. * * Constructing C++ locales does not change the C library locale. * * This library supports efficient construction and copying of locales * through a reference counting implementation of the locale class. */ class locale { public: // Types: /// Definition of locale::category. typedef int category; // Forward decls and friends: class facet; class id; class _Impl; friend class facet; friend class _Impl; template friend bool has_facet(const locale&) throw(); template friend const _Facet& use_facet(const locale&); template friend struct __use_cache; //@{ /** * @brief Category values. * * The standard category values are none, ctype, numeric, collate, time, * monetary, and messages. They form a bitmask that supports union and * intersection. The category all is the union of these values. * * NB: Order must match _S_facet_categories definition in locale.cc */ static const category none = 0; static const category ctype = 1L << 0; static const category numeric = 1L << 1; static const category collate = 1L << 2; static const category time = 1L << 3; static const category monetary = 1L << 4; static const category messages = 1L << 5; static const category all = (ctype | numeric | collate | time | monetary | messages); //@} // Construct/copy/destroy: /** * @brief Default constructor. * * Constructs a copy of the global locale. If no locale has been * explicitly set, this is the C locale. */ locale() throw(); /** * @brief Copy constructor. * * Constructs a copy of @a other. * * @param __other The locale to copy. */ locale(const locale& __other) throw(); /** * @brief Named locale constructor. * * Constructs a copy of the named C library locale. * * @param __s Name of the locale to construct. * @throw std::runtime_error if __s is null or an undefined locale. */ explicit locale(const char* __s); /** * @brief Construct locale with facets from another locale. * * Constructs a copy of the locale @a base. The facets specified by @a * cat are replaced with those from the locale named by @a s. If base is * named, this locale instance will also be named. * * @param __base The locale to copy. * @param __s Name of the locale to use facets from. * @param __cat Set of categories defining the facets to use from __s. * @throw std::runtime_error if __s is null or an undefined locale. */ locale(const locale& __base, const char* __s, category __cat); #if __cplusplus >= 201103L /** * @brief Named locale constructor. * * Constructs a copy of the named C library locale. * * @param __s Name of the locale to construct. * @throw std::runtime_error if __s is an undefined locale. */ explicit locale(const std::string& __s) : locale(__s.c_str()) { } /** * @brief Construct locale with facets from another locale. * * Constructs a copy of the locale @a base. The facets specified by @a * cat are replaced with those from the locale named by @a s. If base is * named, this locale instance will also be named. * * @param __base The locale to copy. * @param __s Name of the locale to use facets from. * @param __cat Set of categories defining the facets to use from __s. * @throw std::runtime_error if __s is an undefined locale. */ locale(const locale& __base, const std::string& __s, category __cat) : locale(__base, __s.c_str(), __cat) { } #endif /** * @brief Construct locale with facets from another locale. * * Constructs a copy of the locale @a base. The facets specified by @a * cat are replaced with those from the locale @a add. If @a base and @a * add are named, this locale instance will also be named. * * @param __base The locale to copy. * @param __add The locale to use facets from. * @param __cat Set of categories defining the facets to use from add. */ locale(const locale& __base, const locale& __add, category __cat); /** * @brief Construct locale with another facet. * * Constructs a copy of the locale @a __other. The facet @a __f * is added to @a __other, replacing an existing facet of type * Facet if there is one. If @a __f is null, this locale is a * copy of @a __other. * * @param __other The locale to copy. * @param __f The facet to add in. */ template locale(const locale& __other, _Facet* __f); /// Locale destructor. ~locale() throw(); /** * @brief Assignment operator. * * Set this locale to be a copy of @a other. * * @param __other The locale to copy. * @return A reference to this locale. */ const locale& operator=(const locale& __other) throw(); /** * @brief Construct locale with another facet. * * Constructs and returns a new copy of this locale. Adds or replaces an * existing facet of type Facet from the locale @a other into the new * locale. * * @tparam _Facet The facet type to copy from other * @param __other The locale to copy from. * @return Newly constructed locale. * @throw std::runtime_error if __other has no facet of type _Facet. */ template locale combine(const locale& __other) const; // Locale operations: /** * @brief Return locale name. * @return Locale name or "*" if unnamed. */ _GLIBCXX_DEFAULT_ABI_TAG string name() const; /** * @brief Locale equality. * * @param __other The locale to compare against. * @return True if other and this refer to the same locale instance, are * copies, or have the same name. False otherwise. */ bool operator==(const locale& __other) const throw(); /** * @brief Locale inequality. * * @param __other The locale to compare against. * @return ! (*this == __other) */ bool operator!=(const locale& __other) const throw() { return !(this->operator==(__other)); } /** * @brief Compare two strings according to collate. * * Template operator to compare two strings using the compare function of * the collate facet in this locale. One use is to provide the locale to * the sort function. For example, a vector v of strings could be sorted * according to locale loc by doing: * @code * std::sort(v.begin(), v.end(), loc); * @endcode * * @param __s1 First string to compare. * @param __s2 Second string to compare. * @return True if collate<_Char> facet compares __s1 < __s2, else false. */ template bool operator()(const basic_string<_Char, _Traits, _Alloc>& __s1, const basic_string<_Char, _Traits, _Alloc>& __s2) const; // Global locale objects: /** * @brief Set global locale * * This function sets the global locale to the argument and returns a * copy of the previous global locale. If the argument has a name, it * will also call std::setlocale(LC_ALL, loc.name()). * * @param __loc The new locale to make global. * @return Copy of the old global locale. */ static locale global(const locale& __loc); /** * @brief Return reference to the C locale. */ static const locale& classic(); private: // The (shared) implementation _Impl* _M_impl; // The "C" reference locale static _Impl* _S_classic; // Current global locale static _Impl* _S_global; // Names of underlying locale categories. // NB: locale::global() has to know how to modify all the // underlying categories, not just the ones required by the C++ // standard. static const char* const* const _S_categories; // Number of standard categories. For C++, these categories are // collate, ctype, monetary, numeric, time, and messages. These // directly correspond to ISO C99 macros LC_COLLATE, LC_CTYPE, // LC_MONETARY, LC_NUMERIC, and LC_TIME. In addition, POSIX (IEEE // 1003.1-2001) specifies LC_MESSAGES. // In addition to the standard categories, the underlying // operating system is allowed to define extra LC_* // macros. For GNU systems, the following are also valid: // LC_PAPER, LC_NAME, LC_ADDRESS, LC_TELEPHONE, LC_MEASUREMENT, // and LC_IDENTIFICATION. enum { _S_categories_size = 6 + _GLIBCXX_NUM_CATEGORIES }; #ifdef __GTHREADS static __gthread_once_t _S_once; #endif explicit locale(_Impl*) throw(); static void _S_initialize(); static void _S_initialize_once() throw(); static category _S_normalize_category(category); void _M_coalesce(const locale& __base, const locale& __add, category __cat); #if _GLIBCXX_USE_CXX11_ABI static const id* const _S_twinned_facets[]; #endif }; // 22.1.1.1.2 Class locale::facet /** * @brief Localization functionality base class. * @ingroup locales * * The facet class is the base class for a localization feature, such as * money, time, and number printing. It provides common support for facets * and reference management. * * Facets may not be copied or assigned. */ class locale::facet { private: friend class locale; friend class locale::_Impl; mutable _Atomic_word _M_refcount; // Contains data from the underlying "C" library for the classic locale. static __c_locale _S_c_locale; // String literal for the name of the classic locale. static const char _S_c_name[2]; #ifdef __GTHREADS static __gthread_once_t _S_once; #endif static void _S_initialize_once(); protected: /** * @brief Facet constructor. * * This is the constructor provided by the standard. If refs is 0, the * facet is destroyed when the last referencing locale is destroyed. * Otherwise the facet will never be destroyed. * * @param __refs The initial value for reference count. */ explicit facet(size_t __refs = 0) throw() : _M_refcount(__refs ? 1 : 0) { } /// Facet destructor. virtual ~facet(); static void _S_create_c_locale(__c_locale& __cloc, const char* __s, __c_locale __old = 0); static __c_locale _S_clone_c_locale(__c_locale& __cloc) throw(); static void _S_destroy_c_locale(__c_locale& __cloc); static __c_locale _S_lc_ctype_c_locale(__c_locale __cloc, const char* __s); // Returns data from the underlying "C" library data for the // classic locale. static __c_locale _S_get_c_locale(); _GLIBCXX_CONST static const char* _S_get_c_name() throw(); #if __cplusplus < 201103L private: facet(const facet&); // Not defined. facet& operator=(const facet&); // Not defined. #else facet(const facet&) = delete; facet& operator=(const facet&) = delete; #endif private: void _M_add_reference() const throw() { __gnu_cxx::__atomic_add_dispatch(&_M_refcount, 1); } void _M_remove_reference() const throw() { // Be race-detector-friendly. For more info see bits/c++config. _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_refcount); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_refcount, -1) == 1) { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_refcount); __try { delete this; } __catch(...) { } } } const facet* _M_sso_shim(const id*) const; const facet* _M_cow_shim(const id*) const; protected: class __shim; // For internal use only. }; // 22.1.1.1.3 Class locale::id /** * @brief Facet ID class. * @ingroup locales * * The ID class provides facets with an index used to identify them. * Every facet class must define a public static member locale::id, or be * derived from a facet that provides this member, otherwise the facet * cannot be used in a locale. The locale::id ensures that each class * type gets a unique identifier. */ class locale::id { private: friend class locale; friend class locale::_Impl; template friend const _Facet& use_facet(const locale&); template friend bool has_facet(const locale&) throw(); // NB: There is no accessor for _M_index because it may be used // before the constructor is run; the effect of calling a member // function (even an inline) would be undefined. mutable size_t _M_index; // Last id number assigned. static _Atomic_word _S_refcount; void operator=(const id&); // Not defined. id(const id&); // Not defined. public: // NB: This class is always a static data member, and thus can be // counted on to be zero-initialized. /// Constructor. id() { } size_t _M_id() const throw(); }; // Implementation object for locale. class locale::_Impl { public: // Friends. friend class locale; friend class locale::facet; template friend bool has_facet(const locale&) throw(); template friend const _Facet& use_facet(const locale&); template friend struct __use_cache; private: // Data Members. _Atomic_word _M_refcount; const facet** _M_facets; size_t _M_facets_size; const facet** _M_caches; char** _M_names; static const locale::id* const _S_id_ctype[]; static const locale::id* const _S_id_numeric[]; static const locale::id* const _S_id_collate[]; static const locale::id* const _S_id_time[]; static const locale::id* const _S_id_monetary[]; static const locale::id* const _S_id_messages[]; static const locale::id* const* const _S_facet_categories[]; void _M_add_reference() throw() { __gnu_cxx::__atomic_add_dispatch(&_M_refcount, 1); } void _M_remove_reference() throw() { // Be race-detector-friendly. For more info see bits/c++config. _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_refcount); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_refcount, -1) == 1) { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_refcount); __try { delete this; } __catch(...) { } } } _Impl(const _Impl&, size_t); _Impl(const char*, size_t); _Impl(size_t) throw(); ~_Impl() throw(); _Impl(const _Impl&); // Not defined. void operator=(const _Impl&); // Not defined. bool _M_check_same_name() { bool __ret = true; if (_M_names[1]) // We must actually compare all the _M_names: can be all equal! for (size_t __i = 0; __ret && __i < _S_categories_size - 1; ++__i) __ret = __builtin_strcmp(_M_names[__i], _M_names[__i + 1]) == 0; return __ret; } void _M_replace_categories(const _Impl*, category); void _M_replace_category(const _Impl*, const locale::id* const*); void _M_replace_facet(const _Impl*, const locale::id*); void _M_install_facet(const locale::id*, const facet*); template void _M_init_facet(_Facet* __facet) { _M_install_facet(&_Facet::id, __facet); } template void _M_init_facet_unchecked(_Facet* __facet) { __facet->_M_add_reference(); _M_facets[_Facet::id._M_id()] = __facet; } void _M_install_cache(const facet*, size_t); void _M_init_extra(facet**); void _M_init_extra(void*, void*, const char*, const char*); }; /** * @brief Facet for localized string comparison. * * This facet encapsulates the code to compare strings in a localized * manner. * * The collate template uses protected virtual functions to provide * the actual results. The public accessors forward the call to * the virtual functions. These virtual functions are hooks for * developers to implement the behavior they require from the * collate facet. */ template class _GLIBCXX_NAMESPACE_CXX11 collate : public locale::facet { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef basic_string<_CharT> string_type; //@} protected: // Underlying "C" library locale information saved from // initialization, needed by collate_byname as well. __c_locale _M_c_locale_collate; public: /// Numpunct facet id. static locale::id id; /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __refs Passed to the base facet class. */ explicit collate(size_t __refs = 0) : facet(__refs), _M_c_locale_collate(_S_get_c_locale()) { } /** * @brief Internal constructor. Not for general use. * * This is a constructor for use by the library itself to set up new * locales. * * @param __cloc The C locale. * @param __refs Passed to the base facet class. */ explicit collate(__c_locale __cloc, size_t __refs = 0) : facet(__refs), _M_c_locale_collate(_S_clone_c_locale(__cloc)) { } /** * @brief Compare two strings. * * This function compares two strings and returns the result by calling * collate::do_compare(). * * @param __lo1 Start of string 1. * @param __hi1 End of string 1. * @param __lo2 Start of string 2. * @param __hi2 End of string 2. * @return 1 if string1 > string2, -1 if string1 < string2, else 0. */ int compare(const _CharT* __lo1, const _CharT* __hi1, const _CharT* __lo2, const _CharT* __hi2) const { return this->do_compare(__lo1, __hi1, __lo2, __hi2); } /** * @brief Transform string to comparable form. * * This function is a wrapper for strxfrm functionality. It takes the * input string and returns a modified string that can be directly * compared to other transformed strings. In the C locale, this * function just returns a copy of the input string. In some other * locales, it may replace two chars with one, change a char for * another, etc. It does so by returning collate::do_transform(). * * @param __lo Start of string. * @param __hi End of string. * @return Transformed string_type. */ string_type transform(const _CharT* __lo, const _CharT* __hi) const { return this->do_transform(__lo, __hi); } /** * @brief Return hash of a string. * * This function computes and returns a hash on the input string. It * does so by returning collate::do_hash(). * * @param __lo Start of string. * @param __hi End of string. * @return Hash value. */ long hash(const _CharT* __lo, const _CharT* __hi) const { return this->do_hash(__lo, __hi); } // Used to abstract out _CharT bits in virtual member functions, below. int _M_compare(const _CharT*, const _CharT*) const throw(); size_t _M_transform(_CharT*, const _CharT*, size_t) const throw(); protected: /// Destructor. virtual ~collate() { _S_destroy_c_locale(_M_c_locale_collate); } /** * @brief Compare two strings. * * This function is a hook for derived classes to change the value * returned. @see compare(). * * @param __lo1 Start of string 1. * @param __hi1 End of string 1. * @param __lo2 Start of string 2. * @param __hi2 End of string 2. * @return 1 if string1 > string2, -1 if string1 < string2, else 0. */ virtual int do_compare(const _CharT* __lo1, const _CharT* __hi1, const _CharT* __lo2, const _CharT* __hi2) const; /** * @brief Transform string to comparable form. * * This function is a hook for derived classes to change the value * returned. * * @param __lo Start. * @param __hi End. * @return transformed string. */ virtual string_type do_transform(const _CharT* __lo, const _CharT* __hi) const; /** * @brief Return hash of a string. * * This function computes and returns a hash on the input string. This * function is a hook for derived classes to change the value returned. * * @param __lo Start of string. * @param __hi End of string. * @return Hash value. */ virtual long do_hash(const _CharT* __lo, const _CharT* __hi) const; }; template locale::id collate<_CharT>::id; // Specializations. template<> int collate::_M_compare(const char*, const char*) const throw(); template<> size_t collate::_M_transform(char*, const char*, size_t) const throw(); #ifdef _GLIBCXX_USE_WCHAR_T template<> int collate::_M_compare(const wchar_t*, const wchar_t*) const throw(); template<> size_t collate::_M_transform(wchar_t*, const wchar_t*, size_t) const throw(); #endif /// class collate_byname [22.2.4.2]. template class _GLIBCXX_NAMESPACE_CXX11 collate_byname : public collate<_CharT> { public: //@{ /// Public typedefs typedef _CharT char_type; typedef basic_string<_CharT> string_type; //@} explicit collate_byname(const char* __s, size_t __refs = 0) : collate<_CharT>(__refs) { if (__builtin_strcmp(__s, "C") != 0 && __builtin_strcmp(__s, "POSIX") != 0) { this->_S_destroy_c_locale(this->_M_c_locale_collate); this->_S_create_c_locale(this->_M_c_locale_collate, __s); } } #if __cplusplus >= 201103L explicit collate_byname(const string& __s, size_t __refs = 0) : collate_byname(__s.c_str(), __refs) { } #endif protected: virtual ~collate_byname() { } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace # include #endif PK!ܷ 8/bits/locale_classes.tccnu[// Locale support -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/locale_classes.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.1 Locales // #ifndef _LOCALE_CLASSES_TCC #define _LOCALE_CLASSES_TCC 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template locale:: locale(const locale& __other, _Facet* __f) { _M_impl = new _Impl(*__other._M_impl, 1); __try { _M_impl->_M_install_facet(&_Facet::id, __f); } __catch(...) { _M_impl->_M_remove_reference(); __throw_exception_again; } delete [] _M_impl->_M_names[0]; _M_impl->_M_names[0] = 0; // Unnamed. } template locale locale:: combine(const locale& __other) const { _Impl* __tmp = new _Impl(*_M_impl, 1); __try { __tmp->_M_replace_facet(__other._M_impl, &_Facet::id); } __catch(...) { __tmp->_M_remove_reference(); __throw_exception_again; } return locale(__tmp); } template bool locale:: operator()(const basic_string<_CharT, _Traits, _Alloc>& __s1, const basic_string<_CharT, _Traits, _Alloc>& __s2) const { typedef std::collate<_CharT> __collate_type; const __collate_type& __collate = use_facet<__collate_type>(*this); return (__collate.compare(__s1.data(), __s1.data() + __s1.length(), __s2.data(), __s2.data() + __s2.length()) < 0); } /** * @brief Test for the presence of a facet. * @ingroup locales * * has_facet tests the locale argument for the presence of the facet type * provided as the template parameter. Facets derived from the facet * parameter will also return true. * * @tparam _Facet The facet type to test the presence of. * @param __loc The locale to test. * @return true if @p __loc contains a facet of type _Facet, else false. */ template bool has_facet(const locale& __loc) throw() { const size_t __i = _Facet::id._M_id(); const locale::facet** __facets = __loc._M_impl->_M_facets; return (__i < __loc._M_impl->_M_facets_size #if __cpp_rtti && dynamic_cast(__facets[__i])); #else && static_cast(__facets[__i])); #endif } /** * @brief Return a facet. * @ingroup locales * * use_facet looks for and returns a reference to a facet of type Facet * where Facet is the template parameter. If has_facet(locale) is true, * there is a suitable facet to return. It throws std::bad_cast if the * locale doesn't contain a facet of type Facet. * * @tparam _Facet The facet type to access. * @param __loc The locale to use. * @return Reference to facet of type Facet. * @throw std::bad_cast if @p __loc doesn't contain a facet of type _Facet. */ template const _Facet& use_facet(const locale& __loc) { const size_t __i = _Facet::id._M_id(); const locale::facet** __facets = __loc._M_impl->_M_facets; if (__i >= __loc._M_impl->_M_facets_size || !__facets[__i]) __throw_bad_cast(); #if __cpp_rtti return dynamic_cast(*__facets[__i]); #else return static_cast(*__facets[__i]); #endif } // Generic version does nothing. template int collate<_CharT>::_M_compare(const _CharT*, const _CharT*) const throw () { return 0; } // Generic version does nothing. template size_t collate<_CharT>::_M_transform(_CharT*, const _CharT*, size_t) const throw () { return 0; } template int collate<_CharT>:: do_compare(const _CharT* __lo1, const _CharT* __hi1, const _CharT* __lo2, const _CharT* __hi2) const { // strcoll assumes zero-terminated strings so we make a copy // and then put a zero at the end. const string_type __one(__lo1, __hi1); const string_type __two(__lo2, __hi2); const _CharT* __p = __one.c_str(); const _CharT* __pend = __one.data() + __one.length(); const _CharT* __q = __two.c_str(); const _CharT* __qend = __two.data() + __two.length(); // strcoll stops when it sees a nul character so we break // the strings into zero-terminated substrings and pass those // to strcoll. for (;;) { const int __res = _M_compare(__p, __q); if (__res) return __res; __p += char_traits<_CharT>::length(__p); __q += char_traits<_CharT>::length(__q); if (__p == __pend && __q == __qend) return 0; else if (__p == __pend) return -1; else if (__q == __qend) return 1; __p++; __q++; } } template typename collate<_CharT>::string_type collate<_CharT>:: do_transform(const _CharT* __lo, const _CharT* __hi) const { string_type __ret; // strxfrm assumes zero-terminated strings so we make a copy const string_type __str(__lo, __hi); const _CharT* __p = __str.c_str(); const _CharT* __pend = __str.data() + __str.length(); size_t __len = (__hi - __lo) * 2; _CharT* __c = new _CharT[__len]; __try { // strxfrm stops when it sees a nul character so we break // the string into zero-terminated substrings and pass those // to strxfrm. for (;;) { // First try a buffer perhaps big enough. size_t __res = _M_transform(__c, __p, __len); // If the buffer was not large enough, try again with the // correct size. if (__res >= __len) { __len = __res + 1; delete [] __c, __c = 0; __c = new _CharT[__len]; __res = _M_transform(__c, __p, __len); } __ret.append(__c, __res); __p += char_traits<_CharT>::length(__p); if (__p == __pend) break; __p++; __ret.push_back(_CharT()); } } __catch(...) { delete [] __c; __throw_exception_again; } delete [] __c; return __ret; } template long collate<_CharT>:: do_hash(const _CharT* __lo, const _CharT* __hi) const { unsigned long __val = 0; for (; __lo < __hi; ++__lo) __val = *__lo + ((__val << 7) | (__val >> (__gnu_cxx::__numeric_traits:: __digits - 7))); return static_cast(__val); } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class collate; extern template class collate_byname; extern template const collate& use_facet >(const locale&); extern template bool has_facet >(const locale&); #ifdef _GLIBCXX_USE_WCHAR_T extern template class collate; extern template class collate_byname; extern template const collate& use_facet >(const locale&); extern template bool has_facet >(const locale&); #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!2t>>8/bits/locale_conv.hnu[// wstring_convert implementation -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/locale_conv.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ #ifndef _LOCALE_CONV_H #define _LOCALE_CONV_H 1 #if __cplusplus < 201103L # include #else #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup locales * @{ */ template bool __do_str_codecvt(const _InChar* __first, const _InChar* __last, _OutStr& __outstr, const _Codecvt& __cvt, _State& __state, size_t& __count, _Fn __fn) { if (__first == __last) { __outstr.clear(); __count = 0; return true; } size_t __outchars = 0; auto __next = __first; const auto __maxlen = __cvt.max_length() + 1; codecvt_base::result __result; do { __outstr.resize(__outstr.size() + (__last - __next) * __maxlen); auto __outnext = &__outstr.front() + __outchars; auto const __outlast = &__outstr.back() + 1; __result = (__cvt.*__fn)(__state, __next, __last, __next, __outnext, __outlast, __outnext); __outchars = __outnext - &__outstr.front(); } while (__result == codecvt_base::partial && __next != __last && (__outstr.size() - __outchars) < __maxlen); if (__result == codecvt_base::error) { __count = __next - __first; return false; } if (__result == codecvt_base::noconv) { __outstr.assign(__first, __last); __count = __last - __first; } else { __outstr.resize(__outchars); __count = __next - __first; } return true; } // Convert narrow character string to wide. template inline bool __str_codecvt_in(const char* __first, const char* __last, basic_string<_CharT, _Traits, _Alloc>& __outstr, const codecvt<_CharT, char, _State>& __cvt, _State& __state, size_t& __count) { using _Codecvt = codecvt<_CharT, char, _State>; using _ConvFn = codecvt_base::result (_Codecvt::*)(_State&, const char*, const char*, const char*&, _CharT*, _CharT*, _CharT*&) const; _ConvFn __fn = &codecvt<_CharT, char, _State>::in; return __do_str_codecvt(__first, __last, __outstr, __cvt, __state, __count, __fn); } template inline bool __str_codecvt_in(const char* __first, const char* __last, basic_string<_CharT, _Traits, _Alloc>& __outstr, const codecvt<_CharT, char, _State>& __cvt) { _State __state = {}; size_t __n; return __str_codecvt_in(__first, __last, __outstr, __cvt, __state, __n); } // Convert wide character string to narrow. template inline bool __str_codecvt_out(const _CharT* __first, const _CharT* __last, basic_string& __outstr, const codecvt<_CharT, char, _State>& __cvt, _State& __state, size_t& __count) { using _Codecvt = codecvt<_CharT, char, _State>; using _ConvFn = codecvt_base::result (_Codecvt::*)(_State&, const _CharT*, const _CharT*, const _CharT*&, char*, char*, char*&) const; _ConvFn __fn = &codecvt<_CharT, char, _State>::out; return __do_str_codecvt(__first, __last, __outstr, __cvt, __state, __count, __fn); } template inline bool __str_codecvt_out(const _CharT* __first, const _CharT* __last, basic_string& __outstr, const codecvt<_CharT, char, _State>& __cvt) { _State __state = {}; size_t __n; return __str_codecvt_out(__first, __last, __outstr, __cvt, __state, __n); } #ifdef _GLIBCXX_USE_WCHAR_T _GLIBCXX_BEGIN_NAMESPACE_CXX11 /// String conversions template, typename _Byte_alloc = allocator> class wstring_convert { public: typedef basic_string, _Byte_alloc> byte_string; typedef basic_string<_Elem, char_traits<_Elem>, _Wide_alloc> wide_string; typedef typename _Codecvt::state_type state_type; typedef typename wide_string::traits_type::int_type int_type; /** Default constructor. * * @param __pcvt The facet to use for conversions. * * Takes ownership of @p __pcvt and will delete it in the destructor. */ explicit wstring_convert(_Codecvt* __pcvt = new _Codecvt()) : _M_cvt(__pcvt) { if (!_M_cvt) __throw_logic_error("wstring_convert"); } /** Construct with an initial converstion state. * * @param __pcvt The facet to use for conversions. * @param __state Initial conversion state. * * Takes ownership of @p __pcvt and will delete it in the destructor. * The object's conversion state will persist between conversions. */ wstring_convert(_Codecvt* __pcvt, state_type __state) : _M_cvt(__pcvt), _M_state(__state), _M_with_cvtstate(true) { if (!_M_cvt) __throw_logic_error("wstring_convert"); } /** Construct with error strings. * * @param __byte_err A string to return on failed conversions. * @param __wide_err A wide string to return on failed conversions. */ explicit wstring_convert(const byte_string& __byte_err, const wide_string& __wide_err = wide_string()) : _M_cvt(new _Codecvt), _M_byte_err_string(__byte_err), _M_wide_err_string(__wide_err), _M_with_strings(true) { if (!_M_cvt) __throw_logic_error("wstring_convert"); } ~wstring_convert() = default; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2176. Special members for wstring_convert and wbuffer_convert wstring_convert(const wstring_convert&) = delete; wstring_convert& operator=(const wstring_convert&) = delete; /// @{ Convert from bytes. wide_string from_bytes(char __byte) { char __bytes[2] = { __byte }; return from_bytes(__bytes, __bytes+1); } wide_string from_bytes(const char* __ptr) { return from_bytes(__ptr, __ptr+char_traits::length(__ptr)); } wide_string from_bytes(const byte_string& __str) { auto __ptr = __str.data(); return from_bytes(__ptr, __ptr + __str.size()); } wide_string from_bytes(const char* __first, const char* __last) { if (!_M_with_cvtstate) _M_state = state_type(); wide_string __out{ _M_wide_err_string.get_allocator() }; if (__str_codecvt_in(__first, __last, __out, *_M_cvt, _M_state, _M_count)) return __out; if (_M_with_strings) return _M_wide_err_string; __throw_range_error("wstring_convert::from_bytes"); } /// @} /// @{ Convert to bytes. byte_string to_bytes(_Elem __wchar) { _Elem __wchars[2] = { __wchar }; return to_bytes(__wchars, __wchars+1); } byte_string to_bytes(const _Elem* __ptr) { return to_bytes(__ptr, __ptr+wide_string::traits_type::length(__ptr)); } byte_string to_bytes(const wide_string& __wstr) { auto __ptr = __wstr.data(); return to_bytes(__ptr, __ptr + __wstr.size()); } byte_string to_bytes(const _Elem* __first, const _Elem* __last) { if (!_M_with_cvtstate) _M_state = state_type(); byte_string __out{ _M_byte_err_string.get_allocator() }; if (__str_codecvt_out(__first, __last, __out, *_M_cvt, _M_state, _M_count)) return __out; if (_M_with_strings) return _M_byte_err_string; __throw_range_error("wstring_convert::to_bytes"); } /// @} // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2174. wstring_convert::converted() should be noexcept /// The number of elements successfully converted in the last conversion. size_t converted() const noexcept { return _M_count; } /// The final conversion state of the last conversion. state_type state() const { return _M_state; } private: unique_ptr<_Codecvt> _M_cvt; byte_string _M_byte_err_string; wide_string _M_wide_err_string; state_type _M_state = state_type(); size_t _M_count = 0; bool _M_with_cvtstate = false; bool _M_with_strings = false; }; _GLIBCXX_END_NAMESPACE_CXX11 /// Buffer conversions template> class wbuffer_convert : public basic_streambuf<_Elem, _Tr> { typedef basic_streambuf<_Elem, _Tr> _Wide_streambuf; public: typedef typename _Codecvt::state_type state_type; /** Default constructor. * * @param __bytebuf The underlying byte stream buffer. * @param __pcvt The facet to use for conversions. * @param __state Initial conversion state. * * Takes ownership of @p __pcvt and will delete it in the destructor. */ explicit wbuffer_convert(streambuf* __bytebuf = 0, _Codecvt* __pcvt = new _Codecvt, state_type __state = state_type()) : _M_buf(__bytebuf), _M_cvt(__pcvt), _M_state(__state) { if (!_M_cvt) __throw_logic_error("wbuffer_convert"); _M_always_noconv = _M_cvt->always_noconv(); if (_M_buf) { this->setp(_M_put_area, _M_put_area + _S_buffer_length); this->setg(_M_get_area + _S_putback_length, _M_get_area + _S_putback_length, _M_get_area + _S_putback_length); } } ~wbuffer_convert() = default; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2176. Special members for wstring_convert and wbuffer_convert wbuffer_convert(const wbuffer_convert&) = delete; wbuffer_convert& operator=(const wbuffer_convert&) = delete; streambuf* rdbuf() const noexcept { return _M_buf; } streambuf* rdbuf(streambuf *__bytebuf) noexcept { auto __prev = _M_buf; _M_buf = __bytebuf; return __prev; } /// The conversion state following the last conversion. state_type state() const noexcept { return _M_state; } protected: int sync() { return _M_buf && _M_conv_put() && !_M_buf->pubsync() ? 0 : -1; } typename _Wide_streambuf::int_type overflow(typename _Wide_streambuf::int_type __out) { if (!_M_buf || !_M_conv_put()) return _Tr::eof(); else if (!_Tr::eq_int_type(__out, _Tr::eof())) return this->sputc(__out); return _Tr::not_eof(__out); } typename _Wide_streambuf::int_type underflow() { if (!_M_buf) return _Tr::eof(); if (this->gptr() < this->egptr() || (_M_buf && _M_conv_get())) return _Tr::to_int_type(*this->gptr()); else return _Tr::eof(); } streamsize xsputn(const typename _Wide_streambuf::char_type* __s, streamsize __n) { if (!_M_buf || __n == 0) return 0; streamsize __done = 0; do { auto __nn = std::min(this->epptr() - this->pptr(), __n - __done); _Tr::copy(this->pptr(), __s + __done, __nn); this->pbump(__nn); __done += __nn; } while (__done < __n && _M_conv_put()); return __done; } private: // fill the get area from converted contents of the byte stream buffer bool _M_conv_get() { const streamsize __pb1 = this->gptr() - this->eback(); const streamsize __pb2 = _S_putback_length; const streamsize __npb = std::min(__pb1, __pb2); _Tr::move(_M_get_area + _S_putback_length - __npb, this->gptr() - __npb, __npb); streamsize __nbytes = sizeof(_M_get_buf) - _M_unconv; __nbytes = std::min(__nbytes, _M_buf->in_avail()); if (__nbytes < 1) __nbytes = 1; __nbytes = _M_buf->sgetn(_M_get_buf + _M_unconv, __nbytes); if (__nbytes < 1) return false; __nbytes += _M_unconv; // convert _M_get_buf into _M_get_area _Elem* __outbuf = _M_get_area + _S_putback_length; _Elem* __outnext = __outbuf; const char* __bnext = _M_get_buf; codecvt_base::result __result; if (_M_always_noconv) __result = codecvt_base::noconv; else { _Elem* __outend = _M_get_area + _S_buffer_length; __result = _M_cvt->in(_M_state, __bnext, __bnext + __nbytes, __bnext, __outbuf, __outend, __outnext); } if (__result == codecvt_base::noconv) { // cast is safe because noconv means _Elem is same type as char auto __get_buf = reinterpret_cast(_M_get_buf); _Tr::copy(__outbuf, __get_buf, __nbytes); _M_unconv = 0; return true; } if ((_M_unconv = _M_get_buf + __nbytes - __bnext)) char_traits::move(_M_get_buf, __bnext, _M_unconv); this->setg(__outbuf, __outbuf, __outnext); return __result != codecvt_base::error; } // unused bool _M_put(...) { return false; } bool _M_put(const char* __p, streamsize __n) { if (_M_buf->sputn(__p, __n) < __n) return false; return true; } // convert the put area and write to the byte stream buffer bool _M_conv_put() { _Elem* const __first = this->pbase(); const _Elem* const __last = this->pptr(); const streamsize __pending = __last - __first; if (_M_always_noconv) return _M_put(__first, __pending); char __outbuf[2 * _S_buffer_length]; const _Elem* __next = __first; const _Elem* __start; do { __start = __next; char* __outnext = __outbuf; char* const __outlast = __outbuf + sizeof(__outbuf); auto __result = _M_cvt->out(_M_state, __next, __last, __next, __outnext, __outlast, __outnext); if (__result == codecvt_base::error) return false; else if (__result == codecvt_base::noconv) return _M_put(__next, __pending); if (!_M_put(__outbuf, __outnext - __outbuf)) return false; } while (__next != __last && __next != __start); if (__next != __last) _Tr::move(__first, __next, __last - __next); this->pbump(__first - __next); return __next != __first; } streambuf* _M_buf; unique_ptr<_Codecvt> _M_cvt; state_type _M_state; static const streamsize _S_buffer_length = 32; static const streamsize _S_putback_length = 3; _Elem _M_put_area[_S_buffer_length]; _Elem _M_get_area[_S_buffer_length]; streamsize _M_unconv = 0; char _M_get_buf[_S_buffer_length-_S_putback_length]; bool _M_always_noconv; }; #endif // _GLIBCXX_USE_WCHAR_T /// @} group locales _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // __cplusplus #endif /* _LOCALE_CONV_H */ PK!Qhh8/bits/locale_facets.hnu[// Locale support -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/locale_facets.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.1 Locales // #ifndef _LOCALE_FACETS_H #define _LOCALE_FACETS_H 1 #pragma GCC system_header #include // For wctype_t #include #include #include #include // For ios_base, ios_base::iostate #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // NB: Don't instantiate required wchar_t facets if no wchar_t support. #ifdef _GLIBCXX_USE_WCHAR_T # define _GLIBCXX_NUM_FACETS 28 # define _GLIBCXX_NUM_CXX11_FACETS 16 #else # define _GLIBCXX_NUM_FACETS 14 # define _GLIBCXX_NUM_CXX11_FACETS 8 #endif #ifdef _GLIBCXX_USE_C99_STDINT_TR1 # define _GLIBCXX_NUM_UNICODE_FACETS 2 #else # define _GLIBCXX_NUM_UNICODE_FACETS 0 #endif // Convert string to numeric value of type _Tp and store results. // NB: This is specialized for all required types, there is no // generic definition. template void __convert_to_v(const char*, _Tp&, ios_base::iostate&, const __c_locale&) throw(); // Explicit specializations for required types. template<> void __convert_to_v(const char*, float&, ios_base::iostate&, const __c_locale&) throw(); template<> void __convert_to_v(const char*, double&, ios_base::iostate&, const __c_locale&) throw(); template<> void __convert_to_v(const char*, long double&, ios_base::iostate&, const __c_locale&) throw(); // NB: __pad is a struct, rather than a function, so it can be // partially-specialized. template struct __pad { static void _S_pad(ios_base& __io, _CharT __fill, _CharT* __news, const _CharT* __olds, streamsize __newlen, streamsize __oldlen); }; // Used by both numeric and monetary facets. // Inserts "group separator" characters into an array of characters. // It's recursive, one iteration per group. It moves the characters // in the buffer this way: "xxxx12345" -> "12,345xxx". Call this // only with __gsize != 0. template _CharT* __add_grouping(_CharT* __s, _CharT __sep, const char* __gbeg, size_t __gsize, const _CharT* __first, const _CharT* __last); // This template permits specializing facet output code for // ostreambuf_iterator. For ostreambuf_iterator, sputn is // significantly more efficient than incrementing iterators. template inline ostreambuf_iterator<_CharT> __write(ostreambuf_iterator<_CharT> __s, const _CharT* __ws, int __len) { __s._M_put(__ws, __len); return __s; } // This is the unspecialized form of the template. template inline _OutIter __write(_OutIter __s, const _CharT* __ws, int __len) { for (int __j = 0; __j < __len; __j++, ++__s) *__s = __ws[__j]; return __s; } // 22.2.1.1 Template class ctype // Include host and configuration specific ctype enums for ctype_base. /** * @brief Common base for ctype facet * * This template class provides implementations of the public functions * that forward to the protected virtual functions. * * This template also provides abstract stubs for the protected virtual * functions. */ template class __ctype_abstract_base : public locale::facet, public ctype_base { public: // Types: /// Typedef for the template parameter typedef _CharT char_type; /** * @brief Test char_type classification. * * This function finds a mask M for @a __c and compares it to * mask @a __m. It does so by returning the value of * ctype::do_is(). * * @param __c The char_type to compare the mask of. * @param __m The mask to compare against. * @return (M & __m) != 0. */ bool is(mask __m, char_type __c) const { return this->do_is(__m, __c); } /** * @brief Return a mask array. * * This function finds the mask for each char_type in the range [lo,hi) * and successively writes it to vec. vec must have as many elements * as the char array. It does so by returning the value of * ctype::do_is(). * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __vec Pointer to an array of mask storage. * @return @a __hi. */ const char_type* is(const char_type *__lo, const char_type *__hi, mask *__vec) const { return this->do_is(__lo, __hi, __vec); } /** * @brief Find char_type matching a mask * * This function searches for and returns the first char_type c in * [lo,hi) for which is(m,c) is true. It does so by returning * ctype::do_scan_is(). * * @param __m The mask to compare against. * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return Pointer to matching char_type if found, else @a __hi. */ const char_type* scan_is(mask __m, const char_type* __lo, const char_type* __hi) const { return this->do_scan_is(__m, __lo, __hi); } /** * @brief Find char_type not matching a mask * * This function searches for and returns the first char_type c in * [lo,hi) for which is(m,c) is false. It does so by returning * ctype::do_scan_not(). * * @param __m The mask to compare against. * @param __lo Pointer to first char in range. * @param __hi Pointer to end of range. * @return Pointer to non-matching char if found, else @a __hi. */ const char_type* scan_not(mask __m, const char_type* __lo, const char_type* __hi) const { return this->do_scan_not(__m, __lo, __hi); } /** * @brief Convert to uppercase. * * This function converts the argument to uppercase if possible. * If not possible (for example, '2'), returns the argument. It does * so by returning ctype::do_toupper(). * * @param __c The char_type to convert. * @return The uppercase char_type if convertible, else @a __c. */ char_type toupper(char_type __c) const { return this->do_toupper(__c); } /** * @brief Convert array to uppercase. * * This function converts each char_type in the range [lo,hi) to * uppercase if possible. Other elements remain untouched. It does so * by returning ctype:: do_toupper(lo, hi). * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return @a __hi. */ const char_type* toupper(char_type *__lo, const char_type* __hi) const { return this->do_toupper(__lo, __hi); } /** * @brief Convert to lowercase. * * This function converts the argument to lowercase if possible. If * not possible (for example, '2'), returns the argument. It does so * by returning ctype::do_tolower(c). * * @param __c The char_type to convert. * @return The lowercase char_type if convertible, else @a __c. */ char_type tolower(char_type __c) const { return this->do_tolower(__c); } /** * @brief Convert array to lowercase. * * This function converts each char_type in the range [__lo,__hi) to * lowercase if possible. Other elements remain untouched. It does so * by returning ctype:: do_tolower(__lo, __hi). * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return @a __hi. */ const char_type* tolower(char_type* __lo, const char_type* __hi) const { return this->do_tolower(__lo, __hi); } /** * @brief Widen char to char_type * * This function converts the char argument to char_type using the * simplest reasonable transformation. It does so by returning * ctype::do_widen(c). * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char to convert. * @return The converted char_type. */ char_type widen(char __c) const { return this->do_widen(__c); } /** * @brief Widen array to char_type * * This function converts each char in the input to char_type using the * simplest reasonable transformation. It does so by returning * ctype::do_widen(c). * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __to Pointer to the destination array. * @return @a __hi. */ const char* widen(const char* __lo, const char* __hi, char_type* __to) const { return this->do_widen(__lo, __hi, __to); } /** * @brief Narrow char_type to char * * This function converts the char_type to char using the simplest * reasonable transformation. If the conversion fails, dfault is * returned instead. It does so by returning * ctype::do_narrow(__c). * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char_type to convert. * @param __dfault Char to return if conversion fails. * @return The converted char. */ char narrow(char_type __c, char __dfault) const { return this->do_narrow(__c, __dfault); } /** * @brief Narrow array to char array * * This function converts each char_type in the input to char using the * simplest reasonable transformation and writes the results to the * destination array. For any char_type in the input that cannot be * converted, @a dfault is used instead. It does so by returning * ctype::do_narrow(__lo, __hi, __dfault, __to). * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __dfault Char to use if conversion fails. * @param __to Pointer to the destination array. * @return @a __hi. */ const char_type* narrow(const char_type* __lo, const char_type* __hi, char __dfault, char* __to) const { return this->do_narrow(__lo, __hi, __dfault, __to); } protected: explicit __ctype_abstract_base(size_t __refs = 0): facet(__refs) { } virtual ~__ctype_abstract_base() { } /** * @brief Test char_type classification. * * This function finds a mask M for @a c and compares it to mask @a m. * * do_is() is a hook for a derived facet to change the behavior of * classifying. do_is() must always return the same result for the * same input. * * @param __c The char_type to find the mask of. * @param __m The mask to compare against. * @return (M & __m) != 0. */ virtual bool do_is(mask __m, char_type __c) const = 0; /** * @brief Return a mask array. * * This function finds the mask for each char_type in the range [lo,hi) * and successively writes it to vec. vec must have as many elements * as the input. * * do_is() is a hook for a derived facet to change the behavior of * classifying. do_is() must always return the same result for the * same input. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __vec Pointer to an array of mask storage. * @return @a __hi. */ virtual const char_type* do_is(const char_type* __lo, const char_type* __hi, mask* __vec) const = 0; /** * @brief Find char_type matching mask * * This function searches for and returns the first char_type c in * [__lo,__hi) for which is(__m,c) is true. * * do_scan_is() is a hook for a derived facet to change the behavior of * match searching. do_is() must always return the same result for the * same input. * * @param __m The mask to compare against. * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return Pointer to a matching char_type if found, else @a __hi. */ virtual const char_type* do_scan_is(mask __m, const char_type* __lo, const char_type* __hi) const = 0; /** * @brief Find char_type not matching mask * * This function searches for and returns a pointer to the first * char_type c of [lo,hi) for which is(m,c) is false. * * do_scan_is() is a hook for a derived facet to change the behavior of * match searching. do_is() must always return the same result for the * same input. * * @param __m The mask to compare against. * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return Pointer to a non-matching char_type if found, else @a __hi. */ virtual const char_type* do_scan_not(mask __m, const char_type* __lo, const char_type* __hi) const = 0; /** * @brief Convert to uppercase. * * This virtual function converts the char_type argument to uppercase * if possible. If not possible (for example, '2'), returns the * argument. * * do_toupper() is a hook for a derived facet to change the behavior of * uppercasing. do_toupper() must always return the same result for * the same input. * * @param __c The char_type to convert. * @return The uppercase char_type if convertible, else @a __c. */ virtual char_type do_toupper(char_type __c) const = 0; /** * @brief Convert array to uppercase. * * This virtual function converts each char_type in the range [__lo,__hi) * to uppercase if possible. Other elements remain untouched. * * do_toupper() is a hook for a derived facet to change the behavior of * uppercasing. do_toupper() must always return the same result for * the same input. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return @a __hi. */ virtual const char_type* do_toupper(char_type* __lo, const char_type* __hi) const = 0; /** * @brief Convert to lowercase. * * This virtual function converts the argument to lowercase if * possible. If not possible (for example, '2'), returns the argument. * * do_tolower() is a hook for a derived facet to change the behavior of * lowercasing. do_tolower() must always return the same result for * the same input. * * @param __c The char_type to convert. * @return The lowercase char_type if convertible, else @a __c. */ virtual char_type do_tolower(char_type __c) const = 0; /** * @brief Convert array to lowercase. * * This virtual function converts each char_type in the range [__lo,__hi) * to lowercase if possible. Other elements remain untouched. * * do_tolower() is a hook for a derived facet to change the behavior of * lowercasing. do_tolower() must always return the same result for * the same input. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return @a __hi. */ virtual const char_type* do_tolower(char_type* __lo, const char_type* __hi) const = 0; /** * @brief Widen char * * This virtual function converts the char to char_type using the * simplest reasonable transformation. * * do_widen() is a hook for a derived facet to change the behavior of * widening. do_widen() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char to convert. * @return The converted char_type */ virtual char_type do_widen(char __c) const = 0; /** * @brief Widen char array * * This function converts each char in the input to char_type using the * simplest reasonable transformation. * * do_widen() is a hook for a derived facet to change the behavior of * widening. do_widen() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start range. * @param __hi Pointer to end of range. * @param __to Pointer to the destination array. * @return @a __hi. */ virtual const char* do_widen(const char* __lo, const char* __hi, char_type* __to) const = 0; /** * @brief Narrow char_type to char * * This virtual function converts the argument to char using the * simplest reasonable transformation. If the conversion fails, dfault * is returned instead. * * do_narrow() is a hook for a derived facet to change the behavior of * narrowing. do_narrow() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char_type to convert. * @param __dfault Char to return if conversion fails. * @return The converted char. */ virtual char do_narrow(char_type __c, char __dfault) const = 0; /** * @brief Narrow char_type array to char * * This virtual function converts each char_type in the range * [__lo,__hi) to char using the simplest reasonable * transformation and writes the results to the destination * array. For any element in the input that cannot be * converted, @a __dfault is used instead. * * do_narrow() is a hook for a derived facet to change the behavior of * narrowing. do_narrow() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __dfault Char to use if conversion fails. * @param __to Pointer to the destination array. * @return @a __hi. */ virtual const char_type* do_narrow(const char_type* __lo, const char_type* __hi, char __dfault, char* __to) const = 0; }; /** * @brief Primary class template ctype facet. * @ingroup locales * * This template class defines classification and conversion functions for * character sets. It wraps cctype functionality. Ctype gets used by * streams for many I/O operations. * * This template provides the protected virtual functions the developer * will have to replace in a derived class or specialization to make a * working facet. The public functions that access them are defined in * __ctype_abstract_base, to allow for implementation flexibility. See * ctype for an example. The functions are documented in * __ctype_abstract_base. * * Note: implementations are provided for all the protected virtual * functions, but will likely not be useful. */ template class ctype : public __ctype_abstract_base<_CharT> { public: // Types: typedef _CharT char_type; typedef typename __ctype_abstract_base<_CharT>::mask mask; /// The facet id for ctype static locale::id id; explicit ctype(size_t __refs = 0) : __ctype_abstract_base<_CharT>(__refs) { } protected: virtual ~ctype(); virtual bool do_is(mask __m, char_type __c) const; virtual const char_type* do_is(const char_type* __lo, const char_type* __hi, mask* __vec) const; virtual const char_type* do_scan_is(mask __m, const char_type* __lo, const char_type* __hi) const; virtual const char_type* do_scan_not(mask __m, const char_type* __lo, const char_type* __hi) const; virtual char_type do_toupper(char_type __c) const; virtual const char_type* do_toupper(char_type* __lo, const char_type* __hi) const; virtual char_type do_tolower(char_type __c) const; virtual const char_type* do_tolower(char_type* __lo, const char_type* __hi) const; virtual char_type do_widen(char __c) const; virtual const char* do_widen(const char* __lo, const char* __hi, char_type* __dest) const; virtual char do_narrow(char_type, char __dfault) const; virtual const char_type* do_narrow(const char_type* __lo, const char_type* __hi, char __dfault, char* __to) const; }; template locale::id ctype<_CharT>::id; /** * @brief The ctype specialization. * @ingroup locales * * This class defines classification and conversion functions for * the char type. It gets used by char streams for many I/O * operations. The char specialization provides a number of * optimizations as well. */ template<> class ctype : public locale::facet, public ctype_base { public: // Types: /// Typedef for the template parameter char. typedef char char_type; protected: // Data Members: __c_locale _M_c_locale_ctype; bool _M_del; __to_type _M_toupper; __to_type _M_tolower; const mask* _M_table; mutable char _M_widen_ok; mutable char _M_widen[1 + static_cast(-1)]; mutable char _M_narrow[1 + static_cast(-1)]; mutable char _M_narrow_ok; // 0 uninitialized, 1 init, // 2 memcpy can't be used public: /// The facet id for ctype static locale::id id; /// The size of the mask table. It is SCHAR_MAX + 1. static const size_t table_size = 1 + static_cast(-1); /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __table If non-zero, table is used as the per-char mask. * Else classic_table() is used. * @param __del If true, passes ownership of table to this facet. * @param __refs Passed to the base facet class. */ explicit ctype(const mask* __table = 0, bool __del = false, size_t __refs = 0); /** * @brief Constructor performs static initialization. * * This constructor is used to construct the initial C locale facet. * * @param __cloc Handle to C locale data. * @param __table If non-zero, table is used as the per-char mask. * @param __del If true, passes ownership of table to this facet. * @param __refs Passed to the base facet class. */ explicit ctype(__c_locale __cloc, const mask* __table = 0, bool __del = false, size_t __refs = 0); /** * @brief Test char classification. * * This function compares the mask table[c] to @a __m. * * @param __c The char to compare the mask of. * @param __m The mask to compare against. * @return True if __m & table[__c] is true, false otherwise. */ inline bool is(mask __m, char __c) const; /** * @brief Return a mask array. * * This function finds the mask for each char in the range [lo, hi) and * successively writes it to vec. vec must have as many elements as * the char array. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __vec Pointer to an array of mask storage. * @return @a __hi. */ inline const char* is(const char* __lo, const char* __hi, mask* __vec) const; /** * @brief Find char matching a mask * * This function searches for and returns the first char in [lo,hi) for * which is(m,char) is true. * * @param __m The mask to compare against. * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return Pointer to a matching char if found, else @a __hi. */ inline const char* scan_is(mask __m, const char* __lo, const char* __hi) const; /** * @brief Find char not matching a mask * * This function searches for and returns a pointer to the first char * in [__lo,__hi) for which is(m,char) is false. * * @param __m The mask to compare against. * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return Pointer to a non-matching char if found, else @a __hi. */ inline const char* scan_not(mask __m, const char* __lo, const char* __hi) const; /** * @brief Convert to uppercase. * * This function converts the char argument to uppercase if possible. * If not possible (for example, '2'), returns the argument. * * toupper() acts as if it returns ctype::do_toupper(c). * do_toupper() must always return the same result for the same input. * * @param __c The char to convert. * @return The uppercase char if convertible, else @a __c. */ char_type toupper(char_type __c) const { return this->do_toupper(__c); } /** * @brief Convert array to uppercase. * * This function converts each char in the range [__lo,__hi) to uppercase * if possible. Other chars remain untouched. * * toupper() acts as if it returns ctype:: do_toupper(__lo, __hi). * do_toupper() must always return the same result for the same input. * * @param __lo Pointer to first char in range. * @param __hi Pointer to end of range. * @return @a __hi. */ const char_type* toupper(char_type *__lo, const char_type* __hi) const { return this->do_toupper(__lo, __hi); } /** * @brief Convert to lowercase. * * This function converts the char argument to lowercase if possible. * If not possible (for example, '2'), returns the argument. * * tolower() acts as if it returns ctype::do_tolower(__c). * do_tolower() must always return the same result for the same input. * * @param __c The char to convert. * @return The lowercase char if convertible, else @a __c. */ char_type tolower(char_type __c) const { return this->do_tolower(__c); } /** * @brief Convert array to lowercase. * * This function converts each char in the range [lo,hi) to lowercase * if possible. Other chars remain untouched. * * tolower() acts as if it returns ctype:: do_tolower(__lo, __hi). * do_tolower() must always return the same result for the same input. * * @param __lo Pointer to first char in range. * @param __hi Pointer to end of range. * @return @a __hi. */ const char_type* tolower(char_type* __lo, const char_type* __hi) const { return this->do_tolower(__lo, __hi); } /** * @brief Widen char * * This function converts the char to char_type using the simplest * reasonable transformation. For an underived ctype facet, the * argument will be returned unchanged. * * This function works as if it returns ctype::do_widen(c). * do_widen() must always return the same result for the same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char to convert. * @return The converted character. */ char_type widen(char __c) const { if (_M_widen_ok) return _M_widen[static_cast(__c)]; this->_M_widen_init(); return this->do_widen(__c); } /** * @brief Widen char array * * This function converts each char in the input to char using the * simplest reasonable transformation. For an underived ctype * facet, the argument will be copied unchanged. * * This function works as if it returns ctype::do_widen(c). * do_widen() must always return the same result for the same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to first char in range. * @param __hi Pointer to end of range. * @param __to Pointer to the destination array. * @return @a __hi. */ const char* widen(const char* __lo, const char* __hi, char_type* __to) const { if (_M_widen_ok == 1) { if (__builtin_expect(__hi != __lo, true)) __builtin_memcpy(__to, __lo, __hi - __lo); return __hi; } if (!_M_widen_ok) _M_widen_init(); return this->do_widen(__lo, __hi, __to); } /** * @brief Narrow char * * This function converts the char to char using the simplest * reasonable transformation. If the conversion fails, dfault is * returned instead. For an underived ctype facet, @a c * will be returned unchanged. * * This function works as if it returns ctype::do_narrow(c). * do_narrow() must always return the same result for the same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char to convert. * @param __dfault Char to return if conversion fails. * @return The converted character. */ char narrow(char_type __c, char __dfault) const { if (_M_narrow[static_cast(__c)]) return _M_narrow[static_cast(__c)]; const char __t = do_narrow(__c, __dfault); if (__t != __dfault) _M_narrow[static_cast(__c)] = __t; return __t; } /** * @brief Narrow char array * * This function converts each char in the input to char using the * simplest reasonable transformation and writes the results to the * destination array. For any char in the input that cannot be * converted, @a dfault is used instead. For an underived ctype * facet, the argument will be copied unchanged. * * This function works as if it returns ctype::do_narrow(lo, hi, * dfault, to). do_narrow() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __dfault Char to use if conversion fails. * @param __to Pointer to the destination array. * @return @a __hi. */ const char_type* narrow(const char_type* __lo, const char_type* __hi, char __dfault, char* __to) const { if (__builtin_expect(_M_narrow_ok == 1, true)) { if (__builtin_expect(__hi != __lo, true)) __builtin_memcpy(__to, __lo, __hi - __lo); return __hi; } if (!_M_narrow_ok) _M_narrow_init(); return this->do_narrow(__lo, __hi, __dfault, __to); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 695. ctype::classic_table() not accessible. /// Returns a pointer to the mask table provided to the constructor, or /// the default from classic_table() if none was provided. const mask* table() const throw() { return _M_table; } /// Returns a pointer to the C locale mask table. static const mask* classic_table() throw(); protected: /** * @brief Destructor. * * This function deletes table() if @a del was true in the * constructor. */ virtual ~ctype(); /** * @brief Convert to uppercase. * * This virtual function converts the char argument to uppercase if * possible. If not possible (for example, '2'), returns the argument. * * do_toupper() is a hook for a derived facet to change the behavior of * uppercasing. do_toupper() must always return the same result for * the same input. * * @param __c The char to convert. * @return The uppercase char if convertible, else @a __c. */ virtual char_type do_toupper(char_type __c) const; /** * @brief Convert array to uppercase. * * This virtual function converts each char in the range [lo,hi) to * uppercase if possible. Other chars remain untouched. * * do_toupper() is a hook for a derived facet to change the behavior of * uppercasing. do_toupper() must always return the same result for * the same input. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return @a __hi. */ virtual const char_type* do_toupper(char_type* __lo, const char_type* __hi) const; /** * @brief Convert to lowercase. * * This virtual function converts the char argument to lowercase if * possible. If not possible (for example, '2'), returns the argument. * * do_tolower() is a hook for a derived facet to change the behavior of * lowercasing. do_tolower() must always return the same result for * the same input. * * @param __c The char to convert. * @return The lowercase char if convertible, else @a __c. */ virtual char_type do_tolower(char_type __c) const; /** * @brief Convert array to lowercase. * * This virtual function converts each char in the range [lo,hi) to * lowercase if possible. Other chars remain untouched. * * do_tolower() is a hook for a derived facet to change the behavior of * lowercasing. do_tolower() must always return the same result for * the same input. * * @param __lo Pointer to first char in range. * @param __hi Pointer to end of range. * @return @a __hi. */ virtual const char_type* do_tolower(char_type* __lo, const char_type* __hi) const; /** * @brief Widen char * * This virtual function converts the char to char using the simplest * reasonable transformation. For an underived ctype facet, the * argument will be returned unchanged. * * do_widen() is a hook for a derived facet to change the behavior of * widening. do_widen() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char to convert. * @return The converted character. */ virtual char_type do_widen(char __c) const { return __c; } /** * @brief Widen char array * * This function converts each char in the range [lo,hi) to char using * the simplest reasonable transformation. For an underived * ctype facet, the argument will be copied unchanged. * * do_widen() is a hook for a derived facet to change the behavior of * widening. do_widen() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __to Pointer to the destination array. * @return @a __hi. */ virtual const char* do_widen(const char* __lo, const char* __hi, char_type* __to) const { if (__builtin_expect(__hi != __lo, true)) __builtin_memcpy(__to, __lo, __hi - __lo); return __hi; } /** * @brief Narrow char * * This virtual function converts the char to char using the simplest * reasonable transformation. If the conversion fails, dfault is * returned instead. For an underived ctype facet, @a c will be * returned unchanged. * * do_narrow() is a hook for a derived facet to change the behavior of * narrowing. do_narrow() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char to convert. * @param __dfault Char to return if conversion fails. * @return The converted char. */ virtual char do_narrow(char_type __c, char __dfault __attribute__((__unused__))) const { return __c; } /** * @brief Narrow char array to char array * * This virtual function converts each char in the range [lo,hi) to * char using the simplest reasonable transformation and writes the * results to the destination array. For any char in the input that * cannot be converted, @a dfault is used instead. For an underived * ctype facet, the argument will be copied unchanged. * * do_narrow() is a hook for a derived facet to change the behavior of * narrowing. do_narrow() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __dfault Char to use if conversion fails. * @param __to Pointer to the destination array. * @return @a __hi. */ virtual const char_type* do_narrow(const char_type* __lo, const char_type* __hi, char __dfault __attribute__((__unused__)), char* __to) const { if (__builtin_expect(__hi != __lo, true)) __builtin_memcpy(__to, __lo, __hi - __lo); return __hi; } private: void _M_narrow_init() const; void _M_widen_init() const; }; #ifdef _GLIBCXX_USE_WCHAR_T /** * @brief The ctype specialization. * @ingroup locales * * This class defines classification and conversion functions for the * wchar_t type. It gets used by wchar_t streams for many I/O operations. * The wchar_t specialization provides a number of optimizations as well. * * ctype inherits its public methods from * __ctype_abstract_base. */ template<> class ctype : public __ctype_abstract_base { public: // Types: /// Typedef for the template parameter wchar_t. typedef wchar_t char_type; typedef wctype_t __wmask_type; protected: __c_locale _M_c_locale_ctype; // Pre-computed narrowed and widened chars. bool _M_narrow_ok; char _M_narrow[128]; wint_t _M_widen[1 + static_cast(-1)]; // Pre-computed elements for do_is. mask _M_bit[16]; __wmask_type _M_wmask[16]; public: // Data Members: /// The facet id for ctype static locale::id id; /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __refs Passed to the base facet class. */ explicit ctype(size_t __refs = 0); /** * @brief Constructor performs static initialization. * * This constructor is used to construct the initial C locale facet. * * @param __cloc Handle to C locale data. * @param __refs Passed to the base facet class. */ explicit ctype(__c_locale __cloc, size_t __refs = 0); protected: __wmask_type _M_convert_to_wmask(const mask __m) const throw(); /// Destructor virtual ~ctype(); /** * @brief Test wchar_t classification. * * This function finds a mask M for @a c and compares it to mask @a m. * * do_is() is a hook for a derived facet to change the behavior of * classifying. do_is() must always return the same result for the * same input. * * @param __c The wchar_t to find the mask of. * @param __m The mask to compare against. * @return (M & __m) != 0. */ virtual bool do_is(mask __m, char_type __c) const; /** * @brief Return a mask array. * * This function finds the mask for each wchar_t in the range [lo,hi) * and successively writes it to vec. vec must have as many elements * as the input. * * do_is() is a hook for a derived facet to change the behavior of * classifying. do_is() must always return the same result for the * same input. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __vec Pointer to an array of mask storage. * @return @a __hi. */ virtual const char_type* do_is(const char_type* __lo, const char_type* __hi, mask* __vec) const; /** * @brief Find wchar_t matching mask * * This function searches for and returns the first wchar_t c in * [__lo,__hi) for which is(__m,c) is true. * * do_scan_is() is a hook for a derived facet to change the behavior of * match searching. do_is() must always return the same result for the * same input. * * @param __m The mask to compare against. * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return Pointer to a matching wchar_t if found, else @a __hi. */ virtual const char_type* do_scan_is(mask __m, const char_type* __lo, const char_type* __hi) const; /** * @brief Find wchar_t not matching mask * * This function searches for and returns a pointer to the first * wchar_t c of [__lo,__hi) for which is(__m,c) is false. * * do_scan_is() is a hook for a derived facet to change the behavior of * match searching. do_is() must always return the same result for the * same input. * * @param __m The mask to compare against. * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return Pointer to a non-matching wchar_t if found, else @a __hi. */ virtual const char_type* do_scan_not(mask __m, const char_type* __lo, const char_type* __hi) const; /** * @brief Convert to uppercase. * * This virtual function converts the wchar_t argument to uppercase if * possible. If not possible (for example, '2'), returns the argument. * * do_toupper() is a hook for a derived facet to change the behavior of * uppercasing. do_toupper() must always return the same result for * the same input. * * @param __c The wchar_t to convert. * @return The uppercase wchar_t if convertible, else @a __c. */ virtual char_type do_toupper(char_type __c) const; /** * @brief Convert array to uppercase. * * This virtual function converts each wchar_t in the range [lo,hi) to * uppercase if possible. Other elements remain untouched. * * do_toupper() is a hook for a derived facet to change the behavior of * uppercasing. do_toupper() must always return the same result for * the same input. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return @a __hi. */ virtual const char_type* do_toupper(char_type* __lo, const char_type* __hi) const; /** * @brief Convert to lowercase. * * This virtual function converts the argument to lowercase if * possible. If not possible (for example, '2'), returns the argument. * * do_tolower() is a hook for a derived facet to change the behavior of * lowercasing. do_tolower() must always return the same result for * the same input. * * @param __c The wchar_t to convert. * @return The lowercase wchar_t if convertible, else @a __c. */ virtual char_type do_tolower(char_type __c) const; /** * @brief Convert array to lowercase. * * This virtual function converts each wchar_t in the range [lo,hi) to * lowercase if possible. Other elements remain untouched. * * do_tolower() is a hook for a derived facet to change the behavior of * lowercasing. do_tolower() must always return the same result for * the same input. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return @a __hi. */ virtual const char_type* do_tolower(char_type* __lo, const char_type* __hi) const; /** * @brief Widen char to wchar_t * * This virtual function converts the char to wchar_t using the * simplest reasonable transformation. For an underived ctype * facet, the argument will be cast to wchar_t. * * do_widen() is a hook for a derived facet to change the behavior of * widening. do_widen() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char to convert. * @return The converted wchar_t. */ virtual char_type do_widen(char __c) const; /** * @brief Widen char array to wchar_t array * * This function converts each char in the input to wchar_t using the * simplest reasonable transformation. For an underived ctype * facet, the argument will be copied, casting each element to wchar_t. * * do_widen() is a hook for a derived facet to change the behavior of * widening. do_widen() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start range. * @param __hi Pointer to end of range. * @param __to Pointer to the destination array. * @return @a __hi. */ virtual const char* do_widen(const char* __lo, const char* __hi, char_type* __to) const; /** * @brief Narrow wchar_t to char * * This virtual function converts the argument to char using * the simplest reasonable transformation. If the conversion * fails, dfault is returned instead. For an underived * ctype facet, @a c will be cast to char and * returned. * * do_narrow() is a hook for a derived facet to change the * behavior of narrowing. do_narrow() must always return the * same result for the same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The wchar_t to convert. * @param __dfault Char to return if conversion fails. * @return The converted char. */ virtual char do_narrow(char_type __c, char __dfault) const; /** * @brief Narrow wchar_t array to char array * * This virtual function converts each wchar_t in the range [lo,hi) to * char using the simplest reasonable transformation and writes the * results to the destination array. For any wchar_t in the input that * cannot be converted, @a dfault is used instead. For an underived * ctype facet, the argument will be copied, casting each * element to char. * * do_narrow() is a hook for a derived facet to change the behavior of * narrowing. do_narrow() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __dfault Char to use if conversion fails. * @param __to Pointer to the destination array. * @return @a __hi. */ virtual const char_type* do_narrow(const char_type* __lo, const char_type* __hi, char __dfault, char* __to) const; // For use at construction time only. void _M_initialize_ctype() throw(); }; #endif //_GLIBCXX_USE_WCHAR_T /// class ctype_byname [22.2.1.2]. template class ctype_byname : public ctype<_CharT> { public: typedef typename ctype<_CharT>::mask mask; explicit ctype_byname(const char* __s, size_t __refs = 0); #if __cplusplus >= 201103L explicit ctype_byname(const string& __s, size_t __refs = 0) : ctype_byname(__s.c_str(), __refs) { } #endif protected: virtual ~ctype_byname() { } }; /// 22.2.1.4 Class ctype_byname specializations. template<> class ctype_byname : public ctype { public: explicit ctype_byname(const char* __s, size_t __refs = 0); #if __cplusplus >= 201103L explicit ctype_byname(const string& __s, size_t __refs = 0); #endif protected: virtual ~ctype_byname(); }; #ifdef _GLIBCXX_USE_WCHAR_T template<> class ctype_byname : public ctype { public: explicit ctype_byname(const char* __s, size_t __refs = 0); #if __cplusplus >= 201103L explicit ctype_byname(const string& __s, size_t __refs = 0); #endif protected: virtual ~ctype_byname(); }; #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace // Include host and configuration specific ctype inlines. #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // 22.2.2 The numeric category. class __num_base { public: // NB: Code depends on the order of _S_atoms_out elements. // Below are the indices into _S_atoms_out. enum { _S_ominus, _S_oplus, _S_ox, _S_oX, _S_odigits, _S_odigits_end = _S_odigits + 16, _S_oudigits = _S_odigits_end, _S_oudigits_end = _S_oudigits + 16, _S_oe = _S_odigits + 14, // For scientific notation, 'e' _S_oE = _S_oudigits + 14, // For scientific notation, 'E' _S_oend = _S_oudigits_end }; // A list of valid numeric literals for output. This array // contains chars that will be passed through the current locale's // ctype<_CharT>.widen() and then used to render numbers. // For the standard "C" locale, this is // "-+xX0123456789abcdef0123456789ABCDEF". static const char* _S_atoms_out; // String literal of acceptable (narrow) input, for num_get. // "-+xX0123456789abcdefABCDEF" static const char* _S_atoms_in; enum { _S_iminus, _S_iplus, _S_ix, _S_iX, _S_izero, _S_ie = _S_izero + 14, _S_iE = _S_izero + 20, _S_iend = 26 }; // num_put // Construct and return valid scanf format for floating point types. static void _S_format_float(const ios_base& __io, char* __fptr, char __mod) throw(); }; template struct __numpunct_cache : public locale::facet { const char* _M_grouping; size_t _M_grouping_size; bool _M_use_grouping; const _CharT* _M_truename; size_t _M_truename_size; const _CharT* _M_falsename; size_t _M_falsename_size; _CharT _M_decimal_point; _CharT _M_thousands_sep; // A list of valid numeric literals for output: in the standard // "C" locale, this is "-+xX0123456789abcdef0123456789ABCDEF". // This array contains the chars after having been passed // through the current locale's ctype<_CharT>.widen(). _CharT _M_atoms_out[__num_base::_S_oend]; // A list of valid numeric literals for input: in the standard // "C" locale, this is "-+xX0123456789abcdefABCDEF" // This array contains the chars after having been passed // through the current locale's ctype<_CharT>.widen(). _CharT _M_atoms_in[__num_base::_S_iend]; bool _M_allocated; __numpunct_cache(size_t __refs = 0) : facet(__refs), _M_grouping(0), _M_grouping_size(0), _M_use_grouping(false), _M_truename(0), _M_truename_size(0), _M_falsename(0), _M_falsename_size(0), _M_decimal_point(_CharT()), _M_thousands_sep(_CharT()), _M_allocated(false) { } ~__numpunct_cache(); void _M_cache(const locale& __loc); private: __numpunct_cache& operator=(const __numpunct_cache&); explicit __numpunct_cache(const __numpunct_cache&); }; template __numpunct_cache<_CharT>::~__numpunct_cache() { if (_M_allocated) { delete [] _M_grouping; delete [] _M_truename; delete [] _M_falsename; } } _GLIBCXX_BEGIN_NAMESPACE_CXX11 /** * @brief Primary class template numpunct. * @ingroup locales * * This facet stores several pieces of information related to printing and * scanning numbers, such as the decimal point character. It takes a * template parameter specifying the char type. The numpunct facet is * used by streams for many I/O operations involving numbers. * * The numpunct template uses protected virtual functions to provide the * actual results. The public accessors forward the call to the virtual * functions. These virtual functions are hooks for developers to * implement the behavior they require from a numpunct facet. */ template class numpunct : public locale::facet { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef basic_string<_CharT> string_type; //@} typedef __numpunct_cache<_CharT> __cache_type; protected: __cache_type* _M_data; public: /// Numpunct facet id. static locale::id id; /** * @brief Numpunct constructor. * * @param __refs Refcount to pass to the base class. */ explicit numpunct(size_t __refs = 0) : facet(__refs), _M_data(0) { _M_initialize_numpunct(); } /** * @brief Internal constructor. Not for general use. * * This is a constructor for use by the library itself to set up the * predefined locale facets. * * @param __cache __numpunct_cache object. * @param __refs Refcount to pass to the base class. */ explicit numpunct(__cache_type* __cache, size_t __refs = 0) : facet(__refs), _M_data(__cache) { _M_initialize_numpunct(); } /** * @brief Internal constructor. Not for general use. * * This is a constructor for use by the library itself to set up new * locales. * * @param __cloc The C locale. * @param __refs Refcount to pass to the base class. */ explicit numpunct(__c_locale __cloc, size_t __refs = 0) : facet(__refs), _M_data(0) { _M_initialize_numpunct(__cloc); } /** * @brief Return decimal point character. * * This function returns a char_type to use as a decimal point. It * does so by returning returning * numpunct::do_decimal_point(). * * @return @a char_type representing a decimal point. */ char_type decimal_point() const { return this->do_decimal_point(); } /** * @brief Return thousands separator character. * * This function returns a char_type to use as a thousands * separator. It does so by returning returning * numpunct::do_thousands_sep(). * * @return char_type representing a thousands separator. */ char_type thousands_sep() const { return this->do_thousands_sep(); } /** * @brief Return grouping specification. * * This function returns a string representing groupings for the * integer part of a number. Groupings indicate where thousands * separators should be inserted in the integer part of a number. * * Each char in the return string is interpret as an integer * rather than a character. These numbers represent the number * of digits in a group. The first char in the string * represents the number of digits in the least significant * group. If a char is negative, it indicates an unlimited * number of digits for the group. If more chars from the * string are required to group a number, the last char is used * repeatedly. * * For example, if the grouping() returns "\003\002" and is * applied to the number 123456789, this corresponds to * 12,34,56,789. Note that if the string was "32", this would * put more than 50 digits into the least significant group if * the character set is ASCII. * * The string is returned by calling * numpunct::do_grouping(). * * @return string representing grouping specification. */ string grouping() const { return this->do_grouping(); } /** * @brief Return string representation of bool true. * * This function returns a string_type containing the text * representation for true bool variables. It does so by calling * numpunct::do_truename(). * * @return string_type representing printed form of true. */ string_type truename() const { return this->do_truename(); } /** * @brief Return string representation of bool false. * * This function returns a string_type containing the text * representation for false bool variables. It does so by calling * numpunct::do_falsename(). * * @return string_type representing printed form of false. */ string_type falsename() const { return this->do_falsename(); } protected: /// Destructor. virtual ~numpunct(); /** * @brief Return decimal point character. * * Returns a char_type to use as a decimal point. This function is a * hook for derived classes to change the value returned. * * @return @a char_type representing a decimal point. */ virtual char_type do_decimal_point() const { return _M_data->_M_decimal_point; } /** * @brief Return thousands separator character. * * Returns a char_type to use as a thousands separator. This function * is a hook for derived classes to change the value returned. * * @return @a char_type representing a thousands separator. */ virtual char_type do_thousands_sep() const { return _M_data->_M_thousands_sep; } /** * @brief Return grouping specification. * * Returns a string representing groupings for the integer part of a * number. This function is a hook for derived classes to change the * value returned. @see grouping() for details. * * @return String representing grouping specification. */ virtual string do_grouping() const { return _M_data->_M_grouping; } /** * @brief Return string representation of bool true. * * Returns a string_type containing the text representation for true * bool variables. This function is a hook for derived classes to * change the value returned. * * @return string_type representing printed form of true. */ virtual string_type do_truename() const { return _M_data->_M_truename; } /** * @brief Return string representation of bool false. * * Returns a string_type containing the text representation for false * bool variables. This function is a hook for derived classes to * change the value returned. * * @return string_type representing printed form of false. */ virtual string_type do_falsename() const { return _M_data->_M_falsename; } // For use at construction time only. void _M_initialize_numpunct(__c_locale __cloc = 0); }; template locale::id numpunct<_CharT>::id; template<> numpunct::~numpunct(); template<> void numpunct::_M_initialize_numpunct(__c_locale __cloc); #ifdef _GLIBCXX_USE_WCHAR_T template<> numpunct::~numpunct(); template<> void numpunct::_M_initialize_numpunct(__c_locale __cloc); #endif /// class numpunct_byname [22.2.3.2]. template class numpunct_byname : public numpunct<_CharT> { public: typedef _CharT char_type; typedef basic_string<_CharT> string_type; explicit numpunct_byname(const char* __s, size_t __refs = 0) : numpunct<_CharT>(__refs) { if (__builtin_strcmp(__s, "C") != 0 && __builtin_strcmp(__s, "POSIX") != 0) { __c_locale __tmp; this->_S_create_c_locale(__tmp, __s); this->_M_initialize_numpunct(__tmp); this->_S_destroy_c_locale(__tmp); } } #if __cplusplus >= 201103L explicit numpunct_byname(const string& __s, size_t __refs = 0) : numpunct_byname(__s.c_str(), __refs) { } #endif protected: virtual ~numpunct_byname() { } }; _GLIBCXX_END_NAMESPACE_CXX11 _GLIBCXX_BEGIN_NAMESPACE_LDBL /** * @brief Primary class template num_get. * @ingroup locales * * This facet encapsulates the code to parse and return a number * from a string. It is used by the istream numeric extraction * operators. * * The num_get template uses protected virtual functions to provide the * actual results. The public accessors forward the call to the virtual * functions. These virtual functions are hooks for developers to * implement the behavior they require from the num_get facet. */ template class num_get : public locale::facet { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef _InIter iter_type; //@} /// Numpunct facet id. static locale::id id; /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __refs Passed to the base facet class. */ explicit num_get(size_t __refs = 0) : facet(__refs) { } /** * @brief Numeric parsing. * * Parses the input stream into the bool @a v. It does so by calling * num_get::do_get(). * * If ios_base::boolalpha is set, attempts to read * ctype::truename() or ctype::falsename(). Sets * @a v to true or false if successful. Sets err to * ios_base::failbit if reading the string fails. Sets err to * ios_base::eofbit if the stream is emptied. * * If ios_base::boolalpha is not set, proceeds as with reading a long, * except if the value is 1, sets @a v to true, if the value is 0, sets * @a v to false, and otherwise set err to ios_base::failbit. * * @param __in Start of input stream. * @param __end End of input stream. * @param __io Source of locale and flags. * @param __err Error flags to set. * @param __v Value to format and insert. * @return Iterator after reading. */ iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, bool& __v) const { return this->do_get(__in, __end, __io, __err, __v); } //@{ /** * @brief Numeric parsing. * * Parses the input stream into the integral variable @a v. It does so * by calling num_get::do_get(). * * Parsing is affected by the flag settings in @a io. * * The basic parse is affected by the value of io.flags() & * ios_base::basefield. If equal to ios_base::oct, parses like the * scanf %o specifier. Else if equal to ios_base::hex, parses like %X * specifier. Else if basefield equal to 0, parses like the %i * specifier. Otherwise, parses like %d for signed and %u for unsigned * types. The matching type length modifier is also used. * * Digit grouping is interpreted according to * numpunct::grouping() and numpunct::thousands_sep(). If the * pattern of digit groups isn't consistent, sets err to * ios_base::failbit. * * If parsing the string yields a valid value for @a v, @a v is set. * Otherwise, sets err to ios_base::failbit and leaves @a v unaltered. * Sets err to ios_base::eofbit if the stream is emptied. * * @param __in Start of input stream. * @param __end End of input stream. * @param __io Source of locale and flags. * @param __err Error flags to set. * @param __v Value to format and insert. * @return Iterator after reading. */ iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, long& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned short& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned int& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned long& __v) const { return this->do_get(__in, __end, __io, __err, __v); } #ifdef _GLIBCXX_USE_LONG_LONG iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, long long& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned long long& __v) const { return this->do_get(__in, __end, __io, __err, __v); } #endif //@} //@{ /** * @brief Numeric parsing. * * Parses the input stream into the integral variable @a v. It does so * by calling num_get::do_get(). * * The input characters are parsed like the scanf %g specifier. The * matching type length modifier is also used. * * The decimal point character used is numpunct::decimal_point(). * Digit grouping is interpreted according to * numpunct::grouping() and numpunct::thousands_sep(). If the * pattern of digit groups isn't consistent, sets err to * ios_base::failbit. * * If parsing the string yields a valid value for @a v, @a v is set. * Otherwise, sets err to ios_base::failbit and leaves @a v unaltered. * Sets err to ios_base::eofbit if the stream is emptied. * * @param __in Start of input stream. * @param __end End of input stream. * @param __io Source of locale and flags. * @param __err Error flags to set. * @param __v Value to format and insert. * @return Iterator after reading. */ iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, float& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, double& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, long double& __v) const { return this->do_get(__in, __end, __io, __err, __v); } //@} /** * @brief Numeric parsing. * * Parses the input stream into the pointer variable @a v. It does so * by calling num_get::do_get(). * * The input characters are parsed like the scanf %p specifier. * * Digit grouping is interpreted according to * numpunct::grouping() and numpunct::thousands_sep(). If the * pattern of digit groups isn't consistent, sets err to * ios_base::failbit. * * Note that the digit grouping effect for pointers is a bit ambiguous * in the standard and shouldn't be relied on. See DR 344. * * If parsing the string yields a valid value for @a v, @a v is set. * Otherwise, sets err to ios_base::failbit and leaves @a v unaltered. * Sets err to ios_base::eofbit if the stream is emptied. * * @param __in Start of input stream. * @param __end End of input stream. * @param __io Source of locale and flags. * @param __err Error flags to set. * @param __v Value to format and insert. * @return Iterator after reading. */ iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, void*& __v) const { return this->do_get(__in, __end, __io, __err, __v); } protected: /// Destructor. virtual ~num_get() { } _GLIBCXX_DEFAULT_ABI_TAG iter_type _M_extract_float(iter_type, iter_type, ios_base&, ios_base::iostate&, string&) const; template _GLIBCXX_DEFAULT_ABI_TAG iter_type _M_extract_int(iter_type, iter_type, ios_base&, ios_base::iostate&, _ValueT&) const; template typename __gnu_cxx::__enable_if<__is_char<_CharT2>::__value, int>::__type _M_find(const _CharT2*, size_t __len, _CharT2 __c) const { int __ret = -1; if (__len <= 10) { if (__c >= _CharT2('0') && __c < _CharT2(_CharT2('0') + __len)) __ret = __c - _CharT2('0'); } else { if (__c >= _CharT2('0') && __c <= _CharT2('9')) __ret = __c - _CharT2('0'); else if (__c >= _CharT2('a') && __c <= _CharT2('f')) __ret = 10 + (__c - _CharT2('a')); else if (__c >= _CharT2('A') && __c <= _CharT2('F')) __ret = 10 + (__c - _CharT2('A')); } return __ret; } template typename __gnu_cxx::__enable_if::__value, int>::__type _M_find(const _CharT2* __zero, size_t __len, _CharT2 __c) const { int __ret = -1; const char_type* __q = char_traits<_CharT2>::find(__zero, __len, __c); if (__q) { __ret = __q - __zero; if (__ret > 15) __ret -= 6; } return __ret; } //@{ /** * @brief Numeric parsing. * * Parses the input stream into the variable @a v. This function is a * hook for derived classes to change the value returned. @see get() * for more details. * * @param __beg Start of input stream. * @param __end End of input stream. * @param __io Source of locale and flags. * @param __err Error flags to set. * @param __v Value to format and insert. * @return Iterator after reading. */ virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, bool&) const; virtual iter_type do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, long& __v) const { return _M_extract_int(__beg, __end, __io, __err, __v); } virtual iter_type do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned short& __v) const { return _M_extract_int(__beg, __end, __io, __err, __v); } virtual iter_type do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned int& __v) const { return _M_extract_int(__beg, __end, __io, __err, __v); } virtual iter_type do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned long& __v) const { return _M_extract_int(__beg, __end, __io, __err, __v); } #ifdef _GLIBCXX_USE_LONG_LONG virtual iter_type do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, long long& __v) const { return _M_extract_int(__beg, __end, __io, __err, __v); } virtual iter_type do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned long long& __v) const { return _M_extract_int(__beg, __end, __io, __err, __v); } #endif virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, float&) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, double&) const; // XXX GLIBCXX_ABI Deprecated #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ virtual iter_type __do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, double&) const; #else virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, long double&) const; #endif virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, void*&) const; // XXX GLIBCXX_ABI Deprecated #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, long double&) const; #endif //@} }; template locale::id num_get<_CharT, _InIter>::id; /** * @brief Primary class template num_put. * @ingroup locales * * This facet encapsulates the code to convert a number to a string. It is * used by the ostream numeric insertion operators. * * The num_put template uses protected virtual functions to provide the * actual results. The public accessors forward the call to the virtual * functions. These virtual functions are hooks for developers to * implement the behavior they require from the num_put facet. */ template class num_put : public locale::facet { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef _OutIter iter_type; //@} /// Numpunct facet id. static locale::id id; /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __refs Passed to the base facet class. */ explicit num_put(size_t __refs = 0) : facet(__refs) { } /** * @brief Numeric formatting. * * Formats the boolean @a v and inserts it into a stream. It does so * by calling num_put::do_put(). * * If ios_base::boolalpha is set, writes ctype::truename() or * ctype::falsename(). Otherwise formats @a v as an int. * * @param __s Stream to write to. * @param __io Source of locale and flags. * @param __fill Char_type to use for filling. * @param __v Value to format and insert. * @return Iterator after writing. */ iter_type put(iter_type __s, ios_base& __io, char_type __fill, bool __v) const { return this->do_put(__s, __io, __fill, __v); } //@{ /** * @brief Numeric formatting. * * Formats the integral value @a v and inserts it into a * stream. It does so by calling num_put::do_put(). * * Formatting is affected by the flag settings in @a io. * * The basic format is affected by the value of io.flags() & * ios_base::basefield. If equal to ios_base::oct, formats like the * printf %o specifier. Else if equal to ios_base::hex, formats like * %x or %X with ios_base::uppercase unset or set respectively. * Otherwise, formats like %d, %ld, %lld for signed and %u, %lu, %llu * for unsigned values. Note that if both oct and hex are set, neither * will take effect. * * If ios_base::showpos is set, '+' is output before positive values. * If ios_base::showbase is set, '0' precedes octal values (except 0) * and '0[xX]' precedes hex values. * * The decimal point character used is numpunct::decimal_point(). * Thousands separators are inserted according to * numpunct::grouping() and numpunct::thousands_sep(). * * If io.width() is non-zero, enough @a fill characters are inserted to * make the result at least that wide. If * (io.flags() & ios_base::adjustfield) == ios_base::left, result is * padded at the end. If ios_base::internal, then padding occurs * immediately after either a '+' or '-' or after '0x' or '0X'. * Otherwise, padding occurs at the beginning. * * @param __s Stream to write to. * @param __io Source of locale and flags. * @param __fill Char_type to use for filling. * @param __v Value to format and insert. * @return Iterator after writing. */ iter_type put(iter_type __s, ios_base& __io, char_type __fill, long __v) const { return this->do_put(__s, __io, __fill, __v); } iter_type put(iter_type __s, ios_base& __io, char_type __fill, unsigned long __v) const { return this->do_put(__s, __io, __fill, __v); } #ifdef _GLIBCXX_USE_LONG_LONG iter_type put(iter_type __s, ios_base& __io, char_type __fill, long long __v) const { return this->do_put(__s, __io, __fill, __v); } iter_type put(iter_type __s, ios_base& __io, char_type __fill, unsigned long long __v) const { return this->do_put(__s, __io, __fill, __v); } #endif //@} //@{ /** * @brief Numeric formatting. * * Formats the floating point value @a v and inserts it into a stream. * It does so by calling num_put::do_put(). * * Formatting is affected by the flag settings in @a io. * * The basic format is affected by the value of io.flags() & * ios_base::floatfield. If equal to ios_base::fixed, formats like the * printf %f specifier. Else if equal to ios_base::scientific, formats * like %e or %E with ios_base::uppercase unset or set respectively. * Otherwise, formats like %g or %G depending on uppercase. Note that * if both fixed and scientific are set, the effect will also be like * %g or %G. * * The output precision is given by io.precision(). This precision is * capped at numeric_limits::digits10 + 2 (different for double and * long double). The default precision is 6. * * If ios_base::showpos is set, '+' is output before positive values. * If ios_base::showpoint is set, a decimal point will always be * output. * * The decimal point character used is numpunct::decimal_point(). * Thousands separators are inserted according to * numpunct::grouping() and numpunct::thousands_sep(). * * If io.width() is non-zero, enough @a fill characters are inserted to * make the result at least that wide. If * (io.flags() & ios_base::adjustfield) == ios_base::left, result is * padded at the end. If ios_base::internal, then padding occurs * immediately after either a '+' or '-' or after '0x' or '0X'. * Otherwise, padding occurs at the beginning. * * @param __s Stream to write to. * @param __io Source of locale and flags. * @param __fill Char_type to use for filling. * @param __v Value to format and insert. * @return Iterator after writing. */ iter_type put(iter_type __s, ios_base& __io, char_type __fill, double __v) const { return this->do_put(__s, __io, __fill, __v); } iter_type put(iter_type __s, ios_base& __io, char_type __fill, long double __v) const { return this->do_put(__s, __io, __fill, __v); } //@} /** * @brief Numeric formatting. * * Formats the pointer value @a v and inserts it into a stream. It * does so by calling num_put::do_put(). * * This function formats @a v as an unsigned long with ios_base::hex * and ios_base::showbase set. * * @param __s Stream to write to. * @param __io Source of locale and flags. * @param __fill Char_type to use for filling. * @param __v Value to format and insert. * @return Iterator after writing. */ iter_type put(iter_type __s, ios_base& __io, char_type __fill, const void* __v) const { return this->do_put(__s, __io, __fill, __v); } protected: template iter_type _M_insert_float(iter_type, ios_base& __io, char_type __fill, char __mod, _ValueT __v) const; void _M_group_float(const char* __grouping, size_t __grouping_size, char_type __sep, const char_type* __p, char_type* __new, char_type* __cs, int& __len) const; template iter_type _M_insert_int(iter_type, ios_base& __io, char_type __fill, _ValueT __v) const; void _M_group_int(const char* __grouping, size_t __grouping_size, char_type __sep, ios_base& __io, char_type* __new, char_type* __cs, int& __len) const; void _M_pad(char_type __fill, streamsize __w, ios_base& __io, char_type* __new, const char_type* __cs, int& __len) const; /// Destructor. virtual ~num_put() { } //@{ /** * @brief Numeric formatting. * * These functions do the work of formatting numeric values and * inserting them into a stream. This function is a hook for derived * classes to change the value returned. * * @param __s Stream to write to. * @param __io Source of locale and flags. * @param __fill Char_type to use for filling. * @param __v Value to format and insert. * @return Iterator after writing. */ virtual iter_type do_put(iter_type __s, ios_base& __io, char_type __fill, bool __v) const; virtual iter_type do_put(iter_type __s, ios_base& __io, char_type __fill, long __v) const { return _M_insert_int(__s, __io, __fill, __v); } virtual iter_type do_put(iter_type __s, ios_base& __io, char_type __fill, unsigned long __v) const { return _M_insert_int(__s, __io, __fill, __v); } #ifdef _GLIBCXX_USE_LONG_LONG virtual iter_type do_put(iter_type __s, ios_base& __io, char_type __fill, long long __v) const { return _M_insert_int(__s, __io, __fill, __v); } virtual iter_type do_put(iter_type __s, ios_base& __io, char_type __fill, unsigned long long __v) const { return _M_insert_int(__s, __io, __fill, __v); } #endif virtual iter_type do_put(iter_type, ios_base&, char_type, double) const; // XXX GLIBCXX_ABI Deprecated #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ virtual iter_type __do_put(iter_type, ios_base&, char_type, double) const; #else virtual iter_type do_put(iter_type, ios_base&, char_type, long double) const; #endif virtual iter_type do_put(iter_type, ios_base&, char_type, const void*) const; // XXX GLIBCXX_ABI Deprecated #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ virtual iter_type do_put(iter_type, ios_base&, char_type, long double) const; #endif //@} }; template locale::id num_put<_CharT, _OutIter>::id; _GLIBCXX_END_NAMESPACE_LDBL // Subclause convenience interfaces, inlines. // NB: These are inline because, when used in a loop, some compilers // can hoist the body out of the loop; then it's just as fast as the // C is*() function. /// Convenience interface to ctype.is(ctype_base::space, __c). template inline bool isspace(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::space, __c); } /// Convenience interface to ctype.is(ctype_base::print, __c). template inline bool isprint(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::print, __c); } /// Convenience interface to ctype.is(ctype_base::cntrl, __c). template inline bool iscntrl(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::cntrl, __c); } /// Convenience interface to ctype.is(ctype_base::upper, __c). template inline bool isupper(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::upper, __c); } /// Convenience interface to ctype.is(ctype_base::lower, __c). template inline bool islower(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::lower, __c); } /// Convenience interface to ctype.is(ctype_base::alpha, __c). template inline bool isalpha(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::alpha, __c); } /// Convenience interface to ctype.is(ctype_base::digit, __c). template inline bool isdigit(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::digit, __c); } /// Convenience interface to ctype.is(ctype_base::punct, __c). template inline bool ispunct(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::punct, __c); } /// Convenience interface to ctype.is(ctype_base::xdigit, __c). template inline bool isxdigit(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::xdigit, __c); } /// Convenience interface to ctype.is(ctype_base::alnum, __c). template inline bool isalnum(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::alnum, __c); } /// Convenience interface to ctype.is(ctype_base::graph, __c). template inline bool isgraph(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::graph, __c); } #if __cplusplus >= 201103L /// Convenience interface to ctype.is(ctype_base::blank, __c). template inline bool isblank(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::blank, __c); } #endif /// Convenience interface to ctype.toupper(__c). template inline _CharT toupper(_CharT __c, const locale& __loc) { return use_facet >(__loc).toupper(__c); } /// Convenience interface to ctype.tolower(__c). template inline _CharT tolower(_CharT __c, const locale& __loc) { return use_facet >(__loc).tolower(__c); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std # include #endif PK!||8/bits/locale_facets.tccnu[// Locale support -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/locale_facets.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ #ifndef _LOCALE_FACETS_TCC #define _LOCALE_FACETS_TCC 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Routine to access a cache for the facet. If the cache didn't // exist before, it gets constructed on the fly. template struct __use_cache { const _Facet* operator() (const locale& __loc) const; }; // Specializations. template struct __use_cache<__numpunct_cache<_CharT> > { const __numpunct_cache<_CharT>* operator() (const locale& __loc) const { const size_t __i = numpunct<_CharT>::id._M_id(); const locale::facet** __caches = __loc._M_impl->_M_caches; if (!__caches[__i]) { __numpunct_cache<_CharT>* __tmp = 0; __try { __tmp = new __numpunct_cache<_CharT>; __tmp->_M_cache(__loc); } __catch(...) { delete __tmp; __throw_exception_again; } __loc._M_impl->_M_install_cache(__tmp, __i); } return static_cast*>(__caches[__i]); } }; template void __numpunct_cache<_CharT>::_M_cache(const locale& __loc) { const numpunct<_CharT>& __np = use_facet >(__loc); char* __grouping = 0; _CharT* __truename = 0; _CharT* __falsename = 0; __try { const string& __g = __np.grouping(); _M_grouping_size = __g.size(); __grouping = new char[_M_grouping_size]; __g.copy(__grouping, _M_grouping_size); _M_use_grouping = (_M_grouping_size && static_cast(__grouping[0]) > 0 && (__grouping[0] != __gnu_cxx::__numeric_traits::__max)); const basic_string<_CharT>& __tn = __np.truename(); _M_truename_size = __tn.size(); __truename = new _CharT[_M_truename_size]; __tn.copy(__truename, _M_truename_size); const basic_string<_CharT>& __fn = __np.falsename(); _M_falsename_size = __fn.size(); __falsename = new _CharT[_M_falsename_size]; __fn.copy(__falsename, _M_falsename_size); _M_decimal_point = __np.decimal_point(); _M_thousands_sep = __np.thousands_sep(); const ctype<_CharT>& __ct = use_facet >(__loc); __ct.widen(__num_base::_S_atoms_out, __num_base::_S_atoms_out + __num_base::_S_oend, _M_atoms_out); __ct.widen(__num_base::_S_atoms_in, __num_base::_S_atoms_in + __num_base::_S_iend, _M_atoms_in); _M_grouping = __grouping; _M_truename = __truename; _M_falsename = __falsename; _M_allocated = true; } __catch(...) { delete [] __grouping; delete [] __truename; delete [] __falsename; __throw_exception_again; } } // Used by both numeric and monetary facets. // Check to make sure that the __grouping_tmp string constructed in // money_get or num_get matches the canonical grouping for a given // locale. // __grouping_tmp is parsed L to R // 1,222,444 == __grouping_tmp of "\1\3\3" // __grouping is parsed R to L // 1,222,444 == __grouping of "\3" == "\3\3\3" _GLIBCXX_PURE bool __verify_grouping(const char* __grouping, size_t __grouping_size, const string& __grouping_tmp) throw (); _GLIBCXX_BEGIN_NAMESPACE_LDBL template _GLIBCXX_DEFAULT_ABI_TAG _InIter num_get<_CharT, _InIter>:: _M_extract_float(_InIter __beg, _InIter __end, ios_base& __io, ios_base::iostate& __err, string& __xtrc) const { typedef char_traits<_CharT> __traits_type; typedef __numpunct_cache<_CharT> __cache_type; __use_cache<__cache_type> __uc; const locale& __loc = __io._M_getloc(); const __cache_type* __lc = __uc(__loc); const _CharT* __lit = __lc->_M_atoms_in; char_type __c = char_type(); // True if __beg becomes equal to __end. bool __testeof = __beg == __end; // First check for sign. if (!__testeof) { __c = *__beg; const bool __plus = __c == __lit[__num_base::_S_iplus]; if ((__plus || __c == __lit[__num_base::_S_iminus]) && !(__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) && !(__c == __lc->_M_decimal_point)) { __xtrc += __plus ? '+' : '-'; if (++__beg != __end) __c = *__beg; else __testeof = true; } } // Next, look for leading zeros. bool __found_mantissa = false; int __sep_pos = 0; while (!__testeof) { if ((__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) || __c == __lc->_M_decimal_point) break; else if (__c == __lit[__num_base::_S_izero]) { if (!__found_mantissa) { __xtrc += '0'; __found_mantissa = true; } ++__sep_pos; if (++__beg != __end) __c = *__beg; else __testeof = true; } else break; } // Only need acceptable digits for floating point numbers. bool __found_dec = false; bool __found_sci = false; string __found_grouping; if (__lc->_M_use_grouping) __found_grouping.reserve(32); const char_type* __lit_zero = __lit + __num_base::_S_izero; if (!__lc->_M_allocated) // "C" locale while (!__testeof) { const int __digit = _M_find(__lit_zero, 10, __c); if (__digit != -1) { __xtrc += '0' + __digit; __found_mantissa = true; } else if (__c == __lc->_M_decimal_point && !__found_dec && !__found_sci) { __xtrc += '.'; __found_dec = true; } else if ((__c == __lit[__num_base::_S_ie] || __c == __lit[__num_base::_S_iE]) && !__found_sci && __found_mantissa) { // Scientific notation. __xtrc += 'e'; __found_sci = true; // Remove optional plus or minus sign, if they exist. if (++__beg != __end) { __c = *__beg; const bool __plus = __c == __lit[__num_base::_S_iplus]; if (__plus || __c == __lit[__num_base::_S_iminus]) __xtrc += __plus ? '+' : '-'; else continue; } else { __testeof = true; break; } } else break; if (++__beg != __end) __c = *__beg; else __testeof = true; } else while (!__testeof) { // According to 22.2.2.1.2, p8-9, first look for thousands_sep // and decimal_point. if (__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) { if (!__found_dec && !__found_sci) { // NB: Thousands separator at the beginning of a string // is a no-no, as is two consecutive thousands separators. if (__sep_pos) { __found_grouping += static_cast(__sep_pos); __sep_pos = 0; } else { // NB: __convert_to_v will not assign __v and will // set the failbit. __xtrc.clear(); break; } } else break; } else if (__c == __lc->_M_decimal_point) { if (!__found_dec && !__found_sci) { // If no grouping chars are seen, no grouping check // is applied. Therefore __found_grouping is adjusted // only if decimal_point comes after some thousands_sep. if (__found_grouping.size()) __found_grouping += static_cast(__sep_pos); __xtrc += '.'; __found_dec = true; } else break; } else { const char_type* __q = __traits_type::find(__lit_zero, 10, __c); if (__q) { __xtrc += '0' + (__q - __lit_zero); __found_mantissa = true; ++__sep_pos; } else if ((__c == __lit[__num_base::_S_ie] || __c == __lit[__num_base::_S_iE]) && !__found_sci && __found_mantissa) { // Scientific notation. if (__found_grouping.size() && !__found_dec) __found_grouping += static_cast(__sep_pos); __xtrc += 'e'; __found_sci = true; // Remove optional plus or minus sign, if they exist. if (++__beg != __end) { __c = *__beg; const bool __plus = __c == __lit[__num_base::_S_iplus]; if ((__plus || __c == __lit[__num_base::_S_iminus]) && !(__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) && !(__c == __lc->_M_decimal_point)) __xtrc += __plus ? '+' : '-'; else continue; } else { __testeof = true; break; } } else break; } if (++__beg != __end) __c = *__beg; else __testeof = true; } // Digit grouping is checked. If grouping and found_grouping don't // match, then get very very upset, and set failbit. if (__found_grouping.size()) { // Add the ending grouping if a decimal or 'e'/'E' wasn't found. if (!__found_dec && !__found_sci) __found_grouping += static_cast(__sep_pos); if (!std::__verify_grouping(__lc->_M_grouping, __lc->_M_grouping_size, __found_grouping)) __err = ios_base::failbit; } return __beg; } template template _GLIBCXX_DEFAULT_ABI_TAG _InIter num_get<_CharT, _InIter>:: _M_extract_int(_InIter __beg, _InIter __end, ios_base& __io, ios_base::iostate& __err, _ValueT& __v) const { typedef char_traits<_CharT> __traits_type; using __gnu_cxx::__add_unsigned; typedef typename __add_unsigned<_ValueT>::__type __unsigned_type; typedef __numpunct_cache<_CharT> __cache_type; __use_cache<__cache_type> __uc; const locale& __loc = __io._M_getloc(); const __cache_type* __lc = __uc(__loc); const _CharT* __lit = __lc->_M_atoms_in; char_type __c = char_type(); // NB: Iff __basefield == 0, __base can change based on contents. const ios_base::fmtflags __basefield = __io.flags() & ios_base::basefield; const bool __oct = __basefield == ios_base::oct; int __base = __oct ? 8 : (__basefield == ios_base::hex ? 16 : 10); // True if __beg becomes equal to __end. bool __testeof = __beg == __end; // First check for sign. bool __negative = false; if (!__testeof) { __c = *__beg; __negative = __c == __lit[__num_base::_S_iminus]; if ((__negative || __c == __lit[__num_base::_S_iplus]) && !(__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) && !(__c == __lc->_M_decimal_point)) { if (++__beg != __end) __c = *__beg; else __testeof = true; } } // Next, look for leading zeros and check required digits // for base formats. bool __found_zero = false; int __sep_pos = 0; while (!__testeof) { if ((__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) || __c == __lc->_M_decimal_point) break; else if (__c == __lit[__num_base::_S_izero] && (!__found_zero || __base == 10)) { __found_zero = true; ++__sep_pos; if (__basefield == 0) __base = 8; if (__base == 8) __sep_pos = 0; } else if (__found_zero && (__c == __lit[__num_base::_S_ix] || __c == __lit[__num_base::_S_iX])) { if (__basefield == 0) __base = 16; if (__base == 16) { __found_zero = false; __sep_pos = 0; } else break; } else break; if (++__beg != __end) { __c = *__beg; if (!__found_zero) break; } else __testeof = true; } // At this point, base is determined. If not hex, only allow // base digits as valid input. const size_t __len = (__base == 16 ? __num_base::_S_iend - __num_base::_S_izero : __base); // Extract. typedef __gnu_cxx::__numeric_traits<_ValueT> __num_traits; string __found_grouping; if (__lc->_M_use_grouping) __found_grouping.reserve(32); bool __testfail = false; bool __testoverflow = false; const __unsigned_type __max = (__negative && __num_traits::__is_signed) ? -static_cast<__unsigned_type>(__num_traits::__min) : __num_traits::__max; const __unsigned_type __smax = __max / __base; __unsigned_type __result = 0; int __digit = 0; const char_type* __lit_zero = __lit + __num_base::_S_izero; if (!__lc->_M_allocated) // "C" locale while (!__testeof) { __digit = _M_find(__lit_zero, __len, __c); if (__digit == -1) break; if (__result > __smax) __testoverflow = true; else { __result *= __base; __testoverflow |= __result > __max - __digit; __result += __digit; ++__sep_pos; } if (++__beg != __end) __c = *__beg; else __testeof = true; } else while (!__testeof) { // According to 22.2.2.1.2, p8-9, first look for thousands_sep // and decimal_point. if (__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) { // NB: Thousands separator at the beginning of a string // is a no-no, as is two consecutive thousands separators. if (__sep_pos) { __found_grouping += static_cast(__sep_pos); __sep_pos = 0; } else { __testfail = true; break; } } else if (__c == __lc->_M_decimal_point) break; else { const char_type* __q = __traits_type::find(__lit_zero, __len, __c); if (!__q) break; __digit = __q - __lit_zero; if (__digit > 15) __digit -= 6; if (__result > __smax) __testoverflow = true; else { __result *= __base; __testoverflow |= __result > __max - __digit; __result += __digit; ++__sep_pos; } } if (++__beg != __end) __c = *__beg; else __testeof = true; } // Digit grouping is checked. If grouping and found_grouping don't // match, then get very very upset, and set failbit. if (__found_grouping.size()) { // Add the ending grouping. __found_grouping += static_cast(__sep_pos); if (!std::__verify_grouping(__lc->_M_grouping, __lc->_M_grouping_size, __found_grouping)) __err = ios_base::failbit; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 23. Num_get overflow result. if ((!__sep_pos && !__found_zero && !__found_grouping.size()) || __testfail) { __v = 0; __err = ios_base::failbit; } else if (__testoverflow) { if (__negative && __num_traits::__is_signed) __v = __num_traits::__min; else __v = __num_traits::__max; __err = ios_base::failbit; } else __v = __negative ? -__result : __result; if (__testeof) __err |= ios_base::eofbit; return __beg; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 17. Bad bool parsing template _InIter num_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, bool& __v) const { if (!(__io.flags() & ios_base::boolalpha)) { // Parse bool values as long. // NB: We can't just call do_get(long) here, as it might // refer to a derived class. long __l = -1; __beg = _M_extract_int(__beg, __end, __io, __err, __l); if (__l == 0 || __l == 1) __v = bool(__l); else { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 23. Num_get overflow result. __v = true; __err = ios_base::failbit; if (__beg == __end) __err |= ios_base::eofbit; } } else { // Parse bool values as alphanumeric. typedef __numpunct_cache<_CharT> __cache_type; __use_cache<__cache_type> __uc; const locale& __loc = __io._M_getloc(); const __cache_type* __lc = __uc(__loc); bool __testf = true; bool __testt = true; bool __donef = __lc->_M_falsename_size == 0; bool __donet = __lc->_M_truename_size == 0; bool __testeof = false; size_t __n = 0; while (!__donef || !__donet) { if (__beg == __end) { __testeof = true; break; } const char_type __c = *__beg; if (!__donef) __testf = __c == __lc->_M_falsename[__n]; if (!__testf && __donet) break; if (!__donet) __testt = __c == __lc->_M_truename[__n]; if (!__testt && __donef) break; if (!__testt && !__testf) break; ++__n; ++__beg; __donef = !__testf || __n >= __lc->_M_falsename_size; __donet = !__testt || __n >= __lc->_M_truename_size; } if (__testf && __n == __lc->_M_falsename_size && __n) { __v = false; if (__testt && __n == __lc->_M_truename_size) __err = ios_base::failbit; else __err = __testeof ? ios_base::eofbit : ios_base::goodbit; } else if (__testt && __n == __lc->_M_truename_size && __n) { __v = true; __err = __testeof ? ios_base::eofbit : ios_base::goodbit; } else { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 23. Num_get overflow result. __v = false; __err = ios_base::failbit; if (__testeof) __err |= ios_base::eofbit; } } return __beg; } template _InIter num_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, float& __v) const { string __xtrc; __xtrc.reserve(32); __beg = _M_extract_float(__beg, __end, __io, __err, __xtrc); std::__convert_to_v(__xtrc.c_str(), __v, __err, _S_get_c_locale()); if (__beg == __end) __err |= ios_base::eofbit; return __beg; } template _InIter num_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, double& __v) const { string __xtrc; __xtrc.reserve(32); __beg = _M_extract_float(__beg, __end, __io, __err, __xtrc); std::__convert_to_v(__xtrc.c_str(), __v, __err, _S_get_c_locale()); if (__beg == __end) __err |= ios_base::eofbit; return __beg; } #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ template _InIter num_get<_CharT, _InIter>:: __do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, double& __v) const { string __xtrc; __xtrc.reserve(32); __beg = _M_extract_float(__beg, __end, __io, __err, __xtrc); std::__convert_to_v(__xtrc.c_str(), __v, __err, _S_get_c_locale()); if (__beg == __end) __err |= ios_base::eofbit; return __beg; } #endif template _InIter num_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, long double& __v) const { string __xtrc; __xtrc.reserve(32); __beg = _M_extract_float(__beg, __end, __io, __err, __xtrc); std::__convert_to_v(__xtrc.c_str(), __v, __err, _S_get_c_locale()); if (__beg == __end) __err |= ios_base::eofbit; return __beg; } template _InIter num_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, void*& __v) const { // Prepare for hex formatted input. typedef ios_base::fmtflags fmtflags; const fmtflags __fmt = __io.flags(); __io.flags((__fmt & ~ios_base::basefield) | ios_base::hex); typedef __gnu_cxx::__conditional_type<(sizeof(void*) <= sizeof(unsigned long)), unsigned long, unsigned long long>::__type _UIntPtrType; _UIntPtrType __ul; __beg = _M_extract_int(__beg, __end, __io, __err, __ul); // Reset from hex formatted input. __io.flags(__fmt); __v = reinterpret_cast(__ul); return __beg; } // For use by integer and floating-point types after they have been // converted into a char_type string. template void num_put<_CharT, _OutIter>:: _M_pad(_CharT __fill, streamsize __w, ios_base& __io, _CharT* __new, const _CharT* __cs, int& __len) const { // [22.2.2.2.2] Stage 3. // If necessary, pad. __pad<_CharT, char_traits<_CharT> >::_S_pad(__io, __fill, __new, __cs, __w, __len); __len = static_cast(__w); } _GLIBCXX_END_NAMESPACE_LDBL template int __int_to_char(_CharT* __bufend, _ValueT __v, const _CharT* __lit, ios_base::fmtflags __flags, bool __dec) { _CharT* __buf = __bufend; if (__builtin_expect(__dec, true)) { // Decimal. do { *--__buf = __lit[(__v % 10) + __num_base::_S_odigits]; __v /= 10; } while (__v != 0); } else if ((__flags & ios_base::basefield) == ios_base::oct) { // Octal. do { *--__buf = __lit[(__v & 0x7) + __num_base::_S_odigits]; __v >>= 3; } while (__v != 0); } else { // Hex. const bool __uppercase = __flags & ios_base::uppercase; const int __case_offset = __uppercase ? __num_base::_S_oudigits : __num_base::_S_odigits; do { *--__buf = __lit[(__v & 0xf) + __case_offset]; __v >>= 4; } while (__v != 0); } return __bufend - __buf; } _GLIBCXX_BEGIN_NAMESPACE_LDBL template void num_put<_CharT, _OutIter>:: _M_group_int(const char* __grouping, size_t __grouping_size, _CharT __sep, ios_base&, _CharT* __new, _CharT* __cs, int& __len) const { _CharT* __p = std::__add_grouping(__new, __sep, __grouping, __grouping_size, __cs, __cs + __len); __len = __p - __new; } template template _OutIter num_put<_CharT, _OutIter>:: _M_insert_int(_OutIter __s, ios_base& __io, _CharT __fill, _ValueT __v) const { using __gnu_cxx::__add_unsigned; typedef typename __add_unsigned<_ValueT>::__type __unsigned_type; typedef __numpunct_cache<_CharT> __cache_type; __use_cache<__cache_type> __uc; const locale& __loc = __io._M_getloc(); const __cache_type* __lc = __uc(__loc); const _CharT* __lit = __lc->_M_atoms_out; const ios_base::fmtflags __flags = __io.flags(); // Long enough to hold hex, dec, and octal representations. const int __ilen = 5 * sizeof(_ValueT); _CharT* __cs = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * __ilen)); // [22.2.2.2.2] Stage 1, numeric conversion to character. // Result is returned right-justified in the buffer. const ios_base::fmtflags __basefield = __flags & ios_base::basefield; const bool __dec = (__basefield != ios_base::oct && __basefield != ios_base::hex); const __unsigned_type __u = ((__v > 0 || !__dec) ? __unsigned_type(__v) : -__unsigned_type(__v)); int __len = __int_to_char(__cs + __ilen, __u, __lit, __flags, __dec); __cs += __ilen - __len; // Add grouping, if necessary. if (__lc->_M_use_grouping) { // Grouping can add (almost) as many separators as the number // of digits + space is reserved for numeric base or sign. _CharT* __cs2 = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * (__len + 1) * 2)); _M_group_int(__lc->_M_grouping, __lc->_M_grouping_size, __lc->_M_thousands_sep, __io, __cs2 + 2, __cs, __len); __cs = __cs2 + 2; } // Complete Stage 1, prepend numeric base or sign. if (__builtin_expect(__dec, true)) { // Decimal. if (__v >= 0) { if (bool(__flags & ios_base::showpos) && __gnu_cxx::__numeric_traits<_ValueT>::__is_signed) *--__cs = __lit[__num_base::_S_oplus], ++__len; } else *--__cs = __lit[__num_base::_S_ominus], ++__len; } else if (bool(__flags & ios_base::showbase) && __v) { if (__basefield == ios_base::oct) *--__cs = __lit[__num_base::_S_odigits], ++__len; else { // 'x' or 'X' const bool __uppercase = __flags & ios_base::uppercase; *--__cs = __lit[__num_base::_S_ox + __uppercase]; // '0' *--__cs = __lit[__num_base::_S_odigits]; __len += 2; } } // Pad. const streamsize __w = __io.width(); if (__w > static_cast(__len)) { _CharT* __cs3 = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * __w)); _M_pad(__fill, __w, __io, __cs3, __cs, __len); __cs = __cs3; } __io.width(0); // [22.2.2.2.2] Stage 4. // Write resulting, fully-formatted string to output iterator. return std::__write(__s, __cs, __len); } template void num_put<_CharT, _OutIter>:: _M_group_float(const char* __grouping, size_t __grouping_size, _CharT __sep, const _CharT* __p, _CharT* __new, _CharT* __cs, int& __len) const { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 282. What types does numpunct grouping refer to? // Add grouping, if necessary. const int __declen = __p ? __p - __cs : __len; _CharT* __p2 = std::__add_grouping(__new, __sep, __grouping, __grouping_size, __cs, __cs + __declen); // Tack on decimal part. int __newlen = __p2 - __new; if (__p) { char_traits<_CharT>::copy(__p2, __p, __len - __declen); __newlen += __len - __declen; } __len = __newlen; } // The following code uses vsnprintf (or vsprintf(), when // _GLIBCXX_USE_C99_STDIO is not defined) to convert floating point // values for insertion into a stream. An optimization would be to // replace them with code that works directly on a wide buffer and // then use __pad to do the padding. It would be good to replace // them anyway to gain back the efficiency that C++ provides by // knowing up front the type of the values to insert. Also, sprintf // is dangerous since may lead to accidental buffer overruns. This // implementation follows the C++ standard fairly directly as // outlined in 22.2.2.2 [lib.locale.num.put] template template _OutIter num_put<_CharT, _OutIter>:: _M_insert_float(_OutIter __s, ios_base& __io, _CharT __fill, char __mod, _ValueT __v) const { typedef __numpunct_cache<_CharT> __cache_type; __use_cache<__cache_type> __uc; const locale& __loc = __io._M_getloc(); const __cache_type* __lc = __uc(__loc); // Use default precision if out of range. const streamsize __prec = __io.precision() < 0 ? 6 : __io.precision(); const int __max_digits = __gnu_cxx::__numeric_traits<_ValueT>::__digits10; // [22.2.2.2.2] Stage 1, numeric conversion to character. int __len; // Long enough for the max format spec. char __fbuf[16]; __num_base::_S_format_float(__io, __fbuf, __mod); #if _GLIBCXX_USE_C99_STDIO && !_GLIBCXX_HAVE_BROKEN_VSNPRINTF // Precision is always used except for hexfloat format. const bool __use_prec = (__io.flags() & ios_base::floatfield) != ios_base::floatfield; // First try a buffer perhaps big enough (most probably sufficient // for non-ios_base::fixed outputs) int __cs_size = __max_digits * 3; char* __cs = static_cast(__builtin_alloca(__cs_size)); if (__use_prec) __len = std::__convert_from_v(_S_get_c_locale(), __cs, __cs_size, __fbuf, __prec, __v); else __len = std::__convert_from_v(_S_get_c_locale(), __cs, __cs_size, __fbuf, __v); // If the buffer was not large enough, try again with the correct size. if (__len >= __cs_size) { __cs_size = __len + 1; __cs = static_cast(__builtin_alloca(__cs_size)); if (__use_prec) __len = std::__convert_from_v(_S_get_c_locale(), __cs, __cs_size, __fbuf, __prec, __v); else __len = std::__convert_from_v(_S_get_c_locale(), __cs, __cs_size, __fbuf, __v); } #else // Consider the possibility of long ios_base::fixed outputs const bool __fixed = __io.flags() & ios_base::fixed; const int __max_exp = __gnu_cxx::__numeric_traits<_ValueT>::__max_exponent10; // The size of the output string is computed as follows. // ios_base::fixed outputs may need up to __max_exp + 1 chars // for the integer part + __prec chars for the fractional part // + 3 chars for sign, decimal point, '\0'. On the other hand, // for non-fixed outputs __max_digits * 2 + __prec chars are // largely sufficient. const int __cs_size = __fixed ? __max_exp + __prec + 4 : __max_digits * 2 + __prec; char* __cs = static_cast(__builtin_alloca(__cs_size)); __len = std::__convert_from_v(_S_get_c_locale(), __cs, 0, __fbuf, __prec, __v); #endif // [22.2.2.2.2] Stage 2, convert to char_type, using correct // numpunct.decimal_point() values for '.' and adding grouping. const ctype<_CharT>& __ctype = use_facet >(__loc); _CharT* __ws = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * __len)); __ctype.widen(__cs, __cs + __len, __ws); // Replace decimal point. _CharT* __wp = 0; const char* __p = char_traits::find(__cs, __len, '.'); if (__p) { __wp = __ws + (__p - __cs); *__wp = __lc->_M_decimal_point; } // Add grouping, if necessary. // N.B. Make sure to not group things like 2e20, i.e., no decimal // point, scientific notation. if (__lc->_M_use_grouping && (__wp || __len < 3 || (__cs[1] <= '9' && __cs[2] <= '9' && __cs[1] >= '0' && __cs[2] >= '0'))) { // Grouping can add (almost) as many separators as the // number of digits, but no more. _CharT* __ws2 = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * __len * 2)); streamsize __off = 0; if (__cs[0] == '-' || __cs[0] == '+') { __off = 1; __ws2[0] = __ws[0]; __len -= 1; } _M_group_float(__lc->_M_grouping, __lc->_M_grouping_size, __lc->_M_thousands_sep, __wp, __ws2 + __off, __ws + __off, __len); __len += __off; __ws = __ws2; } // Pad. const streamsize __w = __io.width(); if (__w > static_cast(__len)) { _CharT* __ws3 = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * __w)); _M_pad(__fill, __w, __io, __ws3, __ws, __len); __ws = __ws3; } __io.width(0); // [22.2.2.2.2] Stage 4. // Write resulting, fully-formatted string to output iterator. return std::__write(__s, __ws, __len); } template _OutIter num_put<_CharT, _OutIter>:: do_put(iter_type __s, ios_base& __io, char_type __fill, bool __v) const { const ios_base::fmtflags __flags = __io.flags(); if ((__flags & ios_base::boolalpha) == 0) { const long __l = __v; __s = _M_insert_int(__s, __io, __fill, __l); } else { typedef __numpunct_cache<_CharT> __cache_type; __use_cache<__cache_type> __uc; const locale& __loc = __io._M_getloc(); const __cache_type* __lc = __uc(__loc); const _CharT* __name = __v ? __lc->_M_truename : __lc->_M_falsename; int __len = __v ? __lc->_M_truename_size : __lc->_M_falsename_size; const streamsize __w = __io.width(); if (__w > static_cast(__len)) { const streamsize __plen = __w - __len; _CharT* __ps = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * __plen)); char_traits<_CharT>::assign(__ps, __plen, __fill); __io.width(0); if ((__flags & ios_base::adjustfield) == ios_base::left) { __s = std::__write(__s, __name, __len); __s = std::__write(__s, __ps, __plen); } else { __s = std::__write(__s, __ps, __plen); __s = std::__write(__s, __name, __len); } return __s; } __io.width(0); __s = std::__write(__s, __name, __len); } return __s; } template _OutIter num_put<_CharT, _OutIter>:: do_put(iter_type __s, ios_base& __io, char_type __fill, double __v) const { return _M_insert_float(__s, __io, __fill, char(), __v); } #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ template _OutIter num_put<_CharT, _OutIter>:: __do_put(iter_type __s, ios_base& __io, char_type __fill, double __v) const { return _M_insert_float(__s, __io, __fill, char(), __v); } #endif template _OutIter num_put<_CharT, _OutIter>:: do_put(iter_type __s, ios_base& __io, char_type __fill, long double __v) const { return _M_insert_float(__s, __io, __fill, 'L', __v); } template _OutIter num_put<_CharT, _OutIter>:: do_put(iter_type __s, ios_base& __io, char_type __fill, const void* __v) const { const ios_base::fmtflags __flags = __io.flags(); const ios_base::fmtflags __fmt = ~(ios_base::basefield | ios_base::uppercase); __io.flags((__flags & __fmt) | (ios_base::hex | ios_base::showbase)); typedef __gnu_cxx::__conditional_type<(sizeof(const void*) <= sizeof(unsigned long)), unsigned long, unsigned long long>::__type _UIntPtrType; __s = _M_insert_int(__s, __io, __fill, reinterpret_cast<_UIntPtrType>(__v)); __io.flags(__flags); return __s; } _GLIBCXX_END_NAMESPACE_LDBL // Construct correctly padded string, as per 22.2.2.2.2 // Assumes // __newlen > __oldlen // __news is allocated for __newlen size // NB: Of the two parameters, _CharT can be deduced from the // function arguments. The other (_Traits) has to be explicitly specified. template void __pad<_CharT, _Traits>::_S_pad(ios_base& __io, _CharT __fill, _CharT* __news, const _CharT* __olds, streamsize __newlen, streamsize __oldlen) { const size_t __plen = static_cast(__newlen - __oldlen); const ios_base::fmtflags __adjust = __io.flags() & ios_base::adjustfield; // Padding last. if (__adjust == ios_base::left) { _Traits::copy(__news, __olds, __oldlen); _Traits::assign(__news + __oldlen, __plen, __fill); return; } size_t __mod = 0; if (__adjust == ios_base::internal) { // Pad after the sign, if there is one. // Pad after 0[xX], if there is one. // Who came up with these rules, anyway? Jeeze. const locale& __loc = __io._M_getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); if (__ctype.widen('-') == __olds[0] || __ctype.widen('+') == __olds[0]) { __news[0] = __olds[0]; __mod = 1; ++__news; } else if (__ctype.widen('0') == __olds[0] && __oldlen > 1 && (__ctype.widen('x') == __olds[1] || __ctype.widen('X') == __olds[1])) { __news[0] = __olds[0]; __news[1] = __olds[1]; __mod = 2; __news += 2; } // else Padding first. } _Traits::assign(__news, __plen, __fill); _Traits::copy(__news + __plen, __olds + __mod, __oldlen - __mod); } template _CharT* __add_grouping(_CharT* __s, _CharT __sep, const char* __gbeg, size_t __gsize, const _CharT* __first, const _CharT* __last) { size_t __idx = 0; size_t __ctr = 0; while (__last - __first > __gbeg[__idx] && static_cast(__gbeg[__idx]) > 0 && __gbeg[__idx] != __gnu_cxx::__numeric_traits::__max) { __last -= __gbeg[__idx]; __idx < __gsize - 1 ? ++__idx : ++__ctr; } while (__first != __last) *__s++ = *__first++; while (__ctr--) { *__s++ = __sep; for (char __i = __gbeg[__idx]; __i > 0; --__i) *__s++ = *__first++; } while (__idx--) { *__s++ = __sep; for (char __i = __gbeg[__idx]; __i > 0; --__i) *__s++ = *__first++; } return __s; } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class _GLIBCXX_NAMESPACE_CXX11 numpunct; extern template class _GLIBCXX_NAMESPACE_CXX11 numpunct_byname; extern template class _GLIBCXX_NAMESPACE_LDBL num_get; extern template class _GLIBCXX_NAMESPACE_LDBL num_put; extern template class ctype_byname; extern template const ctype& use_facet >(const locale&); extern template const numpunct& use_facet >(const locale&); extern template const num_put& use_facet >(const locale&); extern template const num_get& use_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); #ifdef _GLIBCXX_USE_WCHAR_T extern template class _GLIBCXX_NAMESPACE_CXX11 numpunct; extern template class _GLIBCXX_NAMESPACE_CXX11 numpunct_byname; extern template class _GLIBCXX_NAMESPACE_LDBL num_get; extern template class _GLIBCXX_NAMESPACE_LDBL num_put; extern template class ctype_byname; extern template const ctype& use_facet >(const locale&); extern template const numpunct& use_facet >(const locale&); extern template const num_put& use_facet >(const locale&); extern template const num_get& use_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!`t t 8/bits/locale_facets_nonio.hnu[// Locale support -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/locale_facets_nonio.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.1 Locales // #ifndef _LOCALE_FACETS_NONIO_H #define _LOCALE_FACETS_NONIO_H 1 #pragma GCC system_header #include // For struct tm namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief Time format ordering data. * @ingroup locales * * This class provides an enum representing different orderings of * time: day, month, and year. */ class time_base { public: enum dateorder { no_order, dmy, mdy, ymd, ydm }; }; template struct __timepunct_cache : public locale::facet { // List of all known timezones, with GMT first. static const _CharT* _S_timezones[14]; const _CharT* _M_date_format; const _CharT* _M_date_era_format; const _CharT* _M_time_format; const _CharT* _M_time_era_format; const _CharT* _M_date_time_format; const _CharT* _M_date_time_era_format; const _CharT* _M_am; const _CharT* _M_pm; const _CharT* _M_am_pm_format; // Day names, starting with "C"'s Sunday. const _CharT* _M_day1; const _CharT* _M_day2; const _CharT* _M_day3; const _CharT* _M_day4; const _CharT* _M_day5; const _CharT* _M_day6; const _CharT* _M_day7; // Abbreviated day names, starting with "C"'s Sun. const _CharT* _M_aday1; const _CharT* _M_aday2; const _CharT* _M_aday3; const _CharT* _M_aday4; const _CharT* _M_aday5; const _CharT* _M_aday6; const _CharT* _M_aday7; // Month names, starting with "C"'s January. const _CharT* _M_month01; const _CharT* _M_month02; const _CharT* _M_month03; const _CharT* _M_month04; const _CharT* _M_month05; const _CharT* _M_month06; const _CharT* _M_month07; const _CharT* _M_month08; const _CharT* _M_month09; const _CharT* _M_month10; const _CharT* _M_month11; const _CharT* _M_month12; // Abbreviated month names, starting with "C"'s Jan. const _CharT* _M_amonth01; const _CharT* _M_amonth02; const _CharT* _M_amonth03; const _CharT* _M_amonth04; const _CharT* _M_amonth05; const _CharT* _M_amonth06; const _CharT* _M_amonth07; const _CharT* _M_amonth08; const _CharT* _M_amonth09; const _CharT* _M_amonth10; const _CharT* _M_amonth11; const _CharT* _M_amonth12; bool _M_allocated; __timepunct_cache(size_t __refs = 0) : facet(__refs), _M_date_format(0), _M_date_era_format(0), _M_time_format(0), _M_time_era_format(0), _M_date_time_format(0), _M_date_time_era_format(0), _M_am(0), _M_pm(0), _M_am_pm_format(0), _M_day1(0), _M_day2(0), _M_day3(0), _M_day4(0), _M_day5(0), _M_day6(0), _M_day7(0), _M_aday1(0), _M_aday2(0), _M_aday3(0), _M_aday4(0), _M_aday5(0), _M_aday6(0), _M_aday7(0), _M_month01(0), _M_month02(0), _M_month03(0), _M_month04(0), _M_month05(0), _M_month06(0), _M_month07(0), _M_month08(0), _M_month09(0), _M_month10(0), _M_month11(0), _M_month12(0), _M_amonth01(0), _M_amonth02(0), _M_amonth03(0), _M_amonth04(0), _M_amonth05(0), _M_amonth06(0), _M_amonth07(0), _M_amonth08(0), _M_amonth09(0), _M_amonth10(0), _M_amonth11(0), _M_amonth12(0), _M_allocated(false) { } ~__timepunct_cache(); private: __timepunct_cache& operator=(const __timepunct_cache&); explicit __timepunct_cache(const __timepunct_cache&); }; template __timepunct_cache<_CharT>::~__timepunct_cache() { if (_M_allocated) { // Unused. } } // Specializations. template<> const char* __timepunct_cache::_S_timezones[14]; #ifdef _GLIBCXX_USE_WCHAR_T template<> const wchar_t* __timepunct_cache::_S_timezones[14]; #endif // Generic. template const _CharT* __timepunct_cache<_CharT>::_S_timezones[14]; template class __timepunct : public locale::facet { public: // Types: typedef _CharT __char_type; typedef __timepunct_cache<_CharT> __cache_type; protected: __cache_type* _M_data; __c_locale _M_c_locale_timepunct; const char* _M_name_timepunct; public: /// Numpunct facet id. static locale::id id; explicit __timepunct(size_t __refs = 0); explicit __timepunct(__cache_type* __cache, size_t __refs = 0); /** * @brief Internal constructor. Not for general use. * * This is a constructor for use by the library itself to set up new * locales. * * @param __cloc The C locale. * @param __s The name of a locale. * @param refs Passed to the base facet class. */ explicit __timepunct(__c_locale __cloc, const char* __s, size_t __refs = 0); // FIXME: for error checking purposes _M_put should return the return // value of strftime/wcsftime. void _M_put(_CharT* __s, size_t __maxlen, const _CharT* __format, const tm* __tm) const throw (); void _M_date_formats(const _CharT** __date) const { // Always have default first. __date[0] = _M_data->_M_date_format; __date[1] = _M_data->_M_date_era_format; } void _M_time_formats(const _CharT** __time) const { // Always have default first. __time[0] = _M_data->_M_time_format; __time[1] = _M_data->_M_time_era_format; } void _M_date_time_formats(const _CharT** __dt) const { // Always have default first. __dt[0] = _M_data->_M_date_time_format; __dt[1] = _M_data->_M_date_time_era_format; } #if !_GLIBCXX_INLINE_VERSION void _M_am_pm_format(const _CharT*) const { /* Kept for ABI compatibility, see PR65927 */ } #endif void _M_am_pm(const _CharT** __ampm) const { __ampm[0] = _M_data->_M_am; __ampm[1] = _M_data->_M_pm; } void _M_days(const _CharT** __days) const { __days[0] = _M_data->_M_day1; __days[1] = _M_data->_M_day2; __days[2] = _M_data->_M_day3; __days[3] = _M_data->_M_day4; __days[4] = _M_data->_M_day5; __days[5] = _M_data->_M_day6; __days[6] = _M_data->_M_day7; } void _M_days_abbreviated(const _CharT** __days) const { __days[0] = _M_data->_M_aday1; __days[1] = _M_data->_M_aday2; __days[2] = _M_data->_M_aday3; __days[3] = _M_data->_M_aday4; __days[4] = _M_data->_M_aday5; __days[5] = _M_data->_M_aday6; __days[6] = _M_data->_M_aday7; } void _M_months(const _CharT** __months) const { __months[0] = _M_data->_M_month01; __months[1] = _M_data->_M_month02; __months[2] = _M_data->_M_month03; __months[3] = _M_data->_M_month04; __months[4] = _M_data->_M_month05; __months[5] = _M_data->_M_month06; __months[6] = _M_data->_M_month07; __months[7] = _M_data->_M_month08; __months[8] = _M_data->_M_month09; __months[9] = _M_data->_M_month10; __months[10] = _M_data->_M_month11; __months[11] = _M_data->_M_month12; } void _M_months_abbreviated(const _CharT** __months) const { __months[0] = _M_data->_M_amonth01; __months[1] = _M_data->_M_amonth02; __months[2] = _M_data->_M_amonth03; __months[3] = _M_data->_M_amonth04; __months[4] = _M_data->_M_amonth05; __months[5] = _M_data->_M_amonth06; __months[6] = _M_data->_M_amonth07; __months[7] = _M_data->_M_amonth08; __months[8] = _M_data->_M_amonth09; __months[9] = _M_data->_M_amonth10; __months[10] = _M_data->_M_amonth11; __months[11] = _M_data->_M_amonth12; } protected: virtual ~__timepunct(); // For use at construction time only. void _M_initialize_timepunct(__c_locale __cloc = 0); }; template locale::id __timepunct<_CharT>::id; // Specializations. template<> void __timepunct::_M_initialize_timepunct(__c_locale __cloc); template<> void __timepunct::_M_put(char*, size_t, const char*, const tm*) const throw (); #ifdef _GLIBCXX_USE_WCHAR_T template<> void __timepunct::_M_initialize_timepunct(__c_locale __cloc); template<> void __timepunct::_M_put(wchar_t*, size_t, const wchar_t*, const tm*) const throw (); #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace // Include host and configuration specific timepunct functions. #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CXX11 /** * @brief Primary class template time_get. * @ingroup locales * * This facet encapsulates the code to parse and return a date or * time from a string. It is used by the istream numeric * extraction operators. * * The time_get template uses protected virtual functions to provide the * actual results. The public accessors forward the call to the virtual * functions. These virtual functions are hooks for developers to * implement the behavior they require from the time_get facet. */ template class time_get : public locale::facet, public time_base { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef _InIter iter_type; //@} /// Numpunct facet id. static locale::id id; /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __refs Passed to the base facet class. */ explicit time_get(size_t __refs = 0) : facet (__refs) { } /** * @brief Return preferred order of month, day, and year. * * This function returns an enum from time_base::dateorder giving the * preferred ordering if the format @a x given to time_put::put() only * uses month, day, and year. If the format @a x for the associated * locale uses other fields, this function returns * time_base::dateorder::noorder. * * NOTE: The library always returns noorder at the moment. * * @return A member of time_base::dateorder. */ dateorder date_order() const { return this->do_date_order(); } /** * @brief Parse input time string. * * This function parses a time according to the format @a X and puts the * results into a user-supplied struct tm. The result is returned by * calling time_get::do_get_time(). * * If there is a valid time string according to format @a X, @a tm will * be filled in accordingly and the returned iterator will point to the * first character beyond the time string. If an error occurs before * the end, err |= ios_base::failbit. If parsing reads all the * characters, err |= ios_base::eofbit. * * @param __beg Start of string to parse. * @param __end End of string to parse. * @param __io Source of the locale. * @param __err Error flags to set. * @param __tm Pointer to struct tm to fill in. * @return Iterator to first char beyond time string. */ iter_type get_time(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { return this->do_get_time(__beg, __end, __io, __err, __tm); } /** * @brief Parse input date string. * * This function parses a date according to the format @a x and puts the * results into a user-supplied struct tm. The result is returned by * calling time_get::do_get_date(). * * If there is a valid date string according to format @a x, @a tm will * be filled in accordingly and the returned iterator will point to the * first character beyond the date string. If an error occurs before * the end, err |= ios_base::failbit. If parsing reads all the * characters, err |= ios_base::eofbit. * * @param __beg Start of string to parse. * @param __end End of string to parse. * @param __io Source of the locale. * @param __err Error flags to set. * @param __tm Pointer to struct tm to fill in. * @return Iterator to first char beyond date string. */ iter_type get_date(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { return this->do_get_date(__beg, __end, __io, __err, __tm); } /** * @brief Parse input weekday string. * * This function parses a weekday name and puts the results into a * user-supplied struct tm. The result is returned by calling * time_get::do_get_weekday(). * * Parsing starts by parsing an abbreviated weekday name. If a valid * abbreviation is followed by a character that would lead to the full * weekday name, parsing continues until the full name is found or an * error occurs. Otherwise parsing finishes at the end of the * abbreviated name. * * If an error occurs before the end, err |= ios_base::failbit. If * parsing reads all the characters, err |= ios_base::eofbit. * * @param __beg Start of string to parse. * @param __end End of string to parse. * @param __io Source of the locale. * @param __err Error flags to set. * @param __tm Pointer to struct tm to fill in. * @return Iterator to first char beyond weekday name. */ iter_type get_weekday(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { return this->do_get_weekday(__beg, __end, __io, __err, __tm); } /** * @brief Parse input month string. * * This function parses a month name and puts the results into a * user-supplied struct tm. The result is returned by calling * time_get::do_get_monthname(). * * Parsing starts by parsing an abbreviated month name. If a valid * abbreviation is followed by a character that would lead to the full * month name, parsing continues until the full name is found or an * error occurs. Otherwise parsing finishes at the end of the * abbreviated name. * * If an error occurs before the end, err |= ios_base::failbit. If * parsing reads all the characters, err |= * ios_base::eofbit. * * @param __beg Start of string to parse. * @param __end End of string to parse. * @param __io Source of the locale. * @param __err Error flags to set. * @param __tm Pointer to struct tm to fill in. * @return Iterator to first char beyond month name. */ iter_type get_monthname(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { return this->do_get_monthname(__beg, __end, __io, __err, __tm); } /** * @brief Parse input year string. * * This function reads up to 4 characters to parse a year string and * puts the results into a user-supplied struct tm. The result is * returned by calling time_get::do_get_year(). * * 4 consecutive digits are interpreted as a full year. If there are * exactly 2 consecutive digits, the library interprets this as the * number of years since 1900. * * If an error occurs before the end, err |= ios_base::failbit. If * parsing reads all the characters, err |= ios_base::eofbit. * * @param __beg Start of string to parse. * @param __end End of string to parse. * @param __io Source of the locale. * @param __err Error flags to set. * @param __tm Pointer to struct tm to fill in. * @return Iterator to first char beyond year. */ iter_type get_year(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { return this->do_get_year(__beg, __end, __io, __err, __tm); } #if __cplusplus >= 201103L /** * @brief Parse input string according to format. * * This function calls time_get::do_get with the provided * parameters. @see do_get() and get(). * * @param __s Start of string to parse. * @param __end End of string to parse. * @param __io Source of the locale. * @param __err Error flags to set. * @param __tm Pointer to struct tm to fill in. * @param __format Format specifier. * @param __modifier Format modifier. * @return Iterator to first char not parsed. */ inline iter_type get(iter_type __s, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm, char __format, char __modifier = 0) const { return this->do_get(__s, __end, __io, __err, __tm, __format, __modifier); } /** * @brief Parse input string according to format. * * This function parses the input string according to a * provided format string. It does the inverse of * time_put::put. The format string follows the format * specified for strftime(3)/strptime(3). The actual parsing * is done by time_get::do_get. * * @param __s Start of string to parse. * @param __end End of string to parse. * @param __io Source of the locale. * @param __err Error flags to set. * @param __tm Pointer to struct tm to fill in. * @param __fmt Start of the format string. * @param __fmtend End of the format string. * @return Iterator to first char not parsed. */ iter_type get(iter_type __s, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm, const char_type* __fmt, const char_type* __fmtend) const; #endif // __cplusplus >= 201103L protected: /// Destructor. virtual ~time_get() { } /** * @brief Return preferred order of month, day, and year. * * This function returns an enum from time_base::dateorder giving the * preferred ordering if the format @a x given to time_put::put() only * uses month, day, and year. This function is a hook for derived * classes to change the value returned. * * @return A member of time_base::dateorder. */ virtual dateorder do_date_order() const; /** * @brief Parse input time string. * * This function parses a time according to the format @a x and puts the * results into a user-supplied struct tm. This function is a hook for * derived classes to change the value returned. @see get_time() for * details. * * @param __beg Start of string to parse. * @param __end End of string to parse. * @param __io Source of the locale. * @param __err Error flags to set. * @param __tm Pointer to struct tm to fill in. * @return Iterator to first char beyond time string. */ virtual iter_type do_get_time(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const; /** * @brief Parse input date string. * * This function parses a date according to the format @a X and puts the * results into a user-supplied struct tm. This function is a hook for * derived classes to change the value returned. @see get_date() for * details. * * @param __beg Start of string to parse. * @param __end End of string to parse. * @param __io Source of the locale. * @param __err Error flags to set. * @param __tm Pointer to struct tm to fill in. * @return Iterator to first char beyond date string. */ virtual iter_type do_get_date(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const; /** * @brief Parse input weekday string. * * This function parses a weekday name and puts the results into a * user-supplied struct tm. This function is a hook for derived * classes to change the value returned. @see get_weekday() for * details. * * @param __beg Start of string to parse. * @param __end End of string to parse. * @param __io Source of the locale. * @param __err Error flags to set. * @param __tm Pointer to struct tm to fill in. * @return Iterator to first char beyond weekday name. */ virtual iter_type do_get_weekday(iter_type __beg, iter_type __end, ios_base&, ios_base::iostate& __err, tm* __tm) const; /** * @brief Parse input month string. * * This function parses a month name and puts the results into a * user-supplied struct tm. This function is a hook for derived * classes to change the value returned. @see get_monthname() for * details. * * @param __beg Start of string to parse. * @param __end End of string to parse. * @param __io Source of the locale. * @param __err Error flags to set. * @param __tm Pointer to struct tm to fill in. * @return Iterator to first char beyond month name. */ virtual iter_type do_get_monthname(iter_type __beg, iter_type __end, ios_base&, ios_base::iostate& __err, tm* __tm) const; /** * @brief Parse input year string. * * This function reads up to 4 characters to parse a year string and * puts the results into a user-supplied struct tm. This function is a * hook for derived classes to change the value returned. @see * get_year() for details. * * @param __beg Start of string to parse. * @param __end End of string to parse. * @param __io Source of the locale. * @param __err Error flags to set. * @param __tm Pointer to struct tm to fill in. * @return Iterator to first char beyond year. */ virtual iter_type do_get_year(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const; #if __cplusplus >= 201103L /** * @brief Parse input string according to format. * * This function parses the string according to the provided * format and optional modifier. This function is a hook for * derived classes to change the value returned. @see get() * for more details. * * @param __s Start of string to parse. * @param __end End of string to parse. * @param __f Source of the locale. * @param __err Error flags to set. * @param __tm Pointer to struct tm to fill in. * @param __format Format specifier. * @param __modifier Format modifier. * @return Iterator to first char not parsed. */ #if _GLIBCXX_USE_CXX11_ABI virtual #endif iter_type do_get(iter_type __s, iter_type __end, ios_base& __f, ios_base::iostate& __err, tm* __tm, char __format, char __modifier) const; #endif // __cplusplus >= 201103L // Extract numeric component of length __len. iter_type _M_extract_num(iter_type __beg, iter_type __end, int& __member, int __min, int __max, size_t __len, ios_base& __io, ios_base::iostate& __err) const; // Extract any unique array of string literals in a const _CharT* array. iter_type _M_extract_name(iter_type __beg, iter_type __end, int& __member, const _CharT** __names, size_t __indexlen, ios_base& __io, ios_base::iostate& __err) const; // Extract day or month name in a const _CharT* array. iter_type _M_extract_wday_or_month(iter_type __beg, iter_type __end, int& __member, const _CharT** __names, size_t __indexlen, ios_base& __io, ios_base::iostate& __err) const; // Extract on a component-by-component basis, via __format argument. iter_type _M_extract_via_format(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm, const _CharT* __format) const; }; template locale::id time_get<_CharT, _InIter>::id; /// class time_get_byname [22.2.5.2]. template class time_get_byname : public time_get<_CharT, _InIter> { public: // Types: typedef _CharT char_type; typedef _InIter iter_type; explicit time_get_byname(const char*, size_t __refs = 0) : time_get<_CharT, _InIter>(__refs) { } #if __cplusplus >= 201103L explicit time_get_byname(const string& __s, size_t __refs = 0) : time_get_byname(__s.c_str(), __refs) { } #endif protected: virtual ~time_get_byname() { } }; _GLIBCXX_END_NAMESPACE_CXX11 /** * @brief Primary class template time_put. * @ingroup locales * * This facet encapsulates the code to format and output dates and times * according to formats used by strftime(). * * The time_put template uses protected virtual functions to provide the * actual results. The public accessors forward the call to the virtual * functions. These virtual functions are hooks for developers to * implement the behavior they require from the time_put facet. */ template class time_put : public locale::facet { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef _OutIter iter_type; //@} /// Numpunct facet id. static locale::id id; /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __refs Passed to the base facet class. */ explicit time_put(size_t __refs = 0) : facet(__refs) { } /** * @brief Format and output a time or date. * * This function formats the data in struct tm according to the * provided format string. The format string is interpreted as by * strftime(). * * @param __s The stream to write to. * @param __io Source of locale. * @param __fill char_type to use for padding. * @param __tm Struct tm with date and time info to format. * @param __beg Start of format string. * @param __end End of format string. * @return Iterator after writing. */ iter_type put(iter_type __s, ios_base& __io, char_type __fill, const tm* __tm, const _CharT* __beg, const _CharT* __end) const; /** * @brief Format and output a time or date. * * This function formats the data in struct tm according to the * provided format char and optional modifier. The format and modifier * are interpreted as by strftime(). It does so by returning * time_put::do_put(). * * @param __s The stream to write to. * @param __io Source of locale. * @param __fill char_type to use for padding. * @param __tm Struct tm with date and time info to format. * @param __format Format char. * @param __mod Optional modifier char. * @return Iterator after writing. */ iter_type put(iter_type __s, ios_base& __io, char_type __fill, const tm* __tm, char __format, char __mod = 0) const { return this->do_put(__s, __io, __fill, __tm, __format, __mod); } protected: /// Destructor. virtual ~time_put() { } /** * @brief Format and output a time or date. * * This function formats the data in struct tm according to the * provided format char and optional modifier. This function is a hook * for derived classes to change the value returned. @see put() for * more details. * * @param __s The stream to write to. * @param __io Source of locale. * @param __fill char_type to use for padding. * @param __tm Struct tm with date and time info to format. * @param __format Format char. * @param __mod Optional modifier char. * @return Iterator after writing. */ virtual iter_type do_put(iter_type __s, ios_base& __io, char_type __fill, const tm* __tm, char __format, char __mod) const; }; template locale::id time_put<_CharT, _OutIter>::id; /// class time_put_byname [22.2.5.4]. template class time_put_byname : public time_put<_CharT, _OutIter> { public: // Types: typedef _CharT char_type; typedef _OutIter iter_type; explicit time_put_byname(const char*, size_t __refs = 0) : time_put<_CharT, _OutIter>(__refs) { } #if __cplusplus >= 201103L explicit time_put_byname(const string& __s, size_t __refs = 0) : time_put_byname(__s.c_str(), __refs) { } #endif protected: virtual ~time_put_byname() { } }; /** * @brief Money format ordering data. * @ingroup locales * * This class contains an ordered array of 4 fields to represent the * pattern for formatting a money amount. Each field may contain one entry * from the part enum. symbol, sign, and value must be present and the * remaining field must contain either none or space. @see * moneypunct::pos_format() and moneypunct::neg_format() for details of how * these fields are interpreted. */ class money_base { public: enum part { none, space, symbol, sign, value }; struct pattern { char field[4]; }; static const pattern _S_default_pattern; enum { _S_minus, _S_zero, _S_end = 11 }; // String literal of acceptable (narrow) input/output, for // money_get/money_put. "-0123456789" static const char* _S_atoms; // Construct and return valid pattern consisting of some combination of: // space none symbol sign value _GLIBCXX_CONST static pattern _S_construct_pattern(char __precedes, char __space, char __posn) throw (); }; template struct __moneypunct_cache : public locale::facet { const char* _M_grouping; size_t _M_grouping_size; bool _M_use_grouping; _CharT _M_decimal_point; _CharT _M_thousands_sep; const _CharT* _M_curr_symbol; size_t _M_curr_symbol_size; const _CharT* _M_positive_sign; size_t _M_positive_sign_size; const _CharT* _M_negative_sign; size_t _M_negative_sign_size; int _M_frac_digits; money_base::pattern _M_pos_format; money_base::pattern _M_neg_format; // A list of valid numeric literals for input and output: in the standard // "C" locale, this is "-0123456789". This array contains the chars after // having been passed through the current locale's ctype<_CharT>.widen(). _CharT _M_atoms[money_base::_S_end]; bool _M_allocated; __moneypunct_cache(size_t __refs = 0) : facet(__refs), _M_grouping(0), _M_grouping_size(0), _M_use_grouping(false), _M_decimal_point(_CharT()), _M_thousands_sep(_CharT()), _M_curr_symbol(0), _M_curr_symbol_size(0), _M_positive_sign(0), _M_positive_sign_size(0), _M_negative_sign(0), _M_negative_sign_size(0), _M_frac_digits(0), _M_pos_format(money_base::pattern()), _M_neg_format(money_base::pattern()), _M_allocated(false) { } ~__moneypunct_cache(); void _M_cache(const locale& __loc); private: __moneypunct_cache& operator=(const __moneypunct_cache&); explicit __moneypunct_cache(const __moneypunct_cache&); }; template __moneypunct_cache<_CharT, _Intl>::~__moneypunct_cache() { if (_M_allocated) { delete [] _M_grouping; delete [] _M_curr_symbol; delete [] _M_positive_sign; delete [] _M_negative_sign; } } _GLIBCXX_BEGIN_NAMESPACE_CXX11 /** * @brief Primary class template moneypunct. * @ingroup locales * * This facet encapsulates the punctuation, grouping and other formatting * features of money amount string representations. */ template class moneypunct : public locale::facet, public money_base { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef basic_string<_CharT> string_type; //@} typedef __moneypunct_cache<_CharT, _Intl> __cache_type; private: __cache_type* _M_data; public: /// This value is provided by the standard, but no reason for its /// existence. static const bool intl = _Intl; /// Numpunct facet id. static locale::id id; /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __refs Passed to the base facet class. */ explicit moneypunct(size_t __refs = 0) : facet(__refs), _M_data(0) { _M_initialize_moneypunct(); } /** * @brief Constructor performs initialization. * * This is an internal constructor. * * @param __cache Cache for optimization. * @param __refs Passed to the base facet class. */ explicit moneypunct(__cache_type* __cache, size_t __refs = 0) : facet(__refs), _M_data(__cache) { _M_initialize_moneypunct(); } /** * @brief Internal constructor. Not for general use. * * This is a constructor for use by the library itself to set up new * locales. * * @param __cloc The C locale. * @param __s The name of a locale. * @param __refs Passed to the base facet class. */ explicit moneypunct(__c_locale __cloc, const char* __s, size_t __refs = 0) : facet(__refs), _M_data(0) { _M_initialize_moneypunct(__cloc, __s); } /** * @brief Return decimal point character. * * This function returns a char_type to use as a decimal point. It * does so by returning returning * moneypunct::do_decimal_point(). * * @return @a char_type representing a decimal point. */ char_type decimal_point() const { return this->do_decimal_point(); } /** * @brief Return thousands separator character. * * This function returns a char_type to use as a thousands * separator. It does so by returning returning * moneypunct::do_thousands_sep(). * * @return char_type representing a thousands separator. */ char_type thousands_sep() const { return this->do_thousands_sep(); } /** * @brief Return grouping specification. * * This function returns a string representing groupings for the * integer part of an amount. Groupings indicate where thousands * separators should be inserted. * * Each char in the return string is interpret as an integer rather * than a character. These numbers represent the number of digits in a * group. The first char in the string represents the number of digits * in the least significant group. If a char is negative, it indicates * an unlimited number of digits for the group. If more chars from the * string are required to group a number, the last char is used * repeatedly. * * For example, if the grouping() returns \003\002 * and is applied to the number 123456789, this corresponds to * 12,34,56,789. Note that if the string was 32, this would * put more than 50 digits into the least significant group if * the character set is ASCII. * * The string is returned by calling * moneypunct::do_grouping(). * * @return string representing grouping specification. */ string grouping() const { return this->do_grouping(); } /** * @brief Return currency symbol string. * * This function returns a string_type to use as a currency symbol. It * does so by returning returning * moneypunct::do_curr_symbol(). * * @return @a string_type representing a currency symbol. */ string_type curr_symbol() const { return this->do_curr_symbol(); } /** * @brief Return positive sign string. * * This function returns a string_type to use as a sign for positive * amounts. It does so by returning returning * moneypunct::do_positive_sign(). * * If the return value contains more than one character, the first * character appears in the position indicated by pos_format() and the * remainder appear at the end of the formatted string. * * @return @a string_type representing a positive sign. */ string_type positive_sign() const { return this->do_positive_sign(); } /** * @brief Return negative sign string. * * This function returns a string_type to use as a sign for negative * amounts. It does so by returning returning * moneypunct::do_negative_sign(). * * If the return value contains more than one character, the first * character appears in the position indicated by neg_format() and the * remainder appear at the end of the formatted string. * * @return @a string_type representing a negative sign. */ string_type negative_sign() const { return this->do_negative_sign(); } /** * @brief Return number of digits in fraction. * * This function returns the exact number of digits that make up the * fractional part of a money amount. It does so by returning * returning moneypunct::do_frac_digits(). * * The fractional part of a money amount is optional. But if it is * present, there must be frac_digits() digits. * * @return Number of digits in amount fraction. */ int frac_digits() const { return this->do_frac_digits(); } //@{ /** * @brief Return pattern for money values. * * This function returns a pattern describing the formatting of a * positive or negative valued money amount. It does so by returning * returning moneypunct::do_pos_format() or * moneypunct::do_neg_format(). * * The pattern has 4 fields describing the ordering of symbol, sign, * value, and none or space. There must be one of each in the pattern. * The none and space enums may not appear in the first field and space * may not appear in the final field. * * The parts of a money string must appear in the order indicated by * the fields of the pattern. The symbol field indicates that the * value of curr_symbol() may be present. The sign field indicates * that the value of positive_sign() or negative_sign() must be * present. The value field indicates that the absolute value of the * money amount is present. none indicates 0 or more whitespace * characters, except at the end, where it permits no whitespace. * space indicates that 1 or more whitespace characters must be * present. * * For example, for the US locale and pos_format() pattern * {symbol,sign,value,none}, curr_symbol() == '$' * positive_sign() == '+', and value 10.01, and * options set to force the symbol, the corresponding string is * $+10.01. * * @return Pattern for money values. */ pattern pos_format() const { return this->do_pos_format(); } pattern neg_format() const { return this->do_neg_format(); } //@} protected: /// Destructor. virtual ~moneypunct(); /** * @brief Return decimal point character. * * Returns a char_type to use as a decimal point. This function is a * hook for derived classes to change the value returned. * * @return @a char_type representing a decimal point. */ virtual char_type do_decimal_point() const { return _M_data->_M_decimal_point; } /** * @brief Return thousands separator character. * * Returns a char_type to use as a thousands separator. This function * is a hook for derived classes to change the value returned. * * @return @a char_type representing a thousands separator. */ virtual char_type do_thousands_sep() const { return _M_data->_M_thousands_sep; } /** * @brief Return grouping specification. * * Returns a string representing groupings for the integer part of a * number. This function is a hook for derived classes to change the * value returned. @see grouping() for details. * * @return String representing grouping specification. */ virtual string do_grouping() const { return _M_data->_M_grouping; } /** * @brief Return currency symbol string. * * This function returns a string_type to use as a currency symbol. * This function is a hook for derived classes to change the value * returned. @see curr_symbol() for details. * * @return @a string_type representing a currency symbol. */ virtual string_type do_curr_symbol() const { return _M_data->_M_curr_symbol; } /** * @brief Return positive sign string. * * This function returns a string_type to use as a sign for positive * amounts. This function is a hook for derived classes to change the * value returned. @see positive_sign() for details. * * @return @a string_type representing a positive sign. */ virtual string_type do_positive_sign() const { return _M_data->_M_positive_sign; } /** * @brief Return negative sign string. * * This function returns a string_type to use as a sign for negative * amounts. This function is a hook for derived classes to change the * value returned. @see negative_sign() for details. * * @return @a string_type representing a negative sign. */ virtual string_type do_negative_sign() const { return _M_data->_M_negative_sign; } /** * @brief Return number of digits in fraction. * * This function returns the exact number of digits that make up the * fractional part of a money amount. This function is a hook for * derived classes to change the value returned. @see frac_digits() * for details. * * @return Number of digits in amount fraction. */ virtual int do_frac_digits() const { return _M_data->_M_frac_digits; } /** * @brief Return pattern for money values. * * This function returns a pattern describing the formatting of a * positive valued money amount. This function is a hook for derived * classes to change the value returned. @see pos_format() for * details. * * @return Pattern for money values. */ virtual pattern do_pos_format() const { return _M_data->_M_pos_format; } /** * @brief Return pattern for money values. * * This function returns a pattern describing the formatting of a * negative valued money amount. This function is a hook for derived * classes to change the value returned. @see neg_format() for * details. * * @return Pattern for money values. */ virtual pattern do_neg_format() const { return _M_data->_M_neg_format; } // For use at construction time only. void _M_initialize_moneypunct(__c_locale __cloc = 0, const char* __name = 0); }; template locale::id moneypunct<_CharT, _Intl>::id; template const bool moneypunct<_CharT, _Intl>::intl; template<> moneypunct::~moneypunct(); template<> moneypunct::~moneypunct(); template<> void moneypunct::_M_initialize_moneypunct(__c_locale, const char*); template<> void moneypunct::_M_initialize_moneypunct(__c_locale, const char*); #ifdef _GLIBCXX_USE_WCHAR_T template<> moneypunct::~moneypunct(); template<> moneypunct::~moneypunct(); template<> void moneypunct::_M_initialize_moneypunct(__c_locale, const char*); template<> void moneypunct::_M_initialize_moneypunct(__c_locale, const char*); #endif /// class moneypunct_byname [22.2.6.4]. template class moneypunct_byname : public moneypunct<_CharT, _Intl> { public: typedef _CharT char_type; typedef basic_string<_CharT> string_type; static const bool intl = _Intl; explicit moneypunct_byname(const char* __s, size_t __refs = 0) : moneypunct<_CharT, _Intl>(__refs) { if (__builtin_strcmp(__s, "C") != 0 && __builtin_strcmp(__s, "POSIX") != 0) { __c_locale __tmp; this->_S_create_c_locale(__tmp, __s); this->_M_initialize_moneypunct(__tmp); this->_S_destroy_c_locale(__tmp); } } #if __cplusplus >= 201103L explicit moneypunct_byname(const string& __s, size_t __refs = 0) : moneypunct_byname(__s.c_str(), __refs) { } #endif protected: virtual ~moneypunct_byname() { } }; template const bool moneypunct_byname<_CharT, _Intl>::intl; _GLIBCXX_END_NAMESPACE_CXX11 _GLIBCXX_BEGIN_NAMESPACE_LDBL_OR_CXX11 /** * @brief Primary class template money_get. * @ingroup locales * * This facet encapsulates the code to parse and return a monetary * amount from a string. * * The money_get template uses protected virtual functions to * provide the actual results. The public accessors forward the * call to the virtual functions. These virtual functions are * hooks for developers to implement the behavior they require from * the money_get facet. */ template class money_get : public locale::facet { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef _InIter iter_type; typedef basic_string<_CharT> string_type; //@} /// Numpunct facet id. static locale::id id; /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __refs Passed to the base facet class. */ explicit money_get(size_t __refs = 0) : facet(__refs) { } /** * @brief Read and parse a monetary value. * * This function reads characters from @a __s, interprets them as a * monetary value according to moneypunct and ctype facets retrieved * from io.getloc(), and returns the result in @a units as an integral * value moneypunct::frac_digits() * the actual amount. For example, * the string $10.01 in a US locale would store 1001 in @a units. * * Any characters not part of a valid money amount are not consumed. * * If a money value cannot be parsed from the input stream, sets * err=(err|io.failbit). If the stream is consumed before finishing * parsing, sets err=(err|io.failbit|io.eofbit). @a units is * unchanged if parsing fails. * * This function works by returning the result of do_get(). * * @param __s Start of characters to parse. * @param __end End of characters to parse. * @param __intl Parameter to use_facet >. * @param __io Source of facets and io state. * @param __err Error field to set if parsing fails. * @param __units Place to store result of parsing. * @return Iterator referencing first character beyond valid money * amount. */ iter_type get(iter_type __s, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, long double& __units) const { return this->do_get(__s, __end, __intl, __io, __err, __units); } /** * @brief Read and parse a monetary value. * * This function reads characters from @a __s, interprets them as * a monetary value according to moneypunct and ctype facets * retrieved from io.getloc(), and returns the result in @a * digits. For example, the string $10.01 in a US locale would * store 1001 in @a digits. * * Any characters not part of a valid money amount are not consumed. * * If a money value cannot be parsed from the input stream, sets * err=(err|io.failbit). If the stream is consumed before finishing * parsing, sets err=(err|io.failbit|io.eofbit). * * This function works by returning the result of do_get(). * * @param __s Start of characters to parse. * @param __end End of characters to parse. * @param __intl Parameter to use_facet >. * @param __io Source of facets and io state. * @param __err Error field to set if parsing fails. * @param __digits Place to store result of parsing. * @return Iterator referencing first character beyond valid money * amount. */ iter_type get(iter_type __s, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, string_type& __digits) const { return this->do_get(__s, __end, __intl, __io, __err, __digits); } protected: /// Destructor. virtual ~money_get() { } /** * @brief Read and parse a monetary value. * * This function reads and parses characters representing a monetary * value. This function is a hook for derived classes to change the * value returned. @see get() for details. */ // XXX GLIBCXX_ABI Deprecated #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ \ && _GLIBCXX_USE_CXX11_ABI == 0 virtual iter_type __do_get(iter_type __s, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, double& __units) const; #else virtual iter_type do_get(iter_type __s, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, long double& __units) const; #endif /** * @brief Read and parse a monetary value. * * This function reads and parses characters representing a monetary * value. This function is a hook for derived classes to change the * value returned. @see get() for details. */ virtual iter_type do_get(iter_type __s, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, string_type& __digits) const; // XXX GLIBCXX_ABI Deprecated #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ \ && _GLIBCXX_USE_CXX11_ABI == 0 virtual iter_type do_get(iter_type __s, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, long double& __units) const; #endif template iter_type _M_extract(iter_type __s, iter_type __end, ios_base& __io, ios_base::iostate& __err, string& __digits) const; }; template locale::id money_get<_CharT, _InIter>::id; /** * @brief Primary class template money_put. * @ingroup locales * * This facet encapsulates the code to format and output a monetary * amount. * * The money_put template uses protected virtual functions to * provide the actual results. The public accessors forward the * call to the virtual functions. These virtual functions are * hooks for developers to implement the behavior they require from * the money_put facet. */ template class money_put : public locale::facet { public: //@{ /// Public typedefs typedef _CharT char_type; typedef _OutIter iter_type; typedef basic_string<_CharT> string_type; //@} /// Numpunct facet id. static locale::id id; /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __refs Passed to the base facet class. */ explicit money_put(size_t __refs = 0) : facet(__refs) { } /** * @brief Format and output a monetary value. * * This function formats @a units as a monetary value according to * moneypunct and ctype facets retrieved from io.getloc(), and writes * the resulting characters to @a __s. For example, the value 1001 in a * US locale would write $10.01 to @a __s. * * This function works by returning the result of do_put(). * * @param __s The stream to write to. * @param __intl Parameter to use_facet >. * @param __io Source of facets and io state. * @param __fill char_type to use for padding. * @param __units Place to store result of parsing. * @return Iterator after writing. */ iter_type put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, long double __units) const { return this->do_put(__s, __intl, __io, __fill, __units); } /** * @brief Format and output a monetary value. * * This function formats @a digits as a monetary value * according to moneypunct and ctype facets retrieved from * io.getloc(), and writes the resulting characters to @a __s. * For example, the string 1001 in a US locale * would write $10.01 to @a __s. * * This function works by returning the result of do_put(). * * @param __s The stream to write to. * @param __intl Parameter to use_facet >. * @param __io Source of facets and io state. * @param __fill char_type to use for padding. * @param __digits Place to store result of parsing. * @return Iterator after writing. */ iter_type put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, const string_type& __digits) const { return this->do_put(__s, __intl, __io, __fill, __digits); } protected: /// Destructor. virtual ~money_put() { } /** * @brief Format and output a monetary value. * * This function formats @a units as a monetary value according to * moneypunct and ctype facets retrieved from io.getloc(), and writes * the resulting characters to @a __s. For example, the value 1001 in a * US locale would write $10.01 to @a __s. * * This function is a hook for derived classes to change the value * returned. @see put(). * * @param __s The stream to write to. * @param __intl Parameter to use_facet >. * @param __io Source of facets and io state. * @param __fill char_type to use for padding. * @param __units Place to store result of parsing. * @return Iterator after writing. */ // XXX GLIBCXX_ABI Deprecated #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ \ && _GLIBCXX_USE_CXX11_ABI == 0 virtual iter_type __do_put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, double __units) const; #else virtual iter_type do_put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, long double __units) const; #endif /** * @brief Format and output a monetary value. * * This function formats @a digits as a monetary value * according to moneypunct and ctype facets retrieved from * io.getloc(), and writes the resulting characters to @a __s. * For example, the string 1001 in a US locale * would write $10.01 to @a __s. * * This function is a hook for derived classes to change the value * returned. @see put(). * * @param __s The stream to write to. * @param __intl Parameter to use_facet >. * @param __io Source of facets and io state. * @param __fill char_type to use for padding. * @param __digits Place to store result of parsing. * @return Iterator after writing. */ virtual iter_type do_put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, const string_type& __digits) const; // XXX GLIBCXX_ABI Deprecated #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ \ && _GLIBCXX_USE_CXX11_ABI == 0 virtual iter_type do_put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, long double __units) const; #endif template iter_type _M_insert(iter_type __s, ios_base& __io, char_type __fill, const string_type& __digits) const; }; template locale::id money_put<_CharT, _OutIter>::id; _GLIBCXX_END_NAMESPACE_LDBL_OR_CXX11 /** * @brief Messages facet base class providing catalog typedef. * @ingroup locales */ struct messages_base { typedef int catalog; }; _GLIBCXX_BEGIN_NAMESPACE_CXX11 /** * @brief Primary class template messages. * @ingroup locales * * This facet encapsulates the code to retrieve messages from * message catalogs. The only thing defined by the standard for this facet * is the interface. All underlying functionality is * implementation-defined. * * This library currently implements 3 versions of the message facet. The * first version (gnu) is a wrapper around gettext, provided by libintl. * The second version (ieee) is a wrapper around catgets. The final * version (default) does no actual translation. These implementations are * only provided for char and wchar_t instantiations. * * The messages template uses protected virtual functions to * provide the actual results. The public accessors forward the * call to the virtual functions. These virtual functions are * hooks for developers to implement the behavior they require from * the messages facet. */ template class messages : public locale::facet, public messages_base { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef basic_string<_CharT> string_type; //@} protected: // Underlying "C" library locale information saved from // initialization, needed by messages_byname as well. __c_locale _M_c_locale_messages; const char* _M_name_messages; public: /// Numpunct facet id. static locale::id id; /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __refs Passed to the base facet class. */ explicit messages(size_t __refs = 0); // Non-standard. /** * @brief Internal constructor. Not for general use. * * This is a constructor for use by the library itself to set up new * locales. * * @param __cloc The C locale. * @param __s The name of a locale. * @param __refs Refcount to pass to the base class. */ explicit messages(__c_locale __cloc, const char* __s, size_t __refs = 0); /* * @brief Open a message catalog. * * This function opens and returns a handle to a message catalog by * returning do_open(__s, __loc). * * @param __s The catalog to open. * @param __loc Locale to use for character set conversions. * @return Handle to the catalog or value < 0 if open fails. */ catalog open(const basic_string& __s, const locale& __loc) const { return this->do_open(__s, __loc); } // Non-standard and unorthodox, yet effective. /* * @brief Open a message catalog. * * This non-standard function opens and returns a handle to a message * catalog by returning do_open(s, loc). The third argument provides a * message catalog root directory for gnu gettext and is ignored * otherwise. * * @param __s The catalog to open. * @param __loc Locale to use for character set conversions. * @param __dir Message catalog root directory. * @return Handle to the catalog or value < 0 if open fails. */ catalog open(const basic_string&, const locale&, const char*) const; /* * @brief Look up a string in a message catalog. * * This function retrieves and returns a message from a catalog by * returning do_get(c, set, msgid, s). * * For gnu, @a __set and @a msgid are ignored. Returns gettext(s). * For default, returns s. For ieee, returns catgets(c,set,msgid,s). * * @param __c The catalog to access. * @param __set Implementation-defined. * @param __msgid Implementation-defined. * @param __s Default return value if retrieval fails. * @return Retrieved message or @a __s if get fails. */ string_type get(catalog __c, int __set, int __msgid, const string_type& __s) const { return this->do_get(__c, __set, __msgid, __s); } /* * @brief Close a message catalog. * * Closes catalog @a c by calling do_close(c). * * @param __c The catalog to close. */ void close(catalog __c) const { return this->do_close(__c); } protected: /// Destructor. virtual ~messages(); /* * @brief Open a message catalog. * * This function opens and returns a handle to a message catalog in an * implementation-defined manner. This function is a hook for derived * classes to change the value returned. * * @param __s The catalog to open. * @param __loc Locale to use for character set conversions. * @return Handle to the opened catalog, value < 0 if open failed. */ virtual catalog do_open(const basic_string&, const locale&) const; /* * @brief Look up a string in a message catalog. * * This function retrieves and returns a message from a catalog in an * implementation-defined manner. This function is a hook for derived * classes to change the value returned. * * For gnu, @a __set and @a __msgid are ignored. Returns gettext(s). * For default, returns s. For ieee, returns catgets(c,set,msgid,s). * * @param __c The catalog to access. * @param __set Implementation-defined. * @param __msgid Implementation-defined. * @param __s Default return value if retrieval fails. * @return Retrieved message or @a __s if get fails. */ virtual string_type do_get(catalog, int, int, const string_type& __dfault) const; /* * @brief Close a message catalog. * * @param __c The catalog to close. */ virtual void do_close(catalog) const; // Returns a locale and codeset-converted string, given a char* message. char* _M_convert_to_char(const string_type& __msg) const { // XXX return reinterpret_cast(const_cast<_CharT*>(__msg.c_str())); } // Returns a locale and codeset-converted string, given a char* message. string_type _M_convert_from_char(char*) const { // XXX return string_type(); } }; template locale::id messages<_CharT>::id; /// Specializations for required instantiations. template<> string messages::do_get(catalog, int, int, const string&) const; #ifdef _GLIBCXX_USE_WCHAR_T template<> wstring messages::do_get(catalog, int, int, const wstring&) const; #endif /// class messages_byname [22.2.7.2]. template class messages_byname : public messages<_CharT> { public: typedef _CharT char_type; typedef basic_string<_CharT> string_type; explicit messages_byname(const char* __s, size_t __refs = 0); #if __cplusplus >= 201103L explicit messages_byname(const string& __s, size_t __refs = 0) : messages_byname(__s.c_str(), __refs) { } #endif protected: virtual ~messages_byname() { } }; _GLIBCXX_END_NAMESPACE_CXX11 _GLIBCXX_END_NAMESPACE_VERSION } // namespace // Include host and configuration specific messages functions. #include // 22.2.1.5 Template class codecvt #include #include #endif PK!8/bits/locale_facets_nonio.tccnu[// Locale support -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/locale_facets_nonio.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ #ifndef _LOCALE_FACETS_NONIO_TCC #define _LOCALE_FACETS_NONIO_TCC 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template struct __use_cache<__moneypunct_cache<_CharT, _Intl> > { const __moneypunct_cache<_CharT, _Intl>* operator() (const locale& __loc) const { const size_t __i = moneypunct<_CharT, _Intl>::id._M_id(); const locale::facet** __caches = __loc._M_impl->_M_caches; if (!__caches[__i]) { __moneypunct_cache<_CharT, _Intl>* __tmp = 0; __try { __tmp = new __moneypunct_cache<_CharT, _Intl>; __tmp->_M_cache(__loc); } __catch(...) { delete __tmp; __throw_exception_again; } __loc._M_impl->_M_install_cache(__tmp, __i); } return static_cast< const __moneypunct_cache<_CharT, _Intl>*>(__caches[__i]); } }; template void __moneypunct_cache<_CharT, _Intl>::_M_cache(const locale& __loc) { const moneypunct<_CharT, _Intl>& __mp = use_facet >(__loc); _M_decimal_point = __mp.decimal_point(); _M_thousands_sep = __mp.thousands_sep(); _M_frac_digits = __mp.frac_digits(); char* __grouping = 0; _CharT* __curr_symbol = 0; _CharT* __positive_sign = 0; _CharT* __negative_sign = 0; __try { const string& __g = __mp.grouping(); _M_grouping_size = __g.size(); __grouping = new char[_M_grouping_size]; __g.copy(__grouping, _M_grouping_size); _M_use_grouping = (_M_grouping_size && static_cast(__grouping[0]) > 0 && (__grouping[0] != __gnu_cxx::__numeric_traits::__max)); const basic_string<_CharT>& __cs = __mp.curr_symbol(); _M_curr_symbol_size = __cs.size(); __curr_symbol = new _CharT[_M_curr_symbol_size]; __cs.copy(__curr_symbol, _M_curr_symbol_size); const basic_string<_CharT>& __ps = __mp.positive_sign(); _M_positive_sign_size = __ps.size(); __positive_sign = new _CharT[_M_positive_sign_size]; __ps.copy(__positive_sign, _M_positive_sign_size); const basic_string<_CharT>& __ns = __mp.negative_sign(); _M_negative_sign_size = __ns.size(); __negative_sign = new _CharT[_M_negative_sign_size]; __ns.copy(__negative_sign, _M_negative_sign_size); _M_pos_format = __mp.pos_format(); _M_neg_format = __mp.neg_format(); const ctype<_CharT>& __ct = use_facet >(__loc); __ct.widen(money_base::_S_atoms, money_base::_S_atoms + money_base::_S_end, _M_atoms); _M_grouping = __grouping; _M_curr_symbol = __curr_symbol; _M_positive_sign = __positive_sign; _M_negative_sign = __negative_sign; _M_allocated = true; } __catch(...) { delete [] __grouping; delete [] __curr_symbol; delete [] __positive_sign; delete [] __negative_sign; __throw_exception_again; } } _GLIBCXX_BEGIN_NAMESPACE_LDBL_OR_CXX11 template template _InIter money_get<_CharT, _InIter>:: _M_extract(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, string& __units) const { typedef char_traits<_CharT> __traits_type; typedef typename string_type::size_type size_type; typedef money_base::part part; typedef __moneypunct_cache<_CharT, _Intl> __cache_type; const locale& __loc = __io._M_getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); __use_cache<__cache_type> __uc; const __cache_type* __lc = __uc(__loc); const char_type* __lit = __lc->_M_atoms; // Deduced sign. bool __negative = false; // Sign size. size_type __sign_size = 0; // True if sign is mandatory. const bool __mandatory_sign = (__lc->_M_positive_sign_size && __lc->_M_negative_sign_size); // String of grouping info from thousands_sep plucked from __units. string __grouping_tmp; if (__lc->_M_use_grouping) __grouping_tmp.reserve(32); // Last position before the decimal point. int __last_pos = 0; // Separator positions, then, possibly, fractional digits. int __n = 0; // If input iterator is in a valid state. bool __testvalid = true; // Flag marking when a decimal point is found. bool __testdecfound = false; // The tentative returned string is stored here. string __res; __res.reserve(32); const char_type* __lit_zero = __lit + money_base::_S_zero; const money_base::pattern __p = __lc->_M_neg_format; for (int __i = 0; __i < 4 && __testvalid; ++__i) { const part __which = static_cast(__p.field[__i]); switch (__which) { case money_base::symbol: // According to 22.2.6.1.2, p2, symbol is required // if (__io.flags() & ios_base::showbase), otherwise // is optional and consumed only if other characters // are needed to complete the format. if (__io.flags() & ios_base::showbase || __sign_size > 1 || __i == 0 || (__i == 1 && (__mandatory_sign || (static_cast(__p.field[0]) == money_base::sign) || (static_cast(__p.field[2]) == money_base::space))) || (__i == 2 && ((static_cast(__p.field[3]) == money_base::value) || (__mandatory_sign && (static_cast(__p.field[3]) == money_base::sign))))) { const size_type __len = __lc->_M_curr_symbol_size; size_type __j = 0; for (; __beg != __end && __j < __len && *__beg == __lc->_M_curr_symbol[__j]; ++__beg, (void)++__j); if (__j != __len && (__j || __io.flags() & ios_base::showbase)) __testvalid = false; } break; case money_base::sign: // Sign might not exist, or be more than one character long. if (__lc->_M_positive_sign_size && __beg != __end && *__beg == __lc->_M_positive_sign[0]) { __sign_size = __lc->_M_positive_sign_size; ++__beg; } else if (__lc->_M_negative_sign_size && __beg != __end && *__beg == __lc->_M_negative_sign[0]) { __negative = true; __sign_size = __lc->_M_negative_sign_size; ++__beg; } else if (__lc->_M_positive_sign_size && !__lc->_M_negative_sign_size) // "... if no sign is detected, the result is given the sign // that corresponds to the source of the empty string" __negative = true; else if (__mandatory_sign) __testvalid = false; break; case money_base::value: // Extract digits, remove and stash away the // grouping of found thousands separators. for (; __beg != __end; ++__beg) { const char_type __c = *__beg; const char_type* __q = __traits_type::find(__lit_zero, 10, __c); if (__q != 0) { __res += money_base::_S_atoms[__q - __lit]; ++__n; } else if (__c == __lc->_M_decimal_point && !__testdecfound) { if (__lc->_M_frac_digits <= 0) break; __last_pos = __n; __n = 0; __testdecfound = true; } else if (__lc->_M_use_grouping && __c == __lc->_M_thousands_sep && !__testdecfound) { if (__n) { // Mark position for later analysis. __grouping_tmp += static_cast(__n); __n = 0; } else { __testvalid = false; break; } } else break; } if (__res.empty()) __testvalid = false; break; case money_base::space: // At least one space is required. if (__beg != __end && __ctype.is(ctype_base::space, *__beg)) ++__beg; else __testvalid = false; // fallthrough case money_base::none: // Only if not at the end of the pattern. if (__i != 3) for (; __beg != __end && __ctype.is(ctype_base::space, *__beg); ++__beg); break; } } // Need to get the rest of the sign characters, if they exist. if (__sign_size > 1 && __testvalid) { const char_type* __sign = __negative ? __lc->_M_negative_sign : __lc->_M_positive_sign; size_type __i = 1; for (; __beg != __end && __i < __sign_size && *__beg == __sign[__i]; ++__beg, (void)++__i); if (__i != __sign_size) __testvalid = false; } if (__testvalid) { // Strip leading zeros. if (__res.size() > 1) { const size_type __first = __res.find_first_not_of('0'); const bool __only_zeros = __first == string::npos; if (__first) __res.erase(0, __only_zeros ? __res.size() - 1 : __first); } // 22.2.6.1.2, p4 if (__negative && __res[0] != '0') __res.insert(__res.begin(), '-'); // Test for grouping fidelity. if (__grouping_tmp.size()) { // Add the ending grouping. __grouping_tmp += static_cast(__testdecfound ? __last_pos : __n); if (!std::__verify_grouping(__lc->_M_grouping, __lc->_M_grouping_size, __grouping_tmp)) __err |= ios_base::failbit; } // Iff not enough digits were supplied after the decimal-point. if (__testdecfound && __n != __lc->_M_frac_digits) __testvalid = false; } // Iff valid sequence is not recognized. if (!__testvalid) __err |= ios_base::failbit; else __units.swap(__res); // Iff no more characters are available. if (__beg == __end) __err |= ios_base::eofbit; return __beg; } #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ \ && _GLIBCXX_USE_CXX11_ABI == 0 template _InIter money_get<_CharT, _InIter>:: __do_get(iter_type __beg, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, double& __units) const { string __str; __beg = __intl ? _M_extract(__beg, __end, __io, __err, __str) : _M_extract(__beg, __end, __io, __err, __str); std::__convert_to_v(__str.c_str(), __units, __err, _S_get_c_locale()); return __beg; } #endif template _InIter money_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, long double& __units) const { string __str; __beg = __intl ? _M_extract(__beg, __end, __io, __err, __str) : _M_extract(__beg, __end, __io, __err, __str); std::__convert_to_v(__str.c_str(), __units, __err, _S_get_c_locale()); return __beg; } template _InIter money_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, string_type& __digits) const { typedef typename string::size_type size_type; const locale& __loc = __io._M_getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); string __str; __beg = __intl ? _M_extract(__beg, __end, __io, __err, __str) : _M_extract(__beg, __end, __io, __err, __str); const size_type __len = __str.size(); if (__len) { __digits.resize(__len); __ctype.widen(__str.data(), __str.data() + __len, &__digits[0]); } return __beg; } template template _OutIter money_put<_CharT, _OutIter>:: _M_insert(iter_type __s, ios_base& __io, char_type __fill, const string_type& __digits) const { typedef typename string_type::size_type size_type; typedef money_base::part part; typedef __moneypunct_cache<_CharT, _Intl> __cache_type; const locale& __loc = __io._M_getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); __use_cache<__cache_type> __uc; const __cache_type* __lc = __uc(__loc); const char_type* __lit = __lc->_M_atoms; // Determine if negative or positive formats are to be used, and // discard leading negative_sign if it is present. const char_type* __beg = __digits.data(); money_base::pattern __p; const char_type* __sign; size_type __sign_size; if (!(*__beg == __lit[money_base::_S_minus])) { __p = __lc->_M_pos_format; __sign = __lc->_M_positive_sign; __sign_size = __lc->_M_positive_sign_size; } else { __p = __lc->_M_neg_format; __sign = __lc->_M_negative_sign; __sign_size = __lc->_M_negative_sign_size; if (__digits.size()) ++__beg; } // Look for valid numbers in the ctype facet within input digits. size_type __len = __ctype.scan_not(ctype_base::digit, __beg, __beg + __digits.size()) - __beg; if (__len) { // Assume valid input, and attempt to format. // Break down input numbers into base components, as follows: // final_value = grouped units + (decimal point) + (digits) string_type __value; __value.reserve(2 * __len); // Add thousands separators to non-decimal digits, per // grouping rules. long __paddec = __len - __lc->_M_frac_digits; if (__paddec > 0) { if (__lc->_M_frac_digits < 0) __paddec = __len; if (__lc->_M_grouping_size) { __value.assign(2 * __paddec, char_type()); _CharT* __vend = std::__add_grouping(&__value[0], __lc->_M_thousands_sep, __lc->_M_grouping, __lc->_M_grouping_size, __beg, __beg + __paddec); __value.erase(__vend - &__value[0]); } else __value.assign(__beg, __paddec); } // Deal with decimal point, decimal digits. if (__lc->_M_frac_digits > 0) { __value += __lc->_M_decimal_point; if (__paddec >= 0) __value.append(__beg + __paddec, __lc->_M_frac_digits); else { // Have to pad zeros in the decimal position. __value.append(-__paddec, __lit[money_base::_S_zero]); __value.append(__beg, __len); } } // Calculate length of resulting string. const ios_base::fmtflags __f = __io.flags() & ios_base::adjustfield; __len = __value.size() + __sign_size; __len += ((__io.flags() & ios_base::showbase) ? __lc->_M_curr_symbol_size : 0); string_type __res; __res.reserve(2 * __len); const size_type __width = static_cast(__io.width()); const bool __testipad = (__f == ios_base::internal && __len < __width); // Fit formatted digits into the required pattern. for (int __i = 0; __i < 4; ++__i) { const part __which = static_cast(__p.field[__i]); switch (__which) { case money_base::symbol: if (__io.flags() & ios_base::showbase) __res.append(__lc->_M_curr_symbol, __lc->_M_curr_symbol_size); break; case money_base::sign: // Sign might not exist, or be more than one // character long. In that case, add in the rest // below. if (__sign_size) __res += __sign[0]; break; case money_base::value: __res += __value; break; case money_base::space: // At least one space is required, but if internal // formatting is required, an arbitrary number of // fill spaces will be necessary. if (__testipad) __res.append(__width - __len, __fill); else __res += __fill; break; case money_base::none: if (__testipad) __res.append(__width - __len, __fill); break; } } // Special case of multi-part sign parts. if (__sign_size > 1) __res.append(__sign + 1, __sign_size - 1); // Pad, if still necessary. __len = __res.size(); if (__width > __len) { if (__f == ios_base::left) // After. __res.append(__width - __len, __fill); else // Before. __res.insert(0, __width - __len, __fill); __len = __width; } // Write resulting, fully-formatted string to output iterator. __s = std::__write(__s, __res.data(), __len); } __io.width(0); return __s; } #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ \ && _GLIBCXX_USE_CXX11_ABI == 0 template _OutIter money_put<_CharT, _OutIter>:: __do_put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, double __units) const { return this->do_put(__s, __intl, __io, __fill, (long double) __units); } #endif template _OutIter money_put<_CharT, _OutIter>:: do_put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, long double __units) const { const locale __loc = __io.getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); #if _GLIBCXX_USE_C99_STDIO // First try a buffer perhaps big enough. int __cs_size = 64; char* __cs = static_cast(__builtin_alloca(__cs_size)); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 328. Bad sprintf format modifier in money_put<>::do_put() int __len = std::__convert_from_v(_S_get_c_locale(), __cs, __cs_size, "%.*Lf", 0, __units); // If the buffer was not large enough, try again with the correct size. if (__len >= __cs_size) { __cs_size = __len + 1; __cs = static_cast(__builtin_alloca(__cs_size)); __len = std::__convert_from_v(_S_get_c_locale(), __cs, __cs_size, "%.*Lf", 0, __units); } #else // max_exponent10 + 1 for the integer part, + 2 for sign and '\0'. const int __cs_size = __gnu_cxx::__numeric_traits::__max_exponent10 + 3; char* __cs = static_cast(__builtin_alloca(__cs_size)); int __len = std::__convert_from_v(_S_get_c_locale(), __cs, 0, "%.*Lf", 0, __units); #endif string_type __digits(__len, char_type()); __ctype.widen(__cs, __cs + __len, &__digits[0]); return __intl ? _M_insert(__s, __io, __fill, __digits) : _M_insert(__s, __io, __fill, __digits); } template _OutIter money_put<_CharT, _OutIter>:: do_put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, const string_type& __digits) const { return __intl ? _M_insert(__s, __io, __fill, __digits) : _M_insert(__s, __io, __fill, __digits); } _GLIBCXX_END_NAMESPACE_LDBL_OR_CXX11 // NB: Not especially useful. Without an ios_base object or some // kind of locale reference, we are left clawing at the air where // the side of the mountain used to be... template time_base::dateorder time_get<_CharT, _InIter>::do_date_order() const { return time_base::no_order; } // Expand a strftime format string and parse it. E.g., do_get_date() may // pass %m/%d/%Y => extracted characters. template _InIter time_get<_CharT, _InIter>:: _M_extract_via_format(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm, const _CharT* __format) const { const locale& __loc = __io._M_getloc(); const __timepunct<_CharT>& __tp = use_facet<__timepunct<_CharT> >(__loc); const ctype<_CharT>& __ctype = use_facet >(__loc); const size_t __len = char_traits<_CharT>::length(__format); ios_base::iostate __tmperr = ios_base::goodbit; size_t __i = 0; for (; __beg != __end && __i < __len && !__tmperr; ++__i) { if (__ctype.narrow(__format[__i], 0) == '%') { // Verify valid formatting code, attempt to extract. char __c = __ctype.narrow(__format[++__i], 0); int __mem = 0; if (__c == 'E' || __c == 'O') __c = __ctype.narrow(__format[++__i], 0); switch (__c) { const char* __cs; _CharT __wcs[10]; case 'a': // Abbreviated weekday name [tm_wday] const char_type* __days1[7]; __tp._M_days_abbreviated(__days1); __beg = _M_extract_name(__beg, __end, __mem, __days1, 7, __io, __tmperr); if (!__tmperr) __tm->tm_wday = __mem; break; case 'A': // Weekday name [tm_wday]. const char_type* __days2[7]; __tp._M_days(__days2); __beg = _M_extract_name(__beg, __end, __mem, __days2, 7, __io, __tmperr); if (!__tmperr) __tm->tm_wday = __mem; break; case 'h': case 'b': // Abbreviated month name [tm_mon] const char_type* __months1[12]; __tp._M_months_abbreviated(__months1); __beg = _M_extract_name(__beg, __end, __mem, __months1, 12, __io, __tmperr); if (!__tmperr) __tm->tm_mon = __mem; break; case 'B': // Month name [tm_mon]. const char_type* __months2[12]; __tp._M_months(__months2); __beg = _M_extract_name(__beg, __end, __mem, __months2, 12, __io, __tmperr); if (!__tmperr) __tm->tm_mon = __mem; break; case 'c': // Default time and date representation. const char_type* __dt[2]; __tp._M_date_time_formats(__dt); __beg = _M_extract_via_format(__beg, __end, __io, __tmperr, __tm, __dt[0]); break; case 'd': // Day [01, 31]. [tm_mday] __beg = _M_extract_num(__beg, __end, __mem, 1, 31, 2, __io, __tmperr); if (!__tmperr) __tm->tm_mday = __mem; break; case 'e': // Day [1, 31], with single digits preceded by // space. [tm_mday] if (__ctype.is(ctype_base::space, *__beg)) __beg = _M_extract_num(++__beg, __end, __mem, 1, 9, 1, __io, __tmperr); else __beg = _M_extract_num(__beg, __end, __mem, 10, 31, 2, __io, __tmperr); if (!__tmperr) __tm->tm_mday = __mem; break; case 'D': // Equivalent to %m/%d/%y.[tm_mon, tm_mday, tm_year] __cs = "%m/%d/%y"; __ctype.widen(__cs, __cs + 9, __wcs); __beg = _M_extract_via_format(__beg, __end, __io, __tmperr, __tm, __wcs); break; case 'H': // Hour [00, 23]. [tm_hour] __beg = _M_extract_num(__beg, __end, __mem, 0, 23, 2, __io, __tmperr); if (!__tmperr) __tm->tm_hour = __mem; break; case 'I': // Hour [01, 12]. [tm_hour] __beg = _M_extract_num(__beg, __end, __mem, 1, 12, 2, __io, __tmperr); if (!__tmperr) __tm->tm_hour = __mem; break; case 'm': // Month [01, 12]. [tm_mon] __beg = _M_extract_num(__beg, __end, __mem, 1, 12, 2, __io, __tmperr); if (!__tmperr) __tm->tm_mon = __mem - 1; break; case 'M': // Minute [00, 59]. [tm_min] __beg = _M_extract_num(__beg, __end, __mem, 0, 59, 2, __io, __tmperr); if (!__tmperr) __tm->tm_min = __mem; break; case 'n': if (__ctype.narrow(*__beg, 0) == '\n') ++__beg; else __tmperr |= ios_base::failbit; break; case 'R': // Equivalent to (%H:%M). __cs = "%H:%M"; __ctype.widen(__cs, __cs + 6, __wcs); __beg = _M_extract_via_format(__beg, __end, __io, __tmperr, __tm, __wcs); break; case 'S': // Seconds. [tm_sec] // [00, 60] in C99 (one leap-second), [00, 61] in C89. #if _GLIBCXX_USE_C99 __beg = _M_extract_num(__beg, __end, __mem, 0, 60, 2, #else __beg = _M_extract_num(__beg, __end, __mem, 0, 61, 2, #endif __io, __tmperr); if (!__tmperr) __tm->tm_sec = __mem; break; case 't': if (__ctype.narrow(*__beg, 0) == '\t') ++__beg; else __tmperr |= ios_base::failbit; break; case 'T': // Equivalent to (%H:%M:%S). __cs = "%H:%M:%S"; __ctype.widen(__cs, __cs + 9, __wcs); __beg = _M_extract_via_format(__beg, __end, __io, __tmperr, __tm, __wcs); break; case 'x': // Locale's date. const char_type* __dates[2]; __tp._M_date_formats(__dates); __beg = _M_extract_via_format(__beg, __end, __io, __tmperr, __tm, __dates[0]); break; case 'X': // Locale's time. const char_type* __times[2]; __tp._M_time_formats(__times); __beg = _M_extract_via_format(__beg, __end, __io, __tmperr, __tm, __times[0]); break; case 'y': case 'C': // C99 // Two digit year. case 'Y': // Year [1900). // NB: We parse either two digits, implicitly years since // 1900, or 4 digits, full year. In both cases we can // reconstruct [tm_year]. See also libstdc++/26701. __beg = _M_extract_num(__beg, __end, __mem, 0, 9999, 4, __io, __tmperr); if (!__tmperr) __tm->tm_year = __mem < 0 ? __mem + 100 : __mem - 1900; break; case 'Z': // Timezone info. if (__ctype.is(ctype_base::upper, *__beg)) { int __tmp; __beg = _M_extract_name(__beg, __end, __tmp, __timepunct_cache<_CharT>::_S_timezones, 14, __io, __tmperr); // GMT requires special effort. if (__beg != __end && !__tmperr && __tmp == 0 && (*__beg == __ctype.widen('-') || *__beg == __ctype.widen('+'))) { __beg = _M_extract_num(__beg, __end, __tmp, 0, 23, 2, __io, __tmperr); __beg = _M_extract_num(__beg, __end, __tmp, 0, 59, 2, __io, __tmperr); } } else __tmperr |= ios_base::failbit; break; default: // Not recognized. __tmperr |= ios_base::failbit; } } else { // Verify format and input match, extract and discard. if (__format[__i] == *__beg) ++__beg; else __tmperr |= ios_base::failbit; } } if (__tmperr || __i != __len) __err |= ios_base::failbit; return __beg; } template _InIter time_get<_CharT, _InIter>:: _M_extract_num(iter_type __beg, iter_type __end, int& __member, int __min, int __max, size_t __len, ios_base& __io, ios_base::iostate& __err) const { const locale& __loc = __io._M_getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); // As-is works for __len = 1, 2, 4, the values actually used. int __mult = __len == 2 ? 10 : (__len == 4 ? 1000 : 1); ++__min; size_t __i = 0; int __value = 0; for (; __beg != __end && __i < __len; ++__beg, (void)++__i) { const char __c = __ctype.narrow(*__beg, '*'); if (__c >= '0' && __c <= '9') { __value = __value * 10 + (__c - '0'); const int __valuec = __value * __mult; if (__valuec > __max || __valuec + __mult < __min) break; __mult /= 10; } else break; } if (__i == __len) __member = __value; // Special encoding for do_get_year, 'y', and 'Y' above. else if (__len == 4 && __i == 2) __member = __value - 100; else __err |= ios_base::failbit; return __beg; } // Assumptions: // All elements in __names are unique. template _InIter time_get<_CharT, _InIter>:: _M_extract_name(iter_type __beg, iter_type __end, int& __member, const _CharT** __names, size_t __indexlen, ios_base& __io, ios_base::iostate& __err) const { typedef char_traits<_CharT> __traits_type; const locale& __loc = __io._M_getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); int* __matches = static_cast(__builtin_alloca(sizeof(int) * __indexlen)); size_t __nmatches = 0; size_t __pos = 0; bool __testvalid = true; const char_type* __name; // Look for initial matches. // NB: Some of the locale data is in the form of all lowercase // names, and some is in the form of initially-capitalized // names. Look for both. if (__beg != __end) { const char_type __c = *__beg; for (size_t __i1 = 0; __i1 < __indexlen; ++__i1) if (__c == __names[__i1][0] || __c == __ctype.toupper(__names[__i1][0])) __matches[__nmatches++] = __i1; } while (__nmatches > 1) { // Find smallest matching string. size_t __minlen = __traits_type::length(__names[__matches[0]]); for (size_t __i2 = 1; __i2 < __nmatches; ++__i2) __minlen = std::min(__minlen, __traits_type::length(__names[__matches[__i2]])); ++__beg; ++__pos; if (__pos < __minlen && __beg != __end) for (size_t __i3 = 0; __i3 < __nmatches;) { __name = __names[__matches[__i3]]; if (!(__name[__pos] == *__beg)) __matches[__i3] = __matches[--__nmatches]; else ++__i3; } else break; } if (__nmatches == 1) { // Make sure found name is completely extracted. ++__beg; ++__pos; __name = __names[__matches[0]]; const size_t __len = __traits_type::length(__name); while (__pos < __len && __beg != __end && __name[__pos] == *__beg) ++__beg, (void)++__pos; if (__len == __pos) __member = __matches[0]; else __testvalid = false; } else __testvalid = false; if (!__testvalid) __err |= ios_base::failbit; return __beg; } template _InIter time_get<_CharT, _InIter>:: _M_extract_wday_or_month(iter_type __beg, iter_type __end, int& __member, const _CharT** __names, size_t __indexlen, ios_base& __io, ios_base::iostate& __err) const { typedef char_traits<_CharT> __traits_type; const locale& __loc = __io._M_getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); int* __matches = static_cast(__builtin_alloca(2 * sizeof(int) * __indexlen)); size_t __nmatches = 0; size_t* __matches_lengths = 0; size_t __pos = 0; if (__beg != __end) { const char_type __c = *__beg; for (size_t __i = 0; __i < 2 * __indexlen; ++__i) if (__c == __names[__i][0] || __c == __ctype.toupper(__names[__i][0])) __matches[__nmatches++] = __i; } if (__nmatches) { ++__beg; ++__pos; __matches_lengths = static_cast(__builtin_alloca(sizeof(size_t) * __nmatches)); for (size_t __i = 0; __i < __nmatches; ++__i) __matches_lengths[__i] = __traits_type::length(__names[__matches[__i]]); } for (; __beg != __end; ++__beg, (void)++__pos) { size_t __nskipped = 0; const char_type __c = *__beg; for (size_t __i = 0; __i < __nmatches;) { const char_type* __name = __names[__matches[__i]]; if (__pos >= __matches_lengths[__i]) ++__nskipped, ++__i; else if (!(__name[__pos] == __c)) { --__nmatches; __matches[__i] = __matches[__nmatches]; __matches_lengths[__i] = __matches_lengths[__nmatches]; } else ++__i; } if (__nskipped == __nmatches) break; } if ((__nmatches == 1 && __matches_lengths[0] == __pos) || (__nmatches == 2 && (__matches_lengths[0] == __pos || __matches_lengths[1] == __pos))) __member = (__matches[0] >= __indexlen ? __matches[0] - __indexlen : __matches[0]); else __err |= ios_base::failbit; return __beg; } template _InIter time_get<_CharT, _InIter>:: do_get_time(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { const locale& __loc = __io._M_getloc(); const __timepunct<_CharT>& __tp = use_facet<__timepunct<_CharT> >(__loc); const char_type* __times[2]; __tp._M_time_formats(__times); __beg = _M_extract_via_format(__beg, __end, __io, __err, __tm, __times[0]); if (__beg == __end) __err |= ios_base::eofbit; return __beg; } template _InIter time_get<_CharT, _InIter>:: do_get_date(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { const locale& __loc = __io._M_getloc(); const __timepunct<_CharT>& __tp = use_facet<__timepunct<_CharT> >(__loc); const char_type* __dates[2]; __tp._M_date_formats(__dates); __beg = _M_extract_via_format(__beg, __end, __io, __err, __tm, __dates[0]); if (__beg == __end) __err |= ios_base::eofbit; return __beg; } template _InIter time_get<_CharT, _InIter>:: do_get_weekday(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { const locale& __loc = __io._M_getloc(); const __timepunct<_CharT>& __tp = use_facet<__timepunct<_CharT> >(__loc); const char_type* __days[14]; __tp._M_days_abbreviated(__days); __tp._M_days(__days + 7); int __tmpwday; ios_base::iostate __tmperr = ios_base::goodbit; __beg = _M_extract_wday_or_month(__beg, __end, __tmpwday, __days, 7, __io, __tmperr); if (!__tmperr) __tm->tm_wday = __tmpwday; else __err |= ios_base::failbit; if (__beg == __end) __err |= ios_base::eofbit; return __beg; } template _InIter time_get<_CharT, _InIter>:: do_get_monthname(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { const locale& __loc = __io._M_getloc(); const __timepunct<_CharT>& __tp = use_facet<__timepunct<_CharT> >(__loc); const char_type* __months[24]; __tp._M_months_abbreviated(__months); __tp._M_months(__months + 12); int __tmpmon; ios_base::iostate __tmperr = ios_base::goodbit; __beg = _M_extract_wday_or_month(__beg, __end, __tmpmon, __months, 12, __io, __tmperr); if (!__tmperr) __tm->tm_mon = __tmpmon; else __err |= ios_base::failbit; if (__beg == __end) __err |= ios_base::eofbit; return __beg; } template _InIter time_get<_CharT, _InIter>:: do_get_year(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { int __tmpyear; ios_base::iostate __tmperr = ios_base::goodbit; __beg = _M_extract_num(__beg, __end, __tmpyear, 0, 9999, 4, __io, __tmperr); if (!__tmperr) __tm->tm_year = __tmpyear < 0 ? __tmpyear + 100 : __tmpyear - 1900; else __err |= ios_base::failbit; if (__beg == __end) __err |= ios_base::eofbit; return __beg; } #if __cplusplus >= 201103L template inline _InIter time_get<_CharT, _InIter>:: get(iter_type __s, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm, const char_type* __fmt, const char_type* __fmtend) const { const locale& __loc = __io._M_getloc(); ctype<_CharT> const& __ctype = use_facet >(__loc); __err = ios_base::goodbit; while (__fmt != __fmtend && __err == ios_base::goodbit) { if (__s == __end) { __err = ios_base::eofbit | ios_base::failbit; break; } else if (__ctype.narrow(*__fmt, 0) == '%') { char __format; char __mod = 0; if (++__fmt == __fmtend) { __err = ios_base::failbit; break; } const char __c = __ctype.narrow(*__fmt, 0); if (__c != 'E' && __c != 'O') __format = __c; else if (++__fmt != __fmtend) { __mod = __c; __format = __ctype.narrow(*__fmt, 0); } else { __err = ios_base::failbit; break; } __s = this->do_get(__s, __end, __io, __err, __tm, __format, __mod); ++__fmt; } else if (__ctype.is(ctype_base::space, *__fmt)) { ++__fmt; while (__fmt != __fmtend && __ctype.is(ctype_base::space, *__fmt)) ++__fmt; while (__s != __end && __ctype.is(ctype_base::space, *__s)) ++__s; } // TODO real case-insensitive comparison else if (__ctype.tolower(*__s) == __ctype.tolower(*__fmt) || __ctype.toupper(*__s) == __ctype.toupper(*__fmt)) { ++__s; ++__fmt; } else { __err = ios_base::failbit; break; } } return __s; } template inline _InIter time_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm, char __format, char __mod) const { const locale& __loc = __io._M_getloc(); ctype<_CharT> const& __ctype = use_facet >(__loc); __err = ios_base::goodbit; char_type __fmt[4]; __fmt[0] = __ctype.widen('%'); if (!__mod) { __fmt[1] = __format; __fmt[2] = char_type(); } else { __fmt[1] = __mod; __fmt[2] = __format; __fmt[3] = char_type(); } __beg = _M_extract_via_format(__beg, __end, __io, __err, __tm, __fmt); if (__beg == __end) __err |= ios_base::eofbit; return __beg; } #endif // __cplusplus >= 201103L template _OutIter time_put<_CharT, _OutIter>:: put(iter_type __s, ios_base& __io, char_type __fill, const tm* __tm, const _CharT* __beg, const _CharT* __end) const { const locale& __loc = __io._M_getloc(); ctype<_CharT> const& __ctype = use_facet >(__loc); for (; __beg != __end; ++__beg) if (__ctype.narrow(*__beg, 0) != '%') { *__s = *__beg; ++__s; } else if (++__beg != __end) { char __format; char __mod = 0; const char __c = __ctype.narrow(*__beg, 0); if (__c != 'E' && __c != 'O') __format = __c; else if (++__beg != __end) { __mod = __c; __format = __ctype.narrow(*__beg, 0); } else break; __s = this->do_put(__s, __io, __fill, __tm, __format, __mod); } else break; return __s; } template _OutIter time_put<_CharT, _OutIter>:: do_put(iter_type __s, ios_base& __io, char_type, const tm* __tm, char __format, char __mod) const { const locale& __loc = __io._M_getloc(); ctype<_CharT> const& __ctype = use_facet >(__loc); __timepunct<_CharT> const& __tp = use_facet<__timepunct<_CharT> >(__loc); // NB: This size is arbitrary. Should this be a data member, // initialized at construction? const size_t __maxlen = 128; char_type __res[__maxlen]; // NB: In IEE 1003.1-200x, and perhaps other locale models, it // is possible that the format character will be longer than one // character. Possibilities include 'E' or 'O' followed by a // format character: if __mod is not the default argument, assume // it's a valid modifier. char_type __fmt[4]; __fmt[0] = __ctype.widen('%'); if (!__mod) { __fmt[1] = __format; __fmt[2] = char_type(); } else { __fmt[1] = __mod; __fmt[2] = __format; __fmt[3] = char_type(); } __tp._M_put(__res, __maxlen, __fmt, __tm); // Write resulting, fully-formatted string to output iterator. return std::__write(__s, __res, char_traits::length(__res)); } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class moneypunct; extern template class moneypunct; extern template class moneypunct_byname; extern template class moneypunct_byname; extern template class _GLIBCXX_NAMESPACE_LDBL_OR_CXX11 money_get; extern template class _GLIBCXX_NAMESPACE_LDBL_OR_CXX11 money_put; extern template class __timepunct; extern template class time_put; extern template class time_put_byname; extern template class time_get; extern template class time_get_byname; extern template class messages; extern template class messages_byname; extern template const moneypunct& use_facet >(const locale&); extern template const moneypunct& use_facet >(const locale&); extern template const money_put& use_facet >(const locale&); extern template const money_get& use_facet >(const locale&); extern template const __timepunct& use_facet<__timepunct >(const locale&); extern template const time_put& use_facet >(const locale&); extern template const time_get& use_facet >(const locale&); extern template const messages& use_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet<__timepunct >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); #ifdef _GLIBCXX_USE_WCHAR_T extern template class moneypunct; extern template class moneypunct; extern template class moneypunct_byname; extern template class moneypunct_byname; extern template class _GLIBCXX_NAMESPACE_LDBL_OR_CXX11 money_get; extern template class _GLIBCXX_NAMESPACE_LDBL_OR_CXX11 money_put; extern template class __timepunct; extern template class time_put; extern template class time_put_byname; extern template class time_get; extern template class time_get_byname; extern template class messages; extern template class messages_byname; extern template const moneypunct& use_facet >(const locale&); extern template const moneypunct& use_facet >(const locale&); extern template const money_put& use_facet >(const locale&); extern template const money_get& use_facet >(const locale&); extern template const __timepunct& use_facet<__timepunct >(const locale&); extern template const time_put& use_facet >(const locale&); extern template const time_get& use_facet >(const locale&); extern template const messages& use_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet<__timepunct >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!Q8/bits/localefwd.hnu[// Forward declarations -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/localefwd.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.1 Locales // #ifndef _LOCALE_FWD_H #define _LOCALE_FWD_H 1 #pragma GCC system_header #include #include // Defines __c_locale, config-specific include #include // For ostreambuf_iterator, istreambuf_iterator #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup locales Locales * * Classes and functions for internationalization and localization. */ // 22.1.1 Locale class locale; template bool has_facet(const locale&) throw(); template const _Facet& use_facet(const locale&); // 22.1.3 Convenience interfaces template bool isspace(_CharT, const locale&); template bool isprint(_CharT, const locale&); template bool iscntrl(_CharT, const locale&); template bool isupper(_CharT, const locale&); template bool islower(_CharT, const locale&); template bool isalpha(_CharT, const locale&); template bool isdigit(_CharT, const locale&); template bool ispunct(_CharT, const locale&); template bool isxdigit(_CharT, const locale&); template bool isalnum(_CharT, const locale&); template bool isgraph(_CharT, const locale&); #if __cplusplus >= 201103L template bool isblank(_CharT, const locale&); #endif template _CharT toupper(_CharT, const locale&); template _CharT tolower(_CharT, const locale&); // 22.2.1 and 22.2.1.3 ctype class ctype_base; template class ctype; template<> class ctype; #ifdef _GLIBCXX_USE_WCHAR_T template<> class ctype; #endif template class ctype_byname; // NB: Specialized for char and wchar_t in locale_facets.h. class codecvt_base; template class codecvt; template<> class codecvt; #ifdef _GLIBCXX_USE_WCHAR_T template<> class codecvt; #endif template class codecvt_byname; // 22.2.2 and 22.2.3 numeric _GLIBCXX_BEGIN_NAMESPACE_LDBL template > class num_get; template > class num_put; _GLIBCXX_END_NAMESPACE_LDBL _GLIBCXX_BEGIN_NAMESPACE_CXX11 template class numpunct; template class numpunct_byname; _GLIBCXX_END_NAMESPACE_CXX11 _GLIBCXX_BEGIN_NAMESPACE_CXX11 // 22.2.4 collation template class collate; template class collate_byname; _GLIBCXX_END_NAMESPACE_CXX11 // 22.2.5 date and time class time_base; _GLIBCXX_BEGIN_NAMESPACE_CXX11 template > class time_get; template > class time_get_byname; _GLIBCXX_END_NAMESPACE_CXX11 template > class time_put; template > class time_put_byname; // 22.2.6 money class money_base; _GLIBCXX_BEGIN_NAMESPACE_LDBL_OR_CXX11 template > class money_get; template > class money_put; _GLIBCXX_END_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_BEGIN_NAMESPACE_CXX11 template class moneypunct; template class moneypunct_byname; _GLIBCXX_END_NAMESPACE_CXX11 // 22.2.7 message retrieval class messages_base; _GLIBCXX_BEGIN_NAMESPACE_CXX11 template class messages; template class messages_byname; _GLIBCXX_END_NAMESPACE_CXX11 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!"8/bits/mask_array.hnu[// The template and inlines for the -*- C++ -*- mask_array class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/mask_array.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _MASK_ARRAY_H #define _MASK_ARRAY_H 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup numeric_arrays * @{ */ /** * @brief Reference to selected subset of an array. * * A mask_array is a reference to the actual elements of an array specified * by a bitmask in the form of an array of bool. The way to get a * mask_array is to call operator[](valarray) on a valarray. The * returned mask_array then permits carrying operations out on the * referenced subset of elements in the original valarray. * * For example, if a mask_array is obtained using the array (false, true, * false, true) as an argument, the mask array has two elements referring * to array[1] and array[3] in the underlying array. * * @param Tp Element type. */ template class mask_array { public: typedef _Tp value_type; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 253. valarray helper functions are almost entirely useless /// Copy constructor. Both slices refer to the same underlying array. mask_array (const mask_array&); /// Assignment operator. Assigns elements to corresponding elements /// of @a a. mask_array& operator=(const mask_array&); void operator=(const valarray<_Tp>&) const; /// Multiply slice elements by corresponding elements of @a v. void operator*=(const valarray<_Tp>&) const; /// Divide slice elements by corresponding elements of @a v. void operator/=(const valarray<_Tp>&) const; /// Modulo slice elements by corresponding elements of @a v. void operator%=(const valarray<_Tp>&) const; /// Add corresponding elements of @a v to slice elements. void operator+=(const valarray<_Tp>&) const; /// Subtract corresponding elements of @a v from slice elements. void operator-=(const valarray<_Tp>&) const; /// Logical xor slice elements with corresponding elements of @a v. void operator^=(const valarray<_Tp>&) const; /// Logical and slice elements with corresponding elements of @a v. void operator&=(const valarray<_Tp>&) const; /// Logical or slice elements with corresponding elements of @a v. void operator|=(const valarray<_Tp>&) const; /// Left shift slice elements by corresponding elements of @a v. void operator<<=(const valarray<_Tp>&) const; /// Right shift slice elements by corresponding elements of @a v. void operator>>=(const valarray<_Tp>&) const; /// Assign all slice elements to @a t. void operator=(const _Tp&) const; // ~mask_array (); template void operator=(const _Expr<_Dom,_Tp>&) const; template void operator*=(const _Expr<_Dom,_Tp>&) const; template void operator/=(const _Expr<_Dom,_Tp>&) const; template void operator%=(const _Expr<_Dom,_Tp>&) const; template void operator+=(const _Expr<_Dom,_Tp>&) const; template void operator-=(const _Expr<_Dom,_Tp>&) const; template void operator^=(const _Expr<_Dom,_Tp>&) const; template void operator&=(const _Expr<_Dom,_Tp>&) const; template void operator|=(const _Expr<_Dom,_Tp>&) const; template void operator<<=(const _Expr<_Dom,_Tp>&) const; template void operator>>=(const _Expr<_Dom,_Tp>&) const; private: mask_array(_Array<_Tp>, size_t, _Array); friend class valarray<_Tp>; const size_t _M_sz; const _Array _M_mask; const _Array<_Tp> _M_array; // not implemented mask_array(); }; template inline mask_array<_Tp>::mask_array(const mask_array<_Tp>& __a) : _M_sz(__a._M_sz), _M_mask(__a._M_mask), _M_array(__a._M_array) {} template inline mask_array<_Tp>::mask_array(_Array<_Tp> __a, size_t __s, _Array __m) : _M_sz(__s), _M_mask(__m), _M_array(__a) {} template inline mask_array<_Tp>& mask_array<_Tp>::operator=(const mask_array<_Tp>& __a) { std::__valarray_copy(__a._M_array, __a._M_mask, _M_sz, _M_array, _M_mask); return *this; } template inline void mask_array<_Tp>::operator=(const _Tp& __t) const { std::__valarray_fill(_M_array, _M_sz, _M_mask, __t); } template inline void mask_array<_Tp>::operator=(const valarray<_Tp>& __v) const { std::__valarray_copy(_Array<_Tp>(__v), __v.size(), _M_array, _M_mask); } template template inline void mask_array<_Tp>::operator=(const _Expr<_Ex, _Tp>& __e) const { std::__valarray_copy(__e, __e.size(), _M_array, _M_mask); } #undef _DEFINE_VALARRAY_OPERATOR #define _DEFINE_VALARRAY_OPERATOR(_Op, _Name) \ template \ inline void \ mask_array<_Tp>::operator _Op##=(const valarray<_Tp>& __v) const \ { \ _Array_augmented_##_Name(_M_array, _M_mask, \ _Array<_Tp>(__v), __v.size()); \ } \ \ template \ template \ inline void \ mask_array<_Tp>::operator _Op##=(const _Expr<_Dom, _Tp>& __e) const\ { \ _Array_augmented_##_Name(_M_array, _M_mask, __e, __e.size()); \ } _DEFINE_VALARRAY_OPERATOR(*, __multiplies) _DEFINE_VALARRAY_OPERATOR(/, __divides) _DEFINE_VALARRAY_OPERATOR(%, __modulus) _DEFINE_VALARRAY_OPERATOR(+, __plus) _DEFINE_VALARRAY_OPERATOR(-, __minus) _DEFINE_VALARRAY_OPERATOR(^, __bitwise_xor) _DEFINE_VALARRAY_OPERATOR(&, __bitwise_and) _DEFINE_VALARRAY_OPERATOR(|, __bitwise_or) _DEFINE_VALARRAY_OPERATOR(<<, __shift_left) _DEFINE_VALARRAY_OPERATOR(>>, __shift_right) #undef _DEFINE_VALARRAY_OPERATOR // @} group numeric_arrays _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _MASK_ARRAY_H */ PK! 8/bits/memoryfwd.hnu[// Forward declarations -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * Copyright (c) 1996-1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/memoryfwd.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _MEMORYFWD_H #define _MEMORYFWD_H 1 #pragma GCC system_header #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup allocators Allocators * @ingroup memory * * Classes encapsulating memory operations. * * @{ */ template class allocator; template<> class allocator; #if __cplusplus >= 201103L /// Declare uses_allocator so it can be specialized in \ etc. template struct uses_allocator; #endif /// @} group memory _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!mΦ 8/bits/move.hnu[// Move, forward and identity for C++11 + swap -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/move.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{utility} */ #ifndef _MOVE_H #define _MOVE_H 1 #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Used, in C++03 mode too, by allocators, etc. /** * @brief Same as C++11 std::addressof * @ingroup utilities */ template inline _GLIBCXX_CONSTEXPR _Tp* __addressof(_Tp& __r) _GLIBCXX_NOEXCEPT { return __builtin_addressof(__r); } #if __cplusplus >= 201103L _GLIBCXX_END_NAMESPACE_VERSION } // namespace #include // Brings in std::declval too. namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup utilities * @{ */ /** * @brief Forward an lvalue. * @return The parameter cast to the specified type. * * This function is used to implement "perfect forwarding". */ template constexpr _Tp&& forward(typename std::remove_reference<_Tp>::type& __t) noexcept { return static_cast<_Tp&&>(__t); } /** * @brief Forward an rvalue. * @return The parameter cast to the specified type. * * This function is used to implement "perfect forwarding". */ template constexpr _Tp&& forward(typename std::remove_reference<_Tp>::type&& __t) noexcept { static_assert(!std::is_lvalue_reference<_Tp>::value, "template argument" " substituting _Tp is an lvalue reference type"); return static_cast<_Tp&&>(__t); } /** * @brief Convert a value to an rvalue. * @param __t A thing of arbitrary type. * @return The parameter cast to an rvalue-reference to allow moving it. */ template constexpr typename std::remove_reference<_Tp>::type&& move(_Tp&& __t) noexcept { return static_cast::type&&>(__t); } template struct __move_if_noexcept_cond : public __and_<__not_>, is_copy_constructible<_Tp>>::type { }; /** * @brief Conditionally convert a value to an rvalue. * @param __x A thing of arbitrary type. * @return The parameter, possibly cast to an rvalue-reference. * * Same as std::move unless the type's move constructor could throw and the * type is copyable, in which case an lvalue-reference is returned instead. */ template constexpr typename conditional<__move_if_noexcept_cond<_Tp>::value, const _Tp&, _Tp&&>::type move_if_noexcept(_Tp& __x) noexcept { return std::move(__x); } // declval, from type_traits. #if __cplusplus > 201402L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2296. std::addressof should be constexpr # define __cpp_lib_addressof_constexpr 201603 #endif /** * @brief Returns the actual address of the object or function * referenced by r, even in the presence of an overloaded * operator&. * @param __r Reference to an object or function. * @return The actual address. */ template inline _GLIBCXX17_CONSTEXPR _Tp* addressof(_Tp& __r) noexcept { return std::__addressof(__r); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2598. addressof works on temporaries template const _Tp* addressof(const _Tp&&) = delete; // C++11 version of std::exchange for internal use. template inline _Tp __exchange(_Tp& __obj, _Up&& __new_val) { _Tp __old_val = std::move(__obj); __obj = std::forward<_Up>(__new_val); return __old_val; } /// @} group utilities #define _GLIBCXX_MOVE(__val) std::move(__val) #define _GLIBCXX_FORWARD(_Tp, __val) std::forward<_Tp>(__val) #else #define _GLIBCXX_MOVE(__val) (__val) #define _GLIBCXX_FORWARD(_Tp, __val) (__val) #endif /** * @addtogroup utilities * @{ */ /** * @brief Swaps two values. * @param __a A thing of arbitrary type. * @param __b Another thing of arbitrary type. * @return Nothing. */ template inline #if __cplusplus >= 201103L typename enable_if<__and_<__not_<__is_tuple_like<_Tp>>, is_move_constructible<_Tp>, is_move_assignable<_Tp>>::value>::type swap(_Tp& __a, _Tp& __b) noexcept(__and_, is_nothrow_move_assignable<_Tp>>::value) #else void swap(_Tp& __a, _Tp& __b) #endif { // concept requirements __glibcxx_function_requires(_SGIAssignableConcept<_Tp>) _Tp __tmp = _GLIBCXX_MOVE(__a); __a = _GLIBCXX_MOVE(__b); __b = _GLIBCXX_MOVE(__tmp); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 809. std::swap should be overloaded for array types. /// Swap the contents of two arrays. template inline #if __cplusplus >= 201103L typename enable_if<__is_swappable<_Tp>::value>::type swap(_Tp (&__a)[_Nm], _Tp (&__b)[_Nm]) noexcept(__is_nothrow_swappable<_Tp>::value) #else void swap(_Tp (&__a)[_Nm], _Tp (&__b)[_Nm]) #endif { for (size_t __n = 0; __n < _Nm; ++__n) swap(__a[__n], __b[__n]); } /// @} group utilities _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _MOVE_H */ PK!8/bits/nested_exception.hnu[// Nested Exception support header (nested_exception class) for -*- C++ -*- // Copyright (C) 2009-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/nested_exception.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{exception} */ #ifndef _GLIBCXX_NESTED_EXCEPTION_H #define _GLIBCXX_NESTED_EXCEPTION_H 1 #pragma GCC visibility push(default) #if __cplusplus < 201103L # include #else #include #include extern "C++" { namespace std { /** * @addtogroup exceptions * @{ */ /// Exception class with exception_ptr data member. class nested_exception { exception_ptr _M_ptr; public: nested_exception() noexcept : _M_ptr(current_exception()) { } nested_exception(const nested_exception&) noexcept = default; nested_exception& operator=(const nested_exception&) noexcept = default; virtual ~nested_exception() noexcept; [[noreturn]] void rethrow_nested() const { if (_M_ptr) rethrow_exception(_M_ptr); std::terminate(); } exception_ptr nested_ptr() const noexcept { return _M_ptr; } }; template struct _Nested_exception : public _Except, public nested_exception { explicit _Nested_exception(const _Except& __ex) : _Except(__ex) { } explicit _Nested_exception(_Except&& __ex) : _Except(static_cast<_Except&&>(__ex)) { } }; // [except.nested]/8 // Throw an exception of unspecified type that is publicly derived from // both remove_reference_t<_Tp> and nested_exception. template [[noreturn]] inline void __throw_with_nested_impl(_Tp&& __t, true_type) { using _Up = typename remove_reference<_Tp>::type; throw _Nested_exception<_Up>{std::forward<_Tp>(__t)}; } template [[noreturn]] inline void __throw_with_nested_impl(_Tp&& __t, false_type) { throw std::forward<_Tp>(__t); } /// If @p __t is derived from nested_exception, throws @p __t. /// Else, throws an implementation-defined object derived from both. template [[noreturn]] inline void throw_with_nested(_Tp&& __t) { using _Up = typename decay<_Tp>::type; using _CopyConstructible = __and_, is_move_constructible<_Up>>; static_assert(_CopyConstructible::value, "throw_with_nested argument must be CopyConstructible"); using __nest = __and_, __bool_constant, __not_>>; std::__throw_with_nested_impl(std::forward<_Tp>(__t), __nest{}); } // Determine if dynamic_cast would be well-formed. template using __rethrow_if_nested_cond = typename enable_if< __and_, __or_<__not_>, is_convertible<_Tp*, nested_exception*>>>::value >::type; // Attempt dynamic_cast to nested_exception and call rethrow_nested(). template inline __rethrow_if_nested_cond<_Ex> __rethrow_if_nested_impl(const _Ex* __ptr) { if (auto __ne_ptr = dynamic_cast(__ptr)) __ne_ptr->rethrow_nested(); } // Otherwise, no effects. inline void __rethrow_if_nested_impl(const void*) { } /// If @p __ex is derived from nested_exception, @p __ex.rethrow_nested(). template inline void rethrow_if_nested(const _Ex& __ex) { std::__rethrow_if_nested_impl(std::__addressof(__ex)); } // @} group exceptions } // namespace std } // extern "C++" #endif // C++11 #pragma GCC visibility pop #endif // _GLIBCXX_NESTED_EXCEPTION_H PK!@J  8/bits/node_handle.hnu[// Node handles for containers -*- C++ -*- // Copyright (C) 2016-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/node_handle.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. * @headername{map,set,unordered_map,unordered_set} */ #ifndef _NODE_HANDLE #define _NODE_HANDLE 1 #pragma GCC system_header #if __cplusplus > 201402L # define __cpp_lib_node_extract 201606 #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /// Base class for node handle types of maps and sets. template class _Node_handle_common { using _AllocTraits = allocator_traits<_NodeAlloc>; public: using allocator_type = __alloc_rebind<_NodeAlloc, _Val>; allocator_type get_allocator() const noexcept { __glibcxx_assert(!this->empty()); return allocator_type(*_M_alloc); } explicit operator bool() const noexcept { return _M_ptr != nullptr; } [[nodiscard]] bool empty() const noexcept { return _M_ptr == nullptr; } protected: constexpr _Node_handle_common() noexcept : _M_ptr(), _M_alloc() {} ~_Node_handle_common() { _M_destroy(); } _Node_handle_common(_Node_handle_common&& __nh) noexcept : _M_ptr(__nh._M_ptr), _M_alloc(std::move(__nh._M_alloc)) { __nh._M_ptr = nullptr; __nh._M_alloc = nullopt; } _Node_handle_common& operator=(_Node_handle_common&& __nh) noexcept { _M_destroy(); _M_ptr = __nh._M_ptr; if constexpr (is_move_assignable_v<_NodeAlloc>) { if (_AllocTraits::propagate_on_container_move_assignment::value || !this->_M_alloc) this->_M_alloc = std::move(__nh._M_alloc); else { __glibcxx_assert(this->_M_alloc == __nh._M_alloc); } } else { __glibcxx_assert(_M_alloc); } __nh._M_ptr = nullptr; __nh._M_alloc = nullopt; return *this; } _Node_handle_common(typename _AllocTraits::pointer __ptr, const _NodeAlloc& __alloc) : _M_ptr(__ptr), _M_alloc(__alloc) { } void _M_swap(_Node_handle_common& __nh) noexcept { using std::swap; swap(_M_ptr, __nh._M_ptr); if (_AllocTraits::propagate_on_container_swap::value || !_M_alloc || !__nh._M_alloc) _M_alloc.swap(__nh._M_alloc); else { __glibcxx_assert(_M_alloc == __nh._M_alloc); } } private: void _M_destroy() noexcept { if (_M_ptr != nullptr) { allocator_type __alloc(*_M_alloc); allocator_traits::destroy(__alloc, _M_ptr->_M_valptr()); _AllocTraits::deallocate(*_M_alloc, _M_ptr, 1); } } protected: typename _AllocTraits::pointer _M_ptr; private: optional<_NodeAlloc> _M_alloc; template friend class _Rb_tree; }; /// Node handle type for maps. template class _Node_handle : public _Node_handle_common<_Value, _NodeAlloc> { public: constexpr _Node_handle() noexcept = default; ~_Node_handle() = default; _Node_handle(_Node_handle&&) noexcept = default; _Node_handle& operator=(_Node_handle&&) noexcept = default; using key_type = _Key; using mapped_type = typename _Value::second_type; key_type& key() const noexcept { __glibcxx_assert(!this->empty()); return *_M_pkey; } mapped_type& mapped() const noexcept { __glibcxx_assert(!this->empty()); return *_M_pmapped; } void swap(_Node_handle& __nh) noexcept { this->_M_swap(__nh); using std::swap; swap(_M_pkey, __nh._M_pkey); swap(_M_pmapped, __nh._M_pmapped); } friend void swap(_Node_handle& __x, _Node_handle& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } private: using _AllocTraits = allocator_traits<_NodeAlloc>; _Node_handle(typename _AllocTraits::pointer __ptr, const _NodeAlloc& __alloc) : _Node_handle_common<_Value, _NodeAlloc>(__ptr, __alloc) { if (__ptr) { auto& __key = const_cast<_Key&>(__ptr->_M_valptr()->first); _M_pkey = _S_pointer_to(__key); _M_pmapped = _S_pointer_to(__ptr->_M_valptr()->second); } else { _M_pkey = nullptr; _M_pmapped = nullptr; } } template using __pointer = __ptr_rebind>; __pointer<_Key> _M_pkey = nullptr; __pointer _M_pmapped = nullptr; template __pointer<_Tp> _S_pointer_to(_Tp& __obj) { return pointer_traits<__pointer<_Tp>>::pointer_to(__obj); } const key_type& _M_key() const noexcept { return key(); } template friend class _Rb_tree; template friend class _Hashtable; }; /// Node handle type for sets. template class _Node_handle<_Value, _Value, _NodeAlloc> : public _Node_handle_common<_Value, _NodeAlloc> { public: constexpr _Node_handle() noexcept = default; ~_Node_handle() = default; _Node_handle(_Node_handle&&) noexcept = default; _Node_handle& operator=(_Node_handle&&) noexcept = default; using value_type = _Value; value_type& value() const noexcept { __glibcxx_assert(!this->empty()); return *this->_M_ptr->_M_valptr(); } void swap(_Node_handle& __nh) noexcept { this->_M_swap(__nh); } friend void swap(_Node_handle& __x, _Node_handle& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } private: using _AllocTraits = allocator_traits<_NodeAlloc>; _Node_handle(typename _AllocTraits::pointer __ptr, const _NodeAlloc& __alloc) : _Node_handle_common<_Value, _NodeAlloc>(__ptr, __alloc) { } const value_type& _M_key() const noexcept { return value(); } template friend class _Rb_tree; template friend class _Hashtable; }; /// Return type of insert(node_handle&&) on unique maps/sets. template struct _Node_insert_return { _Iterator position = _Iterator(); bool inserted = false; _NodeHandle node; }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++17 #endif PK!@1X008/bits/ostream.tccnu[// ostream classes -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/ostream.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ostream} */ // // ISO C++ 14882: 27.6.2 Output streams // #ifndef _OSTREAM_TCC #define _OSTREAM_TCC 1 #pragma GCC system_header #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template basic_ostream<_CharT, _Traits>::sentry:: sentry(basic_ostream<_CharT, _Traits>& __os) : _M_ok(false), _M_os(__os) { // XXX MT if (__os.tie() && __os.good()) __os.tie()->flush(); if (__os.good()) _M_ok = true; else __os.setstate(ios_base::failbit); } template template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: _M_insert(_ValueT __v) { sentry __cerb(*this); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { const __num_put_type& __np = __check_facet(this->_M_num_put); if (__np.put(*this, *this, this->fill(), __v).failed()) __err |= ios_base::badbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: operator<<(short __n) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 117. basic_ostream uses nonexistent num_put member functions. const ios_base::fmtflags __fmt = this->flags() & ios_base::basefield; if (__fmt == ios_base::oct || __fmt == ios_base::hex) return _M_insert(static_cast(static_cast(__n))); else return _M_insert(static_cast(__n)); } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: operator<<(int __n) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 117. basic_ostream uses nonexistent num_put member functions. const ios_base::fmtflags __fmt = this->flags() & ios_base::basefield; if (__fmt == ios_base::oct || __fmt == ios_base::hex) return _M_insert(static_cast(static_cast(__n))); else return _M_insert(static_cast(__n)); } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: operator<<(__streambuf_type* __sbin) { ios_base::iostate __err = ios_base::goodbit; sentry __cerb(*this); if (__cerb && __sbin) { __try { if (!__copy_streambufs(__sbin, this->rdbuf())) __err |= ios_base::failbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::failbit); } } else if (!__sbin) __err |= ios_base::badbit; if (__err) this->setstate(__err); return *this; } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: put(char_type __c) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 60. What is a formatted input function? // basic_ostream::put(char_type) is an unformatted output function. // DR 63. Exception-handling policy for unformatted output. // Unformatted output functions should catch exceptions thrown // from streambuf members. sentry __cerb(*this); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { const int_type __put = this->rdbuf()->sputc(__c); if (traits_type::eq_int_type(__put, traits_type::eof())) __err |= ios_base::badbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: write(const _CharT* __s, streamsize __n) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 60. What is a formatted input function? // basic_ostream::write(const char_type*, streamsize) is an // unformatted output function. // DR 63. Exception-handling policy for unformatted output. // Unformatted output functions should catch exceptions thrown // from streambuf members. sentry __cerb(*this); if (__cerb) { __try { _M_write(__s, __n); } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } } return *this; } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: flush() { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 60. What is a formatted input function? // basic_ostream::flush() is *not* an unformatted output function. ios_base::iostate __err = ios_base::goodbit; __try { if (this->rdbuf() && this->rdbuf()->pubsync() == -1) __err |= ios_base::badbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); return *this; } template typename basic_ostream<_CharT, _Traits>::pos_type basic_ostream<_CharT, _Traits>:: tellp() { pos_type __ret = pos_type(-1); __try { if (!this->fail()) __ret = this->rdbuf()->pubseekoff(0, ios_base::cur, ios_base::out); } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } return __ret; } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: seekp(pos_type __pos) { ios_base::iostate __err = ios_base::goodbit; __try { if (!this->fail()) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 136. seekp, seekg setting wrong streams? const pos_type __p = this->rdbuf()->pubseekpos(__pos, ios_base::out); // 129. Need error indication from seekp() and seekg() if (__p == pos_type(off_type(-1))) __err |= ios_base::failbit; } } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); return *this; } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: seekp(off_type __off, ios_base::seekdir __dir) { ios_base::iostate __err = ios_base::goodbit; __try { if (!this->fail()) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 136. seekp, seekg setting wrong streams? const pos_type __p = this->rdbuf()->pubseekoff(__off, __dir, ios_base::out); // 129. Need error indication from seekp() and seekg() if (__p == pos_type(off_type(-1))) __err |= ios_base::failbit; } } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); return *this; } template basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __out, const char* __s) { if (!__s) __out.setstate(ios_base::badbit); else { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 167. Improper use of traits_type::length() const size_t __clen = char_traits::length(__s); __try { struct __ptr_guard { _CharT *__p; __ptr_guard (_CharT *__ip): __p(__ip) { } ~__ptr_guard() { delete[] __p; } _CharT* __get() { return __p; } } __pg (new _CharT[__clen]); _CharT *__ws = __pg.__get(); for (size_t __i = 0; __i < __clen; ++__i) __ws[__i] = __out.widen(__s[__i]); __ostream_insert(__out, __ws, __clen); } __catch(__cxxabiv1::__forced_unwind&) { __out._M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { __out._M_setstate(ios_base::badbit); } } return __out; } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class basic_ostream; extern template ostream& endl(ostream&); extern template ostream& ends(ostream&); extern template ostream& flush(ostream&); extern template ostream& operator<<(ostream&, char); extern template ostream& operator<<(ostream&, unsigned char); extern template ostream& operator<<(ostream&, signed char); extern template ostream& operator<<(ostream&, const char*); extern template ostream& operator<<(ostream&, const unsigned char*); extern template ostream& operator<<(ostream&, const signed char*); extern template ostream& ostream::_M_insert(long); extern template ostream& ostream::_M_insert(unsigned long); extern template ostream& ostream::_M_insert(bool); #ifdef _GLIBCXX_USE_LONG_LONG extern template ostream& ostream::_M_insert(long long); extern template ostream& ostream::_M_insert(unsigned long long); #endif extern template ostream& ostream::_M_insert(double); extern template ostream& ostream::_M_insert(long double); extern template ostream& ostream::_M_insert(const void*); #ifdef _GLIBCXX_USE_WCHAR_T extern template class basic_ostream; extern template wostream& endl(wostream&); extern template wostream& ends(wostream&); extern template wostream& flush(wostream&); extern template wostream& operator<<(wostream&, wchar_t); extern template wostream& operator<<(wostream&, char); extern template wostream& operator<<(wostream&, const wchar_t*); extern template wostream& operator<<(wostream&, const char*); extern template wostream& wostream::_M_insert(long); extern template wostream& wostream::_M_insert(unsigned long); extern template wostream& wostream::_M_insert(bool); #ifdef _GLIBCXX_USE_LONG_LONG extern template wostream& wostream::_M_insert(long long); extern template wostream& wostream::_M_insert(unsigned long long); #endif extern template wostream& wostream::_M_insert(double); extern template wostream& wostream::_M_insert(long double); extern template wostream& wostream::_M_insert(const void*); #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!j8/bits/ostream_insert.hnu[// Helpers for ostream inserters -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/ostream_insert.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ostream} */ #ifndef _OSTREAM_INSERT_H #define _OSTREAM_INSERT_H 1 #pragma GCC system_header #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template inline void __ostream_write(basic_ostream<_CharT, _Traits>& __out, const _CharT* __s, streamsize __n) { typedef basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const streamsize __put = __out.rdbuf()->sputn(__s, __n); if (__put != __n) __out.setstate(__ios_base::badbit); } template inline void __ostream_fill(basic_ostream<_CharT, _Traits>& __out, streamsize __n) { typedef basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const _CharT __c = __out.fill(); for (; __n > 0; --__n) { const typename _Traits::int_type __put = __out.rdbuf()->sputc(__c); if (_Traits::eq_int_type(__put, _Traits::eof())) { __out.setstate(__ios_base::badbit); break; } } } template basic_ostream<_CharT, _Traits>& __ostream_insert(basic_ostream<_CharT, _Traits>& __out, const _CharT* __s, streamsize __n) { typedef basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; typename __ostream_type::sentry __cerb(__out); if (__cerb) { __try { const streamsize __w = __out.width(); if (__w > __n) { const bool __left = ((__out.flags() & __ios_base::adjustfield) == __ios_base::left); if (!__left) __ostream_fill(__out, __w - __n); if (__out.good()) __ostream_write(__out, __s, __n); if (__left && __out.good()) __ostream_fill(__out, __w - __n); } else __ostream_write(__out, __s, __n); __out.width(0); } __catch(__cxxabiv1::__forced_unwind&) { __out._M_setstate(__ios_base::badbit); __throw_exception_again; } __catch(...) { __out._M_setstate(__ios_base::badbit); } } return __out; } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template ostream& __ostream_insert(ostream&, const char*, streamsize); #ifdef _GLIBCXX_USE_WCHAR_T extern template wostream& __ostream_insert(wostream&, const wchar_t*, streamsize); #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _OSTREAM_INSERT_H */ PK!3_[8/bits/parse_numbers.hnu[// Components for compile-time parsing of numbers -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/parse_numbers.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{chrono} */ #ifndef _GLIBCXX_PARSE_NUMBERS_H #define _GLIBCXX_PARSE_NUMBERS_H 1 #pragma GCC system_header // From n3642.pdf except I added binary literals and digit separator '\''. #if __cplusplus > 201103L #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __parse_int { template struct _Digit; template struct _Digit<_Base, '0'> : integral_constant { using __valid = true_type; }; template struct _Digit<_Base, '1'> : integral_constant { using __valid = true_type; }; template struct _Digit_impl : integral_constant { static_assert(_Base > _Val, "invalid digit"); using __valid = true_type; }; template struct _Digit<_Base, '2'> : _Digit_impl<_Base, 2> { }; template struct _Digit<_Base, '3'> : _Digit_impl<_Base, 3> { }; template struct _Digit<_Base, '4'> : _Digit_impl<_Base, 4> { }; template struct _Digit<_Base, '5'> : _Digit_impl<_Base, 5> { }; template struct _Digit<_Base, '6'> : _Digit_impl<_Base, 6> { }; template struct _Digit<_Base, '7'> : _Digit_impl<_Base, 7> { }; template struct _Digit<_Base, '8'> : _Digit_impl<_Base, 8> { }; template struct _Digit<_Base, '9'> : _Digit_impl<_Base, 9> { }; template struct _Digit<_Base, 'a'> : _Digit_impl<_Base, 0xa> { }; template struct _Digit<_Base, 'A'> : _Digit_impl<_Base, 0xa> { }; template struct _Digit<_Base, 'b'> : _Digit_impl<_Base, 0xb> { }; template struct _Digit<_Base, 'B'> : _Digit_impl<_Base, 0xb> { }; template struct _Digit<_Base, 'c'> : _Digit_impl<_Base, 0xc> { }; template struct _Digit<_Base, 'C'> : _Digit_impl<_Base, 0xc> { }; template struct _Digit<_Base, 'd'> : _Digit_impl<_Base, 0xd> { }; template struct _Digit<_Base, 'D'> : _Digit_impl<_Base, 0xd> { }; template struct _Digit<_Base, 'e'> : _Digit_impl<_Base, 0xe> { }; template struct _Digit<_Base, 'E'> : _Digit_impl<_Base, 0xe> { }; template struct _Digit<_Base, 'f'> : _Digit_impl<_Base, 0xf> { }; template struct _Digit<_Base, 'F'> : _Digit_impl<_Base, 0xf> { }; // Digit separator template struct _Digit<_Base, '\''> : integral_constant { using __valid = false_type; }; //------------------------------------------------------------------------------ template using __ull_constant = integral_constant; template struct _Power_help { using __next = typename _Power_help<_Base, _Digs...>::type; using __valid_digit = typename _Digit<_Base, _Dig>::__valid; using type = __ull_constant<__next::value * (__valid_digit{} ? _Base : 1ULL)>; }; template struct _Power_help<_Base, _Dig> { using __valid_digit = typename _Digit<_Base, _Dig>::__valid; using type = __ull_constant<__valid_digit::value>; }; template struct _Power : _Power_help<_Base, _Digs...>::type { }; template struct _Power<_Base> : __ull_constant<0> { }; //------------------------------------------------------------------------------ template struct _Number_help { using __digit = _Digit<_Base, _Dig>; using __valid_digit = typename __digit::__valid; using __next = _Number_help<_Base, __valid_digit::value ? _Pow / _Base : _Pow, _Digs...>; using type = __ull_constant<_Pow * __digit::value + __next::type::value>; static_assert((type::value / _Pow) == __digit::value, "integer literal does not fit in unsigned long long"); }; // Skip past digit separators: template struct _Number_help<_Base, _Pow, '\'', _Dig, _Digs...> : _Number_help<_Base, _Pow, _Dig, _Digs...> { }; // Terminating case for recursion: template struct _Number_help<_Base, 1ULL, _Dig> { using type = __ull_constant<_Digit<_Base, _Dig>::value>; }; template struct _Number : _Number_help<_Base, _Power<_Base, _Digs...>::value, _Digs...>::type { }; template struct _Number<_Base> : __ull_constant<0> { }; //------------------------------------------------------------------------------ template struct _Parse_int; template struct _Parse_int<'0', 'b', _Digs...> : _Number<2U, _Digs...>::type { }; template struct _Parse_int<'0', 'B', _Digs...> : _Number<2U, _Digs...>::type { }; template struct _Parse_int<'0', 'x', _Digs...> : _Number<16U, _Digs...>::type { }; template struct _Parse_int<'0', 'X', _Digs...> : _Number<16U, _Digs...>::type { }; template struct _Parse_int<'0', _Digs...> : _Number<8U, _Digs...>::type { }; template struct _Parse_int : _Number<10U, _Digs...>::type { }; } // namespace __parse_int namespace __select_int { template struct _Select_int_base; template struct _Select_int_base<_Val, _IntType, _Ints...> : conditional_t<(_Val <= std::numeric_limits<_IntType>::max()), integral_constant<_IntType, _Val>, _Select_int_base<_Val, _Ints...>> { }; template struct _Select_int_base<_Val> { }; template using _Select_int = typename _Select_int_base< __parse_int::_Parse_int<_Digs...>::value, unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long >::type; } // namespace __select_int _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // __cplusplus > 201103L #endif // _GLIBCXX_PARSE_NUMBERS_H PK!L@  8/bits/postypes.hnu[// Position types -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/postypes.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iosfwd} */ // // ISO C++ 14882: 27.4.1 - Types // ISO C++ 14882: 27.4.3 - Template class fpos // #ifndef _GLIBCXX_POSTYPES_H #define _GLIBCXX_POSTYPES_H 1 #pragma GCC system_header #include // For mbstate_t // XXX If is really needed, make sure to define the macros // before including it, in order not to break (and // in C++11). Reconsider all this as soon as possible... #if (defined(_GLIBCXX_HAVE_INT64_T) && !defined(_GLIBCXX_HAVE_INT64_T_LONG) \ && !defined(_GLIBCXX_HAVE_INT64_T_LONG_LONG)) #ifndef __STDC_LIMIT_MACROS # define _UNDEF__STDC_LIMIT_MACROS # define __STDC_LIMIT_MACROS #endif #ifndef __STDC_CONSTANT_MACROS # define _UNDEF__STDC_CONSTANT_MACROS # define __STDC_CONSTANT_MACROS #endif #include // For int64_t #ifdef _UNDEF__STDC_LIMIT_MACROS # undef __STDC_LIMIT_MACROS # undef _UNDEF__STDC_LIMIT_MACROS #endif #ifdef _UNDEF__STDC_CONSTANT_MACROS # undef __STDC_CONSTANT_MACROS # undef _UNDEF__STDC_CONSTANT_MACROS #endif #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // The types streamoff, streampos and wstreampos and the class // template fpos<> are described in clauses 21.1.2, 21.1.3, 27.1.2, // 27.2, 27.4.1, 27.4.3 and D.6. Despite all this verbiage, the // behaviour of these types is mostly implementation defined or // unspecified. The behaviour in this implementation is as noted // below. /** * @brief Type used by fpos, char_traits, and char_traits. * * In clauses 21.1.3.1 and 27.4.1 streamoff is described as an * implementation defined type. * Note: In versions of GCC up to and including GCC 3.3, streamoff * was typedef long. */ #ifdef _GLIBCXX_HAVE_INT64_T_LONG typedef long streamoff; #elif defined(_GLIBCXX_HAVE_INT64_T_LONG_LONG) typedef long long streamoff; #elif defined(_GLIBCXX_HAVE_INT64_T) typedef int64_t streamoff; #else typedef long long streamoff; #endif /// Integral type for I/O operation counts and buffer sizes. typedef ptrdiff_t streamsize; // Signed integral type /** * @brief Class representing stream positions. * * The standard places no requirements upon the template parameter StateT. * In this implementation StateT must be DefaultConstructible, * CopyConstructible and Assignable. The standard only requires that fpos * should contain a member of type StateT. In this implementation it also * contains an offset stored as a signed integer. * * @param StateT Type passed to and returned from state(). */ template class fpos { private: streamoff _M_off; _StateT _M_state; public: // The standard doesn't require that fpos objects can be default // constructed. This implementation provides a default // constructor that initializes the offset to 0 and default // constructs the state. fpos() : _M_off(0), _M_state() { } // The standard requires that fpos objects can be constructed // from streamoff objects using the constructor syntax, and // fails to give any meaningful semantics. In this // implementation implicit conversion is also allowed, and this // constructor stores the streamoff as the offset and default // constructs the state. /// Construct position from offset. fpos(streamoff __off) : _M_off(__off), _M_state() { } /// Convert to streamoff. operator streamoff() const { return _M_off; } /// Remember the value of @a st. void state(_StateT __st) { _M_state = __st; } /// Return the last set value of @a st. _StateT state() const { return _M_state; } // The standard requires that this operator must be defined, but // gives no semantics. In this implementation it just adds its // argument to the stored offset and returns *this. /// Add offset to this position. fpos& operator+=(streamoff __off) { _M_off += __off; return *this; } // The standard requires that this operator must be defined, but // gives no semantics. In this implementation it just subtracts // its argument from the stored offset and returns *this. /// Subtract offset from this position. fpos& operator-=(streamoff __off) { _M_off -= __off; return *this; } // The standard requires that this operator must be defined, but // defines its semantics only in terms of operator-. In this // implementation it constructs a copy of *this, adds the // argument to that copy using operator+= and then returns the // copy. /// Add position and offset. fpos operator+(streamoff __off) const { fpos __pos(*this); __pos += __off; return __pos; } // The standard requires that this operator must be defined, but // defines its semantics only in terms of operator+. In this // implementation it constructs a copy of *this, subtracts the // argument from that copy using operator-= and then returns the // copy. /// Subtract offset from position. fpos operator-(streamoff __off) const { fpos __pos(*this); __pos -= __off; return __pos; } // The standard requires that this operator must be defined, but // defines its semantics only in terms of operator+. In this // implementation it returns the difference between the offset // stored in *this and in the argument. /// Subtract position to return offset. streamoff operator-(const fpos& __other) const { return _M_off - __other._M_off; } }; // The standard only requires that operator== must be an // equivalence relation. In this implementation two fpos // objects belong to the same equivalence class if the contained // offsets compare equal. /// Test if equivalent to another position. template inline bool operator==(const fpos<_StateT>& __lhs, const fpos<_StateT>& __rhs) { return streamoff(__lhs) == streamoff(__rhs); } template inline bool operator!=(const fpos<_StateT>& __lhs, const fpos<_StateT>& __rhs) { return streamoff(__lhs) != streamoff(__rhs); } // Clauses 21.1.3.1 and 21.1.3.2 describe streampos and wstreampos // as implementation defined types, but clause 27.2 requires that // they must both be typedefs for fpos /// File position for char streams. typedef fpos streampos; /// File position for wchar_t streams. typedef fpos wstreampos; #if __cplusplus >= 201103L /// File position for char16_t streams. typedef fpos u16streampos; /// File position for char32_t streams. typedef fpos u32streampos; #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!UN{#{#8/bits/predefined_ops.hnu[// Default predicates for internal use -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file predefined_ops.h * This is an internal header file, included by other library headers. * You should not attempt to use it directly. @headername{algorithm} */ #ifndef _GLIBCXX_PREDEFINED_OPS_H #define _GLIBCXX_PREDEFINED_OPS_H 1 namespace __gnu_cxx { namespace __ops { struct _Iter_less_iter { template _GLIBCXX14_CONSTEXPR bool operator()(_Iterator1 __it1, _Iterator2 __it2) const { return *__it1 < *__it2; } }; _GLIBCXX14_CONSTEXPR inline _Iter_less_iter __iter_less_iter() { return _Iter_less_iter(); } struct _Iter_less_val { #if __cplusplus >= 201103L constexpr _Iter_less_val() = default; #else _Iter_less_val() { } #endif explicit _Iter_less_val(_Iter_less_iter) { } template bool operator()(_Iterator __it, _Value& __val) const { return *__it < __val; } }; inline _Iter_less_val __iter_less_val() { return _Iter_less_val(); } inline _Iter_less_val __iter_comp_val(_Iter_less_iter) { return _Iter_less_val(); } struct _Val_less_iter { #if __cplusplus >= 201103L constexpr _Val_less_iter() = default; #else _Val_less_iter() { } #endif explicit _Val_less_iter(_Iter_less_iter) { } template bool operator()(_Value& __val, _Iterator __it) const { return __val < *__it; } }; inline _Val_less_iter __val_less_iter() { return _Val_less_iter(); } inline _Val_less_iter __val_comp_iter(_Iter_less_iter) { return _Val_less_iter(); } struct _Iter_equal_to_iter { template bool operator()(_Iterator1 __it1, _Iterator2 __it2) const { return *__it1 == *__it2; } }; inline _Iter_equal_to_iter __iter_equal_to_iter() { return _Iter_equal_to_iter(); } struct _Iter_equal_to_val { template bool operator()(_Iterator __it, _Value& __val) const { return *__it == __val; } }; inline _Iter_equal_to_val __iter_equal_to_val() { return _Iter_equal_to_val(); } inline _Iter_equal_to_val __iter_comp_val(_Iter_equal_to_iter) { return _Iter_equal_to_val(); } template struct _Iter_comp_iter { _Compare _M_comp; explicit _GLIBCXX14_CONSTEXPR _Iter_comp_iter(_Compare __comp) : _M_comp(_GLIBCXX_MOVE(__comp)) { } template _GLIBCXX14_CONSTEXPR bool operator()(_Iterator1 __it1, _Iterator2 __it2) { return bool(_M_comp(*__it1, *__it2)); } }; template _GLIBCXX14_CONSTEXPR inline _Iter_comp_iter<_Compare> __iter_comp_iter(_Compare __comp) { return _Iter_comp_iter<_Compare>(_GLIBCXX_MOVE(__comp)); } template struct _Iter_comp_val { _Compare _M_comp; explicit _Iter_comp_val(_Compare __comp) : _M_comp(_GLIBCXX_MOVE(__comp)) { } explicit _Iter_comp_val(const _Iter_comp_iter<_Compare>& __comp) : _M_comp(__comp._M_comp) { } #if __cplusplus >= 201103L explicit _Iter_comp_val(_Iter_comp_iter<_Compare>&& __comp) : _M_comp(std::move(__comp._M_comp)) { } #endif template bool operator()(_Iterator __it, _Value& __val) { return bool(_M_comp(*__it, __val)); } }; template inline _Iter_comp_val<_Compare> __iter_comp_val(_Compare __comp) { return _Iter_comp_val<_Compare>(_GLIBCXX_MOVE(__comp)); } template inline _Iter_comp_val<_Compare> __iter_comp_val(_Iter_comp_iter<_Compare> __comp) { return _Iter_comp_val<_Compare>(_GLIBCXX_MOVE(__comp)); } template struct _Val_comp_iter { _Compare _M_comp; explicit _Val_comp_iter(_Compare __comp) : _M_comp(_GLIBCXX_MOVE(__comp)) { } explicit _Val_comp_iter(const _Iter_comp_iter<_Compare>& __comp) : _M_comp(__comp._M_comp) { } #if __cplusplus >= 201103L explicit _Val_comp_iter(_Iter_comp_iter<_Compare>&& __comp) : _M_comp(std::move(__comp._M_comp)) { } #endif template bool operator()(_Value& __val, _Iterator __it) { return bool(_M_comp(__val, *__it)); } }; template inline _Val_comp_iter<_Compare> __val_comp_iter(_Compare __comp) { return _Val_comp_iter<_Compare>(_GLIBCXX_MOVE(__comp)); } template inline _Val_comp_iter<_Compare> __val_comp_iter(_Iter_comp_iter<_Compare> __comp) { return _Val_comp_iter<_Compare>(_GLIBCXX_MOVE(__comp)); } template struct _Iter_equals_val { _Value& _M_value; explicit _Iter_equals_val(_Value& __value) : _M_value(__value) { } template bool operator()(_Iterator __it) { return *__it == _M_value; } }; template inline _Iter_equals_val<_Value> __iter_equals_val(_Value& __val) { return _Iter_equals_val<_Value>(__val); } template struct _Iter_equals_iter { _Iterator1 _M_it1; explicit _Iter_equals_iter(_Iterator1 __it1) : _M_it1(__it1) { } template bool operator()(_Iterator2 __it2) { return *__it2 == *_M_it1; } }; template inline _Iter_equals_iter<_Iterator> __iter_comp_iter(_Iter_equal_to_iter, _Iterator __it) { return _Iter_equals_iter<_Iterator>(__it); } template struct _Iter_pred { _Predicate _M_pred; explicit _Iter_pred(_Predicate __pred) : _M_pred(_GLIBCXX_MOVE(__pred)) { } template bool operator()(_Iterator __it) { return bool(_M_pred(*__it)); } }; template inline _Iter_pred<_Predicate> __pred_iter(_Predicate __pred) { return _Iter_pred<_Predicate>(_GLIBCXX_MOVE(__pred)); } template struct _Iter_comp_to_val { _Compare _M_comp; _Value& _M_value; _Iter_comp_to_val(_Compare __comp, _Value& __value) : _M_comp(_GLIBCXX_MOVE(__comp)), _M_value(__value) { } template bool operator()(_Iterator __it) { return bool(_M_comp(*__it, _M_value)); } }; template _Iter_comp_to_val<_Compare, _Value> __iter_comp_val(_Compare __comp, _Value &__val) { return _Iter_comp_to_val<_Compare, _Value>(_GLIBCXX_MOVE(__comp), __val); } template struct _Iter_comp_to_iter { _Compare _M_comp; _Iterator1 _M_it1; _Iter_comp_to_iter(_Compare __comp, _Iterator1 __it1) : _M_comp(_GLIBCXX_MOVE(__comp)), _M_it1(__it1) { } template bool operator()(_Iterator2 __it2) { return bool(_M_comp(*__it2, *_M_it1)); } }; template inline _Iter_comp_to_iter<_Compare, _Iterator> __iter_comp_iter(_Iter_comp_iter<_Compare> __comp, _Iterator __it) { return _Iter_comp_to_iter<_Compare, _Iterator>( _GLIBCXX_MOVE(__comp._M_comp), __it); } template struct _Iter_negate { _Predicate _M_pred; explicit _Iter_negate(_Predicate __pred) : _M_pred(_GLIBCXX_MOVE(__pred)) { } template bool operator()(_Iterator __it) { return !bool(_M_pred(*__it)); } }; template inline _Iter_negate<_Predicate> __negate(_Iter_pred<_Predicate> __pred) { return _Iter_negate<_Predicate>(_GLIBCXX_MOVE(__pred._M_pred)); } } // namespace __ops } // namespace __gnu_cxx #endif PK!qA8/bits/ptr_traits.hnu[// Pointer Traits -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/ptr_traits.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _PTR_TRAITS_H #define _PTR_TRAITS_H 1 #if __cplusplus >= 201103L #include #if __cplusplus > 201703L namespace __gnu_debug { struct _Safe_iterator_base; } #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION class __undefined; // Given Template return T, otherwise invalid. template struct __get_first_arg { using type = __undefined; }; template class _Template, typename _Tp, typename... _Types> struct __get_first_arg<_Template<_Tp, _Types...>> { using type = _Tp; }; template using __get_first_arg_t = typename __get_first_arg<_Tp>::type; // Given Template and U return Template, otherwise invalid. template struct __replace_first_arg { }; template class _Template, typename _Up, typename _Tp, typename... _Types> struct __replace_first_arg<_Template<_Tp, _Types...>, _Up> { using type = _Template<_Up, _Types...>; }; template using __replace_first_arg_t = typename __replace_first_arg<_Tp, _Up>::type; template using __make_not_void = typename conditional::value, __undefined, _Tp>::type; /** * @brief Uniform interface to all pointer-like types * @ingroup pointer_abstractions */ template struct pointer_traits { private: template using __element_type = typename _Tp::element_type; template using __difference_type = typename _Tp::difference_type; template struct __rebind : __replace_first_arg<_Tp, _Up> { }; template struct __rebind<_Tp, _Up, __void_t>> { using type = typename _Tp::template rebind<_Up>; }; public: /// The pointer type. using pointer = _Ptr; /// The type pointed to. using element_type = __detected_or_t<__get_first_arg_t<_Ptr>, __element_type, _Ptr>; /// The type used to represent the difference between two pointers. using difference_type = __detected_or_t; /// A pointer to a different type. template using rebind = typename __rebind<_Ptr, _Up>::type; static _Ptr pointer_to(__make_not_void& __e) { return _Ptr::pointer_to(__e); } static_assert(!is_same::value, "pointer type defines element_type or is like SomePointer"); }; /** * @brief Partial specialization for built-in pointers. * @ingroup pointer_abstractions */ template struct pointer_traits<_Tp*> { /// The pointer type typedef _Tp* pointer; /// The type pointed to typedef _Tp element_type; /// Type used to represent the difference between two pointers typedef ptrdiff_t difference_type; template using rebind = _Up*; /** * @brief Obtain a pointer to an object * @param __r A reference to an object of type @c element_type * @return @c addressof(__r) */ static pointer pointer_to(__make_not_void& __r) noexcept { return std::addressof(__r); } }; /// Convenience alias for rebinding pointers. template using __ptr_rebind = typename pointer_traits<_Ptr>::template rebind<_Tp>; template constexpr _Tp* __to_address(_Tp* __ptr) noexcept { static_assert(!std::is_function<_Tp>::value, "not a function pointer"); return __ptr; } #if __cplusplus <= 201703L template constexpr typename std::pointer_traits<_Ptr>::element_type* __to_address(const _Ptr& __ptr) { return std::__to_address(__ptr.operator->()); } #else template constexpr auto __to_address(const _Ptr& __ptr) noexcept -> decltype(std::pointer_traits<_Ptr>::to_address(__ptr)) { return std::pointer_traits<_Ptr>::to_address(__ptr); } template constexpr auto __to_address(const _Ptr& __ptr, _None...) noexcept { if constexpr (is_base_of_v<__gnu_debug::_Safe_iterator_base, _Ptr>) return std::__to_address(__ptr.base().operator->()); else return std::__to_address(__ptr.operator->()); } /** * @brief Obtain address referenced by a pointer to an object * @param __ptr A pointer to an object * @return @c __ptr * @ingroup pointer_abstractions */ template constexpr _Tp* to_address(_Tp* __ptr) noexcept { return std::__to_address(__ptr); } /** * @brief Obtain address referenced by a pointer to an object * @param __ptr A pointer to an object * @return @c pointer_traits<_Ptr>::to_address(__ptr) if that expression is well-formed, otherwise @c to_address(__ptr.operator->()) * @ingroup pointer_abstractions */ template constexpr auto to_address(const _Ptr& __ptr) noexcept { return std::__to_address(__ptr); } #endif // C++2a _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif #endif PK!.c8/bits/quoted_string.hnu[// Helpers for quoted stream manipulators -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/quoted_string.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iomanip} */ #ifndef _GLIBCXX_QUOTED_STRING_H #define _GLIBCXX_QUOTED_STRING_H 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { /** * @brief Struct for delimited strings. */ template struct _Quoted_string { static_assert(is_reference<_String>::value || is_pointer<_String>::value, "String type must be pointer or reference"); _Quoted_string(_String __str, _CharT __del, _CharT __esc) : _M_string(__str), _M_delim{__del}, _M_escape{__esc} { } _Quoted_string& operator=(_Quoted_string&) = delete; _String _M_string; _CharT _M_delim; _CharT _M_escape; }; #if __cplusplus >= 201703L template struct _Quoted_string, _CharT> { _Quoted_string(basic_string_view<_CharT, _Traits> __str, _CharT __del, _CharT __esc) : _M_string(__str), _M_delim{__del}, _M_escape{__esc} { } _Quoted_string& operator=(_Quoted_string&) = delete; basic_string_view<_CharT, _Traits> _M_string; _CharT _M_delim; _CharT _M_escape; }; #endif // C++17 /** * @brief Inserter for quoted strings. * * _GLIBCXX_RESOLVE_LIB_DEFECTS * DR 2344 quoted()'s interaction with padding is unclear */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const _Quoted_string& __str) { std::basic_ostringstream<_CharT, _Traits> __ostr; __ostr << __str._M_delim; for (const _CharT* __c = __str._M_string; *__c; ++__c) { if (*__c == __str._M_delim || *__c == __str._M_escape) __ostr << __str._M_escape; __ostr << *__c; } __ostr << __str._M_delim; return __os << __ostr.str(); } /** * @brief Inserter for quoted strings. * * _GLIBCXX_RESOLVE_LIB_DEFECTS * DR 2344 quoted()'s interaction with padding is unclear */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const _Quoted_string<_String, _CharT>& __str) { std::basic_ostringstream<_CharT, _Traits> __ostr; __ostr << __str._M_delim; for (auto __c : __str._M_string) { if (__c == __str._M_delim || __c == __str._M_escape) __ostr << __str._M_escape; __ostr << __c; } __ostr << __str._M_delim; return __os << __ostr.str(); } /** * @brief Extractor for delimited strings. * The left and right delimiters can be different. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, const _Quoted_string&, _CharT>& __str) { _CharT __c; __is >> __c; if (!__is.good()) return __is; if (__c != __str._M_delim) { __is.unget(); __is >> __str._M_string; return __is; } __str._M_string.clear(); std::ios_base::fmtflags __flags = __is.flags(__is.flags() & ~std::ios_base::skipws); do { __is >> __c; if (!__is.good()) break; if (__c == __str._M_escape) { __is >> __c; if (!__is.good()) break; } else if (__c == __str._M_delim) break; __str._M_string += __c; } while (true); __is.setf(__flags); return __is; } } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif /* _GLIBCXX_QUOTED_STRING_H */ PK!j8/bits/random.hnu[// random number generation -*- C++ -*- // Copyright (C) 2009-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/random.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{random} */ #ifndef _RANDOM_H #define _RANDOM_H 1 #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // [26.4] Random number generation /** * @defgroup random Random Number Generation * @ingroup numerics * * A facility for generating random numbers on selected distributions. * @{ */ /** * @brief A function template for converting the output of a (integral) * uniform random number generator to a floatng point result in the range * [0-1). */ template _RealType generate_canonical(_UniformRandomNumberGenerator& __g); /* * Implementation-space details. */ namespace __detail { template (std::numeric_limits<_UIntType>::digits)> struct _Shift { static const _UIntType __value = 0; }; template struct _Shift<_UIntType, __w, true> { static const _UIntType __value = _UIntType(1) << __w; }; template struct _Select_uint_least_t { static_assert(__which < 0, /* needs to be dependent */ "sorry, would be too much trouble for a slow result"); }; template struct _Select_uint_least_t<__s, 4> { typedef unsigned int type; }; template struct _Select_uint_least_t<__s, 3> { typedef unsigned long type; }; template struct _Select_uint_least_t<__s, 2> { typedef unsigned long long type; }; #ifdef _GLIBCXX_USE_INT128 template struct _Select_uint_least_t<__s, 1> { typedef unsigned __int128 type; }; #endif // Assume a != 0, a < m, c < m, x < m. template= __m - 1), bool __schrage_ok = __m % __a < __m / __a> struct _Mod { typedef typename _Select_uint_least_t::type _Tp2; static _Tp __calc(_Tp __x) { return static_cast<_Tp>((_Tp2(__a) * __x + __c) % __m); } }; // Schrage. template struct _Mod<_Tp, __m, __a, __c, false, true> { static _Tp __calc(_Tp __x); }; // Special cases: // - for m == 2^n or m == 0, unsigned integer overflow is safe. // - a * (m - 1) + c fits in _Tp, there is no overflow. template struct _Mod<_Tp, __m, __a, __c, true, __s> { static _Tp __calc(_Tp __x) { _Tp __res = __a * __x + __c; if (__m) __res %= __m; return __res; } }; template inline _Tp __mod(_Tp __x) { return _Mod<_Tp, __m, __a, __c>::__calc(__x); } /* * An adaptor class for converting the output of any Generator into * the input for a specific Distribution. */ template struct _Adaptor { static_assert(std::is_floating_point<_DInputType>::value, "template argument must be a floating point type"); public: _Adaptor(_Engine& __g) : _M_g(__g) { } _DInputType min() const { return _DInputType(0); } _DInputType max() const { return _DInputType(1); } /* * Converts a value generated by the adapted random number generator * into a value in the input domain for the dependent random number * distribution. */ _DInputType operator()() { return std::generate_canonical<_DInputType, std::numeric_limits<_DInputType>::digits, _Engine>(_M_g); } private: _Engine& _M_g; }; } // namespace __detail /** * @addtogroup random_generators Random Number Generators * @ingroup random * * These classes define objects which provide random or pseudorandom * numbers, either from a discrete or a continuous interval. The * random number generator supplied as a part of this library are * all uniform random number generators which provide a sequence of * random number uniformly distributed over their range. * * A number generator is a function object with an operator() that * takes zero arguments and returns a number. * * A compliant random number generator must satisfy the following * requirements. * *
Random Number Generator Requirements
To be documented.
* * @{ */ /** * @brief A model of a linear congruential random number generator. * * A random number generator that produces pseudorandom numbers via * linear function: * @f[ * x_{i+1}\leftarrow(ax_{i} + c) \bmod m * @f] * * The template parameter @p _UIntType must be an unsigned integral type * large enough to store values up to (__m-1). If the template parameter * @p __m is 0, the modulus @p __m used is * std::numeric_limits<_UIntType>::max() plus 1. Otherwise, the template * parameters @p __a and @p __c must be less than @p __m. * * The size of the state is @f$1@f$. */ template class linear_congruential_engine { static_assert(std::is_unsigned<_UIntType>::value, "result_type must be an unsigned integral type"); static_assert(__m == 0u || (__a < __m && __c < __m), "template argument substituting __m out of bounds"); public: /** The type of the generated random value. */ typedef _UIntType result_type; /** The multiplier. */ static constexpr result_type multiplier = __a; /** An increment. */ static constexpr result_type increment = __c; /** The modulus. */ static constexpr result_type modulus = __m; static constexpr result_type default_seed = 1u; /** * @brief Constructs a %linear_congruential_engine random number * generator engine with seed @p __s. The default seed value * is 1. * * @param __s The initial seed value. */ explicit linear_congruential_engine(result_type __s = default_seed) { seed(__s); } /** * @brief Constructs a %linear_congruential_engine random number * generator engine seeded from the seed sequence @p __q. * * @param __q the seed sequence. */ template::value> ::type> explicit linear_congruential_engine(_Sseq& __q) { seed(__q); } /** * @brief Reseeds the %linear_congruential_engine random number generator * engine sequence to the seed @p __s. * * @param __s The new seed. */ void seed(result_type __s = default_seed); /** * @brief Reseeds the %linear_congruential_engine random number generator * engine * sequence using values from the seed sequence @p __q. * * @param __q the seed sequence. */ template typename std::enable_if::value>::type seed(_Sseq& __q); /** * @brief Gets the smallest possible value in the output range. * * The minimum depends on the @p __c parameter: if it is zero, the * minimum generated must be > 0, otherwise 0 is allowed. */ static constexpr result_type min() { return __c == 0u ? 1u : 0u; } /** * @brief Gets the largest possible value in the output range. */ static constexpr result_type max() { return __m - 1u; } /** * @brief Discard a sequence of random numbers. */ void discard(unsigned long long __z) { for (; __z != 0ULL; --__z) (*this)(); } /** * @brief Gets the next random number in the sequence. */ result_type operator()() { _M_x = __detail::__mod<_UIntType, __m, __a, __c>(_M_x); return _M_x; } /** * @brief Compares two linear congruential random number generator * objects of the same type for equality. * * @param __lhs A linear congruential random number generator object. * @param __rhs Another linear congruential random number generator * object. * * @returns true if the infinite sequences of generated values * would be equal, false otherwise. */ friend bool operator==(const linear_congruential_engine& __lhs, const linear_congruential_engine& __rhs) { return __lhs._M_x == __rhs._M_x; } /** * @brief Writes the textual representation of the state x(i) of x to * @p __os. * * @param __os The output stream. * @param __lcr A % linear_congruential_engine random number generator. * @returns __os. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::linear_congruential_engine<_UIntType1, __a1, __c1, __m1>& __lcr); /** * @brief Sets the state of the engine by reading its textual * representation from @p __is. * * The textual representation must have been previously written using * an output stream whose imbued locale and whose type's template * specialization arguments _CharT and _Traits were the same as those * of @p __is. * * @param __is The input stream. * @param __lcr A % linear_congruential_engine random number generator. * @returns __is. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::linear_congruential_engine<_UIntType1, __a1, __c1, __m1>& __lcr); private: _UIntType _M_x; }; /** * @brief Compares two linear congruential random number generator * objects of the same type for inequality. * * @param __lhs A linear congruential random number generator object. * @param __rhs Another linear congruential random number generator * object. * * @returns true if the infinite sequences of generated values * would be different, false otherwise. */ template inline bool operator!=(const std::linear_congruential_engine<_UIntType, __a, __c, __m>& __lhs, const std::linear_congruential_engine<_UIntType, __a, __c, __m>& __rhs) { return !(__lhs == __rhs); } /** * A generalized feedback shift register discrete random number generator. * * This algorithm avoids multiplication and division and is designed to be * friendly to a pipelined architecture. If the parameters are chosen * correctly, this generator will produce numbers with a very long period and * fairly good apparent entropy, although still not cryptographically strong. * * The best way to use this generator is with the predefined mt19937 class. * * This algorithm was originally invented by Makoto Matsumoto and * Takuji Nishimura. * * @tparam __w Word size, the number of bits in each element of * the state vector. * @tparam __n The degree of recursion. * @tparam __m The period parameter. * @tparam __r The separation point bit index. * @tparam __a The last row of the twist matrix. * @tparam __u The first right-shift tempering matrix parameter. * @tparam __d The first right-shift tempering matrix mask. * @tparam __s The first left-shift tempering matrix parameter. * @tparam __b The first left-shift tempering matrix mask. * @tparam __t The second left-shift tempering matrix parameter. * @tparam __c The second left-shift tempering matrix mask. * @tparam __l The second right-shift tempering matrix parameter. * @tparam __f Initialization multiplier. */ template class mersenne_twister_engine { static_assert(std::is_unsigned<_UIntType>::value, "result_type must be an unsigned integral type"); static_assert(1u <= __m && __m <= __n, "template argument substituting __m out of bounds"); static_assert(__r <= __w, "template argument substituting " "__r out of bound"); static_assert(__u <= __w, "template argument substituting " "__u out of bound"); static_assert(__s <= __w, "template argument substituting " "__s out of bound"); static_assert(__t <= __w, "template argument substituting " "__t out of bound"); static_assert(__l <= __w, "template argument substituting " "__l out of bound"); static_assert(__w <= std::numeric_limits<_UIntType>::digits, "template argument substituting __w out of bound"); static_assert(__a <= (__detail::_Shift<_UIntType, __w>::__value - 1), "template argument substituting __a out of bound"); static_assert(__b <= (__detail::_Shift<_UIntType, __w>::__value - 1), "template argument substituting __b out of bound"); static_assert(__c <= (__detail::_Shift<_UIntType, __w>::__value - 1), "template argument substituting __c out of bound"); static_assert(__d <= (__detail::_Shift<_UIntType, __w>::__value - 1), "template argument substituting __d out of bound"); static_assert(__f <= (__detail::_Shift<_UIntType, __w>::__value - 1), "template argument substituting __f out of bound"); public: /** The type of the generated random value. */ typedef _UIntType result_type; // parameter values static constexpr size_t word_size = __w; static constexpr size_t state_size = __n; static constexpr size_t shift_size = __m; static constexpr size_t mask_bits = __r; static constexpr result_type xor_mask = __a; static constexpr size_t tempering_u = __u; static constexpr result_type tempering_d = __d; static constexpr size_t tempering_s = __s; static constexpr result_type tempering_b = __b; static constexpr size_t tempering_t = __t; static constexpr result_type tempering_c = __c; static constexpr size_t tempering_l = __l; static constexpr result_type initialization_multiplier = __f; static constexpr result_type default_seed = 5489u; // constructors and member function explicit mersenne_twister_engine(result_type __sd = default_seed) { seed(__sd); } /** * @brief Constructs a %mersenne_twister_engine random number generator * engine seeded from the seed sequence @p __q. * * @param __q the seed sequence. */ template::value> ::type> explicit mersenne_twister_engine(_Sseq& __q) { seed(__q); } void seed(result_type __sd = default_seed); template typename std::enable_if::value>::type seed(_Sseq& __q); /** * @brief Gets the smallest possible value in the output range. */ static constexpr result_type min() { return 0; } /** * @brief Gets the largest possible value in the output range. */ static constexpr result_type max() { return __detail::_Shift<_UIntType, __w>::__value - 1; } /** * @brief Discard a sequence of random numbers. */ void discard(unsigned long long __z); result_type operator()(); /** * @brief Compares two % mersenne_twister_engine random number generator * objects of the same type for equality. * * @param __lhs A % mersenne_twister_engine random number generator * object. * @param __rhs Another % mersenne_twister_engine random number * generator object. * * @returns true if the infinite sequences of generated values * would be equal, false otherwise. */ friend bool operator==(const mersenne_twister_engine& __lhs, const mersenne_twister_engine& __rhs) { return (std::equal(__lhs._M_x, __lhs._M_x + state_size, __rhs._M_x) && __lhs._M_p == __rhs._M_p); } /** * @brief Inserts the current state of a % mersenne_twister_engine * random number generator engine @p __x into the output stream * @p __os. * * @param __os An output stream. * @param __x A % mersenne_twister_engine random number generator * engine. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::mersenne_twister_engine<_UIntType1, __w1, __n1, __m1, __r1, __a1, __u1, __d1, __s1, __b1, __t1, __c1, __l1, __f1>& __x); /** * @brief Extracts the current state of a % mersenne_twister_engine * random number generator engine @p __x from the input stream * @p __is. * * @param __is An input stream. * @param __x A % mersenne_twister_engine random number generator * engine. * * @returns The input stream with the state of @p __x extracted or in * an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::mersenne_twister_engine<_UIntType1, __w1, __n1, __m1, __r1, __a1, __u1, __d1, __s1, __b1, __t1, __c1, __l1, __f1>& __x); private: void _M_gen_rand(); _UIntType _M_x[state_size]; size_t _M_p; }; /** * @brief Compares two % mersenne_twister_engine random number generator * objects of the same type for inequality. * * @param __lhs A % mersenne_twister_engine random number generator * object. * @param __rhs Another % mersenne_twister_engine random number * generator object. * * @returns true if the infinite sequences of generated values * would be different, false otherwise. */ template inline bool operator!=(const std::mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>& __lhs, const std::mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>& __rhs) { return !(__lhs == __rhs); } /** * @brief The Marsaglia-Zaman generator. * * This is a model of a Generalized Fibonacci discrete random number * generator, sometimes referred to as the SWC generator. * * A discrete random number generator that produces pseudorandom * numbers using: * @f[ * x_{i}\leftarrow(x_{i - s} - x_{i - r} - carry_{i-1}) \bmod m * @f] * * The size of the state is @f$r@f$ * and the maximum period of the generator is @f$(m^r - m^s - 1)@f$. */ template class subtract_with_carry_engine { static_assert(std::is_unsigned<_UIntType>::value, "result_type must be an unsigned integral type"); static_assert(0u < __s && __s < __r, "0 < s < r"); static_assert(0u < __w && __w <= std::numeric_limits<_UIntType>::digits, "template argument substituting __w out of bounds"); public: /** The type of the generated random value. */ typedef _UIntType result_type; // parameter values static constexpr size_t word_size = __w; static constexpr size_t short_lag = __s; static constexpr size_t long_lag = __r; static constexpr result_type default_seed = 19780503u; /** * @brief Constructs an explicitly seeded % subtract_with_carry_engine * random number generator. */ explicit subtract_with_carry_engine(result_type __sd = default_seed) { seed(__sd); } /** * @brief Constructs a %subtract_with_carry_engine random number engine * seeded from the seed sequence @p __q. * * @param __q the seed sequence. */ template::value> ::type> explicit subtract_with_carry_engine(_Sseq& __q) { seed(__q); } /** * @brief Seeds the initial state @f$x_0@f$ of the random number * generator. * * N1688[4.19] modifies this as follows. If @p __value == 0, * sets value to 19780503. In any case, with a linear * congruential generator lcg(i) having parameters @f$ m_{lcg} = * 2147483563, a_{lcg} = 40014, c_{lcg} = 0, and lcg(0) = value * @f$, sets @f$ x_{-r} \dots x_{-1} @f$ to @f$ lcg(1) \bmod m * \dots lcg(r) \bmod m @f$ respectively. If @f$ x_{-1} = 0 @f$ * set carry to 1, otherwise sets carry to 0. */ void seed(result_type __sd = default_seed); /** * @brief Seeds the initial state @f$x_0@f$ of the * % subtract_with_carry_engine random number generator. */ template typename std::enable_if::value>::type seed(_Sseq& __q); /** * @brief Gets the inclusive minimum value of the range of random * integers returned by this generator. */ static constexpr result_type min() { return 0; } /** * @brief Gets the inclusive maximum value of the range of random * integers returned by this generator. */ static constexpr result_type max() { return __detail::_Shift<_UIntType, __w>::__value - 1; } /** * @brief Discard a sequence of random numbers. */ void discard(unsigned long long __z) { for (; __z != 0ULL; --__z) (*this)(); } /** * @brief Gets the next random number in the sequence. */ result_type operator()(); /** * @brief Compares two % subtract_with_carry_engine random number * generator objects of the same type for equality. * * @param __lhs A % subtract_with_carry_engine random number generator * object. * @param __rhs Another % subtract_with_carry_engine random number * generator object. * * @returns true if the infinite sequences of generated values * would be equal, false otherwise. */ friend bool operator==(const subtract_with_carry_engine& __lhs, const subtract_with_carry_engine& __rhs) { return (std::equal(__lhs._M_x, __lhs._M_x + long_lag, __rhs._M_x) && __lhs._M_carry == __rhs._M_carry && __lhs._M_p == __rhs._M_p); } /** * @brief Inserts the current state of a % subtract_with_carry_engine * random number generator engine @p __x into the output stream * @p __os. * * @param __os An output stream. * @param __x A % subtract_with_carry_engine random number generator * engine. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::subtract_with_carry_engine<_UIntType1, __w1, __s1, __r1>& __x); /** * @brief Extracts the current state of a % subtract_with_carry_engine * random number generator engine @p __x from the input stream * @p __is. * * @param __is An input stream. * @param __x A % subtract_with_carry_engine random number generator * engine. * * @returns The input stream with the state of @p __x extracted or in * an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::subtract_with_carry_engine<_UIntType1, __w1, __s1, __r1>& __x); private: /// The state of the generator. This is a ring buffer. _UIntType _M_x[long_lag]; _UIntType _M_carry; ///< The carry size_t _M_p; ///< Current index of x(i - r). }; /** * @brief Compares two % subtract_with_carry_engine random number * generator objects of the same type for inequality. * * @param __lhs A % subtract_with_carry_engine random number generator * object. * @param __rhs Another % subtract_with_carry_engine random number * generator object. * * @returns true if the infinite sequences of generated values * would be different, false otherwise. */ template inline bool operator!=(const std::subtract_with_carry_engine<_UIntType, __w, __s, __r>& __lhs, const std::subtract_with_carry_engine<_UIntType, __w, __s, __r>& __rhs) { return !(__lhs == __rhs); } /** * Produces random numbers from some base engine by discarding blocks of * data. * * 0 <= @p __r <= @p __p */ template class discard_block_engine { static_assert(1 <= __r && __r <= __p, "template argument substituting __r out of bounds"); public: /** The type of the generated random value. */ typedef typename _RandomNumberEngine::result_type result_type; // parameter values static constexpr size_t block_size = __p; static constexpr size_t used_block = __r; /** * @brief Constructs a default %discard_block_engine engine. * * The underlying engine is default constructed as well. */ discard_block_engine() : _M_b(), _M_n(0) { } /** * @brief Copy constructs a %discard_block_engine engine. * * Copies an existing base class random number generator. * @param __rng An existing (base class) engine object. */ explicit discard_block_engine(const _RandomNumberEngine& __rng) : _M_b(__rng), _M_n(0) { } /** * @brief Move constructs a %discard_block_engine engine. * * Copies an existing base class random number generator. * @param __rng An existing (base class) engine object. */ explicit discard_block_engine(_RandomNumberEngine&& __rng) : _M_b(std::move(__rng)), _M_n(0) { } /** * @brief Seed constructs a %discard_block_engine engine. * * Constructs the underlying generator engine seeded with @p __s. * @param __s A seed value for the base class engine. */ explicit discard_block_engine(result_type __s) : _M_b(__s), _M_n(0) { } /** * @brief Generator construct a %discard_block_engine engine. * * @param __q A seed sequence. */ template::value && !std::is_same<_Sseq, _RandomNumberEngine>::value> ::type> explicit discard_block_engine(_Sseq& __q) : _M_b(__q), _M_n(0) { } /** * @brief Reseeds the %discard_block_engine object with the default * seed for the underlying base class generator engine. */ void seed() { _M_b.seed(); _M_n = 0; } /** * @brief Reseeds the %discard_block_engine object with the default * seed for the underlying base class generator engine. */ void seed(result_type __s) { _M_b.seed(__s); _M_n = 0; } /** * @brief Reseeds the %discard_block_engine object with the given seed * sequence. * @param __q A seed generator function. */ template void seed(_Sseq& __q) { _M_b.seed(__q); _M_n = 0; } /** * @brief Gets a const reference to the underlying generator engine * object. */ const _RandomNumberEngine& base() const noexcept { return _M_b; } /** * @brief Gets the minimum value in the generated random number range. */ static constexpr result_type min() { return _RandomNumberEngine::min(); } /** * @brief Gets the maximum value in the generated random number range. */ static constexpr result_type max() { return _RandomNumberEngine::max(); } /** * @brief Discard a sequence of random numbers. */ void discard(unsigned long long __z) { for (; __z != 0ULL; --__z) (*this)(); } /** * @brief Gets the next value in the generated random number sequence. */ result_type operator()(); /** * @brief Compares two %discard_block_engine random number generator * objects of the same type for equality. * * @param __lhs A %discard_block_engine random number generator object. * @param __rhs Another %discard_block_engine random number generator * object. * * @returns true if the infinite sequences of generated values * would be equal, false otherwise. */ friend bool operator==(const discard_block_engine& __lhs, const discard_block_engine& __rhs) { return __lhs._M_b == __rhs._M_b && __lhs._M_n == __rhs._M_n; } /** * @brief Inserts the current state of a %discard_block_engine random * number generator engine @p __x into the output stream * @p __os. * * @param __os An output stream. * @param __x A %discard_block_engine random number generator engine. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::discard_block_engine<_RandomNumberEngine1, __p1, __r1>& __x); /** * @brief Extracts the current state of a % subtract_with_carry_engine * random number generator engine @p __x from the input stream * @p __is. * * @param __is An input stream. * @param __x A %discard_block_engine random number generator engine. * * @returns The input stream with the state of @p __x extracted or in * an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::discard_block_engine<_RandomNumberEngine1, __p1, __r1>& __x); private: _RandomNumberEngine _M_b; size_t _M_n; }; /** * @brief Compares two %discard_block_engine random number generator * objects of the same type for inequality. * * @param __lhs A %discard_block_engine random number generator object. * @param __rhs Another %discard_block_engine random number generator * object. * * @returns true if the infinite sequences of generated values * would be different, false otherwise. */ template inline bool operator!=(const std::discard_block_engine<_RandomNumberEngine, __p, __r>& __lhs, const std::discard_block_engine<_RandomNumberEngine, __p, __r>& __rhs) { return !(__lhs == __rhs); } /** * Produces random numbers by combining random numbers from some base * engine to produce random numbers with a specifies number of bits @p __w. */ template class independent_bits_engine { static_assert(std::is_unsigned<_UIntType>::value, "result_type must be an unsigned integral type"); static_assert(0u < __w && __w <= std::numeric_limits<_UIntType>::digits, "template argument substituting __w out of bounds"); public: /** The type of the generated random value. */ typedef _UIntType result_type; /** * @brief Constructs a default %independent_bits_engine engine. * * The underlying engine is default constructed as well. */ independent_bits_engine() : _M_b() { } /** * @brief Copy constructs a %independent_bits_engine engine. * * Copies an existing base class random number generator. * @param __rng An existing (base class) engine object. */ explicit independent_bits_engine(const _RandomNumberEngine& __rng) : _M_b(__rng) { } /** * @brief Move constructs a %independent_bits_engine engine. * * Copies an existing base class random number generator. * @param __rng An existing (base class) engine object. */ explicit independent_bits_engine(_RandomNumberEngine&& __rng) : _M_b(std::move(__rng)) { } /** * @brief Seed constructs a %independent_bits_engine engine. * * Constructs the underlying generator engine seeded with @p __s. * @param __s A seed value for the base class engine. */ explicit independent_bits_engine(result_type __s) : _M_b(__s) { } /** * @brief Generator construct a %independent_bits_engine engine. * * @param __q A seed sequence. */ template::value && !std::is_same<_Sseq, _RandomNumberEngine>::value> ::type> explicit independent_bits_engine(_Sseq& __q) : _M_b(__q) { } /** * @brief Reseeds the %independent_bits_engine object with the default * seed for the underlying base class generator engine. */ void seed() { _M_b.seed(); } /** * @brief Reseeds the %independent_bits_engine object with the default * seed for the underlying base class generator engine. */ void seed(result_type __s) { _M_b.seed(__s); } /** * @brief Reseeds the %independent_bits_engine object with the given * seed sequence. * @param __q A seed generator function. */ template void seed(_Sseq& __q) { _M_b.seed(__q); } /** * @brief Gets a const reference to the underlying generator engine * object. */ const _RandomNumberEngine& base() const noexcept { return _M_b; } /** * @brief Gets the minimum value in the generated random number range. */ static constexpr result_type min() { return 0U; } /** * @brief Gets the maximum value in the generated random number range. */ static constexpr result_type max() { return __detail::_Shift<_UIntType, __w>::__value - 1; } /** * @brief Discard a sequence of random numbers. */ void discard(unsigned long long __z) { for (; __z != 0ULL; --__z) (*this)(); } /** * @brief Gets the next value in the generated random number sequence. */ result_type operator()(); /** * @brief Compares two %independent_bits_engine random number generator * objects of the same type for equality. * * @param __lhs A %independent_bits_engine random number generator * object. * @param __rhs Another %independent_bits_engine random number generator * object. * * @returns true if the infinite sequences of generated values * would be equal, false otherwise. */ friend bool operator==(const independent_bits_engine& __lhs, const independent_bits_engine& __rhs) { return __lhs._M_b == __rhs._M_b; } /** * @brief Extracts the current state of a % subtract_with_carry_engine * random number generator engine @p __x from the input stream * @p __is. * * @param __is An input stream. * @param __x A %independent_bits_engine random number generator * engine. * * @returns The input stream with the state of @p __x extracted or in * an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::independent_bits_engine<_RandomNumberEngine, __w, _UIntType>& __x) { __is >> __x._M_b; return __is; } private: _RandomNumberEngine _M_b; }; /** * @brief Compares two %independent_bits_engine random number generator * objects of the same type for inequality. * * @param __lhs A %independent_bits_engine random number generator * object. * @param __rhs Another %independent_bits_engine random number generator * object. * * @returns true if the infinite sequences of generated values * would be different, false otherwise. */ template inline bool operator!=(const std::independent_bits_engine<_RandomNumberEngine, __w, _UIntType>& __lhs, const std::independent_bits_engine<_RandomNumberEngine, __w, _UIntType>& __rhs) { return !(__lhs == __rhs); } /** * @brief Inserts the current state of a %independent_bits_engine random * number generator engine @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %independent_bits_engine random number generator engine. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::independent_bits_engine<_RandomNumberEngine, __w, _UIntType>& __x) { __os << __x.base(); return __os; } /** * @brief Produces random numbers by combining random numbers from some * base engine to produce random numbers with a specifies number of bits * @p __k. */ template class shuffle_order_engine { static_assert(1u <= __k, "template argument substituting " "__k out of bound"); public: /** The type of the generated random value. */ typedef typename _RandomNumberEngine::result_type result_type; static constexpr size_t table_size = __k; /** * @brief Constructs a default %shuffle_order_engine engine. * * The underlying engine is default constructed as well. */ shuffle_order_engine() : _M_b() { _M_initialize(); } /** * @brief Copy constructs a %shuffle_order_engine engine. * * Copies an existing base class random number generator. * @param __rng An existing (base class) engine object. */ explicit shuffle_order_engine(const _RandomNumberEngine& __rng) : _M_b(__rng) { _M_initialize(); } /** * @brief Move constructs a %shuffle_order_engine engine. * * Copies an existing base class random number generator. * @param __rng An existing (base class) engine object. */ explicit shuffle_order_engine(_RandomNumberEngine&& __rng) : _M_b(std::move(__rng)) { _M_initialize(); } /** * @brief Seed constructs a %shuffle_order_engine engine. * * Constructs the underlying generator engine seeded with @p __s. * @param __s A seed value for the base class engine. */ explicit shuffle_order_engine(result_type __s) : _M_b(__s) { _M_initialize(); } /** * @brief Generator construct a %shuffle_order_engine engine. * * @param __q A seed sequence. */ template::value && !std::is_same<_Sseq, _RandomNumberEngine>::value> ::type> explicit shuffle_order_engine(_Sseq& __q) : _M_b(__q) { _M_initialize(); } /** * @brief Reseeds the %shuffle_order_engine object with the default seed for the underlying base class generator engine. */ void seed() { _M_b.seed(); _M_initialize(); } /** * @brief Reseeds the %shuffle_order_engine object with the default seed * for the underlying base class generator engine. */ void seed(result_type __s) { _M_b.seed(__s); _M_initialize(); } /** * @brief Reseeds the %shuffle_order_engine object with the given seed * sequence. * @param __q A seed generator function. */ template void seed(_Sseq& __q) { _M_b.seed(__q); _M_initialize(); } /** * Gets a const reference to the underlying generator engine object. */ const _RandomNumberEngine& base() const noexcept { return _M_b; } /** * Gets the minimum value in the generated random number range. */ static constexpr result_type min() { return _RandomNumberEngine::min(); } /** * Gets the maximum value in the generated random number range. */ static constexpr result_type max() { return _RandomNumberEngine::max(); } /** * Discard a sequence of random numbers. */ void discard(unsigned long long __z) { for (; __z != 0ULL; --__z) (*this)(); } /** * Gets the next value in the generated random number sequence. */ result_type operator()(); /** * Compares two %shuffle_order_engine random number generator objects * of the same type for equality. * * @param __lhs A %shuffle_order_engine random number generator object. * @param __rhs Another %shuffle_order_engine random number generator * object. * * @returns true if the infinite sequences of generated values * would be equal, false otherwise. */ friend bool operator==(const shuffle_order_engine& __lhs, const shuffle_order_engine& __rhs) { return (__lhs._M_b == __rhs._M_b && std::equal(__lhs._M_v, __lhs._M_v + __k, __rhs._M_v) && __lhs._M_y == __rhs._M_y); } /** * @brief Inserts the current state of a %shuffle_order_engine random * number generator engine @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %shuffle_order_engine random number generator engine. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::shuffle_order_engine<_RandomNumberEngine1, __k1>& __x); /** * @brief Extracts the current state of a % subtract_with_carry_engine * random number generator engine @p __x from the input stream * @p __is. * * @param __is An input stream. * @param __x A %shuffle_order_engine random number generator engine. * * @returns The input stream with the state of @p __x extracted or in * an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::shuffle_order_engine<_RandomNumberEngine1, __k1>& __x); private: void _M_initialize() { for (size_t __i = 0; __i < __k; ++__i) _M_v[__i] = _M_b(); _M_y = _M_b(); } _RandomNumberEngine _M_b; result_type _M_v[__k]; result_type _M_y; }; /** * Compares two %shuffle_order_engine random number generator objects * of the same type for inequality. * * @param __lhs A %shuffle_order_engine random number generator object. * @param __rhs Another %shuffle_order_engine random number generator * object. * * @returns true if the infinite sequences of generated values * would be different, false otherwise. */ template inline bool operator!=(const std::shuffle_order_engine<_RandomNumberEngine, __k>& __lhs, const std::shuffle_order_engine<_RandomNumberEngine, __k>& __rhs) { return !(__lhs == __rhs); } /** * The classic Minimum Standard rand0 of Lewis, Goodman, and Miller. */ typedef linear_congruential_engine minstd_rand0; /** * An alternative LCR (Lehmer Generator function). */ typedef linear_congruential_engine minstd_rand; /** * The classic Mersenne Twister. * * Reference: * M. Matsumoto and T. Nishimura, Mersenne Twister: A 623-Dimensionally * Equidistributed Uniform Pseudo-Random Number Generator, ACM Transactions * on Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30. */ typedef mersenne_twister_engine< uint_fast32_t, 32, 624, 397, 31, 0x9908b0dfUL, 11, 0xffffffffUL, 7, 0x9d2c5680UL, 15, 0xefc60000UL, 18, 1812433253UL> mt19937; /** * An alternative Mersenne Twister. */ typedef mersenne_twister_engine< uint_fast64_t, 64, 312, 156, 31, 0xb5026f5aa96619e9ULL, 29, 0x5555555555555555ULL, 17, 0x71d67fffeda60000ULL, 37, 0xfff7eee000000000ULL, 43, 6364136223846793005ULL> mt19937_64; typedef subtract_with_carry_engine ranlux24_base; typedef subtract_with_carry_engine ranlux48_base; typedef discard_block_engine ranlux24; typedef discard_block_engine ranlux48; typedef shuffle_order_engine knuth_b; typedef minstd_rand0 default_random_engine; /** * A standard interface to a platform-specific non-deterministic * random number generator (if any are available). */ class random_device { public: /** The type of the generated random value. */ typedef unsigned int result_type; // constructors, destructors and member functions #ifdef _GLIBCXX_USE_RANDOM_TR1 explicit random_device(const std::string& __token = "default") { _M_init(__token); } ~random_device() { _M_fini(); } #else explicit random_device(const std::string& __token = "mt19937") { _M_init_pretr1(__token); } public: #endif static constexpr result_type min() { return std::numeric_limits::min(); } static constexpr result_type max() { return std::numeric_limits::max(); } double entropy() const noexcept { #ifdef _GLIBCXX_USE_RANDOM_TR1 return this->_M_getentropy(); #else return 0.0; #endif } result_type operator()() { #ifdef _GLIBCXX_USE_RANDOM_TR1 return this->_M_getval(); #else return this->_M_getval_pretr1(); #endif } // No copy functions. random_device(const random_device&) = delete; void operator=(const random_device&) = delete; private: void _M_init(const std::string& __token); void _M_init_pretr1(const std::string& __token); void _M_fini(); result_type _M_getval(); result_type _M_getval_pretr1(); double _M_getentropy() const noexcept; union { void* _M_file; mt19937 _M_mt; }; }; /* @} */ // group random_generators /** * @addtogroup random_distributions Random Number Distributions * @ingroup random * @{ */ /** * @addtogroup random_distributions_uniform Uniform Distributions * @ingroup random_distributions * @{ */ // std::uniform_int_distribution is defined in /** * @brief Return true if two uniform integer distributions have * different parameters. */ template inline bool operator!=(const std::uniform_int_distribution<_IntType>& __d1, const std::uniform_int_distribution<_IntType>& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %uniform_int_distribution random number * distribution @p __x into the output stream @p os. * * @param __os An output stream. * @param __x A %uniform_int_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>&, const std::uniform_int_distribution<_IntType>&); /** * @brief Extracts a %uniform_int_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %uniform_int_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>&, std::uniform_int_distribution<_IntType>&); /** * @brief Uniform continuous distribution for random numbers. * * A continuous random distribution on the range [min, max) with equal * probability throughout the range. The URNG should be real-valued and * deliver number in the range [0, 1). */ template class uniform_real_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef uniform_real_distribution<_RealType> distribution_type; explicit param_type(_RealType __a = _RealType(0), _RealType __b = _RealType(1)) : _M_a(__a), _M_b(__b) { __glibcxx_assert(_M_a <= _M_b); } result_type a() const { return _M_a; } result_type b() const { return _M_b; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_a; _RealType _M_b; }; public: /** * @brief Constructs a uniform_real_distribution object. * * @param __a [IN] The lower bound of the distribution. * @param __b [IN] The upper bound of the distribution. */ explicit uniform_real_distribution(_RealType __a = _RealType(0), _RealType __b = _RealType(1)) : _M_param(__a, __b) { } explicit uniform_real_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. * * Does nothing for the uniform real distribution. */ void reset() { } result_type a() const { return _M_param.a(); } result_type b() const { return _M_param.b(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the inclusive lower bound of the distribution range. */ result_type min() const { return this->a(); } /** * @brief Returns the inclusive upper bound of the distribution range. */ result_type max() const { return this->b(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); return (__aurng() * (__p.b() - __p.a())) + __p.a(); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two uniform real distributions have * the same parameters. */ friend bool operator==(const uniform_real_distribution& __d1, const uniform_real_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two uniform real distributions have * different parameters. */ template inline bool operator!=(const std::uniform_real_distribution<_IntType>& __d1, const std::uniform_real_distribution<_IntType>& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %uniform_real_distribution random number * distribution @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %uniform_real_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>&, const std::uniform_real_distribution<_RealType>&); /** * @brief Extracts a %uniform_real_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %uniform_real_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>&, std::uniform_real_distribution<_RealType>&); /* @} */ // group random_distributions_uniform /** * @addtogroup random_distributions_normal Normal Distributions * @ingroup random_distributions * @{ */ /** * @brief A normal continuous distribution for random numbers. * * The formula for the normal probability density function is * @f[ * p(x|\mu,\sigma) = \frac{1}{\sigma \sqrt{2 \pi}} * e^{- \frac{{x - \mu}^ {2}}{2 \sigma ^ {2}} } * @f] */ template class normal_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef normal_distribution<_RealType> distribution_type; explicit param_type(_RealType __mean = _RealType(0), _RealType __stddev = _RealType(1)) : _M_mean(__mean), _M_stddev(__stddev) { __glibcxx_assert(_M_stddev > _RealType(0)); } _RealType mean() const { return _M_mean; } _RealType stddev() const { return _M_stddev; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return (__p1._M_mean == __p2._M_mean && __p1._M_stddev == __p2._M_stddev); } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_mean; _RealType _M_stddev; }; public: /** * Constructs a normal distribution with parameters @f$mean@f$ and * standard deviation. */ explicit normal_distribution(result_type __mean = result_type(0), result_type __stddev = result_type(1)) : _M_param(__mean, __stddev) { } explicit normal_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. */ void reset() { _M_saved_available = false; } /** * @brief Returns the mean of the distribution. */ _RealType mean() const { return _M_param.mean(); } /** * @brief Returns the standard deviation of the distribution. */ _RealType stddev() const { return _M_param.stddev(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return std::numeric_limits::lowest(); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two normal distributions have * the same parameters and the sequences that would * be generated are equal. */ template friend bool operator==(const std::normal_distribution<_RealType1>& __d1, const std::normal_distribution<_RealType1>& __d2); /** * @brief Inserts a %normal_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %normal_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::normal_distribution<_RealType1>& __x); /** * @brief Extracts a %normal_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %normal_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error * state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::normal_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; result_type _M_saved = 0; bool _M_saved_available = false; }; /** * @brief Return true if two normal distributions are different. */ template inline bool operator!=(const std::normal_distribution<_RealType>& __d1, const std::normal_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief A lognormal_distribution random number distribution. * * The formula for the normal probability mass function is * @f[ * p(x|m,s) = \frac{1}{sx\sqrt{2\pi}} * \exp{-\frac{(\ln{x} - m)^2}{2s^2}} * @f] */ template class lognormal_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef lognormal_distribution<_RealType> distribution_type; explicit param_type(_RealType __m = _RealType(0), _RealType __s = _RealType(1)) : _M_m(__m), _M_s(__s) { } _RealType m() const { return _M_m; } _RealType s() const { return _M_s; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_m == __p2._M_m && __p1._M_s == __p2._M_s; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_m; _RealType _M_s; }; explicit lognormal_distribution(_RealType __m = _RealType(0), _RealType __s = _RealType(1)) : _M_param(__m, __s), _M_nd() { } explicit lognormal_distribution(const param_type& __p) : _M_param(__p), _M_nd() { } /** * Resets the distribution state. */ void reset() { _M_nd.reset(); } /** * */ _RealType m() const { return _M_param.m(); } _RealType s() const { return _M_param.s(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { return std::exp(__p.s() * _M_nd(__urng) + __p.m()); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two lognormal distributions have * the same parameters and the sequences that would * be generated are equal. */ friend bool operator==(const lognormal_distribution& __d1, const lognormal_distribution& __d2) { return (__d1._M_param == __d2._M_param && __d1._M_nd == __d2._M_nd); } /** * @brief Inserts a %lognormal_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %lognormal_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::lognormal_distribution<_RealType1>& __x); /** * @brief Extracts a %lognormal_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %lognormal_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::lognormal_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; std::normal_distribution _M_nd; }; /** * @brief Return true if two lognormal distributions are different. */ template inline bool operator!=(const std::lognormal_distribution<_RealType>& __d1, const std::lognormal_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief A gamma continuous distribution for random numbers. * * The formula for the gamma probability density function is: * @f[ * p(x|\alpha,\beta) = \frac{1}{\beta\Gamma(\alpha)} * (x/\beta)^{\alpha - 1} e^{-x/\beta} * @f] */ template class gamma_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef gamma_distribution<_RealType> distribution_type; friend class gamma_distribution<_RealType>; explicit param_type(_RealType __alpha_val = _RealType(1), _RealType __beta_val = _RealType(1)) : _M_alpha(__alpha_val), _M_beta(__beta_val) { __glibcxx_assert(_M_alpha > _RealType(0)); _M_initialize(); } _RealType alpha() const { return _M_alpha; } _RealType beta() const { return _M_beta; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return (__p1._M_alpha == __p2._M_alpha && __p1._M_beta == __p2._M_beta); } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: void _M_initialize(); _RealType _M_alpha; _RealType _M_beta; _RealType _M_malpha, _M_a2; }; public: /** * @brief Constructs a gamma distribution with parameters * @f$\alpha@f$ and @f$\beta@f$. */ explicit gamma_distribution(_RealType __alpha_val = _RealType(1), _RealType __beta_val = _RealType(1)) : _M_param(__alpha_val, __beta_val), _M_nd() { } explicit gamma_distribution(const param_type& __p) : _M_param(__p), _M_nd() { } /** * @brief Resets the distribution state. */ void reset() { _M_nd.reset(); } /** * @brief Returns the @f$\alpha@f$ of the distribution. */ _RealType alpha() const { return _M_param.alpha(); } /** * @brief Returns the @f$\beta@f$ of the distribution. */ _RealType beta() const { return _M_param.beta(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two gamma distributions have the same * parameters and the sequences that would be generated * are equal. */ friend bool operator==(const gamma_distribution& __d1, const gamma_distribution& __d2) { return (__d1._M_param == __d2._M_param && __d1._M_nd == __d2._M_nd); } /** * @brief Inserts a %gamma_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %gamma_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::gamma_distribution<_RealType1>& __x); /** * @brief Extracts a %gamma_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %gamma_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::gamma_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; std::normal_distribution _M_nd; }; /** * @brief Return true if two gamma distributions are different. */ template inline bool operator!=(const std::gamma_distribution<_RealType>& __d1, const std::gamma_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief A chi_squared_distribution random number distribution. * * The formula for the normal probability mass function is * @f$p(x|n) = \frac{x^{(n/2) - 1}e^{-x/2}}{\Gamma(n/2) 2^{n/2}}@f$ */ template class chi_squared_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef chi_squared_distribution<_RealType> distribution_type; explicit param_type(_RealType __n = _RealType(1)) : _M_n(__n) { } _RealType n() const { return _M_n; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_n == __p2._M_n; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_n; }; explicit chi_squared_distribution(_RealType __n = _RealType(1)) : _M_param(__n), _M_gd(__n / 2) { } explicit chi_squared_distribution(const param_type& __p) : _M_param(__p), _M_gd(__p.n() / 2) { } /** * @brief Resets the distribution state. */ void reset() { _M_gd.reset(); } /** * */ _RealType n() const { return _M_param.n(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; typedef typename std::gamma_distribution::param_type param_type; _M_gd.param(param_type{__param.n() / 2}); } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return 2 * _M_gd(__urng); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { typedef typename std::gamma_distribution::param_type param_type; return 2 * _M_gd(__urng, param_type(__p.n() / 2)); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { typename std::gamma_distribution::param_type __p2(__p.n() / 2); this->__generate_impl(__f, __t, __urng, __p2); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { typename std::gamma_distribution::param_type __p2(__p.n() / 2); this->__generate_impl(__f, __t, __urng, __p2); } /** * @brief Return true if two Chi-squared distributions have * the same parameters and the sequences that would be * generated are equal. */ friend bool operator==(const chi_squared_distribution& __d1, const chi_squared_distribution& __d2) { return __d1._M_param == __d2._M_param && __d1._M_gd == __d2._M_gd; } /** * @brief Inserts a %chi_squared_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %chi_squared_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::chi_squared_distribution<_RealType1>& __x); /** * @brief Extracts a %chi_squared_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %chi_squared_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::chi_squared_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng); template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const typename std::gamma_distribution::param_type& __p); param_type _M_param; std::gamma_distribution _M_gd; }; /** * @brief Return true if two Chi-squared distributions are different. */ template inline bool operator!=(const std::chi_squared_distribution<_RealType>& __d1, const std::chi_squared_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief A cauchy_distribution random number distribution. * * The formula for the normal probability mass function is * @f$p(x|a,b) = (\pi b (1 + (\frac{x-a}{b})^2))^{-1}@f$ */ template class cauchy_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef cauchy_distribution<_RealType> distribution_type; explicit param_type(_RealType __a = _RealType(0), _RealType __b = _RealType(1)) : _M_a(__a), _M_b(__b) { } _RealType a() const { return _M_a; } _RealType b() const { return _M_b; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_a; _RealType _M_b; }; explicit cauchy_distribution(_RealType __a = _RealType(0), _RealType __b = _RealType(1)) : _M_param(__a, __b) { } explicit cauchy_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. */ void reset() { } /** * */ _RealType a() const { return _M_param.a(); } _RealType b() const { return _M_param.b(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return std::numeric_limits::lowest(); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two Cauchy distributions have * the same parameters. */ friend bool operator==(const cauchy_distribution& __d1, const cauchy_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two Cauchy distributions have * different parameters. */ template inline bool operator!=(const std::cauchy_distribution<_RealType>& __d1, const std::cauchy_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %cauchy_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %cauchy_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::cauchy_distribution<_RealType>& __x); /** * @brief Extracts a %cauchy_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %cauchy_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::cauchy_distribution<_RealType>& __x); /** * @brief A fisher_f_distribution random number distribution. * * The formula for the normal probability mass function is * @f[ * p(x|m,n) = \frac{\Gamma((m+n)/2)}{\Gamma(m/2)\Gamma(n/2)} * (\frac{m}{n})^{m/2} x^{(m/2)-1} * (1 + \frac{mx}{n})^{-(m+n)/2} * @f] */ template class fisher_f_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef fisher_f_distribution<_RealType> distribution_type; explicit param_type(_RealType __m = _RealType(1), _RealType __n = _RealType(1)) : _M_m(__m), _M_n(__n) { } _RealType m() const { return _M_m; } _RealType n() const { return _M_n; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_m == __p2._M_m && __p1._M_n == __p2._M_n; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_m; _RealType _M_n; }; explicit fisher_f_distribution(_RealType __m = _RealType(1), _RealType __n = _RealType(1)) : _M_param(__m, __n), _M_gd_x(__m / 2), _M_gd_y(__n / 2) { } explicit fisher_f_distribution(const param_type& __p) : _M_param(__p), _M_gd_x(__p.m() / 2), _M_gd_y(__p.n() / 2) { } /** * @brief Resets the distribution state. */ void reset() { _M_gd_x.reset(); _M_gd_y.reset(); } /** * */ _RealType m() const { return _M_param.m(); } _RealType n() const { return _M_param.n(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return (_M_gd_x(__urng) * n()) / (_M_gd_y(__urng) * m()); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { typedef typename std::gamma_distribution::param_type param_type; return ((_M_gd_x(__urng, param_type(__p.m() / 2)) * n()) / (_M_gd_y(__urng, param_type(__p.n() / 2)) * m())); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two Fisher f distributions have * the same parameters and the sequences that would * be generated are equal. */ friend bool operator==(const fisher_f_distribution& __d1, const fisher_f_distribution& __d2) { return (__d1._M_param == __d2._M_param && __d1._M_gd_x == __d2._M_gd_x && __d1._M_gd_y == __d2._M_gd_y); } /** * @brief Inserts a %fisher_f_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %fisher_f_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::fisher_f_distribution<_RealType1>& __x); /** * @brief Extracts a %fisher_f_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %fisher_f_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::fisher_f_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng); template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; std::gamma_distribution _M_gd_x, _M_gd_y; }; /** * @brief Return true if two Fisher f distributions are different. */ template inline bool operator!=(const std::fisher_f_distribution<_RealType>& __d1, const std::fisher_f_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief A student_t_distribution random number distribution. * * The formula for the normal probability mass function is: * @f[ * p(x|n) = \frac{1}{\sqrt(n\pi)} \frac{\Gamma((n+1)/2)}{\Gamma(n/2)} * (1 + \frac{x^2}{n}) ^{-(n+1)/2} * @f] */ template class student_t_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef student_t_distribution<_RealType> distribution_type; explicit param_type(_RealType __n = _RealType(1)) : _M_n(__n) { } _RealType n() const { return _M_n; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_n == __p2._M_n; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_n; }; explicit student_t_distribution(_RealType __n = _RealType(1)) : _M_param(__n), _M_nd(), _M_gd(__n / 2, 2) { } explicit student_t_distribution(const param_type& __p) : _M_param(__p), _M_nd(), _M_gd(__p.n() / 2, 2) { } /** * @brief Resets the distribution state. */ void reset() { _M_nd.reset(); _M_gd.reset(); } /** * */ _RealType n() const { return _M_param.n(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return std::numeric_limits::lowest(); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return _M_nd(__urng) * std::sqrt(n() / _M_gd(__urng)); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { typedef typename std::gamma_distribution::param_type param_type; const result_type __g = _M_gd(__urng, param_type(__p.n() / 2, 2)); return _M_nd(__urng) * std::sqrt(__p.n() / __g); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two Student t distributions have * the same parameters and the sequences that would * be generated are equal. */ friend bool operator==(const student_t_distribution& __d1, const student_t_distribution& __d2) { return (__d1._M_param == __d2._M_param && __d1._M_nd == __d2._M_nd && __d1._M_gd == __d2._M_gd); } /** * @brief Inserts a %student_t_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %student_t_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::student_t_distribution<_RealType1>& __x); /** * @brief Extracts a %student_t_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %student_t_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::student_t_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng); template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; std::normal_distribution _M_nd; std::gamma_distribution _M_gd; }; /** * @brief Return true if two Student t distributions are different. */ template inline bool operator!=(const std::student_t_distribution<_RealType>& __d1, const std::student_t_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /* @} */ // group random_distributions_normal /** * @addtogroup random_distributions_bernoulli Bernoulli Distributions * @ingroup random_distributions * @{ */ /** * @brief A Bernoulli random number distribution. * * Generates a sequence of true and false values with likelihood @f$p@f$ * that true will come up and @f$(1 - p)@f$ that false will appear. */ class bernoulli_distribution { public: /** The type of the range of the distribution. */ typedef bool result_type; /** Parameter type. */ struct param_type { typedef bernoulli_distribution distribution_type; explicit param_type(double __p = 0.5) : _M_p(__p) { __glibcxx_assert((_M_p >= 0.0) && (_M_p <= 1.0)); } double p() const { return _M_p; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_p == __p2._M_p; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: double _M_p; }; public: /** * @brief Constructs a Bernoulli distribution with likelihood @p p. * * @param __p [IN] The likelihood of a true result being returned. * Must be in the interval @f$[0, 1]@f$. */ explicit bernoulli_distribution(double __p = 0.5) : _M_param(__p) { } explicit bernoulli_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. * * Does nothing for a Bernoulli distribution. */ void reset() { } /** * @brief Returns the @p p parameter of the distribution. */ double p() const { return _M_param.p(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return std::numeric_limits::min(); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); if ((__aurng() - __aurng.min()) < __p.p() * (__aurng.max() - __aurng.min())) return true; return false; } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two Bernoulli distributions have * the same parameters. */ friend bool operator==(const bernoulli_distribution& __d1, const bernoulli_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two Bernoulli distributions have * different parameters. */ inline bool operator!=(const std::bernoulli_distribution& __d1, const std::bernoulli_distribution& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %bernoulli_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %bernoulli_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::bernoulli_distribution& __x); /** * @brief Extracts a %bernoulli_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %bernoulli_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::bernoulli_distribution& __x) { double __p; if (__is >> __p) __x.param(bernoulli_distribution::param_type(__p)); return __is; } /** * @brief A discrete binomial random number distribution. * * The formula for the binomial probability density function is * @f$p(i|t,p) = \binom{t}{i} p^i (1 - p)^{t - i}@f$ where @f$t@f$ * and @f$p@f$ are the parameters of the distribution. */ template class binomial_distribution { static_assert(std::is_integral<_IntType>::value, "result_type must be an integral type"); public: /** The type of the range of the distribution. */ typedef _IntType result_type; /** Parameter type. */ struct param_type { typedef binomial_distribution<_IntType> distribution_type; friend class binomial_distribution<_IntType>; explicit param_type(_IntType __t = _IntType(1), double __p = 0.5) : _M_t(__t), _M_p(__p) { __glibcxx_assert((_M_t >= _IntType(0)) && (_M_p >= 0.0) && (_M_p <= 1.0)); _M_initialize(); } _IntType t() const { return _M_t; } double p() const { return _M_p; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_t == __p2._M_t && __p1._M_p == __p2._M_p; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: void _M_initialize(); _IntType _M_t; double _M_p; double _M_q; #if _GLIBCXX_USE_C99_MATH_TR1 double _M_d1, _M_d2, _M_s1, _M_s2, _M_c, _M_a1, _M_a123, _M_s, _M_lf, _M_lp1p; #endif bool _M_easy; }; // constructors and member function explicit binomial_distribution(_IntType __t = _IntType(1), double __p = 0.5) : _M_param(__t, __p), _M_nd() { } explicit binomial_distribution(const param_type& __p) : _M_param(__p), _M_nd() { } /** * @brief Resets the distribution state. */ void reset() { _M_nd.reset(); } /** * @brief Returns the distribution @p t parameter. */ _IntType t() const { return _M_param.t(); } /** * @brief Returns the distribution @p p parameter. */ double p() const { return _M_param.p(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return 0; } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return _M_param.t(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two binomial distributions have * the same parameters and the sequences that would * be generated are equal. */ friend bool operator==(const binomial_distribution& __d1, const binomial_distribution& __d2) #ifdef _GLIBCXX_USE_C99_MATH_TR1 { return __d1._M_param == __d2._M_param && __d1._M_nd == __d2._M_nd; } #else { return __d1._M_param == __d2._M_param; } #endif /** * @brief Inserts a %binomial_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %binomial_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::binomial_distribution<_IntType1>& __x); /** * @brief Extracts a %binomial_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %binomial_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error * state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::binomial_distribution<_IntType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); template result_type _M_waiting(_UniformRandomNumberGenerator& __urng, _IntType __t, double __q); param_type _M_param; // NB: Unused when _GLIBCXX_USE_C99_MATH_TR1 is undefined. std::normal_distribution _M_nd; }; /** * @brief Return true if two binomial distributions are different. */ template inline bool operator!=(const std::binomial_distribution<_IntType>& __d1, const std::binomial_distribution<_IntType>& __d2) { return !(__d1 == __d2); } /** * @brief A discrete geometric random number distribution. * * The formula for the geometric probability density function is * @f$p(i|p) = p(1 - p)^{i}@f$ where @f$p@f$ is the parameter of the * distribution. */ template class geometric_distribution { static_assert(std::is_integral<_IntType>::value, "result_type must be an integral type"); public: /** The type of the range of the distribution. */ typedef _IntType result_type; /** Parameter type. */ struct param_type { typedef geometric_distribution<_IntType> distribution_type; friend class geometric_distribution<_IntType>; explicit param_type(double __p = 0.5) : _M_p(__p) { __glibcxx_assert((_M_p > 0.0) && (_M_p < 1.0)); _M_initialize(); } double p() const { return _M_p; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_p == __p2._M_p; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: void _M_initialize() { _M_log_1_p = std::log(1.0 - _M_p); } double _M_p; double _M_log_1_p; }; // constructors and member function explicit geometric_distribution(double __p = 0.5) : _M_param(__p) { } explicit geometric_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. * * Does nothing for the geometric distribution. */ void reset() { } /** * @brief Returns the distribution parameter @p p. */ double p() const { return _M_param.p(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return 0; } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two geometric distributions have * the same parameters. */ friend bool operator==(const geometric_distribution& __d1, const geometric_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two geometric distributions have * different parameters. */ template inline bool operator!=(const std::geometric_distribution<_IntType>& __d1, const std::geometric_distribution<_IntType>& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %geometric_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %geometric_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::geometric_distribution<_IntType>& __x); /** * @brief Extracts a %geometric_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %geometric_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::geometric_distribution<_IntType>& __x); /** * @brief A negative_binomial_distribution random number distribution. * * The formula for the negative binomial probability mass function is * @f$p(i) = \binom{n}{i} p^i (1 - p)^{t - i}@f$ where @f$t@f$ * and @f$p@f$ are the parameters of the distribution. */ template class negative_binomial_distribution { static_assert(std::is_integral<_IntType>::value, "result_type must be an integral type"); public: /** The type of the range of the distribution. */ typedef _IntType result_type; /** Parameter type. */ struct param_type { typedef negative_binomial_distribution<_IntType> distribution_type; explicit param_type(_IntType __k = 1, double __p = 0.5) : _M_k(__k), _M_p(__p) { __glibcxx_assert((_M_k > 0) && (_M_p > 0.0) && (_M_p <= 1.0)); } _IntType k() const { return _M_k; } double p() const { return _M_p; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_k == __p2._M_k && __p1._M_p == __p2._M_p; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _IntType _M_k; double _M_p; }; explicit negative_binomial_distribution(_IntType __k = 1, double __p = 0.5) : _M_param(__k, __p), _M_gd(__k, (1.0 - __p) / __p) { } explicit negative_binomial_distribution(const param_type& __p) : _M_param(__p), _M_gd(__p.k(), (1.0 - __p.p()) / __p.p()) { } /** * @brief Resets the distribution state. */ void reset() { _M_gd.reset(); } /** * @brief Return the @f$k@f$ parameter of the distribution. */ _IntType k() const { return _M_param.k(); } /** * @brief Return the @f$p@f$ parameter of the distribution. */ double p() const { return _M_param.p(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng); template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two negative binomial distributions have * the same parameters and the sequences that would be * generated are equal. */ friend bool operator==(const negative_binomial_distribution& __d1, const negative_binomial_distribution& __d2) { return __d1._M_param == __d2._M_param && __d1._M_gd == __d2._M_gd; } /** * @brief Inserts a %negative_binomial_distribution random * number distribution @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %negative_binomial_distribution random number * distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::negative_binomial_distribution<_IntType1>& __x); /** * @brief Extracts a %negative_binomial_distribution random number * distribution @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %negative_binomial_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::negative_binomial_distribution<_IntType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng); template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; std::gamma_distribution _M_gd; }; /** * @brief Return true if two negative binomial distributions are different. */ template inline bool operator!=(const std::negative_binomial_distribution<_IntType>& __d1, const std::negative_binomial_distribution<_IntType>& __d2) { return !(__d1 == __d2); } /* @} */ // group random_distributions_bernoulli /** * @addtogroup random_distributions_poisson Poisson Distributions * @ingroup random_distributions * @{ */ /** * @brief A discrete Poisson random number distribution. * * The formula for the Poisson probability density function is * @f$p(i|\mu) = \frac{\mu^i}{i!} e^{-\mu}@f$ where @f$\mu@f$ is the * parameter of the distribution. */ template class poisson_distribution { static_assert(std::is_integral<_IntType>::value, "result_type must be an integral type"); public: /** The type of the range of the distribution. */ typedef _IntType result_type; /** Parameter type. */ struct param_type { typedef poisson_distribution<_IntType> distribution_type; friend class poisson_distribution<_IntType>; explicit param_type(double __mean = 1.0) : _M_mean(__mean) { __glibcxx_assert(_M_mean > 0.0); _M_initialize(); } double mean() const { return _M_mean; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_mean == __p2._M_mean; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: // Hosts either log(mean) or the threshold of the simple method. void _M_initialize(); double _M_mean; double _M_lm_thr; #if _GLIBCXX_USE_C99_MATH_TR1 double _M_lfm, _M_sm, _M_d, _M_scx, _M_1cx, _M_c2b, _M_cb; #endif }; // constructors and member function explicit poisson_distribution(double __mean = 1.0) : _M_param(__mean), _M_nd() { } explicit poisson_distribution(const param_type& __p) : _M_param(__p), _M_nd() { } /** * @brief Resets the distribution state. */ void reset() { _M_nd.reset(); } /** * @brief Returns the distribution parameter @p mean. */ double mean() const { return _M_param.mean(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return 0; } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two Poisson distributions have the same * parameters and the sequences that would be generated * are equal. */ friend bool operator==(const poisson_distribution& __d1, const poisson_distribution& __d2) #ifdef _GLIBCXX_USE_C99_MATH_TR1 { return __d1._M_param == __d2._M_param && __d1._M_nd == __d2._M_nd; } #else { return __d1._M_param == __d2._M_param; } #endif /** * @brief Inserts a %poisson_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %poisson_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::poisson_distribution<_IntType1>& __x); /** * @brief Extracts a %poisson_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %poisson_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error * state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::poisson_distribution<_IntType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; // NB: Unused when _GLIBCXX_USE_C99_MATH_TR1 is undefined. std::normal_distribution _M_nd; }; /** * @brief Return true if two Poisson distributions are different. */ template inline bool operator!=(const std::poisson_distribution<_IntType>& __d1, const std::poisson_distribution<_IntType>& __d2) { return !(__d1 == __d2); } /** * @brief An exponential continuous distribution for random numbers. * * The formula for the exponential probability density function is * @f$p(x|\lambda) = \lambda e^{-\lambda x}@f$. * * * * * * * * *
Distribution Statistics
Mean@f$\frac{1}{\lambda}@f$
Median@f$\frac{\ln 2}{\lambda}@f$
Mode@f$zero@f$
Range@f$[0, \infty]@f$
Standard Deviation@f$\frac{1}{\lambda}@f$
*/ template class exponential_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef exponential_distribution<_RealType> distribution_type; explicit param_type(_RealType __lambda = _RealType(1)) : _M_lambda(__lambda) { __glibcxx_assert(_M_lambda > _RealType(0)); } _RealType lambda() const { return _M_lambda; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_lambda == __p2._M_lambda; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_lambda; }; public: /** * @brief Constructs an exponential distribution with inverse scale * parameter @f$\lambda@f$. */ explicit exponential_distribution(const result_type& __lambda = result_type(1)) : _M_param(__lambda) { } explicit exponential_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. * * Has no effect on exponential distributions. */ void reset() { } /** * @brief Returns the inverse scale parameter of the distribution. */ _RealType lambda() const { return _M_param.lambda(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); return -std::log(result_type(1) - __aurng()) / __p.lambda(); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two exponential distributions have the same * parameters. */ friend bool operator==(const exponential_distribution& __d1, const exponential_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two exponential distributions have different * parameters. */ template inline bool operator!=(const std::exponential_distribution<_RealType>& __d1, const std::exponential_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %exponential_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %exponential_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::exponential_distribution<_RealType>& __x); /** * @brief Extracts a %exponential_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %exponential_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::exponential_distribution<_RealType>& __x); /** * @brief A weibull_distribution random number distribution. * * The formula for the normal probability density function is: * @f[ * p(x|\alpha,\beta) = \frac{\alpha}{\beta} (\frac{x}{\beta})^{\alpha-1} * \exp{(-(\frac{x}{\beta})^\alpha)} * @f] */ template class weibull_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef weibull_distribution<_RealType> distribution_type; explicit param_type(_RealType __a = _RealType(1), _RealType __b = _RealType(1)) : _M_a(__a), _M_b(__b) { } _RealType a() const { return _M_a; } _RealType b() const { return _M_b; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_a; _RealType _M_b; }; explicit weibull_distribution(_RealType __a = _RealType(1), _RealType __b = _RealType(1)) : _M_param(__a, __b) { } explicit weibull_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. */ void reset() { } /** * @brief Return the @f$a@f$ parameter of the distribution. */ _RealType a() const { return _M_param.a(); } /** * @brief Return the @f$b@f$ parameter of the distribution. */ _RealType b() const { return _M_param.b(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two Weibull distributions have the same * parameters. */ friend bool operator==(const weibull_distribution& __d1, const weibull_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two Weibull distributions have different * parameters. */ template inline bool operator!=(const std::weibull_distribution<_RealType>& __d1, const std::weibull_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %weibull_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %weibull_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::weibull_distribution<_RealType>& __x); /** * @brief Extracts a %weibull_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %weibull_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::weibull_distribution<_RealType>& __x); /** * @brief A extreme_value_distribution random number distribution. * * The formula for the normal probability mass function is * @f[ * p(x|a,b) = \frac{1}{b} * \exp( \frac{a-x}{b} - \exp(\frac{a-x}{b})) * @f] */ template class extreme_value_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef extreme_value_distribution<_RealType> distribution_type; explicit param_type(_RealType __a = _RealType(0), _RealType __b = _RealType(1)) : _M_a(__a), _M_b(__b) { } _RealType a() const { return _M_a; } _RealType b() const { return _M_b; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_a; _RealType _M_b; }; explicit extreme_value_distribution(_RealType __a = _RealType(0), _RealType __b = _RealType(1)) : _M_param(__a, __b) { } explicit extreme_value_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. */ void reset() { } /** * @brief Return the @f$a@f$ parameter of the distribution. */ _RealType a() const { return _M_param.a(); } /** * @brief Return the @f$b@f$ parameter of the distribution. */ _RealType b() const { return _M_param.b(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return std::numeric_limits::lowest(); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two extreme value distributions have the same * parameters. */ friend bool operator==(const extreme_value_distribution& __d1, const extreme_value_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two extreme value distributions have different * parameters. */ template inline bool operator!=(const std::extreme_value_distribution<_RealType>& __d1, const std::extreme_value_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %extreme_value_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %extreme_value_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::extreme_value_distribution<_RealType>& __x); /** * @brief Extracts a %extreme_value_distribution random number * distribution @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %extreme_value_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::extreme_value_distribution<_RealType>& __x); /** * @brief A discrete_distribution random number distribution. * * The formula for the discrete probability mass function is * */ template class discrete_distribution { static_assert(std::is_integral<_IntType>::value, "result_type must be an integral type"); public: /** The type of the range of the distribution. */ typedef _IntType result_type; /** Parameter type. */ struct param_type { typedef discrete_distribution<_IntType> distribution_type; friend class discrete_distribution<_IntType>; param_type() : _M_prob(), _M_cp() { } template param_type(_InputIterator __wbegin, _InputIterator __wend) : _M_prob(__wbegin, __wend), _M_cp() { _M_initialize(); } param_type(initializer_list __wil) : _M_prob(__wil.begin(), __wil.end()), _M_cp() { _M_initialize(); } template param_type(size_t __nw, double __xmin, double __xmax, _Func __fw); // See: http://cpp-next.com/archive/2010/10/implicit-move-must-go/ param_type(const param_type&) = default; param_type& operator=(const param_type&) = default; std::vector probabilities() const { return _M_prob.empty() ? std::vector(1, 1.0) : _M_prob; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_prob == __p2._M_prob; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: void _M_initialize(); std::vector _M_prob; std::vector _M_cp; }; discrete_distribution() : _M_param() { } template discrete_distribution(_InputIterator __wbegin, _InputIterator __wend) : _M_param(__wbegin, __wend) { } discrete_distribution(initializer_list __wl) : _M_param(__wl) { } template discrete_distribution(size_t __nw, double __xmin, double __xmax, _Func __fw) : _M_param(__nw, __xmin, __xmax, __fw) { } explicit discrete_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. */ void reset() { } /** * @brief Returns the probabilities of the distribution. */ std::vector probabilities() const { return _M_param._M_prob.empty() ? std::vector(1, 1.0) : _M_param._M_prob; } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return _M_param._M_prob.empty() ? result_type(0) : result_type(_M_param._M_prob.size() - 1); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two discrete distributions have the same * parameters. */ friend bool operator==(const discrete_distribution& __d1, const discrete_distribution& __d2) { return __d1._M_param == __d2._M_param; } /** * @brief Inserts a %discrete_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %discrete_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::discrete_distribution<_IntType1>& __x); /** * @brief Extracts a %discrete_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %discrete_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error * state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::discrete_distribution<_IntType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two discrete distributions have different * parameters. */ template inline bool operator!=(const std::discrete_distribution<_IntType>& __d1, const std::discrete_distribution<_IntType>& __d2) { return !(__d1 == __d2); } /** * @brief A piecewise_constant_distribution random number distribution. * * The formula for the piecewise constant probability mass function is * */ template class piecewise_constant_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef piecewise_constant_distribution<_RealType> distribution_type; friend class piecewise_constant_distribution<_RealType>; param_type() : _M_int(), _M_den(), _M_cp() { } template param_type(_InputIteratorB __bfirst, _InputIteratorB __bend, _InputIteratorW __wbegin); template param_type(initializer_list<_RealType> __bi, _Func __fw); template param_type(size_t __nw, _RealType __xmin, _RealType __xmax, _Func __fw); // See: http://cpp-next.com/archive/2010/10/implicit-move-must-go/ param_type(const param_type&) = default; param_type& operator=(const param_type&) = default; std::vector<_RealType> intervals() const { if (_M_int.empty()) { std::vector<_RealType> __tmp(2); __tmp[1] = _RealType(1); return __tmp; } else return _M_int; } std::vector densities() const { return _M_den.empty() ? std::vector(1, 1.0) : _M_den; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_int == __p2._M_int && __p1._M_den == __p2._M_den; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: void _M_initialize(); std::vector<_RealType> _M_int; std::vector _M_den; std::vector _M_cp; }; explicit piecewise_constant_distribution() : _M_param() { } template piecewise_constant_distribution(_InputIteratorB __bfirst, _InputIteratorB __bend, _InputIteratorW __wbegin) : _M_param(__bfirst, __bend, __wbegin) { } template piecewise_constant_distribution(initializer_list<_RealType> __bl, _Func __fw) : _M_param(__bl, __fw) { } template piecewise_constant_distribution(size_t __nw, _RealType __xmin, _RealType __xmax, _Func __fw) : _M_param(__nw, __xmin, __xmax, __fw) { } explicit piecewise_constant_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. */ void reset() { } /** * @brief Returns a vector of the intervals. */ std::vector<_RealType> intervals() const { if (_M_param._M_int.empty()) { std::vector<_RealType> __tmp(2); __tmp[1] = _RealType(1); return __tmp; } else return _M_param._M_int; } /** * @brief Returns a vector of the probability densities. */ std::vector densities() const { return _M_param._M_den.empty() ? std::vector(1, 1.0) : _M_param._M_den; } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return _M_param._M_int.empty() ? result_type(0) : _M_param._M_int.front(); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return _M_param._M_int.empty() ? result_type(1) : _M_param._M_int.back(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two piecewise constant distributions have the * same parameters. */ friend bool operator==(const piecewise_constant_distribution& __d1, const piecewise_constant_distribution& __d2) { return __d1._M_param == __d2._M_param; } /** * @brief Inserts a %piecewise_constant_distribution random * number distribution @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %piecewise_constant_distribution random number * distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::piecewise_constant_distribution<_RealType1>& __x); /** * @brief Extracts a %piecewise_constant_distribution random * number distribution @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %piecewise_constant_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error * state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::piecewise_constant_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two piecewise constant distributions have * different parameters. */ template inline bool operator!=(const std::piecewise_constant_distribution<_RealType>& __d1, const std::piecewise_constant_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief A piecewise_linear_distribution random number distribution. * * The formula for the piecewise linear probability mass function is * */ template class piecewise_linear_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef piecewise_linear_distribution<_RealType> distribution_type; friend class piecewise_linear_distribution<_RealType>; param_type() : _M_int(), _M_den(), _M_cp(), _M_m() { } template param_type(_InputIteratorB __bfirst, _InputIteratorB __bend, _InputIteratorW __wbegin); template param_type(initializer_list<_RealType> __bl, _Func __fw); template param_type(size_t __nw, _RealType __xmin, _RealType __xmax, _Func __fw); // See: http://cpp-next.com/archive/2010/10/implicit-move-must-go/ param_type(const param_type&) = default; param_type& operator=(const param_type&) = default; std::vector<_RealType> intervals() const { if (_M_int.empty()) { std::vector<_RealType> __tmp(2); __tmp[1] = _RealType(1); return __tmp; } else return _M_int; } std::vector densities() const { return _M_den.empty() ? std::vector(2, 1.0) : _M_den; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_int == __p2._M_int && __p1._M_den == __p2._M_den; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: void _M_initialize(); std::vector<_RealType> _M_int; std::vector _M_den; std::vector _M_cp; std::vector _M_m; }; explicit piecewise_linear_distribution() : _M_param() { } template piecewise_linear_distribution(_InputIteratorB __bfirst, _InputIteratorB __bend, _InputIteratorW __wbegin) : _M_param(__bfirst, __bend, __wbegin) { } template piecewise_linear_distribution(initializer_list<_RealType> __bl, _Func __fw) : _M_param(__bl, __fw) { } template piecewise_linear_distribution(size_t __nw, _RealType __xmin, _RealType __xmax, _Func __fw) : _M_param(__nw, __xmin, __xmax, __fw) { } explicit piecewise_linear_distribution(const param_type& __p) : _M_param(__p) { } /** * Resets the distribution state. */ void reset() { } /** * @brief Return the intervals of the distribution. */ std::vector<_RealType> intervals() const { if (_M_param._M_int.empty()) { std::vector<_RealType> __tmp(2); __tmp[1] = _RealType(1); return __tmp; } else return _M_param._M_int; } /** * @brief Return a vector of the probability densities of the * distribution. */ std::vector densities() const { return _M_param._M_den.empty() ? std::vector(2, 1.0) : _M_param._M_den; } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return _M_param._M_int.empty() ? result_type(0) : _M_param._M_int.front(); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return _M_param._M_int.empty() ? result_type(1) : _M_param._M_int.back(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two piecewise linear distributions have the * same parameters. */ friend bool operator==(const piecewise_linear_distribution& __d1, const piecewise_linear_distribution& __d2) { return __d1._M_param == __d2._M_param; } /** * @brief Inserts a %piecewise_linear_distribution random number * distribution @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %piecewise_linear_distribution random number * distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::piecewise_linear_distribution<_RealType1>& __x); /** * @brief Extracts a %piecewise_linear_distribution random number * distribution @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %piecewise_linear_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error * state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::piecewise_linear_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two piecewise linear distributions have * different parameters. */ template inline bool operator!=(const std::piecewise_linear_distribution<_RealType>& __d1, const std::piecewise_linear_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /* @} */ // group random_distributions_poisson /* @} */ // group random_distributions /** * @addtogroup random_utilities Random Number Utilities * @ingroup random * @{ */ /** * @brief The seed_seq class generates sequences of seeds for random * number generators. */ class seed_seq { public: /** The type of the seed vales. */ typedef uint_least32_t result_type; /** Default constructor. */ seed_seq() noexcept : _M_v() { } template seed_seq(std::initializer_list<_IntType> __il); template seed_seq(_InputIterator __begin, _InputIterator __end); // generating functions template void generate(_RandomAccessIterator __begin, _RandomAccessIterator __end); // property functions size_t size() const noexcept { return _M_v.size(); } template void param(_OutputIterator __dest) const { std::copy(_M_v.begin(), _M_v.end(), __dest); } // no copy functions seed_seq(const seed_seq&) = delete; seed_seq& operator=(const seed_seq&) = delete; private: std::vector _M_v; }; /* @} */ // group random_utilities /* @} */ // group random _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!\Hvv8/bits/random.tccnu[// random number generation (out of line) -*- C++ -*- // Copyright (C) 2009-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/random.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{random} */ #ifndef _RANDOM_TCC #define _RANDOM_TCC 1 #include // std::accumulate and std::partial_sum namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /* * (Further) implementation-space details. */ namespace __detail { // General case for x = (ax + c) mod m -- use Schrage's algorithm // to avoid integer overflow. // // Preconditions: a > 0, m > 0. // // Note: only works correctly for __m % __a < __m / __a. template _Tp _Mod<_Tp, __m, __a, __c, false, true>:: __calc(_Tp __x) { if (__a == 1) __x %= __m; else { static const _Tp __q = __m / __a; static const _Tp __r = __m % __a; _Tp __t1 = __a * (__x % __q); _Tp __t2 = __r * (__x / __q); if (__t1 >= __t2) __x = __t1 - __t2; else __x = __m - __t2 + __t1; } if (__c != 0) { const _Tp __d = __m - __x; if (__d > __c) __x += __c; else __x = __c - __d; } return __x; } template _OutputIterator __normalize(_InputIterator __first, _InputIterator __last, _OutputIterator __result, const _Tp& __factor) { for (; __first != __last; ++__first, ++__result) *__result = *__first / __factor; return __result; } } // namespace __detail template constexpr _UIntType linear_congruential_engine<_UIntType, __a, __c, __m>::multiplier; template constexpr _UIntType linear_congruential_engine<_UIntType, __a, __c, __m>::increment; template constexpr _UIntType linear_congruential_engine<_UIntType, __a, __c, __m>::modulus; template constexpr _UIntType linear_congruential_engine<_UIntType, __a, __c, __m>::default_seed; /** * Seeds the LCR with integral value @p __s, adjusted so that the * ring identity is never a member of the convergence set. */ template void linear_congruential_engine<_UIntType, __a, __c, __m>:: seed(result_type __s) { if ((__detail::__mod<_UIntType, __m>(__c) == 0) && (__detail::__mod<_UIntType, __m>(__s) == 0)) _M_x = 1; else _M_x = __detail::__mod<_UIntType, __m>(__s); } /** * Seeds the LCR engine with a value generated by @p __q. */ template template typename std::enable_if::value>::type linear_congruential_engine<_UIntType, __a, __c, __m>:: seed(_Sseq& __q) { const _UIntType __k0 = __m == 0 ? std::numeric_limits<_UIntType>::digits : std::__lg(__m); const _UIntType __k = (__k0 + 31) / 32; uint_least32_t __arr[__k + 3]; __q.generate(__arr + 0, __arr + __k + 3); _UIntType __factor = 1u; _UIntType __sum = 0u; for (size_t __j = 0; __j < __k; ++__j) { __sum += __arr[__j + 3] * __factor; __factor *= __detail::_Shift<_UIntType, 32>::__value; } seed(__sum); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const linear_congruential_engine<_UIntType, __a, __c, __m>& __lcr) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); __os.flags(__ios_base::dec | __ios_base::fixed | __ios_base::left); __os.fill(__os.widen(' ')); __os << __lcr._M_x; __os.flags(__flags); __os.fill(__fill); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, linear_congruential_engine<_UIntType, __a, __c, __m>& __lcr) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec); __is >> __lcr._M_x; __is.flags(__flags); return __is; } template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::word_size; template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::state_size; template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::shift_size; template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::mask_bits; template constexpr _UIntType mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::xor_mask; template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::tempering_u; template constexpr _UIntType mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::tempering_d; template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::tempering_s; template constexpr _UIntType mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::tempering_b; template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::tempering_t; template constexpr _UIntType mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::tempering_c; template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::tempering_l; template constexpr _UIntType mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>:: initialization_multiplier; template constexpr _UIntType mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::default_seed; template void mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>:: seed(result_type __sd) { _M_x[0] = __detail::__mod<_UIntType, __detail::_Shift<_UIntType, __w>::__value>(__sd); for (size_t __i = 1; __i < state_size; ++__i) { _UIntType __x = _M_x[__i - 1]; __x ^= __x >> (__w - 2); __x *= __f; __x += __detail::__mod<_UIntType, __n>(__i); _M_x[__i] = __detail::__mod<_UIntType, __detail::_Shift<_UIntType, __w>::__value>(__x); } _M_p = state_size; } template template typename std::enable_if::value>::type mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>:: seed(_Sseq& __q) { const _UIntType __upper_mask = (~_UIntType()) << __r; const size_t __k = (__w + 31) / 32; uint_least32_t __arr[__n * __k]; __q.generate(__arr + 0, __arr + __n * __k); bool __zero = true; for (size_t __i = 0; __i < state_size; ++__i) { _UIntType __factor = 1u; _UIntType __sum = 0u; for (size_t __j = 0; __j < __k; ++__j) { __sum += __arr[__k * __i + __j] * __factor; __factor *= __detail::_Shift<_UIntType, 32>::__value; } _M_x[__i] = __detail::__mod<_UIntType, __detail::_Shift<_UIntType, __w>::__value>(__sum); if (__zero) { if (__i == 0) { if ((_M_x[0] & __upper_mask) != 0u) __zero = false; } else if (_M_x[__i] != 0u) __zero = false; } } if (__zero) _M_x[0] = __detail::_Shift<_UIntType, __w - 1>::__value; _M_p = state_size; } template void mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>:: _M_gen_rand(void) { const _UIntType __upper_mask = (~_UIntType()) << __r; const _UIntType __lower_mask = ~__upper_mask; for (size_t __k = 0; __k < (__n - __m); ++__k) { _UIntType __y = ((_M_x[__k] & __upper_mask) | (_M_x[__k + 1] & __lower_mask)); _M_x[__k] = (_M_x[__k + __m] ^ (__y >> 1) ^ ((__y & 0x01) ? __a : 0)); } for (size_t __k = (__n - __m); __k < (__n - 1); ++__k) { _UIntType __y = ((_M_x[__k] & __upper_mask) | (_M_x[__k + 1] & __lower_mask)); _M_x[__k] = (_M_x[__k + (__m - __n)] ^ (__y >> 1) ^ ((__y & 0x01) ? __a : 0)); } _UIntType __y = ((_M_x[__n - 1] & __upper_mask) | (_M_x[0] & __lower_mask)); _M_x[__n - 1] = (_M_x[__m - 1] ^ (__y >> 1) ^ ((__y & 0x01) ? __a : 0)); _M_p = 0; } template void mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>:: discard(unsigned long long __z) { while (__z > state_size - _M_p) { __z -= state_size - _M_p; _M_gen_rand(); } _M_p += __z; } template typename mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::result_type mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>:: operator()() { // Reload the vector - cost is O(n) amortized over n calls. if (_M_p >= state_size) _M_gen_rand(); // Calculate o(x(i)). result_type __z = _M_x[_M_p++]; __z ^= (__z >> __u) & __d; __z ^= (__z << __s) & __b; __z ^= (__z << __t) & __c; __z ^= (__z >> __l); return __z; } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::dec | __ios_base::fixed | __ios_base::left); __os.fill(__space); for (size_t __i = 0; __i < __n; ++__i) __os << __x._M_x[__i] << __space; __os << __x._M_p; __os.flags(__flags); __os.fill(__fill); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); for (size_t __i = 0; __i < __n; ++__i) __is >> __x._M_x[__i]; __is >> __x._M_p; __is.flags(__flags); return __is; } template constexpr size_t subtract_with_carry_engine<_UIntType, __w, __s, __r>::word_size; template constexpr size_t subtract_with_carry_engine<_UIntType, __w, __s, __r>::short_lag; template constexpr size_t subtract_with_carry_engine<_UIntType, __w, __s, __r>::long_lag; template constexpr _UIntType subtract_with_carry_engine<_UIntType, __w, __s, __r>::default_seed; template void subtract_with_carry_engine<_UIntType, __w, __s, __r>:: seed(result_type __value) { std::linear_congruential_engine __lcg(__value == 0u ? default_seed : __value); const size_t __n = (__w + 31) / 32; for (size_t __i = 0; __i < long_lag; ++__i) { _UIntType __sum = 0u; _UIntType __factor = 1u; for (size_t __j = 0; __j < __n; ++__j) { __sum += __detail::__mod::__value> (__lcg()) * __factor; __factor *= __detail::_Shift<_UIntType, 32>::__value; } _M_x[__i] = __detail::__mod<_UIntType, __detail::_Shift<_UIntType, __w>::__value>(__sum); } _M_carry = (_M_x[long_lag - 1] == 0) ? 1 : 0; _M_p = 0; } template template typename std::enable_if::value>::type subtract_with_carry_engine<_UIntType, __w, __s, __r>:: seed(_Sseq& __q) { const size_t __k = (__w + 31) / 32; uint_least32_t __arr[__r * __k]; __q.generate(__arr + 0, __arr + __r * __k); for (size_t __i = 0; __i < long_lag; ++__i) { _UIntType __sum = 0u; _UIntType __factor = 1u; for (size_t __j = 0; __j < __k; ++__j) { __sum += __arr[__k * __i + __j] * __factor; __factor *= __detail::_Shift<_UIntType, 32>::__value; } _M_x[__i] = __detail::__mod<_UIntType, __detail::_Shift<_UIntType, __w>::__value>(__sum); } _M_carry = (_M_x[long_lag - 1] == 0) ? 1 : 0; _M_p = 0; } template typename subtract_with_carry_engine<_UIntType, __w, __s, __r>:: result_type subtract_with_carry_engine<_UIntType, __w, __s, __r>:: operator()() { // Derive short lag index from current index. long __ps = _M_p - short_lag; if (__ps < 0) __ps += long_lag; // Calculate new x(i) without overflow or division. // NB: Thanks to the requirements for _UIntType, _M_x[_M_p] + _M_carry // cannot overflow. _UIntType __xi; if (_M_x[__ps] >= _M_x[_M_p] + _M_carry) { __xi = _M_x[__ps] - _M_x[_M_p] - _M_carry; _M_carry = 0; } else { __xi = (__detail::_Shift<_UIntType, __w>::__value - _M_x[_M_p] - _M_carry + _M_x[__ps]); _M_carry = 1; } _M_x[_M_p] = __xi; // Adjust current index to loop around in ring buffer. if (++_M_p >= long_lag) _M_p = 0; return __xi; } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const subtract_with_carry_engine<_UIntType, __w, __s, __r>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::dec | __ios_base::fixed | __ios_base::left); __os.fill(__space); for (size_t __i = 0; __i < __r; ++__i) __os << __x._M_x[__i] << __space; __os << __x._M_carry << __space << __x._M_p; __os.flags(__flags); __os.fill(__fill); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, subtract_with_carry_engine<_UIntType, __w, __s, __r>& __x) { typedef std::basic_ostream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); for (size_t __i = 0; __i < __r; ++__i) __is >> __x._M_x[__i]; __is >> __x._M_carry; __is >> __x._M_p; __is.flags(__flags); return __is; } template constexpr size_t discard_block_engine<_RandomNumberEngine, __p, __r>::block_size; template constexpr size_t discard_block_engine<_RandomNumberEngine, __p, __r>::used_block; template typename discard_block_engine<_RandomNumberEngine, __p, __r>::result_type discard_block_engine<_RandomNumberEngine, __p, __r>:: operator()() { if (_M_n >= used_block) { _M_b.discard(block_size - _M_n); _M_n = 0; } ++_M_n; return _M_b(); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const discard_block_engine<_RandomNumberEngine, __p, __r>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::dec | __ios_base::fixed | __ios_base::left); __os.fill(__space); __os << __x.base() << __space << __x._M_n; __os.flags(__flags); __os.fill(__fill); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, discard_block_engine<_RandomNumberEngine, __p, __r>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); __is >> __x._M_b >> __x._M_n; __is.flags(__flags); return __is; } template typename independent_bits_engine<_RandomNumberEngine, __w, _UIntType>:: result_type independent_bits_engine<_RandomNumberEngine, __w, _UIntType>:: operator()() { typedef typename _RandomNumberEngine::result_type _Eresult_type; const _Eresult_type __r = (_M_b.max() - _M_b.min() < std::numeric_limits<_Eresult_type>::max() ? _M_b.max() - _M_b.min() + 1 : 0); const unsigned __edig = std::numeric_limits<_Eresult_type>::digits; const unsigned __m = __r ? std::__lg(__r) : __edig; typedef typename std::common_type<_Eresult_type, result_type>::type __ctype; const unsigned __cdig = std::numeric_limits<__ctype>::digits; unsigned __n, __n0; __ctype __s0, __s1, __y0, __y1; for (size_t __i = 0; __i < 2; ++__i) { __n = (__w + __m - 1) / __m + __i; __n0 = __n - __w % __n; const unsigned __w0 = __w / __n; // __w0 <= __m __s0 = 0; __s1 = 0; if (__w0 < __cdig) { __s0 = __ctype(1) << __w0; __s1 = __s0 << 1; } __y0 = 0; __y1 = 0; if (__r) { __y0 = __s0 * (__r / __s0); if (__s1) __y1 = __s1 * (__r / __s1); if (__r - __y0 <= __y0 / __n) break; } else break; } result_type __sum = 0; for (size_t __k = 0; __k < __n0; ++__k) { __ctype __u; do __u = _M_b() - _M_b.min(); while (__y0 && __u >= __y0); __sum = __s0 * __sum + (__s0 ? __u % __s0 : __u); } for (size_t __k = __n0; __k < __n; ++__k) { __ctype __u; do __u = _M_b() - _M_b.min(); while (__y1 && __u >= __y1); __sum = __s1 * __sum + (__s1 ? __u % __s1 : __u); } return __sum; } template constexpr size_t shuffle_order_engine<_RandomNumberEngine, __k>::table_size; template typename shuffle_order_engine<_RandomNumberEngine, __k>::result_type shuffle_order_engine<_RandomNumberEngine, __k>:: operator()() { size_t __j = __k * ((_M_y - _M_b.min()) / (_M_b.max() - _M_b.min() + 1.0L)); _M_y = _M_v[__j]; _M_v[__j] = _M_b(); return _M_y; } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const shuffle_order_engine<_RandomNumberEngine, __k>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::dec | __ios_base::fixed | __ios_base::left); __os.fill(__space); __os << __x.base(); for (size_t __i = 0; __i < __k; ++__i) __os << __space << __x._M_v[__i]; __os << __space << __x._M_y; __os.flags(__flags); __os.fill(__fill); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, shuffle_order_engine<_RandomNumberEngine, __k>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); __is >> __x._M_b; for (size_t __i = 0; __i < __k; ++__i) __is >> __x._M_v[__i]; __is >> __x._M_y; __is.flags(__flags); return __is; } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const uniform_int_distribution<_IntType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os << __x.a() << __space << __x.b(); __os.flags(__flags); __os.fill(__fill); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, uniform_int_distribution<_IntType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _IntType __a, __b; if (__is >> __a >> __b) __x.param(typename uniform_int_distribution<_IntType>:: param_type(__a, __b)); __is.flags(__flags); return __is; } template template void uniform_real_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); auto __range = __p.b() - __p.a(); while (__f != __t) *__f++ = __aurng() * __range + __p.a(); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const uniform_real_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.a() << __space << __x.b(); __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, uniform_real_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::skipws); _RealType __a, __b; if (__is >> __a >> __b) __x.param(typename uniform_real_distribution<_RealType>:: param_type(__a, __b)); __is.flags(__flags); return __is; } template void std::bernoulli_distribution:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); auto __limit = __p.p() * (__aurng.max() - __aurng.min()); while (__f != __t) *__f++ = (__aurng() - __aurng.min()) < __limit; } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const bernoulli_distribution& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__os.widen(' ')); __os.precision(std::numeric_limits::max_digits10); __os << __x.p(); __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template template typename geometric_distribution<_IntType>::result_type geometric_distribution<_IntType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { // About the epsilon thing see this thread: // http://gcc.gnu.org/ml/gcc-patches/2006-10/msg00971.html const double __naf = (1 - std::numeric_limits::epsilon()) / 2; // The largest _RealType convertible to _IntType. const double __thr = std::numeric_limits<_IntType>::max() + __naf; __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); double __cand; do __cand = std::floor(std::log(1.0 - __aurng()) / __param._M_log_1_p); while (__cand >= __thr); return result_type(__cand + __naf); } template template void geometric_distribution<_IntType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) // About the epsilon thing see this thread: // http://gcc.gnu.org/ml/gcc-patches/2006-10/msg00971.html const double __naf = (1 - std::numeric_limits::epsilon()) / 2; // The largest _RealType convertible to _IntType. const double __thr = std::numeric_limits<_IntType>::max() + __naf; __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); while (__f != __t) { double __cand; do __cand = std::floor(std::log(1.0 - __aurng()) / __param._M_log_1_p); while (__cand >= __thr); *__f++ = __cand + __naf; } } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const geometric_distribution<_IntType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__os.widen(' ')); __os.precision(std::numeric_limits::max_digits10); __os << __x.p(); __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, geometric_distribution<_IntType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::skipws); double __p; if (__is >> __p) __x.param(typename geometric_distribution<_IntType>::param_type(__p)); __is.flags(__flags); return __is; } // This is Leger's algorithm, also in Devroye, Ch. X, Example 1.5. template template typename negative_binomial_distribution<_IntType>::result_type negative_binomial_distribution<_IntType>:: operator()(_UniformRandomNumberGenerator& __urng) { const double __y = _M_gd(__urng); // XXX Is the constructor too slow? std::poisson_distribution __poisson(__y); return __poisson(__urng); } template template typename negative_binomial_distribution<_IntType>::result_type negative_binomial_distribution<_IntType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { typedef typename std::gamma_distribution::param_type param_type; const double __y = _M_gd(__urng, param_type(__p.k(), (1.0 - __p.p()) / __p.p())); std::poisson_distribution __poisson(__y); return __poisson(__urng); } template template void negative_binomial_distribution<_IntType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) while (__f != __t) { const double __y = _M_gd(__urng); // XXX Is the constructor too slow? std::poisson_distribution __poisson(__y); *__f++ = __poisson(__urng); } } template template void negative_binomial_distribution<_IntType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) typename std::gamma_distribution::param_type __p2(__p.k(), (1.0 - __p.p()) / __p.p()); while (__f != __t) { const double __y = _M_gd(__urng, __p2); std::poisson_distribution __poisson(__y); *__f++ = __poisson(__urng); } } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const negative_binomial_distribution<_IntType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__os.widen(' ')); __os.precision(std::numeric_limits::max_digits10); __os << __x.k() << __space << __x.p() << __space << __x._M_gd; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, negative_binomial_distribution<_IntType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::skipws); _IntType __k; double __p; if (__is >> __k >> __p >> __x._M_gd) __x.param(typename negative_binomial_distribution<_IntType>:: param_type(__k, __p)); __is.flags(__flags); return __is; } template void poisson_distribution<_IntType>::param_type:: _M_initialize() { #if _GLIBCXX_USE_C99_MATH_TR1 if (_M_mean >= 12) { const double __m = std::floor(_M_mean); _M_lm_thr = std::log(_M_mean); _M_lfm = std::lgamma(__m + 1); _M_sm = std::sqrt(__m); const double __pi_4 = 0.7853981633974483096156608458198757L; const double __dx = std::sqrt(2 * __m * std::log(32 * __m / __pi_4)); _M_d = std::round(std::max(6.0, std::min(__m, __dx))); const double __cx = 2 * __m + _M_d; _M_scx = std::sqrt(__cx / 2); _M_1cx = 1 / __cx; _M_c2b = std::sqrt(__pi_4 * __cx) * std::exp(_M_1cx); _M_cb = 2 * __cx * std::exp(-_M_d * _M_1cx * (1 + _M_d / 2)) / _M_d; } else #endif _M_lm_thr = std::exp(-_M_mean); } /** * A rejection algorithm when mean >= 12 and a simple method based * upon the multiplication of uniform random variates otherwise. * NB: The former is available only if _GLIBCXX_USE_C99_MATH_TR1 * is defined. * * Reference: * Devroye, L. Non-Uniform Random Variates Generation. Springer-Verlag, * New York, 1986, Ch. X, Sects. 3.3 & 3.4 (+ Errata!). */ template template typename poisson_distribution<_IntType>::result_type poisson_distribution<_IntType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); #if _GLIBCXX_USE_C99_MATH_TR1 if (__param.mean() >= 12) { double __x; // See comments above... const double __naf = (1 - std::numeric_limits::epsilon()) / 2; const double __thr = std::numeric_limits<_IntType>::max() + __naf; const double __m = std::floor(__param.mean()); // sqrt(pi / 2) const double __spi_2 = 1.2533141373155002512078826424055226L; const double __c1 = __param._M_sm * __spi_2; const double __c2 = __param._M_c2b + __c1; const double __c3 = __c2 + 1; const double __c4 = __c3 + 1; // 1 / 78 const double __178 = 0.0128205128205128205128205128205128L; // e^(1 / 78) const double __e178 = 1.0129030479320018583185514777512983L; const double __c5 = __c4 + __e178; const double __c = __param._M_cb + __c5; const double __2cx = 2 * (2 * __m + __param._M_d); bool __reject = true; do { const double __u = __c * __aurng(); const double __e = -std::log(1.0 - __aurng()); double __w = 0.0; if (__u <= __c1) { const double __n = _M_nd(__urng); const double __y = -std::abs(__n) * __param._M_sm - 1; __x = std::floor(__y); __w = -__n * __n / 2; if (__x < -__m) continue; } else if (__u <= __c2) { const double __n = _M_nd(__urng); const double __y = 1 + std::abs(__n) * __param._M_scx; __x = std::ceil(__y); __w = __y * (2 - __y) * __param._M_1cx; if (__x > __param._M_d) continue; } else if (__u <= __c3) // NB: This case not in the book, nor in the Errata, // but should be ok... __x = -1; else if (__u <= __c4) __x = 0; else if (__u <= __c5) { __x = 1; // Only in the Errata, see libstdc++/83237. __w = __178; } else { const double __v = -std::log(1.0 - __aurng()); const double __y = __param._M_d + __v * __2cx / __param._M_d; __x = std::ceil(__y); __w = -__param._M_d * __param._M_1cx * (1 + __y / 2); } __reject = (__w - __e - __x * __param._M_lm_thr > __param._M_lfm - std::lgamma(__x + __m + 1)); __reject |= __x + __m >= __thr; } while (__reject); return result_type(__x + __m + __naf); } else #endif { _IntType __x = 0; double __prod = 1.0; do { __prod *= __aurng(); __x += 1; } while (__prod > __param._M_lm_thr); return __x - 1; } } template template void poisson_distribution<_IntType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) // We could duplicate everything from operator()... while (__f != __t) *__f++ = this->operator()(__urng, __param); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const poisson_distribution<_IntType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits::max_digits10); __os << __x.mean() << __space << __x._M_nd; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, poisson_distribution<_IntType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::skipws); double __mean; if (__is >> __mean >> __x._M_nd) __x.param(typename poisson_distribution<_IntType>::param_type(__mean)); __is.flags(__flags); return __is; } template void binomial_distribution<_IntType>::param_type:: _M_initialize() { const double __p12 = _M_p <= 0.5 ? _M_p : 1.0 - _M_p; _M_easy = true; #if _GLIBCXX_USE_C99_MATH_TR1 if (_M_t * __p12 >= 8) { _M_easy = false; const double __np = std::floor(_M_t * __p12); const double __pa = __np / _M_t; const double __1p = 1 - __pa; const double __pi_4 = 0.7853981633974483096156608458198757L; const double __d1x = std::sqrt(__np * __1p * std::log(32 * __np / (81 * __pi_4 * __1p))); _M_d1 = std::round(std::max(1.0, __d1x)); const double __d2x = std::sqrt(__np * __1p * std::log(32 * _M_t * __1p / (__pi_4 * __pa))); _M_d2 = std::round(std::max(1.0, __d2x)); // sqrt(pi / 2) const double __spi_2 = 1.2533141373155002512078826424055226L; _M_s1 = std::sqrt(__np * __1p) * (1 + _M_d1 / (4 * __np)); _M_s2 = std::sqrt(__np * __1p) * (1 + _M_d2 / (4 * _M_t * __1p)); _M_c = 2 * _M_d1 / __np; _M_a1 = std::exp(_M_c) * _M_s1 * __spi_2; const double __a12 = _M_a1 + _M_s2 * __spi_2; const double __s1s = _M_s1 * _M_s1; _M_a123 = __a12 + (std::exp(_M_d1 / (_M_t * __1p)) * 2 * __s1s / _M_d1 * std::exp(-_M_d1 * _M_d1 / (2 * __s1s))); const double __s2s = _M_s2 * _M_s2; _M_s = (_M_a123 + 2 * __s2s / _M_d2 * std::exp(-_M_d2 * _M_d2 / (2 * __s2s))); _M_lf = (std::lgamma(__np + 1) + std::lgamma(_M_t - __np + 1)); _M_lp1p = std::log(__pa / __1p); _M_q = -std::log(1 - (__p12 - __pa) / __1p); } else #endif _M_q = -std::log(1 - __p12); } template template typename binomial_distribution<_IntType>::result_type binomial_distribution<_IntType>:: _M_waiting(_UniformRandomNumberGenerator& __urng, _IntType __t, double __q) { _IntType __x = 0; double __sum = 0.0; __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); do { if (__t == __x) return __x; const double __e = -std::log(1.0 - __aurng()); __sum += __e / (__t - __x); __x += 1; } while (__sum <= __q); return __x - 1; } /** * A rejection algorithm when t * p >= 8 and a simple waiting time * method - the second in the referenced book - otherwise. * NB: The former is available only if _GLIBCXX_USE_C99_MATH_TR1 * is defined. * * Reference: * Devroye, L. Non-Uniform Random Variates Generation. Springer-Verlag, * New York, 1986, Ch. X, Sect. 4 (+ Errata!). */ template template typename binomial_distribution<_IntType>::result_type binomial_distribution<_IntType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { result_type __ret; const _IntType __t = __param.t(); const double __p = __param.p(); const double __p12 = __p <= 0.5 ? __p : 1.0 - __p; __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); #if _GLIBCXX_USE_C99_MATH_TR1 if (!__param._M_easy) { double __x; // See comments above... const double __naf = (1 - std::numeric_limits::epsilon()) / 2; const double __thr = std::numeric_limits<_IntType>::max() + __naf; const double __np = std::floor(__t * __p12); // sqrt(pi / 2) const double __spi_2 = 1.2533141373155002512078826424055226L; const double __a1 = __param._M_a1; const double __a12 = __a1 + __param._M_s2 * __spi_2; const double __a123 = __param._M_a123; const double __s1s = __param._M_s1 * __param._M_s1; const double __s2s = __param._M_s2 * __param._M_s2; bool __reject; do { const double __u = __param._M_s * __aurng(); double __v; if (__u <= __a1) { const double __n = _M_nd(__urng); const double __y = __param._M_s1 * std::abs(__n); __reject = __y >= __param._M_d1; if (!__reject) { const double __e = -std::log(1.0 - __aurng()); __x = std::floor(__y); __v = -__e - __n * __n / 2 + __param._M_c; } } else if (__u <= __a12) { const double __n = _M_nd(__urng); const double __y = __param._M_s2 * std::abs(__n); __reject = __y >= __param._M_d2; if (!__reject) { const double __e = -std::log(1.0 - __aurng()); __x = std::floor(-__y); __v = -__e - __n * __n / 2; } } else if (__u <= __a123) { const double __e1 = -std::log(1.0 - __aurng()); const double __e2 = -std::log(1.0 - __aurng()); const double __y = __param._M_d1 + 2 * __s1s * __e1 / __param._M_d1; __x = std::floor(__y); __v = (-__e2 + __param._M_d1 * (1 / (__t - __np) -__y / (2 * __s1s))); __reject = false; } else { const double __e1 = -std::log(1.0 - __aurng()); const double __e2 = -std::log(1.0 - __aurng()); const double __y = __param._M_d2 + 2 * __s2s * __e1 / __param._M_d2; __x = std::floor(-__y); __v = -__e2 - __param._M_d2 * __y / (2 * __s2s); __reject = false; } __reject = __reject || __x < -__np || __x > __t - __np; if (!__reject) { const double __lfx = std::lgamma(__np + __x + 1) + std::lgamma(__t - (__np + __x) + 1); __reject = __v > __param._M_lf - __lfx + __x * __param._M_lp1p; } __reject |= __x + __np >= __thr; } while (__reject); __x += __np + __naf; const _IntType __z = _M_waiting(__urng, __t - _IntType(__x), __param._M_q); __ret = _IntType(__x) + __z; } else #endif __ret = _M_waiting(__urng, __t, __param._M_q); if (__p12 != __p) __ret = __t - __ret; return __ret; } template template void binomial_distribution<_IntType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) // We could duplicate everything from operator()... while (__f != __t) *__f++ = this->operator()(__urng, __param); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const binomial_distribution<_IntType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits::max_digits10); __os << __x.t() << __space << __x.p() << __space << __x._M_nd; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, binomial_distribution<_IntType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _IntType __t; double __p; if (__is >> __t >> __p >> __x._M_nd) __x.param(typename binomial_distribution<_IntType>:: param_type(__t, __p)); __is.flags(__flags); return __is; } template template void std::exponential_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); while (__f != __t) *__f++ = -std::log(result_type(1) - __aurng()) / __p.lambda(); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const exponential_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__os.widen(' ')); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.lambda(); __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, exponential_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __lambda; if (__is >> __lambda) __x.param(typename exponential_distribution<_RealType>:: param_type(__lambda)); __is.flags(__flags); return __is; } /** * Polar method due to Marsaglia. * * Devroye, L. Non-Uniform Random Variates Generation. Springer-Verlag, * New York, 1986, Ch. V, Sect. 4.4. */ template template typename normal_distribution<_RealType>::result_type normal_distribution<_RealType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { result_type __ret; __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); if (_M_saved_available) { _M_saved_available = false; __ret = _M_saved; } else { result_type __x, __y, __r2; do { __x = result_type(2.0) * __aurng() - 1.0; __y = result_type(2.0) * __aurng() - 1.0; __r2 = __x * __x + __y * __y; } while (__r2 > 1.0 || __r2 == 0.0); const result_type __mult = std::sqrt(-2 * std::log(__r2) / __r2); _M_saved = __x * __mult; _M_saved_available = true; __ret = __y * __mult; } __ret = __ret * __param.stddev() + __param.mean(); return __ret; } template template void normal_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) if (__f == __t) return; if (_M_saved_available) { _M_saved_available = false; *__f++ = _M_saved * __param.stddev() + __param.mean(); if (__f == __t) return; } __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); while (__f + 1 < __t) { result_type __x, __y, __r2; do { __x = result_type(2.0) * __aurng() - 1.0; __y = result_type(2.0) * __aurng() - 1.0; __r2 = __x * __x + __y * __y; } while (__r2 > 1.0 || __r2 == 0.0); const result_type __mult = std::sqrt(-2 * std::log(__r2) / __r2); *__f++ = __y * __mult * __param.stddev() + __param.mean(); *__f++ = __x * __mult * __param.stddev() + __param.mean(); } if (__f != __t) { result_type __x, __y, __r2; do { __x = result_type(2.0) * __aurng() - 1.0; __y = result_type(2.0) * __aurng() - 1.0; __r2 = __x * __x + __y * __y; } while (__r2 > 1.0 || __r2 == 0.0); const result_type __mult = std::sqrt(-2 * std::log(__r2) / __r2); _M_saved = __x * __mult; _M_saved_available = true; *__f = __y * __mult * __param.stddev() + __param.mean(); } } template bool operator==(const std::normal_distribution<_RealType>& __d1, const std::normal_distribution<_RealType>& __d2) { if (__d1._M_param == __d2._M_param && __d1._M_saved_available == __d2._M_saved_available) { if (__d1._M_saved_available && __d1._M_saved == __d2._M_saved) return true; else if(!__d1._M_saved_available) return true; else return false; } else return false; } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const normal_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.mean() << __space << __x.stddev() << __space << __x._M_saved_available; if (__x._M_saved_available) __os << __space << __x._M_saved; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, normal_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); double __mean, __stddev; bool __saved_avail; if (__is >> __mean >> __stddev >> __saved_avail) { if (!__saved_avail || (__is >> __x._M_saved)) { __x._M_saved_available = __saved_avail; __x.param(typename normal_distribution<_RealType>:: param_type(__mean, __stddev)); } } __is.flags(__flags); return __is; } template template void lognormal_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) while (__f != __t) *__f++ = std::exp(__p.s() * _M_nd(__urng) + __p.m()); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const lognormal_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.m() << __space << __x.s() << __space << __x._M_nd; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, lognormal_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __m, __s; if (__is >> __m >> __s >> __x._M_nd) __x.param(typename lognormal_distribution<_RealType>:: param_type(__m, __s)); __is.flags(__flags); return __is; } template template void std::chi_squared_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) while (__f != __t) *__f++ = 2 * _M_gd(__urng); } template template void std::chi_squared_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const typename std::gamma_distribution::param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) while (__f != __t) *__f++ = 2 * _M_gd(__urng, __p); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const chi_squared_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.n() << __space << __x._M_gd; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, chi_squared_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __n; if (__is >> __n >> __x._M_gd) __x.param(typename chi_squared_distribution<_RealType>:: param_type(__n)); __is.flags(__flags); return __is; } template template typename cauchy_distribution<_RealType>::result_type cauchy_distribution<_RealType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); _RealType __u; do __u = __aurng(); while (__u == 0.5); const _RealType __pi = 3.1415926535897932384626433832795029L; return __p.a() + __p.b() * std::tan(__pi * __u); } template template void cauchy_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) const _RealType __pi = 3.1415926535897932384626433832795029L; __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); while (__f != __t) { _RealType __u; do __u = __aurng(); while (__u == 0.5); *__f++ = __p.a() + __p.b() * std::tan(__pi * __u); } } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const cauchy_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.a() << __space << __x.b(); __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, cauchy_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __a, __b; if (__is >> __a >> __b) __x.param(typename cauchy_distribution<_RealType>:: param_type(__a, __b)); __is.flags(__flags); return __is; } template template void std::fisher_f_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) while (__f != __t) *__f++ = ((_M_gd_x(__urng) * n()) / (_M_gd_y(__urng) * m())); } template template void std::fisher_f_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) typedef typename std::gamma_distribution::param_type param_type; param_type __p1(__p.m() / 2); param_type __p2(__p.n() / 2); while (__f != __t) *__f++ = ((_M_gd_x(__urng, __p1) * n()) / (_M_gd_y(__urng, __p2) * m())); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const fisher_f_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.m() << __space << __x.n() << __space << __x._M_gd_x << __space << __x._M_gd_y; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, fisher_f_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __m, __n; if (__is >> __m >> __n >> __x._M_gd_x >> __x._M_gd_y) __x.param(typename fisher_f_distribution<_RealType>:: param_type(__m, __n)); __is.flags(__flags); return __is; } template template void std::student_t_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) while (__f != __t) *__f++ = _M_nd(__urng) * std::sqrt(n() / _M_gd(__urng)); } template template void std::student_t_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) typename std::gamma_distribution::param_type __p2(__p.n() / 2, 2); while (__f != __t) *__f++ = _M_nd(__urng) * std::sqrt(__p.n() / _M_gd(__urng, __p2)); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const student_t_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.n() << __space << __x._M_nd << __space << __x._M_gd; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, student_t_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __n; if (__is >> __n >> __x._M_nd >> __x._M_gd) __x.param(typename student_t_distribution<_RealType>::param_type(__n)); __is.flags(__flags); return __is; } template void gamma_distribution<_RealType>::param_type:: _M_initialize() { _M_malpha = _M_alpha < 1.0 ? _M_alpha + _RealType(1.0) : _M_alpha; const _RealType __a1 = _M_malpha - _RealType(1.0) / _RealType(3.0); _M_a2 = _RealType(1.0) / std::sqrt(_RealType(9.0) * __a1); } /** * Marsaglia, G. and Tsang, W. W. * "A Simple Method for Generating Gamma Variables" * ACM Transactions on Mathematical Software, 26, 3, 363-372, 2000. */ template template typename gamma_distribution<_RealType>::result_type gamma_distribution<_RealType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); result_type __u, __v, __n; const result_type __a1 = (__param._M_malpha - _RealType(1.0) / _RealType(3.0)); do { do { __n = _M_nd(__urng); __v = result_type(1.0) + __param._M_a2 * __n; } while (__v <= 0.0); __v = __v * __v * __v; __u = __aurng(); } while (__u > result_type(1.0) - 0.0331 * __n * __n * __n * __n && (std::log(__u) > (0.5 * __n * __n + __a1 * (1.0 - __v + std::log(__v))))); if (__param.alpha() == __param._M_malpha) return __a1 * __v * __param.beta(); else { do __u = __aurng(); while (__u == 0.0); return (std::pow(__u, result_type(1.0) / __param.alpha()) * __a1 * __v * __param.beta()); } } template template void gamma_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); result_type __u, __v, __n; const result_type __a1 = (__param._M_malpha - _RealType(1.0) / _RealType(3.0)); if (__param.alpha() == __param._M_malpha) while (__f != __t) { do { do { __n = _M_nd(__urng); __v = result_type(1.0) + __param._M_a2 * __n; } while (__v <= 0.0); __v = __v * __v * __v; __u = __aurng(); } while (__u > result_type(1.0) - 0.0331 * __n * __n * __n * __n && (std::log(__u) > (0.5 * __n * __n + __a1 * (1.0 - __v + std::log(__v))))); *__f++ = __a1 * __v * __param.beta(); } else while (__f != __t) { do { do { __n = _M_nd(__urng); __v = result_type(1.0) + __param._M_a2 * __n; } while (__v <= 0.0); __v = __v * __v * __v; __u = __aurng(); } while (__u > result_type(1.0) - 0.0331 * __n * __n * __n * __n && (std::log(__u) > (0.5 * __n * __n + __a1 * (1.0 - __v + std::log(__v))))); do __u = __aurng(); while (__u == 0.0); *__f++ = (std::pow(__u, result_type(1.0) / __param.alpha()) * __a1 * __v * __param.beta()); } } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const gamma_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.alpha() << __space << __x.beta() << __space << __x._M_nd; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, gamma_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __alpha_val, __beta_val; if (__is >> __alpha_val >> __beta_val >> __x._M_nd) __x.param(typename gamma_distribution<_RealType>:: param_type(__alpha_val, __beta_val)); __is.flags(__flags); return __is; } template template typename weibull_distribution<_RealType>::result_type weibull_distribution<_RealType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); return __p.b() * std::pow(-std::log(result_type(1) - __aurng()), result_type(1) / __p.a()); } template template void weibull_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); auto __inv_a = result_type(1) / __p.a(); while (__f != __t) *__f++ = __p.b() * std::pow(-std::log(result_type(1) - __aurng()), __inv_a); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const weibull_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.a() << __space << __x.b(); __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, weibull_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __a, __b; if (__is >> __a >> __b) __x.param(typename weibull_distribution<_RealType>:: param_type(__a, __b)); __is.flags(__flags); return __is; } template template typename extreme_value_distribution<_RealType>::result_type extreme_value_distribution<_RealType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); return __p.a() - __p.b() * std::log(-std::log(result_type(1) - __aurng())); } template template void extreme_value_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); while (__f != __t) *__f++ = __p.a() - __p.b() * std::log(-std::log(result_type(1) - __aurng())); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const extreme_value_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.a() << __space << __x.b(); __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, extreme_value_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __a, __b; if (__is >> __a >> __b) __x.param(typename extreme_value_distribution<_RealType>:: param_type(__a, __b)); __is.flags(__flags); return __is; } template void discrete_distribution<_IntType>::param_type:: _M_initialize() { if (_M_prob.size() < 2) { _M_prob.clear(); return; } const double __sum = std::accumulate(_M_prob.begin(), _M_prob.end(), 0.0); // Now normalize the probabilites. __detail::__normalize(_M_prob.begin(), _M_prob.end(), _M_prob.begin(), __sum); // Accumulate partial sums. _M_cp.reserve(_M_prob.size()); std::partial_sum(_M_prob.begin(), _M_prob.end(), std::back_inserter(_M_cp)); // Make sure the last cumulative probability is one. _M_cp[_M_cp.size() - 1] = 1.0; } template template discrete_distribution<_IntType>::param_type:: param_type(size_t __nw, double __xmin, double __xmax, _Func __fw) : _M_prob(), _M_cp() { const size_t __n = __nw == 0 ? 1 : __nw; const double __delta = (__xmax - __xmin) / __n; _M_prob.reserve(__n); for (size_t __k = 0; __k < __nw; ++__k) _M_prob.push_back(__fw(__xmin + __k * __delta + 0.5 * __delta)); _M_initialize(); } template template typename discrete_distribution<_IntType>::result_type discrete_distribution<_IntType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { if (__param._M_cp.empty()) return result_type(0); __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); const double __p = __aurng(); auto __pos = std::lower_bound(__param._M_cp.begin(), __param._M_cp.end(), __p); return __pos - __param._M_cp.begin(); } template template void discrete_distribution<_IntType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) if (__param._M_cp.empty()) { while (__f != __t) *__f++ = result_type(0); return; } __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); while (__f != __t) { const double __p = __aurng(); auto __pos = std::lower_bound(__param._M_cp.begin(), __param._M_cp.end(), __p); *__f++ = __pos - __param._M_cp.begin(); } } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const discrete_distribution<_IntType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits::max_digits10); std::vector __prob = __x.probabilities(); __os << __prob.size(); for (auto __dit = __prob.begin(); __dit != __prob.end(); ++__dit) __os << __space << *__dit; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } namespace __detail { template basic_istream<_CharT, _Traits>& __extract_params(basic_istream<_CharT, _Traits>& __is, vector<_ValT>& __vals, size_t __n) { __vals.reserve(__n); while (__n--) { _ValT __val; if (__is >> __val) __vals.push_back(__val); else break; } return __is; } } // namespace __detail template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, discrete_distribution<_IntType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); size_t __n; if (__is >> __n) { std::vector __prob_vec; if (__detail::__extract_params(__is, __prob_vec, __n)) __x.param({__prob_vec.begin(), __prob_vec.end()}); } __is.flags(__flags); return __is; } template void piecewise_constant_distribution<_RealType>::param_type:: _M_initialize() { if (_M_int.size() < 2 || (_M_int.size() == 2 && _M_int[0] == _RealType(0) && _M_int[1] == _RealType(1))) { _M_int.clear(); _M_den.clear(); return; } const double __sum = std::accumulate(_M_den.begin(), _M_den.end(), 0.0); __detail::__normalize(_M_den.begin(), _M_den.end(), _M_den.begin(), __sum); _M_cp.reserve(_M_den.size()); std::partial_sum(_M_den.begin(), _M_den.end(), std::back_inserter(_M_cp)); // Make sure the last cumulative probability is one. _M_cp[_M_cp.size() - 1] = 1.0; for (size_t __k = 0; __k < _M_den.size(); ++__k) _M_den[__k] /= _M_int[__k + 1] - _M_int[__k]; } template template piecewise_constant_distribution<_RealType>::param_type:: param_type(_InputIteratorB __bbegin, _InputIteratorB __bend, _InputIteratorW __wbegin) : _M_int(), _M_den(), _M_cp() { if (__bbegin != __bend) { for (;;) { _M_int.push_back(*__bbegin); ++__bbegin; if (__bbegin == __bend) break; _M_den.push_back(*__wbegin); ++__wbegin; } } _M_initialize(); } template template piecewise_constant_distribution<_RealType>::param_type:: param_type(initializer_list<_RealType> __bl, _Func __fw) : _M_int(), _M_den(), _M_cp() { _M_int.reserve(__bl.size()); for (auto __biter = __bl.begin(); __biter != __bl.end(); ++__biter) _M_int.push_back(*__biter); _M_den.reserve(_M_int.size() - 1); for (size_t __k = 0; __k < _M_int.size() - 1; ++__k) _M_den.push_back(__fw(0.5 * (_M_int[__k + 1] + _M_int[__k]))); _M_initialize(); } template template piecewise_constant_distribution<_RealType>::param_type:: param_type(size_t __nw, _RealType __xmin, _RealType __xmax, _Func __fw) : _M_int(), _M_den(), _M_cp() { const size_t __n = __nw == 0 ? 1 : __nw; const _RealType __delta = (__xmax - __xmin) / __n; _M_int.reserve(__n + 1); for (size_t __k = 0; __k <= __nw; ++__k) _M_int.push_back(__xmin + __k * __delta); _M_den.reserve(__n); for (size_t __k = 0; __k < __nw; ++__k) _M_den.push_back(__fw(_M_int[__k] + 0.5 * __delta)); _M_initialize(); } template template typename piecewise_constant_distribution<_RealType>::result_type piecewise_constant_distribution<_RealType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); const double __p = __aurng(); if (__param._M_cp.empty()) return __p; auto __pos = std::lower_bound(__param._M_cp.begin(), __param._M_cp.end(), __p); const size_t __i = __pos - __param._M_cp.begin(); const double __pref = __i > 0 ? __param._M_cp[__i - 1] : 0.0; return __param._M_int[__i] + (__p - __pref) / __param._M_den[__i]; } template template void piecewise_constant_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); if (__param._M_cp.empty()) { while (__f != __t) *__f++ = __aurng(); return; } while (__f != __t) { const double __p = __aurng(); auto __pos = std::lower_bound(__param._M_cp.begin(), __param._M_cp.end(), __p); const size_t __i = __pos - __param._M_cp.begin(); const double __pref = __i > 0 ? __param._M_cp[__i - 1] : 0.0; *__f++ = (__param._M_int[__i] + (__p - __pref) / __param._M_den[__i]); } } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const piecewise_constant_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); std::vector<_RealType> __int = __x.intervals(); __os << __int.size() - 1; for (auto __xit = __int.begin(); __xit != __int.end(); ++__xit) __os << __space << *__xit; std::vector __den = __x.densities(); for (auto __dit = __den.begin(); __dit != __den.end(); ++__dit) __os << __space << *__dit; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, piecewise_constant_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); size_t __n; if (__is >> __n) { std::vector<_RealType> __int_vec; if (__detail::__extract_params(__is, __int_vec, __n + 1)) { std::vector __den_vec; if (__detail::__extract_params(__is, __den_vec, __n)) { __x.param({ __int_vec.begin(), __int_vec.end(), __den_vec.begin() }); } } } __is.flags(__flags); return __is; } template void piecewise_linear_distribution<_RealType>::param_type:: _M_initialize() { if (_M_int.size() < 2 || (_M_int.size() == 2 && _M_int[0] == _RealType(0) && _M_int[1] == _RealType(1) && _M_den[0] == _M_den[1])) { _M_int.clear(); _M_den.clear(); return; } double __sum = 0.0; _M_cp.reserve(_M_int.size() - 1); _M_m.reserve(_M_int.size() - 1); for (size_t __k = 0; __k < _M_int.size() - 1; ++__k) { const _RealType __delta = _M_int[__k + 1] - _M_int[__k]; __sum += 0.5 * (_M_den[__k + 1] + _M_den[__k]) * __delta; _M_cp.push_back(__sum); _M_m.push_back((_M_den[__k + 1] - _M_den[__k]) / __delta); } // Now normalize the densities... __detail::__normalize(_M_den.begin(), _M_den.end(), _M_den.begin(), __sum); // ... and partial sums... __detail::__normalize(_M_cp.begin(), _M_cp.end(), _M_cp.begin(), __sum); // ... and slopes. __detail::__normalize(_M_m.begin(), _M_m.end(), _M_m.begin(), __sum); // Make sure the last cumulative probablility is one. _M_cp[_M_cp.size() - 1] = 1.0; } template template piecewise_linear_distribution<_RealType>::param_type:: param_type(_InputIteratorB __bbegin, _InputIteratorB __bend, _InputIteratorW __wbegin) : _M_int(), _M_den(), _M_cp(), _M_m() { for (; __bbegin != __bend; ++__bbegin, ++__wbegin) { _M_int.push_back(*__bbegin); _M_den.push_back(*__wbegin); } _M_initialize(); } template template piecewise_linear_distribution<_RealType>::param_type:: param_type(initializer_list<_RealType> __bl, _Func __fw) : _M_int(), _M_den(), _M_cp(), _M_m() { _M_int.reserve(__bl.size()); _M_den.reserve(__bl.size()); for (auto __biter = __bl.begin(); __biter != __bl.end(); ++__biter) { _M_int.push_back(*__biter); _M_den.push_back(__fw(*__biter)); } _M_initialize(); } template template piecewise_linear_distribution<_RealType>::param_type:: param_type(size_t __nw, _RealType __xmin, _RealType __xmax, _Func __fw) : _M_int(), _M_den(), _M_cp(), _M_m() { const size_t __n = __nw == 0 ? 1 : __nw; const _RealType __delta = (__xmax - __xmin) / __n; _M_int.reserve(__n + 1); _M_den.reserve(__n + 1); for (size_t __k = 0; __k <= __nw; ++__k) { _M_int.push_back(__xmin + __k * __delta); _M_den.push_back(__fw(_M_int[__k] + __delta)); } _M_initialize(); } template template typename piecewise_linear_distribution<_RealType>::result_type piecewise_linear_distribution<_RealType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); const double __p = __aurng(); if (__param._M_cp.empty()) return __p; auto __pos = std::lower_bound(__param._M_cp.begin(), __param._M_cp.end(), __p); const size_t __i = __pos - __param._M_cp.begin(); const double __pref = __i > 0 ? __param._M_cp[__i - 1] : 0.0; const double __a = 0.5 * __param._M_m[__i]; const double __b = __param._M_den[__i]; const double __cm = __p - __pref; _RealType __x = __param._M_int[__i]; if (__a == 0) __x += __cm / __b; else { const double __d = __b * __b + 4.0 * __a * __cm; __x += 0.5 * (std::sqrt(__d) - __b) / __a; } return __x; } template template void piecewise_linear_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) // We could duplicate everything from operator()... while (__f != __t) *__f++ = this->operator()(__urng, __param); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const piecewise_linear_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); std::vector<_RealType> __int = __x.intervals(); __os << __int.size() - 1; for (auto __xit = __int.begin(); __xit != __int.end(); ++__xit) __os << __space << *__xit; std::vector __den = __x.densities(); for (auto __dit = __den.begin(); __dit != __den.end(); ++__dit) __os << __space << *__dit; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, piecewise_linear_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); size_t __n; if (__is >> __n) { vector<_RealType> __int_vec; if (__detail::__extract_params(__is, __int_vec, __n + 1)) { vector __den_vec; if (__detail::__extract_params(__is, __den_vec, __n + 1)) { __x.param({ __int_vec.begin(), __int_vec.end(), __den_vec.begin() }); } } } __is.flags(__flags); return __is; } template seed_seq::seed_seq(std::initializer_list<_IntType> __il) { for (auto __iter = __il.begin(); __iter != __il.end(); ++__iter) _M_v.push_back(__detail::__mod::__value>(*__iter)); } template seed_seq::seed_seq(_InputIterator __begin, _InputIterator __end) { for (_InputIterator __iter = __begin; __iter != __end; ++__iter) _M_v.push_back(__detail::__mod::__value>(*__iter)); } template void seed_seq::generate(_RandomAccessIterator __begin, _RandomAccessIterator __end) { typedef typename iterator_traits<_RandomAccessIterator>::value_type _Type; if (__begin == __end) return; std::fill(__begin, __end, _Type(0x8b8b8b8bu)); const size_t __n = __end - __begin; const size_t __s = _M_v.size(); const size_t __t = (__n >= 623) ? 11 : (__n >= 68) ? 7 : (__n >= 39) ? 5 : (__n >= 7) ? 3 : (__n - 1) / 2; const size_t __p = (__n - __t) / 2; const size_t __q = __p + __t; const size_t __m = std::max(size_t(__s + 1), __n); for (size_t __k = 0; __k < __m; ++__k) { _Type __arg = (__begin[__k % __n] ^ __begin[(__k + __p) % __n] ^ __begin[(__k - 1) % __n]); _Type __r1 = __arg ^ (__arg >> 27); __r1 = __detail::__mod<_Type, __detail::_Shift<_Type, 32>::__value>(1664525u * __r1); _Type __r2 = __r1; if (__k == 0) __r2 += __s; else if (__k <= __s) __r2 += __k % __n + _M_v[__k - 1]; else __r2 += __k % __n; __r2 = __detail::__mod<_Type, __detail::_Shift<_Type, 32>::__value>(__r2); __begin[(__k + __p) % __n] += __r1; __begin[(__k + __q) % __n] += __r2; __begin[__k % __n] = __r2; } for (size_t __k = __m; __k < __m + __n; ++__k) { _Type __arg = (__begin[__k % __n] + __begin[(__k + __p) % __n] + __begin[(__k - 1) % __n]); _Type __r3 = __arg ^ (__arg >> 27); __r3 = __detail::__mod<_Type, __detail::_Shift<_Type, 32>::__value>(1566083941u * __r3); _Type __r4 = __r3 - __k % __n; __r4 = __detail::__mod<_Type, __detail::_Shift<_Type, 32>::__value>(__r4); __begin[(__k + __p) % __n] ^= __r3; __begin[(__k + __q) % __n] ^= __r4; __begin[__k % __n] = __r4; } } template _RealType generate_canonical(_UniformRandomNumberGenerator& __urng) { static_assert(std::is_floating_point<_RealType>::value, "template argument must be a floating point type"); const size_t __b = std::min(static_cast(std::numeric_limits<_RealType>::digits), __bits); const long double __r = static_cast(__urng.max()) - static_cast(__urng.min()) + 1.0L; const size_t __log2r = std::log(__r) / std::log(2.0L); const size_t __m = std::max(1UL, (__b + __log2r - 1UL) / __log2r); _RealType __ret; _RealType __sum = _RealType(0); _RealType __tmp = _RealType(1); for (size_t __k = __m; __k != 0; --__k) { __sum += _RealType(__urng() - __urng.min()) * __tmp; __tmp *= __r; } __ret = __sum / __tmp; if (__builtin_expect(__ret >= _RealType(1), 0)) { #if _GLIBCXX_USE_C99_MATH_TR1 __ret = std::nextafter(_RealType(1), _RealType(0)); #else __ret = _RealType(1) - std::numeric_limits<_RealType>::epsilon() / _RealType(2); #endif } return __ret; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!2b60.'.'8/bits/range_access.hnu[// -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/range_access.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iterator} */ #ifndef _GLIBCXX_RANGE_ACCESS_H #define _GLIBCXX_RANGE_ACCESS_H 1 #pragma GCC system_header #if __cplusplus >= 201103L #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief Return an iterator pointing to the first element of * the container. * @param __cont Container. */ template inline _GLIBCXX17_CONSTEXPR auto begin(_Container& __cont) -> decltype(__cont.begin()) { return __cont.begin(); } /** * @brief Return an iterator pointing to the first element of * the const container. * @param __cont Container. */ template inline _GLIBCXX17_CONSTEXPR auto begin(const _Container& __cont) -> decltype(__cont.begin()) { return __cont.begin(); } /** * @brief Return an iterator pointing to one past the last element of * the container. * @param __cont Container. */ template inline _GLIBCXX17_CONSTEXPR auto end(_Container& __cont) -> decltype(__cont.end()) { return __cont.end(); } /** * @brief Return an iterator pointing to one past the last element of * the const container. * @param __cont Container. */ template inline _GLIBCXX17_CONSTEXPR auto end(const _Container& __cont) -> decltype(__cont.end()) { return __cont.end(); } /** * @brief Return an iterator pointing to the first element of the array. * @param __arr Array. */ template inline _GLIBCXX14_CONSTEXPR _Tp* begin(_Tp (&__arr)[_Nm]) { return __arr; } /** * @brief Return an iterator pointing to one past the last element * of the array. * @param __arr Array. */ template inline _GLIBCXX14_CONSTEXPR _Tp* end(_Tp (&__arr)[_Nm]) { return __arr + _Nm; } #if __cplusplus >= 201402L template class valarray; // These overloads must be declared for cbegin and cend to use them. template _Tp* begin(valarray<_Tp>&); template const _Tp* begin(const valarray<_Tp>&); template _Tp* end(valarray<_Tp>&); template const _Tp* end(const valarray<_Tp>&); /** * @brief Return an iterator pointing to the first element of * the const container. * @param __cont Container. */ template inline constexpr auto cbegin(const _Container& __cont) noexcept(noexcept(std::begin(__cont))) -> decltype(std::begin(__cont)) { return std::begin(__cont); } /** * @brief Return an iterator pointing to one past the last element of * the const container. * @param __cont Container. */ template inline constexpr auto cend(const _Container& __cont) noexcept(noexcept(std::end(__cont))) -> decltype(std::end(__cont)) { return std::end(__cont); } /** * @brief Return a reverse iterator pointing to the last element of * the container. * @param __cont Container. */ template inline _GLIBCXX17_CONSTEXPR auto rbegin(_Container& __cont) -> decltype(__cont.rbegin()) { return __cont.rbegin(); } /** * @brief Return a reverse iterator pointing to the last element of * the const container. * @param __cont Container. */ template inline _GLIBCXX17_CONSTEXPR auto rbegin(const _Container& __cont) -> decltype(__cont.rbegin()) { return __cont.rbegin(); } /** * @brief Return a reverse iterator pointing one past the first element of * the container. * @param __cont Container. */ template inline _GLIBCXX17_CONSTEXPR auto rend(_Container& __cont) -> decltype(__cont.rend()) { return __cont.rend(); } /** * @brief Return a reverse iterator pointing one past the first element of * the const container. * @param __cont Container. */ template inline _GLIBCXX17_CONSTEXPR auto rend(const _Container& __cont) -> decltype(__cont.rend()) { return __cont.rend(); } /** * @brief Return a reverse iterator pointing to the last element of * the array. * @param __arr Array. */ template inline _GLIBCXX17_CONSTEXPR reverse_iterator<_Tp*> rbegin(_Tp (&__arr)[_Nm]) { return reverse_iterator<_Tp*>(__arr + _Nm); } /** * @brief Return a reverse iterator pointing one past the first element of * the array. * @param __arr Array. */ template inline _GLIBCXX17_CONSTEXPR reverse_iterator<_Tp*> rend(_Tp (&__arr)[_Nm]) { return reverse_iterator<_Tp*>(__arr); } /** * @brief Return a reverse iterator pointing to the last element of * the initializer_list. * @param __il initializer_list. */ template inline _GLIBCXX17_CONSTEXPR reverse_iterator rbegin(initializer_list<_Tp> __il) { return reverse_iterator(__il.end()); } /** * @brief Return a reverse iterator pointing one past the first element of * the initializer_list. * @param __il initializer_list. */ template inline _GLIBCXX17_CONSTEXPR reverse_iterator rend(initializer_list<_Tp> __il) { return reverse_iterator(__il.begin()); } /** * @brief Return a reverse iterator pointing to the last element of * the const container. * @param __cont Container. */ template inline _GLIBCXX17_CONSTEXPR auto crbegin(const _Container& __cont) -> decltype(std::rbegin(__cont)) { return std::rbegin(__cont); } /** * @brief Return a reverse iterator pointing one past the first element of * the const container. * @param __cont Container. */ template inline _GLIBCXX17_CONSTEXPR auto crend(const _Container& __cont) -> decltype(std::rend(__cont)) { return std::rend(__cont); } #endif // C++14 #if __cplusplus >= 201703L #define __cpp_lib_nonmember_container_access 201411 /** * @brief Return the size of a container. * @param __cont Container. */ template constexpr auto size(const _Container& __cont) noexcept(noexcept(__cont.size())) -> decltype(__cont.size()) { return __cont.size(); } /** * @brief Return the size of an array. * @param __array Array. */ template constexpr size_t size(const _Tp (&/*__array*/)[_Nm]) noexcept { return _Nm; } /** * @brief Return whether a container is empty. * @param __cont Container. */ template [[nodiscard]] constexpr auto empty(const _Container& __cont) noexcept(noexcept(__cont.empty())) -> decltype(__cont.empty()) { return __cont.empty(); } /** * @brief Return whether an array is empty (always false). * @param __array Container. */ template [[nodiscard]] constexpr bool empty(const _Tp (&/*__array*/)[_Nm]) noexcept { return false; } /** * @brief Return whether an initializer_list is empty. * @param __il Initializer list. */ template [[nodiscard]] constexpr bool empty(initializer_list<_Tp> __il) noexcept { return __il.size() == 0;} /** * @brief Return the data pointer of a container. * @param __cont Container. */ template constexpr auto data(_Container& __cont) noexcept(noexcept(__cont.data())) -> decltype(__cont.data()) { return __cont.data(); } /** * @brief Return the data pointer of a const container. * @param __cont Container. */ template constexpr auto data(const _Container& __cont) noexcept(noexcept(__cont.data())) -> decltype(__cont.data()) { return __cont.data(); } /** * @brief Return the data pointer of an array. * @param __array Array. */ template constexpr _Tp* data(_Tp (&__array)[_Nm]) noexcept { return __array; } /** * @brief Return the data pointer of an initializer list. * @param __il Initializer list. */ template constexpr const _Tp* data(initializer_list<_Tp> __il) noexcept { return __il.begin(); } #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // C++11 #endif // _GLIBCXX_RANGE_ACCESS_H PK!l.l.8/bits/refwrap.hnu[// Implementation of std::reference_wrapper -*- C++ -*- // Copyright (C) 2004-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/refwrap.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{functional} */ #ifndef _GLIBCXX_REFWRAP_H #define _GLIBCXX_REFWRAP_H 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #include // for unary_function and binary_function namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * Derives from @c unary_function or @c binary_function, or perhaps * nothing, depending on the number of arguments provided. The * primary template is the basis case, which derives nothing. */ template struct _Maybe_unary_or_binary_function { }; /// Derives from @c unary_function, as appropriate. template struct _Maybe_unary_or_binary_function<_Res, _T1> : std::unary_function<_T1, _Res> { }; /// Derives from @c binary_function, as appropriate. template struct _Maybe_unary_or_binary_function<_Res, _T1, _T2> : std::binary_function<_T1, _T2, _Res> { }; template struct _Mem_fn_traits; template struct _Mem_fn_traits_base { using __result_type = _Res; using __maybe_type = _Maybe_unary_or_binary_function<_Res, _Class*, _ArgTypes...>; using __arity = integral_constant; }; #define _GLIBCXX_MEM_FN_TRAITS2(_CV, _REF, _LVAL, _RVAL) \ template \ struct _Mem_fn_traits<_Res (_Class::*)(_ArgTypes...) _CV _REF> \ : _Mem_fn_traits_base<_Res, _CV _Class, _ArgTypes...> \ { \ using __vararg = false_type; \ }; \ template \ struct _Mem_fn_traits<_Res (_Class::*)(_ArgTypes... ...) _CV _REF> \ : _Mem_fn_traits_base<_Res, _CV _Class, _ArgTypes...> \ { \ using __vararg = true_type; \ }; #define _GLIBCXX_MEM_FN_TRAITS(_REF, _LVAL, _RVAL) \ _GLIBCXX_MEM_FN_TRAITS2( , _REF, _LVAL, _RVAL) \ _GLIBCXX_MEM_FN_TRAITS2(const , _REF, _LVAL, _RVAL) \ _GLIBCXX_MEM_FN_TRAITS2(volatile , _REF, _LVAL, _RVAL) \ _GLIBCXX_MEM_FN_TRAITS2(const volatile, _REF, _LVAL, _RVAL) _GLIBCXX_MEM_FN_TRAITS( , true_type, true_type) _GLIBCXX_MEM_FN_TRAITS(&, true_type, false_type) _GLIBCXX_MEM_FN_TRAITS(&&, false_type, true_type) #if __cplusplus > 201402L _GLIBCXX_MEM_FN_TRAITS(noexcept, true_type, true_type) _GLIBCXX_MEM_FN_TRAITS(& noexcept, true_type, false_type) _GLIBCXX_MEM_FN_TRAITS(&& noexcept, false_type, true_type) #endif #undef _GLIBCXX_MEM_FN_TRAITS #undef _GLIBCXX_MEM_FN_TRAITS2 /// If we have found a result_type, extract it. template> struct _Maybe_get_result_type { }; template struct _Maybe_get_result_type<_Functor, __void_t> { typedef typename _Functor::result_type result_type; }; /** * Base class for any function object that has a weak result type, as * defined in 20.8.2 [func.require] of C++11. */ template struct _Weak_result_type_impl : _Maybe_get_result_type<_Functor> { }; /// Retrieve the result type for a function type. template struct _Weak_result_type_impl<_Res(_ArgTypes...) _GLIBCXX_NOEXCEPT_QUAL> { typedef _Res result_type; }; /// Retrieve the result type for a varargs function type. template struct _Weak_result_type_impl<_Res(_ArgTypes......) _GLIBCXX_NOEXCEPT_QUAL> { typedef _Res result_type; }; /// Retrieve the result type for a function pointer. template struct _Weak_result_type_impl<_Res(*)(_ArgTypes...) _GLIBCXX_NOEXCEPT_QUAL> { typedef _Res result_type; }; /// Retrieve the result type for a varargs function pointer. template struct _Weak_result_type_impl<_Res(*)(_ArgTypes......) _GLIBCXX_NOEXCEPT_QUAL> { typedef _Res result_type; }; // Let _Weak_result_type_impl perform the real work. template::value> struct _Weak_result_type_memfun : _Weak_result_type_impl<_Functor> { }; // A pointer to member function has a weak result type. template struct _Weak_result_type_memfun<_MemFunPtr, true> { using result_type = typename _Mem_fn_traits<_MemFunPtr>::__result_type; }; // A pointer to data member doesn't have a weak result type. template struct _Weak_result_type_memfun<_Func _Class::*, false> { }; /** * Strip top-level cv-qualifiers from the function object and let * _Weak_result_type_memfun perform the real work. */ template struct _Weak_result_type : _Weak_result_type_memfun::type> { }; // Detect nested argument_type. template> struct _Refwrap_base_arg1 { }; // Nested argument_type. template struct _Refwrap_base_arg1<_Tp, __void_t> { typedef typename _Tp::argument_type argument_type; }; // Detect nested first_argument_type and second_argument_type. template> struct _Refwrap_base_arg2 { }; // Nested first_argument_type and second_argument_type. template struct _Refwrap_base_arg2<_Tp, __void_t> { typedef typename _Tp::first_argument_type first_argument_type; typedef typename _Tp::second_argument_type second_argument_type; }; /** * Derives from unary_function or binary_function when it * can. Specializations handle all of the easy cases. The primary * template determines what to do with a class type, which may * derive from both unary_function and binary_function. */ template struct _Reference_wrapper_base : _Weak_result_type<_Tp>, _Refwrap_base_arg1<_Tp>, _Refwrap_base_arg2<_Tp> { }; // - a function type (unary) template struct _Reference_wrapper_base<_Res(_T1) _GLIBCXX_NOEXCEPT_QUAL> : unary_function<_T1, _Res> { }; template struct _Reference_wrapper_base<_Res(_T1) const> : unary_function<_T1, _Res> { }; template struct _Reference_wrapper_base<_Res(_T1) volatile> : unary_function<_T1, _Res> { }; template struct _Reference_wrapper_base<_Res(_T1) const volatile> : unary_function<_T1, _Res> { }; // - a function type (binary) template struct _Reference_wrapper_base<_Res(_T1, _T2) _GLIBCXX_NOEXCEPT_QUAL> : binary_function<_T1, _T2, _Res> { }; template struct _Reference_wrapper_base<_Res(_T1, _T2) const> : binary_function<_T1, _T2, _Res> { }; template struct _Reference_wrapper_base<_Res(_T1, _T2) volatile> : binary_function<_T1, _T2, _Res> { }; template struct _Reference_wrapper_base<_Res(_T1, _T2) const volatile> : binary_function<_T1, _T2, _Res> { }; // - a function pointer type (unary) template struct _Reference_wrapper_base<_Res(*)(_T1) _GLIBCXX_NOEXCEPT_QUAL> : unary_function<_T1, _Res> { }; // - a function pointer type (binary) template struct _Reference_wrapper_base<_Res(*)(_T1, _T2) _GLIBCXX_NOEXCEPT_QUAL> : binary_function<_T1, _T2, _Res> { }; template::value> struct _Reference_wrapper_base_memfun : _Reference_wrapper_base<_Tp> { }; template struct _Reference_wrapper_base_memfun<_MemFunPtr, true> : _Mem_fn_traits<_MemFunPtr>::__maybe_type { using result_type = typename _Mem_fn_traits<_MemFunPtr>::__result_type; }; /** * @brief Primary class template for reference_wrapper. * @ingroup functors * @{ */ template class reference_wrapper : public _Reference_wrapper_base_memfun::type> { _Tp* _M_data; public: typedef _Tp type; reference_wrapper(_Tp& __indata) noexcept : _M_data(std::__addressof(__indata)) { } reference_wrapper(_Tp&&) = delete; reference_wrapper(const reference_wrapper&) = default; reference_wrapper& operator=(const reference_wrapper&) = default; operator _Tp&() const noexcept { return this->get(); } _Tp& get() const noexcept { return *_M_data; } template typename result_of<_Tp&(_Args&&...)>::type operator()(_Args&&... __args) const { return std::__invoke(get(), std::forward<_Args>(__args)...); } }; /// Denotes a reference should be taken to a variable. template inline reference_wrapper<_Tp> ref(_Tp& __t) noexcept { return reference_wrapper<_Tp>(__t); } /// Denotes a const reference should be taken to a variable. template inline reference_wrapper cref(const _Tp& __t) noexcept { return reference_wrapper(__t); } template void ref(const _Tp&&) = delete; template void cref(const _Tp&&) = delete; /// std::ref overload to prevent wrapping a reference_wrapper template inline reference_wrapper<_Tp> ref(reference_wrapper<_Tp> __t) noexcept { return __t; } /// std::cref overload to prevent wrapping a reference_wrapper template inline reference_wrapper cref(reference_wrapper<_Tp> __t) noexcept { return { __t.get() }; } // @} group functors _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif // _GLIBCXX_REFWRAP_H PK!Z>*z|z|8/bits/regex.hnu[// class template regex -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CXX11 template class basic_regex; template class match_results; _GLIBCXX_END_NAMESPACE_CXX11 namespace __detail { enum class _RegexExecutorPolicy : int { _S_auto, _S_alternate }; template bool __regex_algo_impl(_BiIter __s, _BiIter __e, match_results<_BiIter, _Alloc>& __m, const basic_regex<_CharT, _TraitsT>& __re, regex_constants::match_flag_type __flags); template class _Executor; } _GLIBCXX_BEGIN_NAMESPACE_CXX11 /** * @addtogroup regex * @{ */ /** * @brief Describes aspects of a regular expression. * * A regular expression traits class that satisfies the requirements of * section [28.7]. * * The class %regex is parameterized around a set of related types and * functions used to complete the definition of its semantics. This class * satisfies the requirements of such a traits class. */ template struct regex_traits { public: typedef _Ch_type char_type; typedef std::basic_string string_type; typedef std::locale locale_type; private: struct _RegexMask { typedef std::ctype_base::mask _BaseType; _BaseType _M_base; unsigned char _M_extended; static constexpr unsigned char _S_under = 1 << 0; static constexpr unsigned char _S_valid_mask = 0x1; constexpr _RegexMask(_BaseType __base = 0, unsigned char __extended = 0) : _M_base(__base), _M_extended(__extended) { } constexpr _RegexMask operator&(_RegexMask __other) const { return _RegexMask(_M_base & __other._M_base, _M_extended & __other._M_extended); } constexpr _RegexMask operator|(_RegexMask __other) const { return _RegexMask(_M_base | __other._M_base, _M_extended | __other._M_extended); } constexpr _RegexMask operator^(_RegexMask __other) const { return _RegexMask(_M_base ^ __other._M_base, _M_extended ^ __other._M_extended); } constexpr _RegexMask operator~() const { return _RegexMask(~_M_base, ~_M_extended); } _RegexMask& operator&=(_RegexMask __other) { return *this = (*this) & __other; } _RegexMask& operator|=(_RegexMask __other) { return *this = (*this) | __other; } _RegexMask& operator^=(_RegexMask __other) { return *this = (*this) ^ __other; } constexpr bool operator==(_RegexMask __other) const { return (_M_extended & _S_valid_mask) == (__other._M_extended & _S_valid_mask) && _M_base == __other._M_base; } constexpr bool operator!=(_RegexMask __other) const { return !((*this) == __other); } }; public: typedef _RegexMask char_class_type; public: /** * @brief Constructs a default traits object. */ regex_traits() { } /** * @brief Gives the length of a C-style string starting at @p __p. * * @param __p a pointer to the start of a character sequence. * * @returns the number of characters between @p *__p and the first * default-initialized value of type @p char_type. In other words, uses * the C-string algorithm for determining the length of a sequence of * characters. */ static std::size_t length(const char_type* __p) { return string_type::traits_type::length(__p); } /** * @brief Performs the identity translation. * * @param __c A character to the locale-specific character set. * * @returns __c. */ char_type translate(char_type __c) const { return __c; } /** * @brief Translates a character into a case-insensitive equivalent. * * @param __c A character to the locale-specific character set. * * @returns the locale-specific lower-case equivalent of __c. * @throws std::bad_cast if the imbued locale does not support the ctype * facet. */ char_type translate_nocase(char_type __c) const { typedef std::ctype __ctype_type; const __ctype_type& __fctyp(use_facet<__ctype_type>(_M_locale)); return __fctyp.tolower(__c); } /** * @brief Gets a sort key for a character sequence. * * @param __first beginning of the character sequence. * @param __last one-past-the-end of the character sequence. * * Returns a sort key for the character sequence designated by the * iterator range [F1, F2) such that if the character sequence [G1, G2) * sorts before the character sequence [H1, H2) then * v.transform(G1, G2) < v.transform(H1, H2). * * What this really does is provide a more efficient way to compare a * string to multiple other strings in locales with fancy collation * rules and equivalence classes. * * @returns a locale-specific sort key equivalent to the input range. * * @throws std::bad_cast if the current locale does not have a collate * facet. */ template string_type transform(_Fwd_iter __first, _Fwd_iter __last) const { typedef std::collate __collate_type; const __collate_type& __fclt(use_facet<__collate_type>(_M_locale)); string_type __s(__first, __last); return __fclt.transform(__s.data(), __s.data() + __s.size()); } /** * @brief Gets a sort key for a character sequence, independent of case. * * @param __first beginning of the character sequence. * @param __last one-past-the-end of the character sequence. * * Effects: if typeid(use_facet >) == * typeid(collate_byname<_Ch_type>) and the form of the sort key * returned by collate_byname<_Ch_type>::transform(__first, __last) * is known and can be converted into a primary sort key * then returns that key, otherwise returns an empty string. * * @todo Implement this function correctly. */ template string_type transform_primary(_Fwd_iter __first, _Fwd_iter __last) const { // TODO : this is not entirely correct. // This function requires extra support from the platform. // // Read http://gcc.gnu.org/ml/libstdc++/2013-09/msg00117.html and // http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2003/n1429.htm // for details. typedef std::ctype __ctype_type; const __ctype_type& __fctyp(use_facet<__ctype_type>(_M_locale)); std::vector __s(__first, __last); __fctyp.tolower(__s.data(), __s.data() + __s.size()); return this->transform(__s.data(), __s.data() + __s.size()); } /** * @brief Gets a collation element by name. * * @param __first beginning of the collation element name. * @param __last one-past-the-end of the collation element name. * * @returns a sequence of one or more characters that represents the * collating element consisting of the character sequence designated by * the iterator range [__first, __last). Returns an empty string if the * character sequence is not a valid collating element. */ template string_type lookup_collatename(_Fwd_iter __first, _Fwd_iter __last) const; /** * @brief Maps one or more characters to a named character * classification. * * @param __first beginning of the character sequence. * @param __last one-past-the-end of the character sequence. * @param __icase ignores the case of the classification name. * * @returns an unspecified value that represents the character * classification named by the character sequence designated by * the iterator range [__first, __last). If @p icase is true, * the returned mask identifies the classification regardless of * the case of the characters to be matched (for example, * [[:lower:]] is the same as [[:alpha:]]), otherwise a * case-dependent classification is returned. The value * returned shall be independent of the case of the characters * in the character sequence. If the name is not recognized then * returns a value that compares equal to 0. * * At least the following names (or their wide-character equivalent) are * supported. * - d * - w * - s * - alnum * - alpha * - blank * - cntrl * - digit * - graph * - lower * - print * - punct * - space * - upper * - xdigit */ template char_class_type lookup_classname(_Fwd_iter __first, _Fwd_iter __last, bool __icase = false) const; /** * @brief Determines if @p c is a member of an identified class. * * @param __c a character. * @param __f a class type (as returned from lookup_classname). * * @returns true if the character @p __c is a member of the classification * represented by @p __f, false otherwise. * * @throws std::bad_cast if the current locale does not have a ctype * facet. */ bool isctype(_Ch_type __c, char_class_type __f) const; /** * @brief Converts a digit to an int. * * @param __ch a character representing a digit. * @param __radix the radix if the numeric conversion (limited to 8, 10, * or 16). * * @returns the value represented by the digit __ch in base radix if the * character __ch is a valid digit in base radix; otherwise returns -1. */ int value(_Ch_type __ch, int __radix) const; /** * @brief Imbues the regex_traits object with a copy of a new locale. * * @param __loc A locale. * * @returns a copy of the previous locale in use by the regex_traits * object. * * @note Calling imbue with a different locale than the one currently in * use invalidates all cached data held by *this. */ locale_type imbue(locale_type __loc) { std::swap(_M_locale, __loc); return __loc; } /** * @brief Gets a copy of the current locale in use by the regex_traits * object. */ locale_type getloc() const { return _M_locale; } protected: locale_type _M_locale; }; // [7.8] Class basic_regex /** * Objects of specializations of this class represent regular expressions * constructed from sequences of character type @p _Ch_type. * * Storage for the regular expression is allocated and deallocated as * necessary by the member functions of this class. */ template> class basic_regex { public: static_assert(is_same<_Ch_type, typename _Rx_traits::char_type>::value, "regex traits class must have the same char_type"); // types: typedef _Ch_type value_type; typedef _Rx_traits traits_type; typedef typename traits_type::string_type string_type; typedef regex_constants::syntax_option_type flag_type; typedef typename traits_type::locale_type locale_type; /** * @name Constants * std [28.8.1](1) */ //@{ static constexpr flag_type icase = regex_constants::icase; static constexpr flag_type nosubs = regex_constants::nosubs; static constexpr flag_type optimize = regex_constants::optimize; static constexpr flag_type collate = regex_constants::collate; static constexpr flag_type ECMAScript = regex_constants::ECMAScript; static constexpr flag_type basic = regex_constants::basic; static constexpr flag_type extended = regex_constants::extended; static constexpr flag_type awk = regex_constants::awk; static constexpr flag_type grep = regex_constants::grep; static constexpr flag_type egrep = regex_constants::egrep; //@} // [7.8.2] construct/copy/destroy /** * Constructs a basic regular expression that does not match any * character sequence. */ basic_regex() : _M_flags(ECMAScript), _M_loc(), _M_automaton(nullptr) { } /** * @brief Constructs a basic regular expression from the * sequence [__p, __p + char_traits<_Ch_type>::length(__p)) * interpreted according to the flags in @p __f. * * @param __p A pointer to the start of a C-style null-terminated string * containing a regular expression. * @param __f Flags indicating the syntax rules and options. * * @throws regex_error if @p __p is not a valid regular expression. */ explicit basic_regex(const _Ch_type* __p, flag_type __f = ECMAScript) : basic_regex(__p, __p + char_traits<_Ch_type>::length(__p), __f) { } /** * @brief Constructs a basic regular expression from the sequence * [p, p + len) interpreted according to the flags in @p f. * * @param __p A pointer to the start of a string containing a regular * expression. * @param __len The length of the string containing the regular * expression. * @param __f Flags indicating the syntax rules and options. * * @throws regex_error if @p __p is not a valid regular expression. */ basic_regex(const _Ch_type* __p, std::size_t __len, flag_type __f = ECMAScript) : basic_regex(__p, __p + __len, __f) { } /** * @brief Copy-constructs a basic regular expression. * * @param __rhs A @p regex object. */ basic_regex(const basic_regex& __rhs) = default; /** * @brief Move-constructs a basic regular expression. * * @param __rhs A @p regex object. */ basic_regex(basic_regex&& __rhs) noexcept = default; /** * @brief Constructs a basic regular expression from the string * @p s interpreted according to the flags in @p f. * * @param __s A string containing a regular expression. * @param __f Flags indicating the syntax rules and options. * * @throws regex_error if @p __s is not a valid regular expression. */ template explicit basic_regex(const std::basic_string<_Ch_type, _Ch_traits, _Ch_alloc>& __s, flag_type __f = ECMAScript) : basic_regex(__s.data(), __s.data() + __s.size(), __f) { } /** * @brief Constructs a basic regular expression from the range * [first, last) interpreted according to the flags in @p f. * * @param __first The start of a range containing a valid regular * expression. * @param __last The end of a range containing a valid regular * expression. * @param __f The format flags of the regular expression. * * @throws regex_error if @p [__first, __last) is not a valid regular * expression. */ template basic_regex(_FwdIter __first, _FwdIter __last, flag_type __f = ECMAScript) : basic_regex(std::move(__first), std::move(__last), locale_type(), __f) { } /** * @brief Constructs a basic regular expression from an initializer list. * * @param __l The initializer list. * @param __f The format flags of the regular expression. * * @throws regex_error if @p __l is not a valid regular expression. */ basic_regex(initializer_list<_Ch_type> __l, flag_type __f = ECMAScript) : basic_regex(__l.begin(), __l.end(), __f) { } /** * @brief Destroys a basic regular expression. */ ~basic_regex() { } /** * @brief Assigns one regular expression to another. */ basic_regex& operator=(const basic_regex& __rhs) { return this->assign(__rhs); } /** * @brief Move-assigns one regular expression to another. */ basic_regex& operator=(basic_regex&& __rhs) noexcept { return this->assign(std::move(__rhs)); } /** * @brief Replaces a regular expression with a new one constructed from * a C-style null-terminated string. * * @param __p A pointer to the start of a null-terminated C-style string * containing a regular expression. */ basic_regex& operator=(const _Ch_type* __p) { return this->assign(__p); } /** * @brief Replaces a regular expression with a new one constructed from * an initializer list. * * @param __l The initializer list. * * @throws regex_error if @p __l is not a valid regular expression. */ basic_regex& operator=(initializer_list<_Ch_type> __l) { return this->assign(__l.begin(), __l.end()); } /** * @brief Replaces a regular expression with a new one constructed from * a string. * * @param __s A pointer to a string containing a regular expression. */ template basic_regex& operator=(const basic_string<_Ch_type, _Ch_traits, _Alloc>& __s) { return this->assign(__s); } // [7.8.3] assign /** * @brief the real assignment operator. * * @param __rhs Another regular expression object. */ basic_regex& assign(const basic_regex& __rhs) { basic_regex __tmp(__rhs); this->swap(__tmp); return *this; } /** * @brief The move-assignment operator. * * @param __rhs Another regular expression object. */ basic_regex& assign(basic_regex&& __rhs) noexcept { basic_regex __tmp(std::move(__rhs)); this->swap(__tmp); return *this; } /** * @brief Assigns a new regular expression to a regex object from a * C-style null-terminated string containing a regular expression * pattern. * * @param __p A pointer to a C-style null-terminated string containing * a regular expression pattern. * @param __flags Syntax option flags. * * @throws regex_error if __p does not contain a valid regular * expression pattern interpreted according to @p __flags. If * regex_error is thrown, *this remains unchanged. */ basic_regex& assign(const _Ch_type* __p, flag_type __flags = ECMAScript) { return this->assign(string_type(__p), __flags); } /** * @brief Assigns a new regular expression to a regex object from a * C-style string containing a regular expression pattern. * * @param __p A pointer to a C-style string containing a * regular expression pattern. * @param __len The length of the regular expression pattern string. * @param __flags Syntax option flags. * * @throws regex_error if p does not contain a valid regular * expression pattern interpreted according to @p __flags. If * regex_error is thrown, *this remains unchanged. */ basic_regex& assign(const _Ch_type* __p, std::size_t __len, flag_type __flags) { return this->assign(string_type(__p, __len), __flags); } /** * @brief Assigns a new regular expression to a regex object from a * string containing a regular expression pattern. * * @param __s A string containing a regular expression pattern. * @param __flags Syntax option flags. * * @throws regex_error if __s does not contain a valid regular * expression pattern interpreted according to @p __flags. If * regex_error is thrown, *this remains unchanged. */ template basic_regex& assign(const basic_string<_Ch_type, _Ch_traits, _Alloc>& __s, flag_type __flags = ECMAScript) { return this->assign(basic_regex(__s.data(), __s.data() + __s.size(), _M_loc, __flags)); } /** * @brief Assigns a new regular expression to a regex object. * * @param __first The start of a range containing a valid regular * expression. * @param __last The end of a range containing a valid regular * expression. * @param __flags Syntax option flags. * * @throws regex_error if p does not contain a valid regular * expression pattern interpreted according to @p __flags. If * regex_error is thrown, the object remains unchanged. */ template basic_regex& assign(_InputIterator __first, _InputIterator __last, flag_type __flags = ECMAScript) { return this->assign(string_type(__first, __last), __flags); } /** * @brief Assigns a new regular expression to a regex object. * * @param __l An initializer list representing a regular expression. * @param __flags Syntax option flags. * * @throws regex_error if @p __l does not contain a valid * regular expression pattern interpreted according to @p * __flags. If regex_error is thrown, the object remains * unchanged. */ basic_regex& assign(initializer_list<_Ch_type> __l, flag_type __flags = ECMAScript) { return this->assign(__l.begin(), __l.end(), __flags); } // [7.8.4] const operations /** * @brief Gets the number of marked subexpressions within the regular * expression. */ unsigned int mark_count() const { if (_M_automaton) return _M_automaton->_M_sub_count() - 1; return 0; } /** * @brief Gets the flags used to construct the regular expression * or in the last call to assign(). */ flag_type flags() const { return _M_flags; } // [7.8.5] locale /** * @brief Imbues the regular expression object with the given locale. * * @param __loc A locale. */ locale_type imbue(locale_type __loc) { std::swap(__loc, _M_loc); _M_automaton.reset(); return __loc; } /** * @brief Gets the locale currently imbued in the regular expression * object. */ locale_type getloc() const { return _M_loc; } // [7.8.6] swap /** * @brief Swaps the contents of two regular expression objects. * * @param __rhs Another regular expression object. */ void swap(basic_regex& __rhs) { std::swap(_M_flags, __rhs._M_flags); std::swap(_M_loc, __rhs._M_loc); std::swap(_M_automaton, __rhs._M_automaton); } #ifdef _GLIBCXX_DEBUG void _M_dot(std::ostream& __ostr) { _M_automaton->_M_dot(__ostr); } #endif private: typedef std::shared_ptr> _AutomatonPtr; template basic_regex(_FwdIter __first, _FwdIter __last, locale_type __loc, flag_type __f) : _M_flags(__f), _M_loc(std::move(__loc)), _M_automaton(__detail::__compile_nfa<_Rx_traits>( std::move(__first), std::move(__last), _M_loc, _M_flags)) { } template friend bool __detail::__regex_algo_impl(_Bp, _Bp, match_results<_Bp, _Ap>&, const basic_regex<_Cp, _Rp>&, regex_constants::match_flag_type); template friend class __detail::_Executor; flag_type _M_flags; locale_type _M_loc; _AutomatonPtr _M_automaton; }; #if __cplusplus < 201703L template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::icase; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::nosubs; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::optimize; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::collate; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::ECMAScript; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::basic; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::extended; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::awk; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::grep; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::egrep; #endif // ! C++17 #if __cpp_deduction_guides >= 201606 template basic_regex(_ForwardIterator, _ForwardIterator, regex_constants::syntax_option_type = {}) -> basic_regex::value_type>; #endif /** @brief Standard regular expressions. */ typedef basic_regex regex; #ifdef _GLIBCXX_USE_WCHAR_T /** @brief Standard wide-character regular expressions. */ typedef basic_regex wregex; #endif // [7.8.6] basic_regex swap /** * @brief Swaps the contents of two regular expression objects. * @param __lhs First regular expression. * @param __rhs Second regular expression. */ template inline void swap(basic_regex<_Ch_type, _Rx_traits>& __lhs, basic_regex<_Ch_type, _Rx_traits>& __rhs) { __lhs.swap(__rhs); } // [7.9] Class template sub_match /** * A sequence of characters matched by a particular marked sub-expression. * * An object of this class is essentially a pair of iterators marking a * matched subexpression within a regular expression pattern match. Such * objects can be converted to and compared with std::basic_string objects * of a similar base character type as the pattern matched by the regular * expression. * * The iterators that make up the pair are the usual half-open interval * referencing the actual original pattern matched. */ template class sub_match : public std::pair<_BiIter, _BiIter> { typedef iterator_traits<_BiIter> __iter_traits; public: typedef typename __iter_traits::value_type value_type; typedef typename __iter_traits::difference_type difference_type; typedef _BiIter iterator; typedef std::basic_string string_type; bool matched; constexpr sub_match() : matched() { } /** * Gets the length of the matching sequence. */ difference_type length() const { return this->matched ? std::distance(this->first, this->second) : 0; } /** * @brief Gets the matching sequence as a string. * * @returns the matching sequence as a string. * * This is the implicit conversion operator. It is identical to the * str() member function except that it will want to pop up in * unexpected places and cause a great deal of confusion and cursing * from the unwary. */ operator string_type() const { return this->matched ? string_type(this->first, this->second) : string_type(); } /** * @brief Gets the matching sequence as a string. * * @returns the matching sequence as a string. */ string_type str() const { return this->matched ? string_type(this->first, this->second) : string_type(); } /** * @brief Compares this and another matched sequence. * * @param __s Another matched sequence to compare to this one. * * @retval <0 this matched sequence will collate before @p __s. * @retval =0 this matched sequence is equivalent to @p __s. * @retval <0 this matched sequence will collate after @p __s. */ int compare(const sub_match& __s) const { return this->str().compare(__s.str()); } /** * @brief Compares this sub_match to a string. * * @param __s A string to compare to this sub_match. * * @retval <0 this matched sequence will collate before @p __s. * @retval =0 this matched sequence is equivalent to @p __s. * @retval <0 this matched sequence will collate after @p __s. */ int compare(const string_type& __s) const { return this->str().compare(__s); } /** * @brief Compares this sub_match to a C-style string. * * @param __s A C-style string to compare to this sub_match. * * @retval <0 this matched sequence will collate before @p __s. * @retval =0 this matched sequence is equivalent to @p __s. * @retval <0 this matched sequence will collate after @p __s. */ int compare(const value_type* __s) const { return this->str().compare(__s); } }; /** @brief Standard regex submatch over a C-style null-terminated string. */ typedef sub_match csub_match; /** @brief Standard regex submatch over a standard string. */ typedef sub_match ssub_match; #ifdef _GLIBCXX_USE_WCHAR_T /** @brief Regex submatch over a C-style null-terminated wide string. */ typedef sub_match wcsub_match; /** @brief Regex submatch over a standard wide string. */ typedef sub_match wssub_match; #endif // [7.9.2] sub_match non-member operators /** * @brief Tests the equivalence of two regular expression submatches. * @param __lhs First regular expression submatch. * @param __rhs Second regular expression submatch. * @returns true if @a __lhs is equivalent to @a __rhs, false otherwise. */ template inline bool operator==(const sub_match<_BiIter>& __lhs, const sub_match<_BiIter>& __rhs) { return __lhs.compare(__rhs) == 0; } /** * @brief Tests the inequivalence of two regular expression submatches. * @param __lhs First regular expression submatch. * @param __rhs Second regular expression submatch. * @returns true if @a __lhs is not equivalent to @a __rhs, false otherwise. */ template inline bool operator!=(const sub_match<_BiIter>& __lhs, const sub_match<_BiIter>& __rhs) { return __lhs.compare(__rhs) != 0; } /** * @brief Tests the ordering of two regular expression submatches. * @param __lhs First regular expression submatch. * @param __rhs Second regular expression submatch. * @returns true if @a __lhs precedes @a __rhs, false otherwise. */ template inline bool operator<(const sub_match<_BiIter>& __lhs, const sub_match<_BiIter>& __rhs) { return __lhs.compare(__rhs) < 0; } /** * @brief Tests the ordering of two regular expression submatches. * @param __lhs First regular expression submatch. * @param __rhs Second regular expression submatch. * @returns true if @a __lhs does not succeed @a __rhs, false otherwise. */ template inline bool operator<=(const sub_match<_BiIter>& __lhs, const sub_match<_BiIter>& __rhs) { return __lhs.compare(__rhs) <= 0; } /** * @brief Tests the ordering of two regular expression submatches. * @param __lhs First regular expression submatch. * @param __rhs Second regular expression submatch. * @returns true if @a __lhs does not precede @a __rhs, false otherwise. */ template inline bool operator>=(const sub_match<_BiIter>& __lhs, const sub_match<_BiIter>& __rhs) { return __lhs.compare(__rhs) >= 0; } /** * @brief Tests the ordering of two regular expression submatches. * @param __lhs First regular expression submatch. * @param __rhs Second regular expression submatch. * @returns true if @a __lhs succeeds @a __rhs, false otherwise. */ template inline bool operator>(const sub_match<_BiIter>& __lhs, const sub_match<_BiIter>& __rhs) { return __lhs.compare(__rhs) > 0; } // Alias for sub_match'd string. template using __sub_match_string = basic_string< typename iterator_traits<_Bi_iter>::value_type, _Ch_traits, _Ch_alloc>; /** * @brief Tests the equivalence of a string and a regular expression * submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs is equivalent to @a __rhs, false otherwise. */ template inline bool operator==(const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __rhs.compare(string_type(__lhs.data(), __lhs.size())) == 0; } /** * @brief Tests the inequivalence of a string and a regular expression * submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs is not equivalent to @a __rhs, false otherwise. */ template inline bool operator!=(const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__lhs == __rhs); } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs precedes @a __rhs, false otherwise. */ template inline bool operator<(const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __rhs.compare(string_type(__lhs.data(), __lhs.size())) > 0; } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs succeeds @a __rhs, false otherwise. */ template inline bool operator>(const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs) { return __rhs < __lhs; } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs does not precede @a __rhs, false otherwise. */ template inline bool operator>=(const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__lhs < __rhs); } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs does not succeed @a __rhs, false otherwise. */ template inline bool operator<=(const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__rhs < __lhs); } /** * @brief Tests the equivalence of a regular expression submatch and a * string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs is equivalent to @a __rhs, false otherwise. */ template inline bool operator==(const sub_match<_Bi_iter>& __lhs, const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __lhs.compare(string_type(__rhs.data(), __rhs.size())) == 0; } /** * @brief Tests the inequivalence of a regular expression submatch and a * string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs is not equivalent to @a __rhs, false otherwise. */ template inline bool operator!=(const sub_match<_Bi_iter>& __lhs, const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __rhs) { return !(__lhs == __rhs); } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs precedes @a __rhs, false otherwise. */ template inline bool operator<(const sub_match<_Bi_iter>& __lhs, const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __lhs.compare(string_type(__rhs.data(), __rhs.size())) < 0; } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs succeeds @a __rhs, false otherwise. */ template inline bool operator>(const sub_match<_Bi_iter>& __lhs, const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __rhs) { return __rhs < __lhs; } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs does not precede @a __rhs, false otherwise. */ template inline bool operator>=(const sub_match<_Bi_iter>& __lhs, const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __rhs) { return !(__lhs < __rhs); } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs does not succeed @a __rhs, false otherwise. */ template inline bool operator<=(const sub_match<_Bi_iter>& __lhs, const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __rhs) { return !(__rhs < __lhs); } /** * @brief Tests the equivalence of a C string and a regular expression * submatch. * @param __lhs A C string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs is equivalent to @a __rhs, false otherwise. */ template inline bool operator==(typename iterator_traits<_Bi_iter>::value_type const* __lhs, const sub_match<_Bi_iter>& __rhs) { return __rhs.compare(__lhs) == 0; } /** * @brief Tests the inequivalence of an iterator value and a regular * expression submatch. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs is not equivalent to @a __rhs, false otherwise. */ template inline bool operator!=(typename iterator_traits<_Bi_iter>::value_type const* __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__lhs == __rhs); } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs precedes @a __rhs, false otherwise. */ template inline bool operator<(typename iterator_traits<_Bi_iter>::value_type const* __lhs, const sub_match<_Bi_iter>& __rhs) { return __rhs.compare(__lhs) > 0; } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs succeeds @a __rhs, false otherwise. */ template inline bool operator>(typename iterator_traits<_Bi_iter>::value_type const* __lhs, const sub_match<_Bi_iter>& __rhs) { return __rhs < __lhs; } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs does not precede @a __rhs, false otherwise. */ template inline bool operator>=(typename iterator_traits<_Bi_iter>::value_type const* __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__lhs < __rhs); } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs does not succeed @a __rhs, false otherwise. */ template inline bool operator<=(typename iterator_traits<_Bi_iter>::value_type const* __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__rhs < __lhs); } /** * @brief Tests the equivalence of a regular expression submatch and a * string. * @param __lhs A regular expression submatch. * @param __rhs A pointer to a string? * @returns true if @a __lhs is equivalent to @a __rhs, false otherwise. */ template inline bool operator==(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const* __rhs) { return __lhs.compare(__rhs) == 0; } /** * @brief Tests the inequivalence of a regular expression submatch and a * string. * @param __lhs A regular expression submatch. * @param __rhs A pointer to a string. * @returns true if @a __lhs is not equivalent to @a __rhs, false otherwise. */ template inline bool operator!=(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const* __rhs) { return !(__lhs == __rhs); } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs precedes @a __rhs, false otherwise. */ template inline bool operator<(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const* __rhs) { return __lhs.compare(__rhs) < 0; } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs succeeds @a __rhs, false otherwise. */ template inline bool operator>(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const* __rhs) { return __rhs < __lhs; } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs does not precede @a __rhs, false otherwise. */ template inline bool operator>=(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const* __rhs) { return !(__lhs < __rhs); } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs does not succeed @a __rhs, false otherwise. */ template inline bool operator<=(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const* __rhs) { return !(__rhs < __lhs); } /** * @brief Tests the equivalence of a string and a regular expression * submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs is equivalent to @a __rhs, false otherwise. */ template inline bool operator==(typename iterator_traits<_Bi_iter>::value_type const& __lhs, const sub_match<_Bi_iter>& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __rhs.compare(string_type(1, __lhs)) == 0; } /** * @brief Tests the inequivalence of a string and a regular expression * submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs is not equivalent to @a __rhs, false otherwise. */ template inline bool operator!=(typename iterator_traits<_Bi_iter>::value_type const& __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__lhs == __rhs); } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs precedes @a __rhs, false otherwise. */ template inline bool operator<(typename iterator_traits<_Bi_iter>::value_type const& __lhs, const sub_match<_Bi_iter>& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __rhs.compare(string_type(1, __lhs)) > 0; } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs succeeds @a __rhs, false otherwise. */ template inline bool operator>(typename iterator_traits<_Bi_iter>::value_type const& __lhs, const sub_match<_Bi_iter>& __rhs) { return __rhs < __lhs; } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs does not precede @a __rhs, false otherwise. */ template inline bool operator>=(typename iterator_traits<_Bi_iter>::value_type const& __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__lhs < __rhs); } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs does not succeed @a __rhs, false otherwise. */ template inline bool operator<=(typename iterator_traits<_Bi_iter>::value_type const& __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__rhs < __lhs); } /** * @brief Tests the equivalence of a regular expression submatch and a * string. * @param __lhs A regular expression submatch. * @param __rhs A const string reference. * @returns true if @a __lhs is equivalent to @a __rhs, false otherwise. */ template inline bool operator==(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __lhs.compare(string_type(1, __rhs)) == 0; } /** * @brief Tests the inequivalence of a regular expression submatch and a * string. * @param __lhs A regular expression submatch. * @param __rhs A const string reference. * @returns true if @a __lhs is not equivalent to @a __rhs, false otherwise. */ template inline bool operator!=(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const& __rhs) { return !(__lhs == __rhs); } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A const string reference. * @returns true if @a __lhs precedes @a __rhs, false otherwise. */ template inline bool operator<(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __lhs.compare(string_type(1, __rhs)) < 0; } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A const string reference. * @returns true if @a __lhs succeeds @a __rhs, false otherwise. */ template inline bool operator>(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const& __rhs) { return __rhs < __lhs; } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A const string reference. * @returns true if @a __lhs does not precede @a __rhs, false otherwise. */ template inline bool operator>=(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const& __rhs) { return !(__lhs < __rhs); } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A const string reference. * @returns true if @a __lhs does not succeed @a __rhs, false otherwise. */ template inline bool operator<=(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const& __rhs) { return !(__rhs < __lhs); } /** * @brief Inserts a matched string into an output stream. * * @param __os The output stream. * @param __m A submatch string. * * @returns the output stream with the submatch string inserted. */ template inline basic_ostream<_Ch_type, _Ch_traits>& operator<<(basic_ostream<_Ch_type, _Ch_traits>& __os, const sub_match<_Bi_iter>& __m) { return __os << __m.str(); } // [7.10] Class template match_results /** * @brief The results of a match or search operation. * * A collection of character sequences representing the result of a regular * expression match. Storage for the collection is allocated and freed as * necessary by the member functions of class template match_results. * * This class satisfies the Sequence requirements, with the exception that * only the operations defined for a const-qualified Sequence are supported. * * The sub_match object stored at index 0 represents sub-expression 0, i.e. * the whole match. In this case the %sub_match member matched is always true. * The sub_match object stored at index n denotes what matched the marked * sub-expression n within the matched expression. If the sub-expression n * participated in a regular expression match then the %sub_match member * matched evaluates to true, and members first and second denote the range * of characters [first, second) which formed that match. Otherwise matched * is false, and members first and second point to the end of the sequence * that was searched. * * @nosubgrouping */ template > > class match_results : private std::vector, _Alloc> { private: /* * The vector base is empty if this does not represent a match (!ready()); * Otherwise if it's a match failure, it contains 3 elements: * [0] unmatched * [1] prefix * [2] suffix * Otherwise it contains n+4 elements where n is the number of marked * sub-expressions: * [0] entire match * [1] 1st marked subexpression * ... * [n] nth marked subexpression * [n+1] unmatched * [n+2] prefix * [n+3] suffix */ typedef std::vector, _Alloc> _Base_type; typedef std::iterator_traits<_Bi_iter> __iter_traits; typedef regex_constants::match_flag_type match_flag_type; public: /** * @name 10.? Public Types */ //@{ typedef sub_match<_Bi_iter> value_type; typedef const value_type& const_reference; typedef value_type& reference; typedef typename _Base_type::const_iterator const_iterator; typedef const_iterator iterator; typedef typename __iter_traits::difference_type difference_type; typedef typename allocator_traits<_Alloc>::size_type size_type; typedef _Alloc allocator_type; typedef typename __iter_traits::value_type char_type; typedef std::basic_string string_type; //@} public: /** * @name 28.10.1 Construction, Copying, and Destruction */ //@{ /** * @brief Constructs a default %match_results container. * @post size() returns 0 and str() returns an empty string. */ explicit match_results(const _Alloc& __a = _Alloc()) : _Base_type(__a) { } /** * @brief Copy constructs a %match_results. */ match_results(const match_results& __rhs) = default; /** * @brief Move constructs a %match_results. */ match_results(match_results&& __rhs) noexcept = default; /** * @brief Assigns rhs to *this. */ match_results& operator=(const match_results& __rhs) = default; /** * @brief Move-assigns rhs to *this. */ match_results& operator=(match_results&& __rhs) = default; /** * @brief Destroys a %match_results object. */ ~match_results() { } //@} // 28.10.2, state: /** * @brief Indicates if the %match_results is ready. * @retval true The object has a fully-established result state. * @retval false The object is not ready. */ bool ready() const { return !_Base_type::empty(); } /** * @name 28.10.2 Size */ //@{ /** * @brief Gets the number of matches and submatches. * * The number of matches for a given regular expression will be either 0 * if there was no match or mark_count() + 1 if a match was successful. * Some matches may be empty. * * @returns the number of matches found. */ size_type size() const { return _Base_type::empty() ? 0 : _Base_type::size() - 3; } size_type max_size() const { return _Base_type::max_size(); } /** * @brief Indicates if the %match_results contains no results. * @retval true The %match_results object is empty. * @retval false The %match_results object is not empty. */ bool empty() const { return size() == 0; } //@} /** * @name 10.3 Element Access */ //@{ /** * @brief Gets the length of the indicated submatch. * @param __sub indicates the submatch. * @pre ready() == true * * This function returns the length of the indicated submatch, or the * length of the entire match if @p __sub is zero (the default). */ difference_type length(size_type __sub = 0) const { return (*this)[__sub].length(); } /** * @brief Gets the offset of the beginning of the indicated submatch. * @param __sub indicates the submatch. * @pre ready() == true * * This function returns the offset from the beginning of the target * sequence to the beginning of the submatch, unless the value of @p __sub * is zero (the default), in which case this function returns the offset * from the beginning of the target sequence to the beginning of the * match. */ difference_type position(size_type __sub = 0) const { return std::distance(_M_begin, (*this)[__sub].first); } /** * @brief Gets the match or submatch converted to a string type. * @param __sub indicates the submatch. * @pre ready() == true * * This function gets the submatch (or match, if @p __sub is * zero) extracted from the target range and converted to the * associated string type. */ string_type str(size_type __sub = 0) const { return string_type((*this)[__sub]); } /** * @brief Gets a %sub_match reference for the match or submatch. * @param __sub indicates the submatch. * @pre ready() == true * * This function gets a reference to the indicated submatch, or * the entire match if @p __sub is zero. * * If @p __sub >= size() then this function returns a %sub_match with a * special value indicating no submatch. */ const_reference operator[](size_type __sub) const { __glibcxx_assert( ready() ); return __sub < size() ? _Base_type::operator[](__sub) : _M_unmatched_sub(); } /** * @brief Gets a %sub_match representing the match prefix. * @pre ready() == true * * This function gets a reference to a %sub_match object representing the * part of the target range between the start of the target range and the * start of the match. */ const_reference prefix() const { __glibcxx_assert( ready() ); return !empty() ? _M_prefix() : _M_unmatched_sub(); } /** * @brief Gets a %sub_match representing the match suffix. * @pre ready() == true * * This function gets a reference to a %sub_match object representing the * part of the target range between the end of the match and the end of * the target range. */ const_reference suffix() const { __glibcxx_assert( ready() ); return !empty() ? _M_suffix() : _M_unmatched_sub(); } /** * @brief Gets an iterator to the start of the %sub_match collection. */ const_iterator begin() const { return _Base_type::begin(); } /** * @brief Gets an iterator to the start of the %sub_match collection. */ const_iterator cbegin() const { return this->begin(); } /** * @brief Gets an iterator to one-past-the-end of the collection. */ const_iterator end() const { return _Base_type::end() - (empty() ? 0 : 3); } /** * @brief Gets an iterator to one-past-the-end of the collection. */ const_iterator cend() const { return this->end(); } //@} /** * @name 10.4 Formatting * * These functions perform formatted substitution of the matched * character sequences into their target. The format specifiers and * escape sequences accepted by these functions are determined by * their @p flags parameter as documented above. */ //@{ /** * @pre ready() == true */ template _Out_iter format(_Out_iter __out, const char_type* __fmt_first, const char_type* __fmt_last, match_flag_type __flags = regex_constants::format_default) const; /** * @pre ready() == true */ template _Out_iter format(_Out_iter __out, const basic_string& __fmt, match_flag_type __flags = regex_constants::format_default) const { return format(__out, __fmt.data(), __fmt.data() + __fmt.size(), __flags); } /** * @pre ready() == true */ template basic_string format(const basic_string& __fmt, match_flag_type __flags = regex_constants::format_default) const { basic_string __result; format(std::back_inserter(__result), __fmt, __flags); return __result; } /** * @pre ready() == true */ string_type format(const char_type* __fmt, match_flag_type __flags = regex_constants::format_default) const { string_type __result; format(std::back_inserter(__result), __fmt, __fmt + char_traits::length(__fmt), __flags); return __result; } //@} /** * @name 10.5 Allocator */ //@{ /** * @brief Gets a copy of the allocator. */ allocator_type get_allocator() const { return _Base_type::get_allocator(); } //@} /** * @name 10.6 Swap */ //@{ /** * @brief Swaps the contents of two match_results. */ void swap(match_results& __that) { using std::swap; _Base_type::swap(__that); swap(_M_begin, __that._M_begin); } //@} private: template friend class __detail::_Executor; template friend class regex_iterator; template friend bool __detail::__regex_algo_impl(_Bp, _Bp, match_results<_Bp, _Ap>&, const basic_regex<_Cp, _Rp>&, regex_constants::match_flag_type); void _M_resize(unsigned int __size) { _Base_type::resize(__size + 3); } const_reference _M_unmatched_sub() const { return _Base_type::operator[](_Base_type::size() - 3); } sub_match<_Bi_iter>& _M_unmatched_sub() { return _Base_type::operator[](_Base_type::size() - 3); } const_reference _M_prefix() const { return _Base_type::operator[](_Base_type::size() - 2); } sub_match<_Bi_iter>& _M_prefix() { return _Base_type::operator[](_Base_type::size() - 2); } const_reference _M_suffix() const { return _Base_type::operator[](_Base_type::size() - 1); } sub_match<_Bi_iter>& _M_suffix() { return _Base_type::operator[](_Base_type::size() - 1); } _Bi_iter _M_begin; }; typedef match_results cmatch; typedef match_results smatch; #ifdef _GLIBCXX_USE_WCHAR_T typedef match_results wcmatch; typedef match_results wsmatch; #endif // match_results comparisons /** * @brief Compares two match_results for equality. * @returns true if the two objects refer to the same match, * false otherwise. */ template inline bool operator==(const match_results<_Bi_iter, _Alloc>& __m1, const match_results<_Bi_iter, _Alloc>& __m2) { if (__m1.ready() != __m2.ready()) return false; if (!__m1.ready()) // both are not ready return true; if (__m1.empty() != __m2.empty()) return false; if (__m1.empty()) // both are empty return true; return __m1.prefix() == __m2.prefix() && __m1.size() == __m2.size() && std::equal(__m1.begin(), __m1.end(), __m2.begin()) && __m1.suffix() == __m2.suffix(); } /** * @brief Compares two match_results for inequality. * @returns true if the two objects do not refer to the same match, * false otherwise. */ template inline bool operator!=(const match_results<_Bi_iter, _Alloc>& __m1, const match_results<_Bi_iter, _Alloc>& __m2) { return !(__m1 == __m2); } // [7.10.6] match_results swap /** * @brief Swaps two match results. * @param __lhs A match result. * @param __rhs A match result. * * The contents of the two match_results objects are swapped. */ template inline void swap(match_results<_Bi_iter, _Alloc>& __lhs, match_results<_Bi_iter, _Alloc>& __rhs) { __lhs.swap(__rhs); } _GLIBCXX_END_NAMESPACE_CXX11 // [7.11.2] Function template regex_match /** * @name Matching, Searching, and Replacing */ //@{ /** * @brief Determines if there is a match between the regular expression @p e * and all of the character sequence [first, last). * * @param __s Start of the character sequence to match. * @param __e One-past-the-end of the character sequence to match. * @param __m The match results. * @param __re The regular expression. * @param __flags Controls how the regular expression is matched. * * @retval true A match exists. * @retval false Otherwise. * * @throws an exception of type regex_error. */ template inline bool regex_match(_Bi_iter __s, _Bi_iter __e, match_results<_Bi_iter, _Alloc>& __m, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __flags = regex_constants::match_default) { return __detail::__regex_algo_impl<_Bi_iter, _Alloc, _Ch_type, _Rx_traits, __detail::_RegexExecutorPolicy::_S_auto, true> (__s, __e, __m, __re, __flags); } /** * @brief Indicates if there is a match between the regular expression @p e * and all of the character sequence [first, last). * * @param __first Beginning of the character sequence to match. * @param __last One-past-the-end of the character sequence to match. * @param __re The regular expression. * @param __flags Controls how the regular expression is matched. * * @retval true A match exists. * @retval false Otherwise. * * @throws an exception of type regex_error. */ template inline bool regex_match(_Bi_iter __first, _Bi_iter __last, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __flags = regex_constants::match_default) { match_results<_Bi_iter> __what; return regex_match(__first, __last, __what, __re, __flags); } /** * @brief Determines if there is a match between the regular expression @p e * and a C-style null-terminated string. * * @param __s The C-style null-terminated string to match. * @param __m The match results. * @param __re The regular expression. * @param __f Controls how the regular expression is matched. * * @retval true A match exists. * @retval false Otherwise. * * @throws an exception of type regex_error. */ template inline bool regex_match(const _Ch_type* __s, match_results& __m, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __f = regex_constants::match_default) { return regex_match(__s, __s + _Rx_traits::length(__s), __m, __re, __f); } /** * @brief Determines if there is a match between the regular expression @p e * and a string. * * @param __s The string to match. * @param __m The match results. * @param __re The regular expression. * @param __flags Controls how the regular expression is matched. * * @retval true A match exists. * @retval false Otherwise. * * @throws an exception of type regex_error. */ template inline bool regex_match(const basic_string<_Ch_type, _Ch_traits, _Ch_alloc>& __s, match_results::const_iterator, _Alloc>& __m, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __flags = regex_constants::match_default) { return regex_match(__s.begin(), __s.end(), __m, __re, __flags); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2329. regex_match() with match_results should forbid temporary strings /// Prevent unsafe attempts to get match_results from a temporary string. template bool regex_match(const basic_string<_Ch_type, _Ch_traits, _Ch_alloc>&&, match_results::const_iterator, _Alloc>&, const basic_regex<_Ch_type, _Rx_traits>&, regex_constants::match_flag_type = regex_constants::match_default) = delete; /** * @brief Indicates if there is a match between the regular expression @p e * and a C-style null-terminated string. * * @param __s The C-style null-terminated string to match. * @param __re The regular expression. * @param __f Controls how the regular expression is matched. * * @retval true A match exists. * @retval false Otherwise. * * @throws an exception of type regex_error. */ template inline bool regex_match(const _Ch_type* __s, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __f = regex_constants::match_default) { return regex_match(__s, __s + _Rx_traits::length(__s), __re, __f); } /** * @brief Indicates if there is a match between the regular expression @p e * and a string. * * @param __s [IN] The string to match. * @param __re [IN] The regular expression. * @param __flags [IN] Controls how the regular expression is matched. * * @retval true A match exists. * @retval false Otherwise. * * @throws an exception of type regex_error. */ template inline bool regex_match(const basic_string<_Ch_type, _Ch_traits, _Str_allocator>& __s, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __flags = regex_constants::match_default) { return regex_match(__s.begin(), __s.end(), __re, __flags); } // [7.11.3] Function template regex_search /** * Searches for a regular expression within a range. * @param __s [IN] The start of the string to search. * @param __e [IN] One-past-the-end of the string to search. * @param __m [OUT] The match results. * @param __re [IN] The regular expression to search for. * @param __flags [IN] Search policy flags. * @retval true A match was found within the string. * @retval false No match was found within the string, the content of %m is * undefined. * * @throws an exception of type regex_error. */ template inline bool regex_search(_Bi_iter __s, _Bi_iter __e, match_results<_Bi_iter, _Alloc>& __m, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __flags = regex_constants::match_default) { return __detail::__regex_algo_impl<_Bi_iter, _Alloc, _Ch_type, _Rx_traits, __detail::_RegexExecutorPolicy::_S_auto, false> (__s, __e, __m, __re, __flags); } /** * Searches for a regular expression within a range. * @param __first [IN] The start of the string to search. * @param __last [IN] One-past-the-end of the string to search. * @param __re [IN] The regular expression to search for. * @param __flags [IN] Search policy flags. * @retval true A match was found within the string. * @retval false No match was found within the string. * * @throws an exception of type regex_error. */ template inline bool regex_search(_Bi_iter __first, _Bi_iter __last, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __flags = regex_constants::match_default) { match_results<_Bi_iter> __what; return regex_search(__first, __last, __what, __re, __flags); } /** * @brief Searches for a regular expression within a C-string. * @param __s [IN] A C-string to search for the regex. * @param __m [OUT] The set of regex matches. * @param __e [IN] The regex to search for in @p s. * @param __f [IN] The search flags. * @retval true A match was found within the string. * @retval false No match was found within the string, the content of %m is * undefined. * * @throws an exception of type regex_error. */ template inline bool regex_search(const _Ch_type* __s, match_results& __m, const basic_regex<_Ch_type, _Rx_traits>& __e, regex_constants::match_flag_type __f = regex_constants::match_default) { return regex_search(__s, __s + _Rx_traits::length(__s), __m, __e, __f); } /** * @brief Searches for a regular expression within a C-string. * @param __s [IN] The C-string to search. * @param __e [IN] The regular expression to search for. * @param __f [IN] Search policy flags. * @retval true A match was found within the string. * @retval false No match was found within the string. * * @throws an exception of type regex_error. */ template inline bool regex_search(const _Ch_type* __s, const basic_regex<_Ch_type, _Rx_traits>& __e, regex_constants::match_flag_type __f = regex_constants::match_default) { return regex_search(__s, __s + _Rx_traits::length(__s), __e, __f); } /** * @brief Searches for a regular expression within a string. * @param __s [IN] The string to search. * @param __e [IN] The regular expression to search for. * @param __flags [IN] Search policy flags. * @retval true A match was found within the string. * @retval false No match was found within the string. * * @throws an exception of type regex_error. */ template inline bool regex_search(const basic_string<_Ch_type, _Ch_traits, _String_allocator>& __s, const basic_regex<_Ch_type, _Rx_traits>& __e, regex_constants::match_flag_type __flags = regex_constants::match_default) { return regex_search(__s.begin(), __s.end(), __e, __flags); } /** * @brief Searches for a regular expression within a string. * @param __s [IN] A C++ string to search for the regex. * @param __m [OUT] The set of regex matches. * @param __e [IN] The regex to search for in @p s. * @param __f [IN] The search flags. * @retval true A match was found within the string. * @retval false No match was found within the string, the content of %m is * undefined. * * @throws an exception of type regex_error. */ template inline bool regex_search(const basic_string<_Ch_type, _Ch_traits, _Ch_alloc>& __s, match_results::const_iterator, _Alloc>& __m, const basic_regex<_Ch_type, _Rx_traits>& __e, regex_constants::match_flag_type __f = regex_constants::match_default) { return regex_search(__s.begin(), __s.end(), __m, __e, __f); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2329. regex_search() with match_results should forbid temporary strings /// Prevent unsafe attempts to get match_results from a temporary string. template bool regex_search(const basic_string<_Ch_type, _Ch_traits, _Ch_alloc>&&, match_results::const_iterator, _Alloc>&, const basic_regex<_Ch_type, _Rx_traits>&, regex_constants::match_flag_type = regex_constants::match_default) = delete; // std [28.11.4] Function template regex_replace /** * @brief Search for a regular expression within a range for multiple times, and replace the matched parts through filling a format string. * @param __out [OUT] The output iterator. * @param __first [IN] The start of the string to search. * @param __last [IN] One-past-the-end of the string to search. * @param __e [IN] The regular expression to search for. * @param __fmt [IN] The format string. * @param __flags [IN] Search and replace policy flags. * * @returns __out * @throws an exception of type regex_error. */ template inline _Out_iter regex_replace(_Out_iter __out, _Bi_iter __first, _Bi_iter __last, const basic_regex<_Ch_type, _Rx_traits>& __e, const basic_string<_Ch_type, _St, _Sa>& __fmt, regex_constants::match_flag_type __flags = regex_constants::match_default) { return regex_replace(__out, __first, __last, __e, __fmt.c_str(), __flags); } /** * @brief Search for a regular expression within a range for multiple times, and replace the matched parts through filling a format C-string. * @param __out [OUT] The output iterator. * @param __first [IN] The start of the string to search. * @param __last [IN] One-past-the-end of the string to search. * @param __e [IN] The regular expression to search for. * @param __fmt [IN] The format C-string. * @param __flags [IN] Search and replace policy flags. * * @returns __out * @throws an exception of type regex_error. */ template _Out_iter regex_replace(_Out_iter __out, _Bi_iter __first, _Bi_iter __last, const basic_regex<_Ch_type, _Rx_traits>& __e, const _Ch_type* __fmt, regex_constants::match_flag_type __flags = regex_constants::match_default); /** * @brief Search for a regular expression within a string for multiple times, and replace the matched parts through filling a format string. * @param __s [IN] The string to search and replace. * @param __e [IN] The regular expression to search for. * @param __fmt [IN] The format string. * @param __flags [IN] Search and replace policy flags. * * @returns The string after replacing. * @throws an exception of type regex_error. */ template inline basic_string<_Ch_type, _St, _Sa> regex_replace(const basic_string<_Ch_type, _St, _Sa>& __s, const basic_regex<_Ch_type, _Rx_traits>& __e, const basic_string<_Ch_type, _Fst, _Fsa>& __fmt, regex_constants::match_flag_type __flags = regex_constants::match_default) { basic_string<_Ch_type, _St, _Sa> __result; regex_replace(std::back_inserter(__result), __s.begin(), __s.end(), __e, __fmt, __flags); return __result; } /** * @brief Search for a regular expression within a string for multiple times, and replace the matched parts through filling a format C-string. * @param __s [IN] The string to search and replace. * @param __e [IN] The regular expression to search for. * @param __fmt [IN] The format C-string. * @param __flags [IN] Search and replace policy flags. * * @returns The string after replacing. * @throws an exception of type regex_error. */ template inline basic_string<_Ch_type, _St, _Sa> regex_replace(const basic_string<_Ch_type, _St, _Sa>& __s, const basic_regex<_Ch_type, _Rx_traits>& __e, const _Ch_type* __fmt, regex_constants::match_flag_type __flags = regex_constants::match_default) { basic_string<_Ch_type, _St, _Sa> __result; regex_replace(std::back_inserter(__result), __s.begin(), __s.end(), __e, __fmt, __flags); return __result; } /** * @brief Search for a regular expression within a C-string for multiple times, and replace the matched parts through filling a format string. * @param __s [IN] The C-string to search and replace. * @param __e [IN] The regular expression to search for. * @param __fmt [IN] The format string. * @param __flags [IN] Search and replace policy flags. * * @returns The string after replacing. * @throws an exception of type regex_error. */ template inline basic_string<_Ch_type> regex_replace(const _Ch_type* __s, const basic_regex<_Ch_type, _Rx_traits>& __e, const basic_string<_Ch_type, _St, _Sa>& __fmt, regex_constants::match_flag_type __flags = regex_constants::match_default) { basic_string<_Ch_type> __result; regex_replace(std::back_inserter(__result), __s, __s + char_traits<_Ch_type>::length(__s), __e, __fmt, __flags); return __result; } /** * @brief Search for a regular expression within a C-string for multiple times, and replace the matched parts through filling a format C-string. * @param __s [IN] The C-string to search and replace. * @param __e [IN] The regular expression to search for. * @param __fmt [IN] The format C-string. * @param __flags [IN] Search and replace policy flags. * * @returns The string after replacing. * @throws an exception of type regex_error. */ template inline basic_string<_Ch_type> regex_replace(const _Ch_type* __s, const basic_regex<_Ch_type, _Rx_traits>& __e, const _Ch_type* __fmt, regex_constants::match_flag_type __flags = regex_constants::match_default) { basic_string<_Ch_type> __result; regex_replace(std::back_inserter(__result), __s, __s + char_traits<_Ch_type>::length(__s), __e, __fmt, __flags); return __result; } //@} _GLIBCXX_BEGIN_NAMESPACE_CXX11 // std [28.12] Class template regex_iterator /** * An iterator adaptor that will provide repeated calls of regex_search over * a range until no more matches remain. */ template::value_type, typename _Rx_traits = regex_traits<_Ch_type> > class regex_iterator { public: typedef basic_regex<_Ch_type, _Rx_traits> regex_type; typedef match_results<_Bi_iter> value_type; typedef std::ptrdiff_t difference_type; typedef const value_type* pointer; typedef const value_type& reference; typedef std::forward_iterator_tag iterator_category; /** * @brief Provides a singular iterator, useful for indicating * one-past-the-end of a range. */ regex_iterator() : _M_pregex() { } /** * Constructs a %regex_iterator... * @param __a [IN] The start of a text range to search. * @param __b [IN] One-past-the-end of the text range to search. * @param __re [IN] The regular expression to match. * @param __m [IN] Policy flags for match rules. */ regex_iterator(_Bi_iter __a, _Bi_iter __b, const regex_type& __re, regex_constants::match_flag_type __m = regex_constants::match_default) : _M_begin(__a), _M_end(__b), _M_pregex(&__re), _M_flags(__m), _M_match() { if (!regex_search(_M_begin, _M_end, _M_match, *_M_pregex, _M_flags)) *this = regex_iterator(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2332. regex_iterator should forbid temporary regexes regex_iterator(_Bi_iter, _Bi_iter, const regex_type&&, regex_constants::match_flag_type = regex_constants::match_default) = delete; /** * Copy constructs a %regex_iterator. */ regex_iterator(const regex_iterator& __rhs) = default; /** * @brief Assigns one %regex_iterator to another. */ regex_iterator& operator=(const regex_iterator& __rhs) = default; /** * @brief Tests the equivalence of two regex iterators. */ bool operator==(const regex_iterator& __rhs) const; /** * @brief Tests the inequivalence of two regex iterators. */ bool operator!=(const regex_iterator& __rhs) const { return !(*this == __rhs); } /** * @brief Dereferences a %regex_iterator. */ const value_type& operator*() const { return _M_match; } /** * @brief Selects a %regex_iterator member. */ const value_type* operator->() const { return &_M_match; } /** * @brief Increments a %regex_iterator. */ regex_iterator& operator++(); /** * @brief Postincrements a %regex_iterator. */ regex_iterator operator++(int) { auto __tmp = *this; ++(*this); return __tmp; } private: _Bi_iter _M_begin; _Bi_iter _M_end; const regex_type* _M_pregex; regex_constants::match_flag_type _M_flags; match_results<_Bi_iter> _M_match; }; typedef regex_iterator cregex_iterator; typedef regex_iterator sregex_iterator; #ifdef _GLIBCXX_USE_WCHAR_T typedef regex_iterator wcregex_iterator; typedef regex_iterator wsregex_iterator; #endif // [7.12.2] Class template regex_token_iterator /** * Iterates over submatches in a range (or @a splits a text string). * * The purpose of this iterator is to enumerate all, or all specified, * matches of a regular expression within a text range. The dereferenced * value of an iterator of this class is a std::sub_match object. */ template::value_type, typename _Rx_traits = regex_traits<_Ch_type> > class regex_token_iterator { public: typedef basic_regex<_Ch_type, _Rx_traits> regex_type; typedef sub_match<_Bi_iter> value_type; typedef std::ptrdiff_t difference_type; typedef const value_type* pointer; typedef const value_type& reference; typedef std::forward_iterator_tag iterator_category; public: /** * @brief Default constructs a %regex_token_iterator. * * A default-constructed %regex_token_iterator is a singular iterator * that will compare equal to the one-past-the-end value for any * iterator of the same type. */ regex_token_iterator() : _M_position(), _M_subs(), _M_suffix(), _M_n(0), _M_result(nullptr), _M_has_m1(false) { } /** * Constructs a %regex_token_iterator... * @param __a [IN] The start of the text to search. * @param __b [IN] One-past-the-end of the text to search. * @param __re [IN] The regular expression to search for. * @param __submatch [IN] Which submatch to return. There are some * special values for this parameter: * - -1 each enumerated subexpression does NOT * match the regular expression (aka field * splitting) * - 0 the entire string matching the * subexpression is returned for each match * within the text. * - >0 enumerates only the indicated * subexpression from a match within the text. * @param __m [IN] Policy flags for match rules. */ regex_token_iterator(_Bi_iter __a, _Bi_iter __b, const regex_type& __re, int __submatch = 0, regex_constants::match_flag_type __m = regex_constants::match_default) : _M_position(__a, __b, __re, __m), _M_subs(1, __submatch), _M_n(0) { _M_init(__a, __b); } /** * Constructs a %regex_token_iterator... * @param __a [IN] The start of the text to search. * @param __b [IN] One-past-the-end of the text to search. * @param __re [IN] The regular expression to search for. * @param __submatches [IN] A list of subexpressions to return for each * regular expression match within the text. * @param __m [IN] Policy flags for match rules. */ regex_token_iterator(_Bi_iter __a, _Bi_iter __b, const regex_type& __re, const std::vector& __submatches, regex_constants::match_flag_type __m = regex_constants::match_default) : _M_position(__a, __b, __re, __m), _M_subs(__submatches), _M_n(0) { _M_init(__a, __b); } /** * Constructs a %regex_token_iterator... * @param __a [IN] The start of the text to search. * @param __b [IN] One-past-the-end of the text to search. * @param __re [IN] The regular expression to search for. * @param __submatches [IN] A list of subexpressions to return for each * regular expression match within the text. * @param __m [IN] Policy flags for match rules. */ regex_token_iterator(_Bi_iter __a, _Bi_iter __b, const regex_type& __re, initializer_list __submatches, regex_constants::match_flag_type __m = regex_constants::match_default) : _M_position(__a, __b, __re, __m), _M_subs(__submatches), _M_n(0) { _M_init(__a, __b); } /** * Constructs a %regex_token_iterator... * @param __a [IN] The start of the text to search. * @param __b [IN] One-past-the-end of the text to search. * @param __re [IN] The regular expression to search for. * @param __submatches [IN] A list of subexpressions to return for each * regular expression match within the text. * @param __m [IN] Policy flags for match rules. */ template regex_token_iterator(_Bi_iter __a, _Bi_iter __b, const regex_type& __re, const int (&__submatches)[_Nm], regex_constants::match_flag_type __m = regex_constants::match_default) : _M_position(__a, __b, __re, __m), _M_subs(__submatches, __submatches + _Nm), _M_n(0) { _M_init(__a, __b); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2332. regex_token_iterator should forbid temporary regexes regex_token_iterator(_Bi_iter, _Bi_iter, const regex_type&&, int = 0, regex_constants::match_flag_type = regex_constants::match_default) = delete; regex_token_iterator(_Bi_iter, _Bi_iter, const regex_type&&, const std::vector&, regex_constants::match_flag_type = regex_constants::match_default) = delete; regex_token_iterator(_Bi_iter, _Bi_iter, const regex_type&&, initializer_list, regex_constants::match_flag_type = regex_constants::match_default) = delete; template regex_token_iterator(_Bi_iter, _Bi_iter, const regex_type&&, const int (&)[_Nm], regex_constants::match_flag_type = regex_constants::match_default) = delete; /** * @brief Copy constructs a %regex_token_iterator. * @param __rhs [IN] A %regex_token_iterator to copy. */ regex_token_iterator(const regex_token_iterator& __rhs) : _M_position(__rhs._M_position), _M_subs(__rhs._M_subs), _M_suffix(__rhs._M_suffix), _M_n(__rhs._M_n), _M_has_m1(__rhs._M_has_m1) { _M_normalize_result(); } /** * @brief Assigns a %regex_token_iterator to another. * @param __rhs [IN] A %regex_token_iterator to copy. */ regex_token_iterator& operator=(const regex_token_iterator& __rhs); /** * @brief Compares a %regex_token_iterator to another for equality. */ bool operator==(const regex_token_iterator& __rhs) const; /** * @brief Compares a %regex_token_iterator to another for inequality. */ bool operator!=(const regex_token_iterator& __rhs) const { return !(*this == __rhs); } /** * @brief Dereferences a %regex_token_iterator. */ const value_type& operator*() const { return *_M_result; } /** * @brief Selects a %regex_token_iterator member. */ const value_type* operator->() const { return _M_result; } /** * @brief Increments a %regex_token_iterator. */ regex_token_iterator& operator++(); /** * @brief Postincrements a %regex_token_iterator. */ regex_token_iterator operator++(int) { auto __tmp = *this; ++(*this); return __tmp; } private: typedef regex_iterator<_Bi_iter, _Ch_type, _Rx_traits> _Position; void _M_init(_Bi_iter __a, _Bi_iter __b); const value_type& _M_current_match() const { if (_M_subs[_M_n] == -1) return (*_M_position).prefix(); else return (*_M_position)[_M_subs[_M_n]]; } constexpr bool _M_end_of_seq() const { return _M_result == nullptr; } // [28.12.2.2.4] void _M_normalize_result() { if (_M_position != _Position()) _M_result = &_M_current_match(); else if (_M_has_m1) _M_result = &_M_suffix; else _M_result = nullptr; } _Position _M_position; std::vector _M_subs; value_type _M_suffix; std::size_t _M_n; const value_type* _M_result; // Show whether _M_subs contains -1 bool _M_has_m1; }; /** @brief Token iterator for C-style NULL-terminated strings. */ typedef regex_token_iterator cregex_token_iterator; /** @brief Token iterator for standard strings. */ typedef regex_token_iterator sregex_token_iterator; #ifdef _GLIBCXX_USE_WCHAR_T /** @brief Token iterator for C-style NULL-terminated wide strings. */ typedef regex_token_iterator wcregex_token_iterator; /** @brief Token iterator for standard wide-character strings. */ typedef regex_token_iterator wsregex_token_iterator; #endif //@} // group regex _GLIBCXX_END_NAMESPACE_CXX11 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #include PK!'a@@8/bits/regex.tccnu[// class template regex -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { // Result of merging regex_match and regex_search. // // __policy now can be _S_auto (auto dispatch) and _S_alternate (use // the other one if possible, for test purpose). // // That __match_mode is true means regex_match, else regex_search. template bool __regex_algo_impl(_BiIter __s, _BiIter __e, match_results<_BiIter, _Alloc>& __m, const basic_regex<_CharT, _TraitsT>& __re, regex_constants::match_flag_type __flags) { if (__re._M_automaton == nullptr) return false; typename match_results<_BiIter, _Alloc>::_Base_type& __res = __m; __m._M_begin = __s; __m._M_resize(__re._M_automaton->_M_sub_count()); for (auto& __it : __res) __it.matched = false; bool __ret; if ((__re.flags() & regex_constants::__polynomial) || (__policy == _RegexExecutorPolicy::_S_alternate && !__re._M_automaton->_M_has_backref)) { _Executor<_BiIter, _Alloc, _TraitsT, false> __executor(__s, __e, __m, __re, __flags); if (__match_mode) __ret = __executor._M_match(); else __ret = __executor._M_search(); } else { _Executor<_BiIter, _Alloc, _TraitsT, true> __executor(__s, __e, __m, __re, __flags); if (__match_mode) __ret = __executor._M_match(); else __ret = __executor._M_search(); } if (__ret) { for (auto& __it : __res) if (!__it.matched) __it.first = __it.second = __e; auto& __pre = __m._M_prefix(); auto& __suf = __m._M_suffix(); if (__match_mode) { __pre.matched = false; __pre.first = __s; __pre.second = __s; __suf.matched = false; __suf.first = __e; __suf.second = __e; } else { __pre.first = __s; __pre.second = __res[0].first; __pre.matched = (__pre.first != __pre.second); __suf.first = __res[0].second; __suf.second = __e; __suf.matched = (__suf.first != __suf.second); } } else { __m._M_resize(0); for (auto& __it : __res) { __it.matched = false; __it.first = __it.second = __e; } } return __ret; } } template template typename regex_traits<_Ch_type>::string_type regex_traits<_Ch_type>:: lookup_collatename(_Fwd_iter __first, _Fwd_iter __last) const { typedef std::ctype __ctype_type; const __ctype_type& __fctyp(use_facet<__ctype_type>(_M_locale)); static const char* __collatenames[] = { "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "alert", "backspace", "tab", "newline", "vertical-tab", "form-feed", "carriage-return", "SO", "SI", "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB", "ESC", "IS4", "IS3", "IS2", "IS1", "space", "exclamation-mark", "quotation-mark", "number-sign", "dollar-sign", "percent-sign", "ampersand", "apostrophe", "left-parenthesis", "right-parenthesis", "asterisk", "plus-sign", "comma", "hyphen", "period", "slash", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less-than-sign", "equals-sign", "greater-than-sign", "question-mark", "commercial-at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "left-square-bracket", "backslash", "right-square-bracket", "circumflex", "underscore", "grave-accent", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "left-curly-bracket", "vertical-line", "right-curly-bracket", "tilde", "DEL", }; string __s; for (; __first != __last; ++__first) __s += __fctyp.narrow(*__first, 0); for (const auto& __it : __collatenames) if (__s == __it) return string_type(1, __fctyp.widen( static_cast(&__it - __collatenames))); // TODO Add digraph support: // http://boost.sourceforge.net/libs/regex/doc/collating_names.html return string_type(); } template template typename regex_traits<_Ch_type>::char_class_type regex_traits<_Ch_type>:: lookup_classname(_Fwd_iter __first, _Fwd_iter __last, bool __icase) const { typedef std::ctype __ctype_type; const __ctype_type& __fctyp(use_facet<__ctype_type>(_M_locale)); // Mappings from class name to class mask. static const pair __classnames[] = { {"d", ctype_base::digit}, {"w", {ctype_base::alnum, _RegexMask::_S_under}}, {"s", ctype_base::space}, {"alnum", ctype_base::alnum}, {"alpha", ctype_base::alpha}, {"blank", ctype_base::blank}, {"cntrl", ctype_base::cntrl}, {"digit", ctype_base::digit}, {"graph", ctype_base::graph}, {"lower", ctype_base::lower}, {"print", ctype_base::print}, {"punct", ctype_base::punct}, {"space", ctype_base::space}, {"upper", ctype_base::upper}, {"xdigit", ctype_base::xdigit}, }; string __s; for (; __first != __last; ++__first) __s += __fctyp.narrow(__fctyp.tolower(*__first), 0); for (const auto& __it : __classnames) if (__s == __it.first) { if (__icase && ((__it.second & (ctype_base::lower | ctype_base::upper)) != 0)) return ctype_base::alpha; return __it.second; } return 0; } template bool regex_traits<_Ch_type>:: isctype(_Ch_type __c, char_class_type __f) const { typedef std::ctype __ctype_type; const __ctype_type& __fctyp(use_facet<__ctype_type>(_M_locale)); return __fctyp.is(__f._M_base, __c) // [[:w:]] || ((__f._M_extended & _RegexMask::_S_under) && __c == __fctyp.widen('_')); } template int regex_traits<_Ch_type>:: value(_Ch_type __ch, int __radix) const { std::basic_istringstream __is(string_type(1, __ch)); long __v; if (__radix == 8) __is >> std::oct; else if (__radix == 16) __is >> std::hex; __is >> __v; return __is.fail() ? -1 : __v; } template template _Out_iter match_results<_Bi_iter, _Alloc>:: format(_Out_iter __out, const match_results<_Bi_iter, _Alloc>::char_type* __fmt_first, const match_results<_Bi_iter, _Alloc>::char_type* __fmt_last, match_flag_type __flags) const { __glibcxx_assert( ready() ); regex_traits __traits; typedef std::ctype __ctype_type; const __ctype_type& __fctyp(use_facet<__ctype_type>(__traits.getloc())); auto __output = [&](size_t __idx) { auto& __sub = (*this)[__idx]; if (__sub.matched) __out = std::copy(__sub.first, __sub.second, __out); }; if (__flags & regex_constants::format_sed) { bool __escaping = false; for (; __fmt_first != __fmt_last; __fmt_first++) { if (__escaping) { __escaping = false; if (__fctyp.is(__ctype_type::digit, *__fmt_first)) __output(__traits.value(*__fmt_first, 10)); else *__out++ = *__fmt_first; continue; } if (*__fmt_first == '\\') { __escaping = true; continue; } if (*__fmt_first == '&') { __output(0); continue; } *__out++ = *__fmt_first; } if (__escaping) *__out++ = '\\'; } else { while (1) { auto __next = std::find(__fmt_first, __fmt_last, '$'); if (__next == __fmt_last) break; __out = std::copy(__fmt_first, __next, __out); auto __eat = [&](char __ch) -> bool { if (*__next == __ch) { ++__next; return true; } return false; }; if (++__next == __fmt_last) *__out++ = '$'; else if (__eat('$')) *__out++ = '$'; else if (__eat('&')) __output(0); else if (__eat('`')) { auto& __sub = _M_prefix(); if (__sub.matched) __out = std::copy(__sub.first, __sub.second, __out); } else if (__eat('\'')) { auto& __sub = _M_suffix(); if (__sub.matched) __out = std::copy(__sub.first, __sub.second, __out); } else if (__fctyp.is(__ctype_type::digit, *__next)) { long __num = __traits.value(*__next, 10); if (++__next != __fmt_last && __fctyp.is(__ctype_type::digit, *__next)) { __num *= 10; __num += __traits.value(*__next++, 10); } if (0 <= __num && __num < this->size()) __output(__num); } else *__out++ = '$'; __fmt_first = __next; } __out = std::copy(__fmt_first, __fmt_last, __out); } return __out; } template _Out_iter regex_replace(_Out_iter __out, _Bi_iter __first, _Bi_iter __last, const basic_regex<_Ch_type, _Rx_traits>& __e, const _Ch_type* __fmt, regex_constants::match_flag_type __flags) { typedef regex_iterator<_Bi_iter, _Ch_type, _Rx_traits> _IterT; _IterT __i(__first, __last, __e, __flags); _IterT __end; if (__i == __end) { if (!(__flags & regex_constants::format_no_copy)) __out = std::copy(__first, __last, __out); } else { sub_match<_Bi_iter> __last; auto __len = char_traits<_Ch_type>::length(__fmt); for (; __i != __end; ++__i) { if (!(__flags & regex_constants::format_no_copy)) __out = std::copy(__i->prefix().first, __i->prefix().second, __out); __out = __i->format(__out, __fmt, __fmt + __len, __flags); __last = __i->suffix(); if (__flags & regex_constants::format_first_only) break; } if (!(__flags & regex_constants::format_no_copy)) __out = std::copy(__last.first, __last.second, __out); } return __out; } template bool regex_iterator<_Bi_iter, _Ch_type, _Rx_traits>:: operator==(const regex_iterator& __rhs) const { if (_M_pregex == nullptr && __rhs._M_pregex == nullptr) return true; return _M_pregex == __rhs._M_pregex && _M_begin == __rhs._M_begin && _M_end == __rhs._M_end && _M_flags == __rhs._M_flags && _M_match[0] == __rhs._M_match[0]; } template regex_iterator<_Bi_iter, _Ch_type, _Rx_traits>& regex_iterator<_Bi_iter, _Ch_type, _Rx_traits>:: operator++() { // In all cases in which the call to regex_search returns true, // match.prefix().first shall be equal to the previous value of // match[0].second, and for each index i in the half-open range // [0, match.size()) for which match[i].matched is true, // match[i].position() shall return distance(begin, match[i].first). // [28.12.1.4.5] if (_M_match[0].matched) { auto __start = _M_match[0].second; auto __prefix_first = _M_match[0].second; if (_M_match[0].first == _M_match[0].second) { if (__start == _M_end) { _M_pregex = nullptr; return *this; } else { if (regex_search(__start, _M_end, _M_match, *_M_pregex, _M_flags | regex_constants::match_not_null | regex_constants::match_continuous)) { __glibcxx_assert(_M_match[0].matched); auto& __prefix = _M_match._M_prefix(); __prefix.first = __prefix_first; __prefix.matched = __prefix.first != __prefix.second; // [28.12.1.4.5] _M_match._M_begin = _M_begin; return *this; } else ++__start; } } _M_flags |= regex_constants::match_prev_avail; if (regex_search(__start, _M_end, _M_match, *_M_pregex, _M_flags)) { __glibcxx_assert(_M_match[0].matched); auto& __prefix = _M_match._M_prefix(); __prefix.first = __prefix_first; __prefix.matched = __prefix.first != __prefix.second; // [28.12.1.4.5] _M_match._M_begin = _M_begin; } else _M_pregex = nullptr; } return *this; } template regex_token_iterator<_Bi_iter, _Ch_type, _Rx_traits>& regex_token_iterator<_Bi_iter, _Ch_type, _Rx_traits>:: operator=(const regex_token_iterator& __rhs) { _M_position = __rhs._M_position; _M_subs = __rhs._M_subs; _M_n = __rhs._M_n; _M_suffix = __rhs._M_suffix; _M_has_m1 = __rhs._M_has_m1; _M_normalize_result(); return *this; } template bool regex_token_iterator<_Bi_iter, _Ch_type, _Rx_traits>:: operator==(const regex_token_iterator& __rhs) const { if (_M_end_of_seq() && __rhs._M_end_of_seq()) return true; if (_M_suffix.matched && __rhs._M_suffix.matched && _M_suffix == __rhs._M_suffix) return true; if (_M_end_of_seq() || _M_suffix.matched || __rhs._M_end_of_seq() || __rhs._M_suffix.matched) return false; return _M_position == __rhs._M_position && _M_n == __rhs._M_n && _M_subs == __rhs._M_subs; } template regex_token_iterator<_Bi_iter, _Ch_type, _Rx_traits>& regex_token_iterator<_Bi_iter, _Ch_type, _Rx_traits>:: operator++() { _Position __prev = _M_position; if (_M_suffix.matched) *this = regex_token_iterator(); else if (_M_n + 1 < _M_subs.size()) { _M_n++; _M_result = &_M_current_match(); } else { _M_n = 0; ++_M_position; if (_M_position != _Position()) _M_result = &_M_current_match(); else if (_M_has_m1 && __prev->suffix().length() != 0) { _M_suffix.matched = true; _M_suffix.first = __prev->suffix().first; _M_suffix.second = __prev->suffix().second; _M_result = &_M_suffix; } else *this = regex_token_iterator(); } return *this; } template void regex_token_iterator<_Bi_iter, _Ch_type, _Rx_traits>:: _M_init(_Bi_iter __a, _Bi_iter __b) { _M_has_m1 = false; for (auto __it : _M_subs) if (__it == -1) { _M_has_m1 = true; break; } if (_M_position != _Position()) _M_result = &_M_current_match(); else if (_M_has_m1) { _M_suffix.matched = true; _M_suffix.first = __a; _M_suffix.second = __b; _M_result = &_M_suffix; } else _M_result = nullptr; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace PK!c))8/bits/regex_automaton.hnu[// class template regex -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_automaton.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ // This macro defines the maximal state number a NFA can have. #ifndef _GLIBCXX_REGEX_STATE_LIMIT #define _GLIBCXX_REGEX_STATE_LIMIT 100000 #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { /** * @defgroup regex-detail Base and Implementation Classes * @ingroup regex * @{ */ typedef long _StateIdT; static const _StateIdT _S_invalid_state_id = -1; template using _Matcher = std::function; /// Operation codes that define the type of transitions within the base NFA /// that represents the regular expression. enum _Opcode : int { _S_opcode_unknown, _S_opcode_alternative, _S_opcode_repeat, _S_opcode_backref, _S_opcode_line_begin_assertion, _S_opcode_line_end_assertion, _S_opcode_word_boundary, _S_opcode_subexpr_lookahead, _S_opcode_subexpr_begin, _S_opcode_subexpr_end, _S_opcode_dummy, _S_opcode_match, _S_opcode_accept, }; struct _State_base { protected: _Opcode _M_opcode; // type of outgoing transition public: _StateIdT _M_next; // outgoing transition union // Since they are mutually exclusive. { size_t _M_subexpr; // for _S_opcode_subexpr_* size_t _M_backref_index; // for _S_opcode_backref struct { // for _S_opcode_alternative, _S_opcode_repeat and // _S_opcode_subexpr_lookahead _StateIdT _M_alt; // for _S_opcode_word_boundary or _S_opcode_subexpr_lookahead or // quantifiers (ungreedy if set true) bool _M_neg; }; // For _S_opcode_match __gnu_cxx::__aligned_membuf<_Matcher> _M_matcher_storage; }; protected: explicit _State_base(_Opcode __opcode) : _M_opcode(__opcode), _M_next(_S_invalid_state_id) { } public: bool _M_has_alt() { return _M_opcode == _S_opcode_alternative || _M_opcode == _S_opcode_repeat || _M_opcode == _S_opcode_subexpr_lookahead; } #ifdef _GLIBCXX_DEBUG std::ostream& _M_print(std::ostream& ostr) const; // Prints graphviz dot commands for state. std::ostream& _M_dot(std::ostream& __ostr, _StateIdT __id) const; #endif }; template struct _State : _State_base { typedef _Matcher<_Char_type> _MatcherT; static_assert(sizeof(_MatcherT) == sizeof(_Matcher), "std::function has the same size as " "std::function"); static_assert(alignof(_MatcherT) == alignof(_Matcher), "std::function has the same alignment as " "std::function"); explicit _State(_Opcode __opcode) : _State_base(__opcode) { if (_M_opcode() == _S_opcode_match) new (this->_M_matcher_storage._M_addr()) _MatcherT(); } _State(const _State& __rhs) : _State_base(__rhs) { if (__rhs._M_opcode() == _S_opcode_match) new (this->_M_matcher_storage._M_addr()) _MatcherT(__rhs._M_get_matcher()); } _State(_State&& __rhs) : _State_base(__rhs) { if (__rhs._M_opcode() == _S_opcode_match) new (this->_M_matcher_storage._M_addr()) _MatcherT(std::move(__rhs._M_get_matcher())); } _State& operator=(const _State&) = delete; ~_State() { if (_M_opcode() == _S_opcode_match) _M_get_matcher().~_MatcherT(); } // Since correct ctor and dtor rely on _M_opcode, it's better not to // change it over time. _Opcode _M_opcode() const { return _State_base::_M_opcode; } bool _M_matches(_Char_type __char) const { return _M_get_matcher()(__char); } _MatcherT& _M_get_matcher() { return *static_cast<_MatcherT*>(this->_M_matcher_storage._M_addr()); } const _MatcherT& _M_get_matcher() const { return *static_cast( this->_M_matcher_storage._M_addr()); } }; struct _NFA_base { typedef size_t _SizeT; typedef regex_constants::syntax_option_type _FlagT; explicit _NFA_base(_FlagT __f) : _M_flags(__f), _M_start_state(0), _M_subexpr_count(0), _M_has_backref(false) { } _NFA_base(_NFA_base&&) = default; protected: ~_NFA_base() = default; public: _FlagT _M_options() const { return _M_flags; } _StateIdT _M_start() const { return _M_start_state; } _SizeT _M_sub_count() const { return _M_subexpr_count; } std::vector _M_paren_stack; _FlagT _M_flags; _StateIdT _M_start_state; _SizeT _M_subexpr_count; bool _M_has_backref; }; template struct _NFA : _NFA_base, std::vector<_State> { typedef typename _TraitsT::char_type _Char_type; typedef _State<_Char_type> _StateT; typedef _Matcher<_Char_type> _MatcherT; _NFA(const typename _TraitsT::locale_type& __loc, _FlagT __flags) : _NFA_base(__flags) { _M_traits.imbue(__loc); } // for performance reasons _NFA objects should only be moved not copied _NFA(const _NFA&) = delete; _NFA(_NFA&&) = default; _StateIdT _M_insert_accept() { auto __ret = _M_insert_state(_StateT(_S_opcode_accept)); return __ret; } _StateIdT _M_insert_alt(_StateIdT __next, _StateIdT __alt, bool __neg __attribute__((__unused__))) { _StateT __tmp(_S_opcode_alternative); // It labels every quantifier to make greedy comparison easier in BFS // approach. __tmp._M_next = __next; __tmp._M_alt = __alt; return _M_insert_state(std::move(__tmp)); } _StateIdT _M_insert_repeat(_StateIdT __next, _StateIdT __alt, bool __neg) { _StateT __tmp(_S_opcode_repeat); // It labels every quantifier to make greedy comparison easier in BFS // approach. __tmp._M_next = __next; __tmp._M_alt = __alt; __tmp._M_neg = __neg; return _M_insert_state(std::move(__tmp)); } _StateIdT _M_insert_matcher(_MatcherT __m) { _StateT __tmp(_S_opcode_match); __tmp._M_get_matcher() = std::move(__m); return _M_insert_state(std::move(__tmp)); } _StateIdT _M_insert_subexpr_begin() { auto __id = this->_M_subexpr_count++; this->_M_paren_stack.push_back(__id); _StateT __tmp(_S_opcode_subexpr_begin); __tmp._M_subexpr = __id; return _M_insert_state(std::move(__tmp)); } _StateIdT _M_insert_subexpr_end() { _StateT __tmp(_S_opcode_subexpr_end); __tmp._M_subexpr = this->_M_paren_stack.back(); this->_M_paren_stack.pop_back(); return _M_insert_state(std::move(__tmp)); } _StateIdT _M_insert_backref(size_t __index); _StateIdT _M_insert_line_begin() { return _M_insert_state(_StateT(_S_opcode_line_begin_assertion)); } _StateIdT _M_insert_line_end() { return _M_insert_state(_StateT(_S_opcode_line_end_assertion)); } _StateIdT _M_insert_word_bound(bool __neg) { _StateT __tmp(_S_opcode_word_boundary); __tmp._M_neg = __neg; return _M_insert_state(std::move(__tmp)); } _StateIdT _M_insert_lookahead(_StateIdT __alt, bool __neg) { _StateT __tmp(_S_opcode_subexpr_lookahead); __tmp._M_alt = __alt; __tmp._M_neg = __neg; return _M_insert_state(std::move(__tmp)); } _StateIdT _M_insert_dummy() { return _M_insert_state(_StateT(_S_opcode_dummy)); } _StateIdT _M_insert_state(_StateT __s) { this->push_back(std::move(__s)); if (this->size() > _GLIBCXX_REGEX_STATE_LIMIT) __throw_regex_error( regex_constants::error_space, "Number of NFA states exceeds limit. Please use shorter regex " "string, or use smaller brace expression, or make " "_GLIBCXX_REGEX_STATE_LIMIT larger."); return this->size() - 1; } // Eliminate dummy node in this NFA to make it compact. void _M_eliminate_dummy(); #ifdef _GLIBCXX_DEBUG std::ostream& _M_dot(std::ostream& __ostr) const; #endif public: _TraitsT _M_traits; }; /// Describes a sequence of one or more %_State, its current start /// and end(s). This structure contains fragments of an NFA during /// construction. template class _StateSeq { public: typedef _NFA<_TraitsT> _RegexT; public: _StateSeq(_RegexT& __nfa, _StateIdT __s) : _M_nfa(__nfa), _M_start(__s), _M_end(__s) { } _StateSeq(_RegexT& __nfa, _StateIdT __s, _StateIdT __end) : _M_nfa(__nfa), _M_start(__s), _M_end(__end) { } // Append a state on *this and change *this to the new sequence. void _M_append(_StateIdT __id) { _M_nfa[_M_end]._M_next = __id; _M_end = __id; } // Append a sequence on *this and change *this to the new sequence. void _M_append(const _StateSeq& __s) { _M_nfa[_M_end]._M_next = __s._M_start; _M_end = __s._M_end; } // Clones an entire sequence. _StateSeq _M_clone(); public: _RegexT& _M_nfa; _StateIdT _M_start; _StateIdT _M_end; }; //@} regex-detail } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #include PK!̗8/bits/regex_automaton.tccnu[// class template regex -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_automaton.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { #ifdef _GLIBCXX_DEBUG inline std::ostream& _State_base::_M_print(std::ostream& ostr) const { switch (_M_opcode) { case _S_opcode_alternative: case _S_opcode_repeat: ostr << "alt next=" << _M_next << " alt=" << _M_alt; break; case _S_opcode_subexpr_begin: ostr << "subexpr begin next=" << _M_next << " index=" << _M_subexpr; break; case _S_opcode_subexpr_end: ostr << "subexpr end next=" << _M_next << " index=" << _M_subexpr; break; case _S_opcode_backref: ostr << "backref next=" << _M_next << " index=" << _M_backref_index; break; case _S_opcode_match: ostr << "match next=" << _M_next; break; case _S_opcode_accept: ostr << "accept next=" << _M_next; break; default: ostr << "unknown next=" << _M_next; break; } return ostr; } // Prints graphviz dot commands for state. inline std::ostream& _State_base::_M_dot(std::ostream& __ostr, _StateIdT __id) const { switch (_M_opcode) { case _S_opcode_alternative: case _S_opcode_repeat: __ostr << __id << " [label=\"" << __id << "\\nALT\"];\n" << __id << " -> " << _M_next << " [label=\"next\", tailport=\"s\"];\n" << __id << " -> " << _M_alt << " [label=\"alt\", tailport=\"n\"];\n"; break; case _S_opcode_backref: __ostr << __id << " [label=\"" << __id << "\\nBACKREF " << _M_subexpr << "\"];\n" << __id << " -> " << _M_next << " [label=\"\"];\n"; break; case _S_opcode_line_begin_assertion: __ostr << __id << " [label=\"" << __id << "\\nLINE_BEGIN \"];\n" << __id << " -> " << _M_next << " [label=\"epsilon\"];\n"; break; case _S_opcode_line_end_assertion: __ostr << __id << " [label=\"" << __id << "\\nLINE_END \"];\n" << __id << " -> " << _M_next << " [label=\"epsilon\"];\n"; break; case _S_opcode_word_boundary: __ostr << __id << " [label=\"" << __id << "\\nWORD_BOUNDRY " << _M_neg << "\"];\n" << __id << " -> " << _M_next << " [label=\"epsilon\"];\n"; break; case _S_opcode_subexpr_lookahead: __ostr << __id << " [label=\"" << __id << "\\nLOOK_AHEAD\"];\n" << __id << " -> " << _M_next << " [label=\"epsilon\", tailport=\"s\"];\n" << __id << " -> " << _M_alt << " [label=\"\", tailport=\"n\"];\n"; break; case _S_opcode_subexpr_begin: __ostr << __id << " [label=\"" << __id << "\\nSBEGIN " << _M_subexpr << "\"];\n" << __id << " -> " << _M_next << " [label=\"epsilon\"];\n"; break; case _S_opcode_subexpr_end: __ostr << __id << " [label=\"" << __id << "\\nSEND " << _M_subexpr << "\"];\n" << __id << " -> " << _M_next << " [label=\"epsilon\"];\n"; break; case _S_opcode_dummy: break; case _S_opcode_match: __ostr << __id << " [label=\"" << __id << "\\nMATCH\"];\n" << __id << " -> " << _M_next << " [label=\"\"];\n"; break; case _S_opcode_accept: __ostr << __id << " [label=\"" << __id << "\\nACC\"];\n" ; break; default: _GLIBCXX_DEBUG_ASSERT(false); break; } return __ostr; } template std::ostream& _NFA<_TraitsT>::_M_dot(std::ostream& __ostr) const { __ostr << "digraph _Nfa {\n" " rankdir=LR;\n"; for (size_t __i = 0; __i < this->size(); ++__i) (*this)[__i]._M_dot(__ostr, __i); __ostr << "}\n"; return __ostr; } #endif template _StateIdT _NFA<_TraitsT>::_M_insert_backref(size_t __index) { if (this->_M_flags & regex_constants::__polynomial) __throw_regex_error(regex_constants::error_complexity, "Unexpected back-reference in polynomial mode."); // To figure out whether a backref is valid, a stack is used to store // unfinished sub-expressions. For example, when parsing // "(a(b)(c\\1(d)))" at '\\1', _M_subexpr_count is 3, indicating that 3 // sub expressions are parsed or partially parsed(in the stack), aka, // "(a..", "(b)" and "(c.."). // _M_paren_stack is {1, 3}, for incomplete "(a.." and "(c..". At this // time, "\\2" is valid, but "\\1" and "\\3" are not. if (__index >= _M_subexpr_count) __throw_regex_error( regex_constants::error_backref, "Back-reference index exceeds current sub-expression count."); for (auto __it : this->_M_paren_stack) if (__index == __it) __throw_regex_error( regex_constants::error_backref, "Back-reference referred to an opened sub-expression."); this->_M_has_backref = true; _StateT __tmp(_S_opcode_backref); __tmp._M_backref_index = __index; return _M_insert_state(std::move(__tmp)); } template void _NFA<_TraitsT>::_M_eliminate_dummy() { for (auto& __it : *this) { while (__it._M_next >= 0 && (*this)[__it._M_next]._M_opcode() == _S_opcode_dummy) __it._M_next = (*this)[__it._M_next]._M_next; if (__it._M_has_alt()) while (__it._M_alt >= 0 && (*this)[__it._M_alt]._M_opcode() == _S_opcode_dummy) __it._M_alt = (*this)[__it._M_alt]._M_next; } } // Just apply DFS on the sequence and re-link their links. template _StateSeq<_TraitsT> _StateSeq<_TraitsT>::_M_clone() { std::map<_StateIdT, _StateIdT> __m; std::stack<_StateIdT> __stack; __stack.push(_M_start); while (!__stack.empty()) { auto __u = __stack.top(); __stack.pop(); auto __dup = _M_nfa[__u]; // _M_insert_state() never return -1 auto __id = _M_nfa._M_insert_state(std::move(__dup)); __m[__u] = __id; if (__dup._M_has_alt()) if (__dup._M_alt != _S_invalid_state_id && __m.count(__dup._M_alt) == 0) __stack.push(__dup._M_alt); if (__u == _M_end) continue; if (__dup._M_next != _S_invalid_state_id && __m.count(__dup._M_next) == 0) __stack.push(__dup._M_next); } for (auto __it : __m) { auto __v = __it.second; auto& __ref = _M_nfa[__v]; if (__ref._M_next != _S_invalid_state_id) { __glibcxx_assert(__m.count(__ref._M_next) > 0); __ref._M_next = __m[__ref._M_next]; } if (__ref._M_has_alt()) if (__ref._M_alt != _S_invalid_state_id) { __glibcxx_assert(__m.count(__ref._M_alt) > 0); __ref._M_alt = __m[__ref._M_alt]; } } return _StateSeq(_M_nfa, __m[_M_start], __m[_M_end]); } } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace PK!XFF8/bits/regex_compiler.hnu[// class template regex -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_compiler.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CXX11 template class regex_traits; _GLIBCXX_END_NAMESPACE_CXX11 namespace __detail { /** * @addtogroup regex-detail * @{ */ template struct _BracketMatcher; /** * @brief Builds an NFA from an input iterator range. * * The %_TraitsT type should fulfill requirements [28.3]. */ template class _Compiler { public: typedef typename _TraitsT::char_type _CharT; typedef const _CharT* _IterT; typedef _NFA<_TraitsT> _RegexT; typedef regex_constants::syntax_option_type _FlagT; _Compiler(_IterT __b, _IterT __e, const typename _TraitsT::locale_type& __traits, _FlagT __flags); shared_ptr _M_get_nfa() { return std::move(_M_nfa); } private: typedef _Scanner<_CharT> _ScannerT; typedef typename _TraitsT::string_type _StringT; typedef typename _ScannerT::_TokenT _TokenT; typedef _StateSeq<_TraitsT> _StateSeqT; typedef std::stack<_StateSeqT> _StackT; typedef std::ctype<_CharT> _CtypeT; // accepts a specific token or returns false. bool _M_match_token(_TokenT __token); void _M_disjunction(); void _M_alternative(); bool _M_term(); bool _M_assertion(); bool _M_quantifier(); bool _M_atom(); bool _M_bracket_expression(); template void _M_insert_any_matcher_ecma(); template void _M_insert_any_matcher_posix(); template void _M_insert_char_matcher(); template void _M_insert_character_class_matcher(); template void _M_insert_bracket_matcher(bool __neg); // Cache of the last atom seen in a bracketed range expression. struct _BracketState { enum class _Type : char { _None, _Char, _Class } _M_type = _Type::_None; _CharT _M_char; void set(_CharT __c) noexcept { _M_type = _Type::_Char; _M_char = __c; } _GLIBCXX_NODISCARD _CharT get() const noexcept { return _M_char; } void reset(_Type __t = _Type::_None) noexcept { _M_type = __t; } explicit operator bool() const noexcept { return _M_type != _Type::_None; } // Previous token was a single character. _GLIBCXX_NODISCARD bool _M_is_char() const noexcept { return _M_type == _Type::_Char; } // Previous token was a character class, equivalent class, // collating symbol etc. _GLIBCXX_NODISCARD bool _M_is_class() const noexcept { return _M_type == _Type::_Class; } }; template using _BracketMatcher = std::__detail::_BracketMatcher<_TraitsT, __icase, __collate>; // Returns true if successfully parsed one term and should continue // compiling a bracket expression. // Returns false if the compiler should move on. template bool _M_expression_term(_BracketState& __last_char, _BracketMatcher<__icase, __collate>& __matcher); int _M_cur_int_value(int __radix); bool _M_try_char(); _StateSeqT _M_pop() { auto ret = _M_stack.top(); _M_stack.pop(); return ret; } _FlagT _M_flags; _ScannerT _M_scanner; shared_ptr<_RegexT> _M_nfa; _StringT _M_value; _StackT _M_stack; const _TraitsT& _M_traits; const _CtypeT& _M_ctype; }; template struct __has_contiguous_iter : std::false_type { }; template struct __has_contiguous_iter> : std::true_type { }; template struct __has_contiguous_iter> : std::true_type { }; template struct __is_contiguous_normal_iter : std::false_type { }; template struct __is_contiguous_normal_iter<_CharT*> : std::true_type { }; template struct __is_contiguous_normal_iter<__gnu_cxx::__normal_iterator<_Tp, _Cont>> : __has_contiguous_iter<_Cont>::type { }; template using __enable_if_contiguous_normal_iter = typename enable_if< __is_contiguous_normal_iter<_Iter>::value, std::shared_ptr> >::type; template using __disable_if_contiguous_normal_iter = typename enable_if< !__is_contiguous_normal_iter<_Iter>::value, std::shared_ptr> >::type; template inline __enable_if_contiguous_normal_iter<_FwdIter, _TraitsT> __compile_nfa(_FwdIter __first, _FwdIter __last, const typename _TraitsT::locale_type& __loc, regex_constants::syntax_option_type __flags) { size_t __len = __last - __first; const auto* __cfirst = __len ? std::__addressof(*__first) : nullptr; using _Cmplr = _Compiler<_TraitsT>; return _Cmplr(__cfirst, __cfirst + __len, __loc, __flags)._M_get_nfa(); } template inline __disable_if_contiguous_normal_iter<_FwdIter, _TraitsT> __compile_nfa(_FwdIter __first, _FwdIter __last, const typename _TraitsT::locale_type& __loc, regex_constants::syntax_option_type __flags) { const basic_string __str(__first, __last); return __compile_nfa<_TraitsT>(__str.data(), __str.data() + __str.size(), __loc, __flags); } // [28.13.14] template class _RegexTranslatorBase { public: typedef typename _TraitsT::char_type _CharT; typedef typename _TraitsT::string_type _StringT; typedef _StringT _StrTransT; explicit _RegexTranslatorBase(const _TraitsT& __traits) : _M_traits(__traits) { } _CharT _M_translate(_CharT __ch) const { if (__icase) return _M_traits.translate_nocase(__ch); else if (__collate) return _M_traits.translate(__ch); else return __ch; } _StrTransT _M_transform(_CharT __ch) const { _StrTransT __str(1, __ch); return _M_traits.transform(__str.begin(), __str.end()); } // See LWG 523. It's not efficiently implementable when _TraitsT is not // std::regex_traits<>, and __collate is true. See specializations for // implementations of other cases. bool _M_match_range(const _StrTransT& __first, const _StrTransT& __last, const _StrTransT& __s) const { return __first <= __s && __s <= __last; } protected: bool _M_in_range_icase(_CharT __first, _CharT __last, _CharT __ch) const { typedef std::ctype<_CharT> __ctype_type; const auto& __fctyp = use_facet<__ctype_type>(this->_M_traits.getloc()); auto __lower = __fctyp.tolower(__ch); auto __upper = __fctyp.toupper(__ch); return (__first <= __lower && __lower <= __last) || (__first <= __upper && __upper <= __last); } const _TraitsT& _M_traits; }; template class _RegexTranslator : public _RegexTranslatorBase<_TraitsT, __icase, __collate> { public: typedef _RegexTranslatorBase<_TraitsT, __icase, __collate> _Base; using _Base::_Base; }; template class _RegexTranslator<_TraitsT, __icase, false> : public _RegexTranslatorBase<_TraitsT, __icase, false> { public: typedef _RegexTranslatorBase<_TraitsT, __icase, false> _Base; typedef typename _Base::_CharT _CharT; typedef _CharT _StrTransT; using _Base::_Base; _StrTransT _M_transform(_CharT __ch) const { return __ch; } bool _M_match_range(_CharT __first, _CharT __last, _CharT __ch) const { if (!__icase) return __first <= __ch && __ch <= __last; return this->_M_in_range_icase(__first, __last, __ch); } }; template class _RegexTranslator, true, true> : public _RegexTranslatorBase, true, true> { public: typedef _RegexTranslatorBase, true, true> _Base; typedef typename _Base::_CharT _CharT; typedef typename _Base::_StrTransT _StrTransT; using _Base::_Base; bool _M_match_range(const _StrTransT& __first, const _StrTransT& __last, const _StrTransT& __str) const { __glibcxx_assert(__first.size() == 1); __glibcxx_assert(__last.size() == 1); __glibcxx_assert(__str.size() == 1); return this->_M_in_range_icase(__first[0], __last[0], __str[0]); } }; template class _RegexTranslator<_TraitsT, false, false> { public: typedef typename _TraitsT::char_type _CharT; typedef _CharT _StrTransT; explicit _RegexTranslator(const _TraitsT&) { } _CharT _M_translate(_CharT __ch) const { return __ch; } _StrTransT _M_transform(_CharT __ch) const { return __ch; } bool _M_match_range(_CharT __first, _CharT __last, _CharT __ch) const { return __first <= __ch && __ch <= __last; } }; template struct _AnyMatcher; template struct _AnyMatcher<_TraitsT, false, __icase, __collate> { typedef _RegexTranslator<_TraitsT, __icase, __collate> _TransT; typedef typename _TransT::_CharT _CharT; explicit _AnyMatcher(const _TraitsT& __traits) : _M_translator(__traits) { } bool operator()(_CharT __ch) const { static auto __nul = _M_translator._M_translate('\0'); return _M_translator._M_translate(__ch) != __nul; } _TransT _M_translator; }; template struct _AnyMatcher<_TraitsT, true, __icase, __collate> { typedef _RegexTranslator<_TraitsT, __icase, __collate> _TransT; typedef typename _TransT::_CharT _CharT; explicit _AnyMatcher(const _TraitsT& __traits) : _M_translator(__traits) { } bool operator()(_CharT __ch) const { return _M_apply(__ch, typename is_same<_CharT, char>::type()); } bool _M_apply(_CharT __ch, true_type) const { auto __c = _M_translator._M_translate(__ch); auto __n = _M_translator._M_translate('\n'); auto __r = _M_translator._M_translate('\r'); return __c != __n && __c != __r; } bool _M_apply(_CharT __ch, false_type) const { auto __c = _M_translator._M_translate(__ch); auto __n = _M_translator._M_translate('\n'); auto __r = _M_translator._M_translate('\r'); auto __u2028 = _M_translator._M_translate(u'\u2028'); auto __u2029 = _M_translator._M_translate(u'\u2029'); return __c != __n && __c != __r && __c != __u2028 && __c != __u2029; } _TransT _M_translator; }; template struct _CharMatcher { typedef _RegexTranslator<_TraitsT, __icase, __collate> _TransT; typedef typename _TransT::_CharT _CharT; _CharMatcher(_CharT __ch, const _TraitsT& __traits) : _M_translator(__traits), _M_ch(_M_translator._M_translate(__ch)) { } bool operator()(_CharT __ch) const { return _M_ch == _M_translator._M_translate(__ch); } _TransT _M_translator; _CharT _M_ch; }; /// Matches a character range (bracket expression) template struct _BracketMatcher { public: typedef _RegexTranslator<_TraitsT, __icase, __collate> _TransT; typedef typename _TransT::_CharT _CharT; typedef typename _TransT::_StrTransT _StrTransT; typedef typename _TraitsT::string_type _StringT; typedef typename _TraitsT::char_class_type _CharClassT; public: _BracketMatcher(bool __is_non_matching, const _TraitsT& __traits) : _M_class_set(0), _M_translator(__traits), _M_traits(__traits), _M_is_non_matching(__is_non_matching) { } bool operator()(_CharT __ch) const { _GLIBCXX_DEBUG_ASSERT(_M_is_ready); return _M_apply(__ch, _UseCache()); } void _M_add_char(_CharT __c) { _M_char_set.push_back(_M_translator._M_translate(__c)); _GLIBCXX_DEBUG_ONLY(_M_is_ready = false); } _StringT _M_add_collate_element(const _StringT& __s) { auto __st = _M_traits.lookup_collatename(__s.data(), __s.data() + __s.size()); if (__st.empty()) __throw_regex_error(regex_constants::error_collate, "Invalid collate element."); _M_char_set.push_back(_M_translator._M_translate(__st[0])); _GLIBCXX_DEBUG_ONLY(_M_is_ready = false); return __st; } void _M_add_equivalence_class(const _StringT& __s) { auto __st = _M_traits.lookup_collatename(__s.data(), __s.data() + __s.size()); if (__st.empty()) __throw_regex_error(regex_constants::error_collate, "Invalid equivalence class."); __st = _M_traits.transform_primary(__st.data(), __st.data() + __st.size()); _M_equiv_set.push_back(__st); _GLIBCXX_DEBUG_ONLY(_M_is_ready = false); } // __neg should be true for \D, \S and \W only. void _M_add_character_class(const _StringT& __s, bool __neg) { auto __mask = _M_traits.lookup_classname(__s.data(), __s.data() + __s.size(), __icase); if (__mask == 0) __throw_regex_error(regex_constants::error_collate, "Invalid character class."); if (!__neg) _M_class_set |= __mask; else _M_neg_class_set.push_back(__mask); _GLIBCXX_DEBUG_ONLY(_M_is_ready = false); } void _M_make_range(_CharT __l, _CharT __r) { if (__l > __r) __throw_regex_error(regex_constants::error_range, "Invalid range in bracket expression."); _M_range_set.push_back(make_pair(_M_translator._M_transform(__l), _M_translator._M_transform(__r))); _GLIBCXX_DEBUG_ONLY(_M_is_ready = false); } void _M_ready() { std::sort(_M_char_set.begin(), _M_char_set.end()); auto __end = std::unique(_M_char_set.begin(), _M_char_set.end()); _M_char_set.erase(__end, _M_char_set.end()); _M_make_cache(_UseCache()); _GLIBCXX_DEBUG_ONLY(_M_is_ready = true); } private: // Currently we only use the cache for char typedef typename std::is_same<_CharT, char>::type _UseCache; static constexpr size_t _S_cache_size() { return 1ul << (sizeof(_CharT) * __CHAR_BIT__ * int(_UseCache::value)); } struct _Dummy { }; typedef typename std::conditional<_UseCache::value, std::bitset<_S_cache_size()>, _Dummy>::type _CacheT; typedef typename std::make_unsigned<_CharT>::type _UnsignedCharT; bool _M_apply(_CharT __ch, false_type) const; bool _M_apply(_CharT __ch, true_type) const { return _M_cache[static_cast<_UnsignedCharT>(__ch)]; } void _M_make_cache(true_type) { for (unsigned __i = 0; __i < _M_cache.size(); __i++) _M_cache[__i] = _M_apply(static_cast<_CharT>(__i), false_type()); } void _M_make_cache(false_type) { } private: std::vector<_CharT> _M_char_set; std::vector<_StringT> _M_equiv_set; std::vector> _M_range_set; std::vector<_CharClassT> _M_neg_class_set; _CharClassT _M_class_set; _TransT _M_translator; const _TraitsT& _M_traits; bool _M_is_non_matching; _CacheT _M_cache; #ifdef _GLIBCXX_DEBUG bool _M_is_ready = false; #endif }; //@} regex-detail } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #include PK!ۓ$XKXK8/bits/regex_compiler.tccnu[// class template regex -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_compiler.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ // FIXME make comments doxygen format. /* // This compiler refers to "Regular Expression Matching Can Be Simple And Fast" // (http://swtch.com/~rsc/regexp/regexp1.html), // but doesn't strictly follow it. // // When compiling, states are *chained* instead of tree- or graph-constructed. // It's more like structured programs: there's if statement and loop statement. // // For alternative structure (say "a|b"), aka "if statement", two branches // should be constructed. However, these two shall merge to an "end_tag" at // the end of this operator: // // branch1 // / \ // => begin_tag end_tag => // \ / // branch2 // // This is the difference between this implementation and that in Russ's // article. // // That's why we introduced dummy node here ------ "end_tag" is a dummy node. // All dummy nodes will be eliminated at the end of compilation. */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { template _Compiler<_TraitsT>:: _Compiler(_IterT __b, _IterT __e, const typename _TraitsT::locale_type& __loc, _FlagT __flags) : _M_flags((__flags & (regex_constants::ECMAScript | regex_constants::basic | regex_constants::extended | regex_constants::grep | regex_constants::egrep | regex_constants::awk)) ? __flags : __flags | regex_constants::ECMAScript), _M_scanner(__b, __e, _M_flags, __loc), _M_nfa(make_shared<_RegexT>(__loc, _M_flags)), _M_traits(_M_nfa->_M_traits), _M_ctype(std::use_facet<_CtypeT>(__loc)) { _StateSeqT __r(*_M_nfa, _M_nfa->_M_start()); __r._M_append(_M_nfa->_M_insert_subexpr_begin()); this->_M_disjunction(); if (!_M_match_token(_ScannerT::_S_token_eof)) __throw_regex_error(regex_constants::error_paren); __r._M_append(_M_pop()); __glibcxx_assert(_M_stack.empty()); __r._M_append(_M_nfa->_M_insert_subexpr_end()); __r._M_append(_M_nfa->_M_insert_accept()); _M_nfa->_M_eliminate_dummy(); } template void _Compiler<_TraitsT>:: _M_disjunction() { this->_M_alternative(); while (_M_match_token(_ScannerT::_S_token_or)) { _StateSeqT __alt1 = _M_pop(); this->_M_alternative(); _StateSeqT __alt2 = _M_pop(); auto __end = _M_nfa->_M_insert_dummy(); __alt1._M_append(__end); __alt2._M_append(__end); // __alt2 is state._M_next, __alt1 is state._M_alt. The executor // executes _M_alt before _M_next, as well as executing left // alternative before right one. _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_alt( __alt2._M_start, __alt1._M_start, false), __end)); } } template void _Compiler<_TraitsT>:: _M_alternative() { if (this->_M_term()) { _StateSeqT __re = _M_pop(); this->_M_alternative(); __re._M_append(_M_pop()); _M_stack.push(__re); } else _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_dummy())); } template bool _Compiler<_TraitsT>:: _M_term() { if (this->_M_assertion()) return true; if (this->_M_atom()) { while (this->_M_quantifier()) ; return true; } return false; } template bool _Compiler<_TraitsT>:: _M_assertion() { if (_M_match_token(_ScannerT::_S_token_line_begin)) _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_line_begin())); else if (_M_match_token(_ScannerT::_S_token_line_end)) _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_line_end())); else if (_M_match_token(_ScannerT::_S_token_word_bound)) // _M_value[0] == 'n' means it's negative, say "not word boundary". _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa-> _M_insert_word_bound(_M_value[0] == 'n'))); else if (_M_match_token(_ScannerT::_S_token_subexpr_lookahead_begin)) { auto __neg = _M_value[0] == 'n'; this->_M_disjunction(); if (!_M_match_token(_ScannerT::_S_token_subexpr_end)) __throw_regex_error(regex_constants::error_paren, "Parenthesis is not closed."); auto __tmp = _M_pop(); __tmp._M_append(_M_nfa->_M_insert_accept()); _M_stack.push( _StateSeqT( *_M_nfa, _M_nfa->_M_insert_lookahead(__tmp._M_start, __neg))); } else return false; return true; } template bool _Compiler<_TraitsT>:: _M_quantifier() { bool __neg = (_M_flags & regex_constants::ECMAScript); auto __init = [this, &__neg]() { if (_M_stack.empty()) __throw_regex_error(regex_constants::error_badrepeat, "Nothing to repeat before a quantifier."); __neg = __neg && _M_match_token(_ScannerT::_S_token_opt); }; if (_M_match_token(_ScannerT::_S_token_closure0)) { __init(); auto __e = _M_pop(); _StateSeqT __r(*_M_nfa, _M_nfa->_M_insert_repeat(_S_invalid_state_id, __e._M_start, __neg)); __e._M_append(__r); _M_stack.push(__r); } else if (_M_match_token(_ScannerT::_S_token_closure1)) { __init(); auto __e = _M_pop(); __e._M_append(_M_nfa->_M_insert_repeat(_S_invalid_state_id, __e._M_start, __neg)); _M_stack.push(__e); } else if (_M_match_token(_ScannerT::_S_token_opt)) { __init(); auto __e = _M_pop(); auto __end = _M_nfa->_M_insert_dummy(); _StateSeqT __r(*_M_nfa, _M_nfa->_M_insert_repeat(_S_invalid_state_id, __e._M_start, __neg)); __e._M_append(__end); __r._M_append(__end); _M_stack.push(__r); } else if (_M_match_token(_ScannerT::_S_token_interval_begin)) { if (_M_stack.empty()) __throw_regex_error(regex_constants::error_badrepeat, "Nothing to repeat before a quantifier."); if (!_M_match_token(_ScannerT::_S_token_dup_count)) __throw_regex_error(regex_constants::error_badbrace, "Unexpected token in brace expression."); _StateSeqT __r(_M_pop()); _StateSeqT __e(*_M_nfa, _M_nfa->_M_insert_dummy()); long __min_rep = _M_cur_int_value(10); bool __infi = false; long __n; // {3 if (_M_match_token(_ScannerT::_S_token_comma)) if (_M_match_token(_ScannerT::_S_token_dup_count)) // {3,7} __n = _M_cur_int_value(10) - __min_rep; else __infi = true; else __n = 0; if (!_M_match_token(_ScannerT::_S_token_interval_end)) __throw_regex_error(regex_constants::error_brace, "Unexpected end of brace expression."); __neg = __neg && _M_match_token(_ScannerT::_S_token_opt); for (long __i = 0; __i < __min_rep; ++__i) __e._M_append(__r._M_clone()); if (__infi) { auto __tmp = __r._M_clone(); _StateSeqT __s(*_M_nfa, _M_nfa->_M_insert_repeat(_S_invalid_state_id, __tmp._M_start, __neg)); __tmp._M_append(__s); __e._M_append(__s); } else { if (__n < 0) __throw_regex_error(regex_constants::error_badbrace, "Invalid range in brace expression."); auto __end = _M_nfa->_M_insert_dummy(); // _M_alt is the "match more" branch, and _M_next is the // "match less" one. Switch _M_alt and _M_next of all created // nodes. This is a hack but IMO works well. std::stack<_StateIdT> __stack; for (long __i = 0; __i < __n; ++__i) { auto __tmp = __r._M_clone(); auto __alt = _M_nfa->_M_insert_repeat(__tmp._M_start, __end, __neg); __stack.push(__alt); __e._M_append(_StateSeqT(*_M_nfa, __alt, __tmp._M_end)); } __e._M_append(__end); while (!__stack.empty()) { auto& __tmp = (*_M_nfa)[__stack.top()]; __stack.pop(); std::swap(__tmp._M_next, __tmp._M_alt); } } _M_stack.push(__e); } else return false; return true; } #define __INSERT_REGEX_MATCHER(__func, ...)\ do {\ if (!(_M_flags & regex_constants::icase))\ if (!(_M_flags & regex_constants::collate))\ __func(__VA_ARGS__);\ else\ __func(__VA_ARGS__);\ else\ if (!(_M_flags & regex_constants::collate))\ __func(__VA_ARGS__);\ else\ __func(__VA_ARGS__);\ } while (false) template bool _Compiler<_TraitsT>:: _M_atom() { if (_M_match_token(_ScannerT::_S_token_anychar)) { if (!(_M_flags & regex_constants::ECMAScript)) __INSERT_REGEX_MATCHER(_M_insert_any_matcher_posix); else __INSERT_REGEX_MATCHER(_M_insert_any_matcher_ecma); } else if (_M_try_char()) __INSERT_REGEX_MATCHER(_M_insert_char_matcher); else if (_M_match_token(_ScannerT::_S_token_backref)) _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa-> _M_insert_backref(_M_cur_int_value(10)))); else if (_M_match_token(_ScannerT::_S_token_quoted_class)) __INSERT_REGEX_MATCHER(_M_insert_character_class_matcher); else if (_M_match_token(_ScannerT::_S_token_subexpr_no_group_begin)) { _StateSeqT __r(*_M_nfa, _M_nfa->_M_insert_dummy()); this->_M_disjunction(); if (!_M_match_token(_ScannerT::_S_token_subexpr_end)) __throw_regex_error(regex_constants::error_paren, "Parenthesis is not closed."); __r._M_append(_M_pop()); _M_stack.push(__r); } else if (_M_match_token(_ScannerT::_S_token_subexpr_begin)) { _StateSeqT __r(*_M_nfa, _M_nfa->_M_insert_subexpr_begin()); this->_M_disjunction(); if (!_M_match_token(_ScannerT::_S_token_subexpr_end)) __throw_regex_error(regex_constants::error_paren, "Parenthesis is not closed."); __r._M_append(_M_pop()); __r._M_append(_M_nfa->_M_insert_subexpr_end()); _M_stack.push(__r); } else if (!_M_bracket_expression()) return false; return true; } template bool _Compiler<_TraitsT>:: _M_bracket_expression() { bool __neg = _M_match_token(_ScannerT::_S_token_bracket_neg_begin); if (!(__neg || _M_match_token(_ScannerT::_S_token_bracket_begin))) return false; __INSERT_REGEX_MATCHER(_M_insert_bracket_matcher, __neg); return true; } #undef __INSERT_REGEX_MATCHER template template void _Compiler<_TraitsT>:: _M_insert_any_matcher_ecma() { _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_matcher (_AnyMatcher<_TraitsT, true, __icase, __collate> (_M_traits)))); } template template void _Compiler<_TraitsT>:: _M_insert_any_matcher_posix() { _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_matcher (_AnyMatcher<_TraitsT, false, __icase, __collate> (_M_traits)))); } template template void _Compiler<_TraitsT>:: _M_insert_char_matcher() { _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_matcher (_CharMatcher<_TraitsT, __icase, __collate> (_M_value[0], _M_traits)))); } template template void _Compiler<_TraitsT>:: _M_insert_character_class_matcher() { __glibcxx_assert(_M_value.size() == 1); _BracketMatcher<__icase, __collate> __matcher (_M_ctype.is(_CtypeT::upper, _M_value[0]), _M_traits); __matcher._M_add_character_class(_M_value, false); __matcher._M_ready(); _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_matcher(std::move(__matcher)))); } template template void _Compiler<_TraitsT>:: _M_insert_bracket_matcher(bool __neg) { _BracketMatcher<__icase, __collate> __matcher(__neg, _M_traits); _BracketState __last_char; if (_M_try_char()) __last_char.set(_M_value[0]); else if (_M_match_token(_ScannerT::_S_token_bracket_dash)) // Dash as first character is a normal character. __last_char.set('-'); while (_M_expression_term(__last_char, __matcher)) ; if (__last_char._M_is_char()) __matcher._M_add_char(__last_char.get()); __matcher._M_ready(); _M_stack.push(_StateSeqT( *_M_nfa, _M_nfa->_M_insert_matcher(std::move(__matcher)))); } template template bool _Compiler<_TraitsT>:: _M_expression_term(_BracketState& __last_char, _BracketMatcher<__icase, __collate>& __matcher) { if (_M_match_token(_ScannerT::_S_token_bracket_end)) return false; // Add any previously cached char into the matcher and update cache. const auto __push_char = [&](_CharT __ch) { if (__last_char._M_is_char()) __matcher._M_add_char(__last_char.get()); __last_char.set(__ch); }; // Add any previously cached char into the matcher and update cache. const auto __push_class = [&] { if (__last_char._M_is_char()) __matcher._M_add_char(__last_char.get()); // We don't cache anything here, just record that the last thing // processed was a character class (or similar). __last_char.reset(_BracketState::_Type::_Class); }; if (_M_match_token(_ScannerT::_S_token_collsymbol)) { auto __symbol = __matcher._M_add_collate_element(_M_value); if (__symbol.size() == 1) __push_char(__symbol[0]); else __push_class(); } else if (_M_match_token(_ScannerT::_S_token_equiv_class_name)) { __push_class(); __matcher._M_add_equivalence_class(_M_value); } else if (_M_match_token(_ScannerT::_S_token_char_class_name)) { __push_class(); __matcher._M_add_character_class(_M_value, false); } else if (_M_try_char()) __push_char(_M_value[0]); // POSIX doesn't allow '-' as a start-range char (say [a-z--0]), // except when the '-' is the first or last character in the bracket // expression ([--0]). ECMAScript treats all '-' after a range as a // normal character. Also see above, where _M_expression_term gets called. // // As a result, POSIX rejects [-----], but ECMAScript doesn't. // Boost (1.57.0) always uses POSIX style even in its ECMAScript syntax. // Clang (3.5) always uses ECMAScript style even in its POSIX syntax. // // It turns out that no one reads BNFs ;) else if (_M_match_token(_ScannerT::_S_token_bracket_dash)) { if (_M_match_token(_ScannerT::_S_token_bracket_end)) { // For "-]" the dash is a literal character. __push_char('-'); return false; } else if (__last_char._M_is_class()) { // "\\w-" is invalid, start of range must be a single char. __throw_regex_error(regex_constants::error_range, "Invalid start of range in bracket expression."); } else if (__last_char._M_is_char()) { if (_M_try_char()) { // "x-y" __matcher._M_make_range(__last_char.get(), _M_value[0]); __last_char.reset(); } else if (_M_match_token(_ScannerT::_S_token_bracket_dash)) { // "x--" __matcher._M_make_range(__last_char.get(), '-'); __last_char.reset(); } else __throw_regex_error(regex_constants::error_range, "Invalid end of range in bracket expression."); } else if (_M_flags & regex_constants::ECMAScript) { // A dash that is not part of an existing range. Might be the // start of a new range, or might just be a literal '-' char. // Only ECMAScript allows that in the middle of a bracket expr. __push_char('-'); } else __throw_regex_error(regex_constants::error_range, "Invalid dash in bracket expression."); } else if (_M_match_token(_ScannerT::_S_token_quoted_class)) { __push_class(); __matcher._M_add_character_class(_M_value, _M_ctype.is(_CtypeT::upper, _M_value[0])); } else __throw_regex_error(regex_constants::error_brack, "Unexpected character in bracket expression."); return true; } template bool _Compiler<_TraitsT>:: _M_try_char() { bool __is_char = false; if (_M_match_token(_ScannerT::_S_token_oct_num)) { __is_char = true; _M_value.assign(1, _M_cur_int_value(8)); } else if (_M_match_token(_ScannerT::_S_token_hex_num)) { __is_char = true; _M_value.assign(1, _M_cur_int_value(16)); } else if (_M_match_token(_ScannerT::_S_token_ord_char)) __is_char = true; return __is_char; } template bool _Compiler<_TraitsT>:: _M_match_token(_TokenT __token) { if (__token == _M_scanner._M_get_token()) { _M_value = _M_scanner._M_get_value(); _M_scanner._M_advance(); return true; } return false; } template int _Compiler<_TraitsT>:: _M_cur_int_value(int __radix) { long __v = 0; for (typename _StringT::size_type __i = 0; __i < _M_value.length(); ++__i) __v =__v * __radix + _M_traits.value(_M_value[__i], __radix); return __v; } template bool _BracketMatcher<_TraitsT, __icase, __collate>:: _M_apply(_CharT __ch, false_type) const { return [this, __ch] { if (std::binary_search(_M_char_set.begin(), _M_char_set.end(), _M_translator._M_translate(__ch))) return true; auto __s = _M_translator._M_transform(__ch); for (auto& __it : _M_range_set) if (_M_translator._M_match_range(__it.first, __it.second, __s)) return true; if (_M_traits.isctype(__ch, _M_class_set)) return true; if (std::find(_M_equiv_set.begin(), _M_equiv_set.end(), _M_traits.transform_primary(&__ch, &__ch+1)) != _M_equiv_set.end()) return true; for (auto& __it : _M_neg_class_set) if (!_M_traits.isctype(__ch, __it)) return true; return false; }() ^ _M_is_non_matching; } } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace PK!|t9t98/bits/regex_constants.hnu[// class template regex -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_constants.h * @brief Constant definitions for the std regex library. * * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup regex Regular Expressions * * A facility for performing regular expression pattern matching. * @{ */ /** * @namespace std::regex_constants * @brief ISO C++-0x entities sub namespace for regex. */ namespace regex_constants { /** * @name 5.1 Regular Expression Syntax Options */ //@{ enum __syntax_option { _S_icase, _S_nosubs, _S_optimize, _S_collate, _S_ECMAScript, _S_basic, _S_extended, _S_awk, _S_grep, _S_egrep, _S_polynomial, _S_syntax_last }; /** * @brief This is a bitmask type indicating how to interpret the regex. * * The @c syntax_option_type is implementation defined but it is valid to * perform bitwise operations on these values and expect the right thing to * happen. * * A valid value of type syntax_option_type shall have exactly one of the * elements @c ECMAScript, @c basic, @c extended, @c awk, @c grep, @c egrep * %set. */ enum syntax_option_type : unsigned int { }; /** * Specifies that the matching of regular expressions against a character * sequence shall be performed without regard to case. */ _GLIBCXX17_INLINE constexpr syntax_option_type icase = static_cast(1 << _S_icase); /** * Specifies that when a regular expression is matched against a character * container sequence, no sub-expression matches are to be stored in the * supplied match_results structure. */ _GLIBCXX17_INLINE constexpr syntax_option_type nosubs = static_cast(1 << _S_nosubs); /** * Specifies that the regular expression engine should pay more attention to * the speed with which regular expressions are matched, and less to the * speed with which regular expression objects are constructed. Otherwise * it has no detectable effect on the program output. */ _GLIBCXX17_INLINE constexpr syntax_option_type optimize = static_cast(1 << _S_optimize); /** * Specifies that character ranges of the form [a-b] should be locale * sensitive. */ _GLIBCXX17_INLINE constexpr syntax_option_type collate = static_cast(1 << _S_collate); /** * Specifies that the grammar recognized by the regular expression engine is * that used by ECMAScript in ECMA-262 [Ecma International, ECMAScript * Language Specification, Standard Ecma-262, third edition, 1999], as * modified in section [28.13]. This grammar is similar to that defined * in the PERL scripting language but extended with elements found in the * POSIX regular expression grammar. */ _GLIBCXX17_INLINE constexpr syntax_option_type ECMAScript = static_cast(1 << _S_ECMAScript); /** * Specifies that the grammar recognized by the regular expression engine is * that used by POSIX basic regular expressions in IEEE Std 1003.1-2001, * Portable Operating System Interface (POSIX), Base Definitions and * Headers, Section 9, Regular Expressions [IEEE, Information Technology -- * Portable Operating System Interface (POSIX), IEEE Standard 1003.1-2001]. */ _GLIBCXX17_INLINE constexpr syntax_option_type basic = static_cast(1 << _S_basic); /** * Specifies that the grammar recognized by the regular expression engine is * that used by POSIX extended regular expressions in IEEE Std 1003.1-2001, * Portable Operating System Interface (POSIX), Base Definitions and * Headers, Section 9, Regular Expressions. */ _GLIBCXX17_INLINE constexpr syntax_option_type extended = static_cast(1 << _S_extended); /** * Specifies that the grammar recognized by the regular expression engine is * that used by POSIX utility awk in IEEE Std 1003.1-2001. This option is * identical to syntax_option_type extended, except that C-style escape * sequences are supported. These sequences are: * \\\\, \\a, \\b, \\f, \\n, \\r, \\t , \\v, \\&apos,, &apos,, * and \\ddd (where ddd is one, two, or three octal digits). */ _GLIBCXX17_INLINE constexpr syntax_option_type awk = static_cast(1 << _S_awk); /** * Specifies that the grammar recognized by the regular expression engine is * that used by POSIX utility grep in IEEE Std 1003.1-2001. This option is * identical to syntax_option_type basic, except that newlines are treated * as whitespace. */ _GLIBCXX17_INLINE constexpr syntax_option_type grep = static_cast(1 << _S_grep); /** * Specifies that the grammar recognized by the regular expression engine is * that used by POSIX utility grep when given the -E option in * IEEE Std 1003.1-2001. This option is identical to syntax_option_type * extended, except that newlines are treated as whitespace. */ _GLIBCXX17_INLINE constexpr syntax_option_type egrep = static_cast(1 << _S_egrep); /** * Extension: Ensure both space complexity of compiled regex and * time complexity execution are not exponential. * If specified in a regex with back-references, the exception * regex_constants::error_complexity will be thrown. */ _GLIBCXX17_INLINE constexpr syntax_option_type __polynomial = static_cast(1 << _S_polynomial); constexpr inline syntax_option_type operator&(syntax_option_type __a, syntax_option_type __b) { return (syntax_option_type)(static_cast(__a) & static_cast(__b)); } constexpr inline syntax_option_type operator|(syntax_option_type __a, syntax_option_type __b) { return (syntax_option_type)(static_cast(__a) | static_cast(__b)); } constexpr inline syntax_option_type operator^(syntax_option_type __a, syntax_option_type __b) { return (syntax_option_type)(static_cast(__a) ^ static_cast(__b)); } constexpr inline syntax_option_type operator~(syntax_option_type __a) { return (syntax_option_type)(~static_cast(__a)); } inline syntax_option_type& operator&=(syntax_option_type& __a, syntax_option_type __b) { return __a = __a & __b; } inline syntax_option_type& operator|=(syntax_option_type& __a, syntax_option_type __b) { return __a = __a | __b; } inline syntax_option_type& operator^=(syntax_option_type& __a, syntax_option_type __b) { return __a = __a ^ __b; } //@} /** * @name 5.2 Matching Rules * * Matching a regular expression against a sequence of characters [first, * last) proceeds according to the rules of the grammar specified for the * regular expression object, modified according to the effects listed * below for any bitmask elements set. * */ //@{ enum __match_flag { _S_not_bol, _S_not_eol, _S_not_bow, _S_not_eow, _S_any, _S_not_null, _S_continuous, _S_prev_avail, _S_sed, _S_no_copy, _S_first_only, _S_match_flag_last }; /** * @brief This is a bitmask type indicating regex matching rules. * * The @c match_flag_type is implementation defined but it is valid to * perform bitwise operations on these values and expect the right thing to * happen. */ enum match_flag_type : unsigned int { }; /** * The default matching rules. */ _GLIBCXX17_INLINE constexpr match_flag_type match_default = static_cast(0); /** * The first character in the sequence [first, last) is treated as though it * is not at the beginning of a line, so the character (^) in the regular * expression shall not match [first, first). */ _GLIBCXX17_INLINE constexpr match_flag_type match_not_bol = static_cast(1 << _S_not_bol); /** * The last character in the sequence [first, last) is treated as though it * is not at the end of a line, so the character ($) in the regular * expression shall not match [last, last). */ _GLIBCXX17_INLINE constexpr match_flag_type match_not_eol = static_cast(1 << _S_not_eol); /** * The expression \\b is not matched against the sub-sequence * [first,first). */ _GLIBCXX17_INLINE constexpr match_flag_type match_not_bow = static_cast(1 << _S_not_bow); /** * The expression \\b should not be matched against the sub-sequence * [last,last). */ _GLIBCXX17_INLINE constexpr match_flag_type match_not_eow = static_cast(1 << _S_not_eow); /** * If more than one match is possible then any match is an acceptable * result. */ _GLIBCXX17_INLINE constexpr match_flag_type match_any = static_cast(1 << _S_any); /** * The expression does not match an empty sequence. */ _GLIBCXX17_INLINE constexpr match_flag_type match_not_null = static_cast(1 << _S_not_null); /** * The expression only matches a sub-sequence that begins at first . */ _GLIBCXX17_INLINE constexpr match_flag_type match_continuous = static_cast(1 << _S_continuous); /** * --first is a valid iterator position. When this flag is set then the * flags match_not_bol and match_not_bow are ignored by the regular * expression algorithms 28.11 and iterators 28.12. */ _GLIBCXX17_INLINE constexpr match_flag_type match_prev_avail = static_cast(1 << _S_prev_avail); /** * When a regular expression match is to be replaced by a new string, the * new string is constructed using the rules used by the ECMAScript replace * function in ECMA- 262 [Ecma International, ECMAScript Language * Specification, Standard Ecma-262, third edition, 1999], part 15.5.4.11 * String.prototype.replace. In addition, during search and replace * operations all non-overlapping occurrences of the regular expression * are located and replaced, and sections of the input that did not match * the expression are copied unchanged to the output string. * * Format strings (from ECMA-262 [15.5.4.11]): * @li $$ The dollar-sign itself ($) * @li $& The matched substring. * @li $` The portion of @a string that precedes the matched substring. * This would be match_results::prefix(). * @li $' The portion of @a string that follows the matched substring. * This would be match_results::suffix(). * @li $n The nth capture, where n is in [1,9] and $n is not followed by a * decimal digit. If n <= match_results::size() and the nth capture * is undefined, use the empty string instead. If n > * match_results::size(), the result is implementation-defined. * @li $nn The nnth capture, where nn is a two-digit decimal number on * [01, 99]. If nn <= match_results::size() and the nth capture is * undefined, use the empty string instead. If * nn > match_results::size(), the result is implementation-defined. */ _GLIBCXX17_INLINE constexpr match_flag_type format_default = static_cast(0); /** * When a regular expression match is to be replaced by a new string, the * new string is constructed using the rules used by the POSIX sed utility * in IEEE Std 1003.1- 2001 [IEEE, Information Technology -- Portable * Operating System Interface (POSIX), IEEE Standard 1003.1-2001]. */ _GLIBCXX17_INLINE constexpr match_flag_type format_sed = static_cast(1 << _S_sed); /** * During a search and replace operation, sections of the character * container sequence being searched that do not match the regular * expression shall not be copied to the output string. */ _GLIBCXX17_INLINE constexpr match_flag_type format_no_copy = static_cast(1 << _S_no_copy); /** * When specified during a search and replace operation, only the first * occurrence of the regular expression shall be replaced. */ _GLIBCXX17_INLINE constexpr match_flag_type format_first_only = static_cast(1 << _S_first_only); constexpr inline match_flag_type operator&(match_flag_type __a, match_flag_type __b) { return (match_flag_type)(static_cast(__a) & static_cast(__b)); } constexpr inline match_flag_type operator|(match_flag_type __a, match_flag_type __b) { return (match_flag_type)(static_cast(__a) | static_cast(__b)); } constexpr inline match_flag_type operator^(match_flag_type __a, match_flag_type __b) { return (match_flag_type)(static_cast(__a) ^ static_cast(__b)); } constexpr inline match_flag_type operator~(match_flag_type __a) { return (match_flag_type)(~static_cast(__a)); } inline match_flag_type& operator&=(match_flag_type& __a, match_flag_type __b) { return __a = __a & __b; } inline match_flag_type& operator|=(match_flag_type& __a, match_flag_type __b) { return __a = __a | __b; } inline match_flag_type& operator^=(match_flag_type& __a, match_flag_type __b) { return __a = __a ^ __b; } //@} } // namespace regex_constants /* @} */ // group regex _GLIBCXX_END_NAMESPACE_VERSION } // namespace std PK!tFҾ((8/bits/regex_error.hnu[// class template regex -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_error.h * @brief Error and exception objects for the std regex library. * * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup regex * @{ */ namespace regex_constants { /** * @name 5.3 Error Types */ //@{ enum error_type { _S_error_collate, _S_error_ctype, _S_error_escape, _S_error_backref, _S_error_brack, _S_error_paren, _S_error_brace, _S_error_badbrace, _S_error_range, _S_error_space, _S_error_badrepeat, _S_error_complexity, _S_error_stack, }; /** The expression contained an invalid collating element name. */ constexpr error_type error_collate(_S_error_collate); /** The expression contained an invalid character class name. */ constexpr error_type error_ctype(_S_error_ctype); /** * The expression contained an invalid escaped character, or a trailing * escape. */ constexpr error_type error_escape(_S_error_escape); /** The expression contained an invalid back reference. */ constexpr error_type error_backref(_S_error_backref); /** The expression contained mismatched [ and ]. */ constexpr error_type error_brack(_S_error_brack); /** The expression contained mismatched ( and ). */ constexpr error_type error_paren(_S_error_paren); /** The expression contained mismatched { and } */ constexpr error_type error_brace(_S_error_brace); /** The expression contained an invalid range in a {} expression. */ constexpr error_type error_badbrace(_S_error_badbrace); /** * The expression contained an invalid character range, * such as [b-a] in most encodings. */ constexpr error_type error_range(_S_error_range); /** * There was insufficient memory to convert the expression into a * finite state machine. */ constexpr error_type error_space(_S_error_space); /** * One of *?+{ was not preceded by a valid regular expression. */ constexpr error_type error_badrepeat(_S_error_badrepeat); /** * The complexity of an attempted match against a regular expression * exceeded a pre-set level. */ constexpr error_type error_complexity(_S_error_complexity); /** * There was insufficient memory to determine whether the * regular expression could match the specified character sequence. */ constexpr error_type error_stack(_S_error_stack); //@} } // namespace regex_constants // [7.8] Class regex_error /** * @brief A regular expression exception class. * @ingroup exceptions * * The regular expression library throws objects of this class on error. */ class regex_error : public std::runtime_error { regex_constants::error_type _M_code; public: /** * @brief Constructs a regex_error object. * * @param __ecode the regex error code. */ explicit regex_error(regex_constants::error_type __ecode); virtual ~regex_error() throw(); /** * @brief Gets the regex error code. * * @returns the regex error code. */ regex_constants::error_type code() const { return _M_code; } private: regex_error(regex_constants::error_type __ecode, const char* __what) : std::runtime_error(__what), _M_code(__ecode) { } friend void __throw_regex_error(regex_constants::error_type, const char*); }; //@} // group regex void __throw_regex_error(regex_constants::error_type __ecode); inline void __throw_regex_error(regex_constants::error_type __ecode, const char* __what) { _GLIBCXX_THROW_OR_ABORT(regex_error(__ecode, __what)); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std PK!6@@8/bits/regex_executor.hnu[// class template regex -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_executor.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ // FIXME convert comments to doxygen format. namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { /** * @addtogroup regex-detail * @{ */ /** * @brief Takes a regex and an input string and does the matching. * * The %_Executor class has two modes: DFS mode and BFS mode, controlled * by the template parameter %__dfs_mode. */ template class _Executor { using __search_mode = integral_constant; using __dfs = true_type; using __bfs = false_type; enum class _Match_mode : unsigned char { _Exact, _Prefix }; public: typedef typename iterator_traits<_BiIter>::value_type _CharT; typedef basic_regex<_CharT, _TraitsT> _RegexT; typedef std::vector, _Alloc> _ResultsVec; typedef regex_constants::match_flag_type _FlagT; typedef typename _TraitsT::char_class_type _ClassT; typedef _NFA<_TraitsT> _NFAT; public: _Executor(_BiIter __begin, _BiIter __end, _ResultsVec& __results, const _RegexT& __re, _FlagT __flags) : _M_begin(__begin), _M_end(__end), _M_re(__re), _M_nfa(*__re._M_automaton), _M_results(__results), _M_rep_count(_M_nfa.size()), _M_states(_M_nfa._M_start(), _M_nfa.size()), _M_flags((__flags & regex_constants::match_prev_avail) ? (__flags & ~regex_constants::match_not_bol & ~regex_constants::match_not_bow) : __flags) { } // Set matched when string exactly matches the pattern. bool _M_match() { _M_current = _M_begin; return _M_main(_Match_mode::_Exact); } // Set matched when some prefix of the string matches the pattern. bool _M_search_from_first() { _M_current = _M_begin; return _M_main(_Match_mode::_Prefix); } bool _M_search(); private: void _M_rep_once_more(_Match_mode __match_mode, _StateIdT); void _M_handle_repeat(_Match_mode, _StateIdT); void _M_handle_subexpr_begin(_Match_mode, _StateIdT); void _M_handle_subexpr_end(_Match_mode, _StateIdT); void _M_handle_line_begin_assertion(_Match_mode, _StateIdT); void _M_handle_line_end_assertion(_Match_mode, _StateIdT); void _M_handle_word_boundary(_Match_mode, _StateIdT); void _M_handle_subexpr_lookahead(_Match_mode, _StateIdT); void _M_handle_match(_Match_mode, _StateIdT); void _M_handle_backref(_Match_mode, _StateIdT); void _M_handle_accept(_Match_mode, _StateIdT); void _M_handle_alternative(_Match_mode, _StateIdT); void _M_dfs(_Match_mode __match_mode, _StateIdT __start); bool _M_main(_Match_mode __match_mode) { return _M_main_dispatch(__match_mode, __search_mode{}); } bool _M_main_dispatch(_Match_mode __match_mode, __dfs); bool _M_main_dispatch(_Match_mode __match_mode, __bfs); bool _M_is_word(_CharT __ch) const { static const _CharT __s[2] = { 'w' }; return _M_re._M_automaton->_M_traits.isctype (__ch, _M_re._M_automaton->_M_traits.lookup_classname(__s, __s+1)); } bool _M_at_begin() const { return _M_current == _M_begin && !(_M_flags & (regex_constants::match_not_bol | regex_constants::match_prev_avail)); } bool _M_at_end() const { return _M_current == _M_end && !(_M_flags & regex_constants::match_not_eol); } bool _M_word_boundary() const; bool _M_lookahead(_StateIdT __next); // Holds additional information used in BFS-mode. template struct _State_info; template struct _State_info<__bfs, _ResultsVec> { explicit _State_info(_StateIdT __start, size_t __n) : _M_visited_states(new bool[__n]()), _M_start(__start) { } bool _M_visited(_StateIdT __i) { if (_M_visited_states[__i]) return true; _M_visited_states[__i] = true; return false; } void _M_queue(_StateIdT __i, const _ResultsVec& __res) { _M_match_queue.emplace_back(__i, __res); } // Dummy implementations for BFS mode. _BiIter* _M_get_sol_pos() { return nullptr; } // Saves states that need to be considered for the next character. vector> _M_match_queue; // Indicates which states are already visited. unique_ptr _M_visited_states; // To record current solution. _StateIdT _M_start; }; template struct _State_info<__dfs, _ResultsVec> { explicit _State_info(_StateIdT __start, size_t) : _M_start(__start) { } // Dummy implementations for DFS mode. bool _M_visited(_StateIdT) const { return false; } void _M_queue(_StateIdT, const _ResultsVec&) { } _BiIter* _M_get_sol_pos() { return &_M_sol_pos; } // To record current solution. _StateIdT _M_start; _BiIter _M_sol_pos; }; public: _ResultsVec _M_cur_results; _BiIter _M_current; _BiIter _M_begin; const _BiIter _M_end; const _RegexT& _M_re; const _NFAT& _M_nfa; _ResultsVec& _M_results; vector> _M_rep_count; _State_info<__search_mode, _ResultsVec> _M_states; _FlagT _M_flags; // Do we have a solution so far? bool _M_has_sol; }; //@} regex-detail } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #include PK!VII8/bits/regex_executor.tccnu[// class template regex -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_executor.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { template bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_search() { if (_M_search_from_first()) return true; if (_M_flags & regex_constants::match_continuous) return false; _M_flags |= regex_constants::match_prev_avail; while (_M_begin != _M_end) { ++_M_begin; if (_M_search_from_first()) return true; } return false; } // The _M_main function operates in different modes, DFS mode or BFS mode, // indicated by template parameter __dfs_mode, and dispatches to one of the // _M_main_dispatch overloads. // // ------------------------------------------------------------ // // DFS mode: // // It applies a Depth-First-Search (aka backtracking) on given NFA and input // string. // At the very beginning the executor stands in the start state, then it // tries every possible state transition in current state recursively. Some // state transitions consume input string, say, a single-char-matcher or a // back-reference matcher; some don't, like assertion or other anchor nodes. // When the input is exhausted and/or the current state is an accepting // state, the whole executor returns true. // // TODO: This approach is exponentially slow for certain input. // Try to compile the NFA to a DFA. // // Time complexity: \Omega(match_length), O(2^(_M_nfa.size())) // Space complexity: \theta(match_results.size() + match_length) // template bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_main_dispatch(_Match_mode __match_mode, __dfs) { _M_has_sol = false; *_M_states._M_get_sol_pos() = _BiIter(); _M_cur_results = _M_results; _M_dfs(__match_mode, _M_states._M_start); return _M_has_sol; } // ------------------------------------------------------------ // // BFS mode: // // Russ Cox's article (http://swtch.com/~rsc/regexp/regexp1.html) // explained this algorithm clearly. // // It first computes epsilon closure (states that can be achieved without // consuming characters) for every state that's still matching, // using the same DFS algorithm, but doesn't re-enter states (using // _M_states._M_visited to check), nor follow _S_opcode_match. // // Then apply DFS using every _S_opcode_match (in _M_states._M_match_queue) // as the start state. // // It significantly reduces potential duplicate states, so has a better // upper bound; but it requires more overhead. // // Time complexity: \Omega(match_length * match_results.size()) // O(match_length * _M_nfa.size() * match_results.size()) // Space complexity: \Omega(_M_nfa.size() + match_results.size()) // O(_M_nfa.size() * match_results.size()) template bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_main_dispatch(_Match_mode __match_mode, __bfs) { _M_states._M_queue(_M_states._M_start, _M_results); bool __ret = false; while (1) { _M_has_sol = false; if (_M_states._M_match_queue.empty()) break; std::fill_n(_M_states._M_visited_states.get(), _M_nfa.size(), false); auto __old_queue = std::move(_M_states._M_match_queue); for (auto& __task : __old_queue) { _M_cur_results = std::move(__task.second); _M_dfs(__match_mode, __task.first); } if (__match_mode == _Match_mode::_Prefix) __ret |= _M_has_sol; if (_M_current == _M_end) break; ++_M_current; } if (__match_mode == _Match_mode::_Exact) __ret = _M_has_sol; _M_states._M_match_queue.clear(); return __ret; } // Return whether now match the given sub-NFA. template bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_lookahead(_StateIdT __next) { // Backreferences may refer to captured content. // We may want to make this faster by not copying, // but let's not be clever prematurely. _ResultsVec __what(_M_cur_results); _Executor __sub(_M_current, _M_end, __what, _M_re, _M_flags); __sub._M_states._M_start = __next; if (__sub._M_search_from_first()) { for (size_t __i = 0; __i < __what.size(); __i++) if (__what[__i].matched) _M_cur_results[__i] = __what[__i]; return true; } return false; } // __rep_count records how many times (__rep_count.second) // this node is visited under certain input iterator // (__rep_count.first). This prevent the executor from entering // infinite loop by refusing to continue when it's already been // visited more than twice. It's `twice` instead of `once` because // we need to spare one more time for potential group capture. template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_rep_once_more(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; auto& __rep_count = _M_rep_count[__i]; if (__rep_count.second == 0 || __rep_count.first != _M_current) { auto __back = __rep_count; __rep_count.first = _M_current; __rep_count.second = 1; _M_dfs(__match_mode, __state._M_alt); __rep_count = __back; } else { if (__rep_count.second < 2) { __rep_count.second++; _M_dfs(__match_mode, __state._M_alt); __rep_count.second--; } } } // _M_alt branch is "match once more", while _M_next is "get me out // of this quantifier". Executing _M_next first or _M_alt first don't // mean the same thing, and we need to choose the correct order under // given greedy mode. template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_repeat(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; // Greedy. if (!__state._M_neg) { _M_rep_once_more(__match_mode, __i); // If it's DFS executor and already accepted, we're done. if (!__dfs_mode || !_M_has_sol) _M_dfs(__match_mode, __state._M_next); } else // Non-greedy mode { if (__dfs_mode) { // vice-versa. _M_dfs(__match_mode, __state._M_next); if (!_M_has_sol) _M_rep_once_more(__match_mode, __i); } else { // DON'T attempt anything, because there's already another // state with higher priority accepted. This state cannot // be better by attempting its next node. if (!_M_has_sol) { _M_dfs(__match_mode, __state._M_next); // DON'T attempt anything if it's already accepted. An // accepted state *must* be better than a solution that // matches a non-greedy quantifier one more time. if (!_M_has_sol) _M_rep_once_more(__match_mode, __i); } } } } template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_subexpr_begin(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; auto& __res = _M_cur_results[__state._M_subexpr]; auto __back = __res.first; __res.first = _M_current; _M_dfs(__match_mode, __state._M_next); __res.first = __back; } template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_subexpr_end(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; auto& __res = _M_cur_results[__state._M_subexpr]; auto __back = __res; __res.second = _M_current; __res.matched = true; _M_dfs(__match_mode, __state._M_next); __res = __back; } template inline void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_line_begin_assertion(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; if (_M_at_begin()) _M_dfs(__match_mode, __state._M_next); } template inline void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_line_end_assertion(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; if (_M_at_end()) _M_dfs(__match_mode, __state._M_next); } template inline void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_word_boundary(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; if (_M_word_boundary() == !__state._M_neg) _M_dfs(__match_mode, __state._M_next); } // Here __state._M_alt offers a single start node for a sub-NFA. // We recursively invoke our algorithm to match the sub-NFA. template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_subexpr_lookahead(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; if (_M_lookahead(__state._M_alt) == !__state._M_neg) _M_dfs(__match_mode, __state._M_next); } template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_match(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; if (_M_current == _M_end) return; if (__dfs_mode) { if (__state._M_matches(*_M_current)) { ++_M_current; _M_dfs(__match_mode, __state._M_next); --_M_current; } } else if (__state._M_matches(*_M_current)) _M_states._M_queue(__state._M_next, _M_cur_results); } template struct _Backref_matcher { _Backref_matcher(bool __icase, const _TraitsT& __traits) : _M_traits(__traits) { } bool _M_apply(_BiIter __expected_begin, _BiIter __expected_end, _BiIter __actual_begin, _BiIter __actual_end) { return _M_traits.transform(__expected_begin, __expected_end) == _M_traits.transform(__actual_begin, __actual_end); } const _TraitsT& _M_traits; }; template struct _Backref_matcher<_BiIter, std::regex_traits<_CharT>> { using _TraitsT = std::regex_traits<_CharT>; _Backref_matcher(bool __icase, const _TraitsT& __traits) : _M_icase(__icase), _M_traits(__traits) { } bool _M_apply(_BiIter __expected_begin, _BiIter __expected_end, _BiIter __actual_begin, _BiIter __actual_end) { if (!_M_icase) return _GLIBCXX_STD_A::__equal4(__expected_begin, __expected_end, __actual_begin, __actual_end); typedef std::ctype<_CharT> __ctype_type; const auto& __fctyp = use_facet<__ctype_type>(_M_traits.getloc()); return _GLIBCXX_STD_A::__equal4(__expected_begin, __expected_end, __actual_begin, __actual_end, [this, &__fctyp](_CharT __lhs, _CharT __rhs) { return __fctyp.tolower(__lhs) == __fctyp.tolower(__rhs); }); } bool _M_icase; const _TraitsT& _M_traits; }; // First fetch the matched result from _M_cur_results as __submatch; // then compare it with // (_M_current, _M_current + (__submatch.second - __submatch.first)). // If matched, keep going; else just return and try another state. template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_backref(_Match_mode __match_mode, _StateIdT __i) { __glibcxx_assert(__dfs_mode); const auto& __state = _M_nfa[__i]; auto& __submatch = _M_cur_results[__state._M_backref_index]; if (!__submatch.matched) return; auto __last = _M_current; for (auto __tmp = __submatch.first; __last != _M_end && __tmp != __submatch.second; ++__tmp) ++__last; if (_Backref_matcher<_BiIter, _TraitsT>( _M_re.flags() & regex_constants::icase, _M_re._M_automaton->_M_traits)._M_apply( __submatch.first, __submatch.second, _M_current, __last)) { if (__last != _M_current) { auto __backup = _M_current; _M_current = __last; _M_dfs(__match_mode, __state._M_next); _M_current = __backup; } else _M_dfs(__match_mode, __state._M_next); } } template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_accept(_Match_mode __match_mode, _StateIdT __i) { if (__dfs_mode) { __glibcxx_assert(!_M_has_sol); if (__match_mode == _Match_mode::_Exact) _M_has_sol = _M_current == _M_end; else _M_has_sol = true; if (_M_current == _M_begin && (_M_flags & regex_constants::match_not_null)) _M_has_sol = false; if (_M_has_sol) { if (_M_nfa._M_flags & regex_constants::ECMAScript) _M_results = _M_cur_results; else // POSIX { __glibcxx_assert(_M_states._M_get_sol_pos()); // Here's POSIX's logic: match the longest one. However // we never know which one (lhs or rhs of "|") is longer // unless we try both of them and compare the results. // The member variable _M_sol_pos records the end // position of the last successful match. It's better // to be larger, because POSIX regex is always greedy. // TODO: This could be slow. if (*_M_states._M_get_sol_pos() == _BiIter() || std::distance(_M_begin, *_M_states._M_get_sol_pos()) < std::distance(_M_begin, _M_current)) { *_M_states._M_get_sol_pos() = _M_current; _M_results = _M_cur_results; } } } } else { if (_M_current == _M_begin && (_M_flags & regex_constants::match_not_null)) return; if (__match_mode == _Match_mode::_Prefix || _M_current == _M_end) if (!_M_has_sol) { _M_has_sol = true; _M_results = _M_cur_results; } } } template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_alternative(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; if (_M_nfa._M_flags & regex_constants::ECMAScript) { // TODO: Fix BFS support. It is wrong. _M_dfs(__match_mode, __state._M_alt); // Pick lhs if it matches. Only try rhs if it doesn't. if (!_M_has_sol) _M_dfs(__match_mode, __state._M_next); } else { // Try both and compare the result. // See "case _S_opcode_accept:" handling above. _M_dfs(__match_mode, __state._M_alt); auto __has_sol = _M_has_sol; _M_has_sol = false; _M_dfs(__match_mode, __state._M_next); _M_has_sol |= __has_sol; } } template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_dfs(_Match_mode __match_mode, _StateIdT __i) { if (_M_states._M_visited(__i)) return; switch (_M_nfa[__i]._M_opcode()) { case _S_opcode_repeat: _M_handle_repeat(__match_mode, __i); break; case _S_opcode_subexpr_begin: _M_handle_subexpr_begin(__match_mode, __i); break; case _S_opcode_subexpr_end: _M_handle_subexpr_end(__match_mode, __i); break; case _S_opcode_line_begin_assertion: _M_handle_line_begin_assertion(__match_mode, __i); break; case _S_opcode_line_end_assertion: _M_handle_line_end_assertion(__match_mode, __i); break; case _S_opcode_word_boundary: _M_handle_word_boundary(__match_mode, __i); break; case _S_opcode_subexpr_lookahead: _M_handle_subexpr_lookahead(__match_mode, __i); break; case _S_opcode_match: _M_handle_match(__match_mode, __i); break; case _S_opcode_backref: _M_handle_backref(__match_mode, __i); break; case _S_opcode_accept: _M_handle_accept(__match_mode, __i); break; case _S_opcode_alternative: _M_handle_alternative(__match_mode, __i); break; default: __glibcxx_assert(false); } } // Return whether now is at some word boundary. template bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_word_boundary() const { if (_M_current == _M_begin && (_M_flags & regex_constants::match_not_bow)) return false; if (_M_current == _M_end && (_M_flags & regex_constants::match_not_eow)) return false; bool __left_is_word = false; if (_M_current != _M_begin || (_M_flags & regex_constants::match_prev_avail)) { auto __prev = _M_current; if (_M_is_word(*std::prev(__prev))) __left_is_word = true; } bool __right_is_word = _M_current != _M_end && _M_is_word(*_M_current); return __left_is_word != __right_is_word; } } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace PK!Si<8/bits/regex_scanner.hnu[// class template regex -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_scanner.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { /** * @addtogroup regex-detail * @{ */ struct _ScannerBase { public: /// Token types returned from the scanner. enum _TokenT : unsigned { _S_token_anychar, _S_token_ord_char, _S_token_oct_num, _S_token_hex_num, _S_token_backref, _S_token_subexpr_begin, _S_token_subexpr_no_group_begin, _S_token_subexpr_lookahead_begin, // neg if _M_value[0] == 'n' _S_token_subexpr_end, _S_token_bracket_begin, _S_token_bracket_neg_begin, _S_token_bracket_end, _S_token_interval_begin, _S_token_interval_end, _S_token_quoted_class, _S_token_char_class_name, _S_token_collsymbol, _S_token_equiv_class_name, _S_token_opt, _S_token_or, _S_token_closure0, _S_token_closure1, _S_token_line_begin, _S_token_line_end, _S_token_word_bound, // neg if _M_value[0] == 'n' _S_token_comma, _S_token_dup_count, _S_token_eof, _S_token_bracket_dash, _S_token_unknown = -1u }; protected: typedef regex_constants::syntax_option_type _FlagT; enum _StateT { _S_state_normal, _S_state_in_brace, _S_state_in_bracket, }; protected: _ScannerBase(_FlagT __flags) : _M_state(_S_state_normal), _M_flags(__flags), _M_escape_tbl(_M_is_ecma() ? _M_ecma_escape_tbl : _M_awk_escape_tbl), _M_spec_char(_M_is_ecma() ? _M_ecma_spec_char : _M_flags & regex_constants::basic ? _M_basic_spec_char : _M_flags & regex_constants::extended ? _M_extended_spec_char : _M_flags & regex_constants::grep ? ".[\\*^$\n" : _M_flags & regex_constants::egrep ? ".[\\()*+?{|^$\n" : _M_flags & regex_constants::awk ? _M_extended_spec_char : nullptr), _M_at_bracket_start(false) { __glibcxx_assert(_M_spec_char); } protected: const char* _M_find_escape(char __c) { auto __it = _M_escape_tbl; for (; __it->first != '\0'; ++__it) if (__it->first == __c) return &__it->second; return nullptr; } bool _M_is_ecma() const { return _M_flags & regex_constants::ECMAScript; } bool _M_is_basic() const { return _M_flags & (regex_constants::basic | regex_constants::grep); } bool _M_is_extended() const { return _M_flags & (regex_constants::extended | regex_constants::egrep | regex_constants::awk); } bool _M_is_grep() const { return _M_flags & (regex_constants::grep | regex_constants::egrep); } bool _M_is_awk() const { return _M_flags & regex_constants::awk; } protected: // TODO: Make them static in the next abi change. const std::pair _M_token_tbl[9] = { {'^', _S_token_line_begin}, {'$', _S_token_line_end}, {'.', _S_token_anychar}, {'*', _S_token_closure0}, {'+', _S_token_closure1}, {'?', _S_token_opt}, {'|', _S_token_or}, {'\n', _S_token_or}, // grep and egrep {'\0', _S_token_or}, }; const std::pair _M_ecma_escape_tbl[8] = { {'0', '\0'}, {'b', '\b'}, {'f', '\f'}, {'n', '\n'}, {'r', '\r'}, {'t', '\t'}, {'v', '\v'}, {'\0', '\0'}, }; const std::pair _M_awk_escape_tbl[11] = { {'"', '"'}, {'/', '/'}, {'\\', '\\'}, {'a', '\a'}, {'b', '\b'}, {'f', '\f'}, {'n', '\n'}, {'r', '\r'}, {'t', '\t'}, {'v', '\v'}, {'\0', '\0'}, }; const char* _M_ecma_spec_char = "^$\\.*+?()[]{}|"; const char* _M_basic_spec_char = ".[\\*^$"; const char* _M_extended_spec_char = ".[\\()*+?{|^$"; _StateT _M_state; _FlagT _M_flags; _TokenT _M_token; const std::pair* _M_escape_tbl; const char* _M_spec_char; bool _M_at_bracket_start; }; /** * @brief Scans an input range for regex tokens. * * The %_Scanner class interprets the regular expression pattern in * the input range passed to its constructor as a sequence of parse * tokens passed to the regular expression compiler. The sequence * of tokens provided depends on the flag settings passed to the * constructor: different regular expression grammars will interpret * the same input pattern in syntactically different ways. */ template class _Scanner : public _ScannerBase { public: typedef const _CharT* _IterT; typedef std::basic_string<_CharT> _StringT; typedef regex_constants::syntax_option_type _FlagT; typedef const std::ctype<_CharT> _CtypeT; _Scanner(_IterT __begin, _IterT __end, _FlagT __flags, std::locale __loc); void _M_advance(); _TokenT _M_get_token() const { return _M_token; } const _StringT& _M_get_value() const { return _M_value; } #ifdef _GLIBCXX_DEBUG std::ostream& _M_print(std::ostream&); #endif private: void _M_scan_normal(); void _M_scan_in_bracket(); void _M_scan_in_brace(); void _M_eat_escape_ecma(); void _M_eat_escape_posix(); void _M_eat_escape_awk(); void _M_eat_class(char); _IterT _M_current; _IterT _M_end; _CtypeT& _M_ctype; _StringT _M_value; void (_Scanner::* _M_eat_escape)(); }; //@} regex-detail } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #include PK!$::8/bits/regex_scanner.tccnu[// class template regex -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_scanner.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ // FIXME make comments doxygen format. // N3376 specified 6 regex styles: ECMAScript, basic, extended, grep, egrep // and awk // 1) grep is basic except '\n' is treated as '|' // 2) egrep is extended except '\n' is treated as '|' // 3) awk is extended except special escaping rules, and there's no // back-reference. // // References: // // ECMAScript: ECMA-262 15.10 // // basic, extended: // http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html // // awk: http://pubs.opengroup.org/onlinepubs/000095399/utilities/awk.html namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { template _Scanner<_CharT>:: _Scanner(typename _Scanner::_IterT __begin, typename _Scanner::_IterT __end, _FlagT __flags, std::locale __loc) : _ScannerBase(__flags), _M_current(__begin), _M_end(__end), _M_ctype(std::use_facet<_CtypeT>(__loc)), _M_eat_escape(_M_is_ecma() ? &_Scanner::_M_eat_escape_ecma : &_Scanner::_M_eat_escape_posix) { _M_advance(); } template void _Scanner<_CharT>:: _M_advance() { if (_M_current == _M_end) { _M_token = _S_token_eof; return; } if (_M_state == _S_state_normal) _M_scan_normal(); else if (_M_state == _S_state_in_bracket) _M_scan_in_bracket(); else if (_M_state == _S_state_in_brace) _M_scan_in_brace(); else { __glibcxx_assert(false); } } // Differences between styles: // 1) "\(", "\)", "\{" in basic. It's not escaping. // 2) "(?:", "(?=", "(?!" in ECMAScript. template void _Scanner<_CharT>:: _M_scan_normal() { auto __c = *_M_current++; if (std::strchr(_M_spec_char, _M_ctype.narrow(__c, ' ')) == nullptr) { _M_token = _S_token_ord_char; _M_value.assign(1, __c); return; } if (__c == '\\') { if (_M_current == _M_end) __throw_regex_error( regex_constants::error_escape, "Unexpected end of regex when escaping."); if (!_M_is_basic() || (*_M_current != '(' && *_M_current != ')' && *_M_current != '{')) { (this->*_M_eat_escape)(); return; } __c = *_M_current++; } if (__c == '(') { if (_M_is_ecma() && *_M_current == '?') { if (++_M_current == _M_end) __throw_regex_error( regex_constants::error_paren, "Unexpected end of regex when in an open parenthesis."); if (*_M_current == ':') { ++_M_current; _M_token = _S_token_subexpr_no_group_begin; } else if (*_M_current == '=') { ++_M_current; _M_token = _S_token_subexpr_lookahead_begin; _M_value.assign(1, 'p'); } else if (*_M_current == '!') { ++_M_current; _M_token = _S_token_subexpr_lookahead_begin; _M_value.assign(1, 'n'); } else __throw_regex_error( regex_constants::error_paren, "Invalid special open parenthesis."); } else if (_M_flags & regex_constants::nosubs) _M_token = _S_token_subexpr_no_group_begin; else _M_token = _S_token_subexpr_begin; } else if (__c == ')') _M_token = _S_token_subexpr_end; else if (__c == '[') { _M_state = _S_state_in_bracket; _M_at_bracket_start = true; if (_M_current != _M_end && *_M_current == '^') { _M_token = _S_token_bracket_neg_begin; ++_M_current; } else _M_token = _S_token_bracket_begin; } else if (__c == '{') { _M_state = _S_state_in_brace; _M_token = _S_token_interval_begin; } else if (__c != ']' && __c != '}') { auto __it = _M_token_tbl; auto __narrowc = _M_ctype.narrow(__c, '\0'); for (; __it->first != '\0'; ++__it) if (__it->first == __narrowc) { _M_token = __it->second; return; } __glibcxx_assert(false); } else { _M_token = _S_token_ord_char; _M_value.assign(1, __c); } } // Differences between styles: // 1) different semantics of "[]" and "[^]". // 2) Escaping in bracket expr. template void _Scanner<_CharT>:: _M_scan_in_bracket() { if (_M_current == _M_end) __throw_regex_error( regex_constants::error_brack, "Unexpected end of regex when in bracket expression."); auto __c = *_M_current++; if (__c == '-') _M_token = _S_token_bracket_dash; else if (__c == '[') { if (_M_current == _M_end) __throw_regex_error(regex_constants::error_brack, "Unexpected character class open bracket."); if (*_M_current == '.') { _M_token = _S_token_collsymbol; _M_eat_class(*_M_current++); } else if (*_M_current == ':') { _M_token = _S_token_char_class_name; _M_eat_class(*_M_current++); } else if (*_M_current == '=') { _M_token = _S_token_equiv_class_name; _M_eat_class(*_M_current++); } else { _M_token = _S_token_ord_char; _M_value.assign(1, __c); } } // In POSIX, when encountering "[]" or "[^]", the ']' is interpreted // literally. So "[]]" and "[^]]" are valid regexes. See the testcases // `*/empty_range.cc`. else if (__c == ']' && (_M_is_ecma() || !_M_at_bracket_start)) { _M_token = _S_token_bracket_end; _M_state = _S_state_normal; } // ECMAScript and awk permits escaping in bracket. else if (__c == '\\' && (_M_is_ecma() || _M_is_awk())) (this->*_M_eat_escape)(); else { _M_token = _S_token_ord_char; _M_value.assign(1, __c); } _M_at_bracket_start = false; } // Differences between styles: // 1) "\}" in basic style. template void _Scanner<_CharT>:: _M_scan_in_brace() { if (_M_current == _M_end) __throw_regex_error( regex_constants::error_brace, "Unexpected end of regex when in brace expression."); auto __c = *_M_current++; if (_M_ctype.is(_CtypeT::digit, __c)) { _M_token = _S_token_dup_count; _M_value.assign(1, __c); while (_M_current != _M_end && _M_ctype.is(_CtypeT::digit, *_M_current)) _M_value += *_M_current++; } else if (__c == ',') _M_token = _S_token_comma; // basic use \}. else if (_M_is_basic()) { if (__c == '\\' && _M_current != _M_end && *_M_current == '}') { _M_state = _S_state_normal; _M_token = _S_token_interval_end; ++_M_current; } else __throw_regex_error(regex_constants::error_badbrace, "Unexpected character in brace expression."); } else if (__c == '}') { _M_state = _S_state_normal; _M_token = _S_token_interval_end; } else __throw_regex_error(regex_constants::error_badbrace, "Unexpected character in brace expression."); } template void _Scanner<_CharT>:: _M_eat_escape_ecma() { if (_M_current == _M_end) __throw_regex_error(regex_constants::error_escape, "Unexpected end of regex when escaping."); auto __c = *_M_current++; auto __pos = _M_find_escape(_M_ctype.narrow(__c, '\0')); if (__pos != nullptr && (__c != 'b' || _M_state == _S_state_in_bracket)) { _M_token = _S_token_ord_char; _M_value.assign(1, *__pos); } else if (__c == 'b') { _M_token = _S_token_word_bound; _M_value.assign(1, 'p'); } else if (__c == 'B') { _M_token = _S_token_word_bound; _M_value.assign(1, 'n'); } // N3376 28.13 else if (__c == 'd' || __c == 'D' || __c == 's' || __c == 'S' || __c == 'w' || __c == 'W') { _M_token = _S_token_quoted_class; _M_value.assign(1, __c); } else if (__c == 'c') { if (_M_current == _M_end) __throw_regex_error( regex_constants::error_escape, "Unexpected end of regex when reading control code."); _M_token = _S_token_ord_char; _M_value.assign(1, *_M_current++); } else if (__c == 'x' || __c == 'u') { _M_value.erase(); for (int __i = 0; __i < (__c == 'x' ? 2 : 4); __i++) { if (_M_current == _M_end || !_M_ctype.is(_CtypeT::xdigit, *_M_current)) __throw_regex_error( regex_constants::error_escape, "Unexpected end of regex when ascii character."); _M_value += *_M_current++; } _M_token = _S_token_hex_num; } // ECMAScript recognizes multi-digit back-references. else if (_M_ctype.is(_CtypeT::digit, __c)) { _M_value.assign(1, __c); while (_M_current != _M_end && _M_ctype.is(_CtypeT::digit, *_M_current)) _M_value += *_M_current++; _M_token = _S_token_backref; } else { _M_token = _S_token_ord_char; _M_value.assign(1, __c); } } // Differences between styles: // 1) Extended doesn't support backref, but basic does. template void _Scanner<_CharT>:: _M_eat_escape_posix() { if (_M_current == _M_end) __throw_regex_error(regex_constants::error_escape, "Unexpected end of regex when escaping."); auto __c = *_M_current; auto __pos = std::strchr(_M_spec_char, _M_ctype.narrow(__c, '\0')); if (__pos != nullptr && *__pos != '\0') { _M_token = _S_token_ord_char; _M_value.assign(1, __c); } // We MUST judge awk before handling backrefs. There's no backref in awk. else if (_M_is_awk()) { _M_eat_escape_awk(); return; } else if (_M_is_basic() && _M_ctype.is(_CtypeT::digit, __c) && __c != '0') { _M_token = _S_token_backref; _M_value.assign(1, __c); } else { #ifdef __STRICT_ANSI__ // POSIX says it is undefined to escape ordinary characters __throw_regex_error(regex_constants::error_escape, "Unexpected escape character."); #else _M_token = _S_token_ord_char; _M_value.assign(1, __c); #endif } ++_M_current; } template void _Scanner<_CharT>:: _M_eat_escape_awk() { auto __c = *_M_current++; auto __pos = _M_find_escape(_M_ctype.narrow(__c, '\0')); if (__pos != nullptr) { _M_token = _S_token_ord_char; _M_value.assign(1, *__pos); } // \ddd for oct representation else if (_M_ctype.is(_CtypeT::digit, __c) && __c != '8' && __c != '9') { _M_value.assign(1, __c); for (int __i = 0; __i < 2 && _M_current != _M_end && _M_ctype.is(_CtypeT::digit, *_M_current) && *_M_current != '8' && *_M_current != '9'; __i++) _M_value += *_M_current++; _M_token = _S_token_oct_num; return; } else __throw_regex_error(regex_constants::error_escape, "Unexpected escape character."); } // Eats a character class or throws an exception. // __ch could be ':', '.' or '=', _M_current is the char after ']' when // returning. template void _Scanner<_CharT>:: _M_eat_class(char __ch) { for (_M_value.clear(); _M_current != _M_end && *_M_current != __ch;) _M_value += *_M_current++; if (_M_current == _M_end || *_M_current++ != __ch || _M_current == _M_end // skip __ch || *_M_current++ != ']') // skip ']' { if (__ch == ':') __throw_regex_error(regex_constants::error_ctype, "Unexpected end of character class."); else __throw_regex_error(regex_constants::error_collate, "Unexpected end of character class."); } } #ifdef _GLIBCXX_DEBUG template std::ostream& _Scanner<_CharT>:: _M_print(std::ostream& ostr) { switch (_M_token) { case _S_token_anychar: ostr << "any-character\n"; break; case _S_token_backref: ostr << "backref\n"; break; case _S_token_bracket_begin: ostr << "bracket-begin\n"; break; case _S_token_bracket_neg_begin: ostr << "bracket-neg-begin\n"; break; case _S_token_bracket_end: ostr << "bracket-end\n"; break; case _S_token_char_class_name: ostr << "char-class-name \"" << _M_value << "\"\n"; break; case _S_token_closure0: ostr << "closure0\n"; break; case _S_token_closure1: ostr << "closure1\n"; break; case _S_token_collsymbol: ostr << "collsymbol \"" << _M_value << "\"\n"; break; case _S_token_comma: ostr << "comma\n"; break; case _S_token_dup_count: ostr << "dup count: " << _M_value << "\n"; break; case _S_token_eof: ostr << "EOF\n"; break; case _S_token_equiv_class_name: ostr << "equiv-class-name \"" << _M_value << "\"\n"; break; case _S_token_interval_begin: ostr << "interval begin\n"; break; case _S_token_interval_end: ostr << "interval end\n"; break; case _S_token_line_begin: ostr << "line begin\n"; break; case _S_token_line_end: ostr << "line end\n"; break; case _S_token_opt: ostr << "opt\n"; break; case _S_token_or: ostr << "or\n"; break; case _S_token_ord_char: ostr << "ordinary character: \"" << _M_value << "\"\n"; break; case _S_token_subexpr_begin: ostr << "subexpr begin\n"; break; case _S_token_subexpr_no_group_begin: ostr << "no grouping subexpr begin\n"; break; case _S_token_subexpr_lookahead_begin: ostr << "lookahead subexpr begin\n"; break; case _S_token_subexpr_end: ostr << "subexpr end\n"; break; case _S_token_unknown: ostr << "-- unknown token --\n"; break; case _S_token_oct_num: ostr << "oct number " << _M_value << "\n"; break; case _S_token_hex_num: ostr << "hex number " << _M_value << "\n"; break; case _S_token_quoted_class: ostr << "quoted class " << "\\" << _M_value << "\n"; break; default: _GLIBCXX_DEBUG_ASSERT(false); } return ostr; } #endif } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace PK!Z[[8/bits/shared_ptr.hnu[// shared_ptr and weak_ptr implementation -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // GCC Note: Based on files from version 1.32.0 of the Boost library. // shared_count.hpp // Copyright (c) 2001, 2002, 2003 Peter Dimov and Multi Media Ltd. // shared_ptr.hpp // Copyright (C) 1998, 1999 Greg Colvin and Beman Dawes. // Copyright (C) 2001, 2002, 2003 Peter Dimov // weak_ptr.hpp // Copyright (C) 2001, 2002, 2003 Peter Dimov // enable_shared_from_this.hpp // Copyright (C) 2002 Peter Dimov // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) /** @file * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _SHARED_PTR_H #define _SHARED_PTR_H 1 #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup pointer_abstractions * @{ */ /// 20.7.2.2.11 shared_ptr I/O template inline std::basic_ostream<_Ch, _Tr>& operator<<(std::basic_ostream<_Ch, _Tr>& __os, const __shared_ptr<_Tp, _Lp>& __p) { __os << __p.get(); return __os; } template inline _Del* get_deleter(const __shared_ptr<_Tp, _Lp>& __p) noexcept { #if __cpp_rtti return static_cast<_Del*>(__p._M_get_deleter(typeid(_Del))); #else return 0; #endif } /// 20.7.2.2.10 shared_ptr get_deleter template inline _Del* get_deleter(const shared_ptr<_Tp>& __p) noexcept { #if __cpp_rtti return static_cast<_Del*>(__p._M_get_deleter(typeid(_Del))); #else return 0; #endif } /** * @brief A smart pointer with reference-counted copy semantics. * * The object pointed to is deleted when the last shared_ptr pointing to * it is destroyed or reset. */ template class shared_ptr : public __shared_ptr<_Tp> { template using _Constructible = typename enable_if< is_constructible<__shared_ptr<_Tp>, _Args...>::value >::type; template using _Assignable = typename enable_if< is_assignable<__shared_ptr<_Tp>&, _Arg>::value, shared_ptr& >::type; public: using element_type = typename __shared_ptr<_Tp>::element_type; #if __cplusplus > 201402L # define __cpp_lib_shared_ptr_weak_type 201606 using weak_type = weak_ptr<_Tp>; #endif /** * @brief Construct an empty %shared_ptr. * @post use_count()==0 && get()==0 */ constexpr shared_ptr() noexcept : __shared_ptr<_Tp>() { } shared_ptr(const shared_ptr&) noexcept = default; /** * @brief Construct a %shared_ptr that owns the pointer @a __p. * @param __p A pointer that is convertible to element_type*. * @post use_count() == 1 && get() == __p * @throw std::bad_alloc, in which case @c delete @a __p is called. */ template> explicit shared_ptr(_Yp* __p) : __shared_ptr<_Tp>(__p) { } /** * @brief Construct a %shared_ptr that owns the pointer @a __p * and the deleter @a __d. * @param __p A pointer. * @param __d A deleter. * @post use_count() == 1 && get() == __p * @throw std::bad_alloc, in which case @a __d(__p) is called. * * Requirements: _Deleter's copy constructor and destructor must * not throw * * __shared_ptr will release __p by calling __d(__p) */ template> shared_ptr(_Yp* __p, _Deleter __d) : __shared_ptr<_Tp>(__p, std::move(__d)) { } /** * @brief Construct a %shared_ptr that owns a null pointer * and the deleter @a __d. * @param __p A null pointer constant. * @param __d A deleter. * @post use_count() == 1 && get() == __p * @throw std::bad_alloc, in which case @a __d(__p) is called. * * Requirements: _Deleter's copy constructor and destructor must * not throw * * The last owner will call __d(__p) */ template shared_ptr(nullptr_t __p, _Deleter __d) : __shared_ptr<_Tp>(__p, std::move(__d)) { } /** * @brief Construct a %shared_ptr that owns the pointer @a __p * and the deleter @a __d. * @param __p A pointer. * @param __d A deleter. * @param __a An allocator. * @post use_count() == 1 && get() == __p * @throw std::bad_alloc, in which case @a __d(__p) is called. * * Requirements: _Deleter's copy constructor and destructor must * not throw _Alloc's copy constructor and destructor must not * throw. * * __shared_ptr will release __p by calling __d(__p) */ template> shared_ptr(_Yp* __p, _Deleter __d, _Alloc __a) : __shared_ptr<_Tp>(__p, std::move(__d), std::move(__a)) { } /** * @brief Construct a %shared_ptr that owns a null pointer * and the deleter @a __d. * @param __p A null pointer constant. * @param __d A deleter. * @param __a An allocator. * @post use_count() == 1 && get() == __p * @throw std::bad_alloc, in which case @a __d(__p) is called. * * Requirements: _Deleter's copy constructor and destructor must * not throw _Alloc's copy constructor and destructor must not * throw. * * The last owner will call __d(__p) */ template shared_ptr(nullptr_t __p, _Deleter __d, _Alloc __a) : __shared_ptr<_Tp>(__p, std::move(__d), std::move(__a)) { } // Aliasing constructor /** * @brief Constructs a %shared_ptr instance that stores @a __p * and shares ownership with @a __r. * @param __r A %shared_ptr. * @param __p A pointer that will remain valid while @a *__r is valid. * @post get() == __p && use_count() == __r.use_count() * * This can be used to construct a @c shared_ptr to a sub-object * of an object managed by an existing @c shared_ptr. * * @code * shared_ptr< pair > pii(new pair()); * shared_ptr pi(pii, &pii->first); * assert(pii.use_count() == 2); * @endcode */ template shared_ptr(const shared_ptr<_Yp>& __r, element_type* __p) noexcept : __shared_ptr<_Tp>(__r, __p) { } /** * @brief If @a __r is empty, constructs an empty %shared_ptr; * otherwise construct a %shared_ptr that shares ownership * with @a __r. * @param __r A %shared_ptr. * @post get() == __r.get() && use_count() == __r.use_count() */ template&>> shared_ptr(const shared_ptr<_Yp>& __r) noexcept : __shared_ptr<_Tp>(__r) { } /** * @brief Move-constructs a %shared_ptr instance from @a __r. * @param __r A %shared_ptr rvalue. * @post *this contains the old value of @a __r, @a __r is empty. */ shared_ptr(shared_ptr&& __r) noexcept : __shared_ptr<_Tp>(std::move(__r)) { } /** * @brief Move-constructs a %shared_ptr instance from @a __r. * @param __r A %shared_ptr rvalue. * @post *this contains the old value of @a __r, @a __r is empty. */ template>> shared_ptr(shared_ptr<_Yp>&& __r) noexcept : __shared_ptr<_Tp>(std::move(__r)) { } /** * @brief Constructs a %shared_ptr that shares ownership with @a __r * and stores a copy of the pointer stored in @a __r. * @param __r A weak_ptr. * @post use_count() == __r.use_count() * @throw bad_weak_ptr when __r.expired(), * in which case the constructor has no effect. */ template&>> explicit shared_ptr(const weak_ptr<_Yp>& __r) : __shared_ptr<_Tp>(__r) { } #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" template>> shared_ptr(auto_ptr<_Yp>&& __r); #pragma GCC diagnostic pop #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2399. shared_ptr's constructor from unique_ptr should be constrained template>> shared_ptr(unique_ptr<_Yp, _Del>&& __r) : __shared_ptr<_Tp>(std::move(__r)) { } #if __cplusplus <= 201402L && _GLIBCXX_USE_DEPRECATED // This non-standard constructor exists to support conversions that // were possible in C++11 and C++14 but are ill-formed in C++17. // If an exception is thrown this constructor has no effect. template, __sp_array_delete>* = 0> shared_ptr(unique_ptr<_Yp, _Del>&& __r) : __shared_ptr<_Tp>(std::move(__r), __sp_array_delete()) { } #endif /** * @brief Construct an empty %shared_ptr. * @post use_count() == 0 && get() == nullptr */ constexpr shared_ptr(nullptr_t) noexcept : shared_ptr() { } shared_ptr& operator=(const shared_ptr&) noexcept = default; template _Assignable&> operator=(const shared_ptr<_Yp>& __r) noexcept { this->__shared_ptr<_Tp>::operator=(__r); return *this; } #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" template _Assignable> operator=(auto_ptr<_Yp>&& __r) { this->__shared_ptr<_Tp>::operator=(std::move(__r)); return *this; } #pragma GCC diagnostic pop #endif shared_ptr& operator=(shared_ptr&& __r) noexcept { this->__shared_ptr<_Tp>::operator=(std::move(__r)); return *this; } template _Assignable> operator=(shared_ptr<_Yp>&& __r) noexcept { this->__shared_ptr<_Tp>::operator=(std::move(__r)); return *this; } template _Assignable> operator=(unique_ptr<_Yp, _Del>&& __r) { this->__shared_ptr<_Tp>::operator=(std::move(__r)); return *this; } private: // This constructor is non-standard, it is used by allocate_shared. template shared_ptr(_Sp_alloc_shared_tag<_Alloc> __tag, _Args&&... __args) : __shared_ptr<_Tp>(__tag, std::forward<_Args>(__args)...) { } template friend shared_ptr<_Yp> allocate_shared(const _Alloc& __a, _Args&&... __args); // This constructor is non-standard, it is used by weak_ptr::lock(). shared_ptr(const weak_ptr<_Tp>& __r, std::nothrow_t) : __shared_ptr<_Tp>(__r, std::nothrow) { } friend class weak_ptr<_Tp>; }; #if __cpp_deduction_guides >= 201606 template shared_ptr(weak_ptr<_Tp>) -> shared_ptr<_Tp>; template shared_ptr(unique_ptr<_Tp, _Del>) -> shared_ptr<_Tp>; #endif // 20.7.2.2.7 shared_ptr comparisons template inline bool operator==(const shared_ptr<_Tp>& __a, const shared_ptr<_Up>& __b) noexcept { return __a.get() == __b.get(); } template inline bool operator==(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { return !__a; } template inline bool operator==(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { return !__a; } template inline bool operator!=(const shared_ptr<_Tp>& __a, const shared_ptr<_Up>& __b) noexcept { return __a.get() != __b.get(); } template inline bool operator!=(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { return (bool)__a; } template inline bool operator!=(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { return (bool)__a; } template inline bool operator<(const shared_ptr<_Tp>& __a, const shared_ptr<_Up>& __b) noexcept { using _Tp_elt = typename shared_ptr<_Tp>::element_type; using _Up_elt = typename shared_ptr<_Up>::element_type; using _Vp = typename common_type<_Tp_elt*, _Up_elt*>::type; return less<_Vp>()(__a.get(), __b.get()); } template inline bool operator<(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { using _Tp_elt = typename shared_ptr<_Tp>::element_type; return less<_Tp_elt*>()(__a.get(), nullptr); } template inline bool operator<(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { using _Tp_elt = typename shared_ptr<_Tp>::element_type; return less<_Tp_elt*>()(nullptr, __a.get()); } template inline bool operator<=(const shared_ptr<_Tp>& __a, const shared_ptr<_Up>& __b) noexcept { return !(__b < __a); } template inline bool operator<=(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { return !(nullptr < __a); } template inline bool operator<=(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { return !(__a < nullptr); } template inline bool operator>(const shared_ptr<_Tp>& __a, const shared_ptr<_Up>& __b) noexcept { return (__b < __a); } template inline bool operator>(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { return nullptr < __a; } template inline bool operator>(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { return __a < nullptr; } template inline bool operator>=(const shared_ptr<_Tp>& __a, const shared_ptr<_Up>& __b) noexcept { return !(__a < __b); } template inline bool operator>=(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { return !(__a < nullptr); } template inline bool operator>=(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { return !(nullptr < __a); } template struct less> : public _Sp_less> { }; // 20.7.2.2.8 shared_ptr specialized algorithms. template inline void swap(shared_ptr<_Tp>& __a, shared_ptr<_Tp>& __b) noexcept { __a.swap(__b); } // 20.7.2.2.9 shared_ptr casts. template inline shared_ptr<_Tp> static_pointer_cast(const shared_ptr<_Up>& __r) noexcept { using _Sp = shared_ptr<_Tp>; return _Sp(__r, static_cast(__r.get())); } template inline shared_ptr<_Tp> const_pointer_cast(const shared_ptr<_Up>& __r) noexcept { using _Sp = shared_ptr<_Tp>; return _Sp(__r, const_cast(__r.get())); } template inline shared_ptr<_Tp> dynamic_pointer_cast(const shared_ptr<_Up>& __r) noexcept { using _Sp = shared_ptr<_Tp>; if (auto* __p = dynamic_cast(__r.get())) return _Sp(__r, __p); return _Sp(); } #if __cplusplus > 201402L template inline shared_ptr<_Tp> reinterpret_pointer_cast(const shared_ptr<_Up>& __r) noexcept { using _Sp = shared_ptr<_Tp>; return _Sp(__r, reinterpret_cast(__r.get())); } #endif /** * @brief A smart pointer with weak semantics. * * With forwarding constructors and assignment operators. */ template class weak_ptr : public __weak_ptr<_Tp> { template using _Constructible = typename enable_if< is_constructible<__weak_ptr<_Tp>, _Arg>::value >::type; template using _Assignable = typename enable_if< is_assignable<__weak_ptr<_Tp>&, _Arg>::value, weak_ptr& >::type; public: constexpr weak_ptr() noexcept = default; template&>> weak_ptr(const shared_ptr<_Yp>& __r) noexcept : __weak_ptr<_Tp>(__r) { } weak_ptr(const weak_ptr&) noexcept = default; template&>> weak_ptr(const weak_ptr<_Yp>& __r) noexcept : __weak_ptr<_Tp>(__r) { } weak_ptr(weak_ptr&&) noexcept = default; template>> weak_ptr(weak_ptr<_Yp>&& __r) noexcept : __weak_ptr<_Tp>(std::move(__r)) { } weak_ptr& operator=(const weak_ptr& __r) noexcept = default; template _Assignable&> operator=(const weak_ptr<_Yp>& __r) noexcept { this->__weak_ptr<_Tp>::operator=(__r); return *this; } template _Assignable&> operator=(const shared_ptr<_Yp>& __r) noexcept { this->__weak_ptr<_Tp>::operator=(__r); return *this; } weak_ptr& operator=(weak_ptr&& __r) noexcept = default; template _Assignable> operator=(weak_ptr<_Yp>&& __r) noexcept { this->__weak_ptr<_Tp>::operator=(std::move(__r)); return *this; } shared_ptr<_Tp> lock() const noexcept { return shared_ptr<_Tp>(*this, std::nothrow); } }; #if __cpp_deduction_guides >= 201606 template weak_ptr(shared_ptr<_Tp>) -> weak_ptr<_Tp>; #endif // 20.7.2.3.6 weak_ptr specialized algorithms. template inline void swap(weak_ptr<_Tp>& __a, weak_ptr<_Tp>& __b) noexcept { __a.swap(__b); } /// Primary template owner_less template struct owner_less; /// Void specialization of owner_less template<> struct owner_less : _Sp_owner_less { }; /// Partial specialization of owner_less for shared_ptr. template struct owner_less> : public _Sp_owner_less, weak_ptr<_Tp>> { }; /// Partial specialization of owner_less for weak_ptr. template struct owner_less> : public _Sp_owner_less, shared_ptr<_Tp>> { }; /** * @brief Base class allowing use of member function shared_from_this. */ template class enable_shared_from_this { protected: constexpr enable_shared_from_this() noexcept { } enable_shared_from_this(const enable_shared_from_this&) noexcept { } enable_shared_from_this& operator=(const enable_shared_from_this&) noexcept { return *this; } ~enable_shared_from_this() { } public: shared_ptr<_Tp> shared_from_this() { return shared_ptr<_Tp>(this->_M_weak_this); } shared_ptr shared_from_this() const { return shared_ptr(this->_M_weak_this); } #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 #define __cpp_lib_enable_shared_from_this 201603 weak_ptr<_Tp> weak_from_this() noexcept { return this->_M_weak_this; } weak_ptr weak_from_this() const noexcept { return this->_M_weak_this; } #endif private: template void _M_weak_assign(_Tp1* __p, const __shared_count<>& __n) const noexcept { _M_weak_this._M_assign(__p, __n); } // Found by ADL when this is an associated class. friend const enable_shared_from_this* __enable_shared_from_this_base(const __shared_count<>&, const enable_shared_from_this* __p) { return __p; } template friend class __shared_ptr; mutable weak_ptr<_Tp> _M_weak_this; }; /** * @brief Create an object that is owned by a shared_ptr. * @param __a An allocator. * @param __args Arguments for the @a _Tp object's constructor. * @return A shared_ptr that owns the newly created object. * @throw An exception thrown from @a _Alloc::allocate or from the * constructor of @a _Tp. * * A copy of @a __a will be used to allocate memory for the shared_ptr * and the new object. */ template inline shared_ptr<_Tp> allocate_shared(const _Alloc& __a, _Args&&... __args) { static_assert(!is_array<_Tp>::value, "make_shared not supported"); return shared_ptr<_Tp>(_Sp_alloc_shared_tag<_Alloc>{__a}, std::forward<_Args>(__args)...); } /** * @brief Create an object that is owned by a shared_ptr. * @param __args Arguments for the @a _Tp object's constructor. * @return A shared_ptr that owns the newly created object. * @throw std::bad_alloc, or an exception thrown from the * constructor of @a _Tp. */ template inline shared_ptr<_Tp> make_shared(_Args&&... __args) { typedef typename std::remove_cv<_Tp>::type _Tp_nc; return std::allocate_shared<_Tp>(std::allocator<_Tp_nc>(), std::forward<_Args>(__args)...); } /// std::hash specialization for shared_ptr. template struct hash> : public __hash_base> { size_t operator()(const shared_ptr<_Tp>& __s) const noexcept { return std::hash::element_type*>()(__s.get()); } }; // @} group pointer_abstractions _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _SHARED_PTR_H PK!o)&)&8/bits/shared_ptr_atomic.hnu[// shared_ptr atomic access -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/shared_ptr_atomic.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _SHARED_PTR_ATOMIC_H #define _SHARED_PTR_ATOMIC_H 1 #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup pointer_abstractions * @{ */ struct _Sp_locker { _Sp_locker(const _Sp_locker&) = delete; _Sp_locker& operator=(const _Sp_locker&) = delete; #ifdef __GTHREADS explicit _Sp_locker(const void*) noexcept; _Sp_locker(const void*, const void*) noexcept; ~_Sp_locker(); private: unsigned char _M_key1; unsigned char _M_key2; #else explicit _Sp_locker(const void*, const void* = nullptr) { } #endif }; /** * @brief Report whether shared_ptr atomic operations are lock-free. * @param __p A non-null pointer to a shared_ptr object. * @return True if atomic access to @c *__p is lock-free, false otherwise. * @{ */ template inline bool atomic_is_lock_free(const __shared_ptr<_Tp, _Lp>* __p) { #ifdef __GTHREADS return __gthread_active_p() == 0; #else return true; #endif } template inline bool atomic_is_lock_free(const shared_ptr<_Tp>* __p) { return std::atomic_is_lock_free<_Tp, __default_lock_policy>(__p); } // @} /** * @brief Atomic load for shared_ptr objects. * @param __p A non-null pointer to a shared_ptr object. * @return @c *__p * * The memory order shall not be @c memory_order_release or * @c memory_order_acq_rel. * @{ */ template inline shared_ptr<_Tp> atomic_load_explicit(const shared_ptr<_Tp>* __p, memory_order) { _Sp_locker __lock{__p}; return *__p; } template inline shared_ptr<_Tp> atomic_load(const shared_ptr<_Tp>* __p) { return std::atomic_load_explicit(__p, memory_order_seq_cst); } template inline __shared_ptr<_Tp, _Lp> atomic_load_explicit(const __shared_ptr<_Tp, _Lp>* __p, memory_order) { _Sp_locker __lock{__p}; return *__p; } template inline __shared_ptr<_Tp, _Lp> atomic_load(const __shared_ptr<_Tp, _Lp>* __p) { return std::atomic_load_explicit(__p, memory_order_seq_cst); } // @} /** * @brief Atomic store for shared_ptr objects. * @param __p A non-null pointer to a shared_ptr object. * @param __r The value to store. * * The memory order shall not be @c memory_order_acquire or * @c memory_order_acq_rel. * @{ */ template inline void atomic_store_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r, memory_order) { _Sp_locker __lock{__p}; __p->swap(__r); // use swap so that **__p not destroyed while lock held } template inline void atomic_store(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r) { std::atomic_store_explicit(__p, std::move(__r), memory_order_seq_cst); } template inline void atomic_store_explicit(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp> __r, memory_order) { _Sp_locker __lock{__p}; __p->swap(__r); // use swap so that **__p not destroyed while lock held } template inline void atomic_store(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp> __r) { std::atomic_store_explicit(__p, std::move(__r), memory_order_seq_cst); } // @} /** * @brief Atomic exchange for shared_ptr objects. * @param __p A non-null pointer to a shared_ptr object. * @param __r New value to store in @c *__p. * @return The original value of @c *__p * @{ */ template inline shared_ptr<_Tp> atomic_exchange_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r, memory_order) { _Sp_locker __lock{__p}; __p->swap(__r); return __r; } template inline shared_ptr<_Tp> atomic_exchange(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r) { return std::atomic_exchange_explicit(__p, std::move(__r), memory_order_seq_cst); } template inline __shared_ptr<_Tp, _Lp> atomic_exchange_explicit(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp> __r, memory_order) { _Sp_locker __lock{__p}; __p->swap(__r); return __r; } template inline __shared_ptr<_Tp, _Lp> atomic_exchange(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp> __r) { return std::atomic_exchange_explicit(__p, std::move(__r), memory_order_seq_cst); } // @} /** * @brief Atomic compare-and-swap for shared_ptr objects. * @param __p A non-null pointer to a shared_ptr object. * @param __v A non-null pointer to a shared_ptr object. * @param __w A non-null pointer to a shared_ptr object. * @return True if @c *__p was equivalent to @c *__v, false otherwise. * * The memory order for failure shall not be @c memory_order_release or * @c memory_order_acq_rel, or stronger than the memory order for success. * @{ */ template bool atomic_compare_exchange_strong_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w, memory_order, memory_order) { shared_ptr<_Tp> __x; // goes out of scope after __lock _Sp_locker __lock{__p, __v}; owner_less> __less; if (*__p == *__v && !__less(*__p, *__v) && !__less(*__v, *__p)) { __x = std::move(*__p); *__p = std::move(__w); return true; } __x = std::move(*__v); *__v = *__p; return false; } template inline bool atomic_compare_exchange_strong(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w) { return std::atomic_compare_exchange_strong_explicit(__p, __v, std::move(__w), memory_order_seq_cst, memory_order_seq_cst); } template inline bool atomic_compare_exchange_weak_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w, memory_order __success, memory_order __failure) { return std::atomic_compare_exchange_strong_explicit(__p, __v, std::move(__w), __success, __failure); } template inline bool atomic_compare_exchange_weak(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w) { return std::atomic_compare_exchange_weak_explicit(__p, __v, std::move(__w), memory_order_seq_cst, memory_order_seq_cst); } template bool atomic_compare_exchange_strong_explicit(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp>* __v, __shared_ptr<_Tp, _Lp> __w, memory_order, memory_order) { __shared_ptr<_Tp, _Lp> __x; // goes out of scope after __lock _Sp_locker __lock{__p, __v}; owner_less<__shared_ptr<_Tp, _Lp>> __less; if (*__p == *__v && !__less(*__p, *__v) && !__less(*__v, *__p)) { __x = std::move(*__p); *__p = std::move(__w); return true; } __x = std::move(*__v); *__v = *__p; return false; } template inline bool atomic_compare_exchange_strong(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp>* __v, __shared_ptr<_Tp, _Lp> __w) { return std::atomic_compare_exchange_strong_explicit(__p, __v, std::move(__w), memory_order_seq_cst, memory_order_seq_cst); } template inline bool atomic_compare_exchange_weak_explicit(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp>* __v, __shared_ptr<_Tp, _Lp> __w, memory_order __success, memory_order __failure) { return std::atomic_compare_exchange_strong_explicit(__p, __v, std::move(__w), __success, __failure); } template inline bool atomic_compare_exchange_weak(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp>* __v, __shared_ptr<_Tp, _Lp> __w) { return std::atomic_compare_exchange_weak_explicit(__p, __v, std::move(__w), memory_order_seq_cst, memory_order_seq_cst); } // @} // @} group pointer_abstractions _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _SHARED_PTR_ATOMIC_H PK!_8/bits/shared_ptr_base.hnu[// shared_ptr and weak_ptr implementation details -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // GCC Note: Based on files from version 1.32.0 of the Boost library. // shared_count.hpp // Copyright (c) 2001, 2002, 2003 Peter Dimov and Multi Media Ltd. // shared_ptr.hpp // Copyright (C) 1998, 1999 Greg Colvin and Beman Dawes. // Copyright (C) 2001, 2002, 2003 Peter Dimov // weak_ptr.hpp // Copyright (C) 2001, 2002, 2003 Peter Dimov // enable_shared_from_this.hpp // Copyright (C) 2002 Peter Dimov // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) /** @file bits/shared_ptr_base.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _SHARED_PTR_BASE_H #define _SHARED_PTR_BASE_H 1 #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" template class auto_ptr; #pragma GCC diagnostic pop #endif /** * @brief Exception possibly thrown by @c shared_ptr. * @ingroup exceptions */ class bad_weak_ptr : public std::exception { public: virtual char const* what() const noexcept; virtual ~bad_weak_ptr() noexcept; }; // Substitute for bad_weak_ptr object in the case of -fno-exceptions. inline void __throw_bad_weak_ptr() { _GLIBCXX_THROW_OR_ABORT(bad_weak_ptr()); } using __gnu_cxx::_Lock_policy; using __gnu_cxx::__default_lock_policy; using __gnu_cxx::_S_single; using __gnu_cxx::_S_mutex; using __gnu_cxx::_S_atomic; // Empty helper class except when the template argument is _S_mutex. template<_Lock_policy _Lp> class _Mutex_base { protected: // The atomic policy uses fully-fenced builtins, single doesn't care. enum { _S_need_barriers = 0 }; }; template<> class _Mutex_base<_S_mutex> : public __gnu_cxx::__mutex { protected: // This policy is used when atomic builtins are not available. // The replacement atomic operations might not have the necessary // memory barriers. enum { _S_need_barriers = 1 }; }; template<_Lock_policy _Lp = __default_lock_policy> class _Sp_counted_base : public _Mutex_base<_Lp> { public: _Sp_counted_base() noexcept : _M_use_count(1), _M_weak_count(1) { } virtual ~_Sp_counted_base() noexcept { } // Called when _M_use_count drops to zero, to release the resources // managed by *this. virtual void _M_dispose() noexcept = 0; // Called when _M_weak_count drops to zero. virtual void _M_destroy() noexcept { delete this; } virtual void* _M_get_deleter(const std::type_info&) noexcept = 0; void _M_add_ref_copy() { __gnu_cxx::__atomic_add_dispatch(&_M_use_count, 1); } void _M_add_ref_lock(); bool _M_add_ref_lock_nothrow(); void _M_release() noexcept { // Be race-detector-friendly. For more info see bits/c++config. _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_use_count); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_use_count, -1) == 1) { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_use_count); _M_dispose(); // There must be a memory barrier between dispose() and destroy() // to ensure that the effects of dispose() are observed in the // thread that runs destroy(). // See http://gcc.gnu.org/ml/libstdc++/2005-11/msg00136.html if (_Mutex_base<_Lp>::_S_need_barriers) { __atomic_thread_fence (__ATOMIC_ACQ_REL); } // Be race-detector-friendly. For more info see bits/c++config. _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_weak_count); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_weak_count, -1) == 1) { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_weak_count); _M_destroy(); } } } void _M_weak_add_ref() noexcept { __gnu_cxx::__atomic_add_dispatch(&_M_weak_count, 1); } void _M_weak_release() noexcept { // Be race-detector-friendly. For more info see bits/c++config. _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_weak_count); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_weak_count, -1) == 1) { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_weak_count); if (_Mutex_base<_Lp>::_S_need_barriers) { // See _M_release(), // destroy() must observe results of dispose() __atomic_thread_fence (__ATOMIC_ACQ_REL); } _M_destroy(); } } long _M_get_use_count() const noexcept { // No memory barrier is used here so there is no synchronization // with other threads. return __atomic_load_n(&_M_use_count, __ATOMIC_RELAXED); } private: _Sp_counted_base(_Sp_counted_base const&) = delete; _Sp_counted_base& operator=(_Sp_counted_base const&) = delete; _Atomic_word _M_use_count; // #shared _Atomic_word _M_weak_count; // #weak + (#shared != 0) }; template<> inline void _Sp_counted_base<_S_single>:: _M_add_ref_lock() { if (_M_use_count == 0) __throw_bad_weak_ptr(); ++_M_use_count; } template<> inline void _Sp_counted_base<_S_mutex>:: _M_add_ref_lock() { __gnu_cxx::__scoped_lock sentry(*this); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_use_count, 1) == 0) { _M_use_count = 0; __throw_bad_weak_ptr(); } } template<> inline void _Sp_counted_base<_S_atomic>:: _M_add_ref_lock() { // Perform lock-free add-if-not-zero operation. _Atomic_word __count = _M_get_use_count(); do { if (__count == 0) __throw_bad_weak_ptr(); // Replace the current counter value with the old value + 1, as // long as it's not changed meanwhile. } while (!__atomic_compare_exchange_n(&_M_use_count, &__count, __count + 1, true, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)); } template<> inline bool _Sp_counted_base<_S_single>:: _M_add_ref_lock_nothrow() { if (_M_use_count == 0) return false; ++_M_use_count; return true; } template<> inline bool _Sp_counted_base<_S_mutex>:: _M_add_ref_lock_nothrow() { __gnu_cxx::__scoped_lock sentry(*this); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_use_count, 1) == 0) { _M_use_count = 0; return false; } return true; } template<> inline bool _Sp_counted_base<_S_atomic>:: _M_add_ref_lock_nothrow() { // Perform lock-free add-if-not-zero operation. _Atomic_word __count = _M_get_use_count(); do { if (__count == 0) return false; // Replace the current counter value with the old value + 1, as // long as it's not changed meanwhile. } while (!__atomic_compare_exchange_n(&_M_use_count, &__count, __count + 1, true, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)); return true; } template<> inline void _Sp_counted_base<_S_single>::_M_add_ref_copy() { ++_M_use_count; } template<> inline void _Sp_counted_base<_S_single>::_M_release() noexcept { if (--_M_use_count == 0) { _M_dispose(); if (--_M_weak_count == 0) _M_destroy(); } } template<> inline void _Sp_counted_base<_S_single>::_M_weak_add_ref() noexcept { ++_M_weak_count; } template<> inline void _Sp_counted_base<_S_single>::_M_weak_release() noexcept { if (--_M_weak_count == 0) _M_destroy(); } template<> inline long _Sp_counted_base<_S_single>::_M_get_use_count() const noexcept { return _M_use_count; } // Forward declarations. template class __shared_ptr; template class __weak_ptr; template class __enable_shared_from_this; template class shared_ptr; template class weak_ptr; template struct owner_less; template class enable_shared_from_this; template<_Lock_policy _Lp = __default_lock_policy> class __weak_count; template<_Lock_policy _Lp = __default_lock_policy> class __shared_count; // Counted ptr with no deleter or allocator support template class _Sp_counted_ptr final : public _Sp_counted_base<_Lp> { public: explicit _Sp_counted_ptr(_Ptr __p) noexcept : _M_ptr(__p) { } virtual void _M_dispose() noexcept { delete _M_ptr; } virtual void _M_destroy() noexcept { delete this; } virtual void* _M_get_deleter(const std::type_info&) noexcept { return nullptr; } _Sp_counted_ptr(const _Sp_counted_ptr&) = delete; _Sp_counted_ptr& operator=(const _Sp_counted_ptr&) = delete; private: _Ptr _M_ptr; }; template<> inline void _Sp_counted_ptr::_M_dispose() noexcept { } template<> inline void _Sp_counted_ptr::_M_dispose() noexcept { } template<> inline void _Sp_counted_ptr::_M_dispose() noexcept { } template struct _Sp_ebo_helper; /// Specialization using EBO. template struct _Sp_ebo_helper<_Nm, _Tp, true> : private _Tp { explicit _Sp_ebo_helper(const _Tp& __tp) : _Tp(__tp) { } explicit _Sp_ebo_helper(_Tp&& __tp) : _Tp(std::move(__tp)) { } static _Tp& _S_get(_Sp_ebo_helper& __eboh) { return static_cast<_Tp&>(__eboh); } }; /// Specialization not using EBO. template struct _Sp_ebo_helper<_Nm, _Tp, false> { explicit _Sp_ebo_helper(const _Tp& __tp) : _M_tp(__tp) { } explicit _Sp_ebo_helper(_Tp&& __tp) : _M_tp(std::move(__tp)) { } static _Tp& _S_get(_Sp_ebo_helper& __eboh) { return __eboh._M_tp; } private: _Tp _M_tp; }; // Support for custom deleter and/or allocator template class _Sp_counted_deleter final : public _Sp_counted_base<_Lp> { class _Impl : _Sp_ebo_helper<0, _Deleter>, _Sp_ebo_helper<1, _Alloc> { typedef _Sp_ebo_helper<0, _Deleter> _Del_base; typedef _Sp_ebo_helper<1, _Alloc> _Alloc_base; public: _Impl(_Ptr __p, _Deleter __d, const _Alloc& __a) noexcept : _M_ptr(__p), _Del_base(std::move(__d)), _Alloc_base(__a) { } _Deleter& _M_del() noexcept { return _Del_base::_S_get(*this); } _Alloc& _M_alloc() noexcept { return _Alloc_base::_S_get(*this); } _Ptr _M_ptr; }; public: using __allocator_type = __alloc_rebind<_Alloc, _Sp_counted_deleter>; // __d(__p) must not throw. _Sp_counted_deleter(_Ptr __p, _Deleter __d) noexcept : _M_impl(__p, std::move(__d), _Alloc()) { } // __d(__p) must not throw. _Sp_counted_deleter(_Ptr __p, _Deleter __d, const _Alloc& __a) noexcept : _M_impl(__p, std::move(__d), __a) { } ~_Sp_counted_deleter() noexcept { } virtual void _M_dispose() noexcept { _M_impl._M_del()(_M_impl._M_ptr); } virtual void _M_destroy() noexcept { __allocator_type __a(_M_impl._M_alloc()); __allocated_ptr<__allocator_type> __guard_ptr{ __a, this }; this->~_Sp_counted_deleter(); } virtual void* _M_get_deleter(const std::type_info& __ti) noexcept { #if __cpp_rtti // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2400. shared_ptr's get_deleter() should use addressof() return __ti == typeid(_Deleter) ? std::__addressof(_M_impl._M_del()) : nullptr; #else return nullptr; #endif } private: _Impl _M_impl; }; // helpers for make_shared / allocate_shared struct _Sp_make_shared_tag { private: template friend class _Sp_counted_ptr_inplace; static const type_info& _S_ti() noexcept _GLIBCXX_VISIBILITY(default) { alignas(type_info) static constexpr char __tag[sizeof(type_info)] = { }; return reinterpret_cast(__tag); } }; template struct _Sp_alloc_shared_tag { const _Alloc& _M_a; }; template class _Sp_counted_ptr_inplace final : public _Sp_counted_base<_Lp> { class _Impl : _Sp_ebo_helper<0, _Alloc> { typedef _Sp_ebo_helper<0, _Alloc> _A_base; public: explicit _Impl(_Alloc __a) noexcept : _A_base(__a) { } _Alloc& _M_alloc() noexcept { return _A_base::_S_get(*this); } __gnu_cxx::__aligned_buffer<_Tp> _M_storage; }; public: using __allocator_type = __alloc_rebind<_Alloc, _Sp_counted_ptr_inplace>; template _Sp_counted_ptr_inplace(_Alloc __a, _Args&&... __args) : _M_impl(__a) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2070. allocate_shared should use allocator_traits::construct allocator_traits<_Alloc>::construct(__a, _M_ptr(), std::forward<_Args>(__args)...); // might throw } ~_Sp_counted_ptr_inplace() noexcept { } virtual void _M_dispose() noexcept { allocator_traits<_Alloc>::destroy(_M_impl._M_alloc(), _M_ptr()); } // Override because the allocator needs to know the dynamic type virtual void _M_destroy() noexcept { __allocator_type __a(_M_impl._M_alloc()); __allocated_ptr<__allocator_type> __guard_ptr{ __a, this }; this->~_Sp_counted_ptr_inplace(); } private: friend class __shared_count<_Lp>; // To be able to call _M_ptr(). // No longer used, but code compiled against old libstdc++ headers // might still call it from __shared_ptr ctor to get the pointer out. virtual void* _M_get_deleter(const std::type_info& __ti) noexcept override { // Check for the fake type_info first, so we don't try to access it // as a real type_info object. if (&__ti == &_Sp_make_shared_tag::_S_ti()) return const_cast::type*>(_M_ptr()); #if __cpp_rtti // Callers compiled with old libstdc++ headers and RTTI enabled // might pass this instead: else if (__ti == typeid(_Sp_make_shared_tag)) return const_cast::type*>(_M_ptr()); #else // Cannot detect a real type_info object. If the linker keeps a // definition of this function compiled with -fno-rtti then callers // that have RTTI enabled and pass a real type_info object will get // a null pointer returned. #endif return nullptr; } _Tp* _M_ptr() noexcept { return _M_impl._M_storage._M_ptr(); } _Impl _M_impl; }; // The default deleter for shared_ptr and shared_ptr. struct __sp_array_delete { template void operator()(_Yp* __p) const { delete[] __p; } }; template<_Lock_policy _Lp> class __shared_count { template struct __not_alloc_shared_tag { using type = void; }; template struct __not_alloc_shared_tag<_Sp_alloc_shared_tag<_Tp>> { }; public: constexpr __shared_count() noexcept : _M_pi(0) { } template explicit __shared_count(_Ptr __p) : _M_pi(0) { __try { _M_pi = new _Sp_counted_ptr<_Ptr, _Lp>(__p); } __catch(...) { delete __p; __throw_exception_again; } } template __shared_count(_Ptr __p, /* is_array = */ false_type) : __shared_count(__p) { } template __shared_count(_Ptr __p, /* is_array = */ true_type) : __shared_count(__p, __sp_array_delete{}, allocator()) { } template::type> __shared_count(_Ptr __p, _Deleter __d) : __shared_count(__p, std::move(__d), allocator()) { } template::type> __shared_count(_Ptr __p, _Deleter __d, _Alloc __a) : _M_pi(0) { typedef _Sp_counted_deleter<_Ptr, _Deleter, _Alloc, _Lp> _Sp_cd_type; __try { typename _Sp_cd_type::__allocator_type __a2(__a); auto __guard = std::__allocate_guarded(__a2); _Sp_cd_type* __mem = __guard.get(); ::new (__mem) _Sp_cd_type(__p, std::move(__d), std::move(__a)); _M_pi = __mem; __guard = nullptr; } __catch(...) { __d(__p); // Call _Deleter on __p. __throw_exception_again; } } template __shared_count(_Tp*& __p, _Sp_alloc_shared_tag<_Alloc> __a, _Args&&... __args) { typedef _Sp_counted_ptr_inplace<_Tp, _Alloc, _Lp> _Sp_cp_type; typename _Sp_cp_type::__allocator_type __a2(__a._M_a); auto __guard = std::__allocate_guarded(__a2); _Sp_cp_type* __mem = __guard.get(); auto __pi = ::new (__mem) _Sp_cp_type(__a._M_a, std::forward<_Args>(__args)...); __guard = nullptr; _M_pi = __pi; __p = __pi->_M_ptr(); } #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" // Special case for auto_ptr<_Tp> to provide the strong guarantee. template explicit __shared_count(std::auto_ptr<_Tp>&& __r); #pragma GCC diagnostic pop #endif // Special case for unique_ptr<_Tp,_Del> to provide the strong guarantee. template explicit __shared_count(std::unique_ptr<_Tp, _Del>&& __r) : _M_pi(0) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2415. Inconsistency between unique_ptr and shared_ptr if (__r.get() == nullptr) return; using _Ptr = typename unique_ptr<_Tp, _Del>::pointer; using _Del2 = typename conditional::value, reference_wrapper::type>, _Del>::type; using _Sp_cd_type = _Sp_counted_deleter<_Ptr, _Del2, allocator, _Lp>; using _Alloc = allocator<_Sp_cd_type>; using _Alloc_traits = allocator_traits<_Alloc>; _Alloc __a; _Sp_cd_type* __mem = _Alloc_traits::allocate(__a, 1); _Alloc_traits::construct(__a, __mem, __r.release(), __r.get_deleter()); // non-throwing _M_pi = __mem; } // Throw bad_weak_ptr when __r._M_get_use_count() == 0. explicit __shared_count(const __weak_count<_Lp>& __r); // Does not throw if __r._M_get_use_count() == 0, caller must check. explicit __shared_count(const __weak_count<_Lp>& __r, std::nothrow_t); ~__shared_count() noexcept { if (_M_pi != nullptr) _M_pi->_M_release(); } __shared_count(const __shared_count& __r) noexcept : _M_pi(__r._M_pi) { if (_M_pi != 0) _M_pi->_M_add_ref_copy(); } __shared_count& operator=(const __shared_count& __r) noexcept { _Sp_counted_base<_Lp>* __tmp = __r._M_pi; if (__tmp != _M_pi) { if (__tmp != 0) __tmp->_M_add_ref_copy(); if (_M_pi != 0) _M_pi->_M_release(); _M_pi = __tmp; } return *this; } void _M_swap(__shared_count& __r) noexcept { _Sp_counted_base<_Lp>* __tmp = __r._M_pi; __r._M_pi = _M_pi; _M_pi = __tmp; } long _M_get_use_count() const noexcept { return _M_pi != 0 ? _M_pi->_M_get_use_count() : 0; } bool _M_unique() const noexcept { return this->_M_get_use_count() == 1; } void* _M_get_deleter(const std::type_info& __ti) const noexcept { return _M_pi ? _M_pi->_M_get_deleter(__ti) : nullptr; } bool _M_less(const __shared_count& __rhs) const noexcept { return std::less<_Sp_counted_base<_Lp>*>()(this->_M_pi, __rhs._M_pi); } bool _M_less(const __weak_count<_Lp>& __rhs) const noexcept { return std::less<_Sp_counted_base<_Lp>*>()(this->_M_pi, __rhs._M_pi); } // Friend function injected into enclosing namespace and found by ADL friend inline bool operator==(const __shared_count& __a, const __shared_count& __b) noexcept { return __a._M_pi == __b._M_pi; } private: friend class __weak_count<_Lp>; _Sp_counted_base<_Lp>* _M_pi; }; template<_Lock_policy _Lp> class __weak_count { public: constexpr __weak_count() noexcept : _M_pi(nullptr) { } __weak_count(const __shared_count<_Lp>& __r) noexcept : _M_pi(__r._M_pi) { if (_M_pi != nullptr) _M_pi->_M_weak_add_ref(); } __weak_count(const __weak_count& __r) noexcept : _M_pi(__r._M_pi) { if (_M_pi != nullptr) _M_pi->_M_weak_add_ref(); } __weak_count(__weak_count&& __r) noexcept : _M_pi(__r._M_pi) { __r._M_pi = nullptr; } ~__weak_count() noexcept { if (_M_pi != nullptr) _M_pi->_M_weak_release(); } __weak_count& operator=(const __shared_count<_Lp>& __r) noexcept { _Sp_counted_base<_Lp>* __tmp = __r._M_pi; if (__tmp != nullptr) __tmp->_M_weak_add_ref(); if (_M_pi != nullptr) _M_pi->_M_weak_release(); _M_pi = __tmp; return *this; } __weak_count& operator=(const __weak_count& __r) noexcept { _Sp_counted_base<_Lp>* __tmp = __r._M_pi; if (__tmp != nullptr) __tmp->_M_weak_add_ref(); if (_M_pi != nullptr) _M_pi->_M_weak_release(); _M_pi = __tmp; return *this; } __weak_count& operator=(__weak_count&& __r) noexcept { if (_M_pi != nullptr) _M_pi->_M_weak_release(); _M_pi = __r._M_pi; __r._M_pi = nullptr; return *this; } void _M_swap(__weak_count& __r) noexcept { _Sp_counted_base<_Lp>* __tmp = __r._M_pi; __r._M_pi = _M_pi; _M_pi = __tmp; } long _M_get_use_count() const noexcept { return _M_pi != nullptr ? _M_pi->_M_get_use_count() : 0; } bool _M_less(const __weak_count& __rhs) const noexcept { return std::less<_Sp_counted_base<_Lp>*>()(this->_M_pi, __rhs._M_pi); } bool _M_less(const __shared_count<_Lp>& __rhs) const noexcept { return std::less<_Sp_counted_base<_Lp>*>()(this->_M_pi, __rhs._M_pi); } // Friend function injected into enclosing namespace and found by ADL friend inline bool operator==(const __weak_count& __a, const __weak_count& __b) noexcept { return __a._M_pi == __b._M_pi; } private: friend class __shared_count<_Lp>; _Sp_counted_base<_Lp>* _M_pi; }; // Now that __weak_count is defined we can define this constructor: template<_Lock_policy _Lp> inline __shared_count<_Lp>::__shared_count(const __weak_count<_Lp>& __r) : _M_pi(__r._M_pi) { if (_M_pi != nullptr) _M_pi->_M_add_ref_lock(); else __throw_bad_weak_ptr(); } // Now that __weak_count is defined we can define this constructor: template<_Lock_policy _Lp> inline __shared_count<_Lp>:: __shared_count(const __weak_count<_Lp>& __r, std::nothrow_t) : _M_pi(__r._M_pi) { if (_M_pi != nullptr) if (!_M_pi->_M_add_ref_lock_nothrow()) _M_pi = nullptr; } #define __cpp_lib_shared_ptr_arrays 201603 // Helper traits for shared_ptr of array: // A pointer type Y* is said to be compatible with a pointer type T* when // either Y* is convertible to T* or Y is U[N] and T is U cv []. template struct __sp_compatible_with : false_type { }; template struct __sp_compatible_with<_Yp*, _Tp*> : is_convertible<_Yp*, _Tp*>::type { }; template struct __sp_compatible_with<_Up(*)[_Nm], _Up(*)[]> : true_type { }; template struct __sp_compatible_with<_Up(*)[_Nm], const _Up(*)[]> : true_type { }; template struct __sp_compatible_with<_Up(*)[_Nm], volatile _Up(*)[]> : true_type { }; template struct __sp_compatible_with<_Up(*)[_Nm], const volatile _Up(*)[]> : true_type { }; // Test conversion from Y(*)[N] to U(*)[N] without forming invalid type Y[N]. template struct __sp_is_constructible_arrN : false_type { }; template struct __sp_is_constructible_arrN<_Up, _Nm, _Yp, __void_t<_Yp[_Nm]>> : is_convertible<_Yp(*)[_Nm], _Up(*)[_Nm]>::type { }; // Test conversion from Y(*)[] to U(*)[] without forming invalid type Y[]. template struct __sp_is_constructible_arr : false_type { }; template struct __sp_is_constructible_arr<_Up, _Yp, __void_t<_Yp[]>> : is_convertible<_Yp(*)[], _Up(*)[]>::type { }; // Trait to check if shared_ptr can be constructed from Y*. template struct __sp_is_constructible; // When T is U[N], Y(*)[N] shall be convertible to T*; template struct __sp_is_constructible<_Up[_Nm], _Yp> : __sp_is_constructible_arrN<_Up, _Nm, _Yp>::type { }; // when T is U[], Y(*)[] shall be convertible to T*; template struct __sp_is_constructible<_Up[], _Yp> : __sp_is_constructible_arr<_Up, _Yp>::type { }; // otherwise, Y* shall be convertible to T*. template struct __sp_is_constructible : is_convertible<_Yp*, _Tp*>::type { }; // Define operator* and operator-> for shared_ptr. template::value, bool = is_void<_Tp>::value> class __shared_ptr_access { public: using element_type = _Tp; element_type& operator*() const noexcept { __glibcxx_assert(_M_get() != nullptr); return *_M_get(); } element_type* operator->() const noexcept { _GLIBCXX_DEBUG_PEDASSERT(_M_get() != nullptr); return _M_get(); } private: element_type* _M_get() const noexcept { return static_cast*>(this)->get(); } }; // Define operator-> for shared_ptr. template class __shared_ptr_access<_Tp, _Lp, false, true> { public: using element_type = _Tp; element_type* operator->() const noexcept { auto __ptr = static_cast*>(this)->get(); _GLIBCXX_DEBUG_PEDASSERT(__ptr != nullptr); return __ptr; } }; // Define operator[] for shared_ptr and shared_ptr. template class __shared_ptr_access<_Tp, _Lp, true, false> { public: using element_type = typename remove_extent<_Tp>::type; #if __cplusplus <= 201402L [[__deprecated__("shared_ptr::operator* is absent from C++17")]] element_type& operator*() const noexcept { __glibcxx_assert(_M_get() != nullptr); return *_M_get(); } [[__deprecated__("shared_ptr::operator-> is absent from C++17")]] element_type* operator->() const noexcept { _GLIBCXX_DEBUG_PEDASSERT(_M_get() != nullptr); return _M_get(); } #endif element_type& operator[](ptrdiff_t __i) const { __glibcxx_assert(_M_get() != nullptr); __glibcxx_assert(!extent<_Tp>::value || __i < extent<_Tp>::value); return _M_get()[__i]; } private: element_type* _M_get() const noexcept { return static_cast*>(this)->get(); } }; template class __shared_ptr : public __shared_ptr_access<_Tp, _Lp> { public: using element_type = typename remove_extent<_Tp>::type; private: // Constraint for taking ownership of a pointer of type _Yp*: template using _SafeConv = typename enable_if<__sp_is_constructible<_Tp, _Yp>::value>::type; // Constraint for construction from shared_ptr and weak_ptr: template using _Compatible = typename enable_if<__sp_compatible_with<_Yp*, _Tp*>::value, _Res>::type; // Constraint for assignment from shared_ptr and weak_ptr: template using _Assignable = _Compatible<_Yp, __shared_ptr&>; // Constraint for construction from unique_ptr: template::pointer> using _UniqCompatible = typename enable_if<__and_< __sp_compatible_with<_Yp*, _Tp*>, is_convertible<_Ptr, element_type*> >::value, _Res>::type; // Constraint for assignment from unique_ptr: template using _UniqAssignable = _UniqCompatible<_Yp, _Del, __shared_ptr&>; public: #if __cplusplus > 201402L using weak_type = __weak_ptr<_Tp, _Lp>; #endif constexpr __shared_ptr() noexcept : _M_ptr(0), _M_refcount() { } template> explicit __shared_ptr(_Yp* __p) : _M_ptr(__p), _M_refcount(__p, typename is_array<_Tp>::type()) { static_assert( !is_void<_Yp>::value, "incomplete type" ); static_assert( sizeof(_Yp) > 0, "incomplete type" ); _M_enable_shared_from_this_with(__p); } template> __shared_ptr(_Yp* __p, _Deleter __d) : _M_ptr(__p), _M_refcount(__p, std::move(__d)) { static_assert(__is_invocable<_Deleter&, _Yp*&>::value, "deleter expression d(p) is well-formed"); _M_enable_shared_from_this_with(__p); } template> __shared_ptr(_Yp* __p, _Deleter __d, _Alloc __a) : _M_ptr(__p), _M_refcount(__p, std::move(__d), std::move(__a)) { static_assert(__is_invocable<_Deleter&, _Yp*&>::value, "deleter expression d(p) is well-formed"); _M_enable_shared_from_this_with(__p); } template __shared_ptr(nullptr_t __p, _Deleter __d) : _M_ptr(0), _M_refcount(__p, std::move(__d)) { } template __shared_ptr(nullptr_t __p, _Deleter __d, _Alloc __a) : _M_ptr(0), _M_refcount(__p, std::move(__d), std::move(__a)) { } template __shared_ptr(const __shared_ptr<_Yp, _Lp>& __r, element_type* __p) noexcept : _M_ptr(__p), _M_refcount(__r._M_refcount) // never throws { } __shared_ptr(const __shared_ptr&) noexcept = default; __shared_ptr& operator=(const __shared_ptr&) noexcept = default; ~__shared_ptr() = default; template> __shared_ptr(const __shared_ptr<_Yp, _Lp>& __r) noexcept : _M_ptr(__r._M_ptr), _M_refcount(__r._M_refcount) { } __shared_ptr(__shared_ptr&& __r) noexcept : _M_ptr(__r._M_ptr), _M_refcount() { _M_refcount._M_swap(__r._M_refcount); __r._M_ptr = 0; } template> __shared_ptr(__shared_ptr<_Yp, _Lp>&& __r) noexcept : _M_ptr(__r._M_ptr), _M_refcount() { _M_refcount._M_swap(__r._M_refcount); __r._M_ptr = 0; } template> explicit __shared_ptr(const __weak_ptr<_Yp, _Lp>& __r) : _M_refcount(__r._M_refcount) // may throw { // It is now safe to copy __r._M_ptr, as // _M_refcount(__r._M_refcount) did not throw. _M_ptr = __r._M_ptr; } // If an exception is thrown this constructor has no effect. template> __shared_ptr(unique_ptr<_Yp, _Del>&& __r) : _M_ptr(__r.get()), _M_refcount() { auto __raw = __to_address(__r.get()); _M_refcount = __shared_count<_Lp>(std::move(__r)); _M_enable_shared_from_this_with(__raw); } #if __cplusplus <= 201402L && _GLIBCXX_USE_DEPRECATED protected: // If an exception is thrown this constructor has no effect. template>, is_array<_Tp1>, is_convertible::pointer, _Tp*> >::value, bool>::type = true> __shared_ptr(unique_ptr<_Tp1, _Del>&& __r, __sp_array_delete) : _M_ptr(__r.get()), _M_refcount() { auto __raw = __to_address(__r.get()); _M_refcount = __shared_count<_Lp>(std::move(__r)); _M_enable_shared_from_this_with(__raw); } public: #endif #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" // Postcondition: use_count() == 1 and __r.get() == 0 template> __shared_ptr(auto_ptr<_Yp>&& __r); #pragma GCC diagnostic pop #endif constexpr __shared_ptr(nullptr_t) noexcept : __shared_ptr() { } template _Assignable<_Yp> operator=(const __shared_ptr<_Yp, _Lp>& __r) noexcept { _M_ptr = __r._M_ptr; _M_refcount = __r._M_refcount; // __shared_count::op= doesn't throw return *this; } #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" template _Assignable<_Yp> operator=(auto_ptr<_Yp>&& __r) { __shared_ptr(std::move(__r)).swap(*this); return *this; } #pragma GCC diagnostic pop #endif __shared_ptr& operator=(__shared_ptr&& __r) noexcept { __shared_ptr(std::move(__r)).swap(*this); return *this; } template _Assignable<_Yp> operator=(__shared_ptr<_Yp, _Lp>&& __r) noexcept { __shared_ptr(std::move(__r)).swap(*this); return *this; } template _UniqAssignable<_Yp, _Del> operator=(unique_ptr<_Yp, _Del>&& __r) { __shared_ptr(std::move(__r)).swap(*this); return *this; } void reset() noexcept { __shared_ptr().swap(*this); } template _SafeConv<_Yp> reset(_Yp* __p) // _Yp must be complete. { // Catch self-reset errors. __glibcxx_assert(__p == 0 || __p != _M_ptr); __shared_ptr(__p).swap(*this); } template _SafeConv<_Yp> reset(_Yp* __p, _Deleter __d) { __shared_ptr(__p, std::move(__d)).swap(*this); } template _SafeConv<_Yp> reset(_Yp* __p, _Deleter __d, _Alloc __a) { __shared_ptr(__p, std::move(__d), std::move(__a)).swap(*this); } element_type* get() const noexcept { return _M_ptr; } explicit operator bool() const // never throws { return _M_ptr == 0 ? false : true; } bool unique() const noexcept { return _M_refcount._M_unique(); } long use_count() const noexcept { return _M_refcount._M_get_use_count(); } void swap(__shared_ptr<_Tp, _Lp>& __other) noexcept { std::swap(_M_ptr, __other._M_ptr); _M_refcount._M_swap(__other._M_refcount); } template bool owner_before(__shared_ptr<_Tp1, _Lp> const& __rhs) const noexcept { return _M_refcount._M_less(__rhs._M_refcount); } template bool owner_before(__weak_ptr<_Tp1, _Lp> const& __rhs) const noexcept { return _M_refcount._M_less(__rhs._M_refcount); } protected: // This constructor is non-standard, it is used by allocate_shared. template __shared_ptr(_Sp_alloc_shared_tag<_Alloc> __tag, _Args&&... __args) : _M_ptr(), _M_refcount(_M_ptr, __tag, std::forward<_Args>(__args)...) { _M_enable_shared_from_this_with(_M_ptr); } template friend __shared_ptr<_Tp1, _Lp1> __allocate_shared(const _Alloc& __a, _Args&&... __args); // This constructor is used by __weak_ptr::lock() and // shared_ptr::shared_ptr(const weak_ptr&, std::nothrow_t). __shared_ptr(const __weak_ptr<_Tp, _Lp>& __r, std::nothrow_t) : _M_refcount(__r._M_refcount, std::nothrow) { _M_ptr = _M_refcount._M_get_use_count() ? __r._M_ptr : nullptr; } friend class __weak_ptr<_Tp, _Lp>; private: template using __esft_base_t = decltype(__enable_shared_from_this_base( std::declval&>(), std::declval<_Yp*>())); // Detect an accessible and unambiguous enable_shared_from_this base. template struct __has_esft_base : false_type { }; template struct __has_esft_base<_Yp, __void_t<__esft_base_t<_Yp>>> : __not_> { }; // No enable shared_from_this for arrays template::type> typename enable_if<__has_esft_base<_Yp2>::value>::type _M_enable_shared_from_this_with(_Yp* __p) noexcept { if (auto __base = __enable_shared_from_this_base(_M_refcount, __p)) __base->_M_weak_assign(const_cast<_Yp2*>(__p), _M_refcount); } template::type> typename enable_if::value>::type _M_enable_shared_from_this_with(_Yp*) noexcept { } void* _M_get_deleter(const std::type_info& __ti) const noexcept { return _M_refcount._M_get_deleter(__ti); } template friend class __shared_ptr; template friend class __weak_ptr; template friend _Del* get_deleter(const __shared_ptr<_Tp1, _Lp1>&) noexcept; template friend _Del* get_deleter(const shared_ptr<_Tp1>&) noexcept; element_type* _M_ptr; // Contained pointer. __shared_count<_Lp> _M_refcount; // Reference counter. }; // 20.7.2.2.7 shared_ptr comparisons template inline bool operator==(const __shared_ptr<_Tp1, _Lp>& __a, const __shared_ptr<_Tp2, _Lp>& __b) noexcept { return __a.get() == __b.get(); } template inline bool operator==(const __shared_ptr<_Tp, _Lp>& __a, nullptr_t) noexcept { return !__a; } template inline bool operator==(nullptr_t, const __shared_ptr<_Tp, _Lp>& __a) noexcept { return !__a; } template inline bool operator!=(const __shared_ptr<_Tp1, _Lp>& __a, const __shared_ptr<_Tp2, _Lp>& __b) noexcept { return __a.get() != __b.get(); } template inline bool operator!=(const __shared_ptr<_Tp, _Lp>& __a, nullptr_t) noexcept { return (bool)__a; } template inline bool operator!=(nullptr_t, const __shared_ptr<_Tp, _Lp>& __a) noexcept { return (bool)__a; } template inline bool operator<(const __shared_ptr<_Tp, _Lp>& __a, const __shared_ptr<_Up, _Lp>& __b) noexcept { using _Tp_elt = typename __shared_ptr<_Tp, _Lp>::element_type; using _Up_elt = typename __shared_ptr<_Up, _Lp>::element_type; using _Vp = typename common_type<_Tp_elt*, _Up_elt*>::type; return less<_Vp>()(__a.get(), __b.get()); } template inline bool operator<(const __shared_ptr<_Tp, _Lp>& __a, nullptr_t) noexcept { using _Tp_elt = typename __shared_ptr<_Tp, _Lp>::element_type; return less<_Tp_elt*>()(__a.get(), nullptr); } template inline bool operator<(nullptr_t, const __shared_ptr<_Tp, _Lp>& __a) noexcept { using _Tp_elt = typename __shared_ptr<_Tp, _Lp>::element_type; return less<_Tp_elt*>()(nullptr, __a.get()); } template inline bool operator<=(const __shared_ptr<_Tp1, _Lp>& __a, const __shared_ptr<_Tp2, _Lp>& __b) noexcept { return !(__b < __a); } template inline bool operator<=(const __shared_ptr<_Tp, _Lp>& __a, nullptr_t) noexcept { return !(nullptr < __a); } template inline bool operator<=(nullptr_t, const __shared_ptr<_Tp, _Lp>& __a) noexcept { return !(__a < nullptr); } template inline bool operator>(const __shared_ptr<_Tp1, _Lp>& __a, const __shared_ptr<_Tp2, _Lp>& __b) noexcept { return (__b < __a); } template inline bool operator>(const __shared_ptr<_Tp, _Lp>& __a, nullptr_t) noexcept { return nullptr < __a; } template inline bool operator>(nullptr_t, const __shared_ptr<_Tp, _Lp>& __a) noexcept { return __a < nullptr; } template inline bool operator>=(const __shared_ptr<_Tp1, _Lp>& __a, const __shared_ptr<_Tp2, _Lp>& __b) noexcept { return !(__a < __b); } template inline bool operator>=(const __shared_ptr<_Tp, _Lp>& __a, nullptr_t) noexcept { return !(__a < nullptr); } template inline bool operator>=(nullptr_t, const __shared_ptr<_Tp, _Lp>& __a) noexcept { return !(nullptr < __a); } template struct _Sp_less : public binary_function<_Sp, _Sp, bool> { bool operator()(const _Sp& __lhs, const _Sp& __rhs) const noexcept { typedef typename _Sp::element_type element_type; return std::less()(__lhs.get(), __rhs.get()); } }; template struct less<__shared_ptr<_Tp, _Lp>> : public _Sp_less<__shared_ptr<_Tp, _Lp>> { }; // 20.7.2.2.8 shared_ptr specialized algorithms. template inline void swap(__shared_ptr<_Tp, _Lp>& __a, __shared_ptr<_Tp, _Lp>& __b) noexcept { __a.swap(__b); } // 20.7.2.2.9 shared_ptr casts // The seemingly equivalent code: // shared_ptr<_Tp, _Lp>(static_cast<_Tp*>(__r.get())) // will eventually result in undefined behaviour, attempting to // delete the same object twice. /// static_pointer_cast template inline __shared_ptr<_Tp, _Lp> static_pointer_cast(const __shared_ptr<_Tp1, _Lp>& __r) noexcept { using _Sp = __shared_ptr<_Tp, _Lp>; return _Sp(__r, static_cast(__r.get())); } // The seemingly equivalent code: // shared_ptr<_Tp, _Lp>(const_cast<_Tp*>(__r.get())) // will eventually result in undefined behaviour, attempting to // delete the same object twice. /// const_pointer_cast template inline __shared_ptr<_Tp, _Lp> const_pointer_cast(const __shared_ptr<_Tp1, _Lp>& __r) noexcept { using _Sp = __shared_ptr<_Tp, _Lp>; return _Sp(__r, const_cast(__r.get())); } // The seemingly equivalent code: // shared_ptr<_Tp, _Lp>(dynamic_cast<_Tp*>(__r.get())) // will eventually result in undefined behaviour, attempting to // delete the same object twice. /// dynamic_pointer_cast template inline __shared_ptr<_Tp, _Lp> dynamic_pointer_cast(const __shared_ptr<_Tp1, _Lp>& __r) noexcept { using _Sp = __shared_ptr<_Tp, _Lp>; if (auto* __p = dynamic_cast(__r.get())) return _Sp(__r, __p); return _Sp(); } #if __cplusplus > 201402L template inline __shared_ptr<_Tp, _Lp> reinterpret_pointer_cast(const __shared_ptr<_Tp1, _Lp>& __r) noexcept { using _Sp = __shared_ptr<_Tp, _Lp>; return _Sp(__r, reinterpret_cast(__r.get())); } #endif template class __weak_ptr { template using _Compatible = typename enable_if<__sp_compatible_with<_Yp*, _Tp*>::value, _Res>::type; // Constraint for assignment from shared_ptr and weak_ptr: template using _Assignable = _Compatible<_Yp, __weak_ptr&>; public: using element_type = typename remove_extent<_Tp>::type; constexpr __weak_ptr() noexcept : _M_ptr(nullptr), _M_refcount() { } __weak_ptr(const __weak_ptr&) noexcept = default; ~__weak_ptr() = default; // The "obvious" converting constructor implementation: // // template // __weak_ptr(const __weak_ptr<_Tp1, _Lp>& __r) // : _M_ptr(__r._M_ptr), _M_refcount(__r._M_refcount) // never throws // { } // // has a serious problem. // // __r._M_ptr may already have been invalidated. The _M_ptr(__r._M_ptr) // conversion may require access to *__r._M_ptr (virtual inheritance). // // It is not possible to avoid spurious access violations since // in multithreaded programs __r._M_ptr may be invalidated at any point. template> __weak_ptr(const __weak_ptr<_Yp, _Lp>& __r) noexcept : _M_refcount(__r._M_refcount) { _M_ptr = __r.lock().get(); } template> __weak_ptr(const __shared_ptr<_Yp, _Lp>& __r) noexcept : _M_ptr(__r._M_ptr), _M_refcount(__r._M_refcount) { } __weak_ptr(__weak_ptr&& __r) noexcept : _M_ptr(__r._M_ptr), _M_refcount(std::move(__r._M_refcount)) { __r._M_ptr = nullptr; } template> __weak_ptr(__weak_ptr<_Yp, _Lp>&& __r) noexcept : _M_ptr(__r.lock().get()), _M_refcount(std::move(__r._M_refcount)) { __r._M_ptr = nullptr; } __weak_ptr& operator=(const __weak_ptr& __r) noexcept = default; template _Assignable<_Yp> operator=(const __weak_ptr<_Yp, _Lp>& __r) noexcept { _M_ptr = __r.lock().get(); _M_refcount = __r._M_refcount; return *this; } template _Assignable<_Yp> operator=(const __shared_ptr<_Yp, _Lp>& __r) noexcept { _M_ptr = __r._M_ptr; _M_refcount = __r._M_refcount; return *this; } __weak_ptr& operator=(__weak_ptr&& __r) noexcept { _M_ptr = __r._M_ptr; _M_refcount = std::move(__r._M_refcount); __r._M_ptr = nullptr; return *this; } template _Assignable<_Yp> operator=(__weak_ptr<_Yp, _Lp>&& __r) noexcept { _M_ptr = __r.lock().get(); _M_refcount = std::move(__r._M_refcount); __r._M_ptr = nullptr; return *this; } __shared_ptr<_Tp, _Lp> lock() const noexcept { return __shared_ptr(*this, std::nothrow); } long use_count() const noexcept { return _M_refcount._M_get_use_count(); } bool expired() const noexcept { return _M_refcount._M_get_use_count() == 0; } template bool owner_before(const __shared_ptr<_Tp1, _Lp>& __rhs) const noexcept { return _M_refcount._M_less(__rhs._M_refcount); } template bool owner_before(const __weak_ptr<_Tp1, _Lp>& __rhs) const noexcept { return _M_refcount._M_less(__rhs._M_refcount); } void reset() noexcept { __weak_ptr().swap(*this); } void swap(__weak_ptr& __s) noexcept { std::swap(_M_ptr, __s._M_ptr); _M_refcount._M_swap(__s._M_refcount); } private: // Used by __enable_shared_from_this. void _M_assign(_Tp* __ptr, const __shared_count<_Lp>& __refcount) noexcept { if (use_count() == 0) { _M_ptr = __ptr; _M_refcount = __refcount; } } template friend class __shared_ptr; template friend class __weak_ptr; friend class __enable_shared_from_this<_Tp, _Lp>; friend class enable_shared_from_this<_Tp>; element_type* _M_ptr; // Contained pointer. __weak_count<_Lp> _M_refcount; // Reference counter. }; // 20.7.2.3.6 weak_ptr specialized algorithms. template inline void swap(__weak_ptr<_Tp, _Lp>& __a, __weak_ptr<_Tp, _Lp>& __b) noexcept { __a.swap(__b); } template struct _Sp_owner_less : public binary_function<_Tp, _Tp, bool> { bool operator()(const _Tp& __lhs, const _Tp& __rhs) const noexcept { return __lhs.owner_before(__rhs); } bool operator()(const _Tp& __lhs, const _Tp1& __rhs) const noexcept { return __lhs.owner_before(__rhs); } bool operator()(const _Tp1& __lhs, const _Tp& __rhs) const noexcept { return __lhs.owner_before(__rhs); } }; template<> struct _Sp_owner_less { template auto operator()(const _Tp& __lhs, const _Up& __rhs) const noexcept -> decltype(__lhs.owner_before(__rhs)) { return __lhs.owner_before(__rhs); } using is_transparent = void; }; template struct owner_less<__shared_ptr<_Tp, _Lp>> : public _Sp_owner_less<__shared_ptr<_Tp, _Lp>, __weak_ptr<_Tp, _Lp>> { }; template struct owner_less<__weak_ptr<_Tp, _Lp>> : public _Sp_owner_less<__weak_ptr<_Tp, _Lp>, __shared_ptr<_Tp, _Lp>> { }; template class __enable_shared_from_this { protected: constexpr __enable_shared_from_this() noexcept { } __enable_shared_from_this(const __enable_shared_from_this&) noexcept { } __enable_shared_from_this& operator=(const __enable_shared_from_this&) noexcept { return *this; } ~__enable_shared_from_this() { } public: __shared_ptr<_Tp, _Lp> shared_from_this() { return __shared_ptr<_Tp, _Lp>(this->_M_weak_this); } __shared_ptr shared_from_this() const { return __shared_ptr(this->_M_weak_this); } #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 __weak_ptr<_Tp, _Lp> weak_from_this() noexcept { return this->_M_weak_this; } __weak_ptr weak_from_this() const noexcept { return this->_M_weak_this; } #endif private: template void _M_weak_assign(_Tp1* __p, const __shared_count<_Lp>& __n) const noexcept { _M_weak_this._M_assign(__p, __n); } friend const __enable_shared_from_this* __enable_shared_from_this_base(const __shared_count<_Lp>&, const __enable_shared_from_this* __p) { return __p; } template friend class __shared_ptr; mutable __weak_ptr<_Tp, _Lp> _M_weak_this; }; template inline __shared_ptr<_Tp, _Lp> __allocate_shared(const _Alloc& __a, _Args&&... __args) { static_assert(!is_array<_Tp>::value, "make_shared not supported"); return __shared_ptr<_Tp, _Lp>(_Sp_alloc_shared_tag<_Alloc>{__a}, std::forward<_Args>(__args)...); } template inline __shared_ptr<_Tp, _Lp> __make_shared(_Args&&... __args) { typedef typename std::remove_const<_Tp>::type _Tp_nc; return std::__allocate_shared<_Tp, _Lp>(std::allocator<_Tp_nc>(), std::forward<_Args>(__args)...); } /// std::hash specialization for __shared_ptr. template struct hash<__shared_ptr<_Tp, _Lp>> : public __hash_base> { size_t operator()(const __shared_ptr<_Tp, _Lp>& __s) const noexcept { return hash::element_type*>()( __s.get()); } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _SHARED_PTR_BASE_H PK!$$8/bits/slice_array.hnu[// The template and inlines for the -*- C++ -*- slice_array class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/slice_array.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _SLICE_ARRAY_H #define _SLICE_ARRAY_H 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup numeric_arrays * @{ */ /** * @brief Class defining one-dimensional subset of an array. * * The slice class represents a one-dimensional subset of an array, * specified by three parameters: start offset, size, and stride. The * start offset is the index of the first element of the array that is part * of the subset. The size is the total number of elements in the subset. * Stride is the distance between each successive array element to include * in the subset. * * For example, with an array of size 10, and a slice with offset 1, size 3 * and stride 2, the subset consists of array elements 1, 3, and 5. */ class slice { public: /// Construct an empty slice. slice(); /** * @brief Construct a slice. * * @param __o Offset in array of first element. * @param __d Number of elements in slice. * @param __s Stride between array elements. */ slice(size_t __o, size_t __d, size_t __s); /// Return array offset of first slice element. size_t start() const; /// Return size of slice. size_t size() const; /// Return array stride of slice. size_t stride() const; private: size_t _M_off; // offset size_t _M_sz; // size size_t _M_st; // stride unit }; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 543. valarray slice default constructor inline slice::slice() : _M_off(0), _M_sz(0), _M_st(0) {} inline slice::slice(size_t __o, size_t __d, size_t __s) : _M_off(__o), _M_sz(__d), _M_st(__s) {} inline size_t slice::start() const { return _M_off; } inline size_t slice::size() const { return _M_sz; } inline size_t slice::stride() const { return _M_st; } /** * @brief Reference to one-dimensional subset of an array. * * A slice_array is a reference to the actual elements of an array * specified by a slice. The way to get a slice_array is to call * operator[](slice) on a valarray. The returned slice_array then permits * carrying operations out on the referenced subset of elements in the * original valarray. For example, operator+=(valarray) will add values * to the subset of elements in the underlying valarray this slice_array * refers to. * * @param Tp Element type. */ template class slice_array { public: typedef _Tp value_type; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 253. valarray helper functions are almost entirely useless /// Copy constructor. Both slices refer to the same underlying array. slice_array(const slice_array&); /// Assignment operator. Assigns slice elements to corresponding /// elements of @a a. slice_array& operator=(const slice_array&); /// Assign slice elements to corresponding elements of @a v. void operator=(const valarray<_Tp>&) const; /// Multiply slice elements by corresponding elements of @a v. void operator*=(const valarray<_Tp>&) const; /// Divide slice elements by corresponding elements of @a v. void operator/=(const valarray<_Tp>&) const; /// Modulo slice elements by corresponding elements of @a v. void operator%=(const valarray<_Tp>&) const; /// Add corresponding elements of @a v to slice elements. void operator+=(const valarray<_Tp>&) const; /// Subtract corresponding elements of @a v from slice elements. void operator-=(const valarray<_Tp>&) const; /// Logical xor slice elements with corresponding elements of @a v. void operator^=(const valarray<_Tp>&) const; /// Logical and slice elements with corresponding elements of @a v. void operator&=(const valarray<_Tp>&) const; /// Logical or slice elements with corresponding elements of @a v. void operator|=(const valarray<_Tp>&) const; /// Left shift slice elements by corresponding elements of @a v. void operator<<=(const valarray<_Tp>&) const; /// Right shift slice elements by corresponding elements of @a v. void operator>>=(const valarray<_Tp>&) const; /// Assign all slice elements to @a t. void operator=(const _Tp &) const; // ~slice_array (); template void operator=(const _Expr<_Dom, _Tp>&) const; template void operator*=(const _Expr<_Dom, _Tp>&) const; template void operator/=(const _Expr<_Dom, _Tp>&) const; template void operator%=(const _Expr<_Dom, _Tp>&) const; template void operator+=(const _Expr<_Dom, _Tp>&) const; template void operator-=(const _Expr<_Dom, _Tp>&) const; template void operator^=(const _Expr<_Dom, _Tp>&) const; template void operator&=(const _Expr<_Dom, _Tp>&) const; template void operator|=(const _Expr<_Dom, _Tp>&) const; template void operator<<=(const _Expr<_Dom, _Tp>&) const; template void operator>>=(const _Expr<_Dom, _Tp>&) const; private: friend class valarray<_Tp>; slice_array(_Array<_Tp>, const slice&); const size_t _M_sz; const size_t _M_stride; const _Array<_Tp> _M_array; // not implemented slice_array(); }; template inline slice_array<_Tp>::slice_array(_Array<_Tp> __a, const slice& __s) : _M_sz(__s.size()), _M_stride(__s.stride()), _M_array(__a.begin() + __s.start()) {} template inline slice_array<_Tp>::slice_array(const slice_array<_Tp>& __a) : _M_sz(__a._M_sz), _M_stride(__a._M_stride), _M_array(__a._M_array) {} // template // inline slice_array<_Tp>::~slice_array () {} template inline slice_array<_Tp>& slice_array<_Tp>::operator=(const slice_array<_Tp>& __a) { std::__valarray_copy(__a._M_array, __a._M_sz, __a._M_stride, _M_array, _M_stride); return *this; } template inline void slice_array<_Tp>::operator=(const _Tp& __t) const { std::__valarray_fill(_M_array, _M_sz, _M_stride, __t); } template inline void slice_array<_Tp>::operator=(const valarray<_Tp>& __v) const { std::__valarray_copy(_Array<_Tp>(__v), _M_array, _M_sz, _M_stride); } template template inline void slice_array<_Tp>::operator=(const _Expr<_Dom,_Tp>& __e) const { std::__valarray_copy(__e, _M_sz, _M_array, _M_stride); } #undef _DEFINE_VALARRAY_OPERATOR #define _DEFINE_VALARRAY_OPERATOR(_Op,_Name) \ template \ inline void \ slice_array<_Tp>::operator _Op##=(const valarray<_Tp>& __v) const \ { \ _Array_augmented_##_Name(_M_array, _M_sz, _M_stride, _Array<_Tp>(__v));\ } \ \ template \ template \ inline void \ slice_array<_Tp>::operator _Op##=(const _Expr<_Dom,_Tp>& __e) const\ { \ _Array_augmented_##_Name(_M_array, _M_stride, __e, _M_sz); \ } _DEFINE_VALARRAY_OPERATOR(*, __multiplies) _DEFINE_VALARRAY_OPERATOR(/, __divides) _DEFINE_VALARRAY_OPERATOR(%, __modulus) _DEFINE_VALARRAY_OPERATOR(+, __plus) _DEFINE_VALARRAY_OPERATOR(-, __minus) _DEFINE_VALARRAY_OPERATOR(^, __bitwise_xor) _DEFINE_VALARRAY_OPERATOR(&, __bitwise_and) _DEFINE_VALARRAY_OPERATOR(|, __bitwise_or) _DEFINE_VALARRAY_OPERATOR(<<, __shift_left) _DEFINE_VALARRAY_OPERATOR(>>, __shift_right) #undef _DEFINE_VALARRAY_OPERATOR // @} group numeric_arrays _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _SLICE_ARRAY_H */ PK!x˷˷8/bits/specfun.hnu[// Mathematical Special Functions for -*- C++ -*- // Copyright (C) 2006-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/specfun.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{cmath} */ #ifndef _GLIBCXX_BITS_SPECFUN_H #define _GLIBCXX_BITS_SPECFUN_H 1 #pragma GCC visibility push(default) #include #define __STDCPP_MATH_SPEC_FUNCS__ 201003L #define __cpp_lib_math_special_functions 201603L #if __cplusplus <= 201403L && __STDCPP_WANT_MATH_SPEC_FUNCS__ == 0 # error include and define __STDCPP_WANT_MATH_SPEC_FUNCS__ #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup mathsf Mathematical Special Functions * @ingroup numerics * * A collection of advanced mathematical special functions, * defined by ISO/IEC IS 29124. * @{ */ /** * @mainpage Mathematical Special Functions * * @section intro Introduction and History * The first significant library upgrade on the road to C++2011, * * TR1, included a set of 23 mathematical functions that significantly * extended the standard transcendental functions inherited from C and declared * in @. * * Although most components from TR1 were eventually adopted for C++11 these * math functions were left behind out of concern for implementability. * The math functions were published as a separate international standard * * IS 29124 - Extensions to the C++ Library to Support Mathematical Special * Functions. * * For C++17 these functions were incorporated into the main standard. * * @section contents Contents * The following functions are implemented in namespace @c std: * - @ref assoc_laguerre "assoc_laguerre - Associated Laguerre functions" * - @ref assoc_legendre "assoc_legendre - Associated Legendre functions" * - @ref beta "beta - Beta functions" * - @ref comp_ellint_1 "comp_ellint_1 - Complete elliptic functions of the first kind" * - @ref comp_ellint_2 "comp_ellint_2 - Complete elliptic functions of the second kind" * - @ref comp_ellint_3 "comp_ellint_3 - Complete elliptic functions of the third kind" * - @ref cyl_bessel_i "cyl_bessel_i - Regular modified cylindrical Bessel functions" * - @ref cyl_bessel_j "cyl_bessel_j - Cylindrical Bessel functions of the first kind" * - @ref cyl_bessel_k "cyl_bessel_k - Irregular modified cylindrical Bessel functions" * - @ref cyl_neumann "cyl_neumann - Cylindrical Neumann functions or Cylindrical Bessel functions of the second kind" * - @ref ellint_1 "ellint_1 - Incomplete elliptic functions of the first kind" * - @ref ellint_2 "ellint_2 - Incomplete elliptic functions of the second kind" * - @ref ellint_3 "ellint_3 - Incomplete elliptic functions of the third kind" * - @ref expint "expint - The exponential integral" * - @ref hermite "hermite - Hermite polynomials" * - @ref laguerre "laguerre - Laguerre functions" * - @ref legendre "legendre - Legendre polynomials" * - @ref riemann_zeta "riemann_zeta - The Riemann zeta function" * - @ref sph_bessel "sph_bessel - Spherical Bessel functions" * - @ref sph_legendre "sph_legendre - Spherical Legendre functions" * - @ref sph_neumann "sph_neumann - Spherical Neumann functions" * * The hypergeometric functions were stricken from the TR29124 and C++17 * versions of this math library because of implementation concerns. * However, since they were in the TR1 version and since they are popular * we kept them as an extension in namespace @c __gnu_cxx: * - @ref __gnu_cxx::conf_hyperg "conf_hyperg - Confluent hypergeometric functions" * - @ref __gnu_cxx::hyperg "hyperg - Hypergeometric functions" * * @section general General Features * * @subsection promotion Argument Promotion * The arguments suppled to the non-suffixed functions will be promoted * according to the following rules: * 1. If any argument intended to be floating point is given an integral value * That integral value is promoted to double. * 2. All floating point arguments are promoted up to the largest floating * point precision among them. * * @subsection NaN NaN Arguments * If any of the floating point arguments supplied to these functions is * invalid or NaN (std::numeric_limits::quiet_NaN), * the value NaN is returned. * * @section impl Implementation * * We strive to implement the underlying math with type generic algorithms * to the greatest extent possible. In practice, the functions are thin * wrappers that dispatch to function templates. Type dependence is * controlled with std::numeric_limits and functions thereof. * * We don't promote @c float to @c double or @c double to long double * reflexively. The goal is for @c float functions to operate more quickly, * at the cost of @c float accuracy and possibly a smaller domain of validity. * Similaryly, long double should give you more dynamic range * and slightly more pecision than @c double on many systems. * * @section testing Testing * * These functions have been tested against equivalent implementations * from the * Gnu Scientific Library, GSL and * pbase()) __tmp.assign(this->pbase(), this->epptr() - this->pbase()); __tmp.push_back(__conv); _M_string.swap(__tmp); _M_sync(const_cast(_M_string.data()), this->gptr() - this->eback(), this->pptr() - this->pbase()); } else *this->pptr() = __conv; this->pbump(1); return __c; } template typename basic_stringbuf<_CharT, _Traits, _Alloc>::int_type basic_stringbuf<_CharT, _Traits, _Alloc>:: underflow() { int_type __ret = traits_type::eof(); const bool __testin = this->_M_mode & ios_base::in; if (__testin) { // Update egptr() to match the actual string end. _M_update_egptr(); if (this->gptr() < this->egptr()) __ret = traits_type::to_int_type(*this->gptr()); } return __ret; } template typename basic_stringbuf<_CharT, _Traits, _Alloc>::pos_type basic_stringbuf<_CharT, _Traits, _Alloc>:: seekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode __mode) { pos_type __ret = pos_type(off_type(-1)); bool __testin = (ios_base::in & this->_M_mode & __mode) != 0; bool __testout = (ios_base::out & this->_M_mode & __mode) != 0; const bool __testboth = __testin && __testout && __way != ios_base::cur; __testin &= !(__mode & ios_base::out); __testout &= !(__mode & ios_base::in); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 453. basic_stringbuf::seekoff need not always fail for an empty stream. const char_type* __beg = __testin ? this->eback() : this->pbase(); if ((__beg || !__off) && (__testin || __testout || __testboth)) { _M_update_egptr(); off_type __newoffi = __off; off_type __newoffo = __newoffi; if (__way == ios_base::cur) { __newoffi += this->gptr() - __beg; __newoffo += this->pptr() - __beg; } else if (__way == ios_base::end) __newoffo = __newoffi += this->egptr() - __beg; if ((__testin || __testboth) && __newoffi >= 0 && this->egptr() - __beg >= __newoffi) { this->setg(this->eback(), this->eback() + __newoffi, this->egptr()); __ret = pos_type(__newoffi); } if ((__testout || __testboth) && __newoffo >= 0 && this->egptr() - __beg >= __newoffo) { _M_pbump(this->pbase(), this->epptr(), __newoffo); __ret = pos_type(__newoffo); } } return __ret; } template typename basic_stringbuf<_CharT, _Traits, _Alloc>::pos_type basic_stringbuf<_CharT, _Traits, _Alloc>:: seekpos(pos_type __sp, ios_base::openmode __mode) { pos_type __ret = pos_type(off_type(-1)); const bool __testin = (ios_base::in & this->_M_mode & __mode) != 0; const bool __testout = (ios_base::out & this->_M_mode & __mode) != 0; const char_type* __beg = __testin ? this->eback() : this->pbase(); if ((__beg || !off_type(__sp)) && (__testin || __testout)) { _M_update_egptr(); const off_type __pos(__sp); const bool __testpos = (0 <= __pos && __pos <= this->egptr() - __beg); if (__testpos) { if (__testin) this->setg(this->eback(), this->eback() + __pos, this->egptr()); if (__testout) _M_pbump(this->pbase(), this->epptr(), __pos); __ret = __sp; } } return __ret; } template void basic_stringbuf<_CharT, _Traits, _Alloc>:: _M_sync(char_type* __base, __size_type __i, __size_type __o) { const bool __testin = _M_mode & ios_base::in; const bool __testout = _M_mode & ios_base::out; char_type* __endg = __base + _M_string.size(); char_type* __endp = __base + _M_string.capacity(); if (__base != _M_string.data()) { // setbuf: __i == size of buffer area (_M_string.size() == 0). __endg += __i; __i = 0; __endp = __endg; } if (__testin) this->setg(__base, __base + __i, __endg); if (__testout) { _M_pbump(__base, __endp, __o); // egptr() always tracks the string end. When !__testin, // for the correct functioning of the streambuf inlines // the other get area pointers are identical. if (!__testin) this->setg(__endg, __endg, __endg); } } template void basic_stringbuf<_CharT, _Traits, _Alloc>:: _M_pbump(char_type* __pbeg, char_type* __pend, off_type __off) { this->setp(__pbeg, __pend); while (__off > __gnu_cxx::__numeric_traits::__max) { this->pbump(__gnu_cxx::__numeric_traits::__max); __off -= __gnu_cxx::__numeric_traits::__max; } this->pbump(__off); } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class basic_stringbuf; extern template class basic_istringstream; extern template class basic_ostringstream; extern template class basic_stringstream; #ifdef _GLIBCXX_USE_WCHAR_T extern template class basic_stringbuf; extern template class basic_istringstream; extern template class basic_ostringstream; extern template class basic_stringstream; #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!- 8/bits/std_abs.hnu[// -*- C++ -*- C library enhancements header. // Copyright (C) 2016-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/std_abs.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{cmath, cstdlib} */ #ifndef _GLIBCXX_BITS_STD_ABS_H #define _GLIBCXX_BITS_STD_ABS_H #pragma GCC system_header #include #define _GLIBCXX_INCLUDE_NEXT_C_HEADERS #include_next #ifdef __CORRECT_ISO_CPP_MATH_H_PROTO # include_next #endif #undef _GLIBCXX_INCLUDE_NEXT_C_HEADERS #undef abs extern "C++" { namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using ::abs; #ifndef __CORRECT_ISO_CPP_STDLIB_H_PROTO inline long abs(long __i) { return __builtin_labs(__i); } #endif #ifdef _GLIBCXX_USE_LONG_LONG inline long long abs(long long __x) { return __builtin_llabs (__x); } #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2192. Validity and return type of std::abs(0u) is unclear // 2294. should declare abs(double) #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR double abs(double __x) { return __builtin_fabs(__x); } inline _GLIBCXX_CONSTEXPR float abs(float __x) { return __builtin_fabsf(__x); } inline _GLIBCXX_CONSTEXPR long double abs(long double __x) { return __builtin_fabsl(__x); } #endif #if defined(__GLIBCXX_TYPE_INT_N_0) inline _GLIBCXX_CONSTEXPR __GLIBCXX_TYPE_INT_N_0 abs(__GLIBCXX_TYPE_INT_N_0 __x) { return __x >= 0 ? __x : -__x; } #endif #if defined(__GLIBCXX_TYPE_INT_N_1) inline _GLIBCXX_CONSTEXPR __GLIBCXX_TYPE_INT_N_1 abs(__GLIBCXX_TYPE_INT_N_1 __x) { return __x >= 0 ? __x : -__x; } #endif #if defined(__GLIBCXX_TYPE_INT_N_2) inline _GLIBCXX_CONSTEXPR __GLIBCXX_TYPE_INT_N_2 abs(__GLIBCXX_TYPE_INT_N_2 __x) { return __x >= 0 ? __x : -__x; } #endif #if defined(__GLIBCXX_TYPE_INT_N_3) inline _GLIBCXX_CONSTEXPR __GLIBCXX_TYPE_INT_N_3 abs(__GLIBCXX_TYPE_INT_N_3 __x) { return __x >= 0 ? __x : -__x; } #endif #if !defined(__STRICT_ANSI__) && defined(_GLIBCXX_USE_FLOAT128) inline _GLIBCXX_CONSTEXPR __float128 abs(__float128 __x) { return __x < 0 ? -__x : __x; } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace } #endif // _GLIBCXX_BITS_STD_ABS_H PK!3ZZ8/bits/std_function.hnu[// Implementation of std::function -*- C++ -*- // Copyright (C) 2004-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/std_function.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{functional} */ #ifndef _GLIBCXX_STD_FUNCTION_H #define _GLIBCXX_STD_FUNCTION_H 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #if __cpp_rtti # include #endif #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief Exception class thrown when class template function's * operator() is called with an empty target. * @ingroup exceptions */ class bad_function_call : public std::exception { public: virtual ~bad_function_call() noexcept; const char* what() const noexcept; }; /** * Trait identifying "location-invariant" types, meaning that the * address of the object (or any of its members) will not escape. * Trivially copyable types are location-invariant and users can * specialize this trait for other types. */ template struct __is_location_invariant : is_trivially_copyable<_Tp>::type { }; class _Undefined_class; union _Nocopy_types { void* _M_object; const void* _M_const_object; void (*_M_function_pointer)(); void (_Undefined_class::*_M_member_pointer)(); }; union [[gnu::may_alias]] _Any_data { void* _M_access() { return &_M_pod_data[0]; } const void* _M_access() const { return &_M_pod_data[0]; } template _Tp& _M_access() { return *static_cast<_Tp*>(_M_access()); } template const _Tp& _M_access() const { return *static_cast(_M_access()); } _Nocopy_types _M_unused; char _M_pod_data[sizeof(_Nocopy_types)]; }; enum _Manager_operation { __get_type_info, __get_functor_ptr, __clone_functor, __destroy_functor }; // Simple type wrapper that helps avoid annoying const problems // when casting between void pointers and pointers-to-pointers. template struct _Simple_type_wrapper { _Simple_type_wrapper(_Tp __value) : __value(__value) { } _Tp __value; }; template struct __is_location_invariant<_Simple_type_wrapper<_Tp> > : __is_location_invariant<_Tp> { }; template class function; /// Base class of all polymorphic function object wrappers. class _Function_base { public: static const std::size_t _M_max_size = sizeof(_Nocopy_types); static const std::size_t _M_max_align = __alignof__(_Nocopy_types); template class _Base_manager { protected: static const bool __stored_locally = (__is_location_invariant<_Functor>::value && sizeof(_Functor) <= _M_max_size && __alignof__(_Functor) <= _M_max_align && (_M_max_align % __alignof__(_Functor) == 0)); typedef integral_constant _Local_storage; // Retrieve a pointer to the function object static _Functor* _M_get_pointer(const _Any_data& __source) { const _Functor* __ptr = __stored_locally? std::__addressof(__source._M_access<_Functor>()) /* have stored a pointer */ : __source._M_access<_Functor*>(); return const_cast<_Functor*>(__ptr); } // Clone a location-invariant function object that fits within // an _Any_data structure. static void _M_clone(_Any_data& __dest, const _Any_data& __source, true_type) { ::new (__dest._M_access()) _Functor(__source._M_access<_Functor>()); } // Clone a function object that is not location-invariant or // that cannot fit into an _Any_data structure. static void _M_clone(_Any_data& __dest, const _Any_data& __source, false_type) { __dest._M_access<_Functor*>() = new _Functor(*__source._M_access<_Functor*>()); } // Destroying a location-invariant object may still require // destruction. static void _M_destroy(_Any_data& __victim, true_type) { __victim._M_access<_Functor>().~_Functor(); } // Destroying an object located on the heap. static void _M_destroy(_Any_data& __victim, false_type) { delete __victim._M_access<_Functor*>(); } public: static bool _M_manager(_Any_data& __dest, const _Any_data& __source, _Manager_operation __op) { switch (__op) { #if __cpp_rtti case __get_type_info: __dest._M_access() = &typeid(_Functor); break; #endif case __get_functor_ptr: __dest._M_access<_Functor*>() = _M_get_pointer(__source); break; case __clone_functor: _M_clone(__dest, __source, _Local_storage()); break; case __destroy_functor: _M_destroy(__dest, _Local_storage()); break; } return false; } static void _M_init_functor(_Any_data& __functor, _Functor&& __f) { _M_init_functor(__functor, std::move(__f), _Local_storage()); } template static bool _M_not_empty_function(const function<_Signature>& __f) { return static_cast(__f); } template static bool _M_not_empty_function(_Tp* __fp) { return __fp != nullptr; } template static bool _M_not_empty_function(_Tp _Class::* __mp) { return __mp != nullptr; } template static bool _M_not_empty_function(const _Tp&) { return true; } private: static void _M_init_functor(_Any_data& __functor, _Functor&& __f, true_type) { ::new (__functor._M_access()) _Functor(std::move(__f)); } static void _M_init_functor(_Any_data& __functor, _Functor&& __f, false_type) { __functor._M_access<_Functor*>() = new _Functor(std::move(__f)); } }; _Function_base() : _M_manager(nullptr) { } ~_Function_base() { if (_M_manager) _M_manager(_M_functor, _M_functor, __destroy_functor); } bool _M_empty() const { return !_M_manager; } typedef bool (*_Manager_type)(_Any_data&, const _Any_data&, _Manager_operation); _Any_data _M_functor; _Manager_type _M_manager; }; template class _Function_handler; template class _Function_handler<_Res(_ArgTypes...), _Functor> : public _Function_base::_Base_manager<_Functor> { typedef _Function_base::_Base_manager<_Functor> _Base; public: static _Res _M_invoke(const _Any_data& __functor, _ArgTypes&&... __args) { return (*_Base::_M_get_pointer(__functor))( std::forward<_ArgTypes>(__args)...); } }; template class _Function_handler : public _Function_base::_Base_manager<_Functor> { typedef _Function_base::_Base_manager<_Functor> _Base; public: static void _M_invoke(const _Any_data& __functor, _ArgTypes&&... __args) { (*_Base::_M_get_pointer(__functor))( std::forward<_ArgTypes>(__args)...); } }; template class _Function_handler<_Res(_ArgTypes...), _Member _Class::*> : public _Function_handler { typedef _Function_handler _Base; public: static _Res _M_invoke(const _Any_data& __functor, _ArgTypes&&... __args) { return std::__invoke(_Base::_M_get_pointer(__functor)->__value, std::forward<_ArgTypes>(__args)...); } }; template class _Function_handler : public _Function_base::_Base_manager< _Simple_type_wrapper< _Member _Class::* > > { typedef _Member _Class::* _Functor; typedef _Simple_type_wrapper<_Functor> _Wrapper; typedef _Function_base::_Base_manager<_Wrapper> _Base; public: static bool _M_manager(_Any_data& __dest, const _Any_data& __source, _Manager_operation __op) { switch (__op) { #if __cpp_rtti case __get_type_info: __dest._M_access() = &typeid(_Functor); break; #endif case __get_functor_ptr: __dest._M_access<_Functor*>() = &_Base::_M_get_pointer(__source)->__value; break; default: _Base::_M_manager(__dest, __source, __op); } return false; } static void _M_invoke(const _Any_data& __functor, _ArgTypes&&... __args) { std::__invoke(_Base::_M_get_pointer(__functor)->__value, std::forward<_ArgTypes>(__args)...); } }; template using __check_func_return_type = __or_, is_same<_From, _To>, is_convertible<_From, _To>>; /** * @brief Primary class template for std::function. * @ingroup functors * * Polymorphic function wrapper. */ template class function<_Res(_ArgTypes...)> : public _Maybe_unary_or_binary_function<_Res, _ArgTypes...>, private _Function_base { template::type> struct _Callable : __check_func_return_type<_Res2, _Res> { }; // Used so the return type convertibility checks aren't done when // performing overload resolution for copy construction/assignment. template struct _Callable : false_type { }; template using _Requires = typename enable_if<_Cond::value, _Tp>::type; public: typedef _Res result_type; // [3.7.2.1] construct/copy/destroy /** * @brief Default construct creates an empty function call wrapper. * @post @c !(bool)*this */ function() noexcept : _Function_base() { } /** * @brief Creates an empty function call wrapper. * @post @c !(bool)*this */ function(nullptr_t) noexcept : _Function_base() { } /** * @brief %Function copy constructor. * @param __x A %function object with identical call signature. * @post @c bool(*this) == bool(__x) * * The newly-created %function contains a copy of the target of @a * __x (if it has one). */ function(const function& __x); /** * @brief %Function move constructor. * @param __x A %function object rvalue with identical call signature. * * The newly-created %function contains the target of @a __x * (if it has one). */ function(function&& __x) noexcept : _Function_base() { __x.swap(*this); } /** * @brief Builds a %function that targets a copy of the incoming * function object. * @param __f A %function object that is callable with parameters of * type @c T1, @c T2, ..., @c TN and returns a value convertible * to @c Res. * * The newly-created %function object will target a copy of * @a __f. If @a __f is @c reference_wrapper, then this function * object will contain a reference to the function object @c * __f.get(). If @a __f is a NULL function pointer or NULL * pointer-to-member, the newly-created object will be empty. * * If @a __f is a non-NULL function pointer or an object of type @c * reference_wrapper, this function will not throw. */ template>, void>, typename = _Requires<_Callable<_Functor>, void>> function(_Functor); /** * @brief %Function assignment operator. * @param __x A %function with identical call signature. * @post @c (bool)*this == (bool)x * @returns @c *this * * The target of @a __x is copied to @c *this. If @a __x has no * target, then @c *this will be empty. * * If @a __x targets a function pointer or a reference to a function * object, then this operation will not throw an %exception. */ function& operator=(const function& __x) { function(__x).swap(*this); return *this; } /** * @brief %Function move-assignment operator. * @param __x A %function rvalue with identical call signature. * @returns @c *this * * The target of @a __x is moved to @c *this. If @a __x has no * target, then @c *this will be empty. * * If @a __x targets a function pointer or a reference to a function * object, then this operation will not throw an %exception. */ function& operator=(function&& __x) noexcept { function(std::move(__x)).swap(*this); return *this; } /** * @brief %Function assignment to zero. * @post @c !(bool)*this * @returns @c *this * * The target of @c *this is deallocated, leaving it empty. */ function& operator=(nullptr_t) noexcept { if (_M_manager) { _M_manager(_M_functor, _M_functor, __destroy_functor); _M_manager = nullptr; _M_invoker = nullptr; } return *this; } /** * @brief %Function assignment to a new target. * @param __f A %function object that is callable with parameters of * type @c T1, @c T2, ..., @c TN and returns a value convertible * to @c Res. * @return @c *this * * This %function object wrapper will target a copy of @a * __f. If @a __f is @c reference_wrapper, then this function * object will contain a reference to the function object @c * __f.get(). If @a __f is a NULL function pointer or NULL * pointer-to-member, @c this object will be empty. * * If @a __f is a non-NULL function pointer or an object of type @c * reference_wrapper, this function will not throw. */ template _Requires<_Callable::type>, function&> operator=(_Functor&& __f) { function(std::forward<_Functor>(__f)).swap(*this); return *this; } /// @overload template function& operator=(reference_wrapper<_Functor> __f) noexcept { function(__f).swap(*this); return *this; } // [3.7.2.2] function modifiers /** * @brief Swap the targets of two %function objects. * @param __x A %function with identical call signature. * * Swap the targets of @c this function object and @a __f. This * function will not throw an %exception. */ void swap(function& __x) noexcept { std::swap(_M_functor, __x._M_functor); std::swap(_M_manager, __x._M_manager); std::swap(_M_invoker, __x._M_invoker); } // [3.7.2.3] function capacity /** * @brief Determine if the %function wrapper has a target. * * @return @c true when this %function object contains a target, * or @c false when it is empty. * * This function will not throw an %exception. */ explicit operator bool() const noexcept { return !_M_empty(); } // [3.7.2.4] function invocation /** * @brief Invokes the function targeted by @c *this. * @returns the result of the target. * @throws bad_function_call when @c !(bool)*this * * The function call operator invokes the target function object * stored by @c this. */ _Res operator()(_ArgTypes... __args) const; #if __cpp_rtti // [3.7.2.5] function target access /** * @brief Determine the type of the target of this function object * wrapper. * * @returns the type identifier of the target function object, or * @c typeid(void) if @c !(bool)*this. * * This function will not throw an %exception. */ const type_info& target_type() const noexcept; /** * @brief Access the stored target function object. * * @return Returns a pointer to the stored target function object, * if @c typeid(_Functor).equals(target_type()); otherwise, a NULL * pointer. * * This function does not throw exceptions. * * @{ */ template _Functor* target() noexcept; template const _Functor* target() const noexcept; // @} #endif private: using _Invoker_type = _Res (*)(const _Any_data&, _ArgTypes&&...); _Invoker_type _M_invoker; }; #if __cpp_deduction_guides >= 201606 template struct __function_guide_helper { }; template struct __function_guide_helper< _Res (_Tp::*) (_Args...) noexcept(_Nx) > { using type = _Res(_Args...); }; template struct __function_guide_helper< _Res (_Tp::*) (_Args...) & noexcept(_Nx) > { using type = _Res(_Args...); }; template struct __function_guide_helper< _Res (_Tp::*) (_Args...) const noexcept(_Nx) > { using type = _Res(_Args...); }; template struct __function_guide_helper< _Res (_Tp::*) (_Args...) const & noexcept(_Nx) > { using type = _Res(_Args...); }; template function(_Res(*)(_ArgTypes...)) -> function<_Res(_ArgTypes...)>; template::type> function(_Functor) -> function<_Signature>; #endif // Out-of-line member definitions. template function<_Res(_ArgTypes...)>:: function(const function& __x) : _Function_base() { if (static_cast(__x)) { __x._M_manager(_M_functor, __x._M_functor, __clone_functor); _M_invoker = __x._M_invoker; _M_manager = __x._M_manager; } } template template function<_Res(_ArgTypes...)>:: function(_Functor __f) : _Function_base() { typedef _Function_handler<_Res(_ArgTypes...), _Functor> _My_handler; if (_My_handler::_M_not_empty_function(__f)) { _My_handler::_M_init_functor(_M_functor, std::move(__f)); _M_invoker = &_My_handler::_M_invoke; _M_manager = &_My_handler::_M_manager; } } template _Res function<_Res(_ArgTypes...)>:: operator()(_ArgTypes... __args) const { if (_M_empty()) __throw_bad_function_call(); return _M_invoker(_M_functor, std::forward<_ArgTypes>(__args)...); } #if __cpp_rtti template const type_info& function<_Res(_ArgTypes...)>:: target_type() const noexcept { if (_M_manager) { _Any_data __typeinfo_result; _M_manager(__typeinfo_result, _M_functor, __get_type_info); return *__typeinfo_result._M_access(); } else return typeid(void); } template template _Functor* function<_Res(_ArgTypes...)>:: target() noexcept { const function* __const_this = this; const _Functor* __func = __const_this->template target<_Functor>(); return const_cast<_Functor*>(__func); } template template const _Functor* function<_Res(_ArgTypes...)>:: target() const noexcept { if (typeid(_Functor) == target_type() && _M_manager) { _Any_data __ptr; _M_manager(__ptr, _M_functor, __get_functor_ptr); return __ptr._M_access(); } else return nullptr; } #endif // [20.7.15.2.6] null pointer comparisons /** * @brief Compares a polymorphic function object wrapper against 0 * (the NULL pointer). * @returns @c true if the wrapper has no target, @c false otherwise * * This function will not throw an %exception. */ template inline bool operator==(const function<_Res(_Args...)>& __f, nullptr_t) noexcept { return !static_cast(__f); } /// @overload template inline bool operator==(nullptr_t, const function<_Res(_Args...)>& __f) noexcept { return !static_cast(__f); } /** * @brief Compares a polymorphic function object wrapper against 0 * (the NULL pointer). * @returns @c false if the wrapper has no target, @c true otherwise * * This function will not throw an %exception. */ template inline bool operator!=(const function<_Res(_Args...)>& __f, nullptr_t) noexcept { return static_cast(__f); } /// @overload template inline bool operator!=(nullptr_t, const function<_Res(_Args...)>& __f) noexcept { return static_cast(__f); } // [20.7.15.2.7] specialized algorithms /** * @brief Swap the targets of two polymorphic function object wrappers. * * This function will not throw an %exception. */ // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2062. Effect contradictions w/o no-throw guarantee of std::function swaps template inline void swap(function<_Res(_Args...)>& __x, function<_Res(_Args...)>& __y) noexcept { __x.swap(__y); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif // _GLIBCXX_STD_FUNCTION_H PK!2R$R$8/bits/std_mutex.hnu[// std::mutex implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/std_mutex.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{mutex} */ #ifndef _GLIBCXX_MUTEX_H #define _GLIBCXX_MUTEX_H 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #include #include // for std::swap #ifdef _GLIBCXX_USE_C99_STDINT_TR1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup mutexes Mutexes * @ingroup concurrency * * Classes for mutex support. * @{ */ #ifdef _GLIBCXX_HAS_GTHREADS // Common base class for std::mutex and std::timed_mutex class __mutex_base { protected: typedef __gthread_mutex_t __native_type; #ifdef __GTHREAD_MUTEX_INIT __native_type _M_mutex = __GTHREAD_MUTEX_INIT; constexpr __mutex_base() noexcept = default; #else __native_type _M_mutex; __mutex_base() noexcept { // XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may) __GTHREAD_MUTEX_INIT_FUNCTION(&_M_mutex); } ~__mutex_base() noexcept { __gthread_mutex_destroy(&_M_mutex); } #endif __mutex_base(const __mutex_base&) = delete; __mutex_base& operator=(const __mutex_base&) = delete; }; /// The standard mutex type. class mutex : private __mutex_base { public: typedef __native_type* native_handle_type; #ifdef __GTHREAD_MUTEX_INIT constexpr #endif mutex() noexcept = default; ~mutex() = default; mutex(const mutex&) = delete; mutex& operator=(const mutex&) = delete; void lock() { int __e = __gthread_mutex_lock(&_M_mutex); // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may) if (__e) __throw_system_error(__e); } bool try_lock() noexcept { // XXX EINVAL, EAGAIN, EBUSY return !__gthread_mutex_trylock(&_M_mutex); } void unlock() { // XXX EINVAL, EAGAIN, EPERM __gthread_mutex_unlock(&_M_mutex); } native_handle_type native_handle() noexcept { return &_M_mutex; } }; #endif // _GLIBCXX_HAS_GTHREADS /// Do not acquire ownership of the mutex. struct defer_lock_t { explicit defer_lock_t() = default; }; /// Try to acquire ownership of the mutex without blocking. struct try_to_lock_t { explicit try_to_lock_t() = default; }; /// Assume the calling thread has already obtained mutex ownership /// and manage it. struct adopt_lock_t { explicit adopt_lock_t() = default; }; /// Tag used to prevent a scoped lock from acquiring ownership of a mutex. _GLIBCXX17_INLINE constexpr defer_lock_t defer_lock { }; /// Tag used to prevent a scoped lock from blocking if a mutex is locked. _GLIBCXX17_INLINE constexpr try_to_lock_t try_to_lock { }; /// Tag used to make a scoped lock take ownership of a locked mutex. _GLIBCXX17_INLINE constexpr adopt_lock_t adopt_lock { }; /** @brief A simple scoped lock type. * * A lock_guard controls mutex ownership within a scope, releasing * ownership in the destructor. */ template class lock_guard { public: typedef _Mutex mutex_type; explicit lock_guard(mutex_type& __m) : _M_device(__m) { _M_device.lock(); } lock_guard(mutex_type& __m, adopt_lock_t) noexcept : _M_device(__m) { } // calling thread owns mutex ~lock_guard() { _M_device.unlock(); } lock_guard(const lock_guard&) = delete; lock_guard& operator=(const lock_guard&) = delete; private: mutex_type& _M_device; }; /** @brief A movable scoped lock type. * * A unique_lock controls mutex ownership within a scope. Ownership of the * mutex can be delayed until after construction and can be transferred * to another unique_lock by move construction or move assignment. If a * mutex lock is owned when the destructor runs ownership will be released. */ template class unique_lock { public: typedef _Mutex mutex_type; unique_lock() noexcept : _M_device(0), _M_owns(false) { } explicit unique_lock(mutex_type& __m) : _M_device(std::__addressof(__m)), _M_owns(false) { lock(); _M_owns = true; } unique_lock(mutex_type& __m, defer_lock_t) noexcept : _M_device(std::__addressof(__m)), _M_owns(false) { } unique_lock(mutex_type& __m, try_to_lock_t) : _M_device(std::__addressof(__m)), _M_owns(_M_device->try_lock()) { } unique_lock(mutex_type& __m, adopt_lock_t) noexcept : _M_device(std::__addressof(__m)), _M_owns(true) { // XXX calling thread owns mutex } template unique_lock(mutex_type& __m, const chrono::time_point<_Clock, _Duration>& __atime) : _M_device(std::__addressof(__m)), _M_owns(_M_device->try_lock_until(__atime)) { } template unique_lock(mutex_type& __m, const chrono::duration<_Rep, _Period>& __rtime) : _M_device(std::__addressof(__m)), _M_owns(_M_device->try_lock_for(__rtime)) { } ~unique_lock() { if (_M_owns) unlock(); } unique_lock(const unique_lock&) = delete; unique_lock& operator=(const unique_lock&) = delete; unique_lock(unique_lock&& __u) noexcept : _M_device(__u._M_device), _M_owns(__u._M_owns) { __u._M_device = 0; __u._M_owns = false; } unique_lock& operator=(unique_lock&& __u) noexcept { if(_M_owns) unlock(); unique_lock(std::move(__u)).swap(*this); __u._M_device = 0; __u._M_owns = false; return *this; } void lock() { if (!_M_device) __throw_system_error(int(errc::operation_not_permitted)); else if (_M_owns) __throw_system_error(int(errc::resource_deadlock_would_occur)); else { _M_device->lock(); _M_owns = true; } } bool try_lock() { if (!_M_device) __throw_system_error(int(errc::operation_not_permitted)); else if (_M_owns) __throw_system_error(int(errc::resource_deadlock_would_occur)); else { _M_owns = _M_device->try_lock(); return _M_owns; } } template bool try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime) { if (!_M_device) __throw_system_error(int(errc::operation_not_permitted)); else if (_M_owns) __throw_system_error(int(errc::resource_deadlock_would_occur)); else { _M_owns = _M_device->try_lock_until(__atime); return _M_owns; } } template bool try_lock_for(const chrono::duration<_Rep, _Period>& __rtime) { if (!_M_device) __throw_system_error(int(errc::operation_not_permitted)); else if (_M_owns) __throw_system_error(int(errc::resource_deadlock_would_occur)); else { _M_owns = _M_device->try_lock_for(__rtime); return _M_owns; } } void unlock() { if (!_M_owns) __throw_system_error(int(errc::operation_not_permitted)); else if (_M_device) { _M_device->unlock(); _M_owns = false; } } void swap(unique_lock& __u) noexcept { std::swap(_M_device, __u._M_device); std::swap(_M_owns, __u._M_owns); } mutex_type* release() noexcept { mutex_type* __ret = _M_device; _M_device = 0; _M_owns = false; return __ret; } bool owns_lock() const noexcept { return _M_owns; } explicit operator bool() const noexcept { return owns_lock(); } mutex_type* mutex() const noexcept { return _M_device; } private: mutex_type* _M_device; bool _M_owns; // XXX use atomic_bool }; /// Swap overload for unique_lock objects. template inline void swap(unique_lock<_Mutex>& __x, unique_lock<_Mutex>& __y) noexcept { __x.swap(__y); } // @} group mutexes _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _GLIBCXX_USE_C99_STDINT_TR1 #endif // C++11 #endif // _GLIBCXX_MUTEX_H PK!27B>EE8/bits/stl_algo.hnu[// Algorithm implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_algo.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{algorithm} */ #ifndef _STL_ALGO_H #define _STL_ALGO_H 1 #include // for rand #include #include #include // for _Temporary_buffer #include #if __cplusplus >= 201103L #include #endif // See concept_check.h for the __glibcxx_*_requires macros. namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /// Swaps the median value of *__a, *__b and *__c under __comp to *__result template void __move_median_to_first(_Iterator __result,_Iterator __a, _Iterator __b, _Iterator __c, _Compare __comp) { if (__comp(__a, __b)) { if (__comp(__b, __c)) std::iter_swap(__result, __b); else if (__comp(__a, __c)) std::iter_swap(__result, __c); else std::iter_swap(__result, __a); } else if (__comp(__a, __c)) std::iter_swap(__result, __a); else if (__comp(__b, __c)) std::iter_swap(__result, __c); else std::iter_swap(__result, __b); } /// This is an overload used by find algos for the Input Iterator case. template inline _InputIterator __find_if(_InputIterator __first, _InputIterator __last, _Predicate __pred, input_iterator_tag) { while (__first != __last && !__pred(__first)) ++__first; return __first; } /// This is an overload used by find algos for the RAI case. template _RandomAccessIterator __find_if(_RandomAccessIterator __first, _RandomAccessIterator __last, _Predicate __pred, random_access_iterator_tag) { typename iterator_traits<_RandomAccessIterator>::difference_type __trip_count = (__last - __first) >> 2; for (; __trip_count > 0; --__trip_count) { if (__pred(__first)) return __first; ++__first; if (__pred(__first)) return __first; ++__first; if (__pred(__first)) return __first; ++__first; if (__pred(__first)) return __first; ++__first; } switch (__last - __first) { case 3: if (__pred(__first)) return __first; ++__first; case 2: if (__pred(__first)) return __first; ++__first; case 1: if (__pred(__first)) return __first; ++__first; case 0: default: return __last; } } template inline _Iterator __find_if(_Iterator __first, _Iterator __last, _Predicate __pred) { return __find_if(__first, __last, __pred, std::__iterator_category(__first)); } /// Provided for stable_partition to use. template inline _InputIterator __find_if_not(_InputIterator __first, _InputIterator __last, _Predicate __pred) { return std::__find_if(__first, __last, __gnu_cxx::__ops::__negate(__pred), std::__iterator_category(__first)); } /// Like find_if_not(), but uses and updates a count of the /// remaining range length instead of comparing against an end /// iterator. template _InputIterator __find_if_not_n(_InputIterator __first, _Distance& __len, _Predicate __pred) { for (; __len; --__len, (void) ++__first) if (!__pred(__first)) break; return __first; } // set_difference // set_intersection // set_symmetric_difference // set_union // for_each // find // find_if // find_first_of // adjacent_find // count // count_if // search template _ForwardIterator1 __search(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __predicate) { // Test for empty ranges if (__first1 == __last1 || __first2 == __last2) return __first1; // Test for a pattern of length 1. _ForwardIterator2 __p1(__first2); if (++__p1 == __last2) return std::__find_if(__first1, __last1, __gnu_cxx::__ops::__iter_comp_iter(__predicate, __first2)); // General case. _ForwardIterator2 __p; _ForwardIterator1 __current = __first1; for (;;) { __first1 = std::__find_if(__first1, __last1, __gnu_cxx::__ops::__iter_comp_iter(__predicate, __first2)); if (__first1 == __last1) return __last1; __p = __p1; __current = __first1; if (++__current == __last1) return __last1; while (__predicate(__current, __p)) { if (++__p == __last2) return __first1; if (++__current == __last1) return __last1; } ++__first1; } return __first1; } // search_n /** * This is an helper function for search_n overloaded for forward iterators. */ template _ForwardIterator __search_n_aux(_ForwardIterator __first, _ForwardIterator __last, _Integer __count, _UnaryPredicate __unary_pred, std::forward_iterator_tag) { __first = std::__find_if(__first, __last, __unary_pred); while (__first != __last) { typename iterator_traits<_ForwardIterator>::difference_type __n = __count; _ForwardIterator __i = __first; ++__i; while (__i != __last && __n != 1 && __unary_pred(__i)) { ++__i; --__n; } if (__n == 1) return __first; if (__i == __last) return __last; __first = std::__find_if(++__i, __last, __unary_pred); } return __last; } /** * This is an helper function for search_n overloaded for random access * iterators. */ template _RandomAccessIter __search_n_aux(_RandomAccessIter __first, _RandomAccessIter __last, _Integer __count, _UnaryPredicate __unary_pred, std::random_access_iterator_tag) { typedef typename std::iterator_traits<_RandomAccessIter>::difference_type _DistanceType; _DistanceType __tailSize = __last - __first; _DistanceType __remainder = __count; while (__remainder <= __tailSize) // the main loop... { __first += __remainder; __tailSize -= __remainder; // __first here is always pointing to one past the last element of // next possible match. _RandomAccessIter __backTrack = __first; while (__unary_pred(--__backTrack)) { if (--__remainder == 0) return (__first - __count); // Success } __remainder = __count + 1 - (__first - __backTrack); } return __last; // Failure } template _ForwardIterator __search_n(_ForwardIterator __first, _ForwardIterator __last, _Integer __count, _UnaryPredicate __unary_pred) { if (__count <= 0) return __first; if (__count == 1) return std::__find_if(__first, __last, __unary_pred); return std::__search_n_aux(__first, __last, __count, __unary_pred, std::__iterator_category(__first)); } // find_end for forward iterators. template _ForwardIterator1 __find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2, forward_iterator_tag, forward_iterator_tag, _BinaryPredicate __comp) { if (__first2 == __last2) return __last1; _ForwardIterator1 __result = __last1; while (1) { _ForwardIterator1 __new_result = std::__search(__first1, __last1, __first2, __last2, __comp); if (__new_result == __last1) return __result; else { __result = __new_result; __first1 = __new_result; ++__first1; } } } // find_end for bidirectional iterators (much faster). template _BidirectionalIterator1 __find_end(_BidirectionalIterator1 __first1, _BidirectionalIterator1 __last1, _BidirectionalIterator2 __first2, _BidirectionalIterator2 __last2, bidirectional_iterator_tag, bidirectional_iterator_tag, _BinaryPredicate __comp) { // concept requirements __glibcxx_function_requires(_BidirectionalIteratorConcept< _BidirectionalIterator1>) __glibcxx_function_requires(_BidirectionalIteratorConcept< _BidirectionalIterator2>) typedef reverse_iterator<_BidirectionalIterator1> _RevIterator1; typedef reverse_iterator<_BidirectionalIterator2> _RevIterator2; _RevIterator1 __rlast1(__first1); _RevIterator2 __rlast2(__first2); _RevIterator1 __rresult = std::__search(_RevIterator1(__last1), __rlast1, _RevIterator2(__last2), __rlast2, __comp); if (__rresult == __rlast1) return __last1; else { _BidirectionalIterator1 __result = __rresult.base(); std::advance(__result, -std::distance(__first2, __last2)); return __result; } } /** * @brief Find last matching subsequence in a sequence. * @ingroup non_mutating_algorithms * @param __first1 Start of range to search. * @param __last1 End of range to search. * @param __first2 Start of sequence to match. * @param __last2 End of sequence to match. * @return The last iterator @c i in the range * @p [__first1,__last1-(__last2-__first2)) such that @c *(i+N) == * @p *(__first2+N) for each @c N in the range @p * [0,__last2-__first2), or @p __last1 if no such iterator exists. * * Searches the range @p [__first1,__last1) for a sub-sequence that * compares equal value-by-value with the sequence given by @p * [__first2,__last2) and returns an iterator to the __first * element of the sub-sequence, or @p __last1 if the sub-sequence * is not found. The sub-sequence will be the last such * subsequence contained in [__first1,__last1). * * Because the sub-sequence must lie completely within the range @p * [__first1,__last1) it must start at a position less than @p * __last1-(__last2-__first2) where @p __last2-__first2 is the * length of the sub-sequence. This means that the returned * iterator @c i will be in the range @p * [__first1,__last1-(__last2-__first2)) */ template inline _ForwardIterator1 find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator1>) __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator2>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_ForwardIterator1>::value_type, typename iterator_traits<_ForwardIterator2>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return std::__find_end(__first1, __last1, __first2, __last2, std::__iterator_category(__first1), std::__iterator_category(__first2), __gnu_cxx::__ops::__iter_equal_to_iter()); } /** * @brief Find last matching subsequence in a sequence using a predicate. * @ingroup non_mutating_algorithms * @param __first1 Start of range to search. * @param __last1 End of range to search. * @param __first2 Start of sequence to match. * @param __last2 End of sequence to match. * @param __comp The predicate to use. * @return The last iterator @c i in the range @p * [__first1,__last1-(__last2-__first2)) such that @c * predicate(*(i+N), @p (__first2+N)) is true for each @c N in the * range @p [0,__last2-__first2), or @p __last1 if no such iterator * exists. * * Searches the range @p [__first1,__last1) for a sub-sequence that * compares equal value-by-value with the sequence given by @p * [__first2,__last2) using comp as a predicate and returns an * iterator to the first element of the sub-sequence, or @p __last1 * if the sub-sequence is not found. The sub-sequence will be the * last such subsequence contained in [__first,__last1). * * Because the sub-sequence must lie completely within the range @p * [__first1,__last1) it must start at a position less than @p * __last1-(__last2-__first2) where @p __last2-__first2 is the * length of the sub-sequence. This means that the returned * iterator @c i will be in the range @p * [__first1,__last1-(__last2-__first2)) */ template inline _ForwardIterator1 find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __comp) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator1>) __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator2>) __glibcxx_function_requires(_BinaryPredicateConcept<_BinaryPredicate, typename iterator_traits<_ForwardIterator1>::value_type, typename iterator_traits<_ForwardIterator2>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return std::__find_end(__first1, __last1, __first2, __last2, std::__iterator_category(__first1), std::__iterator_category(__first2), __gnu_cxx::__ops::__iter_comp_iter(__comp)); } #if __cplusplus >= 201103L /** * @brief Checks that a predicate is true for all the elements * of a sequence. * @ingroup non_mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __pred A predicate. * @return True if the check is true, false otherwise. * * Returns true if @p __pred is true for each element in the range * @p [__first,__last), and false otherwise. */ template inline bool all_of(_InputIterator __first, _InputIterator __last, _Predicate __pred) { return __last == std::find_if_not(__first, __last, __pred); } /** * @brief Checks that a predicate is false for all the elements * of a sequence. * @ingroup non_mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __pred A predicate. * @return True if the check is true, false otherwise. * * Returns true if @p __pred is false for each element in the range * @p [__first,__last), and false otherwise. */ template inline bool none_of(_InputIterator __first, _InputIterator __last, _Predicate __pred) { return __last == _GLIBCXX_STD_A::find_if(__first, __last, __pred); } /** * @brief Checks that a predicate is false for at least an element * of a sequence. * @ingroup non_mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __pred A predicate. * @return True if the check is true, false otherwise. * * Returns true if an element exists in the range @p * [__first,__last) such that @p __pred is true, and false * otherwise. */ template inline bool any_of(_InputIterator __first, _InputIterator __last, _Predicate __pred) { return !std::none_of(__first, __last, __pred); } /** * @brief Find the first element in a sequence for which a * predicate is false. * @ingroup non_mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __pred A predicate. * @return The first iterator @c i in the range @p [__first,__last) * such that @p __pred(*i) is false, or @p __last if no such iterator exists. */ template inline _InputIterator find_if_not(_InputIterator __first, _InputIterator __last, _Predicate __pred) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_UnaryPredicateConcept<_Predicate, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__find_if_not(__first, __last, __gnu_cxx::__ops::__pred_iter(__pred)); } /** * @brief Checks whether the sequence is partitioned. * @ingroup mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __pred A predicate. * @return True if the range @p [__first,__last) is partioned by @p __pred, * i.e. if all elements that satisfy @p __pred appear before those that * do not. */ template inline bool is_partitioned(_InputIterator __first, _InputIterator __last, _Predicate __pred) { __first = std::find_if_not(__first, __last, __pred); if (__first == __last) return true; ++__first; return std::none_of(__first, __last, __pred); } /** * @brief Find the partition point of a partitioned range. * @ingroup mutating_algorithms * @param __first An iterator. * @param __last Another iterator. * @param __pred A predicate. * @return An iterator @p mid such that @p all_of(__first, mid, __pred) * and @p none_of(mid, __last, __pred) are both true. */ template _ForwardIterator partition_point(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_UnaryPredicateConcept<_Predicate, typename iterator_traits<_ForwardIterator>::value_type>) // A specific debug-mode test will be necessary... __glibcxx_requires_valid_range(__first, __last); typedef typename iterator_traits<_ForwardIterator>::difference_type _DistanceType; _DistanceType __len = std::distance(__first, __last); _DistanceType __half; _ForwardIterator __middle; while (__len > 0) { __half = __len >> 1; __middle = __first; std::advance(__middle, __half); if (__pred(*__middle)) { __first = __middle; ++__first; __len = __len - __half - 1; } else __len = __half; } return __first; } #endif template _OutputIterator __remove_copy_if(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _Predicate __pred) { for (; __first != __last; ++__first) if (!__pred(__first)) { *__result = *__first; ++__result; } return __result; } /** * @brief Copy a sequence, removing elements of a given value. * @ingroup mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __result An output iterator. * @param __value The value to be removed. * @return An iterator designating the end of the resulting sequence. * * Copies each element in the range @p [__first,__last) not equal * to @p __value to the range beginning at @p __result. * remove_copy() is stable, so the relative order of elements that * are copied is unchanged. */ template inline _OutputIterator remove_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result, const _Tp& __value) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_InputIterator>::value_type, _Tp>) __glibcxx_requires_valid_range(__first, __last); return std::__remove_copy_if(__first, __last, __result, __gnu_cxx::__ops::__iter_equals_val(__value)); } /** * @brief Copy a sequence, removing elements for which a predicate is true. * @ingroup mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __result An output iterator. * @param __pred A predicate. * @return An iterator designating the end of the resulting sequence. * * Copies each element in the range @p [__first,__last) for which * @p __pred returns false to the range beginning at @p __result. * * remove_copy_if() is stable, so the relative order of elements that are * copied is unchanged. */ template inline _OutputIterator remove_copy_if(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _Predicate __pred) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_function_requires(_UnaryPredicateConcept<_Predicate, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__remove_copy_if(__first, __last, __result, __gnu_cxx::__ops::__pred_iter(__pred)); } #if __cplusplus >= 201103L /** * @brief Copy the elements of a sequence for which a predicate is true. * @ingroup mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __result An output iterator. * @param __pred A predicate. * @return An iterator designating the end of the resulting sequence. * * Copies each element in the range @p [__first,__last) for which * @p __pred returns true to the range beginning at @p __result. * * copy_if() is stable, so the relative order of elements that are * copied is unchanged. */ template _OutputIterator copy_if(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _Predicate __pred) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_function_requires(_UnaryPredicateConcept<_Predicate, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first) if (__pred(*__first)) { *__result = *__first; ++__result; } return __result; } template _OutputIterator __copy_n(_InputIterator __first, _Size __n, _OutputIterator __result, input_iterator_tag) { if (__n > 0) { while (true) { *__result = *__first; ++__result; if (--__n > 0) ++__first; else break; } } return __result; } template inline _OutputIterator __copy_n(_RandomAccessIterator __first, _Size __n, _OutputIterator __result, random_access_iterator_tag) { return std::copy(__first, __first + __n, __result); } /** * @brief Copies the range [first,first+n) into [result,result+n). * @ingroup mutating_algorithms * @param __first An input iterator. * @param __n The number of elements to copy. * @param __result An output iterator. * @return result+n. * * This inline function will boil down to a call to @c memmove whenever * possible. Failing that, if random access iterators are passed, then the * loop count will be known (and therefore a candidate for compiler * optimizations such as unrolling). */ template inline _OutputIterator copy_n(_InputIterator __first, _Size __n, _OutputIterator __result) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator>::value_type>) return std::__copy_n(__first, __n, __result, std::__iterator_category(__first)); } /** * @brief Copy the elements of a sequence to separate output sequences * depending on the truth value of a predicate. * @ingroup mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __out_true An output iterator. * @param __out_false An output iterator. * @param __pred A predicate. * @return A pair designating the ends of the resulting sequences. * * Copies each element in the range @p [__first,__last) for which * @p __pred returns true to the range beginning at @p out_true * and each element for which @p __pred returns false to @p __out_false. */ template pair<_OutputIterator1, _OutputIterator2> partition_copy(_InputIterator __first, _InputIterator __last, _OutputIterator1 __out_true, _OutputIterator2 __out_false, _Predicate __pred) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator1, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator2, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_function_requires(_UnaryPredicateConcept<_Predicate, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first) if (__pred(*__first)) { *__out_true = *__first; ++__out_true; } else { *__out_false = *__first; ++__out_false; } return pair<_OutputIterator1, _OutputIterator2>(__out_true, __out_false); } #endif template _ForwardIterator __remove_if(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred) { __first = std::__find_if(__first, __last, __pred); if (__first == __last) return __first; _ForwardIterator __result = __first; ++__first; for (; __first != __last; ++__first) if (!__pred(__first)) { *__result = _GLIBCXX_MOVE(*__first); ++__result; } return __result; } /** * @brief Remove elements from a sequence. * @ingroup mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __value The value to be removed. * @return An iterator designating the end of the resulting sequence. * * All elements equal to @p __value are removed from the range * @p [__first,__last). * * remove() is stable, so the relative order of elements that are * not removed is unchanged. * * Elements between the end of the resulting sequence and @p __last * are still present, but their value is unspecified. */ template inline _ForwardIterator remove(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_ForwardIterator>::value_type, _Tp>) __glibcxx_requires_valid_range(__first, __last); return std::__remove_if(__first, __last, __gnu_cxx::__ops::__iter_equals_val(__value)); } /** * @brief Remove elements from a sequence using a predicate. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @param __pred A predicate. * @return An iterator designating the end of the resulting sequence. * * All elements for which @p __pred returns true are removed from the range * @p [__first,__last). * * remove_if() is stable, so the relative order of elements that are * not removed is unchanged. * * Elements between the end of the resulting sequence and @p __last * are still present, but their value is unspecified. */ template inline _ForwardIterator remove_if(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator>) __glibcxx_function_requires(_UnaryPredicateConcept<_Predicate, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__remove_if(__first, __last, __gnu_cxx::__ops::__pred_iter(__pred)); } template _ForwardIterator __adjacent_find(_ForwardIterator __first, _ForwardIterator __last, _BinaryPredicate __binary_pred) { if (__first == __last) return __last; _ForwardIterator __next = __first; while (++__next != __last) { if (__binary_pred(__first, __next)) return __first; __first = __next; } return __last; } template _ForwardIterator __unique(_ForwardIterator __first, _ForwardIterator __last, _BinaryPredicate __binary_pred) { // Skip the beginning, if already unique. __first = std::__adjacent_find(__first, __last, __binary_pred); if (__first == __last) return __last; // Do the real copy work. _ForwardIterator __dest = __first; ++__first; while (++__first != __last) if (!__binary_pred(__dest, __first)) *++__dest = _GLIBCXX_MOVE(*__first); return ++__dest; } /** * @brief Remove consecutive duplicate values from a sequence. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @return An iterator designating the end of the resulting sequence. * * Removes all but the first element from each group of consecutive * values that compare equal. * unique() is stable, so the relative order of elements that are * not removed is unchanged. * Elements between the end of the resulting sequence and @p __last * are still present, but their value is unspecified. */ template inline _ForwardIterator unique(_ForwardIterator __first, _ForwardIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator>) __glibcxx_function_requires(_EqualityComparableConcept< typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__unique(__first, __last, __gnu_cxx::__ops::__iter_equal_to_iter()); } /** * @brief Remove consecutive values from a sequence using a predicate. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @param __binary_pred A binary predicate. * @return An iterator designating the end of the resulting sequence. * * Removes all but the first element from each group of consecutive * values for which @p __binary_pred returns true. * unique() is stable, so the relative order of elements that are * not removed is unchanged. * Elements between the end of the resulting sequence and @p __last * are still present, but their value is unspecified. */ template inline _ForwardIterator unique(_ForwardIterator __first, _ForwardIterator __last, _BinaryPredicate __binary_pred) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_BinaryPredicate, typename iterator_traits<_ForwardIterator>::value_type, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__unique(__first, __last, __gnu_cxx::__ops::__iter_comp_iter(__binary_pred)); } /** * This is an uglified * unique_copy(_InputIterator, _InputIterator, _OutputIterator, * _BinaryPredicate) * overloaded for forward iterators and output iterator as result. */ template _OutputIterator __unique_copy(_ForwardIterator __first, _ForwardIterator __last, _OutputIterator __result, _BinaryPredicate __binary_pred, forward_iterator_tag, output_iterator_tag) { // concept requirements -- iterators already checked __glibcxx_function_requires(_BinaryPredicateConcept<_BinaryPredicate, typename iterator_traits<_ForwardIterator>::value_type, typename iterator_traits<_ForwardIterator>::value_type>) _ForwardIterator __next = __first; *__result = *__first; while (++__next != __last) if (!__binary_pred(__first, __next)) { __first = __next; *++__result = *__first; } return ++__result; } /** * This is an uglified * unique_copy(_InputIterator, _InputIterator, _OutputIterator, * _BinaryPredicate) * overloaded for input iterators and output iterator as result. */ template _OutputIterator __unique_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _BinaryPredicate __binary_pred, input_iterator_tag, output_iterator_tag) { // concept requirements -- iterators already checked __glibcxx_function_requires(_BinaryPredicateConcept<_BinaryPredicate, typename iterator_traits<_InputIterator>::value_type, typename iterator_traits<_InputIterator>::value_type>) typename iterator_traits<_InputIterator>::value_type __value = *__first; __decltype(__gnu_cxx::__ops::__iter_comp_val(__binary_pred)) __rebound_pred = __gnu_cxx::__ops::__iter_comp_val(__binary_pred); *__result = __value; while (++__first != __last) if (!__rebound_pred(__first, __value)) { __value = *__first; *++__result = __value; } return ++__result; } /** * This is an uglified * unique_copy(_InputIterator, _InputIterator, _OutputIterator, * _BinaryPredicate) * overloaded for input iterators and forward iterator as result. */ template _ForwardIterator __unique_copy(_InputIterator __first, _InputIterator __last, _ForwardIterator __result, _BinaryPredicate __binary_pred, input_iterator_tag, forward_iterator_tag) { // concept requirements -- iterators already checked __glibcxx_function_requires(_BinaryPredicateConcept<_BinaryPredicate, typename iterator_traits<_ForwardIterator>::value_type, typename iterator_traits<_InputIterator>::value_type>) *__result = *__first; while (++__first != __last) if (!__binary_pred(__result, __first)) *++__result = *__first; return ++__result; } /** * This is an uglified reverse(_BidirectionalIterator, * _BidirectionalIterator) * overloaded for bidirectional iterators. */ template void __reverse(_BidirectionalIterator __first, _BidirectionalIterator __last, bidirectional_iterator_tag) { while (true) if (__first == __last || __first == --__last) return; else { std::iter_swap(__first, __last); ++__first; } } /** * This is an uglified reverse(_BidirectionalIterator, * _BidirectionalIterator) * overloaded for random access iterators. */ template void __reverse(_RandomAccessIterator __first, _RandomAccessIterator __last, random_access_iterator_tag) { if (__first == __last) return; --__last; while (__first < __last) { std::iter_swap(__first, __last); ++__first; --__last; } } /** * @brief Reverse a sequence. * @ingroup mutating_algorithms * @param __first A bidirectional iterator. * @param __last A bidirectional iterator. * @return reverse() returns no value. * * Reverses the order of the elements in the range @p [__first,__last), * so that the first element becomes the last etc. * For every @c i such that @p 0<=i<=(__last-__first)/2), @p reverse() * swaps @p *(__first+i) and @p *(__last-(i+1)) */ template inline void reverse(_BidirectionalIterator __first, _BidirectionalIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_BidirectionalIteratorConcept< _BidirectionalIterator>) __glibcxx_requires_valid_range(__first, __last); std::__reverse(__first, __last, std::__iterator_category(__first)); } /** * @brief Copy a sequence, reversing its elements. * @ingroup mutating_algorithms * @param __first A bidirectional iterator. * @param __last A bidirectional iterator. * @param __result An output iterator. * @return An iterator designating the end of the resulting sequence. * * Copies the elements in the range @p [__first,__last) to the * range @p [__result,__result+(__last-__first)) such that the * order of the elements is reversed. For every @c i such that @p * 0<=i<=(__last-__first), @p reverse_copy() performs the * assignment @p *(__result+(__last-__first)-1-i) = *(__first+i). * The ranges @p [__first,__last) and @p * [__result,__result+(__last-__first)) must not overlap. */ template _OutputIterator reverse_copy(_BidirectionalIterator __first, _BidirectionalIterator __last, _OutputIterator __result) { // concept requirements __glibcxx_function_requires(_BidirectionalIteratorConcept< _BidirectionalIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_BidirectionalIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); while (__first != __last) { --__last; *__result = *__last; ++__result; } return __result; } /** * This is a helper function for the rotate algorithm specialized on RAIs. * It returns the greatest common divisor of two integer values. */ template _EuclideanRingElement __gcd(_EuclideanRingElement __m, _EuclideanRingElement __n) { while (__n != 0) { _EuclideanRingElement __t = __m % __n; __m = __n; __n = __t; } return __m; } inline namespace _V2 { /// This is a helper function for the rotate algorithm. template _ForwardIterator __rotate(_ForwardIterator __first, _ForwardIterator __middle, _ForwardIterator __last, forward_iterator_tag) { if (__first == __middle) return __last; else if (__last == __middle) return __first; _ForwardIterator __first2 = __middle; do { std::iter_swap(__first, __first2); ++__first; ++__first2; if (__first == __middle) __middle = __first2; } while (__first2 != __last); _ForwardIterator __ret = __first; __first2 = __middle; while (__first2 != __last) { std::iter_swap(__first, __first2); ++__first; ++__first2; if (__first == __middle) __middle = __first2; else if (__first2 == __last) __first2 = __middle; } return __ret; } /// This is a helper function for the rotate algorithm. template _BidirectionalIterator __rotate(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last, bidirectional_iterator_tag) { // concept requirements __glibcxx_function_requires(_Mutable_BidirectionalIteratorConcept< _BidirectionalIterator>) if (__first == __middle) return __last; else if (__last == __middle) return __first; std::__reverse(__first, __middle, bidirectional_iterator_tag()); std::__reverse(__middle, __last, bidirectional_iterator_tag()); while (__first != __middle && __middle != __last) { std::iter_swap(__first, --__last); ++__first; } if (__first == __middle) { std::__reverse(__middle, __last, bidirectional_iterator_tag()); return __last; } else { std::__reverse(__first, __middle, bidirectional_iterator_tag()); return __first; } } /// This is a helper function for the rotate algorithm. template _RandomAccessIterator __rotate(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last, random_access_iterator_tag) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) if (__first == __middle) return __last; else if (__last == __middle) return __first; typedef typename iterator_traits<_RandomAccessIterator>::difference_type _Distance; typedef typename iterator_traits<_RandomAccessIterator>::value_type _ValueType; _Distance __n = __last - __first; _Distance __k = __middle - __first; if (__k == __n - __k) { std::swap_ranges(__first, __middle, __middle); return __middle; } _RandomAccessIterator __p = __first; _RandomAccessIterator __ret = __first + (__last - __middle); for (;;) { if (__k < __n - __k) { if (__is_pod(_ValueType) && __k == 1) { _ValueType __t = _GLIBCXX_MOVE(*__p); _GLIBCXX_MOVE3(__p + 1, __p + __n, __p); *(__p + __n - 1) = _GLIBCXX_MOVE(__t); return __ret; } _RandomAccessIterator __q = __p + __k; for (_Distance __i = 0; __i < __n - __k; ++ __i) { std::iter_swap(__p, __q); ++__p; ++__q; } __n %= __k; if (__n == 0) return __ret; std::swap(__n, __k); __k = __n - __k; } else { __k = __n - __k; if (__is_pod(_ValueType) && __k == 1) { _ValueType __t = _GLIBCXX_MOVE(*(__p + __n - 1)); _GLIBCXX_MOVE_BACKWARD3(__p, __p + __n - 1, __p + __n); *__p = _GLIBCXX_MOVE(__t); return __ret; } _RandomAccessIterator __q = __p + __n; __p = __q - __k; for (_Distance __i = 0; __i < __n - __k; ++ __i) { --__p; --__q; std::iter_swap(__p, __q); } __n %= __k; if (__n == 0) return __ret; std::swap(__n, __k); } } } // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 488. rotate throws away useful information /** * @brief Rotate the elements of a sequence. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __middle A forward iterator. * @param __last A forward iterator. * @return first + (last - middle). * * Rotates the elements of the range @p [__first,__last) by * @p (__middle - __first) positions so that the element at @p __middle * is moved to @p __first, the element at @p __middle+1 is moved to * @p __first+1 and so on for each element in the range * @p [__first,__last). * * This effectively swaps the ranges @p [__first,__middle) and * @p [__middle,__last). * * Performs * @p *(__first+(n+(__last-__middle))%(__last-__first))=*(__first+n) * for each @p n in the range @p [0,__last-__first). */ template inline _ForwardIterator rotate(_ForwardIterator __first, _ForwardIterator __middle, _ForwardIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator>) __glibcxx_requires_valid_range(__first, __middle); __glibcxx_requires_valid_range(__middle, __last); return std::__rotate(__first, __middle, __last, std::__iterator_category(__first)); } } // namespace _V2 /** * @brief Copy a sequence, rotating its elements. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __middle A forward iterator. * @param __last A forward iterator. * @param __result An output iterator. * @return An iterator designating the end of the resulting sequence. * * Copies the elements of the range @p [__first,__last) to the * range beginning at @result, rotating the copied elements by * @p (__middle-__first) positions so that the element at @p __middle * is moved to @p __result, the element at @p __middle+1 is moved * to @p __result+1 and so on for each element in the range @p * [__first,__last). * * Performs * @p *(__result+(n+(__last-__middle))%(__last-__first))=*(__first+n) * for each @p n in the range @p [0,__last-__first). */ template inline _OutputIterator rotate_copy(_ForwardIterator __first, _ForwardIterator __middle, _ForwardIterator __last, _OutputIterator __result) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __middle); __glibcxx_requires_valid_range(__middle, __last); return std::copy(__first, __middle, std::copy(__middle, __last, __result)); } /// This is a helper function... template _ForwardIterator __partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred, forward_iterator_tag) { if (__first == __last) return __first; while (__pred(*__first)) if (++__first == __last) return __first; _ForwardIterator __next = __first; while (++__next != __last) if (__pred(*__next)) { std::iter_swap(__first, __next); ++__first; } return __first; } /// This is a helper function... template _BidirectionalIterator __partition(_BidirectionalIterator __first, _BidirectionalIterator __last, _Predicate __pred, bidirectional_iterator_tag) { while (true) { while (true) if (__first == __last) return __first; else if (__pred(*__first)) ++__first; else break; --__last; while (true) if (__first == __last) return __first; else if (!bool(__pred(*__last))) --__last; else break; std::iter_swap(__first, __last); ++__first; } } // partition /// This is a helper function... /// Requires __first != __last and !__pred(__first) /// and __len == distance(__first, __last). /// /// !__pred(__first) allows us to guarantee that we don't /// move-assign an element onto itself. template _ForwardIterator __stable_partition_adaptive(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred, _Distance __len, _Pointer __buffer, _Distance __buffer_size) { if (__len == 1) return __first; if (__len <= __buffer_size) { _ForwardIterator __result1 = __first; _Pointer __result2 = __buffer; // The precondition guarantees that !__pred(__first), so // move that element to the buffer before starting the loop. // This ensures that we only call __pred once per element. *__result2 = _GLIBCXX_MOVE(*__first); ++__result2; ++__first; for (; __first != __last; ++__first) if (__pred(__first)) { *__result1 = _GLIBCXX_MOVE(*__first); ++__result1; } else { *__result2 = _GLIBCXX_MOVE(*__first); ++__result2; } _GLIBCXX_MOVE3(__buffer, __result2, __result1); return __result1; } _ForwardIterator __middle = __first; std::advance(__middle, __len / 2); _ForwardIterator __left_split = std::__stable_partition_adaptive(__first, __middle, __pred, __len / 2, __buffer, __buffer_size); // Advance past true-predicate values to satisfy this // function's preconditions. _Distance __right_len = __len - __len / 2; _ForwardIterator __right_split = std::__find_if_not_n(__middle, __right_len, __pred); if (__right_len) __right_split = std::__stable_partition_adaptive(__right_split, __last, __pred, __right_len, __buffer, __buffer_size); std::rotate(__left_split, __middle, __right_split); std::advance(__left_split, std::distance(__middle, __right_split)); return __left_split; } template _ForwardIterator __stable_partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred) { __first = std::__find_if_not(__first, __last, __pred); if (__first == __last) return __first; typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; typedef typename iterator_traits<_ForwardIterator>::difference_type _DistanceType; _Temporary_buffer<_ForwardIterator, _ValueType> __buf(__first, __last); return std::__stable_partition_adaptive(__first, __last, __pred, _DistanceType(__buf.requested_size()), __buf.begin(), _DistanceType(__buf.size())); } /** * @brief Move elements for which a predicate is true to the beginning * of a sequence, preserving relative ordering. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @param __pred A predicate functor. * @return An iterator @p middle such that @p __pred(i) is true for each * iterator @p i in the range @p [first,middle) and false for each @p i * in the range @p [middle,last). * * Performs the same function as @p partition() with the additional * guarantee that the relative ordering of elements in each group is * preserved, so any two elements @p x and @p y in the range * @p [__first,__last) such that @p __pred(x)==__pred(y) will have the same * relative ordering after calling @p stable_partition(). */ template inline _ForwardIterator stable_partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator>) __glibcxx_function_requires(_UnaryPredicateConcept<_Predicate, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__stable_partition(__first, __last, __gnu_cxx::__ops::__pred_iter(__pred)); } /// This is a helper function for the sort routines. template void __heap_select(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last, _Compare __comp) { std::__make_heap(__first, __middle, __comp); for (_RandomAccessIterator __i = __middle; __i < __last; ++__i) if (__comp(__i, __first)) std::__pop_heap(__first, __middle, __i, __comp); } // partial_sort template _RandomAccessIterator __partial_sort_copy(_InputIterator __first, _InputIterator __last, _RandomAccessIterator __result_first, _RandomAccessIterator __result_last, _Compare __comp) { typedef typename iterator_traits<_InputIterator>::value_type _InputValueType; typedef iterator_traits<_RandomAccessIterator> _RItTraits; typedef typename _RItTraits::difference_type _DistanceType; if (__result_first == __result_last) return __result_last; _RandomAccessIterator __result_real_last = __result_first; while (__first != __last && __result_real_last != __result_last) { *__result_real_last = *__first; ++__result_real_last; ++__first; } std::__make_heap(__result_first, __result_real_last, __comp); while (__first != __last) { if (__comp(__first, __result_first)) std::__adjust_heap(__result_first, _DistanceType(0), _DistanceType(__result_real_last - __result_first), _InputValueType(*__first), __comp); ++__first; } std::__sort_heap(__result_first, __result_real_last, __comp); return __result_real_last; } /** * @brief Copy the smallest elements of a sequence. * @ingroup sorting_algorithms * @param __first An iterator. * @param __last Another iterator. * @param __result_first A random-access iterator. * @param __result_last Another random-access iterator. * @return An iterator indicating the end of the resulting sequence. * * Copies and sorts the smallest N values from the range @p [__first,__last) * to the range beginning at @p __result_first, where the number of * elements to be copied, @p N, is the smaller of @p (__last-__first) and * @p (__result_last-__result_first). * After the sort if @e i and @e j are iterators in the range * @p [__result_first,__result_first+N) such that i precedes j then * *j<*i is false. * The value returned is @p __result_first+N. */ template inline _RandomAccessIterator partial_sort_copy(_InputIterator __first, _InputIterator __last, _RandomAccessIterator __result_first, _RandomAccessIterator __result_last) { #ifdef _GLIBCXX_CONCEPT_CHECKS typedef typename iterator_traits<_InputIterator>::value_type _InputValueType; typedef typename iterator_traits<_RandomAccessIterator>::value_type _OutputValueType; #endif // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_ConvertibleConcept<_InputValueType, _OutputValueType>) __glibcxx_function_requires(_LessThanOpConcept<_InputValueType, _OutputValueType>) __glibcxx_function_requires(_LessThanComparableConcept<_OutputValueType>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); __glibcxx_requires_valid_range(__result_first, __result_last); return std::__partial_sort_copy(__first, __last, __result_first, __result_last, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Copy the smallest elements of a sequence using a predicate for * comparison. * @ingroup sorting_algorithms * @param __first An input iterator. * @param __last Another input iterator. * @param __result_first A random-access iterator. * @param __result_last Another random-access iterator. * @param __comp A comparison functor. * @return An iterator indicating the end of the resulting sequence. * * Copies and sorts the smallest N values from the range @p [__first,__last) * to the range beginning at @p result_first, where the number of * elements to be copied, @p N, is the smaller of @p (__last-__first) and * @p (__result_last-__result_first). * After the sort if @e i and @e j are iterators in the range * @p [__result_first,__result_first+N) such that i precedes j then * @p __comp(*j,*i) is false. * The value returned is @p __result_first+N. */ template inline _RandomAccessIterator partial_sort_copy(_InputIterator __first, _InputIterator __last, _RandomAccessIterator __result_first, _RandomAccessIterator __result_last, _Compare __comp) { #ifdef _GLIBCXX_CONCEPT_CHECKS typedef typename iterator_traits<_InputIterator>::value_type _InputValueType; typedef typename iterator_traits<_RandomAccessIterator>::value_type _OutputValueType; #endif // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_ConvertibleConcept<_InputValueType, _OutputValueType>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, _InputValueType, _OutputValueType>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, _OutputValueType, _OutputValueType>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); __glibcxx_requires_valid_range(__result_first, __result_last); return std::__partial_sort_copy(__first, __last, __result_first, __result_last, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } /// This is a helper function for the sort routine. template void __unguarded_linear_insert(_RandomAccessIterator __last, _Compare __comp) { typename iterator_traits<_RandomAccessIterator>::value_type __val = _GLIBCXX_MOVE(*__last); _RandomAccessIterator __next = __last; --__next; while (__comp(__val, __next)) { *__last = _GLIBCXX_MOVE(*__next); __last = __next; --__next; } *__last = _GLIBCXX_MOVE(__val); } /// This is a helper function for the sort routine. template void __insertion_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { if (__first == __last) return; for (_RandomAccessIterator __i = __first + 1; __i != __last; ++__i) { if (__comp(__i, __first)) { typename iterator_traits<_RandomAccessIterator>::value_type __val = _GLIBCXX_MOVE(*__i); _GLIBCXX_MOVE_BACKWARD3(__first, __i, __i + 1); *__first = _GLIBCXX_MOVE(__val); } else std::__unguarded_linear_insert(__i, __gnu_cxx::__ops::__val_comp_iter(__comp)); } } /// This is a helper function for the sort routine. template inline void __unguarded_insertion_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { for (_RandomAccessIterator __i = __first; __i != __last; ++__i) std::__unguarded_linear_insert(__i, __gnu_cxx::__ops::__val_comp_iter(__comp)); } /** * @doctodo * This controls some aspect of the sort routines. */ enum { _S_threshold = 16 }; /// This is a helper function for the sort routine. template void __final_insertion_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { if (__last - __first > int(_S_threshold)) { std::__insertion_sort(__first, __first + int(_S_threshold), __comp); std::__unguarded_insertion_sort(__first + int(_S_threshold), __last, __comp); } else std::__insertion_sort(__first, __last, __comp); } /// This is a helper function... template _RandomAccessIterator __unguarded_partition(_RandomAccessIterator __first, _RandomAccessIterator __last, _RandomAccessIterator __pivot, _Compare __comp) { while (true) { while (__comp(__first, __pivot)) ++__first; --__last; while (__comp(__pivot, __last)) --__last; if (!(__first < __last)) return __first; std::iter_swap(__first, __last); ++__first; } } /// This is a helper function... template inline _RandomAccessIterator __unguarded_partition_pivot(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { _RandomAccessIterator __mid = __first + (__last - __first) / 2; std::__move_median_to_first(__first, __first + 1, __mid, __last - 1, __comp); return std::__unguarded_partition(__first + 1, __last, __first, __comp); } template inline void __partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last, _Compare __comp) { std::__heap_select(__first, __middle, __last, __comp); std::__sort_heap(__first, __middle, __comp); } /// This is a helper function for the sort routine. template void __introsort_loop(_RandomAccessIterator __first, _RandomAccessIterator __last, _Size __depth_limit, _Compare __comp) { while (__last - __first > int(_S_threshold)) { if (__depth_limit == 0) { std::__partial_sort(__first, __last, __last, __comp); return; } --__depth_limit; _RandomAccessIterator __cut = std::__unguarded_partition_pivot(__first, __last, __comp); std::__introsort_loop(__cut, __last, __depth_limit, __comp); __last = __cut; } } // sort template inline void __sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { if (__first != __last) { std::__introsort_loop(__first, __last, std::__lg(__last - __first) * 2, __comp); std::__final_insertion_sort(__first, __last, __comp); } } template void __introselect(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last, _Size __depth_limit, _Compare __comp) { while (__last - __first > 3) { if (__depth_limit == 0) { std::__heap_select(__first, __nth + 1, __last, __comp); // Place the nth largest element in its final position. std::iter_swap(__first, __nth); return; } --__depth_limit; _RandomAccessIterator __cut = std::__unguarded_partition_pivot(__first, __last, __comp); if (__cut <= __nth) __first = __cut; else __last = __cut; } std::__insertion_sort(__first, __last, __comp); } // nth_element // lower_bound moved to stl_algobase.h /** * @brief Finds the first position in which @p __val could be inserted * without changing the ordering. * @ingroup binary_search_algorithms * @param __first An iterator. * @param __last Another iterator. * @param __val The search term. * @param __comp A functor to use for comparisons. * @return An iterator pointing to the first element not less * than @p __val, or end() if every element is less * than @p __val. * @ingroup binary_search_algorithms * * The comparison function should have the same effects on ordering as * the function used for the initial sort. */ template inline _ForwardIterator lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __val, _Compare __comp) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_ForwardIterator>::value_type, _Tp>) __glibcxx_requires_partitioned_lower_pred(__first, __last, __val, __comp); return std::__lower_bound(__first, __last, __val, __gnu_cxx::__ops::__iter_comp_val(__comp)); } template _ForwardIterator __upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __val, _Compare __comp) { typedef typename iterator_traits<_ForwardIterator>::difference_type _DistanceType; _DistanceType __len = std::distance(__first, __last); while (__len > 0) { _DistanceType __half = __len >> 1; _ForwardIterator __middle = __first; std::advance(__middle, __half); if (__comp(__val, __middle)) __len = __half; else { __first = __middle; ++__first; __len = __len - __half - 1; } } return __first; } /** * @brief Finds the last position in which @p __val could be inserted * without changing the ordering. * @ingroup binary_search_algorithms * @param __first An iterator. * @param __last Another iterator. * @param __val The search term. * @return An iterator pointing to the first element greater than @p __val, * or end() if no elements are greater than @p __val. * @ingroup binary_search_algorithms */ template inline _ForwardIterator upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __val) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_LessThanOpConcept< _Tp, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_partitioned_upper(__first, __last, __val); return std::__upper_bound(__first, __last, __val, __gnu_cxx::__ops::__val_less_iter()); } /** * @brief Finds the last position in which @p __val could be inserted * without changing the ordering. * @ingroup binary_search_algorithms * @param __first An iterator. * @param __last Another iterator. * @param __val The search term. * @param __comp A functor to use for comparisons. * @return An iterator pointing to the first element greater than @p __val, * or end() if no elements are greater than @p __val. * @ingroup binary_search_algorithms * * The comparison function should have the same effects on ordering as * the function used for the initial sort. */ template inline _ForwardIterator upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __val, _Compare __comp) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, _Tp, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_partitioned_upper_pred(__first, __last, __val, __comp); return std::__upper_bound(__first, __last, __val, __gnu_cxx::__ops::__val_comp_iter(__comp)); } template pair<_ForwardIterator, _ForwardIterator> __equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __val, _CompareItTp __comp_it_val, _CompareTpIt __comp_val_it) { typedef typename iterator_traits<_ForwardIterator>::difference_type _DistanceType; _DistanceType __len = std::distance(__first, __last); while (__len > 0) { _DistanceType __half = __len >> 1; _ForwardIterator __middle = __first; std::advance(__middle, __half); if (__comp_it_val(__middle, __val)) { __first = __middle; ++__first; __len = __len - __half - 1; } else if (__comp_val_it(__val, __middle)) __len = __half; else { _ForwardIterator __left = std::__lower_bound(__first, __middle, __val, __comp_it_val); std::advance(__first, __len); _ForwardIterator __right = std::__upper_bound(++__middle, __first, __val, __comp_val_it); return pair<_ForwardIterator, _ForwardIterator>(__left, __right); } } return pair<_ForwardIterator, _ForwardIterator>(__first, __first); } /** * @brief Finds the largest subrange in which @p __val could be inserted * at any place in it without changing the ordering. * @ingroup binary_search_algorithms * @param __first An iterator. * @param __last Another iterator. * @param __val The search term. * @return An pair of iterators defining the subrange. * @ingroup binary_search_algorithms * * This is equivalent to * @code * std::make_pair(lower_bound(__first, __last, __val), * upper_bound(__first, __last, __val)) * @endcode * but does not actually call those functions. */ template inline pair<_ForwardIterator, _ForwardIterator> equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __val) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_LessThanOpConcept< typename iterator_traits<_ForwardIterator>::value_type, _Tp>) __glibcxx_function_requires(_LessThanOpConcept< _Tp, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_partitioned_lower(__first, __last, __val); __glibcxx_requires_partitioned_upper(__first, __last, __val); return std::__equal_range(__first, __last, __val, __gnu_cxx::__ops::__iter_less_val(), __gnu_cxx::__ops::__val_less_iter()); } /** * @brief Finds the largest subrange in which @p __val could be inserted * at any place in it without changing the ordering. * @param __first An iterator. * @param __last Another iterator. * @param __val The search term. * @param __comp A functor to use for comparisons. * @return An pair of iterators defining the subrange. * @ingroup binary_search_algorithms * * This is equivalent to * @code * std::make_pair(lower_bound(__first, __last, __val, __comp), * upper_bound(__first, __last, __val, __comp)) * @endcode * but does not actually call those functions. */ template inline pair<_ForwardIterator, _ForwardIterator> equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __val, _Compare __comp) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_ForwardIterator>::value_type, _Tp>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, _Tp, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_partitioned_lower_pred(__first, __last, __val, __comp); __glibcxx_requires_partitioned_upper_pred(__first, __last, __val, __comp); return std::__equal_range(__first, __last, __val, __gnu_cxx::__ops::__iter_comp_val(__comp), __gnu_cxx::__ops::__val_comp_iter(__comp)); } /** * @brief Determines whether an element exists in a range. * @ingroup binary_search_algorithms * @param __first An iterator. * @param __last Another iterator. * @param __val The search term. * @return True if @p __val (or its equivalent) is in [@p * __first,@p __last ]. * * Note that this does not actually return an iterator to @p __val. For * that, use std::find or a container's specialized find member functions. */ template bool binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __val) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_LessThanOpConcept< _Tp, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_partitioned_lower(__first, __last, __val); __glibcxx_requires_partitioned_upper(__first, __last, __val); _ForwardIterator __i = std::__lower_bound(__first, __last, __val, __gnu_cxx::__ops::__iter_less_val()); return __i != __last && !(__val < *__i); } /** * @brief Determines whether an element exists in a range. * @ingroup binary_search_algorithms * @param __first An iterator. * @param __last Another iterator. * @param __val The search term. * @param __comp A functor to use for comparisons. * @return True if @p __val (or its equivalent) is in @p [__first,__last]. * * Note that this does not actually return an iterator to @p __val. For * that, use std::find or a container's specialized find member functions. * * The comparison function should have the same effects on ordering as * the function used for the initial sort. */ template bool binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __val, _Compare __comp) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, _Tp, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_partitioned_lower_pred(__first, __last, __val, __comp); __glibcxx_requires_partitioned_upper_pred(__first, __last, __val, __comp); _ForwardIterator __i = std::__lower_bound(__first, __last, __val, __gnu_cxx::__ops::__iter_comp_val(__comp)); return __i != __last && !bool(__comp(__val, *__i)); } // merge /// This is a helper function for the __merge_adaptive routines. template void __move_merge_adaptive(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) { while (__first1 != __last1 && __first2 != __last2) { if (__comp(__first2, __first1)) { *__result = _GLIBCXX_MOVE(*__first2); ++__first2; } else { *__result = _GLIBCXX_MOVE(*__first1); ++__first1; } ++__result; } if (__first1 != __last1) _GLIBCXX_MOVE3(__first1, __last1, __result); } /// This is a helper function for the __merge_adaptive routines. template void __move_merge_adaptive_backward(_BidirectionalIterator1 __first1, _BidirectionalIterator1 __last1, _BidirectionalIterator2 __first2, _BidirectionalIterator2 __last2, _BidirectionalIterator3 __result, _Compare __comp) { if (__first1 == __last1) { _GLIBCXX_MOVE_BACKWARD3(__first2, __last2, __result); return; } else if (__first2 == __last2) return; --__last1; --__last2; while (true) { if (__comp(__last2, __last1)) { *--__result = _GLIBCXX_MOVE(*__last1); if (__first1 == __last1) { _GLIBCXX_MOVE_BACKWARD3(__first2, ++__last2, __result); return; } --__last1; } else { *--__result = _GLIBCXX_MOVE(*__last2); if (__first2 == __last2) return; --__last2; } } } /// This is a helper function for the merge routines. template _BidirectionalIterator1 __rotate_adaptive(_BidirectionalIterator1 __first, _BidirectionalIterator1 __middle, _BidirectionalIterator1 __last, _Distance __len1, _Distance __len2, _BidirectionalIterator2 __buffer, _Distance __buffer_size) { _BidirectionalIterator2 __buffer_end; if (__len1 > __len2 && __len2 <= __buffer_size) { if (__len2) { __buffer_end = _GLIBCXX_MOVE3(__middle, __last, __buffer); _GLIBCXX_MOVE_BACKWARD3(__first, __middle, __last); return _GLIBCXX_MOVE3(__buffer, __buffer_end, __first); } else return __first; } else if (__len1 <= __buffer_size) { if (__len1) { __buffer_end = _GLIBCXX_MOVE3(__first, __middle, __buffer); _GLIBCXX_MOVE3(__middle, __last, __first); return _GLIBCXX_MOVE_BACKWARD3(__buffer, __buffer_end, __last); } else return __last; } else { std::rotate(__first, __middle, __last); std::advance(__first, std::distance(__middle, __last)); return __first; } } /// This is a helper function for the merge routines. template void __merge_adaptive(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last, _Distance __len1, _Distance __len2, _Pointer __buffer, _Distance __buffer_size, _Compare __comp) { if (__len1 <= __len2 && __len1 <= __buffer_size) { _Pointer __buffer_end = _GLIBCXX_MOVE3(__first, __middle, __buffer); std::__move_merge_adaptive(__buffer, __buffer_end, __middle, __last, __first, __comp); } else if (__len2 <= __buffer_size) { _Pointer __buffer_end = _GLIBCXX_MOVE3(__middle, __last, __buffer); std::__move_merge_adaptive_backward(__first, __middle, __buffer, __buffer_end, __last, __comp); } else { _BidirectionalIterator __first_cut = __first; _BidirectionalIterator __second_cut = __middle; _Distance __len11 = 0; _Distance __len22 = 0; if (__len1 > __len2) { __len11 = __len1 / 2; std::advance(__first_cut, __len11); __second_cut = std::__lower_bound(__middle, __last, *__first_cut, __gnu_cxx::__ops::__iter_comp_val(__comp)); __len22 = std::distance(__middle, __second_cut); } else { __len22 = __len2 / 2; std::advance(__second_cut, __len22); __first_cut = std::__upper_bound(__first, __middle, *__second_cut, __gnu_cxx::__ops::__val_comp_iter(__comp)); __len11 = std::distance(__first, __first_cut); } _BidirectionalIterator __new_middle = std::__rotate_adaptive(__first_cut, __middle, __second_cut, __len1 - __len11, __len22, __buffer, __buffer_size); std::__merge_adaptive(__first, __first_cut, __new_middle, __len11, __len22, __buffer, __buffer_size, __comp); std::__merge_adaptive(__new_middle, __second_cut, __last, __len1 - __len11, __len2 - __len22, __buffer, __buffer_size, __comp); } } /// This is a helper function for the merge routines. template void __merge_without_buffer(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last, _Distance __len1, _Distance __len2, _Compare __comp) { if (__len1 == 0 || __len2 == 0) return; if (__len1 + __len2 == 2) { if (__comp(__middle, __first)) std::iter_swap(__first, __middle); return; } _BidirectionalIterator __first_cut = __first; _BidirectionalIterator __second_cut = __middle; _Distance __len11 = 0; _Distance __len22 = 0; if (__len1 > __len2) { __len11 = __len1 / 2; std::advance(__first_cut, __len11); __second_cut = std::__lower_bound(__middle, __last, *__first_cut, __gnu_cxx::__ops::__iter_comp_val(__comp)); __len22 = std::distance(__middle, __second_cut); } else { __len22 = __len2 / 2; std::advance(__second_cut, __len22); __first_cut = std::__upper_bound(__first, __middle, *__second_cut, __gnu_cxx::__ops::__val_comp_iter(__comp)); __len11 = std::distance(__first, __first_cut); } std::rotate(__first_cut, __middle, __second_cut); _BidirectionalIterator __new_middle = __first_cut; std::advance(__new_middle, std::distance(__middle, __second_cut)); std::__merge_without_buffer(__first, __first_cut, __new_middle, __len11, __len22, __comp); std::__merge_without_buffer(__new_middle, __second_cut, __last, __len1 - __len11, __len2 - __len22, __comp); } template void __inplace_merge(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last, _Compare __comp) { typedef typename iterator_traits<_BidirectionalIterator>::value_type _ValueType; typedef typename iterator_traits<_BidirectionalIterator>::difference_type _DistanceType; if (__first == __middle || __middle == __last) return; const _DistanceType __len1 = std::distance(__first, __middle); const _DistanceType __len2 = std::distance(__middle, __last); typedef _Temporary_buffer<_BidirectionalIterator, _ValueType> _TmpBuf; _TmpBuf __buf(__first, __last); if (__buf.begin() == 0) std::__merge_without_buffer (__first, __middle, __last, __len1, __len2, __comp); else std::__merge_adaptive (__first, __middle, __last, __len1, __len2, __buf.begin(), _DistanceType(__buf.size()), __comp); } /** * @brief Merges two sorted ranges in place. * @ingroup sorting_algorithms * @param __first An iterator. * @param __middle Another iterator. * @param __last Another iterator. * @return Nothing. * * Merges two sorted and consecutive ranges, [__first,__middle) and * [__middle,__last), and puts the result in [__first,__last). The * output will be sorted. The sort is @e stable, that is, for * equivalent elements in the two ranges, elements from the first * range will always come before elements from the second. * * If enough additional memory is available, this takes (__last-__first)-1 * comparisons. Otherwise an NlogN algorithm is used, where N is * distance(__first,__last). */ template inline void inplace_merge(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_BidirectionalIteratorConcept< _BidirectionalIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_BidirectionalIterator>::value_type>) __glibcxx_requires_sorted(__first, __middle); __glibcxx_requires_sorted(__middle, __last); __glibcxx_requires_irreflexive(__first, __last); std::__inplace_merge(__first, __middle, __last, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Merges two sorted ranges in place. * @ingroup sorting_algorithms * @param __first An iterator. * @param __middle Another iterator. * @param __last Another iterator. * @param __comp A functor to use for comparisons. * @return Nothing. * * Merges two sorted and consecutive ranges, [__first,__middle) and * [middle,last), and puts the result in [__first,__last). The output will * be sorted. The sort is @e stable, that is, for equivalent * elements in the two ranges, elements from the first range will always * come before elements from the second. * * If enough additional memory is available, this takes (__last-__first)-1 * comparisons. Otherwise an NlogN algorithm is used, where N is * distance(__first,__last). * * The comparison function should have the same effects on ordering as * the function used for the initial sort. */ template inline void inplace_merge(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_Mutable_BidirectionalIteratorConcept< _BidirectionalIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_BidirectionalIterator>::value_type, typename iterator_traits<_BidirectionalIterator>::value_type>) __glibcxx_requires_sorted_pred(__first, __middle, __comp); __glibcxx_requires_sorted_pred(__middle, __last, __comp); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); std::__inplace_merge(__first, __middle, __last, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } /// This is a helper function for the __merge_sort_loop routines. template _OutputIterator __move_merge(_InputIterator __first1, _InputIterator __last1, _InputIterator __first2, _InputIterator __last2, _OutputIterator __result, _Compare __comp) { while (__first1 != __last1 && __first2 != __last2) { if (__comp(__first2, __first1)) { *__result = _GLIBCXX_MOVE(*__first2); ++__first2; } else { *__result = _GLIBCXX_MOVE(*__first1); ++__first1; } ++__result; } return _GLIBCXX_MOVE3(__first2, __last2, _GLIBCXX_MOVE3(__first1, __last1, __result)); } template void __merge_sort_loop(_RandomAccessIterator1 __first, _RandomAccessIterator1 __last, _RandomAccessIterator2 __result, _Distance __step_size, _Compare __comp) { const _Distance __two_step = 2 * __step_size; while (__last - __first >= __two_step) { __result = std::__move_merge(__first, __first + __step_size, __first + __step_size, __first + __two_step, __result, __comp); __first += __two_step; } __step_size = std::min(_Distance(__last - __first), __step_size); std::__move_merge(__first, __first + __step_size, __first + __step_size, __last, __result, __comp); } template void __chunk_insertion_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Distance __chunk_size, _Compare __comp) { while (__last - __first >= __chunk_size) { std::__insertion_sort(__first, __first + __chunk_size, __comp); __first += __chunk_size; } std::__insertion_sort(__first, __last, __comp); } enum { _S_chunk_size = 7 }; template void __merge_sort_with_buffer(_RandomAccessIterator __first, _RandomAccessIterator __last, _Pointer __buffer, _Compare __comp) { typedef typename iterator_traits<_RandomAccessIterator>::difference_type _Distance; const _Distance __len = __last - __first; const _Pointer __buffer_last = __buffer + __len; _Distance __step_size = _S_chunk_size; std::__chunk_insertion_sort(__first, __last, __step_size, __comp); while (__step_size < __len) { std::__merge_sort_loop(__first, __last, __buffer, __step_size, __comp); __step_size *= 2; std::__merge_sort_loop(__buffer, __buffer_last, __first, __step_size, __comp); __step_size *= 2; } } template void __stable_sort_adaptive(_RandomAccessIterator __first, _RandomAccessIterator __last, _Pointer __buffer, _Distance __buffer_size, _Compare __comp) { const _Distance __len = (__last - __first + 1) / 2; const _RandomAccessIterator __middle = __first + __len; if (__len > __buffer_size) { std::__stable_sort_adaptive(__first, __middle, __buffer, __buffer_size, __comp); std::__stable_sort_adaptive(__middle, __last, __buffer, __buffer_size, __comp); } else { std::__merge_sort_with_buffer(__first, __middle, __buffer, __comp); std::__merge_sort_with_buffer(__middle, __last, __buffer, __comp); } std::__merge_adaptive(__first, __middle, __last, _Distance(__middle - __first), _Distance(__last - __middle), __buffer, __buffer_size, __comp); } /// This is a helper function for the stable sorting routines. template void __inplace_stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { if (__last - __first < 15) { std::__insertion_sort(__first, __last, __comp); return; } _RandomAccessIterator __middle = __first + (__last - __first) / 2; std::__inplace_stable_sort(__first, __middle, __comp); std::__inplace_stable_sort(__middle, __last, __comp); std::__merge_without_buffer(__first, __middle, __last, __middle - __first, __last - __middle, __comp); } // stable_sort // Set algorithms: includes, set_union, set_intersection, set_difference, // set_symmetric_difference. All of these algorithms have the precondition // that their input ranges are sorted and the postcondition that their output // ranges are sorted. template bool __includes(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _Compare __comp) { while (__first1 != __last1 && __first2 != __last2) if (__comp(__first2, __first1)) return false; else if (__comp(__first1, __first2)) ++__first1; else { ++__first1; ++__first2; } return __first2 == __last2; } /** * @brief Determines whether all elements of a sequence exists in a range. * @param __first1 Start of search range. * @param __last1 End of search range. * @param __first2 Start of sequence * @param __last2 End of sequence. * @return True if each element in [__first2,__last2) is contained in order * within [__first1,__last1). False otherwise. * @ingroup set_algorithms * * This operation expects both [__first1,__last1) and * [__first2,__last2) to be sorted. Searches for the presence of * each element in [__first2,__last2) within [__first1,__last1). * The iterators over each range only move forward, so this is a * linear algorithm. If an element in [__first2,__last2) is not * found before the search iterator reaches @p __last2, false is * returned. */ template inline bool includes(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_LessThanOpConcept< typename iterator_traits<_InputIterator1>::value_type, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_LessThanOpConcept< typename iterator_traits<_InputIterator2>::value_type, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_requires_sorted_set(__first1, __last1, __first2); __glibcxx_requires_sorted_set(__first2, __last2, __first1); __glibcxx_requires_irreflexive2(__first1, __last1); __glibcxx_requires_irreflexive2(__first2, __last2); return std::__includes(__first1, __last1, __first2, __last2, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Determines whether all elements of a sequence exists in a range * using comparison. * @ingroup set_algorithms * @param __first1 Start of search range. * @param __last1 End of search range. * @param __first2 Start of sequence * @param __last2 End of sequence. * @param __comp Comparison function to use. * @return True if each element in [__first2,__last2) is contained * in order within [__first1,__last1) according to comp. False * otherwise. @ingroup set_algorithms * * This operation expects both [__first1,__last1) and * [__first2,__last2) to be sorted. Searches for the presence of * each element in [__first2,__last2) within [__first1,__last1), * using comp to decide. The iterators over each range only move * forward, so this is a linear algorithm. If an element in * [__first2,__last2) is not found before the search iterator * reaches @p __last2, false is returned. */ template inline bool includes(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _Compare __comp) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_InputIterator1>::value_type, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_InputIterator2>::value_type, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_requires_sorted_set_pred(__first1, __last1, __first2, __comp); __glibcxx_requires_sorted_set_pred(__first2, __last2, __first1, __comp); __glibcxx_requires_irreflexive_pred2(__first1, __last1, __comp); __glibcxx_requires_irreflexive_pred2(__first2, __last2, __comp); return std::__includes(__first1, __last1, __first2, __last2, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } // nth_element // merge // set_difference // set_intersection // set_union // stable_sort // set_symmetric_difference // min_element // max_element template bool __next_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp) { if (__first == __last) return false; _BidirectionalIterator __i = __first; ++__i; if (__i == __last) return false; __i = __last; --__i; for(;;) { _BidirectionalIterator __ii = __i; --__i; if (__comp(__i, __ii)) { _BidirectionalIterator __j = __last; while (!__comp(__i, --__j)) {} std::iter_swap(__i, __j); std::__reverse(__ii, __last, std::__iterator_category(__first)); return true; } if (__i == __first) { std::__reverse(__first, __last, std::__iterator_category(__first)); return false; } } } /** * @brief Permute range into the next @e dictionary ordering. * @ingroup sorting_algorithms * @param __first Start of range. * @param __last End of range. * @return False if wrapped to first permutation, true otherwise. * * Treats all permutations of the range as a set of @e dictionary sorted * sequences. Permutes the current sequence into the next one of this set. * Returns true if there are more sequences to generate. If the sequence * is the largest of the set, the smallest is generated and false returned. */ template inline bool next_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last) { // concept requirements __glibcxx_function_requires(_BidirectionalIteratorConcept< _BidirectionalIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_BidirectionalIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); return std::__next_permutation (__first, __last, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Permute range into the next @e dictionary ordering using * comparison functor. * @ingroup sorting_algorithms * @param __first Start of range. * @param __last End of range. * @param __comp A comparison functor. * @return False if wrapped to first permutation, true otherwise. * * Treats all permutations of the range [__first,__last) as a set of * @e dictionary sorted sequences ordered by @p __comp. Permutes the current * sequence into the next one of this set. Returns true if there are more * sequences to generate. If the sequence is the largest of the set, the * smallest is generated and false returned. */ template inline bool next_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_BidirectionalIteratorConcept< _BidirectionalIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_BidirectionalIterator>::value_type, typename iterator_traits<_BidirectionalIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); return std::__next_permutation (__first, __last, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } template bool __prev_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp) { if (__first == __last) return false; _BidirectionalIterator __i = __first; ++__i; if (__i == __last) return false; __i = __last; --__i; for(;;) { _BidirectionalIterator __ii = __i; --__i; if (__comp(__ii, __i)) { _BidirectionalIterator __j = __last; while (!__comp(--__j, __i)) {} std::iter_swap(__i, __j); std::__reverse(__ii, __last, std::__iterator_category(__first)); return true; } if (__i == __first) { std::__reverse(__first, __last, std::__iterator_category(__first)); return false; } } } /** * @brief Permute range into the previous @e dictionary ordering. * @ingroup sorting_algorithms * @param __first Start of range. * @param __last End of range. * @return False if wrapped to last permutation, true otherwise. * * Treats all permutations of the range as a set of @e dictionary sorted * sequences. Permutes the current sequence into the previous one of this * set. Returns true if there are more sequences to generate. If the * sequence is the smallest of the set, the largest is generated and false * returned. */ template inline bool prev_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last) { // concept requirements __glibcxx_function_requires(_BidirectionalIteratorConcept< _BidirectionalIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_BidirectionalIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); return std::__prev_permutation(__first, __last, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Permute range into the previous @e dictionary ordering using * comparison functor. * @ingroup sorting_algorithms * @param __first Start of range. * @param __last End of range. * @param __comp A comparison functor. * @return False if wrapped to last permutation, true otherwise. * * Treats all permutations of the range [__first,__last) as a set of * @e dictionary sorted sequences ordered by @p __comp. Permutes the current * sequence into the previous one of this set. Returns true if there are * more sequences to generate. If the sequence is the smallest of the set, * the largest is generated and false returned. */ template inline bool prev_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_BidirectionalIteratorConcept< _BidirectionalIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_BidirectionalIterator>::value_type, typename iterator_traits<_BidirectionalIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); return std::__prev_permutation(__first, __last, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } // replace // replace_if template _OutputIterator __replace_copy_if(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _Predicate __pred, const _Tp& __new_value) { for (; __first != __last; ++__first, (void)++__result) if (__pred(__first)) *__result = __new_value; else *__result = *__first; return __result; } /** * @brief Copy a sequence, replacing each element of one value with another * value. * @param __first An input iterator. * @param __last An input iterator. * @param __result An output iterator. * @param __old_value The value to be replaced. * @param __new_value The replacement value. * @return The end of the output sequence, @p result+(last-first). * * Copies each element in the input range @p [__first,__last) to the * output range @p [__result,__result+(__last-__first)) replacing elements * equal to @p __old_value with @p __new_value. */ template inline _OutputIterator replace_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result, const _Tp& __old_value, const _Tp& __new_value) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_InputIterator>::value_type, _Tp>) __glibcxx_requires_valid_range(__first, __last); return std::__replace_copy_if(__first, __last, __result, __gnu_cxx::__ops::__iter_equals_val(__old_value), __new_value); } /** * @brief Copy a sequence, replacing each value for which a predicate * returns true with another value. * @ingroup mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __result An output iterator. * @param __pred A predicate. * @param __new_value The replacement value. * @return The end of the output sequence, @p __result+(__last-__first). * * Copies each element in the range @p [__first,__last) to the range * @p [__result,__result+(__last-__first)) replacing elements for which * @p __pred returns true with @p __new_value. */ template inline _OutputIterator replace_copy_if(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _Predicate __pred, const _Tp& __new_value) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_function_requires(_UnaryPredicateConcept<_Predicate, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__replace_copy_if(__first, __last, __result, __gnu_cxx::__ops::__pred_iter(__pred), __new_value); } template typename iterator_traits<_InputIterator>::difference_type __count_if(_InputIterator __first, _InputIterator __last, _Predicate __pred) { typename iterator_traits<_InputIterator>::difference_type __n = 0; for (; __first != __last; ++__first) if (__pred(__first)) ++__n; return __n; } #if __cplusplus >= 201103L /** * @brief Determines whether the elements of a sequence are sorted. * @ingroup sorting_algorithms * @param __first An iterator. * @param __last Another iterator. * @return True if the elements are sorted, false otherwise. */ template inline bool is_sorted(_ForwardIterator __first, _ForwardIterator __last) { return std::is_sorted_until(__first, __last) == __last; } /** * @brief Determines whether the elements of a sequence are sorted * according to a comparison functor. * @ingroup sorting_algorithms * @param __first An iterator. * @param __last Another iterator. * @param __comp A comparison functor. * @return True if the elements are sorted, false otherwise. */ template inline bool is_sorted(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp) { return std::is_sorted_until(__first, __last, __comp) == __last; } template _ForwardIterator __is_sorted_until(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp) { if (__first == __last) return __last; _ForwardIterator __next = __first; for (++__next; __next != __last; __first = __next, (void)++__next) if (__comp(__next, __first)) return __next; return __next; } /** * @brief Determines the end of a sorted sequence. * @ingroup sorting_algorithms * @param __first An iterator. * @param __last Another iterator. * @return An iterator pointing to the last iterator i in [__first, __last) * for which the range [__first, i) is sorted. */ template inline _ForwardIterator is_sorted_until(_ForwardIterator __first, _ForwardIterator __last) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); return std::__is_sorted_until(__first, __last, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Determines the end of a sorted sequence using comparison functor. * @ingroup sorting_algorithms * @param __first An iterator. * @param __last Another iterator. * @param __comp A comparison functor. * @return An iterator pointing to the last iterator i in [__first, __last) * for which the range [__first, i) is sorted. */ template inline _ForwardIterator is_sorted_until(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_ForwardIterator>::value_type, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); return std::__is_sorted_until(__first, __last, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } /** * @brief Determines min and max at once as an ordered pair. * @ingroup sorting_algorithms * @param __a A thing of arbitrary type. * @param __b Another thing of arbitrary type. * @return A pair(__b, __a) if __b is smaller than __a, pair(__a, * __b) otherwise. */ template _GLIBCXX14_CONSTEXPR inline pair minmax(const _Tp& __a, const _Tp& __b) { // concept requirements __glibcxx_function_requires(_LessThanComparableConcept<_Tp>) return __b < __a ? pair(__b, __a) : pair(__a, __b); } /** * @brief Determines min and max at once as an ordered pair. * @ingroup sorting_algorithms * @param __a A thing of arbitrary type. * @param __b Another thing of arbitrary type. * @param __comp A @link comparison_functors comparison functor @endlink. * @return A pair(__b, __a) if __b is smaller than __a, pair(__a, * __b) otherwise. */ template _GLIBCXX14_CONSTEXPR inline pair minmax(const _Tp& __a, const _Tp& __b, _Compare __comp) { return __comp(__b, __a) ? pair(__b, __a) : pair(__a, __b); } template _GLIBCXX14_CONSTEXPR pair<_ForwardIterator, _ForwardIterator> __minmax_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp) { _ForwardIterator __next = __first; if (__first == __last || ++__next == __last) return std::make_pair(__first, __first); _ForwardIterator __min{}, __max{}; if (__comp(__next, __first)) { __min = __next; __max = __first; } else { __min = __first; __max = __next; } __first = __next; ++__first; while (__first != __last) { __next = __first; if (++__next == __last) { if (__comp(__first, __min)) __min = __first; else if (!__comp(__first, __max)) __max = __first; break; } if (__comp(__next, __first)) { if (__comp(__next, __min)) __min = __next; if (!__comp(__first, __max)) __max = __first; } else { if (__comp(__first, __min)) __min = __first; if (!__comp(__next, __max)) __max = __next; } __first = __next; ++__first; } return std::make_pair(__min, __max); } /** * @brief Return a pair of iterators pointing to the minimum and maximum * elements in a range. * @ingroup sorting_algorithms * @param __first Start of range. * @param __last End of range. * @return make_pair(m, M), where m is the first iterator i in * [__first, __last) such that no other element in the range is * smaller, and where M is the last iterator i in [__first, __last) * such that no other element in the range is larger. */ template _GLIBCXX14_CONSTEXPR inline pair<_ForwardIterator, _ForwardIterator> minmax_element(_ForwardIterator __first, _ForwardIterator __last) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); return std::__minmax_element(__first, __last, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Return a pair of iterators pointing to the minimum and maximum * elements in a range. * @ingroup sorting_algorithms * @param __first Start of range. * @param __last End of range. * @param __comp Comparison functor. * @return make_pair(m, M), where m is the first iterator i in * [__first, __last) such that no other element in the range is * smaller, and where M is the last iterator i in [__first, __last) * such that no other element in the range is larger. */ template _GLIBCXX14_CONSTEXPR inline pair<_ForwardIterator, _ForwardIterator> minmax_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_ForwardIterator>::value_type, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); return std::__minmax_element(__first, __last, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } // N2722 + DR 915. template _GLIBCXX14_CONSTEXPR inline _Tp min(initializer_list<_Tp> __l) { return *std::min_element(__l.begin(), __l.end()); } template _GLIBCXX14_CONSTEXPR inline _Tp min(initializer_list<_Tp> __l, _Compare __comp) { return *std::min_element(__l.begin(), __l.end(), __comp); } template _GLIBCXX14_CONSTEXPR inline _Tp max(initializer_list<_Tp> __l) { return *std::max_element(__l.begin(), __l.end()); } template _GLIBCXX14_CONSTEXPR inline _Tp max(initializer_list<_Tp> __l, _Compare __comp) { return *std::max_element(__l.begin(), __l.end(), __comp); } template _GLIBCXX14_CONSTEXPR inline pair<_Tp, _Tp> minmax(initializer_list<_Tp> __l) { pair __p = std::minmax_element(__l.begin(), __l.end()); return std::make_pair(*__p.first, *__p.second); } template _GLIBCXX14_CONSTEXPR inline pair<_Tp, _Tp> minmax(initializer_list<_Tp> __l, _Compare __comp) { pair __p = std::minmax_element(__l.begin(), __l.end(), __comp); return std::make_pair(*__p.first, *__p.second); } template bool __is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _BinaryPredicate __pred) { // Efficiently compare identical prefixes: O(N) if sequences // have the same elements in the same order. for (; __first1 != __last1; ++__first1, (void)++__first2) if (!__pred(__first1, __first2)) break; if (__first1 == __last1) return true; // Establish __last2 assuming equal ranges by iterating over the // rest of the list. _ForwardIterator2 __last2 = __first2; std::advance(__last2, std::distance(__first1, __last1)); for (_ForwardIterator1 __scan = __first1; __scan != __last1; ++__scan) { if (__scan != std::__find_if(__first1, __scan, __gnu_cxx::__ops::__iter_comp_iter(__pred, __scan))) continue; // We've seen this one before. auto __matches = std::__count_if(__first2, __last2, __gnu_cxx::__ops::__iter_comp_iter(__pred, __scan)); if (0 == __matches || std::__count_if(__scan, __last1, __gnu_cxx::__ops::__iter_comp_iter(__pred, __scan)) != __matches) return false; } return true; } /** * @brief Checks whether a permutation of the second sequence is equal * to the first sequence. * @ingroup non_mutating_algorithms * @param __first1 Start of first range. * @param __last1 End of first range. * @param __first2 Start of second range. * @return true if there exists a permutation of the elements in the range * [__first2, __first2 + (__last1 - __first1)), beginning with * ForwardIterator2 begin, such that equal(__first1, __last1, begin) * returns true; otherwise, returns false. */ template inline bool is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator1>) __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator2>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_ForwardIterator1>::value_type, typename iterator_traits<_ForwardIterator2>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); return std::__is_permutation(__first1, __last1, __first2, __gnu_cxx::__ops::__iter_equal_to_iter()); } /** * @brief Checks whether a permutation of the second sequence is equal * to the first sequence. * @ingroup non_mutating_algorithms * @param __first1 Start of first range. * @param __last1 End of first range. * @param __first2 Start of second range. * @param __pred A binary predicate. * @return true if there exists a permutation of the elements in * the range [__first2, __first2 + (__last1 - __first1)), * beginning with ForwardIterator2 begin, such that * equal(__first1, __last1, __begin, __pred) returns true; * otherwise, returns false. */ template inline bool is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _BinaryPredicate __pred) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator1>) __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator2>) __glibcxx_function_requires(_BinaryPredicateConcept<_BinaryPredicate, typename iterator_traits<_ForwardIterator1>::value_type, typename iterator_traits<_ForwardIterator2>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); return std::__is_permutation(__first1, __last1, __first2, __gnu_cxx::__ops::__iter_comp_iter(__pred)); } #if __cplusplus > 201103L template bool __is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __pred) { using _Cat1 = typename iterator_traits<_ForwardIterator1>::iterator_category; using _Cat2 = typename iterator_traits<_ForwardIterator2>::iterator_category; using _It1_is_RA = is_same<_Cat1, random_access_iterator_tag>; using _It2_is_RA = is_same<_Cat2, random_access_iterator_tag>; constexpr bool __ra_iters = _It1_is_RA() && _It2_is_RA(); if (__ra_iters) { auto __d1 = std::distance(__first1, __last1); auto __d2 = std::distance(__first2, __last2); if (__d1 != __d2) return false; } // Efficiently compare identical prefixes: O(N) if sequences // have the same elements in the same order. for (; __first1 != __last1 && __first2 != __last2; ++__first1, (void)++__first2) if (!__pred(__first1, __first2)) break; if (__ra_iters) { if (__first1 == __last1) return true; } else { auto __d1 = std::distance(__first1, __last1); auto __d2 = std::distance(__first2, __last2); if (__d1 == 0 && __d2 == 0) return true; if (__d1 != __d2) return false; } for (_ForwardIterator1 __scan = __first1; __scan != __last1; ++__scan) { if (__scan != std::__find_if(__first1, __scan, __gnu_cxx::__ops::__iter_comp_iter(__pred, __scan))) continue; // We've seen this one before. auto __matches = std::__count_if(__first2, __last2, __gnu_cxx::__ops::__iter_comp_iter(__pred, __scan)); if (0 == __matches || std::__count_if(__scan, __last1, __gnu_cxx::__ops::__iter_comp_iter(__pred, __scan)) != __matches) return false; } return true; } /** * @brief Checks whether a permutaion of the second sequence is equal * to the first sequence. * @ingroup non_mutating_algorithms * @param __first1 Start of first range. * @param __last1 End of first range. * @param __first2 Start of second range. * @param __last2 End of first range. * @return true if there exists a permutation of the elements in the range * [__first2, __last2), beginning with ForwardIterator2 begin, * such that equal(__first1, __last1, begin) returns true; * otherwise, returns false. */ template inline bool is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2) { __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return std::__is_permutation(__first1, __last1, __first2, __last2, __gnu_cxx::__ops::__iter_equal_to_iter()); } /** * @brief Checks whether a permutation of the second sequence is equal * to the first sequence. * @ingroup non_mutating_algorithms * @param __first1 Start of first range. * @param __last1 End of first range. * @param __first2 Start of second range. * @param __last2 End of first range. * @param __pred A binary predicate. * @return true if there exists a permutation of the elements in the range * [__first2, __last2), beginning with ForwardIterator2 begin, * such that equal(__first1, __last1, __begin, __pred) returns true; * otherwise, returns false. */ template inline bool is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __pred) { __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return std::__is_permutation(__first1, __last1, __first2, __last2, __gnu_cxx::__ops::__iter_comp_iter(__pred)); } #if __cplusplus > 201402L #define __cpp_lib_clamp 201603 /** * @brief Returns the value clamped between lo and hi. * @ingroup sorting_algorithms * @param __val A value of arbitrary type. * @param __lo A lower limit of arbitrary type. * @param __hi An upper limit of arbitrary type. * @return max(__val, __lo) if __val < __hi or min(__val, __hi) otherwise. */ template constexpr const _Tp& clamp(const _Tp& __val, const _Tp& __lo, const _Tp& __hi) { __glibcxx_assert(!(__hi < __lo)); return (__val < __lo) ? __lo : (__hi < __val) ? __hi : __val; } /** * @brief Returns the value clamped between lo and hi. * @ingroup sorting_algorithms * @param __val A value of arbitrary type. * @param __lo A lower limit of arbitrary type. * @param __hi An upper limit of arbitrary type. * @param __comp A comparison functor. * @return max(__val, __lo, __comp) if __comp(__val, __hi) * or min(__val, __hi, __comp) otherwise. */ template constexpr const _Tp& clamp(const _Tp& __val, const _Tp& __lo, const _Tp& __hi, _Compare __comp) { __glibcxx_assert(!__comp(__hi, __lo)); return __comp(__val, __lo) ? __lo : __comp(__hi, __val) ? __hi : __val; } #endif // C++17 #endif // C++14 #ifdef _GLIBCXX_USE_C99_STDINT_TR1 /** * @brief Generate two uniformly distributed integers using a * single distribution invocation. * @param __b0 The upper bound for the first integer. * @param __b1 The upper bound for the second integer. * @param __g A UniformRandomBitGenerator. * @return A pair (i, j) with i and j uniformly distributed * over [0, __b0) and [0, __b1), respectively. * * Requires: __b0 * __b1 <= __g.max() - __g.min(). * * Using uniform_int_distribution with a range that is very * small relative to the range of the generator ends up wasting * potentially expensively generated randomness, since * uniform_int_distribution does not store leftover randomness * between invocations. * * If we know we want two integers in ranges that are sufficiently * small, we can compose the ranges, use a single distribution * invocation, and significantly reduce the waste. */ template pair<_IntType, _IntType> __gen_two_uniform_ints(_IntType __b0, _IntType __b1, _UniformRandomBitGenerator&& __g) { _IntType __x = uniform_int_distribution<_IntType>{0, (__b0 * __b1) - 1}(__g); return std::make_pair(__x / __b1, __x % __b1); } /** * @brief Shuffle the elements of a sequence using a uniform random * number generator. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @param __g A UniformRandomNumberGenerator (26.5.1.3). * @return Nothing. * * Reorders the elements in the range @p [__first,__last) using @p __g to * provide random numbers. */ template void shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last, _UniformRandomNumberGenerator&& __g) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); if (__first == __last) return; typedef typename iterator_traits<_RandomAccessIterator>::difference_type _DistanceType; typedef typename std::make_unsigned<_DistanceType>::type __ud_type; typedef typename std::uniform_int_distribution<__ud_type> __distr_type; typedef typename __distr_type::param_type __p_type; typedef typename remove_reference<_UniformRandomNumberGenerator>::type _Gen; typedef typename common_type::type __uc_type; const __uc_type __urngrange = __g.max() - __g.min(); const __uc_type __urange = __uc_type(__last - __first); if (__urngrange / __urange >= __urange) // I.e. (__urngrange >= __urange * __urange) but without wrap issues. { _RandomAccessIterator __i = __first + 1; // Since we know the range isn't empty, an even number of elements // means an uneven number of elements /to swap/, in which case we // do the first one up front: if ((__urange % 2) == 0) { __distr_type __d{0, 1}; std::iter_swap(__i++, __first + __d(__g)); } // Now we know that __last - __i is even, so we do the rest in pairs, // using a single distribution invocation to produce swap positions // for two successive elements at a time: while (__i != __last) { const __uc_type __swap_range = __uc_type(__i - __first) + 1; const pair<__uc_type, __uc_type> __pospos = __gen_two_uniform_ints(__swap_range, __swap_range + 1, __g); std::iter_swap(__i++, __first + __pospos.first); std::iter_swap(__i++, __first + __pospos.second); } return; } __distr_type __d; for (_RandomAccessIterator __i = __first + 1; __i != __last; ++__i) std::iter_swap(__i, __first + __d(__g, __p_type(0, __i - __first))); } #endif #endif // C++11 _GLIBCXX_BEGIN_NAMESPACE_ALGO /** * @brief Apply a function to every element of a sequence. * @ingroup non_mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __f A unary function object. * @return @p __f * * Applies the function object @p __f to each element in the range * @p [first,last). @p __f must not modify the order of the sequence. * If @p __f has a return value it is ignored. */ template _Function for_each(_InputIterator __first, _InputIterator __last, _Function __f) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first) __f(*__first); return __f; // N.B. [alg.foreach] says std::move(f) but it's redundant. } /** * @brief Find the first occurrence of a value in a sequence. * @ingroup non_mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __val The value to find. * @return The first iterator @c i in the range @p [__first,__last) * such that @c *i == @p __val, or @p __last if no such iterator exists. */ template inline _InputIterator find(_InputIterator __first, _InputIterator __last, const _Tp& __val) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_InputIterator>::value_type, _Tp>) __glibcxx_requires_valid_range(__first, __last); return std::__find_if(__first, __last, __gnu_cxx::__ops::__iter_equals_val(__val)); } /** * @brief Find the first element in a sequence for which a * predicate is true. * @ingroup non_mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __pred A predicate. * @return The first iterator @c i in the range @p [__first,__last) * such that @p __pred(*i) is true, or @p __last if no such iterator exists. */ template inline _InputIterator find_if(_InputIterator __first, _InputIterator __last, _Predicate __pred) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_UnaryPredicateConcept<_Predicate, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__find_if(__first, __last, __gnu_cxx::__ops::__pred_iter(__pred)); } /** * @brief Find element from a set in a sequence. * @ingroup non_mutating_algorithms * @param __first1 Start of range to search. * @param __last1 End of range to search. * @param __first2 Start of match candidates. * @param __last2 End of match candidates. * @return The first iterator @c i in the range * @p [__first1,__last1) such that @c *i == @p *(i2) such that i2 is an * iterator in [__first2,__last2), or @p __last1 if no such iterator exists. * * Searches the range @p [__first1,__last1) for an element that is * equal to some element in the range [__first2,__last2). If * found, returns an iterator in the range [__first1,__last1), * otherwise returns @p __last1. */ template _InputIterator find_first_of(_InputIterator __first1, _InputIterator __last1, _ForwardIterator __first2, _ForwardIterator __last2) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_InputIterator>::value_type, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); for (; __first1 != __last1; ++__first1) for (_ForwardIterator __iter = __first2; __iter != __last2; ++__iter) if (*__first1 == *__iter) return __first1; return __last1; } /** * @brief Find element from a set in a sequence using a predicate. * @ingroup non_mutating_algorithms * @param __first1 Start of range to search. * @param __last1 End of range to search. * @param __first2 Start of match candidates. * @param __last2 End of match candidates. * @param __comp Predicate to use. * @return The first iterator @c i in the range * @p [__first1,__last1) such that @c comp(*i, @p *(i2)) is true * and i2 is an iterator in [__first2,__last2), or @p __last1 if no * such iterator exists. * * Searches the range @p [__first1,__last1) for an element that is * equal to some element in the range [__first2,__last2). If * found, returns an iterator in the range [__first1,__last1), * otherwise returns @p __last1. */ template _InputIterator find_first_of(_InputIterator __first1, _InputIterator __last1, _ForwardIterator __first2, _ForwardIterator __last2, _BinaryPredicate __comp) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_BinaryPredicate, typename iterator_traits<_InputIterator>::value_type, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); for (; __first1 != __last1; ++__first1) for (_ForwardIterator __iter = __first2; __iter != __last2; ++__iter) if (__comp(*__first1, *__iter)) return __first1; return __last1; } /** * @brief Find two adjacent values in a sequence that are equal. * @ingroup non_mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @return The first iterator @c i such that @c i and @c i+1 are both * valid iterators in @p [__first,__last) and such that @c *i == @c *(i+1), * or @p __last if no such iterator exists. */ template inline _ForwardIterator adjacent_find(_ForwardIterator __first, _ForwardIterator __last) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_EqualityComparableConcept< typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__adjacent_find(__first, __last, __gnu_cxx::__ops::__iter_equal_to_iter()); } /** * @brief Find two adjacent values in a sequence using a predicate. * @ingroup non_mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @param __binary_pred A binary predicate. * @return The first iterator @c i such that @c i and @c i+1 are both * valid iterators in @p [__first,__last) and such that * @p __binary_pred(*i,*(i+1)) is true, or @p __last if no such iterator * exists. */ template inline _ForwardIterator adjacent_find(_ForwardIterator __first, _ForwardIterator __last, _BinaryPredicate __binary_pred) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_BinaryPredicate, typename iterator_traits<_ForwardIterator>::value_type, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__adjacent_find(__first, __last, __gnu_cxx::__ops::__iter_comp_iter(__binary_pred)); } /** * @brief Count the number of copies of a value in a sequence. * @ingroup non_mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __value The value to be counted. * @return The number of iterators @c i in the range @p [__first,__last) * for which @c *i == @p __value */ template inline typename iterator_traits<_InputIterator>::difference_type count(_InputIterator __first, _InputIterator __last, const _Tp& __value) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_InputIterator>::value_type, _Tp>) __glibcxx_requires_valid_range(__first, __last); return std::__count_if(__first, __last, __gnu_cxx::__ops::__iter_equals_val(__value)); } /** * @brief Count the elements of a sequence for which a predicate is true. * @ingroup non_mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __pred A predicate. * @return The number of iterators @c i in the range @p [__first,__last) * for which @p __pred(*i) is true. */ template inline typename iterator_traits<_InputIterator>::difference_type count_if(_InputIterator __first, _InputIterator __last, _Predicate __pred) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_UnaryPredicateConcept<_Predicate, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__count_if(__first, __last, __gnu_cxx::__ops::__pred_iter(__pred)); } /** * @brief Search a sequence for a matching sub-sequence. * @ingroup non_mutating_algorithms * @param __first1 A forward iterator. * @param __last1 A forward iterator. * @param __first2 A forward iterator. * @param __last2 A forward iterator. * @return The first iterator @c i in the range @p * [__first1,__last1-(__last2-__first2)) such that @c *(i+N) == @p * *(__first2+N) for each @c N in the range @p * [0,__last2-__first2), or @p __last1 if no such iterator exists. * * Searches the range @p [__first1,__last1) for a sub-sequence that * compares equal value-by-value with the sequence given by @p * [__first2,__last2) and returns an iterator to the first element * of the sub-sequence, or @p __last1 if the sub-sequence is not * found. * * Because the sub-sequence must lie completely within the range @p * [__first1,__last1) it must start at a position less than @p * __last1-(__last2-__first2) where @p __last2-__first2 is the * length of the sub-sequence. * * This means that the returned iterator @c i will be in the range * @p [__first1,__last1-(__last2-__first2)) */ template inline _ForwardIterator1 search(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator1>) __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator2>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_ForwardIterator1>::value_type, typename iterator_traits<_ForwardIterator2>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return std::__search(__first1, __last1, __first2, __last2, __gnu_cxx::__ops::__iter_equal_to_iter()); } /** * @brief Search a sequence for a matching sub-sequence using a predicate. * @ingroup non_mutating_algorithms * @param __first1 A forward iterator. * @param __last1 A forward iterator. * @param __first2 A forward iterator. * @param __last2 A forward iterator. * @param __predicate A binary predicate. * @return The first iterator @c i in the range * @p [__first1,__last1-(__last2-__first2)) such that * @p __predicate(*(i+N),*(__first2+N)) is true for each @c N in the range * @p [0,__last2-__first2), or @p __last1 if no such iterator exists. * * Searches the range @p [__first1,__last1) for a sub-sequence that * compares equal value-by-value with the sequence given by @p * [__first2,__last2), using @p __predicate to determine equality, * and returns an iterator to the first element of the * sub-sequence, or @p __last1 if no such iterator exists. * * @see search(_ForwardIter1, _ForwardIter1, _ForwardIter2, _ForwardIter2) */ template inline _ForwardIterator1 search(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __predicate) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator1>) __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator2>) __glibcxx_function_requires(_BinaryPredicateConcept<_BinaryPredicate, typename iterator_traits<_ForwardIterator1>::value_type, typename iterator_traits<_ForwardIterator2>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return std::__search(__first1, __last1, __first2, __last2, __gnu_cxx::__ops::__iter_comp_iter(__predicate)); } /** * @brief Search a sequence for a number of consecutive values. * @ingroup non_mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @param __count The number of consecutive values. * @param __val The value to find. * @return The first iterator @c i in the range @p * [__first,__last-__count) such that @c *(i+N) == @p __val for * each @c N in the range @p [0,__count), or @p __last if no such * iterator exists. * * Searches the range @p [__first,__last) for @p count consecutive elements * equal to @p __val. */ template inline _ForwardIterator search_n(_ForwardIterator __first, _ForwardIterator __last, _Integer __count, const _Tp& __val) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_ForwardIterator>::value_type, _Tp>) __glibcxx_requires_valid_range(__first, __last); return std::__search_n(__first, __last, __count, __gnu_cxx::__ops::__iter_equals_val(__val)); } /** * @brief Search a sequence for a number of consecutive values using a * predicate. * @ingroup non_mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @param __count The number of consecutive values. * @param __val The value to find. * @param __binary_pred A binary predicate. * @return The first iterator @c i in the range @p * [__first,__last-__count) such that @p * __binary_pred(*(i+N),__val) is true for each @c N in the range * @p [0,__count), or @p __last if no such iterator exists. * * Searches the range @p [__first,__last) for @p __count * consecutive elements for which the predicate returns true. */ template inline _ForwardIterator search_n(_ForwardIterator __first, _ForwardIterator __last, _Integer __count, const _Tp& __val, _BinaryPredicate __binary_pred) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_BinaryPredicate, typename iterator_traits<_ForwardIterator>::value_type, _Tp>) __glibcxx_requires_valid_range(__first, __last); return std::__search_n(__first, __last, __count, __gnu_cxx::__ops::__iter_comp_val(__binary_pred, __val)); } #if __cplusplus > 201402L /** @brief Search a sequence using a Searcher object. * * @param __first A forward iterator. * @param __last A forward iterator. * @param __searcher A callable object. * @return @p __searcher(__first,__last).first */ template inline _ForwardIterator search(_ForwardIterator __first, _ForwardIterator __last, const _Searcher& __searcher) { return __searcher(__first, __last).first; } #endif /** * @brief Perform an operation on a sequence. * @ingroup mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __result An output iterator. * @param __unary_op A unary operator. * @return An output iterator equal to @p __result+(__last-__first). * * Applies the operator to each element in the input range and assigns * the results to successive elements of the output sequence. * Evaluates @p *(__result+N)=unary_op(*(__first+N)) for each @c N in the * range @p [0,__last-__first). * * @p unary_op must not alter its argument. */ template _OutputIterator transform(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _UnaryOperation __unary_op) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, // "the type returned by a _UnaryOperation" __typeof__(__unary_op(*__first))>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first, (void)++__result) *__result = __unary_op(*__first); return __result; } /** * @brief Perform an operation on corresponding elements of two sequences. * @ingroup mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __result An output iterator. * @param __binary_op A binary operator. * @return An output iterator equal to @p result+(last-first). * * Applies the operator to the corresponding elements in the two * input ranges and assigns the results to successive elements of the * output sequence. * Evaluates @p * *(__result+N)=__binary_op(*(__first1+N),*(__first2+N)) for each * @c N in the range @p [0,__last1-__first1). * * @p binary_op must not alter either of its arguments. */ template _OutputIterator transform(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _OutputIterator __result, _BinaryOperation __binary_op) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, // "the type returned by a _BinaryOperation" __typeof__(__binary_op(*__first1,*__first2))>) __glibcxx_requires_valid_range(__first1, __last1); for (; __first1 != __last1; ++__first1, (void)++__first2, ++__result) *__result = __binary_op(*__first1, *__first2); return __result; } /** * @brief Replace each occurrence of one value in a sequence with another * value. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @param __old_value The value to be replaced. * @param __new_value The replacement value. * @return replace() returns no value. * * For each iterator @c i in the range @p [__first,__last) if @c *i == * @p __old_value then the assignment @c *i = @p __new_value is performed. */ template void replace(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __old_value, const _Tp& __new_value) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_ForwardIterator>::value_type, _Tp>) __glibcxx_function_requires(_ConvertibleConcept<_Tp, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first) if (*__first == __old_value) *__first = __new_value; } /** * @brief Replace each value in a sequence for which a predicate returns * true with another value. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @param __pred A predicate. * @param __new_value The replacement value. * @return replace_if() returns no value. * * For each iterator @c i in the range @p [__first,__last) if @p __pred(*i) * is true then the assignment @c *i = @p __new_value is performed. */ template void replace_if(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred, const _Tp& __new_value) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator>) __glibcxx_function_requires(_ConvertibleConcept<_Tp, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_function_requires(_UnaryPredicateConcept<_Predicate, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first) if (__pred(*__first)) *__first = __new_value; } /** * @brief Assign the result of a function object to each value in a * sequence. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @param __gen A function object taking no arguments and returning * std::iterator_traits<_ForwardIterator>::value_type * @return generate() returns no value. * * Performs the assignment @c *i = @p __gen() for each @c i in the range * @p [__first,__last). */ template void generate(_ForwardIterator __first, _ForwardIterator __last, _Generator __gen) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_GeneratorConcept<_Generator, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first) *__first = __gen(); } /** * @brief Assign the result of a function object to each value in a * sequence. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __n The length of the sequence. * @param __gen A function object taking no arguments and returning * std::iterator_traits<_ForwardIterator>::value_type * @return The end of the sequence, @p __first+__n * * Performs the assignment @c *i = @p __gen() for each @c i in the range * @p [__first,__first+__n). * * _GLIBCXX_RESOLVE_LIB_DEFECTS * DR 865. More algorithms that throw away information */ template _OutputIterator generate_n(_OutputIterator __first, _Size __n, _Generator __gen) { // concept requirements __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, // "the type returned by a _Generator" __typeof__(__gen())>) for (__decltype(__n + 0) __niter = __n; __niter > 0; --__niter, (void) ++__first) *__first = __gen(); return __first; } /** * @brief Copy a sequence, removing consecutive duplicate values. * @ingroup mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __result An output iterator. * @return An iterator designating the end of the resulting sequence. * * Copies each element in the range @p [__first,__last) to the range * beginning at @p __result, except that only the first element is copied * from groups of consecutive elements that compare equal. * unique_copy() is stable, so the relative order of elements that are * copied is unchanged. * * _GLIBCXX_RESOLVE_LIB_DEFECTS * DR 241. Does unique_copy() require CopyConstructible and Assignable? * * _GLIBCXX_RESOLVE_LIB_DEFECTS * DR 538. 241 again: Does unique_copy() require CopyConstructible and * Assignable? */ template inline _OutputIterator unique_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_function_requires(_EqualityComparableConcept< typename iterator_traits<_InputIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); if (__first == __last) return __result; return std::__unique_copy(__first, __last, __result, __gnu_cxx::__ops::__iter_equal_to_iter(), std::__iterator_category(__first), std::__iterator_category(__result)); } /** * @brief Copy a sequence, removing consecutive values using a predicate. * @ingroup mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __result An output iterator. * @param __binary_pred A binary predicate. * @return An iterator designating the end of the resulting sequence. * * Copies each element in the range @p [__first,__last) to the range * beginning at @p __result, except that only the first element is copied * from groups of consecutive elements for which @p __binary_pred returns * true. * unique_copy() is stable, so the relative order of elements that are * copied is unchanged. * * _GLIBCXX_RESOLVE_LIB_DEFECTS * DR 241. Does unique_copy() require CopyConstructible and Assignable? */ template inline _OutputIterator unique_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _BinaryPredicate __binary_pred) { // concept requirements -- predicates checked later __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); if (__first == __last) return __result; return std::__unique_copy(__first, __last, __result, __gnu_cxx::__ops::__iter_comp_iter(__binary_pred), std::__iterator_category(__first), std::__iterator_category(__result)); } #if _GLIBCXX_HOSTED /** * @brief Randomly shuffle the elements of a sequence. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @return Nothing. * * Reorder the elements in the range @p [__first,__last) using a random * distribution, so that every possible ordering of the sequence is * equally likely. */ template inline void random_shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); if (__first != __last) for (_RandomAccessIterator __i = __first + 1; __i != __last; ++__i) { // XXX rand() % N is not uniformly distributed _RandomAccessIterator __j = __first + std::rand() % ((__i - __first) + 1); if (__i != __j) std::iter_swap(__i, __j); } } #endif /** * @brief Shuffle the elements of a sequence using a random number * generator. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @param __rand The RNG functor or function. * @return Nothing. * * Reorders the elements in the range @p [__first,__last) using @p __rand to * provide a random distribution. Calling @p __rand(N) for a positive * integer @p N should return a randomly chosen integer from the * range [0,N). */ template void random_shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last, #if __cplusplus >= 201103L _RandomNumberGenerator&& __rand) #else _RandomNumberGenerator& __rand) #endif { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); if (__first == __last) return; for (_RandomAccessIterator __i = __first + 1; __i != __last; ++__i) { _RandomAccessIterator __j = __first + __rand((__i - __first) + 1); if (__i != __j) std::iter_swap(__i, __j); } } /** * @brief Move elements for which a predicate is true to the beginning * of a sequence. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @param __pred A predicate functor. * @return An iterator @p middle such that @p __pred(i) is true for each * iterator @p i in the range @p [__first,middle) and false for each @p i * in the range @p [middle,__last). * * @p __pred must not modify its operand. @p partition() does not preserve * the relative ordering of elements in each group, use * @p stable_partition() if this is needed. */ template inline _ForwardIterator partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator>) __glibcxx_function_requires(_UnaryPredicateConcept<_Predicate, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__partition(__first, __last, __pred, std::__iterator_category(__first)); } /** * @brief Sort the smallest elements of a sequence. * @ingroup sorting_algorithms * @param __first An iterator. * @param __middle Another iterator. * @param __last Another iterator. * @return Nothing. * * Sorts the smallest @p (__middle-__first) elements in the range * @p [first,last) and moves them to the range @p [__first,__middle). The * order of the remaining elements in the range @p [__middle,__last) is * undefined. * After the sort if @e i and @e j are iterators in the range * @p [__first,__middle) such that i precedes j and @e k is an iterator in * the range @p [__middle,__last) then *j<*i and *k<*i are both false. */ template inline void partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __middle); __glibcxx_requires_valid_range(__middle, __last); __glibcxx_requires_irreflexive(__first, __last); std::__partial_sort(__first, __middle, __last, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Sort the smallest elements of a sequence using a predicate * for comparison. * @ingroup sorting_algorithms * @param __first An iterator. * @param __middle Another iterator. * @param __last Another iterator. * @param __comp A comparison functor. * @return Nothing. * * Sorts the smallest @p (__middle-__first) elements in the range * @p [__first,__last) and moves them to the range @p [__first,__middle). The * order of the remaining elements in the range @p [__middle,__last) is * undefined. * After the sort if @e i and @e j are iterators in the range * @p [__first,__middle) such that i precedes j and @e k is an iterator in * the range @p [__middle,__last) then @p *__comp(j,*i) and @p __comp(*k,*i) * are both false. */ template inline void partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_RandomAccessIterator>::value_type, typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __middle); __glibcxx_requires_valid_range(__middle, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); std::__partial_sort(__first, __middle, __last, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } /** * @brief Sort a sequence just enough to find a particular position. * @ingroup sorting_algorithms * @param __first An iterator. * @param __nth Another iterator. * @param __last Another iterator. * @return Nothing. * * Rearranges the elements in the range @p [__first,__last) so that @p *__nth * is the same element that would have been in that position had the * whole sequence been sorted. The elements either side of @p *__nth are * not completely sorted, but for any iterator @e i in the range * @p [__first,__nth) and any iterator @e j in the range @p [__nth,__last) it * holds that *j < *i is false. */ template inline void nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __nth); __glibcxx_requires_valid_range(__nth, __last); __glibcxx_requires_irreflexive(__first, __last); if (__first == __last || __nth == __last) return; std::__introselect(__first, __nth, __last, std::__lg(__last - __first) * 2, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Sort a sequence just enough to find a particular position * using a predicate for comparison. * @ingroup sorting_algorithms * @param __first An iterator. * @param __nth Another iterator. * @param __last Another iterator. * @param __comp A comparison functor. * @return Nothing. * * Rearranges the elements in the range @p [__first,__last) so that @p *__nth * is the same element that would have been in that position had the * whole sequence been sorted. The elements either side of @p *__nth are * not completely sorted, but for any iterator @e i in the range * @p [__first,__nth) and any iterator @e j in the range @p [__nth,__last) it * holds that @p __comp(*j,*i) is false. */ template inline void nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_RandomAccessIterator>::value_type, typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __nth); __glibcxx_requires_valid_range(__nth, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); if (__first == __last || __nth == __last) return; std::__introselect(__first, __nth, __last, std::__lg(__last - __first) * 2, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } /** * @brief Sort the elements of a sequence. * @ingroup sorting_algorithms * @param __first An iterator. * @param __last Another iterator. * @return Nothing. * * Sorts the elements in the range @p [__first,__last) in ascending order, * such that for each iterator @e i in the range @p [__first,__last-1), * *(i+1)<*i is false. * * The relative ordering of equivalent elements is not preserved, use * @p stable_sort() if this is needed. */ template inline void sort(_RandomAccessIterator __first, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); std::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Sort the elements of a sequence using a predicate for comparison. * @ingroup sorting_algorithms * @param __first An iterator. * @param __last Another iterator. * @param __comp A comparison functor. * @return Nothing. * * Sorts the elements in the range @p [__first,__last) in ascending order, * such that @p __comp(*(i+1),*i) is false for every iterator @e i in the * range @p [__first,__last-1). * * The relative ordering of equivalent elements is not preserved, use * @p stable_sort() if this is needed. */ template inline void sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_RandomAccessIterator>::value_type, typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); std::__sort(__first, __last, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } template _OutputIterator __merge(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) { while (__first1 != __last1 && __first2 != __last2) { if (__comp(__first2, __first1)) { *__result = *__first2; ++__first2; } else { *__result = *__first1; ++__first1; } ++__result; } return std::copy(__first2, __last2, std::copy(__first1, __last1, __result)); } /** * @brief Merges two sorted ranges. * @ingroup sorting_algorithms * @param __first1 An iterator. * @param __first2 Another iterator. * @param __last1 Another iterator. * @param __last2 Another iterator. * @param __result An iterator pointing to the end of the merged range. * @return An iterator pointing to the first element not less * than @e val. * * Merges the ranges @p [__first1,__last1) and @p [__first2,__last2) into * the sorted range @p [__result, __result + (__last1-__first1) + * (__last2-__first2)). Both input ranges must be sorted, and the * output range must not overlap with either of the input ranges. * The sort is @e stable, that is, for equivalent elements in the * two ranges, elements from the first range will always come * before elements from the second. */ template inline _OutputIterator merge(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_LessThanOpConcept< typename iterator_traits<_InputIterator2>::value_type, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_requires_sorted_set(__first1, __last1, __first2); __glibcxx_requires_sorted_set(__first2, __last2, __first1); __glibcxx_requires_irreflexive2(__first1, __last1); __glibcxx_requires_irreflexive2(__first2, __last2); return _GLIBCXX_STD_A::__merge(__first1, __last1, __first2, __last2, __result, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Merges two sorted ranges. * @ingroup sorting_algorithms * @param __first1 An iterator. * @param __first2 Another iterator. * @param __last1 Another iterator. * @param __last2 Another iterator. * @param __result An iterator pointing to the end of the merged range. * @param __comp A functor to use for comparisons. * @return An iterator pointing to the first element "not less * than" @e val. * * Merges the ranges @p [__first1,__last1) and @p [__first2,__last2) into * the sorted range @p [__result, __result + (__last1-__first1) + * (__last2-__first2)). Both input ranges must be sorted, and the * output range must not overlap with either of the input ranges. * The sort is @e stable, that is, for equivalent elements in the * two ranges, elements from the first range will always come * before elements from the second. * * The comparison function should have the same effects on ordering as * the function used for the initial sort. */ template inline _OutputIterator merge(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_InputIterator2>::value_type, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_requires_sorted_set_pred(__first1, __last1, __first2, __comp); __glibcxx_requires_sorted_set_pred(__first2, __last2, __first1, __comp); __glibcxx_requires_irreflexive_pred2(__first1, __last1, __comp); __glibcxx_requires_irreflexive_pred2(__first2, __last2, __comp); return _GLIBCXX_STD_A::__merge(__first1, __last1, __first2, __last2, __result, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } template inline void __stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { typedef typename iterator_traits<_RandomAccessIterator>::value_type _ValueType; typedef typename iterator_traits<_RandomAccessIterator>::difference_type _DistanceType; typedef _Temporary_buffer<_RandomAccessIterator, _ValueType> _TmpBuf; _TmpBuf __buf(__first, __last); if (__buf.begin() == 0) std::__inplace_stable_sort(__first, __last, __comp); else std::__stable_sort_adaptive(__first, __last, __buf.begin(), _DistanceType(__buf.size()), __comp); } /** * @brief Sort the elements of a sequence, preserving the relative order * of equivalent elements. * @ingroup sorting_algorithms * @param __first An iterator. * @param __last Another iterator. * @return Nothing. * * Sorts the elements in the range @p [__first,__last) in ascending order, * such that for each iterator @p i in the range @p [__first,__last-1), * @p *(i+1)<*i is false. * * The relative ordering of equivalent elements is preserved, so any two * elements @p x and @p y in the range @p [__first,__last) such that * @p x inline void stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); _GLIBCXX_STD_A::__stable_sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Sort the elements of a sequence using a predicate for comparison, * preserving the relative order of equivalent elements. * @ingroup sorting_algorithms * @param __first An iterator. * @param __last Another iterator. * @param __comp A comparison functor. * @return Nothing. * * Sorts the elements in the range @p [__first,__last) in ascending order, * such that for each iterator @p i in the range @p [__first,__last-1), * @p __comp(*(i+1),*i) is false. * * The relative ordering of equivalent elements is preserved, so any two * elements @p x and @p y in the range @p [__first,__last) such that * @p __comp(x,y) is false and @p __comp(y,x) is false will have the same * relative ordering after calling @p stable_sort(). */ template inline void stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_RandomAccessIterator>::value_type, typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); _GLIBCXX_STD_A::__stable_sort(__first, __last, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } template _OutputIterator __set_union(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) { while (__first1 != __last1 && __first2 != __last2) { if (__comp(__first1, __first2)) { *__result = *__first1; ++__first1; } else if (__comp(__first2, __first1)) { *__result = *__first2; ++__first2; } else { *__result = *__first1; ++__first1; ++__first2; } ++__result; } return std::copy(__first2, __last2, std::copy(__first1, __last1, __result)); } /** * @brief Return the union of two sorted ranges. * @ingroup set_algorithms * @param __first1 Start of first range. * @param __last1 End of first range. * @param __first2 Start of second range. * @param __last2 End of second range. * @param __result Start of output range. * @return End of the output range. * @ingroup set_algorithms * * This operation iterates over both ranges, copying elements present in * each range in order to the output range. Iterators increment for each * range. When the current element of one range is less than the other, * that element is copied and the iterator advanced. If an element is * contained in both ranges, the element from the first range is copied and * both ranges advance. The output range may not overlap either input * range. */ template inline _OutputIterator set_union(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_LessThanOpConcept< typename iterator_traits<_InputIterator1>::value_type, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_LessThanOpConcept< typename iterator_traits<_InputIterator2>::value_type, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_requires_sorted_set(__first1, __last1, __first2); __glibcxx_requires_sorted_set(__first2, __last2, __first1); __glibcxx_requires_irreflexive2(__first1, __last1); __glibcxx_requires_irreflexive2(__first2, __last2); return _GLIBCXX_STD_A::__set_union(__first1, __last1, __first2, __last2, __result, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Return the union of two sorted ranges using a comparison functor. * @ingroup set_algorithms * @param __first1 Start of first range. * @param __last1 End of first range. * @param __first2 Start of second range. * @param __last2 End of second range. * @param __result Start of output range. * @param __comp The comparison functor. * @return End of the output range. * @ingroup set_algorithms * * This operation iterates over both ranges, copying elements present in * each range in order to the output range. Iterators increment for each * range. When the current element of one range is less than the other * according to @p __comp, that element is copied and the iterator advanced. * If an equivalent element according to @p __comp is contained in both * ranges, the element from the first range is copied and both ranges * advance. The output range may not overlap either input range. */ template inline _OutputIterator set_union(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_InputIterator1>::value_type, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_InputIterator2>::value_type, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_requires_sorted_set_pred(__first1, __last1, __first2, __comp); __glibcxx_requires_sorted_set_pred(__first2, __last2, __first1, __comp); __glibcxx_requires_irreflexive_pred2(__first1, __last1, __comp); __glibcxx_requires_irreflexive_pred2(__first2, __last2, __comp); return _GLIBCXX_STD_A::__set_union(__first1, __last1, __first2, __last2, __result, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } template _OutputIterator __set_intersection(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) { while (__first1 != __last1 && __first2 != __last2) if (__comp(__first1, __first2)) ++__first1; else if (__comp(__first2, __first1)) ++__first2; else { *__result = *__first1; ++__first1; ++__first2; ++__result; } return __result; } /** * @brief Return the intersection of two sorted ranges. * @ingroup set_algorithms * @param __first1 Start of first range. * @param __last1 End of first range. * @param __first2 Start of second range. * @param __last2 End of second range. * @param __result Start of output range. * @return End of the output range. * @ingroup set_algorithms * * This operation iterates over both ranges, copying elements present in * both ranges in order to the output range. Iterators increment for each * range. When the current element of one range is less than the other, * that iterator advances. If an element is contained in both ranges, the * element from the first range is copied and both ranges advance. The * output range may not overlap either input range. */ template inline _OutputIterator set_intersection(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_function_requires(_LessThanOpConcept< typename iterator_traits<_InputIterator1>::value_type, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_LessThanOpConcept< typename iterator_traits<_InputIterator2>::value_type, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_requires_sorted_set(__first1, __last1, __first2); __glibcxx_requires_sorted_set(__first2, __last2, __first1); __glibcxx_requires_irreflexive2(__first1, __last1); __glibcxx_requires_irreflexive2(__first2, __last2); return _GLIBCXX_STD_A::__set_intersection(__first1, __last1, __first2, __last2, __result, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Return the intersection of two sorted ranges using comparison * functor. * @ingroup set_algorithms * @param __first1 Start of first range. * @param __last1 End of first range. * @param __first2 Start of second range. * @param __last2 End of second range. * @param __result Start of output range. * @param __comp The comparison functor. * @return End of the output range. * @ingroup set_algorithms * * This operation iterates over both ranges, copying elements present in * both ranges in order to the output range. Iterators increment for each * range. When the current element of one range is less than the other * according to @p __comp, that iterator advances. If an element is * contained in both ranges according to @p __comp, the element from the * first range is copied and both ranges advance. The output range may not * overlap either input range. */ template inline _OutputIterator set_intersection(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_InputIterator1>::value_type, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_InputIterator2>::value_type, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_requires_sorted_set_pred(__first1, __last1, __first2, __comp); __glibcxx_requires_sorted_set_pred(__first2, __last2, __first1, __comp); __glibcxx_requires_irreflexive_pred2(__first1, __last1, __comp); __glibcxx_requires_irreflexive_pred2(__first2, __last2, __comp); return _GLIBCXX_STD_A::__set_intersection(__first1, __last1, __first2, __last2, __result, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } template _OutputIterator __set_difference(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) { while (__first1 != __last1 && __first2 != __last2) if (__comp(__first1, __first2)) { *__result = *__first1; ++__first1; ++__result; } else if (__comp(__first2, __first1)) ++__first2; else { ++__first1; ++__first2; } return std::copy(__first1, __last1, __result); } /** * @brief Return the difference of two sorted ranges. * @ingroup set_algorithms * @param __first1 Start of first range. * @param __last1 End of first range. * @param __first2 Start of second range. * @param __last2 End of second range. * @param __result Start of output range. * @return End of the output range. * @ingroup set_algorithms * * This operation iterates over both ranges, copying elements present in * the first range but not the second in order to the output range. * Iterators increment for each range. When the current element of the * first range is less than the second, that element is copied and the * iterator advances. If the current element of the second range is less, * the iterator advances, but no element is copied. If an element is * contained in both ranges, no elements are copied and both ranges * advance. The output range may not overlap either input range. */ template inline _OutputIterator set_difference(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_function_requires(_LessThanOpConcept< typename iterator_traits<_InputIterator1>::value_type, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_LessThanOpConcept< typename iterator_traits<_InputIterator2>::value_type, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_requires_sorted_set(__first1, __last1, __first2); __glibcxx_requires_sorted_set(__first2, __last2, __first1); __glibcxx_requires_irreflexive2(__first1, __last1); __glibcxx_requires_irreflexive2(__first2, __last2); return _GLIBCXX_STD_A::__set_difference(__first1, __last1, __first2, __last2, __result, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Return the difference of two sorted ranges using comparison * functor. * @ingroup set_algorithms * @param __first1 Start of first range. * @param __last1 End of first range. * @param __first2 Start of second range. * @param __last2 End of second range. * @param __result Start of output range. * @param __comp The comparison functor. * @return End of the output range. * @ingroup set_algorithms * * This operation iterates over both ranges, copying elements present in * the first range but not the second in order to the output range. * Iterators increment for each range. When the current element of the * first range is less than the second according to @p __comp, that element * is copied and the iterator advances. If the current element of the * second range is less, no element is copied and the iterator advances. * If an element is contained in both ranges according to @p __comp, no * elements are copied and both ranges advance. The output range may not * overlap either input range. */ template inline _OutputIterator set_difference(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_InputIterator1>::value_type, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_InputIterator2>::value_type, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_requires_sorted_set_pred(__first1, __last1, __first2, __comp); __glibcxx_requires_sorted_set_pred(__first2, __last2, __first1, __comp); __glibcxx_requires_irreflexive_pred2(__first1, __last1, __comp); __glibcxx_requires_irreflexive_pred2(__first2, __last2, __comp); return _GLIBCXX_STD_A::__set_difference(__first1, __last1, __first2, __last2, __result, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } template _OutputIterator __set_symmetric_difference(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) { while (__first1 != __last1 && __first2 != __last2) if (__comp(__first1, __first2)) { *__result = *__first1; ++__first1; ++__result; } else if (__comp(__first2, __first1)) { *__result = *__first2; ++__first2; ++__result; } else { ++__first1; ++__first2; } return std::copy(__first2, __last2, std::copy(__first1, __last1, __result)); } /** * @brief Return the symmetric difference of two sorted ranges. * @ingroup set_algorithms * @param __first1 Start of first range. * @param __last1 End of first range. * @param __first2 Start of second range. * @param __last2 End of second range. * @param __result Start of output range. * @return End of the output range. * @ingroup set_algorithms * * This operation iterates over both ranges, copying elements present in * one range but not the other in order to the output range. Iterators * increment for each range. When the current element of one range is less * than the other, that element is copied and the iterator advances. If an * element is contained in both ranges, no elements are copied and both * ranges advance. The output range may not overlap either input range. */ template inline _OutputIterator set_symmetric_difference(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_LessThanOpConcept< typename iterator_traits<_InputIterator1>::value_type, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_LessThanOpConcept< typename iterator_traits<_InputIterator2>::value_type, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_requires_sorted_set(__first1, __last1, __first2); __glibcxx_requires_sorted_set(__first2, __last2, __first1); __glibcxx_requires_irreflexive2(__first1, __last1); __glibcxx_requires_irreflexive2(__first2, __last2); return _GLIBCXX_STD_A::__set_symmetric_difference(__first1, __last1, __first2, __last2, __result, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Return the symmetric difference of two sorted ranges using * comparison functor. * @ingroup set_algorithms * @param __first1 Start of first range. * @param __last1 End of first range. * @param __first2 Start of second range. * @param __last2 End of second range. * @param __result Start of output range. * @param __comp The comparison functor. * @return End of the output range. * @ingroup set_algorithms * * This operation iterates over both ranges, copying elements present in * one range but not the other in order to the output range. Iterators * increment for each range. When the current element of one range is less * than the other according to @p comp, that element is copied and the * iterator advances. If an element is contained in both ranges according * to @p __comp, no elements are copied and both ranges advance. The output * range may not overlap either input range. */ template inline _OutputIterator set_symmetric_difference(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_InputIterator1>::value_type, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_InputIterator2>::value_type, typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_requires_sorted_set_pred(__first1, __last1, __first2, __comp); __glibcxx_requires_sorted_set_pred(__first2, __last2, __first1, __comp); __glibcxx_requires_irreflexive_pred2(__first1, __last1, __comp); __glibcxx_requires_irreflexive_pred2(__first2, __last2, __comp); return _GLIBCXX_STD_A::__set_symmetric_difference(__first1, __last1, __first2, __last2, __result, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } template _GLIBCXX14_CONSTEXPR _ForwardIterator __min_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp) { if (__first == __last) return __first; _ForwardIterator __result = __first; while (++__first != __last) if (__comp(__first, __result)) __result = __first; return __result; } /** * @brief Return the minimum element in a range. * @ingroup sorting_algorithms * @param __first Start of range. * @param __last End of range. * @return Iterator referencing the first instance of the smallest value. */ template _GLIBCXX14_CONSTEXPR _ForwardIterator inline min_element(_ForwardIterator __first, _ForwardIterator __last) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); return _GLIBCXX_STD_A::__min_element(__first, __last, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Return the minimum element in a range using comparison functor. * @ingroup sorting_algorithms * @param __first Start of range. * @param __last End of range. * @param __comp Comparison functor. * @return Iterator referencing the first instance of the smallest value * according to __comp. */ template _GLIBCXX14_CONSTEXPR inline _ForwardIterator min_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_ForwardIterator>::value_type, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); return _GLIBCXX_STD_A::__min_element(__first, __last, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } template _GLIBCXX14_CONSTEXPR _ForwardIterator __max_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp) { if (__first == __last) return __first; _ForwardIterator __result = __first; while (++__first != __last) if (__comp(__result, __first)) __result = __first; return __result; } /** * @brief Return the maximum element in a range. * @ingroup sorting_algorithms * @param __first Start of range. * @param __last End of range. * @return Iterator referencing the first instance of the largest value. */ template _GLIBCXX14_CONSTEXPR inline _ForwardIterator max_element(_ForwardIterator __first, _ForwardIterator __last) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); return _GLIBCXX_STD_A::__max_element(__first, __last, __gnu_cxx::__ops::__iter_less_iter()); } /** * @brief Return the maximum element in a range using comparison functor. * @ingroup sorting_algorithms * @param __first Start of range. * @param __last End of range. * @param __comp Comparison functor. * @return Iterator referencing the first instance of the largest value * according to __comp. */ template _GLIBCXX14_CONSTEXPR inline _ForwardIterator max_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_Compare, typename iterator_traits<_ForwardIterator>::value_type, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); return _GLIBCXX_STD_A::__max_element(__first, __last, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } #if __cplusplus >= 201402L /// Reservoir sampling algorithm. template _RandomAccessIterator __sample(_InputIterator __first, _InputIterator __last, input_iterator_tag, _RandomAccessIterator __out, random_access_iterator_tag, _Size __n, _UniformRandomBitGenerator&& __g) { using __distrib_type = uniform_int_distribution<_Size>; using __param_type = typename __distrib_type::param_type; __distrib_type __d{}; _Size __sample_sz = 0; while (__first != __last && __sample_sz != __n) { __out[__sample_sz++] = *__first; ++__first; } for (auto __pop_sz = __sample_sz; __first != __last; ++__first, (void) ++__pop_sz) { const auto __k = __d(__g, __param_type{0, __pop_sz}); if (__k < __n) __out[__k] = *__first; } return __out + __sample_sz; } /// Selection sampling algorithm. template _OutputIterator __sample(_ForwardIterator __first, _ForwardIterator __last, forward_iterator_tag, _OutputIterator __out, _Cat, _Size __n, _UniformRandomBitGenerator&& __g) { using __distrib_type = uniform_int_distribution<_Size>; using __param_type = typename __distrib_type::param_type; using _USize = make_unsigned_t<_Size>; using _Gen = remove_reference_t<_UniformRandomBitGenerator>; using __uc_type = common_type_t; if (__first == __last) return __out; __distrib_type __d{}; _Size __unsampled_sz = std::distance(__first, __last); __n = std::min(__n, __unsampled_sz); // If possible, we use __gen_two_uniform_ints to efficiently produce // two random numbers using a single distribution invocation: const __uc_type __urngrange = __g.max() - __g.min(); if (__urngrange / __uc_type(__unsampled_sz) >= __uc_type(__unsampled_sz)) // I.e. (__urngrange >= __unsampled_sz * __unsampled_sz) but without // wrapping issues. { while (__n != 0 && __unsampled_sz >= 2) { const pair<_Size, _Size> __p = __gen_two_uniform_ints(__unsampled_sz, __unsampled_sz - 1, __g); --__unsampled_sz; if (__p.first < __n) { *__out++ = *__first; --__n; } ++__first; if (__n == 0) break; --__unsampled_sz; if (__p.second < __n) { *__out++ = *__first; --__n; } ++__first; } } // The loop above is otherwise equivalent to this one-at-a-time version: for (; __n != 0; ++__first) if (__d(__g, __param_type{0, --__unsampled_sz}) < __n) { *__out++ = *__first; --__n; } return __out; } #if __cplusplus > 201402L #define __cpp_lib_sample 201603 /// Take a random sample from a population. template _SampleIterator sample(_PopulationIterator __first, _PopulationIterator __last, _SampleIterator __out, _Distance __n, _UniformRandomBitGenerator&& __g) { using __pop_cat = typename std::iterator_traits<_PopulationIterator>::iterator_category; using __samp_cat = typename std::iterator_traits<_SampleIterator>::iterator_category; static_assert( __or_, is_convertible<__samp_cat, random_access_iterator_tag>>::value, "output range must use a RandomAccessIterator when input range" " does not meet the ForwardIterator requirements"); static_assert(is_integral<_Distance>::value, "sample size must be an integer type"); typename iterator_traits<_PopulationIterator>::difference_type __d = __n; return _GLIBCXX_STD_A:: __sample(__first, __last, __pop_cat{}, __out, __samp_cat{}, __d, std::forward<_UniformRandomBitGenerator>(__g)); } #endif // C++17 #endif // C++14 _GLIBCXX_END_NAMESPACE_ALGO _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_ALGO_H */ PK!!2\>>8/bits/stl_algobase.hnu[// Core algorithmic facilities -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996-1998 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_algobase.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{algorithm} */ #ifndef _STL_ALGOBASE_H #define _STL_ALGOBASE_H 1 #include #include #include #include #include #include #include #include #include #include #include #include // For std::swap #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if __cplusplus < 201103L // See http://gcc.gnu.org/ml/libstdc++/2004-08/msg00167.html: in a // nutshell, we are partially implementing the resolution of DR 187, // when it's safe, i.e., the value_types are equal. template struct __iter_swap { template static void iter_swap(_ForwardIterator1 __a, _ForwardIterator2 __b) { typedef typename iterator_traits<_ForwardIterator1>::value_type _ValueType1; _ValueType1 __tmp = *__a; *__a = *__b; *__b = __tmp; } }; template<> struct __iter_swap { template static void iter_swap(_ForwardIterator1 __a, _ForwardIterator2 __b) { swap(*__a, *__b); } }; #endif /** * @brief Swaps the contents of two iterators. * @ingroup mutating_algorithms * @param __a An iterator. * @param __b Another iterator. * @return Nothing. * * This function swaps the values pointed to by two iterators, not the * iterators themselves. */ template inline void iter_swap(_ForwardIterator1 __a, _ForwardIterator2 __b) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator1>) __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator2>) #if __cplusplus < 201103L typedef typename iterator_traits<_ForwardIterator1>::value_type _ValueType1; typedef typename iterator_traits<_ForwardIterator2>::value_type _ValueType2; __glibcxx_function_requires(_ConvertibleConcept<_ValueType1, _ValueType2>) __glibcxx_function_requires(_ConvertibleConcept<_ValueType2, _ValueType1>) typedef typename iterator_traits<_ForwardIterator1>::reference _ReferenceType1; typedef typename iterator_traits<_ForwardIterator2>::reference _ReferenceType2; std::__iter_swap<__are_same<_ValueType1, _ValueType2>::__value && __are_same<_ValueType1&, _ReferenceType1>::__value && __are_same<_ValueType2&, _ReferenceType2>::__value>:: iter_swap(__a, __b); #else swap(*__a, *__b); #endif } /** * @brief Swap the elements of two sequences. * @ingroup mutating_algorithms * @param __first1 A forward iterator. * @param __last1 A forward iterator. * @param __first2 A forward iterator. * @return An iterator equal to @p first2+(last1-first1). * * Swaps each element in the range @p [first1,last1) with the * corresponding element in the range @p [first2,(last1-first1)). * The ranges must not overlap. */ template _ForwardIterator2 swap_ranges(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator1>) __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator2>) __glibcxx_requires_valid_range(__first1, __last1); for (; __first1 != __last1; ++__first1, (void)++__first2) std::iter_swap(__first1, __first2); return __first2; } /** * @brief This does what you think it does. * @ingroup sorting_algorithms * @param __a A thing of arbitrary type. * @param __b Another thing of arbitrary type. * @return The lesser of the parameters. * * This is the simple classic generic implementation. It will work on * temporary expressions, since they are only evaluated once, unlike a * preprocessor macro. */ template _GLIBCXX14_CONSTEXPR inline const _Tp& min(const _Tp& __a, const _Tp& __b) { // concept requirements __glibcxx_function_requires(_LessThanComparableConcept<_Tp>) //return __b < __a ? __b : __a; if (__b < __a) return __b; return __a; } /** * @brief This does what you think it does. * @ingroup sorting_algorithms * @param __a A thing of arbitrary type. * @param __b Another thing of arbitrary type. * @return The greater of the parameters. * * This is the simple classic generic implementation. It will work on * temporary expressions, since they are only evaluated once, unlike a * preprocessor macro. */ template _GLIBCXX14_CONSTEXPR inline const _Tp& max(const _Tp& __a, const _Tp& __b) { // concept requirements __glibcxx_function_requires(_LessThanComparableConcept<_Tp>) //return __a < __b ? __b : __a; if (__a < __b) return __b; return __a; } /** * @brief This does what you think it does. * @ingroup sorting_algorithms * @param __a A thing of arbitrary type. * @param __b Another thing of arbitrary type. * @param __comp A @link comparison_functors comparison functor@endlink. * @return The lesser of the parameters. * * This will work on temporary expressions, since they are only evaluated * once, unlike a preprocessor macro. */ template _GLIBCXX14_CONSTEXPR inline const _Tp& min(const _Tp& __a, const _Tp& __b, _Compare __comp) { //return __comp(__b, __a) ? __b : __a; if (__comp(__b, __a)) return __b; return __a; } /** * @brief This does what you think it does. * @ingroup sorting_algorithms * @param __a A thing of arbitrary type. * @param __b Another thing of arbitrary type. * @param __comp A @link comparison_functors comparison functor@endlink. * @return The greater of the parameters. * * This will work on temporary expressions, since they are only evaluated * once, unlike a preprocessor macro. */ template _GLIBCXX14_CONSTEXPR inline const _Tp& max(const _Tp& __a, const _Tp& __b, _Compare __comp) { //return __comp(__a, __b) ? __b : __a; if (__comp(__a, __b)) return __b; return __a; } // Fallback implementation of the function in bits/stl_iterator.h used to // remove the __normal_iterator wrapper. See copy, fill, ... template inline _Iterator __niter_base(_Iterator __it) { return __it; } // All of these auxiliary structs serve two purposes. (1) Replace // calls to copy with memmove whenever possible. (Memmove, not memcpy, // because the input and output ranges are permitted to overlap.) // (2) If we're using random access iterators, then write the loop as // a for loop with an explicit count. template struct __copy_move { template static _OI __copy_m(_II __first, _II __last, _OI __result) { for (; __first != __last; ++__result, (void)++__first) *__result = *__first; return __result; } }; #if __cplusplus >= 201103L template struct __copy_move { template static _OI __copy_m(_II __first, _II __last, _OI __result) { for (; __first != __last; ++__result, (void)++__first) *__result = std::move(*__first); return __result; } }; #endif template<> struct __copy_move { template static _OI __copy_m(_II __first, _II __last, _OI __result) { typedef typename iterator_traits<_II>::difference_type _Distance; for(_Distance __n = __last - __first; __n > 0; --__n) { *__result = *__first; ++__first; ++__result; } return __result; } }; #if __cplusplus >= 201103L template<> struct __copy_move { template static _OI __copy_m(_II __first, _II __last, _OI __result) { typedef typename iterator_traits<_II>::difference_type _Distance; for(_Distance __n = __last - __first; __n > 0; --__n) { *__result = std::move(*__first); ++__first; ++__result; } return __result; } }; #endif template struct __copy_move<_IsMove, true, random_access_iterator_tag> { template static _Tp* __copy_m(const _Tp* __first, const _Tp* __last, _Tp* __result) { #if __cplusplus >= 201103L using __assignable = conditional<_IsMove, is_move_assignable<_Tp>, is_copy_assignable<_Tp>>; // trivial types can have deleted assignment static_assert( __assignable::type::value, "type is not assignable" ); #endif const ptrdiff_t _Num = __last - __first; if (_Num) __builtin_memmove(__result, __first, sizeof(_Tp) * _Num); return __result + _Num; } }; template inline _OI __copy_move_a(_II __first, _II __last, _OI __result) { typedef typename iterator_traits<_II>::value_type _ValueTypeI; typedef typename iterator_traits<_OI>::value_type _ValueTypeO; typedef typename iterator_traits<_II>::iterator_category _Category; const bool __simple = (__is_trivial(_ValueTypeI) && __is_pointer<_II>::__value && __is_pointer<_OI>::__value && __are_same<_ValueTypeI, _ValueTypeO>::__value); return std::__copy_move<_IsMove, __simple, _Category>::__copy_m(__first, __last, __result); } // Helpers for streambuf iterators (either istream or ostream). // NB: avoid including , relatively large. template struct char_traits; template class istreambuf_iterator; template class ostreambuf_iterator; template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, ostreambuf_iterator<_CharT, char_traits<_CharT> > >::__type __copy_move_a2(_CharT*, _CharT*, ostreambuf_iterator<_CharT, char_traits<_CharT> >); template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, ostreambuf_iterator<_CharT, char_traits<_CharT> > >::__type __copy_move_a2(const _CharT*, const _CharT*, ostreambuf_iterator<_CharT, char_traits<_CharT> >); template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, _CharT*>::__type __copy_move_a2(istreambuf_iterator<_CharT, char_traits<_CharT> >, istreambuf_iterator<_CharT, char_traits<_CharT> >, _CharT*); template inline _OI __copy_move_a2(_II __first, _II __last, _OI __result) { return _OI(std::__copy_move_a<_IsMove>(std::__niter_base(__first), std::__niter_base(__last), std::__niter_base(__result))); } /** * @brief Copies the range [first,last) into result. * @ingroup mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __result An output iterator. * @return result + (first - last) * * This inline function will boil down to a call to @c memmove whenever * possible. Failing that, if random access iterators are passed, then the * loop count will be known (and therefore a candidate for compiler * optimizations such as unrolling). Result may not be contained within * [first,last); the copy_backward function should be used instead. * * Note that the end of the output range is permitted to be contained * within [first,last). */ template inline _OI copy(_II __first, _II __last, _OI __result) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_II>) __glibcxx_function_requires(_OutputIteratorConcept<_OI, typename iterator_traits<_II>::value_type>) __glibcxx_requires_valid_range(__first, __last); return (std::__copy_move_a2<__is_move_iterator<_II>::__value> (std::__miter_base(__first), std::__miter_base(__last), __result)); } #if __cplusplus >= 201103L /** * @brief Moves the range [first,last) into result. * @ingroup mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __result An output iterator. * @return result + (first - last) * * This inline function will boil down to a call to @c memmove whenever * possible. Failing that, if random access iterators are passed, then the * loop count will be known (and therefore a candidate for compiler * optimizations such as unrolling). Result may not be contained within * [first,last); the move_backward function should be used instead. * * Note that the end of the output range is permitted to be contained * within [first,last). */ template inline _OI move(_II __first, _II __last, _OI __result) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_II>) __glibcxx_function_requires(_OutputIteratorConcept<_OI, typename iterator_traits<_II>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__copy_move_a2(std::__miter_base(__first), std::__miter_base(__last), __result); } #define _GLIBCXX_MOVE3(_Tp, _Up, _Vp) std::move(_Tp, _Up, _Vp) #else #define _GLIBCXX_MOVE3(_Tp, _Up, _Vp) std::copy(_Tp, _Up, _Vp) #endif template struct __copy_move_backward { template static _BI2 __copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result) { while (__first != __last) *--__result = *--__last; return __result; } }; #if __cplusplus >= 201103L template struct __copy_move_backward { template static _BI2 __copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result) { while (__first != __last) *--__result = std::move(*--__last); return __result; } }; #endif template<> struct __copy_move_backward { template static _BI2 __copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result) { typename iterator_traits<_BI1>::difference_type __n; for (__n = __last - __first; __n > 0; --__n) *--__result = *--__last; return __result; } }; #if __cplusplus >= 201103L template<> struct __copy_move_backward { template static _BI2 __copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result) { typename iterator_traits<_BI1>::difference_type __n; for (__n = __last - __first; __n > 0; --__n) *--__result = std::move(*--__last); return __result; } }; #endif template struct __copy_move_backward<_IsMove, true, random_access_iterator_tag> { template static _Tp* __copy_move_b(const _Tp* __first, const _Tp* __last, _Tp* __result) { #if __cplusplus >= 201103L using __assignable = conditional<_IsMove, is_move_assignable<_Tp>, is_copy_assignable<_Tp>>; // trivial types can have deleted assignment static_assert( __assignable::type::value, "type is not assignable" ); #endif const ptrdiff_t _Num = __last - __first; if (_Num) __builtin_memmove(__result - _Num, __first, sizeof(_Tp) * _Num); return __result - _Num; } }; template inline _BI2 __copy_move_backward_a(_BI1 __first, _BI1 __last, _BI2 __result) { typedef typename iterator_traits<_BI1>::value_type _ValueType1; typedef typename iterator_traits<_BI2>::value_type _ValueType2; typedef typename iterator_traits<_BI1>::iterator_category _Category; const bool __simple = (__is_trivial(_ValueType1) && __is_pointer<_BI1>::__value && __is_pointer<_BI2>::__value && __are_same<_ValueType1, _ValueType2>::__value); return std::__copy_move_backward<_IsMove, __simple, _Category>::__copy_move_b(__first, __last, __result); } template inline _BI2 __copy_move_backward_a2(_BI1 __first, _BI1 __last, _BI2 __result) { return _BI2(std::__copy_move_backward_a<_IsMove> (std::__niter_base(__first), std::__niter_base(__last), std::__niter_base(__result))); } /** * @brief Copies the range [first,last) into result. * @ingroup mutating_algorithms * @param __first A bidirectional iterator. * @param __last A bidirectional iterator. * @param __result A bidirectional iterator. * @return result - (first - last) * * The function has the same effect as copy, but starts at the end of the * range and works its way to the start, returning the start of the result. * This inline function will boil down to a call to @c memmove whenever * possible. Failing that, if random access iterators are passed, then the * loop count will be known (and therefore a candidate for compiler * optimizations such as unrolling). * * Result may not be in the range (first,last]. Use copy instead. Note * that the start of the output range may overlap [first,last). */ template inline _BI2 copy_backward(_BI1 __first, _BI1 __last, _BI2 __result) { // concept requirements __glibcxx_function_requires(_BidirectionalIteratorConcept<_BI1>) __glibcxx_function_requires(_Mutable_BidirectionalIteratorConcept<_BI2>) __glibcxx_function_requires(_ConvertibleConcept< typename iterator_traits<_BI1>::value_type, typename iterator_traits<_BI2>::value_type>) __glibcxx_requires_valid_range(__first, __last); return (std::__copy_move_backward_a2<__is_move_iterator<_BI1>::__value> (std::__miter_base(__first), std::__miter_base(__last), __result)); } #if __cplusplus >= 201103L /** * @brief Moves the range [first,last) into result. * @ingroup mutating_algorithms * @param __first A bidirectional iterator. * @param __last A bidirectional iterator. * @param __result A bidirectional iterator. * @return result - (first - last) * * The function has the same effect as move, but starts at the end of the * range and works its way to the start, returning the start of the result. * This inline function will boil down to a call to @c memmove whenever * possible. Failing that, if random access iterators are passed, then the * loop count will be known (and therefore a candidate for compiler * optimizations such as unrolling). * * Result may not be in the range (first,last]. Use move instead. Note * that the start of the output range may overlap [first,last). */ template inline _BI2 move_backward(_BI1 __first, _BI1 __last, _BI2 __result) { // concept requirements __glibcxx_function_requires(_BidirectionalIteratorConcept<_BI1>) __glibcxx_function_requires(_Mutable_BidirectionalIteratorConcept<_BI2>) __glibcxx_function_requires(_ConvertibleConcept< typename iterator_traits<_BI1>::value_type, typename iterator_traits<_BI2>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__copy_move_backward_a2(std::__miter_base(__first), std::__miter_base(__last), __result); } #define _GLIBCXX_MOVE_BACKWARD3(_Tp, _Up, _Vp) std::move_backward(_Tp, _Up, _Vp) #else #define _GLIBCXX_MOVE_BACKWARD3(_Tp, _Up, _Vp) std::copy_backward(_Tp, _Up, _Vp) #endif template inline typename __gnu_cxx::__enable_if::__value, void>::__type __fill_a(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { for (; __first != __last; ++__first) *__first = __value; } template inline typename __gnu_cxx::__enable_if<__is_scalar<_Tp>::__value, void>::__type __fill_a(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { const _Tp __tmp = __value; for (; __first != __last; ++__first) *__first = __tmp; } // Specialization: for char types we can use memset. template inline typename __gnu_cxx::__enable_if<__is_byte<_Tp>::__value, void>::__type __fill_a(_Tp* __first, _Tp* __last, const _Tp& __c) { const _Tp __tmp = __c; if (const size_t __len = __last - __first) __builtin_memset(__first, static_cast(__tmp), __len); } /** * @brief Fills the range [first,last) with copies of value. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @param __value A reference-to-const of arbitrary type. * @return Nothing. * * This function fills a range with copies of the same value. For char * types filling contiguous areas of memory, this becomes an inline call * to @c memset or @c wmemset. */ template inline void fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator>) __glibcxx_requires_valid_range(__first, __last); std::__fill_a(std::__niter_base(__first), std::__niter_base(__last), __value); } template inline typename __gnu_cxx::__enable_if::__value, _OutputIterator>::__type __fill_n_a(_OutputIterator __first, _Size __n, const _Tp& __value) { for (__decltype(__n + 0) __niter = __n; __niter > 0; --__niter, (void) ++__first) *__first = __value; return __first; } template inline typename __gnu_cxx::__enable_if<__is_scalar<_Tp>::__value, _OutputIterator>::__type __fill_n_a(_OutputIterator __first, _Size __n, const _Tp& __value) { const _Tp __tmp = __value; for (__decltype(__n + 0) __niter = __n; __niter > 0; --__niter, (void) ++__first) *__first = __tmp; return __first; } template inline typename __gnu_cxx::__enable_if<__is_byte<_Tp>::__value, _Tp*>::__type __fill_n_a(_Tp* __first, _Size __n, const _Tp& __c) { std::__fill_a(__first, __first + __n, __c); return __first + __n; } /** * @brief Fills the range [first,first+n) with copies of value. * @ingroup mutating_algorithms * @param __first An output iterator. * @param __n The count of copies to perform. * @param __value A reference-to-const of arbitrary type. * @return The iterator at first+n. * * This function fills a range with copies of the same value. For char * types filling contiguous areas of memory, this becomes an inline call * to @c memset or @ wmemset. * * _GLIBCXX_RESOLVE_LIB_DEFECTS * DR 865. More algorithms that throw away information */ template inline _OI fill_n(_OI __first, _Size __n, const _Tp& __value) { // concept requirements __glibcxx_function_requires(_OutputIteratorConcept<_OI, _Tp>) return _OI(std::__fill_n_a(std::__niter_base(__first), __n, __value)); } template struct __equal { template static bool equal(_II1 __first1, _II1 __last1, _II2 __first2) { for (; __first1 != __last1; ++__first1, (void) ++__first2) if (!(*__first1 == *__first2)) return false; return true; } }; template<> struct __equal { template static bool equal(const _Tp* __first1, const _Tp* __last1, const _Tp* __first2) { if (const size_t __len = (__last1 - __first1)) return !__builtin_memcmp(__first1, __first2, sizeof(_Tp) * __len); return true; } }; template inline bool __equal_aux(_II1 __first1, _II1 __last1, _II2 __first2) { typedef typename iterator_traits<_II1>::value_type _ValueType1; typedef typename iterator_traits<_II2>::value_type _ValueType2; const bool __simple = ((__is_integer<_ValueType1>::__value || __is_pointer<_ValueType1>::__value) && __is_pointer<_II1>::__value && __is_pointer<_II2>::__value && __are_same<_ValueType1, _ValueType2>::__value); return std::__equal<__simple>::equal(__first1, __last1, __first2); } template struct __lc_rai { template static _II1 __newlast1(_II1, _II1 __last1, _II2, _II2) { return __last1; } template static bool __cnd2(_II __first, _II __last) { return __first != __last; } }; template<> struct __lc_rai { template static _RAI1 __newlast1(_RAI1 __first1, _RAI1 __last1, _RAI2 __first2, _RAI2 __last2) { const typename iterator_traits<_RAI1>::difference_type __diff1 = __last1 - __first1; const typename iterator_traits<_RAI2>::difference_type __diff2 = __last2 - __first2; return __diff2 < __diff1 ? __first1 + __diff2 : __last1; } template static bool __cnd2(_RAI, _RAI) { return true; } }; template bool __lexicographical_compare_impl(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2, _Compare __comp) { typedef typename iterator_traits<_II1>::iterator_category _Category1; typedef typename iterator_traits<_II2>::iterator_category _Category2; typedef std::__lc_rai<_Category1, _Category2> __rai_type; __last1 = __rai_type::__newlast1(__first1, __last1, __first2, __last2); for (; __first1 != __last1 && __rai_type::__cnd2(__first2, __last2); ++__first1, (void)++__first2) { if (__comp(__first1, __first2)) return true; if (__comp(__first2, __first1)) return false; } return __first1 == __last1 && __first2 != __last2; } template struct __lexicographical_compare { template static bool __lc(_II1, _II1, _II2, _II2); }; template template bool __lexicographical_compare<_BoolType>:: __lc(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2) { return std::__lexicographical_compare_impl(__first1, __last1, __first2, __last2, __gnu_cxx::__ops::__iter_less_iter()); } template<> struct __lexicographical_compare { template static bool __lc(const _Tp* __first1, const _Tp* __last1, const _Up* __first2, const _Up* __last2) { const size_t __len1 = __last1 - __first1; const size_t __len2 = __last2 - __first2; if (const size_t __len = std::min(__len1, __len2)) if (int __result = __builtin_memcmp(__first1, __first2, __len)) return __result < 0; return __len1 < __len2; } }; template inline bool __lexicographical_compare_aux(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2) { typedef typename iterator_traits<_II1>::value_type _ValueType1; typedef typename iterator_traits<_II2>::value_type _ValueType2; const bool __simple = (__is_byte<_ValueType1>::__value && __is_byte<_ValueType2>::__value && !__gnu_cxx::__numeric_traits<_ValueType1>::__is_signed && !__gnu_cxx::__numeric_traits<_ValueType2>::__is_signed && __is_pointer<_II1>::__value && __is_pointer<_II2>::__value); return std::__lexicographical_compare<__simple>::__lc(__first1, __last1, __first2, __last2); } template _ForwardIterator __lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __val, _Compare __comp) { typedef typename iterator_traits<_ForwardIterator>::difference_type _DistanceType; _DistanceType __len = std::distance(__first, __last); while (__len > 0) { _DistanceType __half = __len >> 1; _ForwardIterator __middle = __first; std::advance(__middle, __half); if (__comp(__middle, __val)) { __first = __middle; ++__first; __len = __len - __half - 1; } else __len = __half; } return __first; } /** * @brief Finds the first position in which @a val could be inserted * without changing the ordering. * @param __first An iterator. * @param __last Another iterator. * @param __val The search term. * @return An iterator pointing to the first element not less * than @a val, or end() if every element is less than * @a val. * @ingroup binary_search_algorithms */ template inline _ForwardIterator lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __val) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_LessThanOpConcept< typename iterator_traits<_ForwardIterator>::value_type, _Tp>) __glibcxx_requires_partitioned_lower(__first, __last, __val); return std::__lower_bound(__first, __last, __val, __gnu_cxx::__ops::__iter_less_val()); } /// This is a helper function for the sort routines and for random.tcc. // Precondition: __n > 0. inline _GLIBCXX_CONSTEXPR int __lg(int __n) { return (int)sizeof(int) * __CHAR_BIT__ - 1 - __builtin_clz(__n); } inline _GLIBCXX_CONSTEXPR unsigned __lg(unsigned __n) { return (int)sizeof(int) * __CHAR_BIT__ - 1 - __builtin_clz(__n); } inline _GLIBCXX_CONSTEXPR long __lg(long __n) { return (int)sizeof(long) * __CHAR_BIT__ - 1 - __builtin_clzl(__n); } inline _GLIBCXX_CONSTEXPR unsigned long __lg(unsigned long __n) { return (int)sizeof(long) * __CHAR_BIT__ - 1 - __builtin_clzl(__n); } inline _GLIBCXX_CONSTEXPR long long __lg(long long __n) { return (int)sizeof(long long) * __CHAR_BIT__ - 1 - __builtin_clzll(__n); } inline _GLIBCXX_CONSTEXPR unsigned long long __lg(unsigned long long __n) { return (int)sizeof(long long) * __CHAR_BIT__ - 1 - __builtin_clzll(__n); } _GLIBCXX_BEGIN_NAMESPACE_ALGO /** * @brief Tests a range for element-wise equality. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @return A boolean true or false. * * This compares the elements of two ranges using @c == and returns true or * false depending on whether all of the corresponding elements of the * ranges are equal. */ template inline bool equal(_II1 __first1, _II1 __last1, _II2 __first2) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_II1>) __glibcxx_function_requires(_InputIteratorConcept<_II2>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_II1>::value_type, typename iterator_traits<_II2>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); return std::__equal_aux(std::__niter_base(__first1), std::__niter_base(__last1), std::__niter_base(__first2)); } /** * @brief Tests a range for element-wise equality. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __binary_pred A binary predicate @link functors * functor@endlink. * @return A boolean true or false. * * This compares the elements of two ranges using the binary_pred * parameter, and returns true or * false depending on whether all of the corresponding elements of the * ranges are equal. */ template inline bool equal(_IIter1 __first1, _IIter1 __last1, _IIter2 __first2, _BinaryPredicate __binary_pred) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_IIter1>) __glibcxx_function_requires(_InputIteratorConcept<_IIter2>) __glibcxx_requires_valid_range(__first1, __last1); for (; __first1 != __last1; ++__first1, (void)++__first2) if (!bool(__binary_pred(*__first1, *__first2))) return false; return true; } #if __cplusplus >= 201103L // 4-iterator version of std::equal for use in C++11. template inline bool __equal4(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2) { using _RATag = random_access_iterator_tag; using _Cat1 = typename iterator_traits<_II1>::iterator_category; using _Cat2 = typename iterator_traits<_II2>::iterator_category; using _RAIters = __and_, is_same<_Cat2, _RATag>>; if (_RAIters()) { auto __d1 = std::distance(__first1, __last1); auto __d2 = std::distance(__first2, __last2); if (__d1 != __d2) return false; return _GLIBCXX_STD_A::equal(__first1, __last1, __first2); } for (; __first1 != __last1 && __first2 != __last2; ++__first1, (void)++__first2) if (!(*__first1 == *__first2)) return false; return __first1 == __last1 && __first2 == __last2; } // 4-iterator version of std::equal for use in C++11. template inline bool __equal4(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2, _BinaryPredicate __binary_pred) { using _RATag = random_access_iterator_tag; using _Cat1 = typename iterator_traits<_II1>::iterator_category; using _Cat2 = typename iterator_traits<_II2>::iterator_category; using _RAIters = __and_, is_same<_Cat2, _RATag>>; if (_RAIters()) { auto __d1 = std::distance(__first1, __last1); auto __d2 = std::distance(__first2, __last2); if (__d1 != __d2) return false; return _GLIBCXX_STD_A::equal(__first1, __last1, __first2, __binary_pred); } for (; __first1 != __last1 && __first2 != __last2; ++__first1, (void)++__first2) if (!bool(__binary_pred(*__first1, *__first2))) return false; return __first1 == __last1 && __first2 == __last2; } #endif // C++11 #if __cplusplus > 201103L #define __cpp_lib_robust_nonmodifying_seq_ops 201304 /** * @brief Tests a range for element-wise equality. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __last2 An input iterator. * @return A boolean true or false. * * This compares the elements of two ranges using @c == and returns true or * false depending on whether all of the corresponding elements of the * ranges are equal. */ template inline bool equal(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_II1>) __glibcxx_function_requires(_InputIteratorConcept<_II2>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_II1>::value_type, typename iterator_traits<_II2>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return _GLIBCXX_STD_A::__equal4(__first1, __last1, __first2, __last2); } /** * @brief Tests a range for element-wise equality. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __last2 An input iterator. * @param __binary_pred A binary predicate @link functors * functor@endlink. * @return A boolean true or false. * * This compares the elements of two ranges using the binary_pred * parameter, and returns true or * false depending on whether all of the corresponding elements of the * ranges are equal. */ template inline bool equal(_IIter1 __first1, _IIter1 __last1, _IIter2 __first2, _IIter2 __last2, _BinaryPredicate __binary_pred) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_IIter1>) __glibcxx_function_requires(_InputIteratorConcept<_IIter2>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return _GLIBCXX_STD_A::__equal4(__first1, __last1, __first2, __last2, __binary_pred); } #endif // C++14 /** * @brief Performs @b dictionary comparison on ranges. * @ingroup sorting_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __last2 An input iterator. * @return A boolean true or false. * * Returns true if the sequence of elements defined by the range * [first1,last1) is lexicographically less than the sequence of elements * defined by the range [first2,last2). Returns false otherwise. * (Quoted from [25.3.8]/1.) If the iterators are all character pointers, * then this is an inline call to @c memcmp. */ template inline bool lexicographical_compare(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2) { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename iterator_traits<_II1>::value_type _ValueType1; typedef typename iterator_traits<_II2>::value_type _ValueType2; #endif __glibcxx_function_requires(_InputIteratorConcept<_II1>) __glibcxx_function_requires(_InputIteratorConcept<_II2>) __glibcxx_function_requires(_LessThanOpConcept<_ValueType1, _ValueType2>) __glibcxx_function_requires(_LessThanOpConcept<_ValueType2, _ValueType1>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return std::__lexicographical_compare_aux(std::__niter_base(__first1), std::__niter_base(__last1), std::__niter_base(__first2), std::__niter_base(__last2)); } /** * @brief Performs @b dictionary comparison on ranges. * @ingroup sorting_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __last2 An input iterator. * @param __comp A @link comparison_functors comparison functor@endlink. * @return A boolean true or false. * * The same as the four-parameter @c lexicographical_compare, but uses the * comp parameter instead of @c <. */ template inline bool lexicographical_compare(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2, _Compare __comp) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_II1>) __glibcxx_function_requires(_InputIteratorConcept<_II2>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return std::__lexicographical_compare_impl (__first1, __last1, __first2, __last2, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } template pair<_InputIterator1, _InputIterator2> __mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _BinaryPredicate __binary_pred) { while (__first1 != __last1 && __binary_pred(__first1, __first2)) { ++__first1; ++__first2; } return pair<_InputIterator1, _InputIterator2>(__first1, __first2); } /** * @brief Finds the places in ranges which don't match. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @return A pair of iterators pointing to the first mismatch. * * This compares the elements of two ranges using @c == and returns a pair * of iterators. The first iterator points into the first range, the * second iterator points into the second range, and the elements pointed * to by the iterators are not equal. */ template inline pair<_InputIterator1, _InputIterator2> mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_InputIterator1>::value_type, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); return _GLIBCXX_STD_A::__mismatch(__first1, __last1, __first2, __gnu_cxx::__ops::__iter_equal_to_iter()); } /** * @brief Finds the places in ranges which don't match. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __binary_pred A binary predicate @link functors * functor@endlink. * @return A pair of iterators pointing to the first mismatch. * * This compares the elements of two ranges using the binary_pred * parameter, and returns a pair * of iterators. The first iterator points into the first range, the * second iterator points into the second range, and the elements pointed * to by the iterators are not equal. */ template inline pair<_InputIterator1, _InputIterator2> mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _BinaryPredicate __binary_pred) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_requires_valid_range(__first1, __last1); return _GLIBCXX_STD_A::__mismatch(__first1, __last1, __first2, __gnu_cxx::__ops::__iter_comp_iter(__binary_pred)); } #if __cplusplus > 201103L template pair<_InputIterator1, _InputIterator2> __mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _BinaryPredicate __binary_pred) { while (__first1 != __last1 && __first2 != __last2 && __binary_pred(__first1, __first2)) { ++__first1; ++__first2; } return pair<_InputIterator1, _InputIterator2>(__first1, __first2); } /** * @brief Finds the places in ranges which don't match. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __last2 An input iterator. * @return A pair of iterators pointing to the first mismatch. * * This compares the elements of two ranges using @c == and returns a pair * of iterators. The first iterator points into the first range, the * second iterator points into the second range, and the elements pointed * to by the iterators are not equal. */ template inline pair<_InputIterator1, _InputIterator2> mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_InputIterator1>::value_type, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return _GLIBCXX_STD_A::__mismatch(__first1, __last1, __first2, __last2, __gnu_cxx::__ops::__iter_equal_to_iter()); } /** * @brief Finds the places in ranges which don't match. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __last2 An input iterator. * @param __binary_pred A binary predicate @link functors * functor@endlink. * @return A pair of iterators pointing to the first mismatch. * * This compares the elements of two ranges using the binary_pred * parameter, and returns a pair * of iterators. The first iterator points into the first range, the * second iterator points into the second range, and the elements pointed * to by the iterators are not equal. */ template inline pair<_InputIterator1, _InputIterator2> mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _BinaryPredicate __binary_pred) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return _GLIBCXX_STD_A::__mismatch(__first1, __last1, __first2, __last2, __gnu_cxx::__ops::__iter_comp_iter(__binary_pred)); } #endif _GLIBCXX_END_NAMESPACE_ALGO _GLIBCXX_END_NAMESPACE_VERSION } // namespace std // NB: This file is included within many other C++ includes, as a way // of getting the base algorithms. So, make sure that parallel bits // come in too if requested. #ifdef _GLIBCXX_PARALLEL # include #endif #endif PK!ʔ8/bits/stl_bvector.hnu[// vector specialization -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996-1999 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_bvector.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{vector} */ #ifndef _STL_BVECTOR_H #define _STL_BVECTOR_H 1 #if __cplusplus >= 201103L #include #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER typedef unsigned long _Bit_type; enum { _S_word_bit = int(__CHAR_BIT__ * sizeof(_Bit_type)) }; struct _Bit_reference { _Bit_type * _M_p; _Bit_type _M_mask; _Bit_reference(_Bit_type * __x, _Bit_type __y) : _M_p(__x), _M_mask(__y) { } _Bit_reference() _GLIBCXX_NOEXCEPT : _M_p(0), _M_mask(0) { } operator bool() const _GLIBCXX_NOEXCEPT { return !!(*_M_p & _M_mask); } _Bit_reference& operator=(bool __x) _GLIBCXX_NOEXCEPT { if (__x) *_M_p |= _M_mask; else *_M_p &= ~_M_mask; return *this; } _Bit_reference& operator=(const _Bit_reference& __x) _GLIBCXX_NOEXCEPT { return *this = bool(__x); } bool operator==(const _Bit_reference& __x) const { return bool(*this) == bool(__x); } bool operator<(const _Bit_reference& __x) const { return !bool(*this) && bool(__x); } void flip() _GLIBCXX_NOEXCEPT { *_M_p ^= _M_mask; } }; #if __cplusplus >= 201103L inline void swap(_Bit_reference __x, _Bit_reference __y) noexcept { bool __tmp = __x; __x = __y; __y = __tmp; } inline void swap(_Bit_reference __x, bool& __y) noexcept { bool __tmp = __x; __x = __y; __y = __tmp; } inline void swap(bool& __x, _Bit_reference __y) noexcept { bool __tmp = __x; __x = __y; __y = __tmp; } #endif struct _Bit_iterator_base : public std::iterator { _Bit_type * _M_p; unsigned int _M_offset; _Bit_iterator_base(_Bit_type * __x, unsigned int __y) : _M_p(__x), _M_offset(__y) { } void _M_bump_up() { if (_M_offset++ == int(_S_word_bit) - 1) { _M_offset = 0; ++_M_p; } } void _M_bump_down() { if (_M_offset-- == 0) { _M_offset = int(_S_word_bit) - 1; --_M_p; } } void _M_incr(ptrdiff_t __i) { difference_type __n = __i + _M_offset; _M_p += __n / int(_S_word_bit); __n = __n % int(_S_word_bit); if (__n < 0) { __n += int(_S_word_bit); --_M_p; } _M_offset = static_cast(__n); } bool operator==(const _Bit_iterator_base& __i) const { return _M_p == __i._M_p && _M_offset == __i._M_offset; } bool operator<(const _Bit_iterator_base& __i) const { return _M_p < __i._M_p || (_M_p == __i._M_p && _M_offset < __i._M_offset); } bool operator!=(const _Bit_iterator_base& __i) const { return !(*this == __i); } bool operator>(const _Bit_iterator_base& __i) const { return __i < *this; } bool operator<=(const _Bit_iterator_base& __i) const { return !(__i < *this); } bool operator>=(const _Bit_iterator_base& __i) const { return !(*this < __i); } }; inline ptrdiff_t operator-(const _Bit_iterator_base& __x, const _Bit_iterator_base& __y) { return (int(_S_word_bit) * (__x._M_p - __y._M_p) + __x._M_offset - __y._M_offset); } struct _Bit_iterator : public _Bit_iterator_base { typedef _Bit_reference reference; typedef _Bit_reference* pointer; typedef _Bit_iterator iterator; _Bit_iterator() : _Bit_iterator_base(0, 0) { } _Bit_iterator(_Bit_type * __x, unsigned int __y) : _Bit_iterator_base(__x, __y) { } iterator _M_const_cast() const { return *this; } reference operator*() const { return reference(_M_p, 1UL << _M_offset); } iterator& operator++() { _M_bump_up(); return *this; } iterator operator++(int) { iterator __tmp = *this; _M_bump_up(); return __tmp; } iterator& operator--() { _M_bump_down(); return *this; } iterator operator--(int) { iterator __tmp = *this; _M_bump_down(); return __tmp; } iterator& operator+=(difference_type __i) { _M_incr(__i); return *this; } iterator& operator-=(difference_type __i) { *this += -__i; return *this; } iterator operator+(difference_type __i) const { iterator __tmp = *this; return __tmp += __i; } iterator operator-(difference_type __i) const { iterator __tmp = *this; return __tmp -= __i; } reference operator[](difference_type __i) const { return *(*this + __i); } }; inline _Bit_iterator operator+(ptrdiff_t __n, const _Bit_iterator& __x) { return __x + __n; } struct _Bit_const_iterator : public _Bit_iterator_base { typedef bool reference; typedef bool const_reference; typedef const bool* pointer; typedef _Bit_const_iterator const_iterator; _Bit_const_iterator() : _Bit_iterator_base(0, 0) { } _Bit_const_iterator(_Bit_type * __x, unsigned int __y) : _Bit_iterator_base(__x, __y) { } _Bit_const_iterator(const _Bit_iterator& __x) : _Bit_iterator_base(__x._M_p, __x._M_offset) { } _Bit_iterator _M_const_cast() const { return _Bit_iterator(_M_p, _M_offset); } const_reference operator*() const { return _Bit_reference(_M_p, 1UL << _M_offset); } const_iterator& operator++() { _M_bump_up(); return *this; } const_iterator operator++(int) { const_iterator __tmp = *this; _M_bump_up(); return __tmp; } const_iterator& operator--() { _M_bump_down(); return *this; } const_iterator operator--(int) { const_iterator __tmp = *this; _M_bump_down(); return __tmp; } const_iterator& operator+=(difference_type __i) { _M_incr(__i); return *this; } const_iterator& operator-=(difference_type __i) { *this += -__i; return *this; } const_iterator operator+(difference_type __i) const { const_iterator __tmp = *this; return __tmp += __i; } const_iterator operator-(difference_type __i) const { const_iterator __tmp = *this; return __tmp -= __i; } const_reference operator[](difference_type __i) const { return *(*this + __i); } }; inline _Bit_const_iterator operator+(ptrdiff_t __n, const _Bit_const_iterator& __x) { return __x + __n; } inline void __fill_bvector(_Bit_type * __v, unsigned int __first, unsigned int __last, bool __x) { const _Bit_type __fmask = ~0ul << __first; const _Bit_type __lmask = ~0ul >> (_S_word_bit - __last); const _Bit_type __mask = __fmask & __lmask; if (__x) *__v |= __mask; else *__v &= ~__mask; } inline void fill(_Bit_iterator __first, _Bit_iterator __last, const bool& __x) { if (__first._M_p != __last._M_p) { _Bit_type* __first_p = __first._M_p; if (__first._M_offset != 0) __fill_bvector(__first_p++, __first._M_offset, _S_word_bit, __x); __builtin_memset(__first_p, __x ? ~0 : 0, (__last._M_p - __first_p) * sizeof(_Bit_type)); if (__last._M_offset != 0) __fill_bvector(__last._M_p, 0, __last._M_offset, __x); } else if (__first._M_offset != __last._M_offset) __fill_bvector(__first._M_p, __first._M_offset, __last._M_offset, __x); } template struct _Bvector_base { typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Bit_type>::other _Bit_alloc_type; typedef typename __gnu_cxx::__alloc_traits<_Bit_alloc_type> _Bit_alloc_traits; typedef typename _Bit_alloc_traits::pointer _Bit_pointer; struct _Bvector_impl_data { _Bit_iterator _M_start; _Bit_iterator _M_finish; _Bit_pointer _M_end_of_storage; _Bvector_impl_data() _GLIBCXX_NOEXCEPT : _M_start(), _M_finish(), _M_end_of_storage() { } #if __cplusplus >= 201103L _Bvector_impl_data(_Bvector_impl_data&& __x) noexcept : _M_start(__x._M_start), _M_finish(__x._M_finish) , _M_end_of_storage(__x._M_end_of_storage) { __x._M_reset(); } void _M_move_data(_Bvector_impl_data&& __x) noexcept { this->_M_start = __x._M_start; this->_M_finish = __x._M_finish; this->_M_end_of_storage = __x._M_end_of_storage; __x._M_reset(); } #endif void _M_reset() _GLIBCXX_NOEXCEPT { _M_start = _M_finish = _Bit_iterator(); _M_end_of_storage = _Bit_pointer(); } }; struct _Bvector_impl : public _Bit_alloc_type, public _Bvector_impl_data { public: _Bvector_impl() _GLIBCXX_NOEXCEPT_IF( is_nothrow_default_constructible<_Bit_alloc_type>::value) : _Bit_alloc_type() { } _Bvector_impl(const _Bit_alloc_type& __a) _GLIBCXX_NOEXCEPT : _Bit_alloc_type(__a) { } #if __cplusplus >= 201103L _Bvector_impl(_Bvector_impl&&) = default; #endif _Bit_type* _M_end_addr() const _GLIBCXX_NOEXCEPT { if (this->_M_end_of_storage) return std::__addressof(this->_M_end_of_storage[-1]) + 1; return 0; } }; public: typedef _Alloc allocator_type; _Bit_alloc_type& _M_get_Bit_allocator() _GLIBCXX_NOEXCEPT { return this->_M_impl; } const _Bit_alloc_type& _M_get_Bit_allocator() const _GLIBCXX_NOEXCEPT { return this->_M_impl; } allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_get_Bit_allocator()); } #if __cplusplus >= 201103L _Bvector_base() = default; #else _Bvector_base() { } #endif _Bvector_base(const allocator_type& __a) : _M_impl(__a) { } #if __cplusplus >= 201103L _Bvector_base(_Bvector_base&&) = default; #endif ~_Bvector_base() { this->_M_deallocate(); } protected: _Bvector_impl _M_impl; _Bit_pointer _M_allocate(size_t __n) { return _Bit_alloc_traits::allocate(_M_impl, _S_nword(__n)); } void _M_deallocate() { if (_M_impl._M_start._M_p) { const size_t __n = _M_impl._M_end_addr() - _M_impl._M_start._M_p; _Bit_alloc_traits::deallocate(_M_impl, _M_impl._M_end_of_storage - __n, __n); _M_impl._M_reset(); } } #if __cplusplus >= 201103L void _M_move_data(_Bvector_base&& __x) noexcept { _M_impl._M_move_data(std::move(__x._M_impl)); } #endif static size_t _S_nword(size_t __n) { return (__n + int(_S_word_bit) - 1) / int(_S_word_bit); } }; _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std // Declare a partial specialization of vector. #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER /** * @brief A specialization of vector for booleans which offers fixed time * access to individual elements in any order. * * @ingroup sequences * * @tparam _Alloc Allocator type. * * Note that vector does not actually meet the requirements for being * a container. This is because the reference and pointer types are not * really references and pointers to bool. See DR96 for details. @see * vector for function documentation. * * In some terminology a %vector can be described as a dynamic * C-style array, it offers fast and efficient access to individual * elements in any order and saves the user from worrying about * memory and size allocation. Subscripting ( @c [] ) access is * also provided as with C-style arrays. */ template class vector : protected _Bvector_base<_Alloc> { typedef _Bvector_base<_Alloc> _Base; typedef typename _Base::_Bit_pointer _Bit_pointer; typedef typename _Base::_Bit_alloc_traits _Bit_alloc_traits; #if __cplusplus >= 201103L friend struct std::hash; #endif public: typedef bool value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Bit_reference reference; typedef bool const_reference; typedef _Bit_reference* pointer; typedef const bool* const_pointer; typedef _Bit_iterator iterator; typedef _Bit_const_iterator const_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; typedef _Alloc allocator_type; allocator_type get_allocator() const { return _Base::get_allocator(); } protected: using _Base::_M_allocate; using _Base::_M_deallocate; using _Base::_S_nword; using _Base::_M_get_Bit_allocator; public: #if __cplusplus >= 201103L vector() = default; #else vector() { } #endif explicit vector(const allocator_type& __a) : _Base(__a) { } #if __cplusplus >= 201103L explicit vector(size_type __n, const allocator_type& __a = allocator_type()) : vector(__n, false, __a) { } vector(size_type __n, const bool& __value, const allocator_type& __a = allocator_type()) #else explicit vector(size_type __n, const bool& __value = bool(), const allocator_type& __a = allocator_type()) #endif : _Base(__a) { _M_initialize(__n); _M_initialize_value(__value); } vector(const vector& __x) : _Base(_Bit_alloc_traits::_S_select_on_copy(__x._M_get_Bit_allocator())) { _M_initialize(__x.size()); _M_copy_aligned(__x.begin(), __x.end(), this->_M_impl._M_start); } #if __cplusplus >= 201103L vector(vector&&) = default; vector(vector&& __x, const allocator_type& __a) noexcept(_Bit_alloc_traits::_S_always_equal()) : _Base(__a) { if (__x.get_allocator() == __a) this->_M_move_data(std::move(__x)); else { _M_initialize(__x.size()); _M_copy_aligned(__x.begin(), __x.end(), begin()); __x.clear(); } } vector(const vector& __x, const allocator_type& __a) : _Base(__a) { _M_initialize(__x.size()); _M_copy_aligned(__x.begin(), __x.end(), this->_M_impl._M_start); } vector(initializer_list __l, const allocator_type& __a = allocator_type()) : _Base(__a) { _M_initialize_range(__l.begin(), __l.end(), random_access_iterator_tag()); } #endif #if __cplusplus >= 201103L template> vector(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(__a) { _M_initialize_dispatch(__first, __last, __false_type()); } #else template vector(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(__a) { typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_initialize_dispatch(__first, __last, _Integral()); } #endif ~vector() _GLIBCXX_NOEXCEPT { } vector& operator=(const vector& __x) { if (&__x == this) return *this; #if __cplusplus >= 201103L if (_Bit_alloc_traits::_S_propagate_on_copy_assign()) { if (this->_M_get_Bit_allocator() != __x._M_get_Bit_allocator()) { this->_M_deallocate(); std::__alloc_on_copy(_M_get_Bit_allocator(), __x._M_get_Bit_allocator()); _M_initialize(__x.size()); } else std::__alloc_on_copy(_M_get_Bit_allocator(), __x._M_get_Bit_allocator()); } #endif if (__x.size() > capacity()) { this->_M_deallocate(); _M_initialize(__x.size()); } this->_M_impl._M_finish = _M_copy_aligned(__x.begin(), __x.end(), begin()); return *this; } #if __cplusplus >= 201103L vector& operator=(vector&& __x) noexcept(_Bit_alloc_traits::_S_nothrow_move()) { if (_Bit_alloc_traits::_S_propagate_on_move_assign() || this->_M_get_Bit_allocator() == __x._M_get_Bit_allocator()) { this->_M_deallocate(); this->_M_move_data(std::move(__x)); std::__alloc_on_move(_M_get_Bit_allocator(), __x._M_get_Bit_allocator()); } else { if (__x.size() > capacity()) { this->_M_deallocate(); _M_initialize(__x.size()); } this->_M_impl._M_finish = _M_copy_aligned(__x.begin(), __x.end(), begin()); __x.clear(); } return *this; } vector& operator=(initializer_list __l) { this->assign (__l.begin(), __l.end()); return *this; } #endif // assign(), a generalized assignment member function. Two // versions: one that takes a count, and one that takes a range. // The range version is a member template, so we dispatch on whether // or not the type is an integer. void assign(size_type __n, const bool& __x) { _M_fill_assign(__n, __x); } #if __cplusplus >= 201103L template> void assign(_InputIterator __first, _InputIterator __last) { _M_assign_aux(__first, __last, std::__iterator_category(__first)); } #else template void assign(_InputIterator __first, _InputIterator __last) { typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_assign_dispatch(__first, __last, _Integral()); } #endif #if __cplusplus >= 201103L void assign(initializer_list __l) { _M_assign_aux(__l.begin(), __l.end(), random_access_iterator_tag()); } #endif iterator begin() _GLIBCXX_NOEXCEPT { return this->_M_impl._M_start; } const_iterator begin() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_start; } iterator end() _GLIBCXX_NOEXCEPT { return this->_M_impl._M_finish; } const_iterator end() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_finish; } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return this->_M_impl._M_start; } const_iterator cend() const noexcept { return this->_M_impl._M_finish; } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif size_type size() const _GLIBCXX_NOEXCEPT { return size_type(end() - begin()); } size_type max_size() const _GLIBCXX_NOEXCEPT { const size_type __isize = __gnu_cxx::__numeric_traits::__max - int(_S_word_bit) + 1; const size_type __asize = _Bit_alloc_traits::max_size(_M_get_Bit_allocator()); return (__asize <= __isize / int(_S_word_bit) ? __asize * int(_S_word_bit) : __isize); } size_type capacity() const _GLIBCXX_NOEXCEPT { return size_type(const_iterator(this->_M_impl._M_end_addr(), 0) - begin()); } bool empty() const _GLIBCXX_NOEXCEPT { return begin() == end(); } reference operator[](size_type __n) { return *iterator(this->_M_impl._M_start._M_p + __n / int(_S_word_bit), __n % int(_S_word_bit)); } const_reference operator[](size_type __n) const { return *const_iterator(this->_M_impl._M_start._M_p + __n / int(_S_word_bit), __n % int(_S_word_bit)); } protected: void _M_range_check(size_type __n) const { if (__n >= this->size()) __throw_out_of_range_fmt(__N("vector::_M_range_check: __n " "(which is %zu) >= this->size() " "(which is %zu)"), __n, this->size()); } public: reference at(size_type __n) { _M_range_check(__n); return (*this)[__n]; } const_reference at(size_type __n) const { _M_range_check(__n); return (*this)[__n]; } void reserve(size_type __n) { if (__n > max_size()) __throw_length_error(__N("vector::reserve")); if (capacity() < __n) _M_reallocate(__n); } reference front() { return *begin(); } const_reference front() const { return *begin(); } reference back() { return *(end() - 1); } const_reference back() const { return *(end() - 1); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 464. Suggestion for new member functions in standard containers. // N.B. DR 464 says nothing about vector but we need something // here due to the way we are implementing DR 464 in the debug-mode // vector class. void data() _GLIBCXX_NOEXCEPT { } void push_back(bool __x) { if (this->_M_impl._M_finish._M_p != this->_M_impl._M_end_addr()) *this->_M_impl._M_finish++ = __x; else _M_insert_aux(end(), __x); } void swap(vector& __x) _GLIBCXX_NOEXCEPT { std::swap(this->_M_impl._M_start, __x._M_impl._M_start); std::swap(this->_M_impl._M_finish, __x._M_impl._M_finish); std::swap(this->_M_impl._M_end_of_storage, __x._M_impl._M_end_of_storage); _Bit_alloc_traits::_S_on_swap(_M_get_Bit_allocator(), __x._M_get_Bit_allocator()); } // [23.2.5]/1, third-to-last entry in synopsis listing static void swap(reference __x, reference __y) _GLIBCXX_NOEXCEPT { bool __tmp = __x; __x = __y; __y = __tmp; } iterator #if __cplusplus >= 201103L insert(const_iterator __position, const bool& __x = bool()) #else insert(iterator __position, const bool& __x = bool()) #endif { const difference_type __n = __position - begin(); if (this->_M_impl._M_finish._M_p != this->_M_impl._M_end_addr() && __position == end()) *this->_M_impl._M_finish++ = __x; else _M_insert_aux(__position._M_const_cast(), __x); return begin() + __n; } #if __cplusplus >= 201103L template> iterator insert(const_iterator __position, _InputIterator __first, _InputIterator __last) { difference_type __offset = __position - cbegin(); _M_insert_dispatch(__position._M_const_cast(), __first, __last, __false_type()); return begin() + __offset; } #else template void insert(iterator __position, _InputIterator __first, _InputIterator __last) { typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_insert_dispatch(__position, __first, __last, _Integral()); } #endif #if __cplusplus >= 201103L iterator insert(const_iterator __position, size_type __n, const bool& __x) { difference_type __offset = __position - cbegin(); _M_fill_insert(__position._M_const_cast(), __n, __x); return begin() + __offset; } #else void insert(iterator __position, size_type __n, const bool& __x) { _M_fill_insert(__position, __n, __x); } #endif #if __cplusplus >= 201103L iterator insert(const_iterator __p, initializer_list __l) { return this->insert(__p, __l.begin(), __l.end()); } #endif void pop_back() { --this->_M_impl._M_finish; } iterator #if __cplusplus >= 201103L erase(const_iterator __position) #else erase(iterator __position) #endif { return _M_erase(__position._M_const_cast()); } iterator #if __cplusplus >= 201103L erase(const_iterator __first, const_iterator __last) #else erase(iterator __first, iterator __last) #endif { return _M_erase(__first._M_const_cast(), __last._M_const_cast()); } void resize(size_type __new_size, bool __x = bool()) { if (__new_size < size()) _M_erase_at_end(begin() + difference_type(__new_size)); else insert(end(), __new_size - size(), __x); } #if __cplusplus >= 201103L void shrink_to_fit() { _M_shrink_to_fit(); } #endif void flip() _GLIBCXX_NOEXCEPT { _Bit_type * const __end = this->_M_impl._M_end_addr(); for (_Bit_type * __p = this->_M_impl._M_start._M_p; __p != __end; ++__p) *__p = ~*__p; } void clear() _GLIBCXX_NOEXCEPT { _M_erase_at_end(begin()); } #if __cplusplus >= 201103L template #if __cplusplus > 201402L reference #else void #endif emplace_back(_Args&&... __args) { push_back(bool(__args...)); #if __cplusplus > 201402L return back(); #endif } template iterator emplace(const_iterator __pos, _Args&&... __args) { return insert(__pos, bool(__args...)); } #endif protected: // Precondition: __first._M_offset == 0 && __result._M_offset == 0. iterator _M_copy_aligned(const_iterator __first, const_iterator __last, iterator __result) { _Bit_type* __q = std::copy(__first._M_p, __last._M_p, __result._M_p); return std::copy(const_iterator(__last._M_p, 0), __last, iterator(__q, 0)); } void _M_initialize(size_type __n) { if (__n) { _Bit_pointer __q = this->_M_allocate(__n); this->_M_impl._M_end_of_storage = __q + _S_nword(__n); this->_M_impl._M_start = iterator(std::__addressof(*__q), 0); } else { this->_M_impl._M_end_of_storage = _Bit_pointer(); this->_M_impl._M_start = iterator(0, 0); } this->_M_impl._M_finish = this->_M_impl._M_start + difference_type(__n); } void _M_initialize_value(bool __x) { if (_Bit_type* __p = this->_M_impl._M_start._M_p) __builtin_memset(__p, __x ? ~0 : 0, (this->_M_impl._M_end_addr() - __p) * sizeof(_Bit_type)); } void _M_reallocate(size_type __n); #if __cplusplus >= 201103L bool _M_shrink_to_fit(); #endif // Check whether it's an integral type. If so, it's not an iterator. // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_initialize_dispatch(_Integer __n, _Integer __x, __true_type) { _M_initialize(static_cast(__n)); _M_initialize_value(__x); } template void _M_initialize_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { _M_initialize_range(__first, __last, std::__iterator_category(__first)); } template void _M_initialize_range(_InputIterator __first, _InputIterator __last, std::input_iterator_tag) { for (; __first != __last; ++__first) push_back(*__first); } template void _M_initialize_range(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { const size_type __n = std::distance(__first, __last); _M_initialize(__n); std::copy(__first, __last, this->_M_impl._M_start); } #if __cplusplus < 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_assign_dispatch(_Integer __n, _Integer __val, __true_type) { _M_fill_assign(__n, __val); } template void _M_assign_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { _M_assign_aux(__first, __last, std::__iterator_category(__first)); } #endif void _M_fill_assign(size_t __n, bool __x) { if (__n > size()) { _M_initialize_value(__x); insert(end(), __n - size(), __x); } else { _M_erase_at_end(begin() + __n); _M_initialize_value(__x); } } template void _M_assign_aux(_InputIterator __first, _InputIterator __last, std::input_iterator_tag) { iterator __cur = begin(); for (; __first != __last && __cur != end(); ++__cur, ++__first) *__cur = *__first; if (__first == __last) _M_erase_at_end(__cur); else insert(end(), __first, __last); } template void _M_assign_aux(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { const size_type __len = std::distance(__first, __last); if (__len < size()) _M_erase_at_end(std::copy(__first, __last, begin())); else { _ForwardIterator __mid = __first; std::advance(__mid, size()); std::copy(__first, __mid, begin()); insert(end(), __mid, __last); } } // Check whether it's an integral type. If so, it's not an iterator. // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_insert_dispatch(iterator __pos, _Integer __n, _Integer __x, __true_type) { _M_fill_insert(__pos, __n, __x); } template void _M_insert_dispatch(iterator __pos, _InputIterator __first, _InputIterator __last, __false_type) { _M_insert_range(__pos, __first, __last, std::__iterator_category(__first)); } void _M_fill_insert(iterator __position, size_type __n, bool __x); template void _M_insert_range(iterator __pos, _InputIterator __first, _InputIterator __last, std::input_iterator_tag) { for (; __first != __last; ++__first) { __pos = insert(__pos, *__first); ++__pos; } } template void _M_insert_range(iterator __position, _ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag); void _M_insert_aux(iterator __position, bool __x); size_type _M_check_len(size_type __n, const char* __s) const { if (max_size() - size() < __n) __throw_length_error(__N(__s)); const size_type __len = size() + std::max(size(), __n); return (__len < size() || __len > max_size()) ? max_size() : __len; } void _M_erase_at_end(iterator __pos) { this->_M_impl._M_finish = __pos; } iterator _M_erase(iterator __pos); iterator _M_erase(iterator __first, iterator __last); }; _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #if __cplusplus >= 201103L namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // DR 1182. /// std::hash specialization for vector. template struct hash<_GLIBCXX_STD_C::vector> : public __hash_base> { size_t operator()(const _GLIBCXX_STD_C::vector&) const noexcept; }; _GLIBCXX_END_NAMESPACE_VERSION }// namespace std #endif // C++11 #endif PK!8/bits/stl_construct.hnu[// nonstandard construct and destroy functions -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_construct.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _STL_CONSTRUCT_H #define _STL_CONSTRUCT_H 1 #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * Constructs an object in existing memory by invoking an allocated * object's constructor with an initializer. */ #if __cplusplus >= 201103L template inline void _Construct(_T1* __p, _Args&&... __args) { ::new(static_cast(__p)) _T1(std::forward<_Args>(__args)...); } #else template inline void _Construct(_T1* __p, const _T2& __value) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 402. wrong new expression in [some_]allocator::construct ::new(static_cast(__p)) _T1(__value); } #endif template inline void _Construct_novalue(_T1* __p) { ::new(static_cast(__p)) _T1; } /** * Destroy the object pointed to by a pointer type. */ template inline void _Destroy(_Tp* __pointer) { __pointer->~_Tp(); } template struct _Destroy_aux { template static void __destroy(_ForwardIterator __first, _ForwardIterator __last) { for (; __first != __last; ++__first) std::_Destroy(std::__addressof(*__first)); } }; template<> struct _Destroy_aux { template static void __destroy(_ForwardIterator, _ForwardIterator) { } }; /** * Destroy a range of objects. If the value_type of the object has * a trivial destructor, the compiler should optimize all of this * away, otherwise the objects' destructors must be invoked. */ template inline void _Destroy(_ForwardIterator __first, _ForwardIterator __last) { typedef typename iterator_traits<_ForwardIterator>::value_type _Value_type; #if __cplusplus >= 201103L // A deleted destructor is trivial, this ensures we reject such types: static_assert(is_destructible<_Value_type>::value, "value type is destructible"); #endif std::_Destroy_aux<__has_trivial_destructor(_Value_type)>:: __destroy(__first, __last); } template struct _Destroy_n_aux { template static _ForwardIterator __destroy_n(_ForwardIterator __first, _Size __count) { for (; __count > 0; (void)++__first, --__count) std::_Destroy(std::__addressof(*__first)); return __first; } }; template<> struct _Destroy_n_aux { template static _ForwardIterator __destroy_n(_ForwardIterator __first, _Size __count) { std::advance(__first, __count); return __first; } }; /** * Destroy a range of objects. If the value_type of the object has * a trivial destructor, the compiler should optimize all of this * away, otherwise the objects' destructors must be invoked. */ template inline _ForwardIterator _Destroy_n(_ForwardIterator __first, _Size __count) { typedef typename iterator_traits<_ForwardIterator>::value_type _Value_type; #if __cplusplus >= 201103L // A deleted destructor is trivial, this ensures we reject such types: static_assert(is_destructible<_Value_type>::value, "value type is destructible"); #endif return std::_Destroy_n_aux<__has_trivial_destructor(_Value_type)>:: __destroy_n(__first, __count); } /** * Destroy a range of objects using the supplied allocator. For * nondefault allocators we do not optimize away invocation of * destroy() even if _Tp has a trivial destructor. */ template void _Destroy(_ForwardIterator __first, _ForwardIterator __last, _Allocator& __alloc) { typedef __gnu_cxx::__alloc_traits<_Allocator> __traits; for (; __first != __last; ++__first) __traits::destroy(__alloc, std::__addressof(*__first)); } template inline void _Destroy(_ForwardIterator __first, _ForwardIterator __last, allocator<_Tp>&) { _Destroy(__first, __last); } #if __cplusplus > 201402L template inline void destroy_at(_Tp* __location) { std::_Destroy(__location); } template inline void destroy(_ForwardIterator __first, _ForwardIterator __last) { std::_Destroy(__first, __last); } template inline _ForwardIterator destroy_n(_ForwardIterator __first, _Size __count) { return std::_Destroy_n(__first, __count); } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_CONSTRUCT_H */ PK!A228/bits/stl_deque.hnu[// Deque implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_deque.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{deque} */ #ifndef _STL_DEQUE_H #define _STL_DEQUE_H 1 #include #include #include #if __cplusplus >= 201103L #include #endif #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER /** * @brief This function controls the size of memory nodes. * @param __size The size of an element. * @return The number (not byte size) of elements per node. * * This function started off as a compiler kludge from SGI, but * seems to be a useful wrapper around a repeated constant * expression. The @b 512 is tunable (and no other code needs to * change), but no investigation has been done since inheriting the * SGI code. Touch _GLIBCXX_DEQUE_BUF_SIZE only if you know what * you are doing, however: changing it breaks the binary * compatibility!! */ #ifndef _GLIBCXX_DEQUE_BUF_SIZE #define _GLIBCXX_DEQUE_BUF_SIZE 512 #endif _GLIBCXX_CONSTEXPR inline size_t __deque_buf_size(size_t __size) { return (__size < _GLIBCXX_DEQUE_BUF_SIZE ? size_t(_GLIBCXX_DEQUE_BUF_SIZE / __size) : size_t(1)); } /** * @brief A deque::iterator. * * Quite a bit of intelligence here. Much of the functionality of * deque is actually passed off to this class. A deque holds two * of these internally, marking its valid range. Access to * elements is done as offsets of either of those two, relying on * operator overloading in this class. * * All the functions are op overloads except for _M_set_node. */ template struct _Deque_iterator { #if __cplusplus < 201103L typedef _Deque_iterator<_Tp, _Tp&, _Tp*> iterator; typedef _Deque_iterator<_Tp, const _Tp&, const _Tp*> const_iterator; typedef _Tp* _Elt_pointer; typedef _Tp** _Map_pointer; #else private: template using __ptr_to = typename pointer_traits<_Ptr>::template rebind<_Up>; template using __iter = _Deque_iterator<_Tp, _CvTp&, __ptr_to<_CvTp>>; public: typedef __iter<_Tp> iterator; typedef __iter const_iterator; typedef __ptr_to<_Tp> _Elt_pointer; typedef __ptr_to<_Elt_pointer> _Map_pointer; #endif static size_t _S_buffer_size() _GLIBCXX_NOEXCEPT { return __deque_buf_size(sizeof(_Tp)); } typedef std::random_access_iterator_tag iterator_category; typedef _Tp value_type; typedef _Ptr pointer; typedef _Ref reference; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Deque_iterator _Self; _Elt_pointer _M_cur; _Elt_pointer _M_first; _Elt_pointer _M_last; _Map_pointer _M_node; _Deque_iterator(_Elt_pointer __x, _Map_pointer __y) _GLIBCXX_NOEXCEPT : _M_cur(__x), _M_first(*__y), _M_last(*__y + _S_buffer_size()), _M_node(__y) { } _Deque_iterator() _GLIBCXX_NOEXCEPT : _M_cur(), _M_first(), _M_last(), _M_node() { } _Deque_iterator(const iterator& __x) _GLIBCXX_NOEXCEPT : _M_cur(__x._M_cur), _M_first(__x._M_first), _M_last(__x._M_last), _M_node(__x._M_node) { } iterator _M_const_cast() const _GLIBCXX_NOEXCEPT { return iterator(_M_cur, _M_node); } reference operator*() const _GLIBCXX_NOEXCEPT { return *_M_cur; } pointer operator->() const _GLIBCXX_NOEXCEPT { return _M_cur; } _Self& operator++() _GLIBCXX_NOEXCEPT { ++_M_cur; if (_M_cur == _M_last) { _M_set_node(_M_node + 1); _M_cur = _M_first; } return *this; } _Self operator++(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; ++*this; return __tmp; } _Self& operator--() _GLIBCXX_NOEXCEPT { if (_M_cur == _M_first) { _M_set_node(_M_node - 1); _M_cur = _M_last; } --_M_cur; return *this; } _Self operator--(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; --*this; return __tmp; } _Self& operator+=(difference_type __n) _GLIBCXX_NOEXCEPT { const difference_type __offset = __n + (_M_cur - _M_first); if (__offset >= 0 && __offset < difference_type(_S_buffer_size())) _M_cur += __n; else { const difference_type __node_offset = __offset > 0 ? __offset / difference_type(_S_buffer_size()) : -difference_type((-__offset - 1) / _S_buffer_size()) - 1; _M_set_node(_M_node + __node_offset); _M_cur = _M_first + (__offset - __node_offset * difference_type(_S_buffer_size())); } return *this; } _Self operator+(difference_type __n) const _GLIBCXX_NOEXCEPT { _Self __tmp = *this; return __tmp += __n; } _Self& operator-=(difference_type __n) _GLIBCXX_NOEXCEPT { return *this += -__n; } _Self operator-(difference_type __n) const _GLIBCXX_NOEXCEPT { _Self __tmp = *this; return __tmp -= __n; } reference operator[](difference_type __n) const _GLIBCXX_NOEXCEPT { return *(*this + __n); } /** * Prepares to traverse new_node. Sets everything except * _M_cur, which should therefore be set by the caller * immediately afterwards, based on _M_first and _M_last. */ void _M_set_node(_Map_pointer __new_node) _GLIBCXX_NOEXCEPT { _M_node = __new_node; _M_first = *__new_node; _M_last = _M_first + difference_type(_S_buffer_size()); } }; // Note: we also provide overloads whose operands are of the same type in // order to avoid ambiguous overload resolution when std::rel_ops operators // are in scope (for additional details, see libstdc++/3628) template inline bool operator==(const _Deque_iterator<_Tp, _Ref, _Ptr>& __x, const _Deque_iterator<_Tp, _Ref, _Ptr>& __y) _GLIBCXX_NOEXCEPT { return __x._M_cur == __y._M_cur; } template inline bool operator==(const _Deque_iterator<_Tp, _RefL, _PtrL>& __x, const _Deque_iterator<_Tp, _RefR, _PtrR>& __y) _GLIBCXX_NOEXCEPT { return __x._M_cur == __y._M_cur; } template inline bool operator!=(const _Deque_iterator<_Tp, _Ref, _Ptr>& __x, const _Deque_iterator<_Tp, _Ref, _Ptr>& __y) _GLIBCXX_NOEXCEPT { return !(__x == __y); } template inline bool operator!=(const _Deque_iterator<_Tp, _RefL, _PtrL>& __x, const _Deque_iterator<_Tp, _RefR, _PtrR>& __y) _GLIBCXX_NOEXCEPT { return !(__x == __y); } template inline bool operator<(const _Deque_iterator<_Tp, _Ref, _Ptr>& __x, const _Deque_iterator<_Tp, _Ref, _Ptr>& __y) _GLIBCXX_NOEXCEPT { return (__x._M_node == __y._M_node) ? (__x._M_cur < __y._M_cur) : (__x._M_node < __y._M_node); } template inline bool operator<(const _Deque_iterator<_Tp, _RefL, _PtrL>& __x, const _Deque_iterator<_Tp, _RefR, _PtrR>& __y) _GLIBCXX_NOEXCEPT { return (__x._M_node == __y._M_node) ? (__x._M_cur < __y._M_cur) : (__x._M_node < __y._M_node); } template inline bool operator>(const _Deque_iterator<_Tp, _Ref, _Ptr>& __x, const _Deque_iterator<_Tp, _Ref, _Ptr>& __y) _GLIBCXX_NOEXCEPT { return __y < __x; } template inline bool operator>(const _Deque_iterator<_Tp, _RefL, _PtrL>& __x, const _Deque_iterator<_Tp, _RefR, _PtrR>& __y) _GLIBCXX_NOEXCEPT { return __y < __x; } template inline bool operator<=(const _Deque_iterator<_Tp, _Ref, _Ptr>& __x, const _Deque_iterator<_Tp, _Ref, _Ptr>& __y) _GLIBCXX_NOEXCEPT { return !(__y < __x); } template inline bool operator<=(const _Deque_iterator<_Tp, _RefL, _PtrL>& __x, const _Deque_iterator<_Tp, _RefR, _PtrR>& __y) _GLIBCXX_NOEXCEPT { return !(__y < __x); } template inline bool operator>=(const _Deque_iterator<_Tp, _Ref, _Ptr>& __x, const _Deque_iterator<_Tp, _Ref, _Ptr>& __y) _GLIBCXX_NOEXCEPT { return !(__x < __y); } template inline bool operator>=(const _Deque_iterator<_Tp, _RefL, _PtrL>& __x, const _Deque_iterator<_Tp, _RefR, _PtrR>& __y) _GLIBCXX_NOEXCEPT { return !(__x < __y); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // According to the resolution of DR179 not only the various comparison // operators but also operator- must accept mixed iterator/const_iterator // parameters. template inline typename _Deque_iterator<_Tp, _Ref, _Ptr>::difference_type operator-(const _Deque_iterator<_Tp, _Ref, _Ptr>& __x, const _Deque_iterator<_Tp, _Ref, _Ptr>& __y) _GLIBCXX_NOEXCEPT { return typename _Deque_iterator<_Tp, _Ref, _Ptr>::difference_type (_Deque_iterator<_Tp, _Ref, _Ptr>::_S_buffer_size()) * (__x._M_node - __y._M_node - 1) + (__x._M_cur - __x._M_first) + (__y._M_last - __y._M_cur); } template inline typename _Deque_iterator<_Tp, _RefL, _PtrL>::difference_type operator-(const _Deque_iterator<_Tp, _RefL, _PtrL>& __x, const _Deque_iterator<_Tp, _RefR, _PtrR>& __y) _GLIBCXX_NOEXCEPT { return typename _Deque_iterator<_Tp, _RefL, _PtrL>::difference_type (_Deque_iterator<_Tp, _RefL, _PtrL>::_S_buffer_size()) * (__x._M_node - __y._M_node - 1) + (__x._M_cur - __x._M_first) + (__y._M_last - __y._M_cur); } template inline _Deque_iterator<_Tp, _Ref, _Ptr> operator+(ptrdiff_t __n, const _Deque_iterator<_Tp, _Ref, _Ptr>& __x) _GLIBCXX_NOEXCEPT { return __x + __n; } template void fill(const _Deque_iterator<_Tp, _Tp&, _Tp*>&, const _Deque_iterator<_Tp, _Tp&, _Tp*>&, const _Tp&); template _Deque_iterator<_Tp, _Tp&, _Tp*> copy(_Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, _Tp&, _Tp*>); template inline _Deque_iterator<_Tp, _Tp&, _Tp*> copy(_Deque_iterator<_Tp, _Tp&, _Tp*> __first, _Deque_iterator<_Tp, _Tp&, _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { return std::copy(_Deque_iterator<_Tp, const _Tp&, const _Tp*>(__first), _Deque_iterator<_Tp, const _Tp&, const _Tp*>(__last), __result); } template _Deque_iterator<_Tp, _Tp&, _Tp*> copy_backward(_Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, _Tp&, _Tp*>); template inline _Deque_iterator<_Tp, _Tp&, _Tp*> copy_backward(_Deque_iterator<_Tp, _Tp&, _Tp*> __first, _Deque_iterator<_Tp, _Tp&, _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { return std::copy_backward(_Deque_iterator<_Tp, const _Tp&, const _Tp*>(__first), _Deque_iterator<_Tp, const _Tp&, const _Tp*>(__last), __result); } #if __cplusplus >= 201103L template _Deque_iterator<_Tp, _Tp&, _Tp*> move(_Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, _Tp&, _Tp*>); template inline _Deque_iterator<_Tp, _Tp&, _Tp*> move(_Deque_iterator<_Tp, _Tp&, _Tp*> __first, _Deque_iterator<_Tp, _Tp&, _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { return std::move(_Deque_iterator<_Tp, const _Tp&, const _Tp*>(__first), _Deque_iterator<_Tp, const _Tp&, const _Tp*>(__last), __result); } template _Deque_iterator<_Tp, _Tp&, _Tp*> move_backward(_Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, _Tp&, _Tp*>); template inline _Deque_iterator<_Tp, _Tp&, _Tp*> move_backward(_Deque_iterator<_Tp, _Tp&, _Tp*> __first, _Deque_iterator<_Tp, _Tp&, _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { return std::move_backward(_Deque_iterator<_Tp, const _Tp&, const _Tp*>(__first), _Deque_iterator<_Tp, const _Tp&, const _Tp*>(__last), __result); } #endif /** * Deque base class. This class provides the unified face for %deque's * allocation. This class's constructor and destructor allocate and * deallocate (but do not initialize) storage. This makes %exception * safety easier. * * Nothing in this class ever constructs or destroys an actual Tp element. * (Deque handles that itself.) Only/All memory management is performed * here. */ template class _Deque_base { protected: typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Tp>::other _Tp_alloc_type; typedef __gnu_cxx::__alloc_traits<_Tp_alloc_type> _Alloc_traits; #if __cplusplus < 201103L typedef _Tp* _Ptr; typedef const _Tp* _Ptr_const; #else typedef typename _Alloc_traits::pointer _Ptr; typedef typename _Alloc_traits::const_pointer _Ptr_const; #endif typedef typename _Alloc_traits::template rebind<_Ptr>::other _Map_alloc_type; typedef __gnu_cxx::__alloc_traits<_Map_alloc_type> _Map_alloc_traits; public: typedef _Alloc allocator_type; typedef typename _Alloc_traits::size_type size_type; allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_get_Tp_allocator()); } typedef _Deque_iterator<_Tp, _Tp&, _Ptr> iterator; typedef _Deque_iterator<_Tp, const _Tp&, _Ptr_const> const_iterator; _Deque_base() : _M_impl() { _M_initialize_map(0); } _Deque_base(size_t __num_elements) : _M_impl() { _M_initialize_map(__num_elements); } _Deque_base(const allocator_type& __a, size_t __num_elements) : _M_impl(__a) { _M_initialize_map(__num_elements); } _Deque_base(const allocator_type& __a) : _M_impl(__a) { /* Caller must initialize map. */ } #if __cplusplus >= 201103L _Deque_base(_Deque_base&& __x, false_type) : _M_impl(__x._M_move_impl()) { } _Deque_base(_Deque_base&& __x, true_type) : _M_impl(std::move(__x._M_get_Tp_allocator())) { _M_initialize_map(0); if (__x._M_impl._M_map) this->_M_impl._M_swap_data(__x._M_impl); } _Deque_base(_Deque_base&& __x) : _Deque_base(std::move(__x), typename _Alloc_traits::is_always_equal{}) { } _Deque_base(_Deque_base&& __x, const allocator_type& __a, size_type __n) : _M_impl(__a) { if (__x.get_allocator() == __a) { if (__x._M_impl._M_map) { _M_initialize_map(0); this->_M_impl._M_swap_data(__x._M_impl); } } else { _M_initialize_map(__n); } } #endif ~_Deque_base() _GLIBCXX_NOEXCEPT; protected: typedef typename iterator::_Map_pointer _Map_pointer; //This struct encapsulates the implementation of the std::deque //standard container and at the same time makes use of the EBO //for empty allocators. struct _Deque_impl : public _Tp_alloc_type { _Map_pointer _M_map; size_t _M_map_size; iterator _M_start; iterator _M_finish; _Deque_impl() : _Tp_alloc_type(), _M_map(), _M_map_size(0), _M_start(), _M_finish() { } _Deque_impl(const _Tp_alloc_type& __a) _GLIBCXX_NOEXCEPT : _Tp_alloc_type(__a), _M_map(), _M_map_size(0), _M_start(), _M_finish() { } #if __cplusplus >= 201103L _Deque_impl(_Deque_impl&&) = default; _Deque_impl(_Tp_alloc_type&& __a) noexcept : _Tp_alloc_type(std::move(__a)), _M_map(), _M_map_size(0), _M_start(), _M_finish() { } #endif void _M_swap_data(_Deque_impl& __x) _GLIBCXX_NOEXCEPT { using std::swap; swap(this->_M_start, __x._M_start); swap(this->_M_finish, __x._M_finish); swap(this->_M_map, __x._M_map); swap(this->_M_map_size, __x._M_map_size); } }; _Tp_alloc_type& _M_get_Tp_allocator() _GLIBCXX_NOEXCEPT { return *static_cast<_Tp_alloc_type*>(&this->_M_impl); } const _Tp_alloc_type& _M_get_Tp_allocator() const _GLIBCXX_NOEXCEPT { return *static_cast(&this->_M_impl); } _Map_alloc_type _M_get_map_allocator() const _GLIBCXX_NOEXCEPT { return _Map_alloc_type(_M_get_Tp_allocator()); } _Ptr _M_allocate_node() { typedef __gnu_cxx::__alloc_traits<_Tp_alloc_type> _Traits; return _Traits::allocate(_M_impl, __deque_buf_size(sizeof(_Tp))); } void _M_deallocate_node(_Ptr __p) _GLIBCXX_NOEXCEPT { typedef __gnu_cxx::__alloc_traits<_Tp_alloc_type> _Traits; _Traits::deallocate(_M_impl, __p, __deque_buf_size(sizeof(_Tp))); } _Map_pointer _M_allocate_map(size_t __n) { _Map_alloc_type __map_alloc = _M_get_map_allocator(); return _Map_alloc_traits::allocate(__map_alloc, __n); } void _M_deallocate_map(_Map_pointer __p, size_t __n) _GLIBCXX_NOEXCEPT { _Map_alloc_type __map_alloc = _M_get_map_allocator(); _Map_alloc_traits::deallocate(__map_alloc, __p, __n); } protected: void _M_initialize_map(size_t); void _M_create_nodes(_Map_pointer __nstart, _Map_pointer __nfinish); void _M_destroy_nodes(_Map_pointer __nstart, _Map_pointer __nfinish) _GLIBCXX_NOEXCEPT; enum { _S_initial_map_size = 8 }; _Deque_impl _M_impl; #if __cplusplus >= 201103L private: _Deque_impl _M_move_impl() { if (!_M_impl._M_map) return std::move(_M_impl); // Create a copy of the current allocator. _Tp_alloc_type __alloc{_M_get_Tp_allocator()}; // Put that copy in a moved-from state. _Tp_alloc_type __sink __attribute((__unused__)) {std::move(__alloc)}; // Create an empty map that allocates using the moved-from allocator. _Deque_base __empty{__alloc}; __empty._M_initialize_map(0); // Now safe to modify current allocator and perform non-throwing swaps. _Deque_impl __ret{std::move(_M_get_Tp_allocator())}; _M_impl._M_swap_data(__ret); _M_impl._M_swap_data(__empty._M_impl); return __ret; } #endif }; template _Deque_base<_Tp, _Alloc>:: ~_Deque_base() _GLIBCXX_NOEXCEPT { if (this->_M_impl._M_map) { _M_destroy_nodes(this->_M_impl._M_start._M_node, this->_M_impl._M_finish._M_node + 1); _M_deallocate_map(this->_M_impl._M_map, this->_M_impl._M_map_size); } } /** * @brief Layout storage. * @param __num_elements The count of T's for which to allocate space * at first. * @return Nothing. * * The initial underlying memory layout is a bit complicated... */ template void _Deque_base<_Tp, _Alloc>:: _M_initialize_map(size_t __num_elements) { const size_t __num_nodes = (__num_elements/ __deque_buf_size(sizeof(_Tp)) + 1); this->_M_impl._M_map_size = std::max((size_t) _S_initial_map_size, size_t(__num_nodes + 2)); this->_M_impl._M_map = _M_allocate_map(this->_M_impl._M_map_size); // For "small" maps (needing less than _M_map_size nodes), allocation // starts in the middle elements and grows outwards. So nstart may be // the beginning of _M_map, but for small maps it may be as far in as // _M_map+3. _Map_pointer __nstart = (this->_M_impl._M_map + (this->_M_impl._M_map_size - __num_nodes) / 2); _Map_pointer __nfinish = __nstart + __num_nodes; __try { _M_create_nodes(__nstart, __nfinish); } __catch(...) { _M_deallocate_map(this->_M_impl._M_map, this->_M_impl._M_map_size); this->_M_impl._M_map = _Map_pointer(); this->_M_impl._M_map_size = 0; __throw_exception_again; } this->_M_impl._M_start._M_set_node(__nstart); this->_M_impl._M_finish._M_set_node(__nfinish - 1); this->_M_impl._M_start._M_cur = _M_impl._M_start._M_first; this->_M_impl._M_finish._M_cur = (this->_M_impl._M_finish._M_first + __num_elements % __deque_buf_size(sizeof(_Tp))); } template void _Deque_base<_Tp, _Alloc>:: _M_create_nodes(_Map_pointer __nstart, _Map_pointer __nfinish) { _Map_pointer __cur; __try { for (__cur = __nstart; __cur < __nfinish; ++__cur) *__cur = this->_M_allocate_node(); } __catch(...) { _M_destroy_nodes(__nstart, __cur); __throw_exception_again; } } template void _Deque_base<_Tp, _Alloc>:: _M_destroy_nodes(_Map_pointer __nstart, _Map_pointer __nfinish) _GLIBCXX_NOEXCEPT { for (_Map_pointer __n = __nstart; __n < __nfinish; ++__n) _M_deallocate_node(*__n); } /** * @brief A standard container using fixed-size memory allocation and * constant-time manipulation of elements at either end. * * @ingroup sequences * * @tparam _Tp Type of element. * @tparam _Alloc Allocator type, defaults to allocator<_Tp>. * * Meets the requirements of a container, a * reversible container, and a * sequence, including the * optional sequence requirements. * * In previous HP/SGI versions of deque, there was an extra template * parameter so users could control the node size. This extension turned * out to violate the C++ standard (it can be detected using template * template parameters), and it was removed. * * Here's how a deque manages memory. Each deque has 4 members: * * - Tp** _M_map * - size_t _M_map_size * - iterator _M_start, _M_finish * * map_size is at least 8. %map is an array of map_size * pointers-to-@a nodes. (The name %map has nothing to do with the * std::map class, and @b nodes should not be confused with * std::list's usage of @a node.) * * A @a node has no specific type name as such, but it is referred * to as @a node in this file. It is a simple array-of-Tp. If Tp * is very large, there will be one Tp element per node (i.e., an * @a array of one). For non-huge Tp's, node size is inversely * related to Tp size: the larger the Tp, the fewer Tp's will fit * in a node. The goal here is to keep the total size of a node * relatively small and constant over different Tp's, to improve * allocator efficiency. * * Not every pointer in the %map array will point to a node. If * the initial number of elements in the deque is small, the * /middle/ %map pointers will be valid, and the ones at the edges * will be unused. This same situation will arise as the %map * grows: available %map pointers, if any, will be on the ends. As * new nodes are created, only a subset of the %map's pointers need * to be copied @a outward. * * Class invariants: * - For any nonsingular iterator i: * - i.node points to a member of the %map array. (Yes, you read that * correctly: i.node does not actually point to a node.) The member of * the %map array is what actually points to the node. * - i.first == *(i.node) (This points to the node (first Tp element).) * - i.last == i.first + node_size * - i.cur is a pointer in the range [i.first, i.last). NOTE: * the implication of this is that i.cur is always a dereferenceable * pointer, even if i is a past-the-end iterator. * - Start and Finish are always nonsingular iterators. NOTE: this * means that an empty deque must have one node, a deque with > class deque : protected _Deque_base<_Tp, _Alloc> { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Alloc::value_type _Alloc_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) # endif __glibcxx_class_requires2(_Tp, _Alloc_value_type, _SameTypeConcept) #endif #if __cplusplus >= 201103L static_assert(is_same::type, _Tp>::value, "std::deque must have a non-const, non-volatile value_type"); # ifdef __STRICT_ANSI__ static_assert(is_same::value, "std::deque must have the same value_type as its allocator"); # endif #endif typedef _Deque_base<_Tp, _Alloc> _Base; typedef typename _Base::_Tp_alloc_type _Tp_alloc_type; typedef typename _Base::_Alloc_traits _Alloc_traits; typedef typename _Base::_Map_pointer _Map_pointer; public: typedef _Tp value_type; typedef typename _Alloc_traits::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef typename _Alloc_traits::reference reference; typedef typename _Alloc_traits::const_reference const_reference; typedef typename _Base::iterator iterator; typedef typename _Base::const_iterator const_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Alloc allocator_type; protected: static size_t _S_buffer_size() _GLIBCXX_NOEXCEPT { return __deque_buf_size(sizeof(_Tp)); } // Functions controlling memory layout, and nothing else. using _Base::_M_initialize_map; using _Base::_M_create_nodes; using _Base::_M_destroy_nodes; using _Base::_M_allocate_node; using _Base::_M_deallocate_node; using _Base::_M_allocate_map; using _Base::_M_deallocate_map; using _Base::_M_get_Tp_allocator; /** * A total of four data members accumulated down the hierarchy. * May be accessed via _M_impl.* */ using _Base::_M_impl; public: // [23.2.1.1] construct/copy/destroy // (assign() and get_allocator() are also listed in this section) /** * @brief Creates a %deque with no elements. */ deque() : _Base() { } /** * @brief Creates a %deque with no elements. * @param __a An allocator object. */ explicit deque(const allocator_type& __a) : _Base(__a, 0) { } #if __cplusplus >= 201103L /** * @brief Creates a %deque with default constructed elements. * @param __n The number of elements to initially create. * @param __a An allocator. * * This constructor fills the %deque with @a n default * constructed elements. */ explicit deque(size_type __n, const allocator_type& __a = allocator_type()) : _Base(__a, __n) { _M_default_initialize(); } /** * @brief Creates a %deque with copies of an exemplar element. * @param __n The number of elements to initially create. * @param __value An element to copy. * @param __a An allocator. * * This constructor fills the %deque with @a __n copies of @a __value. */ deque(size_type __n, const value_type& __value, const allocator_type& __a = allocator_type()) : _Base(__a, __n) { _M_fill_initialize(__value); } #else /** * @brief Creates a %deque with copies of an exemplar element. * @param __n The number of elements to initially create. * @param __value An element to copy. * @param __a An allocator. * * This constructor fills the %deque with @a __n copies of @a __value. */ explicit deque(size_type __n, const value_type& __value = value_type(), const allocator_type& __a = allocator_type()) : _Base(__a, __n) { _M_fill_initialize(__value); } #endif /** * @brief %Deque copy constructor. * @param __x A %deque of identical element and allocator types. * * The newly-created %deque uses a copy of the allocator object used * by @a __x (unless the allocator traits dictate a different object). */ deque(const deque& __x) : _Base(_Alloc_traits::_S_select_on_copy(__x._M_get_Tp_allocator()), __x.size()) { std::__uninitialized_copy_a(__x.begin(), __x.end(), this->_M_impl._M_start, _M_get_Tp_allocator()); } #if __cplusplus >= 201103L /** * @brief %Deque move constructor. * @param __x A %deque of identical element and allocator types. * * The newly-created %deque contains the exact contents of @a __x. * The contents of @a __x are a valid, but unspecified %deque. */ deque(deque&& __x) : _Base(std::move(__x)) { } /// Copy constructor with alternative allocator deque(const deque& __x, const allocator_type& __a) : _Base(__a, __x.size()) { std::__uninitialized_copy_a(__x.begin(), __x.end(), this->_M_impl._M_start, _M_get_Tp_allocator()); } /// Move constructor with alternative allocator deque(deque&& __x, const allocator_type& __a) : _Base(std::move(__x), __a, __x.size()) { if (__x.get_allocator() != __a) { std::__uninitialized_move_a(__x.begin(), __x.end(), this->_M_impl._M_start, _M_get_Tp_allocator()); __x.clear(); } } /** * @brief Builds a %deque from an initializer list. * @param __l An initializer_list. * @param __a An allocator object. * * Create a %deque consisting of copies of the elements in the * initializer_list @a __l. * * This will call the element type's copy constructor N times * (where N is __l.size()) and do no memory reallocation. */ deque(initializer_list __l, const allocator_type& __a = allocator_type()) : _Base(__a) { _M_range_initialize(__l.begin(), __l.end(), random_access_iterator_tag()); } #endif /** * @brief Builds a %deque from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __a An allocator object. * * Create a %deque consisting of copies of the elements from [__first, * __last). * * If the iterators are forward, bidirectional, or random-access, then * this will call the elements' copy constructor N times (where N is * distance(__first,__last)) and do no memory reallocation. But if only * input iterators are used, then this will do at most 2N calls to the * copy constructor, and logN memory reallocations. */ #if __cplusplus >= 201103L template> deque(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(__a) { _M_initialize_dispatch(__first, __last, __false_type()); } #else template deque(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(__a) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_initialize_dispatch(__first, __last, _Integral()); } #endif /** * The dtor only erases the elements, and note that if the elements * themselves are pointers, the pointed-to memory is not touched in any * way. Managing the pointer is the user's responsibility. */ ~deque() { _M_destroy_data(begin(), end(), _M_get_Tp_allocator()); } /** * @brief %Deque assignment operator. * @param __x A %deque of identical element and allocator types. * * All the elements of @a x are copied. * * The newly-created %deque uses a copy of the allocator object used * by @a __x (unless the allocator traits dictate a different object). */ deque& operator=(const deque& __x); #if __cplusplus >= 201103L /** * @brief %Deque move assignment operator. * @param __x A %deque of identical element and allocator types. * * The contents of @a __x are moved into this deque (without copying, * if the allocators permit it). * @a __x is a valid, but unspecified %deque. */ deque& operator=(deque&& __x) noexcept(_Alloc_traits::_S_always_equal()) { using __always_equal = typename _Alloc_traits::is_always_equal; _M_move_assign1(std::move(__x), __always_equal{}); return *this; } /** * @brief Assigns an initializer list to a %deque. * @param __l An initializer_list. * * This function fills a %deque with copies of the elements in the * initializer_list @a __l. * * Note that the assignment completely changes the %deque and that the * resulting %deque's size is the same as the number of elements * assigned. */ deque& operator=(initializer_list __l) { _M_assign_aux(__l.begin(), __l.end(), random_access_iterator_tag()); return *this; } #endif /** * @brief Assigns a given value to a %deque. * @param __n Number of elements to be assigned. * @param __val Value to be assigned. * * This function fills a %deque with @a n copies of the given * value. Note that the assignment completely changes the * %deque and that the resulting %deque's size is the same as * the number of elements assigned. */ void assign(size_type __n, const value_type& __val) { _M_fill_assign(__n, __val); } /** * @brief Assigns a range to a %deque. * @param __first An input iterator. * @param __last An input iterator. * * This function fills a %deque with copies of the elements in the * range [__first,__last). * * Note that the assignment completely changes the %deque and that the * resulting %deque's size is the same as the number of elements * assigned. */ #if __cplusplus >= 201103L template> void assign(_InputIterator __first, _InputIterator __last) { _M_assign_dispatch(__first, __last, __false_type()); } #else template void assign(_InputIterator __first, _InputIterator __last) { typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_assign_dispatch(__first, __last, _Integral()); } #endif #if __cplusplus >= 201103L /** * @brief Assigns an initializer list to a %deque. * @param __l An initializer_list. * * This function fills a %deque with copies of the elements in the * initializer_list @a __l. * * Note that the assignment completely changes the %deque and that the * resulting %deque's size is the same as the number of elements * assigned. */ void assign(initializer_list __l) { _M_assign_aux(__l.begin(), __l.end(), random_access_iterator_tag()); } #endif /// Get a copy of the memory allocation object. allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return _Base::get_allocator(); } // iterators /** * Returns a read/write iterator that points to the first element in the * %deque. Iteration is done in ordinary element order. */ iterator begin() _GLIBCXX_NOEXCEPT { return this->_M_impl._M_start; } /** * Returns a read-only (constant) iterator that points to the first * element in the %deque. Iteration is done in ordinary element order. */ const_iterator begin() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_start; } /** * Returns a read/write iterator that points one past the last * element in the %deque. Iteration is done in ordinary * element order. */ iterator end() _GLIBCXX_NOEXCEPT { return this->_M_impl._M_finish; } /** * Returns a read-only (constant) iterator that points one past * the last element in the %deque. Iteration is done in * ordinary element order. */ const_iterator end() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_finish; } /** * Returns a read/write reverse iterator that points to the * last element in the %deque. Iteration is done in reverse * element order. */ reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(this->_M_impl._M_finish); } /** * Returns a read-only (constant) reverse iterator that points * to the last element in the %deque. Iteration is done in * reverse element order. */ const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(this->_M_impl._M_finish); } /** * Returns a read/write reverse iterator that points to one * before the first element in the %deque. Iteration is done * in reverse element order. */ reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(this->_M_impl._M_start); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first element in the %deque. Iteration is * done in reverse element order. */ const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(this->_M_impl._M_start); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the first * element in the %deque. Iteration is done in ordinary element order. */ const_iterator cbegin() const noexcept { return this->_M_impl._M_start; } /** * Returns a read-only (constant) iterator that points one past * the last element in the %deque. Iteration is done in * ordinary element order. */ const_iterator cend() const noexcept { return this->_M_impl._M_finish; } /** * Returns a read-only (constant) reverse iterator that points * to the last element in the %deque. Iteration is done in * reverse element order. */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(this->_M_impl._M_finish); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first element in the %deque. Iteration is * done in reverse element order. */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(this->_M_impl._M_start); } #endif // [23.2.1.2] capacity /** Returns the number of elements in the %deque. */ size_type size() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_finish - this->_M_impl._M_start; } /** Returns the size() of the largest possible %deque. */ size_type max_size() const _GLIBCXX_NOEXCEPT { return _Alloc_traits::max_size(_M_get_Tp_allocator()); } #if __cplusplus >= 201103L /** * @brief Resizes the %deque to the specified number of elements. * @param __new_size Number of elements the %deque should contain. * * This function will %resize the %deque to the specified * number of elements. If the number is smaller than the * %deque's current size the %deque is truncated, otherwise * default constructed elements are appended. */ void resize(size_type __new_size) { const size_type __len = size(); if (__new_size > __len) _M_default_append(__new_size - __len); else if (__new_size < __len) _M_erase_at_end(this->_M_impl._M_start + difference_type(__new_size)); } /** * @brief Resizes the %deque to the specified number of elements. * @param __new_size Number of elements the %deque should contain. * @param __x Data with which new elements should be populated. * * This function will %resize the %deque to the specified * number of elements. If the number is smaller than the * %deque's current size the %deque is truncated, otherwise the * %deque is extended and new elements are populated with given * data. */ void resize(size_type __new_size, const value_type& __x) { const size_type __len = size(); if (__new_size > __len) _M_fill_insert(this->_M_impl._M_finish, __new_size - __len, __x); else if (__new_size < __len) _M_erase_at_end(this->_M_impl._M_start + difference_type(__new_size)); } #else /** * @brief Resizes the %deque to the specified number of elements. * @param __new_size Number of elements the %deque should contain. * @param __x Data with which new elements should be populated. * * This function will %resize the %deque to the specified * number of elements. If the number is smaller than the * %deque's current size the %deque is truncated, otherwise the * %deque is extended and new elements are populated with given * data. */ void resize(size_type __new_size, value_type __x = value_type()) { const size_type __len = size(); if (__new_size > __len) _M_fill_insert(this->_M_impl._M_finish, __new_size - __len, __x); else if (__new_size < __len) _M_erase_at_end(this->_M_impl._M_start + difference_type(__new_size)); } #endif #if __cplusplus >= 201103L /** A non-binding request to reduce memory use. */ void shrink_to_fit() noexcept { _M_shrink_to_fit(); } #endif /** * Returns true if the %deque is empty. (Thus begin() would * equal end().) */ bool empty() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_finish == this->_M_impl._M_start; } // element access /** * @brief Subscript access to the data contained in the %deque. * @param __n The index of the element for which data should be * accessed. * @return Read/write reference to data. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ reference operator[](size_type __n) _GLIBCXX_NOEXCEPT { __glibcxx_requires_subscript(__n); return this->_M_impl._M_start[difference_type(__n)]; } /** * @brief Subscript access to the data contained in the %deque. * @param __n The index of the element for which data should be * accessed. * @return Read-only (constant) reference to data. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ const_reference operator[](size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_subscript(__n); return this->_M_impl._M_start[difference_type(__n)]; } protected: /// Safety check used only from at(). void _M_range_check(size_type __n) const { if (__n >= this->size()) __throw_out_of_range_fmt(__N("deque::_M_range_check: __n " "(which is %zu)>= this->size() " "(which is %zu)"), __n, this->size()); } public: /** * @brief Provides access to the data contained in the %deque. * @param __n The index of the element for which data should be * accessed. * @return Read/write reference to data. * @throw std::out_of_range If @a __n is an invalid index. * * This function provides for safer data access. The parameter * is first checked that it is in the range of the deque. The * function throws out_of_range if the check fails. */ reference at(size_type __n) { _M_range_check(__n); return (*this)[__n]; } /** * @brief Provides access to the data contained in the %deque. * @param __n The index of the element for which data should be * accessed. * @return Read-only (constant) reference to data. * @throw std::out_of_range If @a __n is an invalid index. * * This function provides for safer data access. The parameter is first * checked that it is in the range of the deque. The function throws * out_of_range if the check fails. */ const_reference at(size_type __n) const { _M_range_check(__n); return (*this)[__n]; } /** * Returns a read/write reference to the data at the first * element of the %deque. */ reference front() _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); return *begin(); } /** * Returns a read-only (constant) reference to the data at the first * element of the %deque. */ const_reference front() const _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); return *begin(); } /** * Returns a read/write reference to the data at the last element of the * %deque. */ reference back() _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); iterator __tmp = end(); --__tmp; return *__tmp; } /** * Returns a read-only (constant) reference to the data at the last * element of the %deque. */ const_reference back() const _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); const_iterator __tmp = end(); --__tmp; return *__tmp; } // [23.2.1.2] modifiers /** * @brief Add data to the front of the %deque. * @param __x Data to be added. * * This is a typical stack operation. The function creates an * element at the front of the %deque and assigns the given * data to it. Due to the nature of a %deque this operation * can be done in constant time. */ void push_front(const value_type& __x) { if (this->_M_impl._M_start._M_cur != this->_M_impl._M_start._M_first) { _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_start._M_cur - 1, __x); --this->_M_impl._M_start._M_cur; } else _M_push_front_aux(__x); } #if __cplusplus >= 201103L void push_front(value_type&& __x) { emplace_front(std::move(__x)); } template #if __cplusplus > 201402L reference #else void #endif emplace_front(_Args&&... __args); #endif /** * @brief Add data to the end of the %deque. * @param __x Data to be added. * * This is a typical stack operation. The function creates an * element at the end of the %deque and assigns the given data * to it. Due to the nature of a %deque this operation can be * done in constant time. */ void push_back(const value_type& __x) { if (this->_M_impl._M_finish._M_cur != this->_M_impl._M_finish._M_last - 1) { _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish._M_cur, __x); ++this->_M_impl._M_finish._M_cur; } else _M_push_back_aux(__x); } #if __cplusplus >= 201103L void push_back(value_type&& __x) { emplace_back(std::move(__x)); } template #if __cplusplus > 201402L reference #else void #endif emplace_back(_Args&&... __args); #endif /** * @brief Removes first element. * * This is a typical stack operation. It shrinks the %deque by one. * * Note that no data is returned, and if the first element's data is * needed, it should be retrieved before pop_front() is called. */ void pop_front() _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); if (this->_M_impl._M_start._M_cur != this->_M_impl._M_start._M_last - 1) { _Alloc_traits::destroy(this->_M_impl, this->_M_impl._M_start._M_cur); ++this->_M_impl._M_start._M_cur; } else _M_pop_front_aux(); } /** * @brief Removes last element. * * This is a typical stack operation. It shrinks the %deque by one. * * Note that no data is returned, and if the last element's data is * needed, it should be retrieved before pop_back() is called. */ void pop_back() _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); if (this->_M_impl._M_finish._M_cur != this->_M_impl._M_finish._M_first) { --this->_M_impl._M_finish._M_cur; _Alloc_traits::destroy(this->_M_impl, this->_M_impl._M_finish._M_cur); } else _M_pop_back_aux(); } #if __cplusplus >= 201103L /** * @brief Inserts an object in %deque before specified iterator. * @param __position A const_iterator into the %deque. * @param __args Arguments. * @return An iterator that points to the inserted data. * * This function will insert an object of type T constructed * with T(std::forward(args)...) before the specified location. */ template iterator emplace(const_iterator __position, _Args&&... __args); /** * @brief Inserts given value into %deque before specified iterator. * @param __position A const_iterator into the %deque. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value before the * specified location. */ iterator insert(const_iterator __position, const value_type& __x); #else /** * @brief Inserts given value into %deque before specified iterator. * @param __position An iterator into the %deque. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value before the * specified location. */ iterator insert(iterator __position, const value_type& __x); #endif #if __cplusplus >= 201103L /** * @brief Inserts given rvalue into %deque before specified iterator. * @param __position A const_iterator into the %deque. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given rvalue before the * specified location. */ iterator insert(const_iterator __position, value_type&& __x) { return emplace(__position, std::move(__x)); } /** * @brief Inserts an initializer list into the %deque. * @param __p An iterator into the %deque. * @param __l An initializer_list. * * This function will insert copies of the data in the * initializer_list @a __l into the %deque before the location * specified by @a __p. This is known as list insert. */ iterator insert(const_iterator __p, initializer_list __l) { auto __offset = __p - cbegin(); _M_range_insert_aux(__p._M_const_cast(), __l.begin(), __l.end(), std::random_access_iterator_tag()); return begin() + __offset; } #endif #if __cplusplus >= 201103L /** * @brief Inserts a number of copies of given data into the %deque. * @param __position A const_iterator into the %deque. * @param __n Number of elements to be inserted. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a specified number of copies of the given * data before the location specified by @a __position. */ iterator insert(const_iterator __position, size_type __n, const value_type& __x) { difference_type __offset = __position - cbegin(); _M_fill_insert(__position._M_const_cast(), __n, __x); return begin() + __offset; } #else /** * @brief Inserts a number of copies of given data into the %deque. * @param __position An iterator into the %deque. * @param __n Number of elements to be inserted. * @param __x Data to be inserted. * * This function will insert a specified number of copies of the given * data before the location specified by @a __position. */ void insert(iterator __position, size_type __n, const value_type& __x) { _M_fill_insert(__position, __n, __x); } #endif #if __cplusplus >= 201103L /** * @brief Inserts a range into the %deque. * @param __position A const_iterator into the %deque. * @param __first An input iterator. * @param __last An input iterator. * @return An iterator that points to the inserted data. * * This function will insert copies of the data in the range * [__first,__last) into the %deque before the location specified * by @a __position. This is known as range insert. */ template> iterator insert(const_iterator __position, _InputIterator __first, _InputIterator __last) { difference_type __offset = __position - cbegin(); _M_insert_dispatch(__position._M_const_cast(), __first, __last, __false_type()); return begin() + __offset; } #else /** * @brief Inserts a range into the %deque. * @param __position An iterator into the %deque. * @param __first An input iterator. * @param __last An input iterator. * * This function will insert copies of the data in the range * [__first,__last) into the %deque before the location specified * by @a __position. This is known as range insert. */ template void insert(iterator __position, _InputIterator __first, _InputIterator __last) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_insert_dispatch(__position, __first, __last, _Integral()); } #endif /** * @brief Remove element at given position. * @param __position Iterator pointing to element to be erased. * @return An iterator pointing to the next element (or end()). * * This function will erase the element at the given position and thus * shorten the %deque by one. * * The user is cautioned that * this function only erases the element, and that if the element is * itself a pointer, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibility. */ iterator #if __cplusplus >= 201103L erase(const_iterator __position) #else erase(iterator __position) #endif { return _M_erase(__position._M_const_cast()); } /** * @brief Remove a range of elements. * @param __first Iterator pointing to the first element to be erased. * @param __last Iterator pointing to one past the last element to be * erased. * @return An iterator pointing to the element pointed to by @a last * prior to erasing (or end()). * * This function will erase the elements in the range * [__first,__last) and shorten the %deque accordingly. * * The user is cautioned that * this function only erases the elements, and that if the elements * themselves are pointers, the pointed-to memory is not touched in any * way. Managing the pointer is the user's responsibility. */ iterator #if __cplusplus >= 201103L erase(const_iterator __first, const_iterator __last) #else erase(iterator __first, iterator __last) #endif { return _M_erase(__first._M_const_cast(), __last._M_const_cast()); } /** * @brief Swaps data with another %deque. * @param __x A %deque of the same element and allocator types. * * This exchanges the elements between two deques in constant time. * (Four pointers, so it should be quite fast.) * Note that the global std::swap() function is specialized such that * std::swap(d1,d2) will feed to this function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(deque& __x) _GLIBCXX_NOEXCEPT { #if __cplusplus >= 201103L __glibcxx_assert(_Alloc_traits::propagate_on_container_swap::value || _M_get_Tp_allocator() == __x._M_get_Tp_allocator()); #endif _M_impl._M_swap_data(__x._M_impl); _Alloc_traits::_S_on_swap(_M_get_Tp_allocator(), __x._M_get_Tp_allocator()); } /** * Erases all the elements. Note that this function only erases the * elements, and that if the elements themselves are pointers, the * pointed-to memory is not touched in any way. Managing the pointer is * the user's responsibility. */ void clear() _GLIBCXX_NOEXCEPT { _M_erase_at_end(begin()); } protected: // Internal constructor functions follow. // called by the range constructor to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_initialize_dispatch(_Integer __n, _Integer __x, __true_type) { _M_initialize_map(static_cast(__n)); _M_fill_initialize(__x); } // called by the range constructor to implement [23.1.1]/9 template void _M_initialize_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { _M_range_initialize(__first, __last, std::__iterator_category(__first)); } // called by the second initialize_dispatch above //@{ /** * @brief Fills the deque with whatever is in [first,last). * @param __first An input iterator. * @param __last An input iterator. * @return Nothing. * * If the iterators are actually forward iterators (or better), then the * memory layout can be done all at once. Else we move forward using * push_back on each value from the iterator. */ template void _M_range_initialize(_InputIterator __first, _InputIterator __last, std::input_iterator_tag); // called by the second initialize_dispatch above template void _M_range_initialize(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag); //@} /** * @brief Fills the %deque with copies of value. * @param __value Initial value. * @return Nothing. * @pre _M_start and _M_finish have already been initialized, * but none of the %deque's elements have yet been constructed. * * This function is called only when the user provides an explicit size * (with or without an explicit exemplar value). */ void _M_fill_initialize(const value_type& __value); #if __cplusplus >= 201103L // called by deque(n). void _M_default_initialize(); #endif // Internal assign functions follow. The *_aux functions do the actual // assignment work for the range versions. // called by the range assign to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_assign_dispatch(_Integer __n, _Integer __val, __true_type) { _M_fill_assign(__n, __val); } // called by the range assign to implement [23.1.1]/9 template void _M_assign_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { _M_assign_aux(__first, __last, std::__iterator_category(__first)); } // called by the second assign_dispatch above template void _M_assign_aux(_InputIterator __first, _InputIterator __last, std::input_iterator_tag); // called by the second assign_dispatch above template void _M_assign_aux(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { const size_type __len = std::distance(__first, __last); if (__len > size()) { _ForwardIterator __mid = __first; std::advance(__mid, size()); std::copy(__first, __mid, begin()); _M_range_insert_aux(end(), __mid, __last, std::__iterator_category(__first)); } else _M_erase_at_end(std::copy(__first, __last, begin())); } // Called by assign(n,t), and the range assign when it turns out // to be the same thing. void _M_fill_assign(size_type __n, const value_type& __val) { if (__n > size()) { std::fill(begin(), end(), __val); _M_fill_insert(end(), __n - size(), __val); } else { _M_erase_at_end(begin() + difference_type(__n)); std::fill(begin(), end(), __val); } } //@{ /// Helper functions for push_* and pop_*. #if __cplusplus < 201103L void _M_push_back_aux(const value_type&); void _M_push_front_aux(const value_type&); #else template void _M_push_back_aux(_Args&&... __args); template void _M_push_front_aux(_Args&&... __args); #endif void _M_pop_back_aux(); void _M_pop_front_aux(); //@} // Internal insert functions follow. The *_aux functions do the actual // insertion work when all shortcuts fail. // called by the range insert to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_insert_dispatch(iterator __pos, _Integer __n, _Integer __x, __true_type) { _M_fill_insert(__pos, __n, __x); } // called by the range insert to implement [23.1.1]/9 template void _M_insert_dispatch(iterator __pos, _InputIterator __first, _InputIterator __last, __false_type) { _M_range_insert_aux(__pos, __first, __last, std::__iterator_category(__first)); } // called by the second insert_dispatch above template void _M_range_insert_aux(iterator __pos, _InputIterator __first, _InputIterator __last, std::input_iterator_tag); // called by the second insert_dispatch above template void _M_range_insert_aux(iterator __pos, _ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag); // Called by insert(p,n,x), and the range insert when it turns out to be // the same thing. Can use fill functions in optimal situations, // otherwise passes off to insert_aux(p,n,x). void _M_fill_insert(iterator __pos, size_type __n, const value_type& __x); // called by insert(p,x) #if __cplusplus < 201103L iterator _M_insert_aux(iterator __pos, const value_type& __x); #else template iterator _M_insert_aux(iterator __pos, _Args&&... __args); #endif // called by insert(p,n,x) via fill_insert void _M_insert_aux(iterator __pos, size_type __n, const value_type& __x); // called by range_insert_aux for forward iterators template void _M_insert_aux(iterator __pos, _ForwardIterator __first, _ForwardIterator __last, size_type __n); // Internal erase functions follow. void _M_destroy_data_aux(iterator __first, iterator __last); // Called by ~deque(). // NB: Doesn't deallocate the nodes. template void _M_destroy_data(iterator __first, iterator __last, const _Alloc1&) { _M_destroy_data_aux(__first, __last); } void _M_destroy_data(iterator __first, iterator __last, const std::allocator<_Tp>&) { if (!__has_trivial_destructor(value_type)) _M_destroy_data_aux(__first, __last); } // Called by erase(q1, q2). void _M_erase_at_begin(iterator __pos) { _M_destroy_data(begin(), __pos, _M_get_Tp_allocator()); _M_destroy_nodes(this->_M_impl._M_start._M_node, __pos._M_node); this->_M_impl._M_start = __pos; } // Called by erase(q1, q2), resize(), clear(), _M_assign_aux, // _M_fill_assign, operator=. void _M_erase_at_end(iterator __pos) { _M_destroy_data(__pos, end(), _M_get_Tp_allocator()); _M_destroy_nodes(__pos._M_node + 1, this->_M_impl._M_finish._M_node + 1); this->_M_impl._M_finish = __pos; } iterator _M_erase(iterator __pos); iterator _M_erase(iterator __first, iterator __last); #if __cplusplus >= 201103L // Called by resize(sz). void _M_default_append(size_type __n); bool _M_shrink_to_fit(); #endif //@{ /// Memory-handling helpers for the previous internal insert functions. iterator _M_reserve_elements_at_front(size_type __n) { const size_type __vacancies = this->_M_impl._M_start._M_cur - this->_M_impl._M_start._M_first; if (__n > __vacancies) _M_new_elements_at_front(__n - __vacancies); return this->_M_impl._M_start - difference_type(__n); } iterator _M_reserve_elements_at_back(size_type __n) { const size_type __vacancies = (this->_M_impl._M_finish._M_last - this->_M_impl._M_finish._M_cur) - 1; if (__n > __vacancies) _M_new_elements_at_back(__n - __vacancies); return this->_M_impl._M_finish + difference_type(__n); } void _M_new_elements_at_front(size_type __new_elements); void _M_new_elements_at_back(size_type __new_elements); //@} //@{ /** * @brief Memory-handling helpers for the major %map. * * Makes sure the _M_map has space for new nodes. Does not * actually add the nodes. Can invalidate _M_map pointers. * (And consequently, %deque iterators.) */ void _M_reserve_map_at_back(size_type __nodes_to_add = 1) { if (__nodes_to_add + 1 > this->_M_impl._M_map_size - (this->_M_impl._M_finish._M_node - this->_M_impl._M_map)) _M_reallocate_map(__nodes_to_add, false); } void _M_reserve_map_at_front(size_type __nodes_to_add = 1) { if (__nodes_to_add > size_type(this->_M_impl._M_start._M_node - this->_M_impl._M_map)) _M_reallocate_map(__nodes_to_add, true); } void _M_reallocate_map(size_type __nodes_to_add, bool __add_at_front); //@} #if __cplusplus >= 201103L // Constant-time, nothrow move assignment when source object's memory // can be moved because the allocators are equal. void _M_move_assign1(deque&& __x, /* always equal: */ true_type) noexcept { this->_M_impl._M_swap_data(__x._M_impl); __x.clear(); std::__alloc_on_move(_M_get_Tp_allocator(), __x._M_get_Tp_allocator()); } // When the allocators are not equal the operation could throw, because // we might need to allocate a new map for __x after moving from it // or we might need to allocate new elements for *this. void _M_move_assign1(deque&& __x, /* always equal: */ false_type) { constexpr bool __move_storage = _Alloc_traits::_S_propagate_on_move_assign(); _M_move_assign2(std::move(__x), __bool_constant<__move_storage>()); } // Destroy all elements and deallocate all memory, then replace // with elements created from __args. template void _M_replace_map(_Args&&... __args) { // Create new data first, so if allocation fails there are no effects. deque __newobj(std::forward<_Args>(__args)...); // Free existing storage using existing allocator. clear(); _M_deallocate_node(*begin()._M_node); // one node left after clear() _M_deallocate_map(this->_M_impl._M_map, this->_M_impl._M_map_size); this->_M_impl._M_map = nullptr; this->_M_impl._M_map_size = 0; // Take ownership of replacement memory. this->_M_impl._M_swap_data(__newobj._M_impl); } // Do move assignment when the allocator propagates. void _M_move_assign2(deque&& __x, /* propagate: */ true_type) { // Make a copy of the original allocator state. auto __alloc = __x._M_get_Tp_allocator(); // The allocator propagates so storage can be moved from __x, // leaving __x in a valid empty state with a moved-from allocator. _M_replace_map(std::move(__x)); // Move the corresponding allocator state too. _M_get_Tp_allocator() = std::move(__alloc); } // Do move assignment when it may not be possible to move source // object's memory, resulting in a linear-time operation. void _M_move_assign2(deque&& __x, /* propagate: */ false_type) { if (__x._M_get_Tp_allocator() == this->_M_get_Tp_allocator()) { // The allocators are equal so storage can be moved from __x, // leaving __x in a valid empty state with its current allocator. _M_replace_map(std::move(__x), __x.get_allocator()); } else { // The rvalue's allocator cannot be moved and is not equal, // so we need to individually move each element. _M_assign_aux(std::__make_move_if_noexcept_iterator(__x.begin()), std::__make_move_if_noexcept_iterator(__x.end()), std::random_access_iterator_tag()); __x.clear(); } } #endif }; #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> deque(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> deque<_ValT, _Allocator>; #endif /** * @brief Deque equality comparison. * @param __x A %deque. * @param __y A %deque of the same type as @a __x. * @return True iff the size and elements of the deques are equal. * * This is an equivalence relation. It is linear in the size of the * deques. Deques are considered equivalent if their sizes are equal, * and if corresponding elements compare equal. */ template inline bool operator==(const deque<_Tp, _Alloc>& __x, const deque<_Tp, _Alloc>& __y) { return __x.size() == __y.size() && std::equal(__x.begin(), __x.end(), __y.begin()); } /** * @brief Deque ordering relation. * @param __x A %deque. * @param __y A %deque of the same type as @a __x. * @return True iff @a x is lexicographically less than @a __y. * * This is a total ordering relation. It is linear in the size of the * deques. The elements must be comparable with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const deque<_Tp, _Alloc>& __x, const deque<_Tp, _Alloc>& __y) { return std::lexicographical_compare(__x.begin(), __x.end(), __y.begin(), __y.end()); } /// Based on operator== template inline bool operator!=(const deque<_Tp, _Alloc>& __x, const deque<_Tp, _Alloc>& __y) { return !(__x == __y); } /// Based on operator< template inline bool operator>(const deque<_Tp, _Alloc>& __x, const deque<_Tp, _Alloc>& __y) { return __y < __x; } /// Based on operator< template inline bool operator<=(const deque<_Tp, _Alloc>& __x, const deque<_Tp, _Alloc>& __y) { return !(__y < __x); } /// Based on operator< template inline bool operator>=(const deque<_Tp, _Alloc>& __x, const deque<_Tp, _Alloc>& __y) { return !(__x < __y); } /// See std::deque::swap(). template inline void swap(deque<_Tp,_Alloc>& __x, deque<_Tp,_Alloc>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { __x.swap(__y); } #undef _GLIBCXX_DEQUE_BUF_SIZE _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_DEQUE_H */ PK!Ho(8/bits/stl_function.hnu[// Functor implementations -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996-1998 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_function.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{functional} */ #ifndef _STL_FUNCTION_H #define _STL_FUNCTION_H 1 #if __cplusplus > 201103L #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // 20.3.1 base classes /** @defgroup functors Function Objects * @ingroup utilities * * Function objects, or @e functors, are objects with an @c operator() * defined and accessible. They can be passed as arguments to algorithm * templates and used in place of a function pointer. Not only is the * resulting expressiveness of the library increased, but the generated * code can be more efficient than what you might write by hand. When we * refer to @a functors, then, generally we include function pointers in * the description as well. * * Often, functors are only created as temporaries passed to algorithm * calls, rather than being created as named variables. * * Two examples taken from the standard itself follow. To perform a * by-element addition of two vectors @c a and @c b containing @c double, * and put the result in @c a, use * \code * transform (a.begin(), a.end(), b.begin(), a.begin(), plus()); * \endcode * To negate every element in @c a, use * \code * transform(a.begin(), a.end(), a.begin(), negate()); * \endcode * The addition and negation functions will be inlined directly. * * The standard functors are derived from structs named @c unary_function * and @c binary_function. These two classes contain nothing but typedefs, * to aid in generic (template) programming. If you write your own * functors, you might consider doing the same. * * @{ */ /** * This is one of the @link functors functor base classes@endlink. */ template struct unary_function { /// @c argument_type is the type of the argument typedef _Arg argument_type; /// @c result_type is the return type typedef _Result result_type; }; /** * This is one of the @link functors functor base classes@endlink. */ template struct binary_function { /// @c first_argument_type is the type of the first argument typedef _Arg1 first_argument_type; /// @c second_argument_type is the type of the second argument typedef _Arg2 second_argument_type; /// @c result_type is the return type typedef _Result result_type; }; /** @} */ // 20.3.2 arithmetic /** @defgroup arithmetic_functors Arithmetic Classes * @ingroup functors * * Because basic math often needs to be done during an algorithm, * the library provides functors for those operations. See the * documentation for @link functors the base classes@endlink * for examples of their use. * * @{ */ #if __cplusplus > 201103L struct __is_transparent; // undefined template struct plus; template struct minus; template struct multiplies; template struct divides; template struct modulus; template struct negate; #endif /// One of the @link arithmetic_functors math functors@endlink. template struct plus : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x + __y; } }; /// One of the @link arithmetic_functors math functors@endlink. template struct minus : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x - __y; } }; /// One of the @link arithmetic_functors math functors@endlink. template struct multiplies : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x * __y; } }; /// One of the @link arithmetic_functors math functors@endlink. template struct divides : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x / __y; } }; /// One of the @link arithmetic_functors math functors@endlink. template struct modulus : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x % __y; } }; /// One of the @link arithmetic_functors math functors@endlink. template struct negate : public unary_function<_Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x) const { return -__x; } }; #if __cplusplus > 201103L #define __cpp_lib_transparent_operators 201510 template<> struct plus { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) + std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) + std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) + std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link arithmetic_functors math functors@endlink. template<> struct minus { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) - std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) - std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) - std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link arithmetic_functors math functors@endlink. template<> struct multiplies { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) * std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) * std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) * std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link arithmetic_functors math functors@endlink. template<> struct divides { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) / std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) / std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) / std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link arithmetic_functors math functors@endlink. template<> struct modulus { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) % std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) % std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) % std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link arithmetic_functors math functors@endlink. template<> struct negate { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t) const noexcept(noexcept(-std::forward<_Tp>(__t))) -> decltype(-std::forward<_Tp>(__t)) { return -std::forward<_Tp>(__t); } typedef __is_transparent is_transparent; }; #endif /** @} */ // 20.3.3 comparisons /** @defgroup comparison_functors Comparison Classes * @ingroup functors * * The library provides six wrapper functors for all the basic comparisons * in C++, like @c <. * * @{ */ #if __cplusplus > 201103L template struct equal_to; template struct not_equal_to; template struct greater; template struct less; template struct greater_equal; template struct less_equal; #endif /// One of the @link comparison_functors comparison functors@endlink. template struct equal_to : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x == __y; } }; /// One of the @link comparison_functors comparison functors@endlink. template struct not_equal_to : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x != __y; } }; /// One of the @link comparison_functors comparison functors@endlink. template struct greater : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x > __y; } }; /// One of the @link comparison_functors comparison functors@endlink. template struct less : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x < __y; } }; /// One of the @link comparison_functors comparison functors@endlink. template struct greater_equal : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x >= __y; } }; /// One of the @link comparison_functors comparison functors@endlink. template struct less_equal : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x <= __y; } }; // Partial specialization of std::greater for pointers. template struct greater<_Tp*> : public binary_function<_Tp*, _Tp*, bool> { _GLIBCXX14_CONSTEXPR bool operator()(_Tp* __x, _Tp* __y) const _GLIBCXX_NOTHROW { if (__builtin_constant_p (__x > __y)) return __x > __y; return (__UINTPTR_TYPE__)__x > (__UINTPTR_TYPE__)__y; } }; // Partial specialization of std::less for pointers. template struct less<_Tp*> : public binary_function<_Tp*, _Tp*, bool> { _GLIBCXX14_CONSTEXPR bool operator()(_Tp* __x, _Tp* __y) const _GLIBCXX_NOTHROW { if (__builtin_constant_p (__x < __y)) return __x < __y; return (__UINTPTR_TYPE__)__x < (__UINTPTR_TYPE__)__y; } }; // Partial specialization of std::greater_equal for pointers. template struct greater_equal<_Tp*> : public binary_function<_Tp*, _Tp*, bool> { _GLIBCXX14_CONSTEXPR bool operator()(_Tp* __x, _Tp* __y) const _GLIBCXX_NOTHROW { if (__builtin_constant_p (__x >= __y)) return __x >= __y; return (__UINTPTR_TYPE__)__x >= (__UINTPTR_TYPE__)__y; } }; // Partial specialization of std::less_equal for pointers. template struct less_equal<_Tp*> : public binary_function<_Tp*, _Tp*, bool> { _GLIBCXX14_CONSTEXPR bool operator()(_Tp* __x, _Tp* __y) const _GLIBCXX_NOTHROW { if (__builtin_constant_p (__x <= __y)) return __x <= __y; return (__UINTPTR_TYPE__)__x <= (__UINTPTR_TYPE__)__y; } }; #if __cplusplus >= 201402L /// One of the @link comparison_functors comparison functors@endlink. template<> struct equal_to { template constexpr auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) == std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) == std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) == std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link comparison_functors comparison functors@endlink. template<> struct not_equal_to { template constexpr auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) != std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) != std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) != std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link comparison_functors comparison functors@endlink. template<> struct greater { template constexpr auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) > std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) > std::forward<_Up>(__u)) { return _S_cmp(std::forward<_Tp>(__t), std::forward<_Up>(__u), __ptr_cmp<_Tp, _Up>{}); } template constexpr bool operator()(_Tp* __t, _Up* __u) const noexcept { return greater>{}(__t, __u); } typedef __is_transparent is_transparent; private: template static constexpr decltype(auto) _S_cmp(_Tp&& __t, _Up&& __u, false_type) { return std::forward<_Tp>(__t) > std::forward<_Up>(__u); } template static constexpr bool _S_cmp(_Tp&& __t, _Up&& __u, true_type) noexcept { return greater{}( static_cast(std::forward<_Tp>(__t)), static_cast(std::forward<_Up>(__u))); } // True if there is no viable operator> member function. template struct __not_overloaded2 : true_type { }; // False if we can call T.operator>(U) template struct __not_overloaded2<_Tp, _Up, __void_t< decltype(std::declval<_Tp>().operator>(std::declval<_Up>()))>> : false_type { }; // True if there is no overloaded operator> for these operands. template struct __not_overloaded : __not_overloaded2<_Tp, _Up> { }; // False if we can call operator>(T,U) template struct __not_overloaded<_Tp, _Up, __void_t< decltype(operator>(std::declval<_Tp>(), std::declval<_Up>()))>> : false_type { }; template using __ptr_cmp = __and_<__not_overloaded<_Tp, _Up>, is_convertible<_Tp, const volatile void*>, is_convertible<_Up, const volatile void*>>; }; /// One of the @link comparison_functors comparison functors@endlink. template<> struct less { template constexpr auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) < std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) < std::forward<_Up>(__u)) { return _S_cmp(std::forward<_Tp>(__t), std::forward<_Up>(__u), __ptr_cmp<_Tp, _Up>{}); } template constexpr bool operator()(_Tp* __t, _Up* __u) const noexcept { return less>{}(__t, __u); } typedef __is_transparent is_transparent; private: template static constexpr decltype(auto) _S_cmp(_Tp&& __t, _Up&& __u, false_type) { return std::forward<_Tp>(__t) < std::forward<_Up>(__u); } template static constexpr bool _S_cmp(_Tp&& __t, _Up&& __u, true_type) noexcept { return less{}( static_cast(std::forward<_Tp>(__t)), static_cast(std::forward<_Up>(__u))); } // True if there is no viable operator< member function. template struct __not_overloaded2 : true_type { }; // False if we can call T.operator<(U) template struct __not_overloaded2<_Tp, _Up, __void_t< decltype(std::declval<_Tp>().operator<(std::declval<_Up>()))>> : false_type { }; // True if there is no overloaded operator< for these operands. template struct __not_overloaded : __not_overloaded2<_Tp, _Up> { }; // False if we can call operator<(T,U) template struct __not_overloaded<_Tp, _Up, __void_t< decltype(operator<(std::declval<_Tp>(), std::declval<_Up>()))>> : false_type { }; template using __ptr_cmp = __and_<__not_overloaded<_Tp, _Up>, is_convertible<_Tp, const volatile void*>, is_convertible<_Up, const volatile void*>>; }; /// One of the @link comparison_functors comparison functors@endlink. template<> struct greater_equal { template constexpr auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) >= std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) >= std::forward<_Up>(__u)) { return _S_cmp(std::forward<_Tp>(__t), std::forward<_Up>(__u), __ptr_cmp<_Tp, _Up>{}); } template constexpr bool operator()(_Tp* __t, _Up* __u) const noexcept { return greater_equal>{}(__t, __u); } typedef __is_transparent is_transparent; private: template static constexpr decltype(auto) _S_cmp(_Tp&& __t, _Up&& __u, false_type) { return std::forward<_Tp>(__t) >= std::forward<_Up>(__u); } template static constexpr bool _S_cmp(_Tp&& __t, _Up&& __u, true_type) noexcept { return greater_equal{}( static_cast(std::forward<_Tp>(__t)), static_cast(std::forward<_Up>(__u))); } // True if there is no viable operator>= member function. template struct __not_overloaded2 : true_type { }; // False if we can call T.operator>=(U) template struct __not_overloaded2<_Tp, _Up, __void_t< decltype(std::declval<_Tp>().operator>=(std::declval<_Up>()))>> : false_type { }; // True if there is no overloaded operator>= for these operands. template struct __not_overloaded : __not_overloaded2<_Tp, _Up> { }; // False if we can call operator>=(T,U) template struct __not_overloaded<_Tp, _Up, __void_t< decltype(operator>=(std::declval<_Tp>(), std::declval<_Up>()))>> : false_type { }; template using __ptr_cmp = __and_<__not_overloaded<_Tp, _Up>, is_convertible<_Tp, const volatile void*>, is_convertible<_Up, const volatile void*>>; }; /// One of the @link comparison_functors comparison functors@endlink. template<> struct less_equal { template constexpr auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) <= std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) <= std::forward<_Up>(__u)) { return _S_cmp(std::forward<_Tp>(__t), std::forward<_Up>(__u), __ptr_cmp<_Tp, _Up>{}); } template constexpr bool operator()(_Tp* __t, _Up* __u) const noexcept { return less_equal>{}(__t, __u); } typedef __is_transparent is_transparent; private: template static constexpr decltype(auto) _S_cmp(_Tp&& __t, _Up&& __u, false_type) { return std::forward<_Tp>(__t) <= std::forward<_Up>(__u); } template static constexpr bool _S_cmp(_Tp&& __t, _Up&& __u, true_type) noexcept { return less_equal{}( static_cast(std::forward<_Tp>(__t)), static_cast(std::forward<_Up>(__u))); } // True if there is no viable operator<= member function. template struct __not_overloaded2 : true_type { }; // False if we can call T.operator<=(U) template struct __not_overloaded2<_Tp, _Up, __void_t< decltype(std::declval<_Tp>().operator<=(std::declval<_Up>()))>> : false_type { }; // True if there is no overloaded operator<= for these operands. template struct __not_overloaded : __not_overloaded2<_Tp, _Up> { }; // False if we can call operator<=(T,U) template struct __not_overloaded<_Tp, _Up, __void_t< decltype(operator<=(std::declval<_Tp>(), std::declval<_Up>()))>> : false_type { }; template using __ptr_cmp = __and_<__not_overloaded<_Tp, _Up>, is_convertible<_Tp, const volatile void*>, is_convertible<_Up, const volatile void*>>; }; #endif // C++14 /** @} */ // 20.3.4 logical operations /** @defgroup logical_functors Boolean Operations Classes * @ingroup functors * * Here are wrapper functors for Boolean operations: @c &&, @c ||, * and @c !. * * @{ */ #if __cplusplus > 201103L template struct logical_and; template struct logical_or; template struct logical_not; #endif /// One of the @link logical_functors Boolean operations functors@endlink. template struct logical_and : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x && __y; } }; /// One of the @link logical_functors Boolean operations functors@endlink. template struct logical_or : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x || __y; } }; /// One of the @link logical_functors Boolean operations functors@endlink. template struct logical_not : public unary_function<_Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x) const { return !__x; } }; #if __cplusplus > 201103L /// One of the @link logical_functors Boolean operations functors@endlink. template<> struct logical_and { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) && std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) && std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) && std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link logical_functors Boolean operations functors@endlink. template<> struct logical_or { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) || std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) || std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) || std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link logical_functors Boolean operations functors@endlink. template<> struct logical_not { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t) const noexcept(noexcept(!std::forward<_Tp>(__t))) -> decltype(!std::forward<_Tp>(__t)) { return !std::forward<_Tp>(__t); } typedef __is_transparent is_transparent; }; #endif /** @} */ #if __cplusplus > 201103L template struct bit_and; template struct bit_or; template struct bit_xor; template struct bit_not; #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 660. Missing Bitwise Operations. template struct bit_and : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x & __y; } }; template struct bit_or : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x | __y; } }; template struct bit_xor : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x ^ __y; } }; template struct bit_not : public unary_function<_Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x) const { return ~__x; } }; #if __cplusplus > 201103L template <> struct bit_and { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) & std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) & std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) & std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; template <> struct bit_or { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) | std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) | std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) | std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; template <> struct bit_xor { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) ^ std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) ^ std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) ^ std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; template <> struct bit_not { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t) const noexcept(noexcept(~std::forward<_Tp>(__t))) -> decltype(~std::forward<_Tp>(__t)) { return ~std::forward<_Tp>(__t); } typedef __is_transparent is_transparent; }; #endif // 20.3.5 negators /** @defgroup negators Negators * @ingroup functors * * The functions @c not1 and @c not2 each take a predicate functor * and return an instance of @c unary_negate or * @c binary_negate, respectively. These classes are functors whose * @c operator() performs the stored predicate function and then returns * the negation of the result. * * For example, given a vector of integers and a trivial predicate, * \code * struct IntGreaterThanThree * : public std::unary_function * { * bool operator() (int x) { return x > 3; } * }; * * std::find_if (v.begin(), v.end(), not1(IntGreaterThanThree())); * \endcode * The call to @c find_if will locate the first index (i) of @c v for which * !(v[i] > 3) is true. * * The not1/unary_negate combination works on predicates taking a single * argument. The not2/binary_negate combination works on predicates which * take two arguments. * * @{ */ /// One of the @link negators negation functors@endlink. template class unary_negate : public unary_function { protected: _Predicate _M_pred; public: _GLIBCXX14_CONSTEXPR explicit unary_negate(const _Predicate& __x) : _M_pred(__x) { } _GLIBCXX14_CONSTEXPR bool operator()(const typename _Predicate::argument_type& __x) const { return !_M_pred(__x); } }; /// One of the @link negators negation functors@endlink. template _GLIBCXX14_CONSTEXPR inline unary_negate<_Predicate> not1(const _Predicate& __pred) { return unary_negate<_Predicate>(__pred); } /// One of the @link negators negation functors@endlink. template class binary_negate : public binary_function { protected: _Predicate _M_pred; public: _GLIBCXX14_CONSTEXPR explicit binary_negate(const _Predicate& __x) : _M_pred(__x) { } _GLIBCXX14_CONSTEXPR bool operator()(const typename _Predicate::first_argument_type& __x, const typename _Predicate::second_argument_type& __y) const { return !_M_pred(__x, __y); } }; /// One of the @link negators negation functors@endlink. template _GLIBCXX14_CONSTEXPR inline binary_negate<_Predicate> not2(const _Predicate& __pred) { return binary_negate<_Predicate>(__pred); } /** @} */ // 20.3.7 adaptors pointers functions /** @defgroup pointer_adaptors Adaptors for pointers to functions * @ingroup functors * * The advantage of function objects over pointers to functions is that * the objects in the standard library declare nested typedefs describing * their argument and result types with uniform names (e.g., @c result_type * from the base classes @c unary_function and @c binary_function). * Sometimes those typedefs are required, not just optional. * * Adaptors are provided to turn pointers to unary (single-argument) and * binary (double-argument) functions into function objects. The * long-winded functor @c pointer_to_unary_function is constructed with a * function pointer @c f, and its @c operator() called with argument @c x * returns @c f(x). The functor @c pointer_to_binary_function does the same * thing, but with a double-argument @c f and @c operator(). * * The function @c ptr_fun takes a pointer-to-function @c f and constructs * an instance of the appropriate functor. * * @{ */ /// One of the @link pointer_adaptors adaptors for function pointers@endlink. template class pointer_to_unary_function : public unary_function<_Arg, _Result> { protected: _Result (*_M_ptr)(_Arg); public: pointer_to_unary_function() { } explicit pointer_to_unary_function(_Result (*__x)(_Arg)) : _M_ptr(__x) { } _Result operator()(_Arg __x) const { return _M_ptr(__x); } }; /// One of the @link pointer_adaptors adaptors for function pointers@endlink. template inline pointer_to_unary_function<_Arg, _Result> ptr_fun(_Result (*__x)(_Arg)) { return pointer_to_unary_function<_Arg, _Result>(__x); } /// One of the @link pointer_adaptors adaptors for function pointers@endlink. template class pointer_to_binary_function : public binary_function<_Arg1, _Arg2, _Result> { protected: _Result (*_M_ptr)(_Arg1, _Arg2); public: pointer_to_binary_function() { } explicit pointer_to_binary_function(_Result (*__x)(_Arg1, _Arg2)) : _M_ptr(__x) { } _Result operator()(_Arg1 __x, _Arg2 __y) const { return _M_ptr(__x, __y); } }; /// One of the @link pointer_adaptors adaptors for function pointers@endlink. template inline pointer_to_binary_function<_Arg1, _Arg2, _Result> ptr_fun(_Result (*__x)(_Arg1, _Arg2)) { return pointer_to_binary_function<_Arg1, _Arg2, _Result>(__x); } /** @} */ template struct _Identity : public unary_function<_Tp, _Tp> { _Tp& operator()(_Tp& __x) const { return __x; } const _Tp& operator()(const _Tp& __x) const { return __x; } }; // Partial specialization, avoids confusing errors in e.g. std::set. template struct _Identity : _Identity<_Tp> { }; template struct _Select1st : public unary_function<_Pair, typename _Pair::first_type> { typename _Pair::first_type& operator()(_Pair& __x) const { return __x.first; } const typename _Pair::first_type& operator()(const _Pair& __x) const { return __x.first; } #if __cplusplus >= 201103L template typename _Pair2::first_type& operator()(_Pair2& __x) const { return __x.first; } template const typename _Pair2::first_type& operator()(const _Pair2& __x) const { return __x.first; } #endif }; template struct _Select2nd : public unary_function<_Pair, typename _Pair::second_type> { typename _Pair::second_type& operator()(_Pair& __x) const { return __x.second; } const typename _Pair::second_type& operator()(const _Pair& __x) const { return __x.second; } }; // 20.3.8 adaptors pointers members /** @defgroup memory_adaptors Adaptors for pointers to members * @ingroup functors * * There are a total of 8 = 2^3 function objects in this family. * (1) Member functions taking no arguments vs member functions taking * one argument. * (2) Call through pointer vs call through reference. * (3) Const vs non-const member function. * * All of this complexity is in the function objects themselves. You can * ignore it by using the helper function mem_fun and mem_fun_ref, * which create whichever type of adaptor is appropriate. * * @{ */ /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class mem_fun_t : public unary_function<_Tp*, _Ret> { public: explicit mem_fun_t(_Ret (_Tp::*__pf)()) : _M_f(__pf) { } _Ret operator()(_Tp* __p) const { return (__p->*_M_f)(); } private: _Ret (_Tp::*_M_f)(); }; /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class const_mem_fun_t : public unary_function { public: explicit const_mem_fun_t(_Ret (_Tp::*__pf)() const) : _M_f(__pf) { } _Ret operator()(const _Tp* __p) const { return (__p->*_M_f)(); } private: _Ret (_Tp::*_M_f)() const; }; /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class mem_fun_ref_t : public unary_function<_Tp, _Ret> { public: explicit mem_fun_ref_t(_Ret (_Tp::*__pf)()) : _M_f(__pf) { } _Ret operator()(_Tp& __r) const { return (__r.*_M_f)(); } private: _Ret (_Tp::*_M_f)(); }; /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class const_mem_fun_ref_t : public unary_function<_Tp, _Ret> { public: explicit const_mem_fun_ref_t(_Ret (_Tp::*__pf)() const) : _M_f(__pf) { } _Ret operator()(const _Tp& __r) const { return (__r.*_M_f)(); } private: _Ret (_Tp::*_M_f)() const; }; /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class mem_fun1_t : public binary_function<_Tp*, _Arg, _Ret> { public: explicit mem_fun1_t(_Ret (_Tp::*__pf)(_Arg)) : _M_f(__pf) { } _Ret operator()(_Tp* __p, _Arg __x) const { return (__p->*_M_f)(__x); } private: _Ret (_Tp::*_M_f)(_Arg); }; /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class const_mem_fun1_t : public binary_function { public: explicit const_mem_fun1_t(_Ret (_Tp::*__pf)(_Arg) const) : _M_f(__pf) { } _Ret operator()(const _Tp* __p, _Arg __x) const { return (__p->*_M_f)(__x); } private: _Ret (_Tp::*_M_f)(_Arg) const; }; /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class mem_fun1_ref_t : public binary_function<_Tp, _Arg, _Ret> { public: explicit mem_fun1_ref_t(_Ret (_Tp::*__pf)(_Arg)) : _M_f(__pf) { } _Ret operator()(_Tp& __r, _Arg __x) const { return (__r.*_M_f)(__x); } private: _Ret (_Tp::*_M_f)(_Arg); }; /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class const_mem_fun1_ref_t : public binary_function<_Tp, _Arg, _Ret> { public: explicit const_mem_fun1_ref_t(_Ret (_Tp::*__pf)(_Arg) const) : _M_f(__pf) { } _Ret operator()(const _Tp& __r, _Arg __x) const { return (__r.*_M_f)(__x); } private: _Ret (_Tp::*_M_f)(_Arg) const; }; // Mem_fun adaptor helper functions. There are only two: // mem_fun and mem_fun_ref. template inline mem_fun_t<_Ret, _Tp> mem_fun(_Ret (_Tp::*__f)()) { return mem_fun_t<_Ret, _Tp>(__f); } template inline const_mem_fun_t<_Ret, _Tp> mem_fun(_Ret (_Tp::*__f)() const) { return const_mem_fun_t<_Ret, _Tp>(__f); } template inline mem_fun_ref_t<_Ret, _Tp> mem_fun_ref(_Ret (_Tp::*__f)()) { return mem_fun_ref_t<_Ret, _Tp>(__f); } template inline const_mem_fun_ref_t<_Ret, _Tp> mem_fun_ref(_Ret (_Tp::*__f)() const) { return const_mem_fun_ref_t<_Ret, _Tp>(__f); } template inline mem_fun1_t<_Ret, _Tp, _Arg> mem_fun(_Ret (_Tp::*__f)(_Arg)) { return mem_fun1_t<_Ret, _Tp, _Arg>(__f); } template inline const_mem_fun1_t<_Ret, _Tp, _Arg> mem_fun(_Ret (_Tp::*__f)(_Arg) const) { return const_mem_fun1_t<_Ret, _Tp, _Arg>(__f); } template inline mem_fun1_ref_t<_Ret, _Tp, _Arg> mem_fun_ref(_Ret (_Tp::*__f)(_Arg)) { return mem_fun1_ref_t<_Ret, _Tp, _Arg>(__f); } template inline const_mem_fun1_ref_t<_Ret, _Tp, _Arg> mem_fun_ref(_Ret (_Tp::*__f)(_Arg) const) { return const_mem_fun1_ref_t<_Ret, _Tp, _Arg>(__f); } /** @} */ _GLIBCXX_END_NAMESPACE_VERSION } // namespace #if (__cplusplus < 201103L) || _GLIBCXX_USE_DEPRECATED # include #endif #endif /* _STL_FUNCTION_H */ PK!6^ NN8/bits/stl_heap.hnu[// Heap implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * Copyright (c) 1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_heap.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{queue} */ #ifndef _STL_HEAP_H #define _STL_HEAP_H 1 #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup heap_algorithms Heap * @ingroup sorting_algorithms */ template _Distance __is_heap_until(_RandomAccessIterator __first, _Distance __n, _Compare& __comp) { _Distance __parent = 0; for (_Distance __child = 1; __child < __n; ++__child) { if (__comp(__first + __parent, __first + __child)) return __child; if ((__child & 1) == 0) ++__parent; } return __n; } // __is_heap, a predicate testing whether or not a range is a heap. // This function is an extension, not part of the C++ standard. template inline bool __is_heap(_RandomAccessIterator __first, _Distance __n) { __gnu_cxx::__ops::_Iter_less_iter __comp; return std::__is_heap_until(__first, __n, __comp) == __n; } template inline bool __is_heap(_RandomAccessIterator __first, _Compare __comp, _Distance __n) { typedef __decltype(__comp) _Cmp; __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp)); return std::__is_heap_until(__first, __n, __cmp) == __n; } template inline bool __is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { return std::__is_heap(__first, std::distance(__first, __last)); } template inline bool __is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { return std::__is_heap(__first, _GLIBCXX_MOVE(__comp), std::distance(__first, __last)); } // Heap-manipulation functions: push_heap, pop_heap, make_heap, sort_heap, // + is_heap and is_heap_until in C++0x. template void __push_heap(_RandomAccessIterator __first, _Distance __holeIndex, _Distance __topIndex, _Tp __value, _Compare& __comp) { _Distance __parent = (__holeIndex - 1) / 2; while (__holeIndex > __topIndex && __comp(__first + __parent, __value)) { *(__first + __holeIndex) = _GLIBCXX_MOVE(*(__first + __parent)); __holeIndex = __parent; __parent = (__holeIndex - 1) / 2; } *(__first + __holeIndex) = _GLIBCXX_MOVE(__value); } /** * @brief Push an element onto a heap. * @param __first Start of heap. * @param __last End of heap + element. * @ingroup heap_algorithms * * This operation pushes the element at last-1 onto the valid heap * over the range [__first,__last-1). After completion, * [__first,__last) is a valid heap. */ template inline void push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { typedef typename iterator_traits<_RandomAccessIterator>::value_type _ValueType; typedef typename iterator_traits<_RandomAccessIterator>::difference_type _DistanceType; // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept<_ValueType>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); __glibcxx_requires_heap(__first, __last - 1); __gnu_cxx::__ops::_Iter_less_val __comp; _ValueType __value = _GLIBCXX_MOVE(*(__last - 1)); std::__push_heap(__first, _DistanceType((__last - __first) - 1), _DistanceType(0), _GLIBCXX_MOVE(__value), __comp); } /** * @brief Push an element onto a heap using comparison functor. * @param __first Start of heap. * @param __last End of heap + element. * @param __comp Comparison functor. * @ingroup heap_algorithms * * This operation pushes the element at __last-1 onto the valid * heap over the range [__first,__last-1). After completion, * [__first,__last) is a valid heap. Compare operations are * performed using comp. */ template inline void push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { typedef typename iterator_traits<_RandomAccessIterator>::value_type _ValueType; typedef typename iterator_traits<_RandomAccessIterator>::difference_type _DistanceType; // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); __glibcxx_requires_heap_pred(__first, __last - 1, __comp); __decltype(__gnu_cxx::__ops::__iter_comp_val(_GLIBCXX_MOVE(__comp))) __cmp(_GLIBCXX_MOVE(__comp)); _ValueType __value = _GLIBCXX_MOVE(*(__last - 1)); std::__push_heap(__first, _DistanceType((__last - __first) - 1), _DistanceType(0), _GLIBCXX_MOVE(__value), __cmp); } template void __adjust_heap(_RandomAccessIterator __first, _Distance __holeIndex, _Distance __len, _Tp __value, _Compare __comp) { const _Distance __topIndex = __holeIndex; _Distance __secondChild = __holeIndex; while (__secondChild < (__len - 1) / 2) { __secondChild = 2 * (__secondChild + 1); if (__comp(__first + __secondChild, __first + (__secondChild - 1))) __secondChild--; *(__first + __holeIndex) = _GLIBCXX_MOVE(*(__first + __secondChild)); __holeIndex = __secondChild; } if ((__len & 1) == 0 && __secondChild == (__len - 2) / 2) { __secondChild = 2 * (__secondChild + 1); *(__first + __holeIndex) = _GLIBCXX_MOVE(*(__first + (__secondChild - 1))); __holeIndex = __secondChild - 1; } __decltype(__gnu_cxx::__ops::__iter_comp_val(_GLIBCXX_MOVE(__comp))) __cmp(_GLIBCXX_MOVE(__comp)); std::__push_heap(__first, __holeIndex, __topIndex, _GLIBCXX_MOVE(__value), __cmp); } template inline void __pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _RandomAccessIterator __result, _Compare& __comp) { typedef typename iterator_traits<_RandomAccessIterator>::value_type _ValueType; typedef typename iterator_traits<_RandomAccessIterator>::difference_type _DistanceType; _ValueType __value = _GLIBCXX_MOVE(*__result); *__result = _GLIBCXX_MOVE(*__first); std::__adjust_heap(__first, _DistanceType(0), _DistanceType(__last - __first), _GLIBCXX_MOVE(__value), __comp); } /** * @brief Pop an element off a heap. * @param __first Start of heap. * @param __last End of heap. * @pre [__first, __last) is a valid, non-empty range. * @ingroup heap_algorithms * * This operation pops the top of the heap. The elements __first * and __last-1 are swapped and [__first,__last-1) is made into a * heap. */ template inline void pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_non_empty_range(__first, __last); __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); __glibcxx_requires_heap(__first, __last); if (__last - __first > 1) { --__last; __gnu_cxx::__ops::_Iter_less_iter __comp; std::__pop_heap(__first, __last, __last, __comp); } } /** * @brief Pop an element off a heap using comparison functor. * @param __first Start of heap. * @param __last End of heap. * @param __comp Comparison functor to use. * @ingroup heap_algorithms * * This operation pops the top of the heap. The elements __first * and __last-1 are swapped and [__first,__last-1) is made into a * heap. Comparisons are made using comp. */ template inline void pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); __glibcxx_requires_non_empty_range(__first, __last); __glibcxx_requires_heap_pred(__first, __last, __comp); if (__last - __first > 1) { typedef __decltype(__comp) _Cmp; __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp)); --__last; std::__pop_heap(__first, __last, __last, __cmp); } } template void __make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare& __comp) { typedef typename iterator_traits<_RandomAccessIterator>::value_type _ValueType; typedef typename iterator_traits<_RandomAccessIterator>::difference_type _DistanceType; if (__last - __first < 2) return; const _DistanceType __len = __last - __first; _DistanceType __parent = (__len - 2) / 2; while (true) { _ValueType __value = _GLIBCXX_MOVE(*(__first + __parent)); std::__adjust_heap(__first, __parent, __len, _GLIBCXX_MOVE(__value), __comp); if (__parent == 0) return; __parent--; } } /** * @brief Construct a heap over a range. * @param __first Start of heap. * @param __last End of heap. * @ingroup heap_algorithms * * This operation makes the elements in [__first,__last) into a heap. */ template inline void make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); __gnu_cxx::__ops::_Iter_less_iter __comp; std::__make_heap(__first, __last, __comp); } /** * @brief Construct a heap over a range using comparison functor. * @param __first Start of heap. * @param __last End of heap. * @param __comp Comparison functor to use. * @ingroup heap_algorithms * * This operation makes the elements in [__first,__last) into a heap. * Comparisons are made using __comp. */ template inline void make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); typedef __decltype(__comp) _Cmp; __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp)); std::__make_heap(__first, __last, __cmp); } template void __sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare& __comp) { while (__last - __first > 1) { --__last; std::__pop_heap(__first, __last, __last, __comp); } } /** * @brief Sort a heap. * @param __first Start of heap. * @param __last End of heap. * @ingroup heap_algorithms * * This operation sorts the valid heap in the range [__first,__last). */ template inline void sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); __glibcxx_requires_heap(__first, __last); __gnu_cxx::__ops::_Iter_less_iter __comp; std::__sort_heap(__first, __last, __comp); } /** * @brief Sort a heap using comparison functor. * @param __first Start of heap. * @param __last End of heap. * @param __comp Comparison functor to use. * @ingroup heap_algorithms * * This operation sorts the valid heap in the range [__first,__last). * Comparisons are made using __comp. */ template inline void sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); __glibcxx_requires_heap_pred(__first, __last, __comp); typedef __decltype(__comp) _Cmp; __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp)); std::__sort_heap(__first, __last, __cmp); } #if __cplusplus >= 201103L /** * @brief Search the end of a heap. * @param __first Start of range. * @param __last End of range. * @return An iterator pointing to the first element not in the heap. * @ingroup heap_algorithms * * This operation returns the last iterator i in [__first, __last) for which * the range [__first, i) is a heap. */ template inline _RandomAccessIterator is_heap_until(_RandomAccessIterator __first, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); __gnu_cxx::__ops::_Iter_less_iter __comp; return __first + std::__is_heap_until(__first, std::distance(__first, __last), __comp); } /** * @brief Search the end of a heap using comparison functor. * @param __first Start of range. * @param __last End of range. * @param __comp Comparison functor to use. * @return An iterator pointing to the first element not in the heap. * @ingroup heap_algorithms * * This operation returns the last iterator i in [__first, __last) for which * the range [__first, i) is a heap. Comparisons are made using __comp. */ template inline _RandomAccessIterator is_heap_until(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); typedef __decltype(__comp) _Cmp; __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp)); return __first + std::__is_heap_until(__first, std::distance(__first, __last), __cmp); } /** * @brief Determines whether a range is a heap. * @param __first Start of range. * @param __last End of range. * @return True if range is a heap, false otherwise. * @ingroup heap_algorithms */ template inline bool is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { return std::is_heap_until(__first, __last) == __last; } /** * @brief Determines whether a range is a heap using comparison functor. * @param __first Start of range. * @param __last End of range. * @param __comp Comparison functor to use. * @return True if range is a heap, false otherwise. * @ingroup heap_algorithms */ template inline bool is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); const auto __dist = std::distance(__first, __last); typedef __decltype(__comp) _Cmp; __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp)); return std::__is_heap_until(__first, __dist, __cmp) == __dist; } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _STL_HEAP_H */ PK!338/bits/stl_iterator.hnu[// Iterators -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996-1998 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_iterator.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iterator} * * This file implements reverse_iterator, back_insert_iterator, * front_insert_iterator, insert_iterator, __normal_iterator, and their * supporting functions and overloaded operators. */ #ifndef _STL_ITERATOR_H #define _STL_ITERATOR_H 1 #include #include #include #include #if __cplusplus > 201402L # define __cpp_lib_array_constexpr 201603 #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup iterators * @{ */ // 24.4.1 Reverse iterators /** * Bidirectional and random access iterators have corresponding reverse * %iterator adaptors that iterate through the data structure in the * opposite direction. They have the same signatures as the corresponding * iterators. The fundamental relation between a reverse %iterator and its * corresponding %iterator @c i is established by the identity: * @code * &*(reverse_iterator(i)) == &*(i - 1) * @endcode * * This mapping is dictated by the fact that while there is always a * pointer past the end of an array, there might not be a valid pointer * before the beginning of an array. [24.4.1]/1,2 * * Reverse iterators can be tricky and surprising at first. Their * semantics make sense, however, and the trickiness is a side effect of * the requirement that the iterators must be safe. */ template class reverse_iterator : public iterator::iterator_category, typename iterator_traits<_Iterator>::value_type, typename iterator_traits<_Iterator>::difference_type, typename iterator_traits<_Iterator>::pointer, typename iterator_traits<_Iterator>::reference> { protected: _Iterator current; typedef iterator_traits<_Iterator> __traits_type; public: typedef _Iterator iterator_type; typedef typename __traits_type::difference_type difference_type; typedef typename __traits_type::pointer pointer; typedef typename __traits_type::reference reference; /** * The default constructor value-initializes member @p current. * If it is a pointer, that means it is zero-initialized. */ // _GLIBCXX_RESOLVE_LIB_DEFECTS // 235 No specification of default ctor for reverse_iterator // 1012. reverse_iterator default ctor should value initialize _GLIBCXX17_CONSTEXPR reverse_iterator() : current() { } /** * This %iterator will move in the opposite direction that @p x does. */ explicit _GLIBCXX17_CONSTEXPR reverse_iterator(iterator_type __x) : current(__x) { } /** * The copy constructor is normal. */ _GLIBCXX17_CONSTEXPR reverse_iterator(const reverse_iterator& __x) : current(__x.current) { } /** * A %reverse_iterator across other types can be copied if the * underlying %iterator can be converted to the type of @c current. */ template _GLIBCXX17_CONSTEXPR reverse_iterator(const reverse_iterator<_Iter>& __x) : current(__x.base()) { } /** * @return @c current, the %iterator used for underlying work. */ _GLIBCXX17_CONSTEXPR iterator_type base() const { return current; } /** * @return A reference to the value at @c --current * * This requires that @c --current is dereferenceable. * * @warning This implementation requires that for an iterator of the * underlying iterator type, @c x, a reference obtained by * @c *x remains valid after @c x has been modified or * destroyed. This is a bug: http://gcc.gnu.org/PR51823 */ _GLIBCXX17_CONSTEXPR reference operator*() const { _Iterator __tmp = current; return *--__tmp; } /** * @return A pointer to the value at @c --current * * This requires that @c --current is dereferenceable. */ // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2188. Reverse iterator does not fully support targets that overload & _GLIBCXX17_CONSTEXPR pointer operator->() const { return std::__addressof(operator*()); } /** * @return @c *this * * Decrements the underlying iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator& operator++() { --current; return *this; } /** * @return The original value of @c *this * * Decrements the underlying iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator operator++(int) { reverse_iterator __tmp = *this; --current; return __tmp; } /** * @return @c *this * * Increments the underlying iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator& operator--() { ++current; return *this; } /** * @return A reverse_iterator with the previous value of @c *this * * Increments the underlying iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator operator--(int) { reverse_iterator __tmp = *this; ++current; return __tmp; } /** * @return A reverse_iterator that refers to @c current - @a __n * * The underlying iterator must be a Random Access Iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator operator+(difference_type __n) const { return reverse_iterator(current - __n); } /** * @return *this * * Moves the underlying iterator backwards @a __n steps. * The underlying iterator must be a Random Access Iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator& operator+=(difference_type __n) { current -= __n; return *this; } /** * @return A reverse_iterator that refers to @c current - @a __n * * The underlying iterator must be a Random Access Iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator operator-(difference_type __n) const { return reverse_iterator(current + __n); } /** * @return *this * * Moves the underlying iterator forwards @a __n steps. * The underlying iterator must be a Random Access Iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator& operator-=(difference_type __n) { current += __n; return *this; } /** * @return The value at @c current - @a __n - 1 * * The underlying iterator must be a Random Access Iterator. */ _GLIBCXX17_CONSTEXPR reference operator[](difference_type __n) const { return *(*this + __n); } }; //@{ /** * @param __x A %reverse_iterator. * @param __y A %reverse_iterator. * @return A simple bool. * * Reverse iterators forward many operations to their underlying base() * iterators. Others are implemented in terms of one another. * */ template inline _GLIBCXX17_CONSTEXPR bool operator==(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) { return __x.base() == __y.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator<(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) { return __y.base() < __x.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator!=(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) { return !(__x == __y); } template inline _GLIBCXX17_CONSTEXPR bool operator>(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) { return __y < __x; } template inline _GLIBCXX17_CONSTEXPR bool operator<=(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) { return !(__y < __x); } template inline _GLIBCXX17_CONSTEXPR bool operator>=(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) { return !(__x < __y); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 280. Comparison of reverse_iterator to const reverse_iterator. template inline _GLIBCXX17_CONSTEXPR bool operator==(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) { return __x.base() == __y.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator<(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) { return __y.base() < __x.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator!=(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) { return !(__x == __y); } template inline _GLIBCXX17_CONSTEXPR bool operator>(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) { return __y < __x; } template inline _GLIBCXX17_CONSTEXPR bool operator<=(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) { return !(__y < __x); } template inline _GLIBCXX17_CONSTEXPR bool operator>=(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) { return !(__x < __y); } //@} #if __cplusplus < 201103L template inline typename reverse_iterator<_Iterator>::difference_type operator-(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) { return __y.base() - __x.base(); } template inline typename reverse_iterator<_IteratorL>::difference_type operator-(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) { return __y.base() - __x.base(); } #else // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 685. reverse_iterator/move_iterator difference has invalid signatures template inline _GLIBCXX17_CONSTEXPR auto operator-(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) -> decltype(__y.base() - __x.base()) { return __y.base() - __x.base(); } #endif template inline _GLIBCXX17_CONSTEXPR reverse_iterator<_Iterator> operator+(typename reverse_iterator<_Iterator>::difference_type __n, const reverse_iterator<_Iterator>& __x) { return reverse_iterator<_Iterator>(__x.base() - __n); } #if __cplusplus >= 201103L // Same as C++14 make_reverse_iterator but used in C++03 mode too. template inline _GLIBCXX17_CONSTEXPR reverse_iterator<_Iterator> __make_reverse_iterator(_Iterator __i) { return reverse_iterator<_Iterator>(__i); } # if __cplusplus > 201103L # define __cpp_lib_make_reverse_iterator 201402 // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 2285. make_reverse_iterator /// Generator function for reverse_iterator. template inline _GLIBCXX17_CONSTEXPR reverse_iterator<_Iterator> make_reverse_iterator(_Iterator __i) { return reverse_iterator<_Iterator>(__i); } # endif #endif #if __cplusplus >= 201103L template auto __niter_base(reverse_iterator<_Iterator> __it) -> decltype(__make_reverse_iterator(__niter_base(__it.base()))) { return __make_reverse_iterator(__niter_base(__it.base())); } template struct __is_move_iterator > : __is_move_iterator<_Iterator> { }; template auto __miter_base(reverse_iterator<_Iterator> __it) -> decltype(__make_reverse_iterator(__miter_base(__it.base()))) { return __make_reverse_iterator(__miter_base(__it.base())); } #endif // 24.4.2.2.1 back_insert_iterator /** * @brief Turns assignment into insertion. * * These are output iterators, constructed from a container-of-T. * Assigning a T to the iterator appends it to the container using * push_back. * * Tip: Using the back_inserter function to create these iterators can * save typing. */ template class back_insert_iterator : public iterator { protected: _Container* container; public: /// A nested typedef for the type of whatever container you used. typedef _Container container_type; /// The only way to create this %iterator is with a container. explicit back_insert_iterator(_Container& __x) : container(std::__addressof(__x)) { } /** * @param __value An instance of whatever type * container_type::const_reference is; presumably a * reference-to-const T for container. * @return This %iterator, for chained operations. * * This kind of %iterator doesn't really have a @a position in the * container (you can think of the position as being permanently at * the end, if you like). Assigning a value to the %iterator will * always append the value to the end of the container. */ #if __cplusplus < 201103L back_insert_iterator& operator=(typename _Container::const_reference __value) { container->push_back(__value); return *this; } #else back_insert_iterator& operator=(const typename _Container::value_type& __value) { container->push_back(__value); return *this; } back_insert_iterator& operator=(typename _Container::value_type&& __value) { container->push_back(std::move(__value)); return *this; } #endif /// Simply returns *this. back_insert_iterator& operator*() { return *this; } /// Simply returns *this. (This %iterator does not @a move.) back_insert_iterator& operator++() { return *this; } /// Simply returns *this. (This %iterator does not @a move.) back_insert_iterator operator++(int) { return *this; } }; /** * @param __x A container of arbitrary type. * @return An instance of back_insert_iterator working on @p __x. * * This wrapper function helps in creating back_insert_iterator instances. * Typing the name of the %iterator requires knowing the precise full * type of the container, which can be tedious and impedes generic * programming. Using this function lets you take advantage of automatic * template parameter deduction, making the compiler match the correct * types for you. */ template inline back_insert_iterator<_Container> back_inserter(_Container& __x) { return back_insert_iterator<_Container>(__x); } /** * @brief Turns assignment into insertion. * * These are output iterators, constructed from a container-of-T. * Assigning a T to the iterator prepends it to the container using * push_front. * * Tip: Using the front_inserter function to create these iterators can * save typing. */ template class front_insert_iterator : public iterator { protected: _Container* container; public: /// A nested typedef for the type of whatever container you used. typedef _Container container_type; /// The only way to create this %iterator is with a container. explicit front_insert_iterator(_Container& __x) : container(std::__addressof(__x)) { } /** * @param __value An instance of whatever type * container_type::const_reference is; presumably a * reference-to-const T for container. * @return This %iterator, for chained operations. * * This kind of %iterator doesn't really have a @a position in the * container (you can think of the position as being permanently at * the front, if you like). Assigning a value to the %iterator will * always prepend the value to the front of the container. */ #if __cplusplus < 201103L front_insert_iterator& operator=(typename _Container::const_reference __value) { container->push_front(__value); return *this; } #else front_insert_iterator& operator=(const typename _Container::value_type& __value) { container->push_front(__value); return *this; } front_insert_iterator& operator=(typename _Container::value_type&& __value) { container->push_front(std::move(__value)); return *this; } #endif /// Simply returns *this. front_insert_iterator& operator*() { return *this; } /// Simply returns *this. (This %iterator does not @a move.) front_insert_iterator& operator++() { return *this; } /// Simply returns *this. (This %iterator does not @a move.) front_insert_iterator operator++(int) { return *this; } }; /** * @param __x A container of arbitrary type. * @return An instance of front_insert_iterator working on @p x. * * This wrapper function helps in creating front_insert_iterator instances. * Typing the name of the %iterator requires knowing the precise full * type of the container, which can be tedious and impedes generic * programming. Using this function lets you take advantage of automatic * template parameter deduction, making the compiler match the correct * types for you. */ template inline front_insert_iterator<_Container> front_inserter(_Container& __x) { return front_insert_iterator<_Container>(__x); } /** * @brief Turns assignment into insertion. * * These are output iterators, constructed from a container-of-T. * Assigning a T to the iterator inserts it in the container at the * %iterator's position, rather than overwriting the value at that * position. * * (Sequences will actually insert a @e copy of the value before the * %iterator's position.) * * Tip: Using the inserter function to create these iterators can * save typing. */ template class insert_iterator : public iterator { protected: _Container* container; typename _Container::iterator iter; public: /// A nested typedef for the type of whatever container you used. typedef _Container container_type; /** * The only way to create this %iterator is with a container and an * initial position (a normal %iterator into the container). */ insert_iterator(_Container& __x, typename _Container::iterator __i) : container(std::__addressof(__x)), iter(__i) {} /** * @param __value An instance of whatever type * container_type::const_reference is; presumably a * reference-to-const T for container. * @return This %iterator, for chained operations. * * This kind of %iterator maintains its own position in the * container. Assigning a value to the %iterator will insert the * value into the container at the place before the %iterator. * * The position is maintained such that subsequent assignments will * insert values immediately after one another. For example, * @code * // vector v contains A and Z * * insert_iterator i (v, ++v.begin()); * i = 1; * i = 2; * i = 3; * * // vector v contains A, 1, 2, 3, and Z * @endcode */ #if __cplusplus < 201103L insert_iterator& operator=(typename _Container::const_reference __value) { iter = container->insert(iter, __value); ++iter; return *this; } #else insert_iterator& operator=(const typename _Container::value_type& __value) { iter = container->insert(iter, __value); ++iter; return *this; } insert_iterator& operator=(typename _Container::value_type&& __value) { iter = container->insert(iter, std::move(__value)); ++iter; return *this; } #endif /// Simply returns *this. insert_iterator& operator*() { return *this; } /// Simply returns *this. (This %iterator does not @a move.) insert_iterator& operator++() { return *this; } /// Simply returns *this. (This %iterator does not @a move.) insert_iterator& operator++(int) { return *this; } }; /** * @param __x A container of arbitrary type. * @param __i An iterator into the container. * @return An instance of insert_iterator working on @p __x. * * This wrapper function helps in creating insert_iterator instances. * Typing the name of the %iterator requires knowing the precise full * type of the container, which can be tedious and impedes generic * programming. Using this function lets you take advantage of automatic * template parameter deduction, making the compiler match the correct * types for you. */ template inline insert_iterator<_Container> inserter(_Container& __x, _Iterator __i) { return insert_iterator<_Container>(__x, typename _Container::iterator(__i)); } // @} group iterators _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // This iterator adapter is @a normal in the sense that it does not // change the semantics of any of the operators of its iterator // parameter. Its primary purpose is to convert an iterator that is // not a class, e.g. a pointer, into an iterator that is a class. // The _Container parameter exists solely so that different containers // using this template can instantiate different types, even if the // _Iterator parameter is the same. using std::iterator_traits; using std::iterator; template class __normal_iterator { protected: _Iterator _M_current; typedef iterator_traits<_Iterator> __traits_type; public: typedef _Iterator iterator_type; typedef typename __traits_type::iterator_category iterator_category; typedef typename __traits_type::value_type value_type; typedef typename __traits_type::difference_type difference_type; typedef typename __traits_type::reference reference; typedef typename __traits_type::pointer pointer; _GLIBCXX_CONSTEXPR __normal_iterator() _GLIBCXX_NOEXCEPT : _M_current(_Iterator()) { } explicit __normal_iterator(const _Iterator& __i) _GLIBCXX_NOEXCEPT : _M_current(__i) { } // Allow iterator to const_iterator conversion template __normal_iterator(const __normal_iterator<_Iter, typename __enable_if< (std::__are_same<_Iter, typename _Container::pointer>::__value), _Container>::__type>& __i) _GLIBCXX_NOEXCEPT : _M_current(__i.base()) { } // Forward iterator requirements reference operator*() const _GLIBCXX_NOEXCEPT { return *_M_current; } pointer operator->() const _GLIBCXX_NOEXCEPT { return _M_current; } __normal_iterator& operator++() _GLIBCXX_NOEXCEPT { ++_M_current; return *this; } __normal_iterator operator++(int) _GLIBCXX_NOEXCEPT { return __normal_iterator(_M_current++); } // Bidirectional iterator requirements __normal_iterator& operator--() _GLIBCXX_NOEXCEPT { --_M_current; return *this; } __normal_iterator operator--(int) _GLIBCXX_NOEXCEPT { return __normal_iterator(_M_current--); } // Random access iterator requirements reference operator[](difference_type __n) const _GLIBCXX_NOEXCEPT { return _M_current[__n]; } __normal_iterator& operator+=(difference_type __n) _GLIBCXX_NOEXCEPT { _M_current += __n; return *this; } __normal_iterator operator+(difference_type __n) const _GLIBCXX_NOEXCEPT { return __normal_iterator(_M_current + __n); } __normal_iterator& operator-=(difference_type __n) _GLIBCXX_NOEXCEPT { _M_current -= __n; return *this; } __normal_iterator operator-(difference_type __n) const _GLIBCXX_NOEXCEPT { return __normal_iterator(_M_current - __n); } const _Iterator& base() const _GLIBCXX_NOEXCEPT { return _M_current; } }; // Note: In what follows, the left- and right-hand-side iterators are // allowed to vary in types (conceptually in cv-qualification) so that // comparison between cv-qualified and non-cv-qualified iterators be // valid. However, the greedy and unfriendly operators in std::rel_ops // will make overload resolution ambiguous (when in scope) if we don't // provide overloads whose operands are of the same type. Can someone // remind me what generic programming is about? -- Gaby // Forward iterator requirements template inline bool operator==(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() == __rhs.base(); } template inline bool operator==(const __normal_iterator<_Iterator, _Container>& __lhs, const __normal_iterator<_Iterator, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() == __rhs.base(); } template inline bool operator!=(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() != __rhs.base(); } template inline bool operator!=(const __normal_iterator<_Iterator, _Container>& __lhs, const __normal_iterator<_Iterator, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() != __rhs.base(); } // Random access iterator requirements template inline bool operator<(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() < __rhs.base(); } template inline bool operator<(const __normal_iterator<_Iterator, _Container>& __lhs, const __normal_iterator<_Iterator, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() < __rhs.base(); } template inline bool operator>(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() > __rhs.base(); } template inline bool operator>(const __normal_iterator<_Iterator, _Container>& __lhs, const __normal_iterator<_Iterator, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() > __rhs.base(); } template inline bool operator<=(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() <= __rhs.base(); } template inline bool operator<=(const __normal_iterator<_Iterator, _Container>& __lhs, const __normal_iterator<_Iterator, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() <= __rhs.base(); } template inline bool operator>=(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() >= __rhs.base(); } template inline bool operator>=(const __normal_iterator<_Iterator, _Container>& __lhs, const __normal_iterator<_Iterator, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() >= __rhs.base(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // According to the resolution of DR179 not only the various comparison // operators but also operator- must accept mixed iterator/const_iterator // parameters. template #if __cplusplus >= 201103L // DR 685. inline auto operator-(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) noexcept -> decltype(__lhs.base() - __rhs.base()) #else inline typename __normal_iterator<_IteratorL, _Container>::difference_type operator-(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) #endif { return __lhs.base() - __rhs.base(); } template inline typename __normal_iterator<_Iterator, _Container>::difference_type operator-(const __normal_iterator<_Iterator, _Container>& __lhs, const __normal_iterator<_Iterator, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() - __rhs.base(); } template inline __normal_iterator<_Iterator, _Container> operator+(typename __normal_iterator<_Iterator, _Container>::difference_type __n, const __normal_iterator<_Iterator, _Container>& __i) _GLIBCXX_NOEXCEPT { return __normal_iterator<_Iterator, _Container>(__i.base() + __n); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template _Iterator __niter_base(__gnu_cxx::__normal_iterator<_Iterator, _Container> __it) { return __it.base(); } #if __cplusplus >= 201103L /** * @addtogroup iterators * @{ */ // 24.4.3 Move iterators /** * Class template move_iterator is an iterator adapter with the same * behavior as the underlying iterator except that its dereference * operator implicitly converts the value returned by the underlying * iterator's dereference operator to an rvalue reference. Some * generic algorithms can be called with move iterators to replace * copying with moving. */ template class move_iterator { protected: _Iterator _M_current; typedef iterator_traits<_Iterator> __traits_type; typedef typename __traits_type::reference __base_ref; public: typedef _Iterator iterator_type; typedef typename __traits_type::iterator_category iterator_category; typedef typename __traits_type::value_type value_type; typedef typename __traits_type::difference_type difference_type; // NB: DR 680. typedef _Iterator pointer; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2106. move_iterator wrapping iterators returning prvalues typedef typename conditional::value, typename remove_reference<__base_ref>::type&&, __base_ref>::type reference; _GLIBCXX17_CONSTEXPR move_iterator() : _M_current() { } explicit _GLIBCXX17_CONSTEXPR move_iterator(iterator_type __i) : _M_current(__i) { } template _GLIBCXX17_CONSTEXPR move_iterator(const move_iterator<_Iter>& __i) : _M_current(__i.base()) { } _GLIBCXX17_CONSTEXPR iterator_type base() const { return _M_current; } _GLIBCXX17_CONSTEXPR reference operator*() const { return static_cast(*_M_current); } _GLIBCXX17_CONSTEXPR pointer operator->() const { return _M_current; } _GLIBCXX17_CONSTEXPR move_iterator& operator++() { ++_M_current; return *this; } _GLIBCXX17_CONSTEXPR move_iterator operator++(int) { move_iterator __tmp = *this; ++_M_current; return __tmp; } _GLIBCXX17_CONSTEXPR move_iterator& operator--() { --_M_current; return *this; } _GLIBCXX17_CONSTEXPR move_iterator operator--(int) { move_iterator __tmp = *this; --_M_current; return __tmp; } _GLIBCXX17_CONSTEXPR move_iterator operator+(difference_type __n) const { return move_iterator(_M_current + __n); } _GLIBCXX17_CONSTEXPR move_iterator& operator+=(difference_type __n) { _M_current += __n; return *this; } _GLIBCXX17_CONSTEXPR move_iterator operator-(difference_type __n) const { return move_iterator(_M_current - __n); } _GLIBCXX17_CONSTEXPR move_iterator& operator-=(difference_type __n) { _M_current -= __n; return *this; } _GLIBCXX17_CONSTEXPR reference operator[](difference_type __n) const { return std::move(_M_current[__n]); } }; // Note: See __normal_iterator operators note from Gaby to understand // why there are always 2 versions for most of the move_iterator // operators. template inline _GLIBCXX17_CONSTEXPR bool operator==(const move_iterator<_IteratorL>& __x, const move_iterator<_IteratorR>& __y) { return __x.base() == __y.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator==(const move_iterator<_Iterator>& __x, const move_iterator<_Iterator>& __y) { return __x.base() == __y.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator!=(const move_iterator<_IteratorL>& __x, const move_iterator<_IteratorR>& __y) { return !(__x == __y); } template inline _GLIBCXX17_CONSTEXPR bool operator!=(const move_iterator<_Iterator>& __x, const move_iterator<_Iterator>& __y) { return !(__x == __y); } template inline _GLIBCXX17_CONSTEXPR bool operator<(const move_iterator<_IteratorL>& __x, const move_iterator<_IteratorR>& __y) { return __x.base() < __y.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator<(const move_iterator<_Iterator>& __x, const move_iterator<_Iterator>& __y) { return __x.base() < __y.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator<=(const move_iterator<_IteratorL>& __x, const move_iterator<_IteratorR>& __y) { return !(__y < __x); } template inline _GLIBCXX17_CONSTEXPR bool operator<=(const move_iterator<_Iterator>& __x, const move_iterator<_Iterator>& __y) { return !(__y < __x); } template inline _GLIBCXX17_CONSTEXPR bool operator>(const move_iterator<_IteratorL>& __x, const move_iterator<_IteratorR>& __y) { return __y < __x; } template inline _GLIBCXX17_CONSTEXPR bool operator>(const move_iterator<_Iterator>& __x, const move_iterator<_Iterator>& __y) { return __y < __x; } template inline _GLIBCXX17_CONSTEXPR bool operator>=(const move_iterator<_IteratorL>& __x, const move_iterator<_IteratorR>& __y) { return !(__x < __y); } template inline _GLIBCXX17_CONSTEXPR bool operator>=(const move_iterator<_Iterator>& __x, const move_iterator<_Iterator>& __y) { return !(__x < __y); } // DR 685. template inline _GLIBCXX17_CONSTEXPR auto operator-(const move_iterator<_IteratorL>& __x, const move_iterator<_IteratorR>& __y) -> decltype(__x.base() - __y.base()) { return __x.base() - __y.base(); } template inline _GLIBCXX17_CONSTEXPR move_iterator<_Iterator> operator+(typename move_iterator<_Iterator>::difference_type __n, const move_iterator<_Iterator>& __x) { return __x + __n; } template inline _GLIBCXX17_CONSTEXPR move_iterator<_Iterator> make_move_iterator(_Iterator __i) { return move_iterator<_Iterator>(__i); } template::value_type>::value, _Iterator, move_iterator<_Iterator>>::type> inline _GLIBCXX17_CONSTEXPR _ReturnType __make_move_if_noexcept_iterator(_Iterator __i) { return _ReturnType(__i); } // Overload for pointers that matches std::move_if_noexcept more closely, // returning a constant iterator when we don't want to move. template::value, const _Tp*, move_iterator<_Tp*>>::type> inline _GLIBCXX17_CONSTEXPR _ReturnType __make_move_if_noexcept_iterator(_Tp* __i) { return _ReturnType(__i); } // @} group iterators template auto __niter_base(move_iterator<_Iterator> __it) -> decltype(make_move_iterator(__niter_base(__it.base()))) { return make_move_iterator(__niter_base(__it.base())); } template struct __is_move_iterator > { enum { __value = 1 }; typedef __true_type __type; }; template auto __miter_base(move_iterator<_Iterator> __it) -> decltype(__miter_base(__it.base())) { return __miter_base(__it.base()); } #define _GLIBCXX_MAKE_MOVE_ITERATOR(_Iter) std::make_move_iterator(_Iter) #define _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(_Iter) \ std::__make_move_if_noexcept_iterator(_Iter) #else #define _GLIBCXX_MAKE_MOVE_ITERATOR(_Iter) (_Iter) #define _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(_Iter) (_Iter) #endif // C++11 #if __cpp_deduction_guides >= 201606 // These helper traits are used for deduction guides // of associative containers. template using __iter_key_t = remove_const_t< typename iterator_traits<_InputIterator>::value_type::first_type>; template using __iter_val_t = typename iterator_traits<_InputIterator>::value_type::second_type; template struct pair; template using __iter_to_alloc_t = pair>, __iter_val_t<_InputIterator>>; #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #ifdef _GLIBCXX_DEBUG # include #endif #endif PK!() 8/bits/stl_iterator_base_funcs.hnu[// Functions used by iterators -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996-1998 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_iterator_base_funcs.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iterator} * * This file contains all of the general iterator-related utility * functions, such as distance() and advance(). */ #ifndef _STL_ITERATOR_BASE_FUNCS_H #define _STL_ITERATOR_BASE_FUNCS_H 1 #pragma GCC system_header #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER // Forward declaration for the overloads of __distance. template struct _List_iterator; template struct _List_const_iterator; _GLIBCXX_END_NAMESPACE_CONTAINER template inline _GLIBCXX14_CONSTEXPR typename iterator_traits<_InputIterator>::difference_type __distance(_InputIterator __first, _InputIterator __last, input_iterator_tag) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) typename iterator_traits<_InputIterator>::difference_type __n = 0; while (__first != __last) { ++__first; ++__n; } return __n; } template inline _GLIBCXX14_CONSTEXPR typename iterator_traits<_RandomAccessIterator>::difference_type __distance(_RandomAccessIterator __first, _RandomAccessIterator __last, random_access_iterator_tag) { // concept requirements __glibcxx_function_requires(_RandomAccessIteratorConcept< _RandomAccessIterator>) return __last - __first; } #if _GLIBCXX_USE_CXX11_ABI // Forward declaration because of the qualified call in distance. template ptrdiff_t __distance(_GLIBCXX_STD_C::_List_iterator<_Tp>, _GLIBCXX_STD_C::_List_iterator<_Tp>, input_iterator_tag); template ptrdiff_t __distance(_GLIBCXX_STD_C::_List_const_iterator<_Tp>, _GLIBCXX_STD_C::_List_const_iterator<_Tp>, input_iterator_tag); #endif /** * @brief A generalization of pointer arithmetic. * @param __first An input iterator. * @param __last An input iterator. * @return The distance between them. * * Returns @c n such that __first + n == __last. This requires * that @p __last must be reachable from @p __first. Note that @c * n may be negative. * * For random access iterators, this uses their @c + and @c - operations * and are constant time. For other %iterator classes they are linear time. */ template inline _GLIBCXX17_CONSTEXPR typename iterator_traits<_InputIterator>::difference_type distance(_InputIterator __first, _InputIterator __last) { // concept requirements -- taken care of in __distance return std::__distance(__first, __last, std::__iterator_category(__first)); } template inline _GLIBCXX14_CONSTEXPR void __advance(_InputIterator& __i, _Distance __n, input_iterator_tag) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_assert(__n >= 0); while (__n--) ++__i; } template inline _GLIBCXX14_CONSTEXPR void __advance(_BidirectionalIterator& __i, _Distance __n, bidirectional_iterator_tag) { // concept requirements __glibcxx_function_requires(_BidirectionalIteratorConcept< _BidirectionalIterator>) if (__n > 0) while (__n--) ++__i; else while (__n++) --__i; } template inline _GLIBCXX14_CONSTEXPR void __advance(_RandomAccessIterator& __i, _Distance __n, random_access_iterator_tag) { // concept requirements __glibcxx_function_requires(_RandomAccessIteratorConcept< _RandomAccessIterator>) if (__builtin_constant_p(__n) && __n == 1) ++__i; else if (__builtin_constant_p(__n) && __n == -1) --__i; else __i += __n; } /** * @brief A generalization of pointer arithmetic. * @param __i An input iterator. * @param __n The @a delta by which to change @p __i. * @return Nothing. * * This increments @p i by @p n. For bidirectional and random access * iterators, @p __n may be negative, in which case @p __i is decremented. * * For random access iterators, this uses their @c + and @c - operations * and are constant time. For other %iterator classes they are linear time. */ template inline _GLIBCXX17_CONSTEXPR void advance(_InputIterator& __i, _Distance __n) { // concept requirements -- taken care of in __advance typename iterator_traits<_InputIterator>::difference_type __d = __n; std::__advance(__i, __d, std::__iterator_category(__i)); } #if __cplusplus >= 201103L template inline _GLIBCXX17_CONSTEXPR _InputIterator next(_InputIterator __x, typename iterator_traits<_InputIterator>::difference_type __n = 1) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) std::advance(__x, __n); return __x; } template inline _GLIBCXX17_CONSTEXPR _BidirectionalIterator prev(_BidirectionalIterator __x, typename iterator_traits<_BidirectionalIterator>::difference_type __n = 1) { // concept requirements __glibcxx_function_requires(_BidirectionalIteratorConcept< _BidirectionalIterator>) std::advance(__x, -__n); return __x; } #endif // C++11 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _STL_ITERATOR_BASE_FUNCS_H */ PK!a~!! 8/bits/stl_iterator_base_types.hnu[// Types used in iterator implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996-1998 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_iterator_base_types.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iterator} * * This file contains all of the general iterator-related utility types, * such as iterator_traits and struct iterator. */ #ifndef _STL_ITERATOR_BASE_TYPES_H #define _STL_ITERATOR_BASE_TYPES_H 1 #pragma GCC system_header #include #if __cplusplus >= 201103L # include // For __void_t, is_convertible #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup iterators Iterators * Abstractions for uniform iterating through various underlying types. */ //@{ /** * @defgroup iterator_tags Iterator Tags * These are empty types, used to distinguish different iterators. The * distinction is not made by what they contain, but simply by what they * are. Different underlying algorithms can then be used based on the * different operations supported by different iterator types. */ //@{ /// Marking input iterators. struct input_iterator_tag { }; /// Marking output iterators. struct output_iterator_tag { }; /// Forward iterators support a superset of input iterator operations. struct forward_iterator_tag : public input_iterator_tag { }; /// Bidirectional iterators support a superset of forward iterator /// operations. struct bidirectional_iterator_tag : public forward_iterator_tag { }; /// Random-access iterators support a superset of bidirectional /// iterator operations. struct random_access_iterator_tag : public bidirectional_iterator_tag { }; //@} /** * @brief Common %iterator class. * * This class does nothing but define nested typedefs. %Iterator classes * can inherit from this class to save some work. The typedefs are then * used in specializations and overloading. * * In particular, there are no default implementations of requirements * such as @c operator++ and the like. (How could there be?) */ template struct iterator { /// One of the @link iterator_tags tag types@endlink. typedef _Category iterator_category; /// The type "pointed to" by the iterator. typedef _Tp value_type; /// Distance between iterators is represented as this type. typedef _Distance difference_type; /// This type represents a pointer-to-value_type. typedef _Pointer pointer; /// This type represents a reference-to-value_type. typedef _Reference reference; }; /** * @brief Traits class for iterators. * * This class does nothing but define nested typedefs. The general * version simply @a forwards the nested typedefs from the Iterator * argument. Specialized versions for pointers and pointers-to-const * provide tighter, more correct semantics. */ #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2408. SFINAE-friendly common_type/iterator_traits is missing in C++14 template> struct __iterator_traits { }; template struct __iterator_traits<_Iterator, __void_t> { typedef typename _Iterator::iterator_category iterator_category; typedef typename _Iterator::value_type value_type; typedef typename _Iterator::difference_type difference_type; typedef typename _Iterator::pointer pointer; typedef typename _Iterator::reference reference; }; template struct iterator_traits : public __iterator_traits<_Iterator> { }; #else template struct iterator_traits { typedef typename _Iterator::iterator_category iterator_category; typedef typename _Iterator::value_type value_type; typedef typename _Iterator::difference_type difference_type; typedef typename _Iterator::pointer pointer; typedef typename _Iterator::reference reference; }; #endif /// Partial specialization for pointer types. template struct iterator_traits<_Tp*> { typedef random_access_iterator_tag iterator_category; typedef _Tp value_type; typedef ptrdiff_t difference_type; typedef _Tp* pointer; typedef _Tp& reference; }; /// Partial specialization for const pointer types. template struct iterator_traits { typedef random_access_iterator_tag iterator_category; typedef _Tp value_type; typedef ptrdiff_t difference_type; typedef const _Tp* pointer; typedef const _Tp& reference; }; /** * This function is not a part of the C++ standard but is syntactic * sugar for internal library use only. */ template inline _GLIBCXX_CONSTEXPR typename iterator_traits<_Iter>::iterator_category __iterator_category(const _Iter&) { return typename iterator_traits<_Iter>::iterator_category(); } //@} #if __cplusplus < 201103L // If _Iterator has a base returns it otherwise _Iterator is returned // untouched template struct _Iter_base { typedef _Iterator iterator_type; static iterator_type _S_base(_Iterator __it) { return __it; } }; template struct _Iter_base<_Iterator, true> { typedef typename _Iterator::iterator_type iterator_type; static iterator_type _S_base(_Iterator __it) { return __it.base(); } }; #endif #if __cplusplus >= 201103L template using _RequireInputIter = typename enable_if::iterator_category, input_iterator_tag>::value>::type; #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _STL_ITERATOR_BASE_TYPES_H */ PK!-`8/bits/stl_list.hnu[// List implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_list.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{list} */ #ifndef _STL_LIST_H #define _STL_LIST_H 1 #include #include #if __cplusplus >= 201103L #include #include #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { // Supporting structures are split into common and templated // types; the latter publicly inherits from the former in an // effort to reduce code duplication. This results in some // "needless" static_cast'ing later on, but it's all safe // downcasting. /// Common part of a node in the %list. struct _List_node_base { _List_node_base* _M_next; _List_node_base* _M_prev; static void swap(_List_node_base& __x, _List_node_base& __y) _GLIBCXX_USE_NOEXCEPT; void _M_transfer(_List_node_base* const __first, _List_node_base* const __last) _GLIBCXX_USE_NOEXCEPT; void _M_reverse() _GLIBCXX_USE_NOEXCEPT; void _M_hook(_List_node_base* const __position) _GLIBCXX_USE_NOEXCEPT; void _M_unhook() _GLIBCXX_USE_NOEXCEPT; }; /// The %list node header. struct _List_node_header : public _List_node_base { #if _GLIBCXX_USE_CXX11_ABI std::size_t _M_size; #endif _List_node_header() _GLIBCXX_NOEXCEPT { _M_init(); } #if __cplusplus >= 201103L _List_node_header(_List_node_header&& __x) noexcept : _List_node_base{ __x._M_next, __x._M_prev } # if _GLIBCXX_USE_CXX11_ABI , _M_size(__x._M_size) # endif { if (__x._M_base()->_M_next == __x._M_base()) this->_M_next = this->_M_prev = this; else { this->_M_next->_M_prev = this->_M_prev->_M_next = this->_M_base(); __x._M_init(); } } void _M_move_nodes(_List_node_header&& __x) { _List_node_base* const __xnode = __x._M_base(); if (__xnode->_M_next == __xnode) _M_init(); else { _List_node_base* const __node = this->_M_base(); __node->_M_next = __xnode->_M_next; __node->_M_prev = __xnode->_M_prev; __node->_M_next->_M_prev = __node->_M_prev->_M_next = __node; # if _GLIBCXX_USE_CXX11_ABI _M_size = __x._M_size; # endif __x._M_init(); } } #endif void _M_init() _GLIBCXX_NOEXCEPT { this->_M_next = this->_M_prev = this; #if _GLIBCXX_USE_CXX11_ABI this->_M_size = 0; #endif } private: _List_node_base* _M_base() { return this; } }; } // namespace detail _GLIBCXX_BEGIN_NAMESPACE_CONTAINER /// An actual node in the %list. template struct _List_node : public __detail::_List_node_base { #if __cplusplus >= 201103L __gnu_cxx::__aligned_membuf<_Tp> _M_storage; _Tp* _M_valptr() { return _M_storage._M_ptr(); } _Tp const* _M_valptr() const { return _M_storage._M_ptr(); } #else _Tp _M_data; _Tp* _M_valptr() { return std::__addressof(_M_data); } _Tp const* _M_valptr() const { return std::__addressof(_M_data); } #endif }; /** * @brief A list::iterator. * * All the functions are op overloads. */ template struct _List_iterator { typedef _List_iterator<_Tp> _Self; typedef _List_node<_Tp> _Node; typedef ptrdiff_t difference_type; typedef std::bidirectional_iterator_tag iterator_category; typedef _Tp value_type; typedef _Tp* pointer; typedef _Tp& reference; _List_iterator() _GLIBCXX_NOEXCEPT : _M_node() { } explicit _List_iterator(__detail::_List_node_base* __x) _GLIBCXX_NOEXCEPT : _M_node(__x) { } _Self _M_const_cast() const _GLIBCXX_NOEXCEPT { return *this; } // Must downcast from _List_node_base to _List_node to get to value. reference operator*() const _GLIBCXX_NOEXCEPT { return *static_cast<_Node*>(_M_node)->_M_valptr(); } pointer operator->() const _GLIBCXX_NOEXCEPT { return static_cast<_Node*>(_M_node)->_M_valptr(); } _Self& operator++() _GLIBCXX_NOEXCEPT { _M_node = _M_node->_M_next; return *this; } _Self operator++(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _M_node->_M_next; return __tmp; } _Self& operator--() _GLIBCXX_NOEXCEPT { _M_node = _M_node->_M_prev; return *this; } _Self operator--(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _M_node->_M_prev; return __tmp; } bool operator==(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node == __x._M_node; } bool operator!=(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node != __x._M_node; } // The only member points to the %list element. __detail::_List_node_base* _M_node; }; /** * @brief A list::const_iterator. * * All the functions are op overloads. */ template struct _List_const_iterator { typedef _List_const_iterator<_Tp> _Self; typedef const _List_node<_Tp> _Node; typedef _List_iterator<_Tp> iterator; typedef ptrdiff_t difference_type; typedef std::bidirectional_iterator_tag iterator_category; typedef _Tp value_type; typedef const _Tp* pointer; typedef const _Tp& reference; _List_const_iterator() _GLIBCXX_NOEXCEPT : _M_node() { } explicit _List_const_iterator(const __detail::_List_node_base* __x) _GLIBCXX_NOEXCEPT : _M_node(__x) { } _List_const_iterator(const iterator& __x) _GLIBCXX_NOEXCEPT : _M_node(__x._M_node) { } iterator _M_const_cast() const _GLIBCXX_NOEXCEPT { return iterator(const_cast<__detail::_List_node_base*>(_M_node)); } // Must downcast from List_node_base to _List_node to get to value. reference operator*() const _GLIBCXX_NOEXCEPT { return *static_cast<_Node*>(_M_node)->_M_valptr(); } pointer operator->() const _GLIBCXX_NOEXCEPT { return static_cast<_Node*>(_M_node)->_M_valptr(); } _Self& operator++() _GLIBCXX_NOEXCEPT { _M_node = _M_node->_M_next; return *this; } _Self operator++(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _M_node->_M_next; return __tmp; } _Self& operator--() _GLIBCXX_NOEXCEPT { _M_node = _M_node->_M_prev; return *this; } _Self operator--(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _M_node->_M_prev; return __tmp; } bool operator==(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node == __x._M_node; } bool operator!=(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node != __x._M_node; } // The only member points to the %list element. const __detail::_List_node_base* _M_node; }; template inline bool operator==(const _List_iterator<_Val>& __x, const _List_const_iterator<_Val>& __y) _GLIBCXX_NOEXCEPT { return __x._M_node == __y._M_node; } template inline bool operator!=(const _List_iterator<_Val>& __x, const _List_const_iterator<_Val>& __y) _GLIBCXX_NOEXCEPT { return __x._M_node != __y._M_node; } _GLIBCXX_BEGIN_NAMESPACE_CXX11 /// See bits/stl_deque.h's _Deque_base for an explanation. template class _List_base { protected: typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Tp>::other _Tp_alloc_type; typedef __gnu_cxx::__alloc_traits<_Tp_alloc_type> _Tp_alloc_traits; typedef typename _Tp_alloc_traits::template rebind<_List_node<_Tp> >::other _Node_alloc_type; typedef __gnu_cxx::__alloc_traits<_Node_alloc_type> _Node_alloc_traits; #if !_GLIBCXX_INLINE_VERSION static size_t _S_distance(const __detail::_List_node_base* __first, const __detail::_List_node_base* __last) { size_t __n = 0; while (__first != __last) { __first = __first->_M_next; ++__n; } return __n; } #endif struct _List_impl : public _Node_alloc_type { __detail::_List_node_header _M_node; _List_impl() _GLIBCXX_NOEXCEPT_IF( is_nothrow_default_constructible<_Node_alloc_type>::value) : _Node_alloc_type() { } _List_impl(const _Node_alloc_type& __a) _GLIBCXX_NOEXCEPT : _Node_alloc_type(__a) { } #if __cplusplus >= 201103L _List_impl(_List_impl&&) = default; _List_impl(_Node_alloc_type&& __a, _List_impl&& __x) : _Node_alloc_type(std::move(__a)), _M_node(std::move(__x._M_node)) { } _List_impl(_Node_alloc_type&& __a) noexcept : _Node_alloc_type(std::move(__a)) { } #endif }; _List_impl _M_impl; #if _GLIBCXX_USE_CXX11_ABI size_t _M_get_size() const { return _M_impl._M_node._M_size; } void _M_set_size(size_t __n) { _M_impl._M_node._M_size = __n; } void _M_inc_size(size_t __n) { _M_impl._M_node._M_size += __n; } void _M_dec_size(size_t __n) { _M_impl._M_node._M_size -= __n; } # if !_GLIBCXX_INLINE_VERSION size_t _M_distance(const __detail::_List_node_base* __first, const __detail::_List_node_base* __last) const { return _S_distance(__first, __last); } // return the stored size size_t _M_node_count() const { return _M_get_size(); } # endif #else // dummy implementations used when the size is not stored size_t _M_get_size() const { return 0; } void _M_set_size(size_t) { } void _M_inc_size(size_t) { } void _M_dec_size(size_t) { } # if !_GLIBCXX_INLINE_VERSION size_t _M_distance(const void*, const void*) const { return 0; } // count the number of nodes size_t _M_node_count() const { return _S_distance(_M_impl._M_node._M_next, std::__addressof(_M_impl._M_node)); } # endif #endif typename _Node_alloc_traits::pointer _M_get_node() { return _Node_alloc_traits::allocate(_M_impl, 1); } void _M_put_node(typename _Node_alloc_traits::pointer __p) _GLIBCXX_NOEXCEPT { _Node_alloc_traits::deallocate(_M_impl, __p, 1); } public: typedef _Alloc allocator_type; _Node_alloc_type& _M_get_Node_allocator() _GLIBCXX_NOEXCEPT { return _M_impl; } const _Node_alloc_type& _M_get_Node_allocator() const _GLIBCXX_NOEXCEPT { return _M_impl; } #if __cplusplus >= 201103L _List_base() = default; #else _List_base() { } #endif _List_base(const _Node_alloc_type& __a) _GLIBCXX_NOEXCEPT : _M_impl(__a) { } #if __cplusplus >= 201103L _List_base(_List_base&&) = default; # if !_GLIBCXX_INLINE_VERSION _List_base(_List_base&& __x, _Node_alloc_type&& __a) : _M_impl(std::move(__a)) { if (__x._M_get_Node_allocator() == _M_get_Node_allocator()) _M_move_nodes(std::move(__x)); // else caller must move individual elements. } # endif // Used when allocator is_always_equal. _List_base(_Node_alloc_type&& __a, _List_base&& __x) : _M_impl(std::move(__a), std::move(__x._M_impl)) { } // Used when allocator !is_always_equal. _List_base(_Node_alloc_type&& __a) : _M_impl(std::move(__a)) { } void _M_move_nodes(_List_base&& __x) { _M_impl._M_node._M_move_nodes(std::move(__x._M_impl._M_node)); } #endif // This is what actually destroys the list. ~_List_base() _GLIBCXX_NOEXCEPT { _M_clear(); } void _M_clear() _GLIBCXX_NOEXCEPT; void _M_init() _GLIBCXX_NOEXCEPT { this->_M_impl._M_node._M_init(); } }; /** * @brief A standard container with linear time access to elements, * and fixed time insertion/deletion at any point in the sequence. * * @ingroup sequences * * @tparam _Tp Type of element. * @tparam _Alloc Allocator type, defaults to allocator<_Tp>. * * Meets the requirements of a container, a * reversible container, and a * sequence, including the * optional sequence requirements with the * %exception of @c at and @c operator[]. * * This is a @e doubly @e linked %list. Traversal up and down the * %list requires linear time, but adding and removing elements (or * @e nodes) is done in constant time, regardless of where the * change takes place. Unlike std::vector and std::deque, * random-access iterators are not provided, so subscripting ( @c * [] ) access is not allowed. For algorithms which only need * sequential access, this lack makes no difference. * * Also unlike the other standard containers, std::list provides * specialized algorithms %unique to linked lists, such as * splicing, sorting, and in-place reversal. * * A couple points on memory allocation for list: * * First, we never actually allocate a Tp, we allocate * List_node's and trust [20.1.5]/4 to DTRT. This is to ensure * that after elements from %list are spliced into * %list, destroying the memory of the second %list is a * valid operation, i.e., Alloc1 giveth and Alloc2 taketh away. * * Second, a %list conceptually represented as * @code * A <---> B <---> C <---> D * @endcode * is actually circular; a link exists between A and D. The %list * class holds (as its only data member) a private list::iterator * pointing to @e D, not to @e A! To get to the head of the %list, * we start at the tail and move forward by one. When this member * iterator's next/previous pointers refer to itself, the %list is * %empty. */ template > class list : protected _List_base<_Tp, _Alloc> { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Alloc::value_type _Alloc_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) # endif __glibcxx_class_requires2(_Tp, _Alloc_value_type, _SameTypeConcept) #endif #if __cplusplus >= 201103L static_assert(is_same::type, _Tp>::value, "std::list must have a non-const, non-volatile value_type"); # ifdef __STRICT_ANSI__ static_assert(is_same::value, "std::list must have the same value_type as its allocator"); # endif #endif typedef _List_base<_Tp, _Alloc> _Base; typedef typename _Base::_Tp_alloc_type _Tp_alloc_type; typedef typename _Base::_Tp_alloc_traits _Tp_alloc_traits; typedef typename _Base::_Node_alloc_type _Node_alloc_type; typedef typename _Base::_Node_alloc_traits _Node_alloc_traits; public: typedef _Tp value_type; typedef typename _Tp_alloc_traits::pointer pointer; typedef typename _Tp_alloc_traits::const_pointer const_pointer; typedef typename _Tp_alloc_traits::reference reference; typedef typename _Tp_alloc_traits::const_reference const_reference; typedef _List_iterator<_Tp> iterator; typedef _List_const_iterator<_Tp> const_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Alloc allocator_type; protected: // Note that pointers-to-_Node's can be ctor-converted to // iterator types. typedef _List_node<_Tp> _Node; using _Base::_M_impl; using _Base::_M_put_node; using _Base::_M_get_node; using _Base::_M_get_Node_allocator; /** * @param __args An instance of user data. * * Allocates space for a new node and constructs a copy of * @a __args in it. */ #if __cplusplus < 201103L _Node* _M_create_node(const value_type& __x) { _Node* __p = this->_M_get_node(); __try { _Tp_alloc_type __alloc(_M_get_Node_allocator()); __alloc.construct(__p->_M_valptr(), __x); } __catch(...) { _M_put_node(__p); __throw_exception_again; } return __p; } #else template _Node* _M_create_node(_Args&&... __args) { auto __p = this->_M_get_node(); auto& __alloc = _M_get_Node_allocator(); __allocated_ptr<_Node_alloc_type> __guard{__alloc, __p}; _Node_alloc_traits::construct(__alloc, __p->_M_valptr(), std::forward<_Args>(__args)...); __guard = nullptr; return __p; } #endif #if _GLIBCXX_USE_CXX11_ABI static size_t _S_distance(const_iterator __first, const_iterator __last) { return std::distance(__first, __last); } // return the stored size size_t _M_node_count() const { return this->_M_get_size(); } #else // dummy implementations used when the size is not stored static size_t _S_distance(const_iterator, const_iterator) { return 0; } // count the number of nodes size_t _M_node_count() const { return std::distance(begin(), end()); } #endif public: // [23.2.2.1] construct/copy/destroy // (assign() and get_allocator() are also listed in this section) /** * @brief Creates a %list with no elements. */ #if __cplusplus >= 201103L list() = default; #else list() { } #endif /** * @brief Creates a %list with no elements. * @param __a An allocator object. */ explicit list(const allocator_type& __a) _GLIBCXX_NOEXCEPT : _Base(_Node_alloc_type(__a)) { } #if __cplusplus >= 201103L /** * @brief Creates a %list with default constructed elements. * @param __n The number of elements to initially create. * @param __a An allocator object. * * This constructor fills the %list with @a __n default * constructed elements. */ explicit list(size_type __n, const allocator_type& __a = allocator_type()) : _Base(_Node_alloc_type(__a)) { _M_default_initialize(__n); } /** * @brief Creates a %list with copies of an exemplar element. * @param __n The number of elements to initially create. * @param __value An element to copy. * @param __a An allocator object. * * This constructor fills the %list with @a __n copies of @a __value. */ list(size_type __n, const value_type& __value, const allocator_type& __a = allocator_type()) : _Base(_Node_alloc_type(__a)) { _M_fill_initialize(__n, __value); } #else /** * @brief Creates a %list with copies of an exemplar element. * @param __n The number of elements to initially create. * @param __value An element to copy. * @param __a An allocator object. * * This constructor fills the %list with @a __n copies of @a __value. */ explicit list(size_type __n, const value_type& __value = value_type(), const allocator_type& __a = allocator_type()) : _Base(_Node_alloc_type(__a)) { _M_fill_initialize(__n, __value); } #endif /** * @brief %List copy constructor. * @param __x A %list of identical element and allocator types. * * The newly-created %list uses a copy of the allocation object used * by @a __x (unless the allocator traits dictate a different object). */ list(const list& __x) : _Base(_Node_alloc_traits:: _S_select_on_copy(__x._M_get_Node_allocator())) { _M_initialize_dispatch(__x.begin(), __x.end(), __false_type()); } #if __cplusplus >= 201103L /** * @brief %List move constructor. * * The newly-created %list contains the exact contents of the moved * instance. The contents of the moved instance are a valid, but * unspecified %list. */ list(list&&) = default; /** * @brief Builds a %list from an initializer_list * @param __l An initializer_list of value_type. * @param __a An allocator object. * * Create a %list consisting of copies of the elements in the * initializer_list @a __l. This is linear in __l.size(). */ list(initializer_list __l, const allocator_type& __a = allocator_type()) : _Base(_Node_alloc_type(__a)) { _M_initialize_dispatch(__l.begin(), __l.end(), __false_type()); } list(const list& __x, const allocator_type& __a) : _Base(_Node_alloc_type(__a)) { _M_initialize_dispatch(__x.begin(), __x.end(), __false_type()); } private: list(list&& __x, const allocator_type& __a, true_type) noexcept : _Base(_Node_alloc_type(__a), std::move(__x)) { } list(list&& __x, const allocator_type& __a, false_type) : _Base(_Node_alloc_type(__a)) { if (__x._M_get_Node_allocator() == this->_M_get_Node_allocator()) this->_M_move_nodes(std::move(__x)); else insert(begin(), std::__make_move_if_noexcept_iterator(__x.begin()), std::__make_move_if_noexcept_iterator(__x.end())); } public: list(list&& __x, const allocator_type& __a) noexcept(_Node_alloc_traits::_S_always_equal()) : list(std::move(__x), __a, typename _Node_alloc_traits::is_always_equal{}) { } #endif /** * @brief Builds a %list from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __a An allocator object. * * Create a %list consisting of copies of the elements from * [@a __first,@a __last). This is linear in N (where N is * distance(@a __first,@a __last)). */ #if __cplusplus >= 201103L template> list(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(_Node_alloc_type(__a)) { _M_initialize_dispatch(__first, __last, __false_type()); } #else template list(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(_Node_alloc_type(__a)) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_initialize_dispatch(__first, __last, _Integral()); } #endif #if __cplusplus >= 201103L /** * No explicit dtor needed as the _Base dtor takes care of * things. The _Base dtor only erases the elements, and note * that if the elements themselves are pointers, the pointed-to * memory is not touched in any way. Managing the pointer is * the user's responsibility. */ ~list() = default; #endif /** * @brief %List assignment operator. * @param __x A %list of identical element and allocator types. * * All the elements of @a __x are copied. * * Whether the allocator is copied depends on the allocator traits. */ list& operator=(const list& __x); #if __cplusplus >= 201103L /** * @brief %List move assignment operator. * @param __x A %list of identical element and allocator types. * * The contents of @a __x are moved into this %list (without copying). * * Afterwards @a __x is a valid, but unspecified %list * * Whether the allocator is moved depends on the allocator traits. */ list& operator=(list&& __x) noexcept(_Node_alloc_traits::_S_nothrow_move()) { constexpr bool __move_storage = _Node_alloc_traits::_S_propagate_on_move_assign() || _Node_alloc_traits::_S_always_equal(); _M_move_assign(std::move(__x), __bool_constant<__move_storage>()); return *this; } /** * @brief %List initializer list assignment operator. * @param __l An initializer_list of value_type. * * Replace the contents of the %list with copies of the elements * in the initializer_list @a __l. This is linear in l.size(). */ list& operator=(initializer_list __l) { this->assign(__l.begin(), __l.end()); return *this; } #endif /** * @brief Assigns a given value to a %list. * @param __n Number of elements to be assigned. * @param __val Value to be assigned. * * This function fills a %list with @a __n copies of the given * value. Note that the assignment completely changes the %list * and that the resulting %list's size is the same as the number * of elements assigned. */ void assign(size_type __n, const value_type& __val) { _M_fill_assign(__n, __val); } /** * @brief Assigns a range to a %list. * @param __first An input iterator. * @param __last An input iterator. * * This function fills a %list with copies of the elements in the * range [@a __first,@a __last). * * Note that the assignment completely changes the %list and * that the resulting %list's size is the same as the number of * elements assigned. */ #if __cplusplus >= 201103L template> void assign(_InputIterator __first, _InputIterator __last) { _M_assign_dispatch(__first, __last, __false_type()); } #else template void assign(_InputIterator __first, _InputIterator __last) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_assign_dispatch(__first, __last, _Integral()); } #endif #if __cplusplus >= 201103L /** * @brief Assigns an initializer_list to a %list. * @param __l An initializer_list of value_type. * * Replace the contents of the %list with copies of the elements * in the initializer_list @a __l. This is linear in __l.size(). */ void assign(initializer_list __l) { this->_M_assign_dispatch(__l.begin(), __l.end(), __false_type()); } #endif /// Get a copy of the memory allocation object. allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_Base::_M_get_Node_allocator()); } // iterators /** * Returns a read/write iterator that points to the first element in the * %list. Iteration is done in ordinary element order. */ iterator begin() _GLIBCXX_NOEXCEPT { return iterator(this->_M_impl._M_node._M_next); } /** * Returns a read-only (constant) iterator that points to the * first element in the %list. Iteration is done in ordinary * element order. */ const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(this->_M_impl._M_node._M_next); } /** * Returns a read/write iterator that points one past the last * element in the %list. Iteration is done in ordinary element * order. */ iterator end() _GLIBCXX_NOEXCEPT { return iterator(&this->_M_impl._M_node); } /** * Returns a read-only (constant) iterator that points one past * the last element in the %list. Iteration is done in ordinary * element order. */ const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(&this->_M_impl._M_node); } /** * Returns a read/write reverse iterator that points to the last * element in the %list. Iteration is done in reverse element * order. */ reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } /** * Returns a read-only (constant) reverse iterator that points to * the last element in the %list. Iteration is done in reverse * element order. */ const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } /** * Returns a read/write reverse iterator that points to one * before the first element in the %list. Iteration is done in * reverse element order. */ reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } /** * Returns a read-only (constant) reverse iterator that points to one * before the first element in the %list. Iteration is done in reverse * element order. */ const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the * first element in the %list. Iteration is done in ordinary * element order. */ const_iterator cbegin() const noexcept { return const_iterator(this->_M_impl._M_node._M_next); } /** * Returns a read-only (constant) iterator that points one past * the last element in the %list. Iteration is done in ordinary * element order. */ const_iterator cend() const noexcept { return const_iterator(&this->_M_impl._M_node); } /** * Returns a read-only (constant) reverse iterator that points to * the last element in the %list. Iteration is done in reverse * element order. */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } /** * Returns a read-only (constant) reverse iterator that points to one * before the first element in the %list. Iteration is done in reverse * element order. */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // [23.2.2.2] capacity /** * Returns true if the %list is empty. (Thus begin() would equal * end().) */ bool empty() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_node._M_next == &this->_M_impl._M_node; } /** Returns the number of elements in the %list. */ size_type size() const _GLIBCXX_NOEXCEPT { return _M_node_count(); } /** Returns the size() of the largest possible %list. */ size_type max_size() const _GLIBCXX_NOEXCEPT { return _Node_alloc_traits::max_size(_M_get_Node_allocator()); } #if __cplusplus >= 201103L /** * @brief Resizes the %list to the specified number of elements. * @param __new_size Number of elements the %list should contain. * * This function will %resize the %list to the specified number * of elements. If the number is smaller than the %list's * current size the %list is truncated, otherwise default * constructed elements are appended. */ void resize(size_type __new_size); /** * @brief Resizes the %list to the specified number of elements. * @param __new_size Number of elements the %list should contain. * @param __x Data with which new elements should be populated. * * This function will %resize the %list to the specified number * of elements. If the number is smaller than the %list's * current size the %list is truncated, otherwise the %list is * extended and new elements are populated with given data. */ void resize(size_type __new_size, const value_type& __x); #else /** * @brief Resizes the %list to the specified number of elements. * @param __new_size Number of elements the %list should contain. * @param __x Data with which new elements should be populated. * * This function will %resize the %list to the specified number * of elements. If the number is smaller than the %list's * current size the %list is truncated, otherwise the %list is * extended and new elements are populated with given data. */ void resize(size_type __new_size, value_type __x = value_type()); #endif // element access /** * Returns a read/write reference to the data at the first * element of the %list. */ reference front() _GLIBCXX_NOEXCEPT { return *begin(); } /** * Returns a read-only (constant) reference to the data at the first * element of the %list. */ const_reference front() const _GLIBCXX_NOEXCEPT { return *begin(); } /** * Returns a read/write reference to the data at the last element * of the %list. */ reference back() _GLIBCXX_NOEXCEPT { iterator __tmp = end(); --__tmp; return *__tmp; } /** * Returns a read-only (constant) reference to the data at the last * element of the %list. */ const_reference back() const _GLIBCXX_NOEXCEPT { const_iterator __tmp = end(); --__tmp; return *__tmp; } // [23.2.2.3] modifiers /** * @brief Add data to the front of the %list. * @param __x Data to be added. * * This is a typical stack operation. The function creates an * element at the front of the %list and assigns the given data * to it. Due to the nature of a %list this operation can be * done in constant time, and does not invalidate iterators and * references. */ void push_front(const value_type& __x) { this->_M_insert(begin(), __x); } #if __cplusplus >= 201103L void push_front(value_type&& __x) { this->_M_insert(begin(), std::move(__x)); } template #if __cplusplus > 201402L reference #else void #endif emplace_front(_Args&&... __args) { this->_M_insert(begin(), std::forward<_Args>(__args)...); #if __cplusplus > 201402L return front(); #endif } #endif /** * @brief Removes first element. * * This is a typical stack operation. It shrinks the %list by * one. Due to the nature of a %list this operation can be done * in constant time, and only invalidates iterators/references to * the element being removed. * * Note that no data is returned, and if the first element's data * is needed, it should be retrieved before pop_front() is * called. */ void pop_front() _GLIBCXX_NOEXCEPT { this->_M_erase(begin()); } /** * @brief Add data to the end of the %list. * @param __x Data to be added. * * This is a typical stack operation. The function creates an * element at the end of the %list and assigns the given data to * it. Due to the nature of a %list this operation can be done * in constant time, and does not invalidate iterators and * references. */ void push_back(const value_type& __x) { this->_M_insert(end(), __x); } #if __cplusplus >= 201103L void push_back(value_type&& __x) { this->_M_insert(end(), std::move(__x)); } template #if __cplusplus > 201402L reference #else void #endif emplace_back(_Args&&... __args) { this->_M_insert(end(), std::forward<_Args>(__args)...); #if __cplusplus > 201402L return back(); #endif } #endif /** * @brief Removes last element. * * This is a typical stack operation. It shrinks the %list by * one. Due to the nature of a %list this operation can be done * in constant time, and only invalidates iterators/references to * the element being removed. * * Note that no data is returned, and if the last element's data * is needed, it should be retrieved before pop_back() is called. */ void pop_back() _GLIBCXX_NOEXCEPT { this->_M_erase(iterator(this->_M_impl._M_node._M_prev)); } #if __cplusplus >= 201103L /** * @brief Constructs object in %list before specified iterator. * @param __position A const_iterator into the %list. * @param __args Arguments. * @return An iterator that points to the inserted data. * * This function will insert an object of type T constructed * with T(std::forward(args)...) before the specified * location. Due to the nature of a %list this operation can * be done in constant time, and does not invalidate iterators * and references. */ template iterator emplace(const_iterator __position, _Args&&... __args); /** * @brief Inserts given value into %list before specified iterator. * @param __position A const_iterator into the %list. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value before * the specified location. Due to the nature of a %list this * operation can be done in constant time, and does not * invalidate iterators and references. */ iterator insert(const_iterator __position, const value_type& __x); #else /** * @brief Inserts given value into %list before specified iterator. * @param __position An iterator into the %list. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value before * the specified location. Due to the nature of a %list this * operation can be done in constant time, and does not * invalidate iterators and references. */ iterator insert(iterator __position, const value_type& __x); #endif #if __cplusplus >= 201103L /** * @brief Inserts given rvalue into %list before specified iterator. * @param __position A const_iterator into the %list. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given rvalue before * the specified location. Due to the nature of a %list this * operation can be done in constant time, and does not * invalidate iterators and references. */ iterator insert(const_iterator __position, value_type&& __x) { return emplace(__position, std::move(__x)); } /** * @brief Inserts the contents of an initializer_list into %list * before specified const_iterator. * @param __p A const_iterator into the %list. * @param __l An initializer_list of value_type. * @return An iterator pointing to the first element inserted * (or __position). * * This function will insert copies of the data in the * initializer_list @a l into the %list before the location * specified by @a p. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ iterator insert(const_iterator __p, initializer_list __l) { return this->insert(__p, __l.begin(), __l.end()); } #endif #if __cplusplus >= 201103L /** * @brief Inserts a number of copies of given data into the %list. * @param __position A const_iterator into the %list. * @param __n Number of elements to be inserted. * @param __x Data to be inserted. * @return An iterator pointing to the first element inserted * (or __position). * * This function will insert a specified number of copies of the * given data before the location specified by @a position. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ iterator insert(const_iterator __position, size_type __n, const value_type& __x); #else /** * @brief Inserts a number of copies of given data into the %list. * @param __position An iterator into the %list. * @param __n Number of elements to be inserted. * @param __x Data to be inserted. * * This function will insert a specified number of copies of the * given data before the location specified by @a position. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ void insert(iterator __position, size_type __n, const value_type& __x) { list __tmp(__n, __x, get_allocator()); splice(__position, __tmp); } #endif #if __cplusplus >= 201103L /** * @brief Inserts a range into the %list. * @param __position A const_iterator into the %list. * @param __first An input iterator. * @param __last An input iterator. * @return An iterator pointing to the first element inserted * (or __position). * * This function will insert copies of the data in the range [@a * first,@a last) into the %list before the location specified by * @a position. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ template> iterator insert(const_iterator __position, _InputIterator __first, _InputIterator __last); #else /** * @brief Inserts a range into the %list. * @param __position An iterator into the %list. * @param __first An input iterator. * @param __last An input iterator. * * This function will insert copies of the data in the range [@a * first,@a last) into the %list before the location specified by * @a position. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ template void insert(iterator __position, _InputIterator __first, _InputIterator __last) { list __tmp(__first, __last, get_allocator()); splice(__position, __tmp); } #endif /** * @brief Remove element at given position. * @param __position Iterator pointing to element to be erased. * @return An iterator pointing to the next element (or end()). * * This function will erase the element at the given position and thus * shorten the %list by one. * * Due to the nature of a %list this operation can be done in * constant time, and only invalidates iterators/references to * the element being removed. The user is also cautioned that * this function only erases the element, and that if the element * is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ iterator #if __cplusplus >= 201103L erase(const_iterator __position) noexcept; #else erase(iterator __position); #endif /** * @brief Remove a range of elements. * @param __first Iterator pointing to the first element to be erased. * @param __last Iterator pointing to one past the last element to be * erased. * @return An iterator pointing to the element pointed to by @a last * prior to erasing (or end()). * * This function will erase the elements in the range @a * [first,last) and shorten the %list accordingly. * * This operation is linear time in the size of the range and only * invalidates iterators/references to the element being removed. * The user is also cautioned that this function only erases the * elements, and that if the elements themselves are pointers, the * pointed-to memory is not touched in any way. Managing the pointer * is the user's responsibility. */ iterator #if __cplusplus >= 201103L erase(const_iterator __first, const_iterator __last) noexcept #else erase(iterator __first, iterator __last) #endif { while (__first != __last) __first = erase(__first); return __last._M_const_cast(); } /** * @brief Swaps data with another %list. * @param __x A %list of the same element and allocator types. * * This exchanges the elements between two lists in constant * time. Note that the global std::swap() function is * specialized such that std::swap(l1,l2) will feed to this * function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(list& __x) _GLIBCXX_NOEXCEPT { __detail::_List_node_base::swap(this->_M_impl._M_node, __x._M_impl._M_node); size_t __xsize = __x._M_get_size(); __x._M_set_size(this->_M_get_size()); this->_M_set_size(__xsize); _Node_alloc_traits::_S_on_swap(this->_M_get_Node_allocator(), __x._M_get_Node_allocator()); } /** * Erases all the elements. Note that this function only erases * the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibility. */ void clear() _GLIBCXX_NOEXCEPT { _Base::_M_clear(); _Base::_M_init(); } // [23.2.2.4] list operations /** * @brief Insert contents of another %list. * @param __position Iterator referencing the element to insert before. * @param __x Source list. * * The elements of @a __x are inserted in constant time in front of * the element referenced by @a __position. @a __x becomes an empty * list. * * Requires this != @a __x. */ void #if __cplusplus >= 201103L splice(const_iterator __position, list&& __x) noexcept #else splice(iterator __position, list& __x) #endif { if (!__x.empty()) { _M_check_equal_allocators(__x); this->_M_transfer(__position._M_const_cast(), __x.begin(), __x.end()); this->_M_inc_size(__x._M_get_size()); __x._M_set_size(0); } } #if __cplusplus >= 201103L void splice(const_iterator __position, list& __x) noexcept { splice(__position, std::move(__x)); } #endif #if __cplusplus >= 201103L /** * @brief Insert element from another %list. * @param __position Const_iterator referencing the element to * insert before. * @param __x Source list. * @param __i Const_iterator referencing the element to move. * * Removes the element in list @a __x referenced by @a __i and * inserts it into the current list before @a __position. */ void splice(const_iterator __position, list&& __x, const_iterator __i) noexcept #else /** * @brief Insert element from another %list. * @param __position Iterator referencing the element to insert before. * @param __x Source list. * @param __i Iterator referencing the element to move. * * Removes the element in list @a __x referenced by @a __i and * inserts it into the current list before @a __position. */ void splice(iterator __position, list& __x, iterator __i) #endif { iterator __j = __i._M_const_cast(); ++__j; if (__position == __i || __position == __j) return; if (this != std::__addressof(__x)) _M_check_equal_allocators(__x); this->_M_transfer(__position._M_const_cast(), __i._M_const_cast(), __j); this->_M_inc_size(1); __x._M_dec_size(1); } #if __cplusplus >= 201103L /** * @brief Insert element from another %list. * @param __position Const_iterator referencing the element to * insert before. * @param __x Source list. * @param __i Const_iterator referencing the element to move. * * Removes the element in list @a __x referenced by @a __i and * inserts it into the current list before @a __position. */ void splice(const_iterator __position, list& __x, const_iterator __i) noexcept { splice(__position, std::move(__x), __i); } #endif #if __cplusplus >= 201103L /** * @brief Insert range from another %list. * @param __position Const_iterator referencing the element to * insert before. * @param __x Source list. * @param __first Const_iterator referencing the start of range in x. * @param __last Const_iterator referencing the end of range in x. * * Removes elements in the range [__first,__last) and inserts them * before @a __position in constant time. * * Undefined if @a __position is in [__first,__last). */ void splice(const_iterator __position, list&& __x, const_iterator __first, const_iterator __last) noexcept #else /** * @brief Insert range from another %list. * @param __position Iterator referencing the element to insert before. * @param __x Source list. * @param __first Iterator referencing the start of range in x. * @param __last Iterator referencing the end of range in x. * * Removes elements in the range [__first,__last) and inserts them * before @a __position in constant time. * * Undefined if @a __position is in [__first,__last). */ void splice(iterator __position, list& __x, iterator __first, iterator __last) #endif { if (__first != __last) { if (this != std::__addressof(__x)) _M_check_equal_allocators(__x); size_t __n = _S_distance(__first, __last); this->_M_inc_size(__n); __x._M_dec_size(__n); this->_M_transfer(__position._M_const_cast(), __first._M_const_cast(), __last._M_const_cast()); } } #if __cplusplus >= 201103L /** * @brief Insert range from another %list. * @param __position Const_iterator referencing the element to * insert before. * @param __x Source list. * @param __first Const_iterator referencing the start of range in x. * @param __last Const_iterator referencing the end of range in x. * * Removes elements in the range [__first,__last) and inserts them * before @a __position in constant time. * * Undefined if @a __position is in [__first,__last). */ void splice(const_iterator __position, list& __x, const_iterator __first, const_iterator __last) noexcept { splice(__position, std::move(__x), __first, __last); } #endif /** * @brief Remove all elements equal to value. * @param __value The value to remove. * * Removes every element in the list equal to @a value. * Remaining elements stay in list order. Note that this * function only erases the elements, and that if the elements * themselves are pointers, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ void remove(const _Tp& __value); /** * @brief Remove all elements satisfying a predicate. * @tparam _Predicate Unary predicate function or object. * * Removes every element in the list for which the predicate * returns true. Remaining elements stay in list order. Note * that this function only erases the elements, and that if the * elements themselves are pointers, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibility. */ template void remove_if(_Predicate); /** * @brief Remove consecutive duplicate elements. * * For each consecutive set of elements with the same value, * remove all but the first one. Remaining elements stay in * list order. Note that this function only erases the * elements, and that if the elements themselves are pointers, * the pointed-to memory is not touched in any way. Managing * the pointer is the user's responsibility. */ void unique(); /** * @brief Remove consecutive elements satisfying a predicate. * @tparam _BinaryPredicate Binary predicate function or object. * * For each consecutive set of elements [first,last) that * satisfy predicate(first,i) where i is an iterator in * [first,last), remove all but the first one. Remaining * elements stay in list order. Note that this function only * erases the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibility. */ template void unique(_BinaryPredicate); /** * @brief Merge sorted lists. * @param __x Sorted list to merge. * * Assumes that both @a __x and this list are sorted according to * operator<(). Merges elements of @a __x into this list in * sorted order, leaving @a __x empty when complete. Elements in * this list precede elements in @a __x that are equal. */ #if __cplusplus >= 201103L void merge(list&& __x); void merge(list& __x) { merge(std::move(__x)); } #else void merge(list& __x); #endif /** * @brief Merge sorted lists according to comparison function. * @tparam _StrictWeakOrdering Comparison function defining * sort order. * @param __x Sorted list to merge. * @param __comp Comparison functor. * * Assumes that both @a __x and this list are sorted according to * StrictWeakOrdering. Merges elements of @a __x into this list * in sorted order, leaving @a __x empty when complete. Elements * in this list precede elements in @a __x that are equivalent * according to StrictWeakOrdering(). */ #if __cplusplus >= 201103L template void merge(list&& __x, _StrictWeakOrdering __comp); template void merge(list& __x, _StrictWeakOrdering __comp) { merge(std::move(__x), __comp); } #else template void merge(list& __x, _StrictWeakOrdering __comp); #endif /** * @brief Reverse the elements in list. * * Reverse the order of elements in the list in linear time. */ void reverse() _GLIBCXX_NOEXCEPT { this->_M_impl._M_node._M_reverse(); } /** * @brief Sort the elements. * * Sorts the elements of this list in NlogN time. Equivalent * elements remain in list order. */ void sort(); /** * @brief Sort the elements according to comparison function. * * Sorts the elements of this list in NlogN time. Equivalent * elements remain in list order. */ template void sort(_StrictWeakOrdering); protected: // Internal constructor functions follow. // Called by the range constructor to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_initialize_dispatch(_Integer __n, _Integer __x, __true_type) { _M_fill_initialize(static_cast(__n), __x); } // Called by the range constructor to implement [23.1.1]/9 template void _M_initialize_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { for (; __first != __last; ++__first) #if __cplusplus >= 201103L emplace_back(*__first); #else push_back(*__first); #endif } // Called by list(n,v,a), and the range constructor when it turns out // to be the same thing. void _M_fill_initialize(size_type __n, const value_type& __x) { for (; __n; --__n) push_back(__x); } #if __cplusplus >= 201103L // Called by list(n). void _M_default_initialize(size_type __n) { for (; __n; --__n) emplace_back(); } // Called by resize(sz). void _M_default_append(size_type __n); #endif // Internal assign functions follow. // Called by the range assign to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_assign_dispatch(_Integer __n, _Integer __val, __true_type) { _M_fill_assign(__n, __val); } // Called by the range assign to implement [23.1.1]/9 template void _M_assign_dispatch(_InputIterator __first, _InputIterator __last, __false_type); // Called by assign(n,t), and the range assign when it turns out // to be the same thing. void _M_fill_assign(size_type __n, const value_type& __val); // Moves the elements from [first,last) before position. void _M_transfer(iterator __position, iterator __first, iterator __last) { __position._M_node->_M_transfer(__first._M_node, __last._M_node); } // Inserts new element at position given and with value given. #if __cplusplus < 201103L void _M_insert(iterator __position, const value_type& __x) { _Node* __tmp = _M_create_node(__x); __tmp->_M_hook(__position._M_node); this->_M_inc_size(1); } #else template void _M_insert(iterator __position, _Args&&... __args) { _Node* __tmp = _M_create_node(std::forward<_Args>(__args)...); __tmp->_M_hook(__position._M_node); this->_M_inc_size(1); } #endif // Erases element at position given. void _M_erase(iterator __position) _GLIBCXX_NOEXCEPT { this->_M_dec_size(1); __position._M_node->_M_unhook(); _Node* __n = static_cast<_Node*>(__position._M_node); #if __cplusplus >= 201103L _Node_alloc_traits::destroy(_M_get_Node_allocator(), __n->_M_valptr()); #else _Tp_alloc_type(_M_get_Node_allocator()).destroy(__n->_M_valptr()); #endif _M_put_node(__n); } // To implement the splice (and merge) bits of N1599. void _M_check_equal_allocators(list& __x) _GLIBCXX_NOEXCEPT { if (std::__alloc_neq:: _S_do_it(_M_get_Node_allocator(), __x._M_get_Node_allocator())) __builtin_abort(); } // Used to implement resize. const_iterator _M_resize_pos(size_type& __new_size) const; #if __cplusplus >= 201103L void _M_move_assign(list&& __x, true_type) noexcept { this->_M_clear(); this->_M_move_nodes(std::move(__x)); std::__alloc_on_move(this->_M_get_Node_allocator(), __x._M_get_Node_allocator()); } void _M_move_assign(list&& __x, false_type) { if (__x._M_get_Node_allocator() == this->_M_get_Node_allocator()) _M_move_assign(std::move(__x), true_type{}); else // The rvalue's allocator cannot be moved, or is not equal, // so we need to individually move each element. _M_assign_dispatch(std::__make_move_if_noexcept_iterator(__x.begin()), std::__make_move_if_noexcept_iterator(__x.end()), __false_type{}); } #endif }; #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> list(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> list<_ValT, _Allocator>; #endif _GLIBCXX_END_NAMESPACE_CXX11 /** * @brief List equality comparison. * @param __x A %list. * @param __y A %list of the same type as @a __x. * @return True iff the size and elements of the lists are equal. * * This is an equivalence relation. It is linear in the size of * the lists. Lists are considered equivalent if their sizes are * equal, and if corresponding elements compare equal. */ template inline bool operator==(const list<_Tp, _Alloc>& __x, const list<_Tp, _Alloc>& __y) { #if _GLIBCXX_USE_CXX11_ABI if (__x.size() != __y.size()) return false; #endif typedef typename list<_Tp, _Alloc>::const_iterator const_iterator; const_iterator __end1 = __x.end(); const_iterator __end2 = __y.end(); const_iterator __i1 = __x.begin(); const_iterator __i2 = __y.begin(); while (__i1 != __end1 && __i2 != __end2 && *__i1 == *__i2) { ++__i1; ++__i2; } return __i1 == __end1 && __i2 == __end2; } /** * @brief List ordering relation. * @param __x A %list. * @param __y A %list of the same type as @a __x. * @return True iff @a __x is lexicographically less than @a __y. * * This is a total ordering relation. It is linear in the size of the * lists. The elements must be comparable with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const list<_Tp, _Alloc>& __x, const list<_Tp, _Alloc>& __y) { return std::lexicographical_compare(__x.begin(), __x.end(), __y.begin(), __y.end()); } /// Based on operator== template inline bool operator!=(const list<_Tp, _Alloc>& __x, const list<_Tp, _Alloc>& __y) { return !(__x == __y); } /// Based on operator< template inline bool operator>(const list<_Tp, _Alloc>& __x, const list<_Tp, _Alloc>& __y) { return __y < __x; } /// Based on operator< template inline bool operator<=(const list<_Tp, _Alloc>& __x, const list<_Tp, _Alloc>& __y) { return !(__y < __x); } /// Based on operator< template inline bool operator>=(const list<_Tp, _Alloc>& __x, const list<_Tp, _Alloc>& __y) { return !(__x < __y); } /// See std::list::swap(). template inline void swap(list<_Tp, _Alloc>& __x, list<_Tp, _Alloc>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { __x.swap(__y); } _GLIBCXX_END_NAMESPACE_CONTAINER #if _GLIBCXX_USE_CXX11_ABI // Detect when distance is used to compute the size of the whole list. template inline ptrdiff_t __distance(_GLIBCXX_STD_C::_List_iterator<_Tp> __first, _GLIBCXX_STD_C::_List_iterator<_Tp> __last, input_iterator_tag __tag) { typedef _GLIBCXX_STD_C::_List_const_iterator<_Tp> _CIter; return std::__distance(_CIter(__first), _CIter(__last), __tag); } template inline ptrdiff_t __distance(_GLIBCXX_STD_C::_List_const_iterator<_Tp> __first, _GLIBCXX_STD_C::_List_const_iterator<_Tp> __last, input_iterator_tag) { typedef __detail::_List_node_header _Sentinel; _GLIBCXX_STD_C::_List_const_iterator<_Tp> __beyond = __last; ++__beyond; const bool __whole = __first == __beyond; if (__builtin_constant_p (__whole) && __whole) return static_cast(__last._M_node)->_M_size; ptrdiff_t __n = 0; while (__first != __last) { ++__first; ++__n; } return __n; } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_LIST_H */ PK!y!778/bits/stl_map.hnu[// Map implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_map.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{map} */ #ifndef _STL_MAP_H #define _STL_MAP_H 1 #include #include #if __cplusplus >= 201103L #include #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER template class multimap; /** * @brief A standard container made up of (key,value) pairs, which can be * retrieved based on a key, in logarithmic time. * * @ingroup associative_containers * * @tparam _Key Type of key objects. * @tparam _Tp Type of mapped objects. * @tparam _Compare Comparison function object type, defaults to less<_Key>. * @tparam _Alloc Allocator type, defaults to * allocator. * * Meets the requirements of a container, a * reversible container, and an * associative container (using unique keys). * For a @c map the key_type is Key, the mapped_type is T, and the * value_type is std::pair. * * Maps support bidirectional iterators. * * The private tree data is declared exactly the same way for map and * multimap; the distinction is made entirely in how the tree functions are * called (*_unique versus *_equal, same as the standard). */ template , typename _Alloc = std::allocator > > class map { public: typedef _Key key_type; typedef _Tp mapped_type; typedef std::pair value_type; typedef _Compare key_compare; typedef _Alloc allocator_type; private: #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Alloc::value_type _Alloc_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) # endif __glibcxx_class_requires4(_Compare, bool, _Key, _Key, _BinaryFunctionConcept) __glibcxx_class_requires2(value_type, _Alloc_value_type, _SameTypeConcept) #endif #if __cplusplus >= 201103L && defined(__STRICT_ANSI__) static_assert(is_same::value, "std::map must have the same value_type as its allocator"); #endif public: class value_compare : public std::binary_function { friend class map<_Key, _Tp, _Compare, _Alloc>; protected: _Compare comp; value_compare(_Compare __c) : comp(__c) { } public: bool operator()(const value_type& __x, const value_type& __y) const { return comp(__x.first, __y.first); } }; private: /// This turns a red-black tree into a [multi]map. typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind::other _Pair_alloc_type; typedef _Rb_tree, key_compare, _Pair_alloc_type> _Rep_type; /// The actual tree structure. _Rep_type _M_t; typedef __gnu_cxx::__alloc_traits<_Pair_alloc_type> _Alloc_traits; public: // many of these are specified differently in ISO, but the following are // "functionally equivalent" typedef typename _Alloc_traits::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef typename _Alloc_traits::reference reference; typedef typename _Alloc_traits::const_reference const_reference; typedef typename _Rep_type::iterator iterator; typedef typename _Rep_type::const_iterator const_iterator; typedef typename _Rep_type::size_type size_type; typedef typename _Rep_type::difference_type difference_type; typedef typename _Rep_type::reverse_iterator reverse_iterator; typedef typename _Rep_type::const_reverse_iterator const_reverse_iterator; #if __cplusplus > 201402L using node_type = typename _Rep_type::node_type; using insert_return_type = typename _Rep_type::insert_return_type; #endif // [23.3.1.1] construct/copy/destroy // (get_allocator() is also listed in this section) /** * @brief Default constructor creates no elements. */ #if __cplusplus < 201103L map() : _M_t() { } #else map() = default; #endif /** * @brief Creates a %map with no elements. * @param __comp A comparison object. * @param __a An allocator object. */ explicit map(const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Pair_alloc_type(__a)) { } /** * @brief %Map copy constructor. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L map(const map& __x) : _M_t(__x._M_t) { } #else map(const map&) = default; /** * @brief %Map move constructor. * * The newly-created %map contains the exact contents of the moved * instance. The moved instance is a valid, but unspecified, %map. */ map(map&&) = default; /** * @brief Builds a %map from an initializer_list. * @param __l An initializer_list. * @param __comp A comparison object. * @param __a An allocator object. * * Create a %map consisting of copies of the elements in the * initializer_list @a __l. * This is linear in N if the range is already sorted, and NlogN * otherwise (where N is @a __l.size()). */ map(initializer_list __l, const _Compare& __comp = _Compare(), const allocator_type& __a = allocator_type()) : _M_t(__comp, _Pair_alloc_type(__a)) { _M_t._M_insert_unique(__l.begin(), __l.end()); } /// Allocator-extended default constructor. explicit map(const allocator_type& __a) : _M_t(_Compare(), _Pair_alloc_type(__a)) { } /// Allocator-extended copy constructor. map(const map& __m, const allocator_type& __a) : _M_t(__m._M_t, _Pair_alloc_type(__a)) { } /// Allocator-extended move constructor. map(map&& __m, const allocator_type& __a) noexcept(is_nothrow_copy_constructible<_Compare>::value && _Alloc_traits::_S_always_equal()) : _M_t(std::move(__m._M_t), _Pair_alloc_type(__a)) { } /// Allocator-extended initialier-list constructor. map(initializer_list __l, const allocator_type& __a) : _M_t(_Compare(), _Pair_alloc_type(__a)) { _M_t._M_insert_unique(__l.begin(), __l.end()); } /// Allocator-extended range constructor. template map(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _M_t(_Compare(), _Pair_alloc_type(__a)) { _M_t._M_insert_unique(__first, __last); } #endif /** * @brief Builds a %map from a range. * @param __first An input iterator. * @param __last An input iterator. * * Create a %map consisting of copies of the elements from * [__first,__last). This is linear in N if the range is * already sorted, and NlogN otherwise (where N is * distance(__first,__last)). */ template map(_InputIterator __first, _InputIterator __last) : _M_t() { _M_t._M_insert_unique(__first, __last); } /** * @brief Builds a %map from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __comp A comparison functor. * @param __a An allocator object. * * Create a %map consisting of copies of the elements from * [__first,__last). This is linear in N if the range is * already sorted, and NlogN otherwise (where N is * distance(__first,__last)). */ template map(_InputIterator __first, _InputIterator __last, const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Pair_alloc_type(__a)) { _M_t._M_insert_unique(__first, __last); } #if __cplusplus >= 201103L /** * The dtor only erases the elements, and note that if the elements * themselves are pointers, the pointed-to memory is not touched in any * way. Managing the pointer is the user's responsibility. */ ~map() = default; #endif /** * @brief %Map assignment operator. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L map& operator=(const map& __x) { _M_t = __x._M_t; return *this; } #else map& operator=(const map&) = default; /// Move assignment operator. map& operator=(map&&) = default; /** * @brief %Map list assignment operator. * @param __l An initializer_list. * * This function fills a %map with copies of the elements in the * initializer list @a __l. * * Note that the assignment completely changes the %map and * that the resulting %map's size is the same as the number * of elements assigned. */ map& operator=(initializer_list __l) { _M_t._M_assign_unique(__l.begin(), __l.end()); return *this; } #endif /// Get a copy of the memory allocation object. allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_t.get_allocator()); } // iterators /** * Returns a read/write iterator that points to the first pair in the * %map. * Iteration is done in ascending order according to the keys. */ iterator begin() _GLIBCXX_NOEXCEPT { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points to the first pair * in the %map. Iteration is done in ascending order according to the * keys. */ const_iterator begin() const _GLIBCXX_NOEXCEPT { return _M_t.begin(); } /** * Returns a read/write iterator that points one past the last * pair in the %map. Iteration is done in ascending order * according to the keys. */ iterator end() _GLIBCXX_NOEXCEPT { return _M_t.end(); } /** * Returns a read-only (constant) iterator that points one past the last * pair in the %map. Iteration is done in ascending order according to * the keys. */ const_iterator end() const _GLIBCXX_NOEXCEPT { return _M_t.end(); } /** * Returns a read/write reverse iterator that points to the last pair in * the %map. Iteration is done in descending order according to the * keys. */ reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to the * last pair in the %map. Iteration is done in descending order * according to the keys. */ const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return _M_t.rbegin(); } /** * Returns a read/write reverse iterator that points to one before the * first pair in the %map. Iteration is done in descending order * according to the keys. */ reverse_iterator rend() _GLIBCXX_NOEXCEPT { return _M_t.rend(); } /** * Returns a read-only (constant) reverse iterator that points to one * before the first pair in the %map. Iteration is done in descending * order according to the keys. */ const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return _M_t.rend(); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the first pair * in the %map. Iteration is done in ascending order according to the * keys. */ const_iterator cbegin() const noexcept { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * pair in the %map. Iteration is done in ascending order according to * the keys. */ const_iterator cend() const noexcept { return _M_t.end(); } /** * Returns a read-only (constant) reverse iterator that points to the * last pair in the %map. Iteration is done in descending order * according to the keys. */ const_reverse_iterator crbegin() const noexcept { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to one * before the first pair in the %map. Iteration is done in descending * order according to the keys. */ const_reverse_iterator crend() const noexcept { return _M_t.rend(); } #endif // capacity /** Returns true if the %map is empty. (Thus begin() would equal * end().) */ bool empty() const _GLIBCXX_NOEXCEPT { return _M_t.empty(); } /** Returns the size of the %map. */ size_type size() const _GLIBCXX_NOEXCEPT { return _M_t.size(); } /** Returns the maximum size of the %map. */ size_type max_size() const _GLIBCXX_NOEXCEPT { return _M_t.max_size(); } // [23.3.1.2] element access /** * @brief Subscript ( @c [] ) access to %map data. * @param __k The key for which data should be retrieved. * @return A reference to the data of the (key,data) %pair. * * Allows for easy lookup with the subscript ( @c [] ) * operator. Returns data associated with the key specified in * subscript. If the key does not exist, a pair with that key * is created using default values, which is then returned. * * Lookup requires logarithmic time. */ mapped_type& operator[](const key_type& __k) { // concept requirements __glibcxx_function_requires(_DefaultConstructibleConcept) iterator __i = lower_bound(__k); // __i->first is greater than or equivalent to __k. if (__i == end() || key_comp()(__k, (*__i).first)) #if __cplusplus >= 201103L __i = _M_t._M_emplace_hint_unique(__i, std::piecewise_construct, std::tuple(__k), std::tuple<>()); #else __i = insert(__i, value_type(__k, mapped_type())); #endif return (*__i).second; } #if __cplusplus >= 201103L mapped_type& operator[](key_type&& __k) { // concept requirements __glibcxx_function_requires(_DefaultConstructibleConcept) iterator __i = lower_bound(__k); // __i->first is greater than or equivalent to __k. if (__i == end() || key_comp()(__k, (*__i).first)) __i = _M_t._M_emplace_hint_unique(__i, std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::tuple<>()); return (*__i).second; } #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 464. Suggestion for new member functions in standard containers. /** * @brief Access to %map data. * @param __k The key for which data should be retrieved. * @return A reference to the data whose key is equivalent to @a __k, if * such a data is present in the %map. * @throw std::out_of_range If no such data is present. */ mapped_type& at(const key_type& __k) { iterator __i = lower_bound(__k); if (__i == end() || key_comp()(__k, (*__i).first)) __throw_out_of_range(__N("map::at")); return (*__i).second; } const mapped_type& at(const key_type& __k) const { const_iterator __i = lower_bound(__k); if (__i == end() || key_comp()(__k, (*__i).first)) __throw_out_of_range(__N("map::at")); return (*__i).second; } // modifiers #if __cplusplus >= 201103L /** * @brief Attempts to build and insert a std::pair into the %map. * * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * * @return A pair, of which the first element is an iterator that points * to the possibly inserted pair, and the second is a bool that * is true if the pair was actually inserted. * * This function attempts to build and insert a (key, value) %pair into * the %map. * A %map relies on unique keys and thus a %pair is only inserted if its * first element (the key) is not already present in the %map. * * Insertion requires logarithmic time. */ template std::pair emplace(_Args&&... __args) { return _M_t._M_emplace_unique(std::forward<_Args>(__args)...); } /** * @brief Attempts to build and insert a std::pair into the %map. * * @param __pos An iterator that serves as a hint as to where the pair * should be inserted. * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * @return An iterator that points to the element with key of the * std::pair built from @a __args (may or may not be that * std::pair). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument emplace() * does. * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires logarithmic time (if the hint is not taken). */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_t._M_emplace_hint_unique(__pos, std::forward<_Args>(__args)...); } #endif #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_t.extract(__pos); } /// Extract a node. node_type extract(const key_type& __x) { return _M_t.extract(__x); } /// Re-insert an extracted node. insert_return_type insert(node_type&& __nh) { return _M_t._M_reinsert_node_unique(std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator __hint, node_type&& __nh) { return _M_t._M_reinsert_node_hint_unique(__hint, std::move(__nh)); } template friend class std::_Rb_tree_merge_helper; template void merge(map<_Key, _Tp, _C2, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_unique(_Merge_helper::_S_get_tree(__source)); } template void merge(map<_Key, _Tp, _C2, _Alloc>&& __source) { merge(__source); } template void merge(multimap<_Key, _Tp, _C2, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_unique(_Merge_helper::_S_get_tree(__source)); } template void merge(multimap<_Key, _Tp, _C2, _Alloc>&& __source) { merge(__source); } #endif // C++17 #if __cplusplus > 201402L #define __cpp_lib_map_try_emplace 201411 /** * @brief Attempts to build and insert a std::pair into the %map. * * @param __k Key to use for finding a possibly existing pair in * the map. * @param __args Arguments used to generate the .second for a new pair * instance. * * @return A pair, of which the first element is an iterator that points * to the possibly inserted pair, and the second is a bool that * is true if the pair was actually inserted. * * This function attempts to build and insert a (key, value) %pair into * the %map. * A %map relies on unique keys and thus a %pair is only inserted if its * first element (the key) is not already present in the %map. * If a %pair is not inserted, this function has no effect. * * Insertion requires logarithmic time. */ template pair try_emplace(const key_type& __k, _Args&&... __args) { iterator __i = lower_bound(__k); if (__i == end() || key_comp()(__k, (*__i).first)) { __i = emplace_hint(__i, std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple( std::forward<_Args>(__args)...)); return {__i, true}; } return {__i, false}; } // move-capable overload template pair try_emplace(key_type&& __k, _Args&&... __args) { iterator __i = lower_bound(__k); if (__i == end() || key_comp()(__k, (*__i).first)) { __i = emplace_hint(__i, std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple( std::forward<_Args>(__args)...)); return {__i, true}; } return {__i, false}; } /** * @brief Attempts to build and insert a std::pair into the %map. * * @param __hint An iterator that serves as a hint as to where the * pair should be inserted. * @param __k Key to use for finding a possibly existing pair in * the map. * @param __args Arguments used to generate the .second for a new pair * instance. * @return An iterator that points to the element with key of the * std::pair built from @a __args (may or may not be that * std::pair). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument * try_emplace() does. However, if insertion did not take place, * this function has no effect. * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires logarithmic time (if the hint is not taken). */ template iterator try_emplace(const_iterator __hint, const key_type& __k, _Args&&... __args) { iterator __i; auto __true_hint = _M_t._M_get_insert_hint_unique_pos(__hint, __k); if (__true_hint.second) __i = emplace_hint(iterator(__true_hint.second), std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple( std::forward<_Args>(__args)...)); else __i = iterator(__true_hint.first); return __i; } // move-capable overload template iterator try_emplace(const_iterator __hint, key_type&& __k, _Args&&... __args) { iterator __i; auto __true_hint = _M_t._M_get_insert_hint_unique_pos(__hint, __k); if (__true_hint.second) __i = emplace_hint(iterator(__true_hint.second), std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple( std::forward<_Args>(__args)...)); else __i = iterator(__true_hint.first); return __i; } #endif /** * @brief Attempts to insert a std::pair into the %map. * @param __x Pair to be inserted (see std::make_pair for easy * creation of pairs). * * @return A pair, of which the first element is an iterator that * points to the possibly inserted pair, and the second is * a bool that is true if the pair was actually inserted. * * This function attempts to insert a (key, value) %pair into the %map. * A %map relies on unique keys and thus a %pair is only inserted if its * first element (the key) is not already present in the %map. * * Insertion requires logarithmic time. * @{ */ std::pair insert(const value_type& __x) { return _M_t._M_insert_unique(__x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init std::pair insert(value_type&& __x) { return _M_t._M_insert_unique(std::move(__x)); } template __enable_if_t::value, pair> insert(_Pair&& __x) { return _M_t._M_emplace_unique(std::forward<_Pair>(__x)); } #endif // @} #if __cplusplus >= 201103L /** * @brief Attempts to insert a list of std::pairs into the %map. * @param __list A std::initializer_list of pairs to be * inserted. * * Complexity similar to that of the range constructor. */ void insert(std::initializer_list __list) { insert(__list.begin(), __list.end()); } #endif /** * @brief Attempts to insert a std::pair into the %map. * @param __position An iterator that serves as a hint as to where the * pair should be inserted. * @param __x Pair to be inserted (see std::make_pair for easy creation * of pairs). * @return An iterator that points to the element with key of * @a __x (may or may not be the %pair passed in). * * This function is not concerned about whether the insertion * took place, and thus does not return a boolean like the * single-argument insert() does. Note that the first * parameter is only a hint and can potentially improve the * performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires logarithmic time (if the hint is not taken). * @{ */ iterator #if __cplusplus >= 201103L insert(const_iterator __position, const value_type& __x) #else insert(iterator __position, const value_type& __x) #endif { return _M_t._M_insert_unique_(__position, __x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __position, value_type&& __x) { return _M_t._M_insert_unique_(__position, std::move(__x)); } template __enable_if_t::value, iterator> insert(const_iterator __position, _Pair&& __x) { return _M_t._M_emplace_hint_unique(__position, std::forward<_Pair>(__x)); } #endif // @} /** * @brief Template function that attempts to insert a range of elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_t._M_insert_unique(__first, __last); } #if __cplusplus > 201402L #define __cpp_lib_map_insertion 201411 /** * @brief Attempts to insert or assign a std::pair into the %map. * @param __k Key to use for finding a possibly existing pair in * the map. * @param __obj Argument used to generate the .second for a pair * instance. * * @return A pair, of which the first element is an iterator that * points to the possibly inserted pair, and the second is * a bool that is true if the pair was actually inserted. * * This function attempts to insert a (key, value) %pair into the %map. * A %map relies on unique keys and thus a %pair is only inserted if its * first element (the key) is not already present in the %map. * If the %pair was already in the %map, the .second of the %pair * is assigned from __obj. * * Insertion requires logarithmic time. */ template pair insert_or_assign(const key_type& __k, _Obj&& __obj) { iterator __i = lower_bound(__k); if (__i == end() || key_comp()(__k, (*__i).first)) { __i = emplace_hint(__i, std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple( std::forward<_Obj>(__obj))); return {__i, true}; } (*__i).second = std::forward<_Obj>(__obj); return {__i, false}; } // move-capable overload template pair insert_or_assign(key_type&& __k, _Obj&& __obj) { iterator __i = lower_bound(__k); if (__i == end() || key_comp()(__k, (*__i).first)) { __i = emplace_hint(__i, std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple( std::forward<_Obj>(__obj))); return {__i, true}; } (*__i).second = std::forward<_Obj>(__obj); return {__i, false}; } /** * @brief Attempts to insert or assign a std::pair into the %map. * @param __hint An iterator that serves as a hint as to where the * pair should be inserted. * @param __k Key to use for finding a possibly existing pair in * the map. * @param __obj Argument used to generate the .second for a pair * instance. * * @return An iterator that points to the element with key of * @a __x (may or may not be the %pair passed in). * * This function attempts to insert a (key, value) %pair into the %map. * A %map relies on unique keys and thus a %pair is only inserted if its * first element (the key) is not already present in the %map. * If the %pair was already in the %map, the .second of the %pair * is assigned from __obj. * * Insertion requires logarithmic time. */ template iterator insert_or_assign(const_iterator __hint, const key_type& __k, _Obj&& __obj) { iterator __i; auto __true_hint = _M_t._M_get_insert_hint_unique_pos(__hint, __k); if (__true_hint.second) { return emplace_hint(iterator(__true_hint.second), std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple( std::forward<_Obj>(__obj))); } __i = iterator(__true_hint.first); (*__i).second = std::forward<_Obj>(__obj); return __i; } // move-capable overload template iterator insert_or_assign(const_iterator __hint, key_type&& __k, _Obj&& __obj) { iterator __i; auto __true_hint = _M_t._M_get_insert_hint_unique_pos(__hint, __k); if (__true_hint.second) { return emplace_hint(iterator(__true_hint.second), std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple( std::forward<_Obj>(__obj))); } __i = iterator(__true_hint.first); (*__i).second = std::forward<_Obj>(__obj); return __i; } #endif #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases an element from a %map. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given * iterator, from a %map. Note that this function only erases * the element, and that if the element is itself a pointer, * the pointed-to memory is not touched in any way. Managing * the pointer is the user's responsibility. * * @{ */ iterator erase(const_iterator __position) { return _M_t.erase(__position); } // LWG 2059 _GLIBCXX_ABI_TAG_CXX11 iterator erase(iterator __position) { return _M_t.erase(__position); } // @} #else /** * @brief Erases an element from a %map. * @param __position An iterator pointing to the element to be erased. * * This function erases an element, pointed to by the given * iterator, from a %map. Note that this function only erases * the element, and that if the element is itself a pointer, * the pointed-to memory is not touched in any way. Managing * the pointer is the user's responsibility. */ void erase(iterator __position) { _M_t.erase(__position); } #endif /** * @brief Erases elements according to the provided key. * @param __x Key of element to be erased. * @return The number of elements erased. * * This function erases all the elements located by the given key from * a %map. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_t.erase(__x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases a [first,last) range of elements from a %map. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * @return The iterator @a __last. * * This function erases a sequence of elements from a %map. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __first, const_iterator __last) { return _M_t.erase(__first, __last); } #else /** * @brief Erases a [__first,__last) range of elements from a %map. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * * This function erases a sequence of elements from a %map. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ void erase(iterator __first, iterator __last) { _M_t.erase(__first, __last); } #endif /** * @brief Swaps data with another %map. * @param __x A %map of the same element and allocator types. * * This exchanges the elements between two maps in constant * time. (It is only swapping a pointer, an integer, and an * instance of the @c Compare type (which itself is often * stateless and empty), so it should be quite fast.) Note * that the global std::swap() function is specialized such * that std::swap(m1,m2) will feed to this function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(map& __x) _GLIBCXX_NOEXCEPT_IF(__is_nothrow_swappable<_Compare>::value) { _M_t.swap(__x._M_t); } /** * Erases all elements in a %map. Note that this function only * erases the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibility. */ void clear() _GLIBCXX_NOEXCEPT { _M_t.clear(); } // observers /** * Returns the key comparison object out of which the %map was * constructed. */ key_compare key_comp() const { return _M_t.key_comp(); } /** * Returns a value comparison object, built from the key comparison * object out of which the %map was constructed. */ value_compare value_comp() const { return value_compare(_M_t.key_comp()); } // [23.3.1.3] map operations //@{ /** * @brief Tries to locate an element in a %map. * @param __x Key of (key, value) %pair to be located. * @return Iterator pointing to sought-after element, or end() if not * found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after %pair. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_t.find(__x); } #if __cplusplus > 201103L template auto find(const _Kt& __x) -> decltype(_M_t._M_find_tr(__x)) { return _M_t._M_find_tr(__x); } #endif //@} //@{ /** * @brief Tries to locate an element in a %map. * @param __x Key of (key, value) %pair to be located. * @return Read-only (constant) iterator pointing to sought-after * element, or end() if not found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns a constant * iterator pointing to the sought after %pair. If unsuccessful it * returns the past-the-end ( @c end() ) iterator. */ const_iterator find(const key_type& __x) const { return _M_t.find(__x); } #if __cplusplus > 201103L template auto find(const _Kt& __x) const -> decltype(_M_t._M_find_tr(__x)) { return _M_t._M_find_tr(__x); } #endif //@} //@{ /** * @brief Finds the number of elements with given key. * @param __x Key of (key, value) pairs to be located. * @return Number of elements with specified key. * * This function only makes sense for multimaps; for map the result will * either be 0 (not present) or 1 (present). */ size_type count(const key_type& __x) const { return _M_t.find(__x) == _M_t.end() ? 0 : 1; } #if __cplusplus > 201103L template auto count(const _Kt& __x) const -> decltype(_M_t._M_count_tr(__x)) { return _M_t._M_count_tr(__x); } #endif //@} //@{ /** * @brief Finds the beginning of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Iterator pointing to first element equal to or greater * than key, or end(). * * This function returns the first element of a subsequence of elements * that matches the given key. If unsuccessful it returns an iterator * pointing to the first element that has a greater value than given key * or end() if no such element exists. */ iterator lower_bound(const key_type& __x) { return _M_t.lower_bound(__x); } #if __cplusplus > 201103L template auto lower_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_lower_bound_tr(__x))) { return iterator(_M_t._M_lower_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the beginning of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Read-only (constant) iterator pointing to first element * equal to or greater than key, or end(). * * This function returns the first element of a subsequence of elements * that matches the given key. If unsuccessful it returns an iterator * pointing to the first element that has a greater value than given key * or end() if no such element exists. */ const_iterator lower_bound(const key_type& __x) const { return _M_t.lower_bound(__x); } #if __cplusplus > 201103L template auto lower_bound(const _Kt& __x) const -> decltype(const_iterator(_M_t._M_lower_bound_tr(__x))) { return const_iterator(_M_t._M_lower_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the end of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Iterator pointing to the first element * greater than key, or end(). */ iterator upper_bound(const key_type& __x) { return _M_t.upper_bound(__x); } #if __cplusplus > 201103L template auto upper_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_upper_bound_tr(__x))) { return iterator(_M_t._M_upper_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the end of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Read-only (constant) iterator pointing to first iterator * greater than key, or end(). */ const_iterator upper_bound(const key_type& __x) const { return _M_t.upper_bound(__x); } #if __cplusplus > 201103L template auto upper_bound(const _Kt& __x) const -> decltype(const_iterator(_M_t._M_upper_bound_tr(__x))) { return const_iterator(_M_t._M_upper_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key of (key, value) pairs to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. * * This function is equivalent to * @code * std::make_pair(c.lower_bound(val), * c.upper_bound(val)) * @endcode * (but is faster than making the calls separately). * * This function probably only makes sense for multimaps. */ std::pair equal_range(const key_type& __x) { return _M_t.equal_range(__x); } #if __cplusplus > 201103L template auto equal_range(const _Kt& __x) -> decltype(pair(_M_t._M_equal_range_tr(__x))) { return pair(_M_t._M_equal_range_tr(__x)); } #endif //@} //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key of (key, value) pairs to be located. * @return Pair of read-only (constant) iterators that possibly points * to the subsequence matching given key. * * This function is equivalent to * @code * std::make_pair(c.lower_bound(val), * c.upper_bound(val)) * @endcode * (but is faster than making the calls separately). * * This function probably only makes sense for multimaps. */ std::pair equal_range(const key_type& __x) const { return _M_t.equal_range(__x); } #if __cplusplus > 201103L template auto equal_range(const _Kt& __x) const -> decltype(pair( _M_t._M_equal_range_tr(__x))) { return pair( _M_t._M_equal_range_tr(__x)); } #endif //@} template friend bool operator==(const map<_K1, _T1, _C1, _A1>&, const map<_K1, _T1, _C1, _A1>&); template friend bool operator<(const map<_K1, _T1, _C1, _A1>&, const map<_K1, _T1, _C1, _A1>&); }; #if __cpp_deduction_guides >= 201606 template>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> map(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Compare, _Allocator>; template, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> map(initializer_list>, _Compare = _Compare(), _Allocator = _Allocator()) -> map<_Key, _Tp, _Compare, _Allocator>; template , typename = _RequireAllocator<_Allocator>> map(_InputIterator, _InputIterator, _Allocator) -> map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, less<__iter_key_t<_InputIterator>>, _Allocator>; template> map(initializer_list>, _Allocator) -> map<_Key, _Tp, less<_Key>, _Allocator>; #endif /** * @brief Map equality comparison. * @param __x A %map. * @param __y A %map of the same type as @a x. * @return True iff the size and elements of the maps are equal. * * This is an equivalence relation. It is linear in the size of the * maps. Maps are considered equivalent if their sizes are equal, * and if corresponding elements compare equal. */ template inline bool operator==(const map<_Key, _Tp, _Compare, _Alloc>& __x, const map<_Key, _Tp, _Compare, _Alloc>& __y) { return __x._M_t == __y._M_t; } /** * @brief Map ordering relation. * @param __x A %map. * @param __y A %map of the same type as @a x. * @return True iff @a x is lexicographically less than @a y. * * This is a total ordering relation. It is linear in the size of the * maps. The elements must be comparable with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const map<_Key, _Tp, _Compare, _Alloc>& __x, const map<_Key, _Tp, _Compare, _Alloc>& __y) { return __x._M_t < __y._M_t; } /// Based on operator== template inline bool operator!=(const map<_Key, _Tp, _Compare, _Alloc>& __x, const map<_Key, _Tp, _Compare, _Alloc>& __y) { return !(__x == __y); } /// Based on operator< template inline bool operator>(const map<_Key, _Tp, _Compare, _Alloc>& __x, const map<_Key, _Tp, _Compare, _Alloc>& __y) { return __y < __x; } /// Based on operator< template inline bool operator<=(const map<_Key, _Tp, _Compare, _Alloc>& __x, const map<_Key, _Tp, _Compare, _Alloc>& __y) { return !(__y < __x); } /// Based on operator< template inline bool operator>=(const map<_Key, _Tp, _Compare, _Alloc>& __x, const map<_Key, _Tp, _Compare, _Alloc>& __y) { return !(__x < __y); } /// See std::map::swap(). template inline void swap(map<_Key, _Tp, _Compare, _Alloc>& __x, map<_Key, _Tp, _Compare, _Alloc>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { __x.swap(__y); } _GLIBCXX_END_NAMESPACE_CONTAINER #if __cplusplus > 201402L // Allow std::map access to internals of compatible maps. template struct _Rb_tree_merge_helper<_GLIBCXX_STD_C::map<_Key, _Val, _Cmp1, _Alloc>, _Cmp2> { private: friend class _GLIBCXX_STD_C::map<_Key, _Val, _Cmp1, _Alloc>; static auto& _S_get_tree(_GLIBCXX_STD_C::map<_Key, _Val, _Cmp2, _Alloc>& __map) { return __map._M_t; } static auto& _S_get_tree(_GLIBCXX_STD_C::multimap<_Key, _Val, _Cmp2, _Alloc>& __map) { return __map._M_t; } }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_MAP_H */ PK!~UU8/bits/stl_multimap.hnu[// Multimap implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_multimap.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{map} */ #ifndef _STL_MULTIMAP_H #define _STL_MULTIMAP_H 1 #include #if __cplusplus >= 201103L #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER template class map; /** * @brief A standard container made up of (key,value) pairs, which can be * retrieved based on a key, in logarithmic time. * * @ingroup associative_containers * * @tparam _Key Type of key objects. * @tparam _Tp Type of mapped objects. * @tparam _Compare Comparison function object type, defaults to less<_Key>. * @tparam _Alloc Allocator type, defaults to * allocator. * * Meets the requirements of a container, a * reversible container, and an * associative container (using equivalent * keys). For a @c multimap the key_type is Key, the mapped_type * is T, and the value_type is std::pair. * * Multimaps support bidirectional iterators. * * The private tree data is declared exactly the same way for map and * multimap; the distinction is made entirely in how the tree functions are * called (*_unique versus *_equal, same as the standard). */ template , typename _Alloc = std::allocator > > class multimap { public: typedef _Key key_type; typedef _Tp mapped_type; typedef std::pair value_type; typedef _Compare key_compare; typedef _Alloc allocator_type; private: #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Alloc::value_type _Alloc_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) # endif __glibcxx_class_requires4(_Compare, bool, _Key, _Key, _BinaryFunctionConcept) __glibcxx_class_requires2(value_type, _Alloc_value_type, _SameTypeConcept) #endif #if __cplusplus >= 201103L && defined(__STRICT_ANSI__) static_assert(is_same::value, "std::multimap must have the same value_type as its allocator"); #endif public: class value_compare : public std::binary_function { friend class multimap<_Key, _Tp, _Compare, _Alloc>; protected: _Compare comp; value_compare(_Compare __c) : comp(__c) { } public: bool operator()(const value_type& __x, const value_type& __y) const { return comp(__x.first, __y.first); } }; private: /// This turns a red-black tree into a [multi]map. typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind::other _Pair_alloc_type; typedef _Rb_tree, key_compare, _Pair_alloc_type> _Rep_type; /// The actual tree structure. _Rep_type _M_t; typedef __gnu_cxx::__alloc_traits<_Pair_alloc_type> _Alloc_traits; public: // many of these are specified differently in ISO, but the following are // "functionally equivalent" typedef typename _Alloc_traits::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef typename _Alloc_traits::reference reference; typedef typename _Alloc_traits::const_reference const_reference; typedef typename _Rep_type::iterator iterator; typedef typename _Rep_type::const_iterator const_iterator; typedef typename _Rep_type::size_type size_type; typedef typename _Rep_type::difference_type difference_type; typedef typename _Rep_type::reverse_iterator reverse_iterator; typedef typename _Rep_type::const_reverse_iterator const_reverse_iterator; #if __cplusplus > 201402L using node_type = typename _Rep_type::node_type; #endif // [23.3.2] construct/copy/destroy // (get_allocator() is also listed in this section) /** * @brief Default constructor creates no elements. */ #if __cplusplus < 201103L multimap() : _M_t() { } #else multimap() = default; #endif /** * @brief Creates a %multimap with no elements. * @param __comp A comparison object. * @param __a An allocator object. */ explicit multimap(const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Pair_alloc_type(__a)) { } /** * @brief %Multimap copy constructor. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L multimap(const multimap& __x) : _M_t(__x._M_t) { } #else multimap(const multimap&) = default; /** * @brief %Multimap move constructor. * * The newly-created %multimap contains the exact contents of the * moved instance. The moved instance is a valid, but unspecified * %multimap. */ multimap(multimap&&) = default; /** * @brief Builds a %multimap from an initializer_list. * @param __l An initializer_list. * @param __comp A comparison functor. * @param __a An allocator object. * * Create a %multimap consisting of copies of the elements from * the initializer_list. This is linear in N if the list is already * sorted, and NlogN otherwise (where N is @a __l.size()). */ multimap(initializer_list __l, const _Compare& __comp = _Compare(), const allocator_type& __a = allocator_type()) : _M_t(__comp, _Pair_alloc_type(__a)) { _M_t._M_insert_equal(__l.begin(), __l.end()); } /// Allocator-extended default constructor. explicit multimap(const allocator_type& __a) : _M_t(_Compare(), _Pair_alloc_type(__a)) { } /// Allocator-extended copy constructor. multimap(const multimap& __m, const allocator_type& __a) : _M_t(__m._M_t, _Pair_alloc_type(__a)) { } /// Allocator-extended move constructor. multimap(multimap&& __m, const allocator_type& __a) noexcept(is_nothrow_copy_constructible<_Compare>::value && _Alloc_traits::_S_always_equal()) : _M_t(std::move(__m._M_t), _Pair_alloc_type(__a)) { } /// Allocator-extended initialier-list constructor. multimap(initializer_list __l, const allocator_type& __a) : _M_t(_Compare(), _Pair_alloc_type(__a)) { _M_t._M_insert_equal(__l.begin(), __l.end()); } /// Allocator-extended range constructor. template multimap(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _M_t(_Compare(), _Pair_alloc_type(__a)) { _M_t._M_insert_equal(__first, __last); } #endif /** * @brief Builds a %multimap from a range. * @param __first An input iterator. * @param __last An input iterator. * * Create a %multimap consisting of copies of the elements from * [__first,__last). This is linear in N if the range is already sorted, * and NlogN otherwise (where N is distance(__first,__last)). */ template multimap(_InputIterator __first, _InputIterator __last) : _M_t() { _M_t._M_insert_equal(__first, __last); } /** * @brief Builds a %multimap from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __comp A comparison functor. * @param __a An allocator object. * * Create a %multimap consisting of copies of the elements from * [__first,__last). This is linear in N if the range is already sorted, * and NlogN otherwise (where N is distance(__first,__last)). */ template multimap(_InputIterator __first, _InputIterator __last, const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Pair_alloc_type(__a)) { _M_t._M_insert_equal(__first, __last); } #if __cplusplus >= 201103L /** * The dtor only erases the elements, and note that if the elements * themselves are pointers, the pointed-to memory is not touched in any * way. Managing the pointer is the user's responsibility. */ ~multimap() = default; #endif /** * @brief %Multimap assignment operator. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L multimap& operator=(const multimap& __x) { _M_t = __x._M_t; return *this; } #else multimap& operator=(const multimap&) = default; /// Move assignment operator. multimap& operator=(multimap&&) = default; /** * @brief %Multimap list assignment operator. * @param __l An initializer_list. * * This function fills a %multimap with copies of the elements * in the initializer list @a __l. * * Note that the assignment completely changes the %multimap and * that the resulting %multimap's size is the same as the number * of elements assigned. */ multimap& operator=(initializer_list __l) { _M_t._M_assign_equal(__l.begin(), __l.end()); return *this; } #endif /// Get a copy of the memory allocation object. allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_t.get_allocator()); } // iterators /** * Returns a read/write iterator that points to the first pair in the * %multimap. Iteration is done in ascending order according to the * keys. */ iterator begin() _GLIBCXX_NOEXCEPT { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points to the first pair * in the %multimap. Iteration is done in ascending order according to * the keys. */ const_iterator begin() const _GLIBCXX_NOEXCEPT { return _M_t.begin(); } /** * Returns a read/write iterator that points one past the last pair in * the %multimap. Iteration is done in ascending order according to the * keys. */ iterator end() _GLIBCXX_NOEXCEPT { return _M_t.end(); } /** * Returns a read-only (constant) iterator that points one past the last * pair in the %multimap. Iteration is done in ascending order according * to the keys. */ const_iterator end() const _GLIBCXX_NOEXCEPT { return _M_t.end(); } /** * Returns a read/write reverse iterator that points to the last pair in * the %multimap. Iteration is done in descending order according to the * keys. */ reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to the * last pair in the %multimap. Iteration is done in descending order * according to the keys. */ const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return _M_t.rbegin(); } /** * Returns a read/write reverse iterator that points to one before the * first pair in the %multimap. Iteration is done in descending order * according to the keys. */ reverse_iterator rend() _GLIBCXX_NOEXCEPT { return _M_t.rend(); } /** * Returns a read-only (constant) reverse iterator that points to one * before the first pair in the %multimap. Iteration is done in * descending order according to the keys. */ const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return _M_t.rend(); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the first pair * in the %multimap. Iteration is done in ascending order according to * the keys. */ const_iterator cbegin() const noexcept { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * pair in the %multimap. Iteration is done in ascending order according * to the keys. */ const_iterator cend() const noexcept { return _M_t.end(); } /** * Returns a read-only (constant) reverse iterator that points to the * last pair in the %multimap. Iteration is done in descending order * according to the keys. */ const_reverse_iterator crbegin() const noexcept { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to one * before the first pair in the %multimap. Iteration is done in * descending order according to the keys. */ const_reverse_iterator crend() const noexcept { return _M_t.rend(); } #endif // capacity /** Returns true if the %multimap is empty. */ bool empty() const _GLIBCXX_NOEXCEPT { return _M_t.empty(); } /** Returns the size of the %multimap. */ size_type size() const _GLIBCXX_NOEXCEPT { return _M_t.size(); } /** Returns the maximum size of the %multimap. */ size_type max_size() const _GLIBCXX_NOEXCEPT { return _M_t.max_size(); } // modifiers #if __cplusplus >= 201103L /** * @brief Build and insert a std::pair into the %multimap. * * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * * @return An iterator that points to the inserted (key,value) pair. * * This function builds and inserts a (key, value) %pair into the * %multimap. * Contrary to a std::map the %multimap does not rely on unique keys and * thus multiple pairs with the same key can be inserted. * * Insertion requires logarithmic time. */ template iterator emplace(_Args&&... __args) { return _M_t._M_emplace_equal(std::forward<_Args>(__args)...); } /** * @brief Builds and inserts a std::pair into the %multimap. * * @param __pos An iterator that serves as a hint as to where the pair * should be inserted. * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * @return An iterator that points to the inserted (key,value) pair. * * This function inserts a (key, value) pair into the %multimap. * Contrary to a std::map the %multimap does not rely on unique keys and * thus multiple pairs with the same key can be inserted. * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires logarithmic time (if the hint is not taken). */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_t._M_emplace_hint_equal(__pos, std::forward<_Args>(__args)...); } #endif /** * @brief Inserts a std::pair into the %multimap. * @param __x Pair to be inserted (see std::make_pair for easy creation * of pairs). * @return An iterator that points to the inserted (key,value) pair. * * This function inserts a (key, value) pair into the %multimap. * Contrary to a std::map the %multimap does not rely on unique keys and * thus multiple pairs with the same key can be inserted. * * Insertion requires logarithmic time. * @{ */ iterator insert(const value_type& __x) { return _M_t._M_insert_equal(__x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(value_type&& __x) { return _M_t._M_insert_equal(std::move(__x)); } template __enable_if_t::value, iterator> insert(_Pair&& __x) { return _M_t._M_emplace_equal(std::forward<_Pair>(__x)); } #endif // @} /** * @brief Inserts a std::pair into the %multimap. * @param __position An iterator that serves as a hint as to where the * pair should be inserted. * @param __x Pair to be inserted (see std::make_pair for easy creation * of pairs). * @return An iterator that points to the inserted (key,value) pair. * * This function inserts a (key, value) pair into the %multimap. * Contrary to a std::map the %multimap does not rely on unique keys and * thus multiple pairs with the same key can be inserted. * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires logarithmic time (if the hint is not taken). * @{ */ iterator #if __cplusplus >= 201103L insert(const_iterator __position, const value_type& __x) #else insert(iterator __position, const value_type& __x) #endif { return _M_t._M_insert_equal_(__position, __x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __position, value_type&& __x) { return _M_t._M_insert_equal_(__position, std::move(__x)); } template __enable_if_t::value, iterator> insert(const_iterator __position, _Pair&& __x) { return _M_t._M_emplace_hint_equal(__position, std::forward<_Pair>(__x)); } #endif // @} /** * @brief A template function that attempts to insert a range * of elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_t._M_insert_equal(__first, __last); } #if __cplusplus >= 201103L /** * @brief Attempts to insert a list of std::pairs into the %multimap. * @param __l A std::initializer_list of pairs to be * inserted. * * Complexity similar to that of the range constructor. */ void insert(initializer_list __l) { this->insert(__l.begin(), __l.end()); } #endif #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_t.extract(__pos); } /// Extract a node. node_type extract(const key_type& __x) { return _M_t.extract(__x); } /// Re-insert an extracted node. iterator insert(node_type&& __nh) { return _M_t._M_reinsert_node_equal(std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator __hint, node_type&& __nh) { return _M_t._M_reinsert_node_hint_equal(__hint, std::move(__nh)); } template friend class std::_Rb_tree_merge_helper; template void merge(multimap<_Key, _Tp, _C2, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_equal(_Merge_helper::_S_get_tree(__source)); } template void merge(multimap<_Key, _Tp, _C2, _Alloc>&& __source) { merge(__source); } template void merge(map<_Key, _Tp, _C2, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_equal(_Merge_helper::_S_get_tree(__source)); } template void merge(map<_Key, _Tp, _C2, _Alloc>&& __source) { merge(__source); } #endif // C++17 #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases an element from a %multimap. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given iterator, * from a %multimap. Note that this function only erases the element, * and that if the element is itself a pointer, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibility. * * @{ */ iterator erase(const_iterator __position) { return _M_t.erase(__position); } // LWG 2059. _GLIBCXX_ABI_TAG_CXX11 iterator erase(iterator __position) { return _M_t.erase(__position); } // @} #else /** * @brief Erases an element from a %multimap. * @param __position An iterator pointing to the element to be erased. * * This function erases an element, pointed to by the given iterator, * from a %multimap. Note that this function only erases the element, * and that if the element is itself a pointer, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibility. */ void erase(iterator __position) { _M_t.erase(__position); } #endif /** * @brief Erases elements according to the provided key. * @param __x Key of element to be erased. * @return The number of elements erased. * * This function erases all elements located by the given key from a * %multimap. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_t.erase(__x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases a [first,last) range of elements from a %multimap. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to be * erased . * @return The iterator @a __last. * * This function erases a sequence of elements from a %multimap. * Note that this function only erases the elements, and that if * the elements themselves are pointers, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ iterator erase(const_iterator __first, const_iterator __last) { return _M_t.erase(__first, __last); } #else // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases a [first,last) range of elements from a %multimap. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * * This function erases a sequence of elements from a %multimap. * Note that this function only erases the elements, and that if * the elements themselves are pointers, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ void erase(iterator __first, iterator __last) { _M_t.erase(__first, __last); } #endif /** * @brief Swaps data with another %multimap. * @param __x A %multimap of the same element and allocator types. * * This exchanges the elements between two multimaps in constant time. * (It is only swapping a pointer, an integer, and an instance of * the @c Compare type (which itself is often stateless and empty), so it * should be quite fast.) * Note that the global std::swap() function is specialized such that * std::swap(m1,m2) will feed to this function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(multimap& __x) _GLIBCXX_NOEXCEPT_IF(__is_nothrow_swappable<_Compare>::value) { _M_t.swap(__x._M_t); } /** * Erases all elements in a %multimap. Note that this function only * erases the elements, and that if the elements themselves are pointers, * the pointed-to memory is not touched in any way. Managing the pointer * is the user's responsibility. */ void clear() _GLIBCXX_NOEXCEPT { _M_t.clear(); } // observers /** * Returns the key comparison object out of which the %multimap * was constructed. */ key_compare key_comp() const { return _M_t.key_comp(); } /** * Returns a value comparison object, built from the key comparison * object out of which the %multimap was constructed. */ value_compare value_comp() const { return value_compare(_M_t.key_comp()); } // multimap operations //@{ /** * @brief Tries to locate an element in a %multimap. * @param __x Key of (key, value) pair to be located. * @return Iterator pointing to sought-after element, * or end() if not found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after %pair. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_t.find(__x); } #if __cplusplus > 201103L template auto find(const _Kt& __x) -> decltype(_M_t._M_find_tr(__x)) { return _M_t._M_find_tr(__x); } #endif //@} //@{ /** * @brief Tries to locate an element in a %multimap. * @param __x Key of (key, value) pair to be located. * @return Read-only (constant) iterator pointing to sought-after * element, or end() if not found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns a constant * iterator pointing to the sought after %pair. If unsuccessful it * returns the past-the-end ( @c end() ) iterator. */ const_iterator find(const key_type& __x) const { return _M_t.find(__x); } #if __cplusplus > 201103L template auto find(const _Kt& __x) const -> decltype(_M_t._M_find_tr(__x)) { return _M_t._M_find_tr(__x); } #endif //@} //@{ /** * @brief Finds the number of elements with given key. * @param __x Key of (key, value) pairs to be located. * @return Number of elements with specified key. */ size_type count(const key_type& __x) const { return _M_t.count(__x); } #if __cplusplus > 201103L template auto count(const _Kt& __x) const -> decltype(_M_t._M_count_tr(__x)) { return _M_t._M_count_tr(__x); } #endif //@} //@{ /** * @brief Finds the beginning of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Iterator pointing to first element equal to or greater * than key, or end(). * * This function returns the first element of a subsequence of elements * that matches the given key. If unsuccessful it returns an iterator * pointing to the first element that has a greater value than given key * or end() if no such element exists. */ iterator lower_bound(const key_type& __x) { return _M_t.lower_bound(__x); } #if __cplusplus > 201103L template auto lower_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_lower_bound_tr(__x))) { return iterator(_M_t._M_lower_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the beginning of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Read-only (constant) iterator pointing to first element * equal to or greater than key, or end(). * * This function returns the first element of a subsequence of * elements that matches the given key. If unsuccessful the * iterator will point to the next greatest element or, if no * such greater element exists, to end(). */ const_iterator lower_bound(const key_type& __x) const { return _M_t.lower_bound(__x); } #if __cplusplus > 201103L template auto lower_bound(const _Kt& __x) const -> decltype(const_iterator(_M_t._M_lower_bound_tr(__x))) { return const_iterator(_M_t._M_lower_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the end of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Iterator pointing to the first element * greater than key, or end(). */ iterator upper_bound(const key_type& __x) { return _M_t.upper_bound(__x); } #if __cplusplus > 201103L template auto upper_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_upper_bound_tr(__x))) { return iterator(_M_t._M_upper_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the end of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Read-only (constant) iterator pointing to first iterator * greater than key, or end(). */ const_iterator upper_bound(const key_type& __x) const { return _M_t.upper_bound(__x); } #if __cplusplus > 201103L template auto upper_bound(const _Kt& __x) const -> decltype(const_iterator(_M_t._M_upper_bound_tr(__x))) { return const_iterator(_M_t._M_upper_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key of (key, value) pairs to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. * * This function is equivalent to * @code * std::make_pair(c.lower_bound(val), * c.upper_bound(val)) * @endcode * (but is faster than making the calls separately). */ std::pair equal_range(const key_type& __x) { return _M_t.equal_range(__x); } #if __cplusplus > 201103L template auto equal_range(const _Kt& __x) -> decltype(pair(_M_t._M_equal_range_tr(__x))) { return pair(_M_t._M_equal_range_tr(__x)); } #endif //@} //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key of (key, value) pairs to be located. * @return Pair of read-only (constant) iterators that possibly points * to the subsequence matching given key. * * This function is equivalent to * @code * std::make_pair(c.lower_bound(val), * c.upper_bound(val)) * @endcode * (but is faster than making the calls separately). */ std::pair equal_range(const key_type& __x) const { return _M_t.equal_range(__x); } #if __cplusplus > 201103L template auto equal_range(const _Kt& __x) const -> decltype(pair( _M_t._M_equal_range_tr(__x))) { return pair( _M_t._M_equal_range_tr(__x)); } #endif //@} template friend bool operator==(const multimap<_K1, _T1, _C1, _A1>&, const multimap<_K1, _T1, _C1, _A1>&); template friend bool operator<(const multimap<_K1, _T1, _C1, _A1>&, const multimap<_K1, _T1, _C1, _A1>&); }; #if __cpp_deduction_guides >= 201606 template>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> multimap(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Compare, _Allocator>; template, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> multimap(initializer_list>, _Compare = _Compare(), _Allocator = _Allocator()) -> multimap<_Key, _Tp, _Compare, _Allocator>; template, typename = _RequireAllocator<_Allocator>> multimap(_InputIterator, _InputIterator, _Allocator) -> multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, less<__iter_key_t<_InputIterator>>, _Allocator>; template> multimap(initializer_list>, _Allocator) -> multimap<_Key, _Tp, less<_Key>, _Allocator>; #endif /** * @brief Multimap equality comparison. * @param __x A %multimap. * @param __y A %multimap of the same type as @a __x. * @return True iff the size and elements of the maps are equal. * * This is an equivalence relation. It is linear in the size of the * multimaps. Multimaps are considered equivalent if their sizes are equal, * and if corresponding elements compare equal. */ template inline bool operator==(const multimap<_Key, _Tp, _Compare, _Alloc>& __x, const multimap<_Key, _Tp, _Compare, _Alloc>& __y) { return __x._M_t == __y._M_t; } /** * @brief Multimap ordering relation. * @param __x A %multimap. * @param __y A %multimap of the same type as @a __x. * @return True iff @a x is lexicographically less than @a y. * * This is a total ordering relation. It is linear in the size of the * multimaps. The elements must be comparable with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const multimap<_Key, _Tp, _Compare, _Alloc>& __x, const multimap<_Key, _Tp, _Compare, _Alloc>& __y) { return __x._M_t < __y._M_t; } /// Based on operator== template inline bool operator!=(const multimap<_Key, _Tp, _Compare, _Alloc>& __x, const multimap<_Key, _Tp, _Compare, _Alloc>& __y) { return !(__x == __y); } /// Based on operator< template inline bool operator>(const multimap<_Key, _Tp, _Compare, _Alloc>& __x, const multimap<_Key, _Tp, _Compare, _Alloc>& __y) { return __y < __x; } /// Based on operator< template inline bool operator<=(const multimap<_Key, _Tp, _Compare, _Alloc>& __x, const multimap<_Key, _Tp, _Compare, _Alloc>& __y) { return !(__y < __x); } /// Based on operator< template inline bool operator>=(const multimap<_Key, _Tp, _Compare, _Alloc>& __x, const multimap<_Key, _Tp, _Compare, _Alloc>& __y) { return !(__x < __y); } /// See std::multimap::swap(). template inline void swap(multimap<_Key, _Tp, _Compare, _Alloc>& __x, multimap<_Key, _Tp, _Compare, _Alloc>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { __x.swap(__y); } _GLIBCXX_END_NAMESPACE_CONTAINER #if __cplusplus > 201402L // Allow std::multimap access to internals of compatible maps. template struct _Rb_tree_merge_helper<_GLIBCXX_STD_C::multimap<_Key, _Val, _Cmp1, _Alloc>, _Cmp2> { private: friend class _GLIBCXX_STD_C::multimap<_Key, _Val, _Cmp1, _Alloc>; static auto& _S_get_tree(_GLIBCXX_STD_C::map<_Key, _Val, _Cmp2, _Alloc>& __map) { return __map._M_t; } static auto& _S_get_tree(_GLIBCXX_STD_C::multimap<_Key, _Val, _Cmp2, _Alloc>& __map) { return __map._M_t; } }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_MULTIMAP_H */ PK!Ǧ8/bits/stl_multiset.hnu[// Multiset implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_multiset.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{set} */ #ifndef _STL_MULTISET_H #define _STL_MULTISET_H 1 #include #if __cplusplus >= 201103L #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER template class set; /** * @brief A standard container made up of elements, which can be retrieved * in logarithmic time. * * @ingroup associative_containers * * * @tparam _Key Type of key objects. * @tparam _Compare Comparison function object type, defaults to less<_Key>. * @tparam _Alloc Allocator type, defaults to allocator<_Key>. * * Meets the requirements of a container, a * reversible container, and an * associative container (using equivalent * keys). For a @c multiset the key_type and value_type are Key. * * Multisets support bidirectional iterators. * * The private tree data is declared exactly the same way for set and * multiset; the distinction is made entirely in how the tree functions are * called (*_unique versus *_equal, same as the standard). */ template , typename _Alloc = std::allocator<_Key> > class multiset { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Alloc::value_type _Alloc_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Key, _SGIAssignableConcept) # endif __glibcxx_class_requires4(_Compare, bool, _Key, _Key, _BinaryFunctionConcept) __glibcxx_class_requires2(_Key, _Alloc_value_type, _SameTypeConcept) #endif #if __cplusplus >= 201103L static_assert(is_same::type, _Key>::value, "std::multiset must have a non-const, non-volatile value_type"); # ifdef __STRICT_ANSI__ static_assert(is_same::value, "std::multiset must have the same value_type as its allocator"); # endif #endif public: // typedefs: typedef _Key key_type; typedef _Key value_type; typedef _Compare key_compare; typedef _Compare value_compare; typedef _Alloc allocator_type; private: /// This turns a red-black tree into a [multi]set. typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Key>::other _Key_alloc_type; typedef _Rb_tree, key_compare, _Key_alloc_type> _Rep_type; /// The actual tree structure. _Rep_type _M_t; typedef __gnu_cxx::__alloc_traits<_Key_alloc_type> _Alloc_traits; public: typedef typename _Alloc_traits::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef typename _Alloc_traits::reference reference; typedef typename _Alloc_traits::const_reference const_reference; // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 103. set::iterator is required to be modifiable, // but this allows modification of keys. typedef typename _Rep_type::const_iterator iterator; typedef typename _Rep_type::const_iterator const_iterator; typedef typename _Rep_type::const_reverse_iterator reverse_iterator; typedef typename _Rep_type::const_reverse_iterator const_reverse_iterator; typedef typename _Rep_type::size_type size_type; typedef typename _Rep_type::difference_type difference_type; #if __cplusplus > 201402L using node_type = typename _Rep_type::node_type; #endif // allocation/deallocation /** * @brief Default constructor creates no elements. */ #if __cplusplus < 201103L multiset() : _M_t() { } #else multiset() = default; #endif /** * @brief Creates a %multiset with no elements. * @param __comp Comparator to use. * @param __a An allocator object. */ explicit multiset(const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Key_alloc_type(__a)) { } /** * @brief Builds a %multiset from a range. * @param __first An input iterator. * @param __last An input iterator. * * Create a %multiset consisting of copies of the elements from * [first,last). This is linear in N if the range is already sorted, * and NlogN otherwise (where N is distance(__first,__last)). */ template multiset(_InputIterator __first, _InputIterator __last) : _M_t() { _M_t._M_insert_equal(__first, __last); } /** * @brief Builds a %multiset from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __comp A comparison functor. * @param __a An allocator object. * * Create a %multiset consisting of copies of the elements from * [__first,__last). This is linear in N if the range is already sorted, * and NlogN otherwise (where N is distance(__first,__last)). */ template multiset(_InputIterator __first, _InputIterator __last, const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Key_alloc_type(__a)) { _M_t._M_insert_equal(__first, __last); } /** * @brief %Multiset copy constructor. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L multiset(const multiset& __x) : _M_t(__x._M_t) { } #else multiset(const multiset&) = default; /** * @brief %Multiset move constructor. * * The newly-created %multiset contains the exact contents of the * moved instance. The moved instance is a valid, but unspecified * %multiset. */ multiset(multiset&&) = default; /** * @brief Builds a %multiset from an initializer_list. * @param __l An initializer_list. * @param __comp A comparison functor. * @param __a An allocator object. * * Create a %multiset consisting of copies of the elements from * the list. This is linear in N if the list is already sorted, * and NlogN otherwise (where N is @a __l.size()). */ multiset(initializer_list __l, const _Compare& __comp = _Compare(), const allocator_type& __a = allocator_type()) : _M_t(__comp, _Key_alloc_type(__a)) { _M_t._M_insert_equal(__l.begin(), __l.end()); } /// Allocator-extended default constructor. explicit multiset(const allocator_type& __a) : _M_t(_Compare(), _Key_alloc_type(__a)) { } /// Allocator-extended copy constructor. multiset(const multiset& __m, const allocator_type& __a) : _M_t(__m._M_t, _Key_alloc_type(__a)) { } /// Allocator-extended move constructor. multiset(multiset&& __m, const allocator_type& __a) noexcept(is_nothrow_copy_constructible<_Compare>::value && _Alloc_traits::_S_always_equal()) : _M_t(std::move(__m._M_t), _Key_alloc_type(__a)) { } /// Allocator-extended initialier-list constructor. multiset(initializer_list __l, const allocator_type& __a) : _M_t(_Compare(), _Key_alloc_type(__a)) { _M_t._M_insert_equal(__l.begin(), __l.end()); } /// Allocator-extended range constructor. template multiset(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _M_t(_Compare(), _Key_alloc_type(__a)) { _M_t._M_insert_equal(__first, __last); } /** * The dtor only erases the elements, and note that if the elements * themselves are pointers, the pointed-to memory is not touched in any * way. Managing the pointer is the user's responsibility. */ ~multiset() = default; #endif /** * @brief %Multiset assignment operator. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L multiset& operator=(const multiset& __x) { _M_t = __x._M_t; return *this; } #else multiset& operator=(const multiset&) = default; /// Move assignment operator. multiset& operator=(multiset&&) = default; /** * @brief %Multiset list assignment operator. * @param __l An initializer_list. * * This function fills a %multiset with copies of the elements in the * initializer list @a __l. * * Note that the assignment completely changes the %multiset and * that the resulting %multiset's size is the same as the number * of elements assigned. */ multiset& operator=(initializer_list __l) { _M_t._M_assign_equal(__l.begin(), __l.end()); return *this; } #endif // accessors: /// Returns the comparison object. key_compare key_comp() const { return _M_t.key_comp(); } /// Returns the comparison object. value_compare value_comp() const { return _M_t.key_comp(); } /// Returns the memory allocation object. allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_t.get_allocator()); } /** * Returns a read-only (constant) iterator that points to the first * element in the %multiset. Iteration is done in ascending order * according to the keys. */ iterator begin() const _GLIBCXX_NOEXCEPT { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * element in the %multiset. Iteration is done in ascending order * according to the keys. */ iterator end() const _GLIBCXX_NOEXCEPT { return _M_t.end(); } /** * Returns a read-only (constant) reverse iterator that points to the * last element in the %multiset. Iteration is done in descending order * according to the keys. */ reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to the * last element in the %multiset. Iteration is done in descending order * according to the keys. */ reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return _M_t.rend(); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the first * element in the %multiset. Iteration is done in ascending order * according to the keys. */ iterator cbegin() const noexcept { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * element in the %multiset. Iteration is done in ascending order * according to the keys. */ iterator cend() const noexcept { return _M_t.end(); } /** * Returns a read-only (constant) reverse iterator that points to the * last element in the %multiset. Iteration is done in descending order * according to the keys. */ reverse_iterator crbegin() const noexcept { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to the * last element in the %multiset. Iteration is done in descending order * according to the keys. */ reverse_iterator crend() const noexcept { return _M_t.rend(); } #endif /// Returns true if the %set is empty. bool empty() const _GLIBCXX_NOEXCEPT { return _M_t.empty(); } /// Returns the size of the %set. size_type size() const _GLIBCXX_NOEXCEPT { return _M_t.size(); } /// Returns the maximum size of the %set. size_type max_size() const _GLIBCXX_NOEXCEPT { return _M_t.max_size(); } /** * @brief Swaps data with another %multiset. * @param __x A %multiset of the same element and allocator types. * * This exchanges the elements between two multisets in constant time. * (It is only swapping a pointer, an integer, and an instance of the @c * Compare type (which itself is often stateless and empty), so it should * be quite fast.) * Note that the global std::swap() function is specialized such that * std::swap(s1,s2) will feed to this function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(multiset& __x) _GLIBCXX_NOEXCEPT_IF(__is_nothrow_swappable<_Compare>::value) { _M_t.swap(__x._M_t); } // insert/erase #if __cplusplus >= 201103L /** * @brief Builds and inserts an element into the %multiset. * @param __args Arguments used to generate the element instance to be * inserted. * @return An iterator that points to the inserted element. * * This function inserts an element into the %multiset. Contrary * to a std::set the %multiset does not rely on unique keys and thus * multiple copies of the same element can be inserted. * * Insertion requires logarithmic time. */ template iterator emplace(_Args&&... __args) { return _M_t._M_emplace_equal(std::forward<_Args>(__args)...); } /** * @brief Builds and inserts an element into the %multiset. * @param __pos An iterator that serves as a hint as to where the * element should be inserted. * @param __args Arguments used to generate the element instance to be * inserted. * @return An iterator that points to the inserted element. * * This function inserts an element into the %multiset. Contrary * to a std::set the %multiset does not rely on unique keys and thus * multiple copies of the same element can be inserted. * * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires logarithmic time (if the hint is not taken). */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_t._M_emplace_hint_equal(__pos, std::forward<_Args>(__args)...); } #endif /** * @brief Inserts an element into the %multiset. * @param __x Element to be inserted. * @return An iterator that points to the inserted element. * * This function inserts an element into the %multiset. Contrary * to a std::set the %multiset does not rely on unique keys and thus * multiple copies of the same element can be inserted. * * Insertion requires logarithmic time. */ iterator insert(const value_type& __x) { return _M_t._M_insert_equal(__x); } #if __cplusplus >= 201103L iterator insert(value_type&& __x) { return _M_t._M_insert_equal(std::move(__x)); } #endif /** * @brief Inserts an element into the %multiset. * @param __position An iterator that serves as a hint as to where the * element should be inserted. * @param __x Element to be inserted. * @return An iterator that points to the inserted element. * * This function inserts an element into the %multiset. Contrary * to a std::set the %multiset does not rely on unique keys and thus * multiple copies of the same element can be inserted. * * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires logarithmic time (if the hint is not taken). */ iterator insert(const_iterator __position, const value_type& __x) { return _M_t._M_insert_equal_(__position, __x); } #if __cplusplus >= 201103L iterator insert(const_iterator __position, value_type&& __x) { return _M_t._M_insert_equal_(__position, std::move(__x)); } #endif /** * @brief A template function that tries to insert a range of elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_t._M_insert_equal(__first, __last); } #if __cplusplus >= 201103L /** * @brief Attempts to insert a list of elements into the %multiset. * @param __l A std::initializer_list of elements * to be inserted. * * Complexity similar to that of the range constructor. */ void insert(initializer_list __l) { this->insert(__l.begin(), __l.end()); } #endif #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_t.extract(__pos); } /// Extract a node. node_type extract(const key_type& __x) { return _M_t.extract(__x); } /// Re-insert an extracted node. iterator insert(node_type&& __nh) { return _M_t._M_reinsert_node_equal(std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator __hint, node_type&& __nh) { return _M_t._M_reinsert_node_hint_equal(__hint, std::move(__nh)); } template friend class std::_Rb_tree_merge_helper; template void merge(multiset<_Key, _Compare1, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_equal(_Merge_helper::_S_get_tree(__source)); } template void merge(multiset<_Key, _Compare1, _Alloc>&& __source) { merge(__source); } template void merge(set<_Key, _Compare1, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_equal(_Merge_helper::_S_get_tree(__source)); } template void merge(set<_Key, _Compare1, _Alloc>&& __source) { merge(__source); } #endif // C++17 #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases an element from a %multiset. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given iterator, * from a %multiset. Note that this function only erases the element, * and that if the element is itself a pointer, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibility. */ _GLIBCXX_ABI_TAG_CXX11 iterator erase(const_iterator __position) { return _M_t.erase(__position); } #else /** * @brief Erases an element from a %multiset. * @param __position An iterator pointing to the element to be erased. * * This function erases an element, pointed to by the given iterator, * from a %multiset. Note that this function only erases the element, * and that if the element is itself a pointer, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibility. */ void erase(iterator __position) { _M_t.erase(__position); } #endif /** * @brief Erases elements according to the provided key. * @param __x Key of element to be erased. * @return The number of elements erased. * * This function erases all elements located by the given key from a * %multiset. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_t.erase(__x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases a [first,last) range of elements from a %multiset. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * @return The iterator @a last. * * This function erases a sequence of elements from a %multiset. * Note that this function only erases the elements, and that if * the elements themselves are pointers, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ _GLIBCXX_ABI_TAG_CXX11 iterator erase(const_iterator __first, const_iterator __last) { return _M_t.erase(__first, __last); } #else /** * @brief Erases a [first,last) range of elements from a %multiset. * @param first Iterator pointing to the start of the range to be * erased. * @param last Iterator pointing to the end of the range to be erased. * * This function erases a sequence of elements from a %multiset. * Note that this function only erases the elements, and that if * the elements themselves are pointers, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ void erase(iterator __first, iterator __last) { _M_t.erase(__first, __last); } #endif /** * Erases all elements in a %multiset. Note that this function only * erases the elements, and that if the elements themselves are pointers, * the pointed-to memory is not touched in any way. Managing the pointer * is the user's responsibility. */ void clear() _GLIBCXX_NOEXCEPT { _M_t.clear(); } // multiset operations: //@{ /** * @brief Finds the number of elements with given key. * @param __x Key of elements to be located. * @return Number of elements with specified key. */ size_type count(const key_type& __x) const { return _M_t.count(__x); } #if __cplusplus > 201103L template auto count(const _Kt& __x) const -> decltype(_M_t._M_count_tr(__x)) { return _M_t._M_count_tr(__x); } #endif //@} // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload //@{ /** * @brief Tries to locate an element in a %set. * @param __x Element to be located. * @return Iterator pointing to sought-after element, or end() if not * found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after element. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_t.find(__x); } const_iterator find(const key_type& __x) const { return _M_t.find(__x); } #if __cplusplus > 201103L template auto find(const _Kt& __x) -> decltype(iterator{_M_t._M_find_tr(__x)}) { return iterator{_M_t._M_find_tr(__x)}; } template auto find(const _Kt& __x) const -> decltype(const_iterator{_M_t._M_find_tr(__x)}) { return const_iterator{_M_t._M_find_tr(__x)}; } #endif //@} //@{ /** * @brief Finds the beginning of a subsequence matching given key. * @param __x Key to be located. * @return Iterator pointing to first element equal to or greater * than key, or end(). * * This function returns the first element of a subsequence of elements * that matches the given key. If unsuccessful it returns an iterator * pointing to the first element that has a greater value than given key * or end() if no such element exists. */ iterator lower_bound(const key_type& __x) { return _M_t.lower_bound(__x); } const_iterator lower_bound(const key_type& __x) const { return _M_t.lower_bound(__x); } #if __cplusplus > 201103L template auto lower_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_lower_bound_tr(__x))) { return iterator(_M_t._M_lower_bound_tr(__x)); } template auto lower_bound(const _Kt& __x) const -> decltype(iterator(_M_t._M_lower_bound_tr(__x))) { return iterator(_M_t._M_lower_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the end of a subsequence matching given key. * @param __x Key to be located. * @return Iterator pointing to the first element * greater than key, or end(). */ iterator upper_bound(const key_type& __x) { return _M_t.upper_bound(__x); } const_iterator upper_bound(const key_type& __x) const { return _M_t.upper_bound(__x); } #if __cplusplus > 201103L template auto upper_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_upper_bound_tr(__x))) { return iterator(_M_t._M_upper_bound_tr(__x)); } template auto upper_bound(const _Kt& __x) const -> decltype(iterator(_M_t._M_upper_bound_tr(__x))) { return iterator(_M_t._M_upper_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. * * This function is equivalent to * @code * std::make_pair(c.lower_bound(val), * c.upper_bound(val)) * @endcode * (but is faster than making the calls separately). * * This function probably only makes sense for multisets. */ std::pair equal_range(const key_type& __x) { return _M_t.equal_range(__x); } std::pair equal_range(const key_type& __x) const { return _M_t.equal_range(__x); } #if __cplusplus > 201103L template auto equal_range(const _Kt& __x) -> decltype(pair(_M_t._M_equal_range_tr(__x))) { return pair(_M_t._M_equal_range_tr(__x)); } template auto equal_range(const _Kt& __x) const -> decltype(pair(_M_t._M_equal_range_tr(__x))) { return pair(_M_t._M_equal_range_tr(__x)); } #endif //@} template friend bool operator==(const multiset<_K1, _C1, _A1>&, const multiset<_K1, _C1, _A1>&); template friend bool operator< (const multiset<_K1, _C1, _A1>&, const multiset<_K1, _C1, _A1>&); }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> multiset(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> multiset::value_type, _Compare, _Allocator>; template, typename _Allocator = allocator<_Key>, typename = _RequireAllocator<_Allocator>> multiset(initializer_list<_Key>, _Compare = _Compare(), _Allocator = _Allocator()) -> multiset<_Key, _Compare, _Allocator>; template, typename = _RequireAllocator<_Allocator>> multiset(_InputIterator, _InputIterator, _Allocator) -> multiset::value_type, less::value_type>, _Allocator>; template> multiset(initializer_list<_Key>, _Allocator) -> multiset<_Key, less<_Key>, _Allocator>; #endif /** * @brief Multiset equality comparison. * @param __x A %multiset. * @param __y A %multiset of the same type as @a __x. * @return True iff the size and elements of the multisets are equal. * * This is an equivalence relation. It is linear in the size of the * multisets. * Multisets are considered equivalent if their sizes are equal, and if * corresponding elements compare equal. */ template inline bool operator==(const multiset<_Key, _Compare, _Alloc>& __x, const multiset<_Key, _Compare, _Alloc>& __y) { return __x._M_t == __y._M_t; } /** * @brief Multiset ordering relation. * @param __x A %multiset. * @param __y A %multiset of the same type as @a __x. * @return True iff @a __x is lexicographically less than @a __y. * * This is a total ordering relation. It is linear in the size of the * sets. The elements must be comparable with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const multiset<_Key, _Compare, _Alloc>& __x, const multiset<_Key, _Compare, _Alloc>& __y) { return __x._M_t < __y._M_t; } /// Returns !(x == y). template inline bool operator!=(const multiset<_Key, _Compare, _Alloc>& __x, const multiset<_Key, _Compare, _Alloc>& __y) { return !(__x == __y); } /// Returns y < x. template inline bool operator>(const multiset<_Key,_Compare,_Alloc>& __x, const multiset<_Key,_Compare,_Alloc>& __y) { return __y < __x; } /// Returns !(y < x) template inline bool operator<=(const multiset<_Key, _Compare, _Alloc>& __x, const multiset<_Key, _Compare, _Alloc>& __y) { return !(__y < __x); } /// Returns !(x < y) template inline bool operator>=(const multiset<_Key, _Compare, _Alloc>& __x, const multiset<_Key, _Compare, _Alloc>& __y) { return !(__x < __y); } /// See std::multiset::swap(). template inline void swap(multiset<_Key, _Compare, _Alloc>& __x, multiset<_Key, _Compare, _Alloc>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { __x.swap(__y); } _GLIBCXX_END_NAMESPACE_CONTAINER #if __cplusplus > 201402L // Allow std::multiset access to internals of compatible sets. template struct _Rb_tree_merge_helper<_GLIBCXX_STD_C::multiset<_Val, _Cmp1, _Alloc>, _Cmp2> { private: friend class _GLIBCXX_STD_C::multiset<_Val, _Cmp1, _Alloc>; static auto& _S_get_tree(_GLIBCXX_STD_C::set<_Val, _Cmp2, _Alloc>& __set) { return __set._M_t; } static auto& _S_get_tree(_GLIBCXX_STD_C::multiset<_Val, _Cmp2, _Alloc>& __set) { return __set._M_t; } }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_MULTISET_H */ PK!4668/bits/stl_numeric.hnu[// Numeric functions implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_numeric.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{numeric} */ #ifndef _STL_NUMERIC_H #define _STL_NUMERIC_H 1 #include #include #include // For _GLIBCXX_MOVE #if __cplusplus >= 201103L namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief Create a range of sequentially increasing values. * * For each element in the range @p [first,last) assigns @p value and * increments @p value as if by @p ++value. * * @param __first Start of range. * @param __last End of range. * @param __value Starting value. * @return Nothing. */ template void iota(_ForwardIterator __first, _ForwardIterator __last, _Tp __value) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator>) __glibcxx_function_requires(_ConvertibleConcept<_Tp, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first) { *__first = __value; ++__value; } } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_ALGO /** * @brief Accumulate values in a range. * * Accumulates the values in the range [first,last) using operator+(). The * initial value is @a init. The values are processed in order. * * @param __first Start of range. * @param __last End of range. * @param __init Starting value to add other values to. * @return The final sum. */ template inline _Tp accumulate(_InputIterator __first, _InputIterator __last, _Tp __init) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first) __init = __init + *__first; return __init; } /** * @brief Accumulate values in a range with operation. * * Accumulates the values in the range [first,last) using the function * object @p __binary_op. The initial value is @p __init. The values are * processed in order. * * @param __first Start of range. * @param __last End of range. * @param __init Starting value to add other values to. * @param __binary_op Function object to accumulate with. * @return The final sum. */ template inline _Tp accumulate(_InputIterator __first, _InputIterator __last, _Tp __init, _BinaryOperation __binary_op) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first) __init = __binary_op(__init, *__first); return __init; } /** * @brief Compute inner product of two ranges. * * Starting with an initial value of @p __init, multiplies successive * elements from the two ranges and adds each product into the accumulated * value using operator+(). The values in the ranges are processed in * order. * * @param __first1 Start of range 1. * @param __last1 End of range 1. * @param __first2 Start of range 2. * @param __init Starting value to add other values to. * @return The final inner product. */ template inline _Tp inner_product(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _Tp __init) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_requires_valid_range(__first1, __last1); for (; __first1 != __last1; ++__first1, (void)++__first2) __init = __init + (*__first1 * *__first2); return __init; } /** * @brief Compute inner product of two ranges. * * Starting with an initial value of @p __init, applies @p __binary_op2 to * successive elements from the two ranges and accumulates each result into * the accumulated value using @p __binary_op1. The values in the ranges are * processed in order. * * @param __first1 Start of range 1. * @param __last1 End of range 1. * @param __first2 Start of range 2. * @param __init Starting value to add other values to. * @param __binary_op1 Function object to accumulate with. * @param __binary_op2 Function object to apply to pairs of input values. * @return The final inner product. */ template inline _Tp inner_product(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _Tp __init, _BinaryOperation1 __binary_op1, _BinaryOperation2 __binary_op2) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_requires_valid_range(__first1, __last1); for (; __first1 != __last1; ++__first1, (void)++__first2) __init = __binary_op1(__init, __binary_op2(*__first1, *__first2)); return __init; } /** * @brief Return list of partial sums * * Accumulates the values in the range [first,last) using the @c + operator. * As each successive input value is added into the total, that partial sum * is written to @p __result. Therefore, the first value in @p __result is * the first value of the input, the second value in @p __result is the sum * of the first and second input values, and so on. * * @param __first Start of input range. * @param __last End of input range. * @param __result Output sum. * @return Iterator pointing just beyond the values written to __result. */ template _OutputIterator partial_sum(_InputIterator __first, _InputIterator __last, _OutputIterator __result) { typedef typename iterator_traits<_InputIterator>::value_type _ValueType; // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, _ValueType>) __glibcxx_requires_valid_range(__first, __last); if (__first == __last) return __result; _ValueType __value = *__first; *__result = __value; while (++__first != __last) { __value = __value + *__first; *++__result = __value; } return ++__result; } /** * @brief Return list of partial sums * * Accumulates the values in the range [first,last) using @p __binary_op. * As each successive input value is added into the total, that partial sum * is written to @p __result. Therefore, the first value in @p __result is * the first value of the input, the second value in @p __result is the sum * of the first and second input values, and so on. * * @param __first Start of input range. * @param __last End of input range. * @param __result Output sum. * @param __binary_op Function object. * @return Iterator pointing just beyond the values written to __result. */ template _OutputIterator partial_sum(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _BinaryOperation __binary_op) { typedef typename iterator_traits<_InputIterator>::value_type _ValueType; // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, _ValueType>) __glibcxx_requires_valid_range(__first, __last); if (__first == __last) return __result; _ValueType __value = *__first; *__result = __value; while (++__first != __last) { __value = __binary_op(__value, *__first); *++__result = __value; } return ++__result; } /** * @brief Return differences between adjacent values. * * Computes the difference between adjacent values in the range * [first,last) using operator-() and writes the result to @p __result. * * @param __first Start of input range. * @param __last End of input range. * @param __result Output sums. * @return Iterator pointing just beyond the values written to result. * * _GLIBCXX_RESOLVE_LIB_DEFECTS * DR 539. partial_sum and adjacent_difference should mention requirements */ template _OutputIterator adjacent_difference(_InputIterator __first, _InputIterator __last, _OutputIterator __result) { typedef typename iterator_traits<_InputIterator>::value_type _ValueType; // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, _ValueType>) __glibcxx_requires_valid_range(__first, __last); if (__first == __last) return __result; _ValueType __value = *__first; *__result = __value; while (++__first != __last) { _ValueType __tmp = *__first; *++__result = __tmp - __value; __value = _GLIBCXX_MOVE(__tmp); } return ++__result; } /** * @brief Return differences between adjacent values. * * Computes the difference between adjacent values in the range * [__first,__last) using the function object @p __binary_op and writes the * result to @p __result. * * @param __first Start of input range. * @param __last End of input range. * @param __result Output sum. * @param __binary_op Function object. * @return Iterator pointing just beyond the values written to result. * * _GLIBCXX_RESOLVE_LIB_DEFECTS * DR 539. partial_sum and adjacent_difference should mention requirements */ template _OutputIterator adjacent_difference(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _BinaryOperation __binary_op) { typedef typename iterator_traits<_InputIterator>::value_type _ValueType; // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, _ValueType>) __glibcxx_requires_valid_range(__first, __last); if (__first == __last) return __result; _ValueType __value = *__first; *__result = __value; while (++__first != __last) { _ValueType __tmp = *__first; *++__result = __binary_op(__tmp, __value); __value = _GLIBCXX_MOVE(__tmp); } return ++__result; } _GLIBCXX_END_NAMESPACE_ALGO } // namespace std #endif /* _STL_NUMERIC_H */ PK!pp¬HH8/bits/stl_pair.hnu[// Pair implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_pair.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{utility} */ #ifndef _STL_PAIR_H #define _STL_PAIR_H 1 #include // for std::move / std::forward, and std::swap #if __cplusplus >= 201103L #include // for std::__decay_and_strip too #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup utilities * @{ */ #if __cplusplus >= 201103L /// piecewise_construct_t struct piecewise_construct_t { explicit piecewise_construct_t() = default; }; /// piecewise_construct _GLIBCXX17_INLINE constexpr piecewise_construct_t piecewise_construct = piecewise_construct_t(); // Forward declarations. template class tuple; template struct _Index_tuple; // Concept utility functions, reused in conditionally-explicit // constructors. // See PR 70437, don't look at is_constructible or // is_convertible if the types are the same to // avoid querying those properties for incomplete types. template struct _PCC { template static constexpr bool _ConstructiblePair() { return __and_, is_constructible<_T2, const _U2&>>::value; } template static constexpr bool _ImplicitlyConvertiblePair() { return __and_, is_convertible>::value; } template static constexpr bool _MoveConstructiblePair() { return __and_, is_constructible<_T2, _U2&&>>::value; } template static constexpr bool _ImplicitlyMoveConvertiblePair() { return __and_, is_convertible<_U2&&, _T2>>::value; } template static constexpr bool _CopyMovePair() { using __do_converts = __and_, is_convertible<_U2&&, _T2>>; using __converts = typename conditional<__implicit, __do_converts, __not_<__do_converts>>::type; return __and_, is_constructible<_T2, _U2&&>, __converts >::value; } template static constexpr bool _MoveCopyPair() { using __do_converts = __and_, is_convertible>; using __converts = typename conditional<__implicit, __do_converts, __not_<__do_converts>>::type; return __and_, is_constructible<_T2, const _U2&&>, __converts >::value; } }; template struct _PCC { template static constexpr bool _ConstructiblePair() { return false; } template static constexpr bool _ImplicitlyConvertiblePair() { return false; } template static constexpr bool _MoveConstructiblePair() { return false; } template static constexpr bool _ImplicitlyMoveConvertiblePair() { return false; } }; // PR libstdc++/79141, a utility type for preventing // initialization of an argument of a disabled assignment // operator from a pair of empty braces. struct __nonesuch_no_braces : std::__nonesuch { explicit __nonesuch_no_braces(const __nonesuch&) = delete; }; #endif // C++11 template class __pair_base { #if __cplusplus >= 201103L template friend struct pair; __pair_base() = default; ~__pair_base() = default; __pair_base(const __pair_base&) = default; __pair_base& operator=(const __pair_base&) = delete; #endif // C++11 }; /** * @brief Struct holding two objects of arbitrary type. * * @tparam _T1 Type of first object. * @tparam _T2 Type of second object. */ template struct pair : private __pair_base<_T1, _T2> { typedef _T1 first_type; /// @c first_type is the first bound type typedef _T2 second_type; /// @c second_type is the second bound type _T1 first; /// @c first is a copy of the first object _T2 second; /// @c second is a copy of the second object // _GLIBCXX_RESOLVE_LIB_DEFECTS // 265. std::pair::pair() effects overly restrictive /** The default constructor creates @c first and @c second using their * respective default constructors. */ #if __cplusplus >= 201103L template , __is_implicitly_default_constructible<_U2>> ::value, bool>::type = true> #endif _GLIBCXX_CONSTEXPR pair() : first(), second() { } #if __cplusplus >= 201103L template , is_default_constructible<_U2>, __not_< __and_<__is_implicitly_default_constructible<_U1>, __is_implicitly_default_constructible<_U2>>>> ::value, bool>::type = false> explicit constexpr pair() : first(), second() { } #endif /** Two objects may be passed to a @c pair constructor to be copied. */ #if __cplusplus < 201103L pair(const _T1& __a, const _T2& __b) : first(__a), second(__b) { } #else // Shortcut for constraining the templates that don't take pairs. using _PCCP = _PCC; template() && _PCCP::template _ImplicitlyConvertiblePair<_U1, _U2>(), bool>::type=true> constexpr pair(const _T1& __a, const _T2& __b) : first(__a), second(__b) { } template() && !_PCCP::template _ImplicitlyConvertiblePair<_U1, _U2>(), bool>::type=false> explicit constexpr pair(const _T1& __a, const _T2& __b) : first(__a), second(__b) { } #endif /** There is also a templated copy ctor for the @c pair class itself. */ #if __cplusplus < 201103L template pair(const pair<_U1, _U2>& __p) : first(__p.first), second(__p.second) { } #else // Shortcut for constraining the templates that take pairs. template using _PCCFP = _PCC::value || !is_same<_T2, _U2>::value, _T1, _T2>; template::template _ConstructiblePair<_U1, _U2>() && _PCCFP<_U1, _U2>::template _ImplicitlyConvertiblePair<_U1, _U2>(), bool>::type=true> constexpr pair(const pair<_U1, _U2>& __p) : first(__p.first), second(__p.second) { } template::template _ConstructiblePair<_U1, _U2>() && !_PCCFP<_U1, _U2>::template _ImplicitlyConvertiblePair<_U1, _U2>(), bool>::type=false> explicit constexpr pair(const pair<_U1, _U2>& __p) : first(__p.first), second(__p.second) { } constexpr pair(const pair&) = default; constexpr pair(pair&&) = default; // DR 811. template(), bool>::type=true> constexpr pair(_U1&& __x, const _T2& __y) : first(std::forward<_U1>(__x)), second(__y) { } template(), bool>::type=false> explicit constexpr pair(_U1&& __x, const _T2& __y) : first(std::forward<_U1>(__x)), second(__y) { } template(), bool>::type=true> constexpr pair(const _T1& __x, _U2&& __y) : first(__x), second(std::forward<_U2>(__y)) { } template(), bool>::type=false> explicit pair(const _T1& __x, _U2&& __y) : first(__x), second(std::forward<_U2>(__y)) { } template() && _PCCP::template _ImplicitlyMoveConvertiblePair<_U1, _U2>(), bool>::type=true> constexpr pair(_U1&& __x, _U2&& __y) : first(std::forward<_U1>(__x)), second(std::forward<_U2>(__y)) { } template() && !_PCCP::template _ImplicitlyMoveConvertiblePair<_U1, _U2>(), bool>::type=false> explicit constexpr pair(_U1&& __x, _U2&& __y) : first(std::forward<_U1>(__x)), second(std::forward<_U2>(__y)) { } template::template _MoveConstructiblePair<_U1, _U2>() && _PCCFP<_U1, _U2>::template _ImplicitlyMoveConvertiblePair<_U1, _U2>(), bool>::type=true> constexpr pair(pair<_U1, _U2>&& __p) : first(std::forward<_U1>(__p.first)), second(std::forward<_U2>(__p.second)) { } template::template _MoveConstructiblePair<_U1, _U2>() && !_PCCFP<_U1, _U2>::template _ImplicitlyMoveConvertiblePair<_U1, _U2>(), bool>::type=false> explicit constexpr pair(pair<_U1, _U2>&& __p) : first(std::forward<_U1>(__p.first)), second(std::forward<_U2>(__p.second)) { } template pair(piecewise_construct_t, tuple<_Args1...>, tuple<_Args2...>); pair& operator=(typename conditional< __and_, is_copy_assignable<_T2>>::value, const pair&, const __nonesuch_no_braces&>::type __p) { first = __p.first; second = __p.second; return *this; } pair& operator=(typename conditional< __and_, is_move_assignable<_T2>>::value, pair&&, __nonesuch_no_braces&&>::type __p) noexcept(__and_, is_nothrow_move_assignable<_T2>>::value) { first = std::forward(__p.first); second = std::forward(__p.second); return *this; } template typename enable_if<__and_, is_assignable<_T2&, const _U2&>>::value, pair&>::type operator=(const pair<_U1, _U2>& __p) { first = __p.first; second = __p.second; return *this; } template typename enable_if<__and_, is_assignable<_T2&, _U2&&>>::value, pair&>::type operator=(pair<_U1, _U2>&& __p) { first = std::forward<_U1>(__p.first); second = std::forward<_U2>(__p.second); return *this; } void swap(pair& __p) noexcept(__and_<__is_nothrow_swappable<_T1>, __is_nothrow_swappable<_T2>>::value) { using std::swap; swap(first, __p.first); swap(second, __p.second); } private: template pair(tuple<_Args1...>&, tuple<_Args2...>&, _Index_tuple<_Indexes1...>, _Index_tuple<_Indexes2...>); #endif }; #if __cpp_deduction_guides >= 201606 template pair(_T1, _T2) -> pair<_T1, _T2>; #endif /// Two pairs of the same type are equal iff their members are equal. template inline _GLIBCXX_CONSTEXPR bool operator==(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) { return __x.first == __y.first && __x.second == __y.second; } /// template inline _GLIBCXX_CONSTEXPR bool operator<(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) { return __x.first < __y.first || (!(__y.first < __x.first) && __x.second < __y.second); } /// Uses @c operator== to find the result. template inline _GLIBCXX_CONSTEXPR bool operator!=(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) { return !(__x == __y); } /// Uses @c operator< to find the result. template inline _GLIBCXX_CONSTEXPR bool operator>(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) { return __y < __x; } /// Uses @c operator< to find the result. template inline _GLIBCXX_CONSTEXPR bool operator<=(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) { return !(__y < __x); } /// Uses @c operator< to find the result. template inline _GLIBCXX_CONSTEXPR bool operator>=(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) { return !(__x < __y); } #if __cplusplus >= 201103L /// See std::pair::swap(). // Note: no std::swap overloads in C++03 mode, this has performance // implications, see, eg, libstdc++/38466. template inline #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 // Constrained free swap overload, see p0185r1 typename enable_if<__and_<__is_swappable<_T1>, __is_swappable<_T2>>::value>::type #else void #endif swap(pair<_T1, _T2>& __x, pair<_T1, _T2>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 template typename enable_if, __is_swappable<_T2>>::value>::type swap(pair<_T1, _T2>&, pair<_T1, _T2>&) = delete; #endif #endif // __cplusplus >= 201103L /** * @brief A convenience wrapper for creating a pair from two objects. * @param __x The first object. * @param __y The second object. * @return A newly-constructed pair<> object of the appropriate type. * * The standard requires that the objects be passed by reference-to-const, * but LWG issue #181 says they should be passed by const value. We follow * the LWG by default. */ // _GLIBCXX_RESOLVE_LIB_DEFECTS // 181. make_pair() unintended behavior #if __cplusplus >= 201103L // NB: DR 706. template constexpr pair::__type, typename __decay_and_strip<_T2>::__type> make_pair(_T1&& __x, _T2&& __y) { typedef typename __decay_and_strip<_T1>::__type __ds_type1; typedef typename __decay_and_strip<_T2>::__type __ds_type2; typedef pair<__ds_type1, __ds_type2> __pair_type; return __pair_type(std::forward<_T1>(__x), std::forward<_T2>(__y)); } #else template inline pair<_T1, _T2> make_pair(_T1 __x, _T2 __y) { return pair<_T1, _T2>(__x, __y); } #endif /// @} _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_PAIR_H */ PK!FM ^ ^8/bits/stl_queue.hnu[// Queue implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_queue.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{queue} */ #ifndef _STL_QUEUE_H #define _STL_QUEUE_H 1 #include #include #if __cplusplus >= 201103L # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief A standard container giving FIFO behavior. * * @ingroup sequences * * @tparam _Tp Type of element. * @tparam _Sequence Type of underlying sequence, defaults to deque<_Tp>. * * Meets many of the requirements of a * container, * but does not define anything to do with iterators. Very few of the * other standard container interfaces are defined. * * This is not a true container, but an @e adaptor. It holds another * container, and provides a wrapper interface to that container. The * wrapper is what enforces strict first-in-first-out %queue behavior. * * The second template parameter defines the type of the underlying * sequence/container. It defaults to std::deque, but it can be any type * that supports @c front, @c back, @c push_back, and @c pop_front, * such as std::list or an appropriate user-defined type. * * Members not found in @a normal containers are @c container_type, * which is a typedef for the second Sequence parameter, and @c push and * @c pop, which are standard %queue/FIFO operations. */ template > class queue { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Sequence::value_type _Sequence_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) # endif __glibcxx_class_requires(_Sequence, _FrontInsertionSequenceConcept) __glibcxx_class_requires(_Sequence, _BackInsertionSequenceConcept) __glibcxx_class_requires2(_Tp, _Sequence_value_type, _SameTypeConcept) #endif template friend bool operator==(const queue<_Tp1, _Seq1>&, const queue<_Tp1, _Seq1>&); template friend bool operator<(const queue<_Tp1, _Seq1>&, const queue<_Tp1, _Seq1>&); #if __cplusplus >= 201103L template using _Uses = typename enable_if::value>::type; #endif public: typedef typename _Sequence::value_type value_type; typedef typename _Sequence::reference reference; typedef typename _Sequence::const_reference const_reference; typedef typename _Sequence::size_type size_type; typedef _Sequence container_type; protected: /* Maintainers wondering why this isn't uglified as per style * guidelines should note that this name is specified in the standard, * C++98 [23.2.3.1]. * (Why? Presumably for the same reason that it's protected instead * of private: to allow derivation. But none of the other * containers allow for derivation. Odd.) */ /// @c c is the underlying container. _Sequence c; public: /** * @brief Default constructor creates no elements. */ #if __cplusplus < 201103L explicit queue(const _Sequence& __c = _Sequence()) : c(__c) { } #else template::value>::type> queue() : c() { } explicit queue(const _Sequence& __c) : c(__c) { } explicit queue(_Sequence&& __c) : c(std::move(__c)) { } template> explicit queue(const _Alloc& __a) : c(__a) { } template> queue(const _Sequence& __c, const _Alloc& __a) : c(__c, __a) { } template> queue(_Sequence&& __c, const _Alloc& __a) : c(std::move(__c), __a) { } template> queue(const queue& __q, const _Alloc& __a) : c(__q.c, __a) { } template> queue(queue&& __q, const _Alloc& __a) : c(std::move(__q.c), __a) { } #endif /** * Returns true if the %queue is empty. */ bool empty() const { return c.empty(); } /** Returns the number of elements in the %queue. */ size_type size() const { return c.size(); } /** * Returns a read/write reference to the data at the first * element of the %queue. */ reference front() { __glibcxx_requires_nonempty(); return c.front(); } /** * Returns a read-only (constant) reference to the data at the first * element of the %queue. */ const_reference front() const { __glibcxx_requires_nonempty(); return c.front(); } /** * Returns a read/write reference to the data at the last * element of the %queue. */ reference back() { __glibcxx_requires_nonempty(); return c.back(); } /** * Returns a read-only (constant) reference to the data at the last * element of the %queue. */ const_reference back() const { __glibcxx_requires_nonempty(); return c.back(); } /** * @brief Add data to the end of the %queue. * @param __x Data to be added. * * This is a typical %queue operation. The function creates an * element at the end of the %queue and assigns the given data * to it. The time complexity of the operation depends on the * underlying sequence. */ void push(const value_type& __x) { c.push_back(__x); } #if __cplusplus >= 201103L void push(value_type&& __x) { c.push_back(std::move(__x)); } #if __cplusplus > 201402L template decltype(auto) emplace(_Args&&... __args) { return c.emplace_back(std::forward<_Args>(__args)...); } #else template void emplace(_Args&&... __args) { c.emplace_back(std::forward<_Args>(__args)...); } #endif #endif /** * @brief Removes first element. * * This is a typical %queue operation. It shrinks the %queue by one. * The time complexity of the operation depends on the underlying * sequence. * * Note that no data is returned, and if the first element's * data is needed, it should be retrieved before pop() is * called. */ void pop() { __glibcxx_requires_nonempty(); c.pop_front(); } #if __cplusplus >= 201103L void swap(queue& __q) #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 noexcept(__is_nothrow_swappable<_Sequence>::value) #else noexcept(__is_nothrow_swappable<_Tp>::value) #endif { using std::swap; swap(c, __q.c); } #endif // __cplusplus >= 201103L }; #if __cpp_deduction_guides >= 201606 template::value>> queue(_Container) -> queue; template::value>, typename = enable_if_t<__is_allocator<_Allocator>::value>> queue(_Container, _Allocator) -> queue; #endif /** * @brief Queue equality comparison. * @param __x A %queue. * @param __y A %queue of the same type as @a __x. * @return True iff the size and elements of the queues are equal. * * This is an equivalence relation. Complexity and semantics depend on the * underlying sequence type, but the expected rules are: this relation is * linear in the size of the sequences, and queues are considered equivalent * if their sequences compare equal. */ template inline bool operator==(const queue<_Tp, _Seq>& __x, const queue<_Tp, _Seq>& __y) { return __x.c == __y.c; } /** * @brief Queue ordering relation. * @param __x A %queue. * @param __y A %queue of the same type as @a x. * @return True iff @a __x is lexicographically less than @a __y. * * This is an total ordering relation. Complexity and semantics * depend on the underlying sequence type, but the expected rules * are: this relation is linear in the size of the sequences, the * elements must be comparable with @c <, and * std::lexicographical_compare() is usually used to make the * determination. */ template inline bool operator<(const queue<_Tp, _Seq>& __x, const queue<_Tp, _Seq>& __y) { return __x.c < __y.c; } /// Based on operator== template inline bool operator!=(const queue<_Tp, _Seq>& __x, const queue<_Tp, _Seq>& __y) { return !(__x == __y); } /// Based on operator< template inline bool operator>(const queue<_Tp, _Seq>& __x, const queue<_Tp, _Seq>& __y) { return __y < __x; } /// Based on operator< template inline bool operator<=(const queue<_Tp, _Seq>& __x, const queue<_Tp, _Seq>& __y) { return !(__y < __x); } /// Based on operator< template inline bool operator>=(const queue<_Tp, _Seq>& __x, const queue<_Tp, _Seq>& __y) { return !(__x < __y); } #if __cplusplus >= 201103L template inline #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 // Constrained free swap overload, see p0185r1 typename enable_if<__is_swappable<_Seq>::value>::type #else void #endif swap(queue<_Tp, _Seq>& __x, queue<_Tp, _Seq>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template struct uses_allocator, _Alloc> : public uses_allocator<_Seq, _Alloc>::type { }; #endif // __cplusplus >= 201103L /** * @brief A standard container automatically sorting its contents. * * @ingroup sequences * * @tparam _Tp Type of element. * @tparam _Sequence Type of underlying sequence, defaults to vector<_Tp>. * @tparam _Compare Comparison function object type, defaults to * less<_Sequence::value_type>. * * This is not a true container, but an @e adaptor. It holds * another container, and provides a wrapper interface to that * container. The wrapper is what enforces priority-based sorting * and %queue behavior. Very few of the standard container/sequence * interface requirements are met (e.g., iterators). * * The second template parameter defines the type of the underlying * sequence/container. It defaults to std::vector, but it can be * any type that supports @c front(), @c push_back, @c pop_back, * and random-access iterators, such as std::deque or an * appropriate user-defined type. * * The third template parameter supplies the means of making * priority comparisons. It defaults to @c less but * can be anything defining a strict weak ordering. * * Members not found in @a normal containers are @c container_type, * which is a typedef for the second Sequence parameter, and @c * push, @c pop, and @c top, which are standard %queue operations. * * @note No equality/comparison operators are provided for * %priority_queue. * * @note Sorting of the elements takes place as they are added to, * and removed from, the %priority_queue using the * %priority_queue's member functions. If you access the elements * by other means, and change their data such that the sorting * order would be different, the %priority_queue will not re-sort * the elements for you. (How could it know to do so?) */ template, typename _Compare = less > class priority_queue { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Sequence::value_type _Sequence_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) # endif __glibcxx_class_requires(_Sequence, _SequenceConcept) __glibcxx_class_requires(_Sequence, _RandomAccessContainerConcept) __glibcxx_class_requires2(_Tp, _Sequence_value_type, _SameTypeConcept) __glibcxx_class_requires4(_Compare, bool, _Tp, _Tp, _BinaryFunctionConcept) #endif #if __cplusplus >= 201103L template using _Uses = typename enable_if::value>::type; #endif public: typedef typename _Sequence::value_type value_type; typedef typename _Sequence::reference reference; typedef typename _Sequence::const_reference const_reference; typedef typename _Sequence::size_type size_type; typedef _Sequence container_type; // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 2684. priority_queue lacking comparator typedef typedef _Compare value_compare; protected: // See queue::c for notes on these names. _Sequence c; _Compare comp; public: /** * @brief Default constructor creates no elements. */ #if __cplusplus < 201103L explicit priority_queue(const _Compare& __x = _Compare(), const _Sequence& __s = _Sequence()) : c(__s), comp(__x) { std::make_heap(c.begin(), c.end(), comp); } #else template, is_default_constructible<_Seq>>::value>::type> priority_queue() : c(), comp() { } explicit priority_queue(const _Compare& __x, const _Sequence& __s) : c(__s), comp(__x) { std::make_heap(c.begin(), c.end(), comp); } explicit priority_queue(const _Compare& __x, _Sequence&& __s = _Sequence()) : c(std::move(__s)), comp(__x) { std::make_heap(c.begin(), c.end(), comp); } template> explicit priority_queue(const _Alloc& __a) : c(__a), comp() { } template> priority_queue(const _Compare& __x, const _Alloc& __a) : c(__a), comp(__x) { } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2537. Constructors [...] taking allocators should call make_heap template> priority_queue(const _Compare& __x, const _Sequence& __c, const _Alloc& __a) : c(__c, __a), comp(__x) { std::make_heap(c.begin(), c.end(), comp); } template> priority_queue(const _Compare& __x, _Sequence&& __c, const _Alloc& __a) : c(std::move(__c), __a), comp(__x) { std::make_heap(c.begin(), c.end(), comp); } template> priority_queue(const priority_queue& __q, const _Alloc& __a) : c(__q.c, __a), comp(__q.comp) { } template> priority_queue(priority_queue&& __q, const _Alloc& __a) : c(std::move(__q.c), __a), comp(std::move(__q.comp)) { } #endif /** * @brief Builds a %queue from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __x A comparison functor describing a strict weak ordering. * @param __s An initial sequence with which to start. * * Begins by copying @a __s, inserting a copy of the elements * from @a [first,last) into the copy of @a __s, then ordering * the copy according to @a __x. * * For more information on function objects, see the * documentation on @link functors functor base * classes@endlink. */ #if __cplusplus < 201103L template priority_queue(_InputIterator __first, _InputIterator __last, const _Compare& __x = _Compare(), const _Sequence& __s = _Sequence()) : c(__s), comp(__x) { __glibcxx_requires_valid_range(__first, __last); c.insert(c.end(), __first, __last); std::make_heap(c.begin(), c.end(), comp); } #else template priority_queue(_InputIterator __first, _InputIterator __last, const _Compare& __x, const _Sequence& __s) : c(__s), comp(__x) { __glibcxx_requires_valid_range(__first, __last); c.insert(c.end(), __first, __last); std::make_heap(c.begin(), c.end(), comp); } template priority_queue(_InputIterator __first, _InputIterator __last, const _Compare& __x = _Compare(), _Sequence&& __s = _Sequence()) : c(std::move(__s)), comp(__x) { __glibcxx_requires_valid_range(__first, __last); c.insert(c.end(), __first, __last); std::make_heap(c.begin(), c.end(), comp); } #endif /** * Returns true if the %queue is empty. */ bool empty() const { return c.empty(); } /** Returns the number of elements in the %queue. */ size_type size() const { return c.size(); } /** * Returns a read-only (constant) reference to the data at the first * element of the %queue. */ const_reference top() const { __glibcxx_requires_nonempty(); return c.front(); } /** * @brief Add data to the %queue. * @param __x Data to be added. * * This is a typical %queue operation. * The time complexity of the operation depends on the underlying * sequence. */ void push(const value_type& __x) { c.push_back(__x); std::push_heap(c.begin(), c.end(), comp); } #if __cplusplus >= 201103L void push(value_type&& __x) { c.push_back(std::move(__x)); std::push_heap(c.begin(), c.end(), comp); } template void emplace(_Args&&... __args) { c.emplace_back(std::forward<_Args>(__args)...); std::push_heap(c.begin(), c.end(), comp); } #endif /** * @brief Removes first element. * * This is a typical %queue operation. It shrinks the %queue * by one. The time complexity of the operation depends on the * underlying sequence. * * Note that no data is returned, and if the first element's * data is needed, it should be retrieved before pop() is * called. */ void pop() { __glibcxx_requires_nonempty(); std::pop_heap(c.begin(), c.end(), comp); c.pop_back(); } #if __cplusplus >= 201103L void swap(priority_queue& __pq) noexcept(__and_< #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 __is_nothrow_swappable<_Sequence>, #else __is_nothrow_swappable<_Tp>, #endif __is_nothrow_swappable<_Compare> >::value) { using std::swap; swap(c, __pq.c); swap(comp, __pq.comp); } #endif // __cplusplus >= 201103L }; #if __cpp_deduction_guides >= 201606 template::value>, typename = enable_if_t::value>> priority_queue(_Compare, _Container) -> priority_queue; template::value_type, typename _Compare = less<_ValT>, typename _Container = vector<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = enable_if_t::value>, typename = enable_if_t::value>> priority_queue(_InputIterator, _InputIterator, _Compare = _Compare(), _Container = _Container()) -> priority_queue<_ValT, _Container, _Compare>; template::value>, typename = enable_if_t::value>, typename = enable_if_t<__is_allocator<_Allocator>::value>> priority_queue(_Compare, _Container, _Allocator) -> priority_queue; #endif // No equality/comparison operators are provided for priority_queue. #if __cplusplus >= 201103L template inline #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 // Constrained free swap overload, see p0185r1 typename enable_if<__and_<__is_swappable<_Sequence>, __is_swappable<_Compare>>::value>::type #else void #endif swap(priority_queue<_Tp, _Sequence, _Compare>& __x, priority_queue<_Tp, _Sequence, _Compare>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template struct uses_allocator, _Alloc> : public uses_allocator<_Sequence, _Alloc>::type { }; #endif // __cplusplus >= 201103L _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _STL_QUEUE_H */ PK!ғ|8/bits/stl_raw_storage_iter.hnu[// -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_raw_storage_iter.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _STL_RAW_STORAGE_ITERATOR_H #define _STL_RAW_STORAGE_ITERATOR_H 1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * This iterator class lets algorithms store their results into * uninitialized memory. */ template class raw_storage_iterator : public iterator { protected: _OutputIterator _M_iter; public: explicit raw_storage_iterator(_OutputIterator __x) : _M_iter(__x) {} raw_storage_iterator& operator*() { return *this; } raw_storage_iterator& operator=(const _Tp& __element) { std::_Construct(std::__addressof(*_M_iter), __element); return *this; } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2127. Move-construction with raw_storage_iterator raw_storage_iterator& operator=(_Tp&& __element) { std::_Construct(std::__addressof(*_M_iter), std::move(__element)); return *this; } #endif raw_storage_iterator& operator++() { ++_M_iter; return *this; } raw_storage_iterator operator++(int) { raw_storage_iterator __tmp = *this; ++_M_iter; return __tmp; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2454. Add raw_storage_iterator::base() member _OutputIterator base() const { return _M_iter; } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!`Dy8/bits/stl_relops.hnu[// std::rel_ops implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the, 2009 Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * Copyright (c) 1996,1997 * Silicon Graphics * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * */ /** @file bits/stl_relops.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{utility} * * Inclusion of this file has been removed from * all of the other STL headers for safety reasons, except std_utility.h. * For more information, see the thread of about twenty messages starting * with http://gcc.gnu.org/ml/libstdc++/2001-01/msg00223.html, or * http://gcc.gnu.org/onlinedocs/libstdc++/faq.html#faq.ambiguous_overloads * * Short summary: the rel_ops operators should be avoided for the present. */ #ifndef _STL_RELOPS_H #define _STL_RELOPS_H 1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace rel_ops { /** @namespace std::rel_ops * @brief The generated relational operators are sequestered here. */ /** * @brief Defines @c != for arbitrary types, in terms of @c ==. * @param __x A thing. * @param __y Another thing. * @return __x != __y * * This function uses @c == to determine its result. */ template inline bool operator!=(const _Tp& __x, const _Tp& __y) { return !(__x == __y); } /** * @brief Defines @c > for arbitrary types, in terms of @c <. * @param __x A thing. * @param __y Another thing. * @return __x > __y * * This function uses @c < to determine its result. */ template inline bool operator>(const _Tp& __x, const _Tp& __y) { return __y < __x; } /** * @brief Defines @c <= for arbitrary types, in terms of @c <. * @param __x A thing. * @param __y Another thing. * @return __x <= __y * * This function uses @c < to determine its result. */ template inline bool operator<=(const _Tp& __x, const _Tp& __y) { return !(__y < __x); } /** * @brief Defines @c >= for arbitrary types, in terms of @c <. * @param __x A thing. * @param __y Another thing. * @return __x >= __y * * This function uses @c < to determine its result. */ template inline bool operator>=(const _Tp& __x, const _Tp& __y) { return !(__x < __y); } } // namespace rel_ops _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_RELOPS_H */ PK!28/bits/stl_set.hnu[// Set implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_set.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{set} */ #ifndef _STL_SET_H #define _STL_SET_H 1 #include #if __cplusplus >= 201103L #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER template class multiset; /** * @brief A standard container made up of unique keys, which can be * retrieved in logarithmic time. * * @ingroup associative_containers * * @tparam _Key Type of key objects. * @tparam _Compare Comparison function object type, defaults to less<_Key>. * @tparam _Alloc Allocator type, defaults to allocator<_Key>. * * Meets the requirements of a container, a * reversible container, and an * associative container (using unique keys). * * Sets support bidirectional iterators. * * The private tree data is declared exactly the same way for set and * multiset; the distinction is made entirely in how the tree functions are * called (*_unique versus *_equal, same as the standard). */ template, typename _Alloc = std::allocator<_Key> > class set { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Alloc::value_type _Alloc_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Key, _SGIAssignableConcept) # endif __glibcxx_class_requires4(_Compare, bool, _Key, _Key, _BinaryFunctionConcept) __glibcxx_class_requires2(_Key, _Alloc_value_type, _SameTypeConcept) #endif #if __cplusplus >= 201103L static_assert(is_same::type, _Key>::value, "std::set must have a non-const, non-volatile value_type"); # ifdef __STRICT_ANSI__ static_assert(is_same::value, "std::set must have the same value_type as its allocator"); # endif #endif public: // typedefs: //@{ /// Public typedefs. typedef _Key key_type; typedef _Key value_type; typedef _Compare key_compare; typedef _Compare value_compare; typedef _Alloc allocator_type; //@} private: typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Key>::other _Key_alloc_type; typedef _Rb_tree, key_compare, _Key_alloc_type> _Rep_type; _Rep_type _M_t; // Red-black tree representing set. typedef __gnu_cxx::__alloc_traits<_Key_alloc_type> _Alloc_traits; public: //@{ /// Iterator-related typedefs. typedef typename _Alloc_traits::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef typename _Alloc_traits::reference reference; typedef typename _Alloc_traits::const_reference const_reference; // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 103. set::iterator is required to be modifiable, // but this allows modification of keys. typedef typename _Rep_type::const_iterator iterator; typedef typename _Rep_type::const_iterator const_iterator; typedef typename _Rep_type::const_reverse_iterator reverse_iterator; typedef typename _Rep_type::const_reverse_iterator const_reverse_iterator; typedef typename _Rep_type::size_type size_type; typedef typename _Rep_type::difference_type difference_type; //@} #if __cplusplus > 201402L using node_type = typename _Rep_type::node_type; using insert_return_type = typename _Rep_type::insert_return_type; #endif // allocation/deallocation /** * @brief Default constructor creates no elements. */ #if __cplusplus < 201103L set() : _M_t() { } #else set() = default; #endif /** * @brief Creates a %set with no elements. * @param __comp Comparator to use. * @param __a An allocator object. */ explicit set(const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Key_alloc_type(__a)) { } /** * @brief Builds a %set from a range. * @param __first An input iterator. * @param __last An input iterator. * * Create a %set consisting of copies of the elements from * [__first,__last). This is linear in N if the range is * already sorted, and NlogN otherwise (where N is * distance(__first,__last)). */ template set(_InputIterator __first, _InputIterator __last) : _M_t() { _M_t._M_insert_unique(__first, __last); } /** * @brief Builds a %set from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __comp A comparison functor. * @param __a An allocator object. * * Create a %set consisting of copies of the elements from * [__first,__last). This is linear in N if the range is * already sorted, and NlogN otherwise (where N is * distance(__first,__last)). */ template set(_InputIterator __first, _InputIterator __last, const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Key_alloc_type(__a)) { _M_t._M_insert_unique(__first, __last); } /** * @brief %Set copy constructor. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L set(const set& __x) : _M_t(__x._M_t) { } #else set(const set&) = default; /** * @brief %Set move constructor * * The newly-created %set contains the exact contents of the moved * instance. The moved instance is a valid, but unspecified, %set. */ set(set&&) = default; /** * @brief Builds a %set from an initializer_list. * @param __l An initializer_list. * @param __comp A comparison functor. * @param __a An allocator object. * * Create a %set consisting of copies of the elements in the list. * This is linear in N if the list is already sorted, and NlogN * otherwise (where N is @a __l.size()). */ set(initializer_list __l, const _Compare& __comp = _Compare(), const allocator_type& __a = allocator_type()) : _M_t(__comp, _Key_alloc_type(__a)) { _M_t._M_insert_unique(__l.begin(), __l.end()); } /// Allocator-extended default constructor. explicit set(const allocator_type& __a) : _M_t(_Compare(), _Key_alloc_type(__a)) { } /// Allocator-extended copy constructor. set(const set& __x, const allocator_type& __a) : _M_t(__x._M_t, _Key_alloc_type(__a)) { } /// Allocator-extended move constructor. set(set&& __x, const allocator_type& __a) noexcept(is_nothrow_copy_constructible<_Compare>::value && _Alloc_traits::_S_always_equal()) : _M_t(std::move(__x._M_t), _Key_alloc_type(__a)) { } /// Allocator-extended initialier-list constructor. set(initializer_list __l, const allocator_type& __a) : _M_t(_Compare(), _Key_alloc_type(__a)) { _M_t._M_insert_unique(__l.begin(), __l.end()); } /// Allocator-extended range constructor. template set(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _M_t(_Compare(), _Key_alloc_type(__a)) { _M_t._M_insert_unique(__first, __last); } /** * The dtor only erases the elements, and note that if the elements * themselves are pointers, the pointed-to memory is not touched in any * way. Managing the pointer is the user's responsibility. */ ~set() = default; #endif /** * @brief %Set assignment operator. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L set& operator=(const set& __x) { _M_t = __x._M_t; return *this; } #else set& operator=(const set&) = default; /// Move assignment operator. set& operator=(set&&) = default; /** * @brief %Set list assignment operator. * @param __l An initializer_list. * * This function fills a %set with copies of the elements in the * initializer list @a __l. * * Note that the assignment completely changes the %set and * that the resulting %set's size is the same as the number * of elements assigned. */ set& operator=(initializer_list __l) { _M_t._M_assign_unique(__l.begin(), __l.end()); return *this; } #endif // accessors: /// Returns the comparison object with which the %set was constructed. key_compare key_comp() const { return _M_t.key_comp(); } /// Returns the comparison object with which the %set was constructed. value_compare value_comp() const { return _M_t.key_comp(); } /// Returns the allocator object with which the %set was constructed. allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_t.get_allocator()); } /** * Returns a read-only (constant) iterator that points to the first * element in the %set. Iteration is done in ascending order according * to the keys. */ iterator begin() const _GLIBCXX_NOEXCEPT { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * element in the %set. Iteration is done in ascending order according * to the keys. */ iterator end() const _GLIBCXX_NOEXCEPT { return _M_t.end(); } /** * Returns a read-only (constant) iterator that points to the last * element in the %set. Iteration is done in descending order according * to the keys. */ reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to the * last pair in the %set. Iteration is done in descending order * according to the keys. */ reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return _M_t.rend(); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the first * element in the %set. Iteration is done in ascending order according * to the keys. */ iterator cbegin() const noexcept { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * element in the %set. Iteration is done in ascending order according * to the keys. */ iterator cend() const noexcept { return _M_t.end(); } /** * Returns a read-only (constant) iterator that points to the last * element in the %set. Iteration is done in descending order according * to the keys. */ reverse_iterator crbegin() const noexcept { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to the * last pair in the %set. Iteration is done in descending order * according to the keys. */ reverse_iterator crend() const noexcept { return _M_t.rend(); } #endif /// Returns true if the %set is empty. bool empty() const _GLIBCXX_NOEXCEPT { return _M_t.empty(); } /// Returns the size of the %set. size_type size() const _GLIBCXX_NOEXCEPT { return _M_t.size(); } /// Returns the maximum size of the %set. size_type max_size() const _GLIBCXX_NOEXCEPT { return _M_t.max_size(); } /** * @brief Swaps data with another %set. * @param __x A %set of the same element and allocator types. * * This exchanges the elements between two sets in constant * time. (It is only swapping a pointer, an integer, and an * instance of the @c Compare type (which itself is often * stateless and empty), so it should be quite fast.) Note * that the global std::swap() function is specialized such * that std::swap(s1,s2) will feed to this function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(set& __x) _GLIBCXX_NOEXCEPT_IF(__is_nothrow_swappable<_Compare>::value) { _M_t.swap(__x._M_t); } // insert/erase #if __cplusplus >= 201103L /** * @brief Attempts to build and insert an element into the %set. * @param __args Arguments used to generate an element. * @return A pair, of which the first element is an iterator that points * to the possibly inserted element, and the second is a bool * that is true if the element was actually inserted. * * This function attempts to build and insert an element into the %set. * A %set relies on unique keys and thus an element is only inserted if * it is not already present in the %set. * * Insertion requires logarithmic time. */ template std::pair emplace(_Args&&... __args) { return _M_t._M_emplace_unique(std::forward<_Args>(__args)...); } /** * @brief Attempts to insert an element into the %set. * @param __pos An iterator that serves as a hint as to where the * element should be inserted. * @param __args Arguments used to generate the element to be * inserted. * @return An iterator that points to the element with key equivalent to * the one generated from @a __args (may or may not be the * element itself). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument emplace() * does. Note that the first parameter is only a hint and can * potentially improve the performance of the insertion process. A bad * hint would cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires logarithmic time (if the hint is not taken). */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_t._M_emplace_hint_unique(__pos, std::forward<_Args>(__args)...); } #endif /** * @brief Attempts to insert an element into the %set. * @param __x Element to be inserted. * @return A pair, of which the first element is an iterator that points * to the possibly inserted element, and the second is a bool * that is true if the element was actually inserted. * * This function attempts to insert an element into the %set. A %set * relies on unique keys and thus an element is only inserted if it is * not already present in the %set. * * Insertion requires logarithmic time. */ std::pair insert(const value_type& __x) { std::pair __p = _M_t._M_insert_unique(__x); return std::pair(__p.first, __p.second); } #if __cplusplus >= 201103L std::pair insert(value_type&& __x) { std::pair __p = _M_t._M_insert_unique(std::move(__x)); return std::pair(__p.first, __p.second); } #endif /** * @brief Attempts to insert an element into the %set. * @param __position An iterator that serves as a hint as to where the * element should be inserted. * @param __x Element to be inserted. * @return An iterator that points to the element with key of * @a __x (may or may not be the element passed in). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument insert() * does. Note that the first parameter is only a hint and can * potentially improve the performance of the insertion process. A bad * hint would cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires logarithmic time (if the hint is not taken). */ iterator insert(const_iterator __position, const value_type& __x) { return _M_t._M_insert_unique_(__position, __x); } #if __cplusplus >= 201103L iterator insert(const_iterator __position, value_type&& __x) { return _M_t._M_insert_unique_(__position, std::move(__x)); } #endif /** * @brief A template function that attempts to insert a range * of elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_t._M_insert_unique(__first, __last); } #if __cplusplus >= 201103L /** * @brief Attempts to insert a list of elements into the %set. * @param __l A std::initializer_list of elements * to be inserted. * * Complexity similar to that of the range constructor. */ void insert(initializer_list __l) { this->insert(__l.begin(), __l.end()); } #endif #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_t.extract(__pos); } /// Extract a node. node_type extract(const key_type& __x) { return _M_t.extract(__x); } /// Re-insert an extracted node. insert_return_type insert(node_type&& __nh) { return _M_t._M_reinsert_node_unique(std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator __hint, node_type&& __nh) { return _M_t._M_reinsert_node_hint_unique(__hint, std::move(__nh)); } template friend class std::_Rb_tree_merge_helper; template void merge(set<_Key, _Compare1, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_unique(_Merge_helper::_S_get_tree(__source)); } template void merge(set<_Key, _Compare1, _Alloc>&& __source) { merge(__source); } template void merge(multiset<_Key, _Compare1, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_unique(_Merge_helper::_S_get_tree(__source)); } template void merge(multiset<_Key, _Compare1, _Alloc>&& __source) { merge(__source); } #endif // C++17 #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases an element from a %set. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a __position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given iterator, * from a %set. Note that this function only erases the element, and * that if the element is itself a pointer, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ _GLIBCXX_ABI_TAG_CXX11 iterator erase(const_iterator __position) { return _M_t.erase(__position); } #else /** * @brief Erases an element from a %set. * @param position An iterator pointing to the element to be erased. * * This function erases an element, pointed to by the given iterator, * from a %set. Note that this function only erases the element, and * that if the element is itself a pointer, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ void erase(iterator __position) { _M_t.erase(__position); } #endif /** * @brief Erases elements according to the provided key. * @param __x Key of element to be erased. * @return The number of elements erased. * * This function erases all the elements located by the given key from * a %set. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_t.erase(__x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases a [__first,__last) range of elements from a %set. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * @return The iterator @a __last. * * This function erases a sequence of elements from a %set. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ _GLIBCXX_ABI_TAG_CXX11 iterator erase(const_iterator __first, const_iterator __last) { return _M_t.erase(__first, __last); } #else /** * @brief Erases a [first,last) range of elements from a %set. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * * This function erases a sequence of elements from a %set. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ void erase(iterator __first, iterator __last) { _M_t.erase(__first, __last); } #endif /** * Erases all elements in a %set. Note that this function only erases * the elements, and that if the elements themselves are pointers, the * pointed-to memory is not touched in any way. Managing the pointer is * the user's responsibility. */ void clear() _GLIBCXX_NOEXCEPT { _M_t.clear(); } // set operations: //@{ /** * @brief Finds the number of elements. * @param __x Element to located. * @return Number of elements with specified key. * * This function only makes sense for multisets; for set the result will * either be 0 (not present) or 1 (present). */ size_type count(const key_type& __x) const { return _M_t.find(__x) == _M_t.end() ? 0 : 1; } #if __cplusplus > 201103L template auto count(const _Kt& __x) const -> decltype(_M_t._M_count_tr(__x)) { return _M_t._M_count_tr(__x); } #endif //@} // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload //@{ /** * @brief Tries to locate an element in a %set. * @param __x Element to be located. * @return Iterator pointing to sought-after element, or end() if not * found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after element. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_t.find(__x); } const_iterator find(const key_type& __x) const { return _M_t.find(__x); } #if __cplusplus > 201103L template auto find(const _Kt& __x) -> decltype(iterator{_M_t._M_find_tr(__x)}) { return iterator{_M_t._M_find_tr(__x)}; } template auto find(const _Kt& __x) const -> decltype(const_iterator{_M_t._M_find_tr(__x)}) { return const_iterator{_M_t._M_find_tr(__x)}; } #endif //@} //@{ /** * @brief Finds the beginning of a subsequence matching given key. * @param __x Key to be located. * @return Iterator pointing to first element equal to or greater * than key, or end(). * * This function returns the first element of a subsequence of elements * that matches the given key. If unsuccessful it returns an iterator * pointing to the first element that has a greater value than given key * or end() if no such element exists. */ iterator lower_bound(const key_type& __x) { return _M_t.lower_bound(__x); } const_iterator lower_bound(const key_type& __x) const { return _M_t.lower_bound(__x); } #if __cplusplus > 201103L template auto lower_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_lower_bound_tr(__x))) { return iterator(_M_t._M_lower_bound_tr(__x)); } template auto lower_bound(const _Kt& __x) const -> decltype(const_iterator(_M_t._M_lower_bound_tr(__x))) { return const_iterator(_M_t._M_lower_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the end of a subsequence matching given key. * @param __x Key to be located. * @return Iterator pointing to the first element * greater than key, or end(). */ iterator upper_bound(const key_type& __x) { return _M_t.upper_bound(__x); } const_iterator upper_bound(const key_type& __x) const { return _M_t.upper_bound(__x); } #if __cplusplus > 201103L template auto upper_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_upper_bound_tr(__x))) { return iterator(_M_t._M_upper_bound_tr(__x)); } template auto upper_bound(const _Kt& __x) const -> decltype(iterator(_M_t._M_upper_bound_tr(__x))) { return const_iterator(_M_t._M_upper_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. * * This function is equivalent to * @code * std::make_pair(c.lower_bound(val), * c.upper_bound(val)) * @endcode * (but is faster than making the calls separately). * * This function probably only makes sense for multisets. */ std::pair equal_range(const key_type& __x) { return _M_t.equal_range(__x); } std::pair equal_range(const key_type& __x) const { return _M_t.equal_range(__x); } #if __cplusplus > 201103L template auto equal_range(const _Kt& __x) -> decltype(pair(_M_t._M_equal_range_tr(__x))) { return pair(_M_t._M_equal_range_tr(__x)); } template auto equal_range(const _Kt& __x) const -> decltype(pair(_M_t._M_equal_range_tr(__x))) { return pair(_M_t._M_equal_range_tr(__x)); } #endif //@} template friend bool operator==(const set<_K1, _C1, _A1>&, const set<_K1, _C1, _A1>&); template friend bool operator<(const set<_K1, _C1, _A1>&, const set<_K1, _C1, _A1>&); }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> set(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> set::value_type, _Compare, _Allocator>; template, typename _Allocator = allocator<_Key>, typename = _RequireAllocator<_Allocator>> set(initializer_list<_Key>, _Compare = _Compare(), _Allocator = _Allocator()) -> set<_Key, _Compare, _Allocator>; template, typename = _RequireAllocator<_Allocator>> set(_InputIterator, _InputIterator, _Allocator) -> set::value_type, less::value_type>, _Allocator>; template> set(initializer_list<_Key>, _Allocator) -> set<_Key, less<_Key>, _Allocator>; #endif /** * @brief Set equality comparison. * @param __x A %set. * @param __y A %set of the same type as @a x. * @return True iff the size and elements of the sets are equal. * * This is an equivalence relation. It is linear in the size of the sets. * Sets are considered equivalent if their sizes are equal, and if * corresponding elements compare equal. */ template inline bool operator==(const set<_Key, _Compare, _Alloc>& __x, const set<_Key, _Compare, _Alloc>& __y) { return __x._M_t == __y._M_t; } /** * @brief Set ordering relation. * @param __x A %set. * @param __y A %set of the same type as @a x. * @return True iff @a __x is lexicographically less than @a __y. * * This is a total ordering relation. It is linear in the size of the * sets. The elements must be comparable with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const set<_Key, _Compare, _Alloc>& __x, const set<_Key, _Compare, _Alloc>& __y) { return __x._M_t < __y._M_t; } /// Returns !(x == y). template inline bool operator!=(const set<_Key, _Compare, _Alloc>& __x, const set<_Key, _Compare, _Alloc>& __y) { return !(__x == __y); } /// Returns y < x. template inline bool operator>(const set<_Key, _Compare, _Alloc>& __x, const set<_Key, _Compare, _Alloc>& __y) { return __y < __x; } /// Returns !(y < x) template inline bool operator<=(const set<_Key, _Compare, _Alloc>& __x, const set<_Key, _Compare, _Alloc>& __y) { return !(__y < __x); } /// Returns !(x < y) template inline bool operator>=(const set<_Key, _Compare, _Alloc>& __x, const set<_Key, _Compare, _Alloc>& __y) { return !(__x < __y); } /// See std::set::swap(). template inline void swap(set<_Key, _Compare, _Alloc>& __x, set<_Key, _Compare, _Alloc>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { __x.swap(__y); } _GLIBCXX_END_NAMESPACE_CONTAINER #if __cplusplus > 201402L // Allow std::set access to internals of compatible sets. template struct _Rb_tree_merge_helper<_GLIBCXX_STD_C::set<_Val, _Cmp1, _Alloc>, _Cmp2> { private: friend class _GLIBCXX_STD_C::set<_Val, _Cmp1, _Alloc>; static auto& _S_get_tree(_GLIBCXX_STD_C::set<_Val, _Cmp2, _Alloc>& __set) { return __set._M_t; } static auto& _S_get_tree(_GLIBCXX_STD_C::multiset<_Val, _Cmp2, _Alloc>& __set) { return __set._M_t; } }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } //namespace std #endif /* _STL_SET_H */ PK! /f..8/bits/stl_stack.hnu[// Stack implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_stack.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{stack} */ #ifndef _STL_STACK_H #define _STL_STACK_H 1 #include #include #if __cplusplus >= 201103L # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief A standard container giving FILO behavior. * * @ingroup sequences * * @tparam _Tp Type of element. * @tparam _Sequence Type of underlying sequence, defaults to deque<_Tp>. * * Meets many of the requirements of a * container, * but does not define anything to do with iterators. Very few of the * other standard container interfaces are defined. * * This is not a true container, but an @e adaptor. It holds * another container, and provides a wrapper interface to that * container. The wrapper is what enforces strict * first-in-last-out %stack behavior. * * The second template parameter defines the type of the underlying * sequence/container. It defaults to std::deque, but it can be * any type that supports @c back, @c push_back, and @c pop_back, * such as std::list, std::vector, or an appropriate user-defined * type. * * Members not found in @a normal containers are @c container_type, * which is a typedef for the second Sequence parameter, and @c * push, @c pop, and @c top, which are standard %stack/FILO * operations. */ template > class stack { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Sequence::value_type _Sequence_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) __glibcxx_class_requires(_Sequence, _BackInsertionSequenceConcept) # endif __glibcxx_class_requires2(_Tp, _Sequence_value_type, _SameTypeConcept) #endif template friend bool operator==(const stack<_Tp1, _Seq1>&, const stack<_Tp1, _Seq1>&); template friend bool operator<(const stack<_Tp1, _Seq1>&, const stack<_Tp1, _Seq1>&); #if __cplusplus >= 201103L template using _Uses = typename enable_if::value>::type; #endif public: typedef typename _Sequence::value_type value_type; typedef typename _Sequence::reference reference; typedef typename _Sequence::const_reference const_reference; typedef typename _Sequence::size_type size_type; typedef _Sequence container_type; protected: // See queue::c for notes on this name. _Sequence c; public: // XXX removed old def ctor, added def arg to this one to match 14882 /** * @brief Default constructor creates no elements. */ #if __cplusplus < 201103L explicit stack(const _Sequence& __c = _Sequence()) : c(__c) { } #else template::value>::type> stack() : c() { } explicit stack(const _Sequence& __c) : c(__c) { } explicit stack(_Sequence&& __c) : c(std::move(__c)) { } template> explicit stack(const _Alloc& __a) : c(__a) { } template> stack(const _Sequence& __c, const _Alloc& __a) : c(__c, __a) { } template> stack(_Sequence&& __c, const _Alloc& __a) : c(std::move(__c), __a) { } template> stack(const stack& __q, const _Alloc& __a) : c(__q.c, __a) { } template> stack(stack&& __q, const _Alloc& __a) : c(std::move(__q.c), __a) { } #endif /** * Returns true if the %stack is empty. */ bool empty() const { return c.empty(); } /** Returns the number of elements in the %stack. */ size_type size() const { return c.size(); } /** * Returns a read/write reference to the data at the first * element of the %stack. */ reference top() { __glibcxx_requires_nonempty(); return c.back(); } /** * Returns a read-only (constant) reference to the data at the first * element of the %stack. */ const_reference top() const { __glibcxx_requires_nonempty(); return c.back(); } /** * @brief Add data to the top of the %stack. * @param __x Data to be added. * * This is a typical %stack operation. The function creates an * element at the top of the %stack and assigns the given data * to it. The time complexity of the operation depends on the * underlying sequence. */ void push(const value_type& __x) { c.push_back(__x); } #if __cplusplus >= 201103L void push(value_type&& __x) { c.push_back(std::move(__x)); } #if __cplusplus > 201402L template decltype(auto) emplace(_Args&&... __args) { return c.emplace_back(std::forward<_Args>(__args)...); } #else template void emplace(_Args&&... __args) { c.emplace_back(std::forward<_Args>(__args)...); } #endif #endif /** * @brief Removes first element. * * This is a typical %stack operation. It shrinks the %stack * by one. The time complexity of the operation depends on the * underlying sequence. * * Note that no data is returned, and if the first element's * data is needed, it should be retrieved before pop() is * called. */ void pop() { __glibcxx_requires_nonempty(); c.pop_back(); } #if __cplusplus >= 201103L void swap(stack& __s) #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 noexcept(__is_nothrow_swappable<_Sequence>::value) #else noexcept(__is_nothrow_swappable<_Tp>::value) #endif { using std::swap; swap(c, __s.c); } #endif // __cplusplus >= 201103L }; #if __cpp_deduction_guides >= 201606 template::value>> stack(_Container) -> stack; template::value>, typename = enable_if_t<__is_allocator<_Allocator>::value>> stack(_Container, _Allocator) -> stack; #endif /** * @brief Stack equality comparison. * @param __x A %stack. * @param __y A %stack of the same type as @a __x. * @return True iff the size and elements of the stacks are equal. * * This is an equivalence relation. Complexity and semantics * depend on the underlying sequence type, but the expected rules * are: this relation is linear in the size of the sequences, and * stacks are considered equivalent if their sequences compare * equal. */ template inline bool operator==(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y) { return __x.c == __y.c; } /** * @brief Stack ordering relation. * @param __x A %stack. * @param __y A %stack of the same type as @a x. * @return True iff @a x is lexicographically less than @a __y. * * This is an total ordering relation. Complexity and semantics * depend on the underlying sequence type, but the expected rules * are: this relation is linear in the size of the sequences, the * elements must be comparable with @c <, and * std::lexicographical_compare() is usually used to make the * determination. */ template inline bool operator<(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y) { return __x.c < __y.c; } /// Based on operator== template inline bool operator!=(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y) { return !(__x == __y); } /// Based on operator< template inline bool operator>(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y) { return __y < __x; } /// Based on operator< template inline bool operator<=(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y) { return !(__y < __x); } /// Based on operator< template inline bool operator>=(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y) { return !(__x < __y); } #if __cplusplus >= 201103L template inline #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 // Constrained free swap overload, see p0185r1 typename enable_if<__is_swappable<_Seq>::value>::type #else void #endif swap(stack<_Tp, _Seq>& __x, stack<_Tp, _Seq>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template struct uses_allocator, _Alloc> : public uses_allocator<_Seq, _Alloc>::type { }; #endif // __cplusplus >= 201103L _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _STL_STACK_H */ PK!PZ8 8/bits/stl_tempbuf.hnu[// Temporary buffer implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_tempbuf.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _STL_TEMPBUF_H #define _STL_TEMPBUF_H 1 #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief Allocates a temporary buffer. * @param __len The number of objects of type Tp. * @return See full description. * * Reinventing the wheel, but this time with prettier spokes! * * This function tries to obtain storage for @c __len adjacent Tp * objects. The objects themselves are not constructed, of course. * A pair<> is returned containing the buffer s address and * capacity (in the units of sizeof(_Tp)), or a pair of 0 values if * no storage can be obtained. Note that the capacity obtained * may be less than that requested if the memory is unavailable; * you should compare len with the .second return value. * * Provides the nothrow exception guarantee. */ template pair<_Tp*, ptrdiff_t> get_temporary_buffer(ptrdiff_t __len) _GLIBCXX_NOEXCEPT { const ptrdiff_t __max = __gnu_cxx::__numeric_traits::__max / sizeof(_Tp); if (__len > __max) __len = __max; while (__len > 0) { _Tp* __tmp = static_cast<_Tp*>(::operator new(__len * sizeof(_Tp), std::nothrow)); if (__tmp != 0) return std::pair<_Tp*, ptrdiff_t>(__tmp, __len); __len /= 2; } return std::pair<_Tp*, ptrdiff_t>(static_cast<_Tp*>(0), 0); } /** * @brief The companion to get_temporary_buffer(). * @param __p A buffer previously allocated by get_temporary_buffer. * @return None. * * Frees the memory pointed to by __p. */ template inline void return_temporary_buffer(_Tp* __p) { ::operator delete(__p, std::nothrow); } /** * This class is used in two places: stl_algo.h and ext/memory, * where it is wrapped as the temporary_buffer class. See * temporary_buffer docs for more notes. */ template class _Temporary_buffer { // concept requirements __glibcxx_class_requires(_ForwardIterator, _ForwardIteratorConcept) public: typedef _Tp value_type; typedef value_type* pointer; typedef pointer iterator; typedef ptrdiff_t size_type; protected: size_type _M_original_len; size_type _M_len; pointer _M_buffer; public: /// As per Table mumble. size_type size() const { return _M_len; } /// Returns the size requested by the constructor; may be >size(). size_type requested_size() const { return _M_original_len; } /// As per Table mumble. iterator begin() { return _M_buffer; } /// As per Table mumble. iterator end() { return _M_buffer + _M_len; } /** * Constructs a temporary buffer of a size somewhere between * zero and the size of the given range. */ _Temporary_buffer(_ForwardIterator __first, _ForwardIterator __last); ~_Temporary_buffer() { std::_Destroy(_M_buffer, _M_buffer + _M_len); std::return_temporary_buffer(_M_buffer); } private: // Disable copy constructor and assignment operator. _Temporary_buffer(const _Temporary_buffer&); void operator=(const _Temporary_buffer&); }; template struct __uninitialized_construct_buf_dispatch { template static void __ucr(_Pointer __first, _Pointer __last, _ForwardIterator __seed) { if(__first == __last) return; _Pointer __cur = __first; __try { std::_Construct(std::__addressof(*__first), _GLIBCXX_MOVE(*__seed)); _Pointer __prev = __cur; ++__cur; for(; __cur != __last; ++__cur, ++__prev) std::_Construct(std::__addressof(*__cur), _GLIBCXX_MOVE(*__prev)); *__seed = _GLIBCXX_MOVE(*__prev); } __catch(...) { std::_Destroy(__first, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_construct_buf_dispatch { template static void __ucr(_Pointer, _Pointer, _ForwardIterator) { } }; // Constructs objects in the range [first, last). // Note that while these new objects will take valid values, // their exact value is not defined. In particular they may // be 'moved from'. // // While *__seed may be altered during this algorithm, it will have // the same value when the algorithm finishes, unless one of the // constructions throws. // // Requirements: _Pointer::value_type(_Tp&&) is valid. template inline void __uninitialized_construct_buf(_Pointer __first, _Pointer __last, _ForwardIterator __seed) { typedef typename std::iterator_traits<_Pointer>::value_type _ValueType; std::__uninitialized_construct_buf_dispatch< __has_trivial_constructor(_ValueType)>:: __ucr(__first, __last, __seed); } template _Temporary_buffer<_ForwardIterator, _Tp>:: _Temporary_buffer(_ForwardIterator __first, _ForwardIterator __last) : _M_original_len(std::distance(__first, __last)), _M_len(0), _M_buffer(0) { __try { std::pair __p(std::get_temporary_buffer< value_type>(_M_original_len)); _M_buffer = __p.first; _M_len = __p.second; if (_M_buffer) std::__uninitialized_construct_buf(_M_buffer, _M_buffer + _M_len, __first); } __catch(...) { std::return_temporary_buffer(_M_buffer); _M_buffer = 0; _M_len = 0; __throw_exception_again; } } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _STL_TEMPBUF_H */ PK!mi$$8/bits/stl_tree.hnu[// RB tree implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * */ /** @file bits/stl_tree.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{map,set} */ #ifndef _STL_TREE_H #define _STL_TREE_H 1 #pragma GCC system_header #include #include #include #include #include #if __cplusplus >= 201103L # include #endif #if __cplusplus > 201402L # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if __cplusplus > 201103L # define __cpp_lib_generic_associative_lookup 201304 #endif // Red-black tree class, designed for use in implementing STL // associative containers (set, multiset, map, and multimap). The // insertion and deletion algorithms are based on those in Cormen, // Leiserson, and Rivest, Introduction to Algorithms (MIT Press, // 1990), except that // // (1) the header cell is maintained with links not only to the root // but also to the leftmost node of the tree, to enable constant // time begin(), and to the rightmost node of the tree, to enable // linear time performance when used with the generic set algorithms // (set_union, etc.) // // (2) when a node being deleted has two children its successor node // is relinked into its place, rather than copied, so that the only // iterators invalidated are those referring to the deleted node. enum _Rb_tree_color { _S_red = false, _S_black = true }; struct _Rb_tree_node_base { typedef _Rb_tree_node_base* _Base_ptr; typedef const _Rb_tree_node_base* _Const_Base_ptr; _Rb_tree_color _M_color; _Base_ptr _M_parent; _Base_ptr _M_left; _Base_ptr _M_right; static _Base_ptr _S_minimum(_Base_ptr __x) _GLIBCXX_NOEXCEPT { while (__x->_M_left != 0) __x = __x->_M_left; return __x; } static _Const_Base_ptr _S_minimum(_Const_Base_ptr __x) _GLIBCXX_NOEXCEPT { while (__x->_M_left != 0) __x = __x->_M_left; return __x; } static _Base_ptr _S_maximum(_Base_ptr __x) _GLIBCXX_NOEXCEPT { while (__x->_M_right != 0) __x = __x->_M_right; return __x; } static _Const_Base_ptr _S_maximum(_Const_Base_ptr __x) _GLIBCXX_NOEXCEPT { while (__x->_M_right != 0) __x = __x->_M_right; return __x; } }; // Helper type offering value initialization guarantee on the compare functor. template struct _Rb_tree_key_compare { _Key_compare _M_key_compare; _Rb_tree_key_compare() _GLIBCXX_NOEXCEPT_IF( is_nothrow_default_constructible<_Key_compare>::value) : _M_key_compare() { } _Rb_tree_key_compare(const _Key_compare& __comp) : _M_key_compare(__comp) { } #if __cplusplus >= 201103L // Copy constructor added for consistency with C++98 mode. _Rb_tree_key_compare(const _Rb_tree_key_compare&) = default; _Rb_tree_key_compare(_Rb_tree_key_compare&& __x) noexcept(is_nothrow_copy_constructible<_Key_compare>::value) : _M_key_compare(__x._M_key_compare) { } #endif }; // Helper type to manage default initialization of node count and header. struct _Rb_tree_header { _Rb_tree_node_base _M_header; size_t _M_node_count; // Keeps track of size of tree. _Rb_tree_header() _GLIBCXX_NOEXCEPT { _M_header._M_color = _S_red; _M_reset(); } #if __cplusplus >= 201103L _Rb_tree_header(_Rb_tree_header&& __x) noexcept { if (__x._M_header._M_parent != nullptr) _M_move_data(__x); else { _M_header._M_color = _S_red; _M_reset(); } } #endif void _M_move_data(_Rb_tree_header& __from) { _M_header._M_color = __from._M_header._M_color; _M_header._M_parent = __from._M_header._M_parent; _M_header._M_left = __from._M_header._M_left; _M_header._M_right = __from._M_header._M_right; _M_header._M_parent->_M_parent = &_M_header; _M_node_count = __from._M_node_count; __from._M_reset(); } void _M_reset() { _M_header._M_parent = 0; _M_header._M_left = &_M_header; _M_header._M_right = &_M_header; _M_node_count = 0; } }; template struct _Rb_tree_node : public _Rb_tree_node_base { typedef _Rb_tree_node<_Val>* _Link_type; #if __cplusplus < 201103L _Val _M_value_field; _Val* _M_valptr() { return std::__addressof(_M_value_field); } const _Val* _M_valptr() const { return std::__addressof(_M_value_field); } #else __gnu_cxx::__aligned_membuf<_Val> _M_storage; _Val* _M_valptr() { return _M_storage._M_ptr(); } const _Val* _M_valptr() const { return _M_storage._M_ptr(); } #endif }; _GLIBCXX_PURE _Rb_tree_node_base* _Rb_tree_increment(_Rb_tree_node_base* __x) throw (); _GLIBCXX_PURE const _Rb_tree_node_base* _Rb_tree_increment(const _Rb_tree_node_base* __x) throw (); _GLIBCXX_PURE _Rb_tree_node_base* _Rb_tree_decrement(_Rb_tree_node_base* __x) throw (); _GLIBCXX_PURE const _Rb_tree_node_base* _Rb_tree_decrement(const _Rb_tree_node_base* __x) throw (); template struct _Rb_tree_iterator { typedef _Tp value_type; typedef _Tp& reference; typedef _Tp* pointer; typedef bidirectional_iterator_tag iterator_category; typedef ptrdiff_t difference_type; typedef _Rb_tree_iterator<_Tp> _Self; typedef _Rb_tree_node_base::_Base_ptr _Base_ptr; typedef _Rb_tree_node<_Tp>* _Link_type; _Rb_tree_iterator() _GLIBCXX_NOEXCEPT : _M_node() { } explicit _Rb_tree_iterator(_Base_ptr __x) _GLIBCXX_NOEXCEPT : _M_node(__x) { } reference operator*() const _GLIBCXX_NOEXCEPT { return *static_cast<_Link_type>(_M_node)->_M_valptr(); } pointer operator->() const _GLIBCXX_NOEXCEPT { return static_cast<_Link_type> (_M_node)->_M_valptr(); } _Self& operator++() _GLIBCXX_NOEXCEPT { _M_node = _Rb_tree_increment(_M_node); return *this; } _Self operator++(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _Rb_tree_increment(_M_node); return __tmp; } _Self& operator--() _GLIBCXX_NOEXCEPT { _M_node = _Rb_tree_decrement(_M_node); return *this; } _Self operator--(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _Rb_tree_decrement(_M_node); return __tmp; } bool operator==(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node == __x._M_node; } bool operator!=(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node != __x._M_node; } _Base_ptr _M_node; }; template struct _Rb_tree_const_iterator { typedef _Tp value_type; typedef const _Tp& reference; typedef const _Tp* pointer; typedef _Rb_tree_iterator<_Tp> iterator; typedef bidirectional_iterator_tag iterator_category; typedef ptrdiff_t difference_type; typedef _Rb_tree_const_iterator<_Tp> _Self; typedef _Rb_tree_node_base::_Const_Base_ptr _Base_ptr; typedef const _Rb_tree_node<_Tp>* _Link_type; _Rb_tree_const_iterator() _GLIBCXX_NOEXCEPT : _M_node() { } explicit _Rb_tree_const_iterator(_Base_ptr __x) _GLIBCXX_NOEXCEPT : _M_node(__x) { } _Rb_tree_const_iterator(const iterator& __it) _GLIBCXX_NOEXCEPT : _M_node(__it._M_node) { } iterator _M_const_cast() const _GLIBCXX_NOEXCEPT { return iterator(const_cast(_M_node)); } reference operator*() const _GLIBCXX_NOEXCEPT { return *static_cast<_Link_type>(_M_node)->_M_valptr(); } pointer operator->() const _GLIBCXX_NOEXCEPT { return static_cast<_Link_type>(_M_node)->_M_valptr(); } _Self& operator++() _GLIBCXX_NOEXCEPT { _M_node = _Rb_tree_increment(_M_node); return *this; } _Self operator++(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _Rb_tree_increment(_M_node); return __tmp; } _Self& operator--() _GLIBCXX_NOEXCEPT { _M_node = _Rb_tree_decrement(_M_node); return *this; } _Self operator--(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _Rb_tree_decrement(_M_node); return __tmp; } bool operator==(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node == __x._M_node; } bool operator!=(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node != __x._M_node; } _Base_ptr _M_node; }; template inline bool operator==(const _Rb_tree_iterator<_Val>& __x, const _Rb_tree_const_iterator<_Val>& __y) _GLIBCXX_NOEXCEPT { return __x._M_node == __y._M_node; } template inline bool operator!=(const _Rb_tree_iterator<_Val>& __x, const _Rb_tree_const_iterator<_Val>& __y) _GLIBCXX_NOEXCEPT { return __x._M_node != __y._M_node; } void _Rb_tree_insert_and_rebalance(const bool __insert_left, _Rb_tree_node_base* __x, _Rb_tree_node_base* __p, _Rb_tree_node_base& __header) throw (); _Rb_tree_node_base* _Rb_tree_rebalance_for_erase(_Rb_tree_node_base* const __z, _Rb_tree_node_base& __header) throw (); #if __cplusplus > 201103L template> struct __has_is_transparent { }; template struct __has_is_transparent<_Cmp, _SfinaeType, __void_t> { typedef void type; }; #endif #if __cplusplus > 201402L template struct _Rb_tree_merge_helper { }; #endif template > class _Rb_tree { typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Rb_tree_node<_Val> >::other _Node_allocator; typedef __gnu_cxx::__alloc_traits<_Node_allocator> _Alloc_traits; protected: typedef _Rb_tree_node_base* _Base_ptr; typedef const _Rb_tree_node_base* _Const_Base_ptr; typedef _Rb_tree_node<_Val>* _Link_type; typedef const _Rb_tree_node<_Val>* _Const_Link_type; private: // Functor recycling a pool of nodes and using allocation once the pool // is empty. struct _Reuse_or_alloc_node { _Reuse_or_alloc_node(_Rb_tree& __t) : _M_root(__t._M_root()), _M_nodes(__t._M_rightmost()), _M_t(__t) { if (_M_root) { _M_root->_M_parent = 0; if (_M_nodes->_M_left) _M_nodes = _M_nodes->_M_left; } else _M_nodes = 0; } #if __cplusplus >= 201103L _Reuse_or_alloc_node(const _Reuse_or_alloc_node&) = delete; #endif ~_Reuse_or_alloc_node() { _M_t._M_erase(static_cast<_Link_type>(_M_root)); } template _Link_type #if __cplusplus < 201103L operator()(const _Arg& __arg) #else operator()(_Arg&& __arg) #endif { _Link_type __node = static_cast<_Link_type>(_M_extract()); if (__node) { _M_t._M_destroy_node(__node); _M_t._M_construct_node(__node, _GLIBCXX_FORWARD(_Arg, __arg)); return __node; } return _M_t._M_create_node(_GLIBCXX_FORWARD(_Arg, __arg)); } private: _Base_ptr _M_extract() { if (!_M_nodes) return _M_nodes; _Base_ptr __node = _M_nodes; _M_nodes = _M_nodes->_M_parent; if (_M_nodes) { if (_M_nodes->_M_right == __node) { _M_nodes->_M_right = 0; if (_M_nodes->_M_left) { _M_nodes = _M_nodes->_M_left; while (_M_nodes->_M_right) _M_nodes = _M_nodes->_M_right; if (_M_nodes->_M_left) _M_nodes = _M_nodes->_M_left; } } else // __node is on the left. _M_nodes->_M_left = 0; } else _M_root = 0; return __node; } _Base_ptr _M_root; _Base_ptr _M_nodes; _Rb_tree& _M_t; }; // Functor similar to the previous one but without any pool of nodes to // recycle. struct _Alloc_node { _Alloc_node(_Rb_tree& __t) : _M_t(__t) { } template _Link_type #if __cplusplus < 201103L operator()(const _Arg& __arg) const #else operator()(_Arg&& __arg) const #endif { return _M_t._M_create_node(_GLIBCXX_FORWARD(_Arg, __arg)); } private: _Rb_tree& _M_t; }; public: typedef _Key key_type; typedef _Val value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Alloc allocator_type; _Node_allocator& _M_get_Node_allocator() _GLIBCXX_NOEXCEPT { return this->_M_impl; } const _Node_allocator& _M_get_Node_allocator() const _GLIBCXX_NOEXCEPT { return this->_M_impl; } allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_get_Node_allocator()); } protected: _Link_type _M_get_node() { return _Alloc_traits::allocate(_M_get_Node_allocator(), 1); } void _M_put_node(_Link_type __p) _GLIBCXX_NOEXCEPT { _Alloc_traits::deallocate(_M_get_Node_allocator(), __p, 1); } #if __cplusplus < 201103L void _M_construct_node(_Link_type __node, const value_type& __x) { __try { get_allocator().construct(__node->_M_valptr(), __x); } __catch(...) { _M_put_node(__node); __throw_exception_again; } } _Link_type _M_create_node(const value_type& __x) { _Link_type __tmp = _M_get_node(); _M_construct_node(__tmp, __x); return __tmp; } void _M_destroy_node(_Link_type __p) { get_allocator().destroy(__p->_M_valptr()); } #else template void _M_construct_node(_Link_type __node, _Args&&... __args) { __try { ::new(__node) _Rb_tree_node<_Val>; _Alloc_traits::construct(_M_get_Node_allocator(), __node->_M_valptr(), std::forward<_Args>(__args)...); } __catch(...) { __node->~_Rb_tree_node<_Val>(); _M_put_node(__node); __throw_exception_again; } } template _Link_type _M_create_node(_Args&&... __args) { _Link_type __tmp = _M_get_node(); _M_construct_node(__tmp, std::forward<_Args>(__args)...); return __tmp; } void _M_destroy_node(_Link_type __p) noexcept { _Alloc_traits::destroy(_M_get_Node_allocator(), __p->_M_valptr()); __p->~_Rb_tree_node<_Val>(); } #endif void _M_drop_node(_Link_type __p) _GLIBCXX_NOEXCEPT { _M_destroy_node(__p); _M_put_node(__p); } template _Link_type _M_clone_node(_Const_Link_type __x, _NodeGen& __node_gen) { _Link_type __tmp = __node_gen(*__x->_M_valptr()); __tmp->_M_color = __x->_M_color; __tmp->_M_left = 0; __tmp->_M_right = 0; return __tmp; } protected: #if _GLIBCXX_INLINE_VERSION template #else // Unused _Is_pod_comparator is kept as it is part of mangled name. template #endif struct _Rb_tree_impl : public _Node_allocator , public _Rb_tree_key_compare<_Key_compare> , public _Rb_tree_header { typedef _Rb_tree_key_compare<_Key_compare> _Base_key_compare; _Rb_tree_impl() _GLIBCXX_NOEXCEPT_IF( is_nothrow_default_constructible<_Node_allocator>::value && is_nothrow_default_constructible<_Base_key_compare>::value ) : _Node_allocator() { } _Rb_tree_impl(const _Rb_tree_impl& __x) : _Node_allocator(_Alloc_traits::_S_select_on_copy(__x)) , _Base_key_compare(__x._M_key_compare) { } #if __cplusplus < 201103L _Rb_tree_impl(const _Key_compare& __comp, const _Node_allocator& __a) : _Node_allocator(__a), _Base_key_compare(__comp) { } #else _Rb_tree_impl(_Rb_tree_impl&&) = default; _Rb_tree_impl(const _Key_compare& __comp, _Node_allocator&& __a) : _Node_allocator(std::move(__a)), _Base_key_compare(__comp) { } #endif }; _Rb_tree_impl<_Compare> _M_impl; protected: _Base_ptr& _M_root() _GLIBCXX_NOEXCEPT { return this->_M_impl._M_header._M_parent; } _Const_Base_ptr _M_root() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_header._M_parent; } _Base_ptr& _M_leftmost() _GLIBCXX_NOEXCEPT { return this->_M_impl._M_header._M_left; } _Const_Base_ptr _M_leftmost() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_header._M_left; } _Base_ptr& _M_rightmost() _GLIBCXX_NOEXCEPT { return this->_M_impl._M_header._M_right; } _Const_Base_ptr _M_rightmost() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_header._M_right; } _Link_type _M_begin() _GLIBCXX_NOEXCEPT { return static_cast<_Link_type>(this->_M_impl._M_header._M_parent); } _Const_Link_type _M_begin() const _GLIBCXX_NOEXCEPT { return static_cast<_Const_Link_type> (this->_M_impl._M_header._M_parent); } _Base_ptr _M_end() _GLIBCXX_NOEXCEPT { return &this->_M_impl._M_header; } _Const_Base_ptr _M_end() const _GLIBCXX_NOEXCEPT { return &this->_M_impl._M_header; } static const_reference _S_value(_Const_Link_type __x) { return *__x->_M_valptr(); } static const _Key& _S_key(_Const_Link_type __x) { #if __cplusplus >= 201103L // If we're asking for the key we're presumably using the comparison // object, and so this is a good place to sanity check it. static_assert(__is_invocable<_Compare&, const _Key&, const _Key&>{}, "comparison object must be invocable " "with two arguments of key type"); # if __cplusplus >= 201703L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2542. Missing const requirements for associative containers if constexpr (__is_invocable<_Compare&, const _Key&, const _Key&>{}) static_assert( is_invocable_v, "comparison object must be invocable as const"); # endif // C++17 #endif // C++11 return _KeyOfValue()(*__x->_M_valptr()); } static _Link_type _S_left(_Base_ptr __x) _GLIBCXX_NOEXCEPT { return static_cast<_Link_type>(__x->_M_left); } static _Const_Link_type _S_left(_Const_Base_ptr __x) _GLIBCXX_NOEXCEPT { return static_cast<_Const_Link_type>(__x->_M_left); } static _Link_type _S_right(_Base_ptr __x) _GLIBCXX_NOEXCEPT { return static_cast<_Link_type>(__x->_M_right); } static _Const_Link_type _S_right(_Const_Base_ptr __x) _GLIBCXX_NOEXCEPT { return static_cast<_Const_Link_type>(__x->_M_right); } static const_reference _S_value(_Const_Base_ptr __x) { return *static_cast<_Const_Link_type>(__x)->_M_valptr(); } static const _Key& _S_key(_Const_Base_ptr __x) { return _S_key(static_cast<_Const_Link_type>(__x)); } static _Base_ptr _S_minimum(_Base_ptr __x) _GLIBCXX_NOEXCEPT { return _Rb_tree_node_base::_S_minimum(__x); } static _Const_Base_ptr _S_minimum(_Const_Base_ptr __x) _GLIBCXX_NOEXCEPT { return _Rb_tree_node_base::_S_minimum(__x); } static _Base_ptr _S_maximum(_Base_ptr __x) _GLIBCXX_NOEXCEPT { return _Rb_tree_node_base::_S_maximum(__x); } static _Const_Base_ptr _S_maximum(_Const_Base_ptr __x) _GLIBCXX_NOEXCEPT { return _Rb_tree_node_base::_S_maximum(__x); } public: typedef _Rb_tree_iterator iterator; typedef _Rb_tree_const_iterator const_iterator; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; #if __cplusplus > 201402L using node_type = _Node_handle<_Key, _Val, _Node_allocator>; using insert_return_type = _Node_insert_return< conditional_t, const_iterator, iterator>, node_type>; #endif pair<_Base_ptr, _Base_ptr> _M_get_insert_unique_pos(const key_type& __k); pair<_Base_ptr, _Base_ptr> _M_get_insert_equal_pos(const key_type& __k); pair<_Base_ptr, _Base_ptr> _M_get_insert_hint_unique_pos(const_iterator __pos, const key_type& __k); pair<_Base_ptr, _Base_ptr> _M_get_insert_hint_equal_pos(const_iterator __pos, const key_type& __k); private: #if __cplusplus >= 201103L template iterator _M_insert_(_Base_ptr __x, _Base_ptr __y, _Arg&& __v, _NodeGen&); iterator _M_insert_node(_Base_ptr __x, _Base_ptr __y, _Link_type __z); template iterator _M_insert_lower(_Base_ptr __y, _Arg&& __v); template iterator _M_insert_equal_lower(_Arg&& __x); iterator _M_insert_lower_node(_Base_ptr __p, _Link_type __z); iterator _M_insert_equal_lower_node(_Link_type __z); #else template iterator _M_insert_(_Base_ptr __x, _Base_ptr __y, const value_type& __v, _NodeGen&); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 233. Insertion hints in associative containers. iterator _M_insert_lower(_Base_ptr __y, const value_type& __v); iterator _M_insert_equal_lower(const value_type& __x); #endif template _Link_type _M_copy(_Const_Link_type __x, _Base_ptr __p, _NodeGen&); template _Link_type _M_copy(const _Rb_tree& __x, _NodeGen& __gen) { _Link_type __root = _M_copy(__x._M_begin(), _M_end(), __gen); _M_leftmost() = _S_minimum(__root); _M_rightmost() = _S_maximum(__root); _M_impl._M_node_count = __x._M_impl._M_node_count; return __root; } _Link_type _M_copy(const _Rb_tree& __x) { _Alloc_node __an(*this); return _M_copy(__x, __an); } void _M_erase(_Link_type __x); iterator _M_lower_bound(_Link_type __x, _Base_ptr __y, const _Key& __k); const_iterator _M_lower_bound(_Const_Link_type __x, _Const_Base_ptr __y, const _Key& __k) const; iterator _M_upper_bound(_Link_type __x, _Base_ptr __y, const _Key& __k); const_iterator _M_upper_bound(_Const_Link_type __x, _Const_Base_ptr __y, const _Key& __k) const; public: // allocation/deallocation #if __cplusplus < 201103L _Rb_tree() { } #else _Rb_tree() = default; #endif _Rb_tree(const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_impl(__comp, _Node_allocator(__a)) { } _Rb_tree(const _Rb_tree& __x) : _M_impl(__x._M_impl) { if (__x._M_root() != 0) _M_root() = _M_copy(__x); } #if __cplusplus >= 201103L _Rb_tree(const allocator_type& __a) : _M_impl(_Compare(), _Node_allocator(__a)) { } _Rb_tree(const _Rb_tree& __x, const allocator_type& __a) : _M_impl(__x._M_impl._M_key_compare, _Node_allocator(__a)) { if (__x._M_root() != nullptr) _M_root() = _M_copy(__x); } _Rb_tree(_Rb_tree&&) = default; _Rb_tree(_Rb_tree&& __x, const allocator_type& __a) : _Rb_tree(std::move(__x), _Node_allocator(__a)) { } _Rb_tree(_Rb_tree&& __x, _Node_allocator&& __a); #endif ~_Rb_tree() _GLIBCXX_NOEXCEPT { _M_erase(_M_begin()); } _Rb_tree& operator=(const _Rb_tree& __x); // Accessors. _Compare key_comp() const { return _M_impl._M_key_compare; } iterator begin() _GLIBCXX_NOEXCEPT { return iterator(this->_M_impl._M_header._M_left); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(this->_M_impl._M_header._M_left); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(&this->_M_impl._M_header); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(&this->_M_impl._M_header); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } bool empty() const _GLIBCXX_NOEXCEPT { return _M_impl._M_node_count == 0; } size_type size() const _GLIBCXX_NOEXCEPT { return _M_impl._M_node_count; } size_type max_size() const _GLIBCXX_NOEXCEPT { return _Alloc_traits::max_size(_M_get_Node_allocator()); } void swap(_Rb_tree& __t) _GLIBCXX_NOEXCEPT_IF(__is_nothrow_swappable<_Compare>::value); // Insert/erase. #if __cplusplus >= 201103L template pair _M_insert_unique(_Arg&& __x); template iterator _M_insert_equal(_Arg&& __x); template iterator _M_insert_unique_(const_iterator __pos, _Arg&& __x, _NodeGen&); template iterator _M_insert_unique_(const_iterator __pos, _Arg&& __x) { _Alloc_node __an(*this); return _M_insert_unique_(__pos, std::forward<_Arg>(__x), __an); } template iterator _M_insert_equal_(const_iterator __pos, _Arg&& __x, _NodeGen&); template iterator _M_insert_equal_(const_iterator __pos, _Arg&& __x) { _Alloc_node __an(*this); return _M_insert_equal_(__pos, std::forward<_Arg>(__x), __an); } template pair _M_emplace_unique(_Args&&... __args); template iterator _M_emplace_equal(_Args&&... __args); template iterator _M_emplace_hint_unique(const_iterator __pos, _Args&&... __args); template iterator _M_emplace_hint_equal(const_iterator __pos, _Args&&... __args); #else pair _M_insert_unique(const value_type& __x); iterator _M_insert_equal(const value_type& __x); template iterator _M_insert_unique_(const_iterator __pos, const value_type& __x, _NodeGen&); iterator _M_insert_unique_(const_iterator __pos, const value_type& __x) { _Alloc_node __an(*this); return _M_insert_unique_(__pos, __x, __an); } template iterator _M_insert_equal_(const_iterator __pos, const value_type& __x, _NodeGen&); iterator _M_insert_equal_(const_iterator __pos, const value_type& __x) { _Alloc_node __an(*this); return _M_insert_equal_(__pos, __x, __an); } #endif template void _M_insert_unique(_InputIterator __first, _InputIterator __last); template void _M_insert_equal(_InputIterator __first, _InputIterator __last); private: void _M_erase_aux(const_iterator __position); void _M_erase_aux(const_iterator __first, const_iterator __last); public: #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. _GLIBCXX_ABI_TAG_CXX11 iterator erase(const_iterator __position) { __glibcxx_assert(__position != end()); const_iterator __result = __position; ++__result; _M_erase_aux(__position); return __result._M_const_cast(); } // LWG 2059. _GLIBCXX_ABI_TAG_CXX11 iterator erase(iterator __position) { __glibcxx_assert(__position != end()); iterator __result = __position; ++__result; _M_erase_aux(__position); return __result; } #else void erase(iterator __position) { __glibcxx_assert(__position != end()); _M_erase_aux(__position); } void erase(const_iterator __position) { __glibcxx_assert(__position != end()); _M_erase_aux(__position); } #endif size_type erase(const key_type& __x); #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. _GLIBCXX_ABI_TAG_CXX11 iterator erase(const_iterator __first, const_iterator __last) { _M_erase_aux(__first, __last); return __last._M_const_cast(); } #else void erase(iterator __first, iterator __last) { _M_erase_aux(__first, __last); } void erase(const_iterator __first, const_iterator __last) { _M_erase_aux(__first, __last); } #endif void erase(const key_type* __first, const key_type* __last); void clear() _GLIBCXX_NOEXCEPT { _M_erase(_M_begin()); _M_impl._M_reset(); } // Set operations. iterator find(const key_type& __k); const_iterator find(const key_type& __k) const; size_type count(const key_type& __k) const; iterator lower_bound(const key_type& __k) { return _M_lower_bound(_M_begin(), _M_end(), __k); } const_iterator lower_bound(const key_type& __k) const { return _M_lower_bound(_M_begin(), _M_end(), __k); } iterator upper_bound(const key_type& __k) { return _M_upper_bound(_M_begin(), _M_end(), __k); } const_iterator upper_bound(const key_type& __k) const { return _M_upper_bound(_M_begin(), _M_end(), __k); } pair equal_range(const key_type& __k); pair equal_range(const key_type& __k) const; #if __cplusplus > 201103L template::type> iterator _M_find_tr(const _Kt& __k) { const _Rb_tree* __const_this = this; return __const_this->_M_find_tr(__k)._M_const_cast(); } template::type> const_iterator _M_find_tr(const _Kt& __k) const { auto __j = _M_lower_bound_tr(__k); if (__j != end() && _M_impl._M_key_compare(__k, _S_key(__j._M_node))) __j = end(); return __j; } template::type> size_type _M_count_tr(const _Kt& __k) const { auto __p = _M_equal_range_tr(__k); return std::distance(__p.first, __p.second); } template::type> iterator _M_lower_bound_tr(const _Kt& __k) { const _Rb_tree* __const_this = this; return __const_this->_M_lower_bound_tr(__k)._M_const_cast(); } template::type> const_iterator _M_lower_bound_tr(const _Kt& __k) const { auto __x = _M_begin(); auto __y = _M_end(); while (__x != 0) if (!_M_impl._M_key_compare(_S_key(__x), __k)) { __y = __x; __x = _S_left(__x); } else __x = _S_right(__x); return const_iterator(__y); } template::type> iterator _M_upper_bound_tr(const _Kt& __k) { const _Rb_tree* __const_this = this; return __const_this->_M_upper_bound_tr(__k)._M_const_cast(); } template::type> const_iterator _M_upper_bound_tr(const _Kt& __k) const { auto __x = _M_begin(); auto __y = _M_end(); while (__x != 0) if (_M_impl._M_key_compare(__k, _S_key(__x))) { __y = __x; __x = _S_left(__x); } else __x = _S_right(__x); return const_iterator(__y); } template::type> pair _M_equal_range_tr(const _Kt& __k) { const _Rb_tree* __const_this = this; auto __ret = __const_this->_M_equal_range_tr(__k); return { __ret.first._M_const_cast(), __ret.second._M_const_cast() }; } template::type> pair _M_equal_range_tr(const _Kt& __k) const { auto __low = _M_lower_bound_tr(__k); auto __high = __low; auto& __cmp = _M_impl._M_key_compare; while (__high != end() && !__cmp(__k, _S_key(__high._M_node))) ++__high; return { __low, __high }; } #endif // Debugging. bool __rb_verify() const; #if __cplusplus >= 201103L _Rb_tree& operator=(_Rb_tree&&) noexcept(_Alloc_traits::_S_nothrow_move() && is_nothrow_move_assignable<_Compare>::value); template void _M_assign_unique(_Iterator, _Iterator); template void _M_assign_equal(_Iterator, _Iterator); private: // Move elements from container with equal allocator. void _M_move_data(_Rb_tree& __x, std::true_type) { _M_impl._M_move_data(__x._M_impl); } // Move elements from container with possibly non-equal allocator, // which might result in a copy not a move. void _M_move_data(_Rb_tree&, std::false_type); // Move assignment from container with equal allocator. void _M_move_assign(_Rb_tree&, std::true_type); // Move assignment from container with possibly non-equal allocator, // which might result in a copy not a move. void _M_move_assign(_Rb_tree&, std::false_type); #endif #if __cplusplus > 201402L public: /// Re-insert an extracted node. insert_return_type _M_reinsert_node_unique(node_type&& __nh) { insert_return_type __ret; if (__nh.empty()) __ret.position = end(); else { __glibcxx_assert(_M_get_Node_allocator() == *__nh._M_alloc); auto __res = _M_get_insert_unique_pos(__nh._M_key()); if (__res.second) { __ret.position = _M_insert_node(__res.first, __res.second, __nh._M_ptr); __nh._M_ptr = nullptr; __ret.inserted = true; } else { __ret.node = std::move(__nh); __ret.position = iterator(__res.first); __ret.inserted = false; } } return __ret; } /// Re-insert an extracted node. iterator _M_reinsert_node_equal(node_type&& __nh) { iterator __ret; if (__nh.empty()) __ret = end(); else { __glibcxx_assert(_M_get_Node_allocator() == *__nh._M_alloc); auto __res = _M_get_insert_equal_pos(__nh._M_key()); if (__res.second) __ret = _M_insert_node(__res.first, __res.second, __nh._M_ptr); else __ret = _M_insert_equal_lower_node(__nh._M_ptr); __nh._M_ptr = nullptr; } return __ret; } /// Re-insert an extracted node. iterator _M_reinsert_node_hint_unique(const_iterator __hint, node_type&& __nh) { iterator __ret; if (__nh.empty()) __ret = end(); else { __glibcxx_assert(_M_get_Node_allocator() == *__nh._M_alloc); auto __res = _M_get_insert_hint_unique_pos(__hint, __nh._M_key()); if (__res.second) { __ret = _M_insert_node(__res.first, __res.second, __nh._M_ptr); __nh._M_ptr = nullptr; } else __ret = iterator(__res.first); } return __ret; } /// Re-insert an extracted node. iterator _M_reinsert_node_hint_equal(const_iterator __hint, node_type&& __nh) { iterator __ret; if (__nh.empty()) __ret = end(); else { __glibcxx_assert(_M_get_Node_allocator() == *__nh._M_alloc); auto __res = _M_get_insert_hint_equal_pos(__hint, __nh._M_key()); if (__res.second) __ret = _M_insert_node(__res.first, __res.second, __nh._M_ptr); else __ret = _M_insert_equal_lower_node(__nh._M_ptr); __nh._M_ptr = nullptr; } return __ret; } /// Extract a node. node_type extract(const_iterator __pos) { auto __ptr = _Rb_tree_rebalance_for_erase( __pos._M_const_cast()._M_node, _M_impl._M_header); --_M_impl._M_node_count; return { static_cast<_Link_type>(__ptr), _M_get_Node_allocator() }; } /// Extract a node. node_type extract(const key_type& __k) { node_type __nh; auto __pos = find(__k); if (__pos != end()) __nh = extract(const_iterator(__pos)); return __nh; } template using _Compatible_tree = _Rb_tree<_Key, _Val, _KeyOfValue, _Compare2, _Alloc>; template friend class _Rb_tree_merge_helper; /// Merge from a compatible container into one with unique keys. template void _M_merge_unique(_Compatible_tree<_Compare2>& __src) noexcept { using _Merge_helper = _Rb_tree_merge_helper<_Rb_tree, _Compare2>; for (auto __i = __src.begin(), __end = __src.end(); __i != __end;) { auto __pos = __i++; auto __res = _M_get_insert_unique_pos(_KeyOfValue()(*__pos)); if (__res.second) { auto& __src_impl = _Merge_helper::_S_get_impl(__src); auto __ptr = _Rb_tree_rebalance_for_erase( __pos._M_node, __src_impl._M_header); --__src_impl._M_node_count; _M_insert_node(__res.first, __res.second, static_cast<_Link_type>(__ptr)); } } } /// Merge from a compatible container into one with equivalent keys. template void _M_merge_equal(_Compatible_tree<_Compare2>& __src) noexcept { using _Merge_helper = _Rb_tree_merge_helper<_Rb_tree, _Compare2>; for (auto __i = __src.begin(), __end = __src.end(); __i != __end;) { auto __pos = __i++; auto __res = _M_get_insert_equal_pos(_KeyOfValue()(*__pos)); if (__res.second) { auto& __src_impl = _Merge_helper::_S_get_impl(__src); auto __ptr = _Rb_tree_rebalance_for_erase( __pos._M_node, __src_impl._M_header); --__src_impl._M_node_count; _M_insert_node(__res.first, __res.second, static_cast<_Link_type>(__ptr)); } } } #endif // C++17 }; template inline bool operator==(const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __x, const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __y) { return __x.size() == __y.size() && std::equal(__x.begin(), __x.end(), __y.begin()); } template inline bool operator<(const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __x, const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __y) { return std::lexicographical_compare(__x.begin(), __x.end(), __y.begin(), __y.end()); } template inline bool operator!=(const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __x, const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __y) { return !(__x == __y); } template inline bool operator>(const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __x, const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __y) { return __y < __x; } template inline bool operator<=(const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __x, const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __y) { return !(__y < __x); } template inline bool operator>=(const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __x, const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __y) { return !(__x < __y); } template inline void swap(_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __x, _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __y) { __x.swap(__y); } #if __cplusplus >= 201103L template _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _Rb_tree(_Rb_tree&& __x, _Node_allocator&& __a) : _M_impl(__x._M_impl._M_key_compare, std::move(__a)) { using __eq = typename _Alloc_traits::is_always_equal; if (__x._M_root() != nullptr) _M_move_data(__x, __eq()); } template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_move_data(_Rb_tree& __x, std::false_type) { if (_M_get_Node_allocator() == __x._M_get_Node_allocator()) _M_move_data(__x, std::true_type()); else { _Alloc_node __an(*this); auto __lbd = [&__an](const value_type& __cval) { auto& __val = const_cast(__cval); return __an(std::move_if_noexcept(__val)); }; _M_root() = _M_copy(__x, __lbd); } } template inline void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_move_assign(_Rb_tree& __x, true_type) { clear(); if (__x._M_root() != nullptr) _M_move_data(__x, std::true_type()); std::__alloc_on_move(_M_get_Node_allocator(), __x._M_get_Node_allocator()); } template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_move_assign(_Rb_tree& __x, false_type) { if (_M_get_Node_allocator() == __x._M_get_Node_allocator()) return _M_move_assign(__x, true_type{}); // Try to move each node reusing existing nodes and copying __x nodes // structure. _Reuse_or_alloc_node __roan(*this); _M_impl._M_reset(); if (__x._M_root() != nullptr) { auto __lbd = [&__roan](const value_type& __cval) { auto& __val = const_cast(__cval); return __roan(std::move_if_noexcept(__val)); }; _M_root() = _M_copy(__x, __lbd); __x.clear(); } } template inline _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: operator=(_Rb_tree&& __x) noexcept(_Alloc_traits::_S_nothrow_move() && is_nothrow_move_assignable<_Compare>::value) { _M_impl._M_key_compare = std::move(__x._M_impl._M_key_compare); _M_move_assign(__x, __bool_constant<_Alloc_traits::_S_nothrow_move()>()); return *this; } template template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_assign_unique(_Iterator __first, _Iterator __last) { _Reuse_or_alloc_node __roan(*this); _M_impl._M_reset(); for (; __first != __last; ++__first) _M_insert_unique_(end(), *__first, __roan); } template template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_assign_equal(_Iterator __first, _Iterator __last) { _Reuse_or_alloc_node __roan(*this); _M_impl._M_reset(); for (; __first != __last; ++__first) _M_insert_equal_(end(), *__first, __roan); } #endif template _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: operator=(const _Rb_tree& __x) { if (this != &__x) { // Note that _Key may be a constant type. #if __cplusplus >= 201103L if (_Alloc_traits::_S_propagate_on_copy_assign()) { auto& __this_alloc = this->_M_get_Node_allocator(); auto& __that_alloc = __x._M_get_Node_allocator(); if (!_Alloc_traits::_S_always_equal() && __this_alloc != __that_alloc) { // Replacement allocator cannot free existing storage, we need // to erase nodes first. clear(); std::__alloc_on_copy(__this_alloc, __that_alloc); } } #endif _Reuse_or_alloc_node __roan(*this); _M_impl._M_reset(); _M_impl._M_key_compare = __x._M_impl._M_key_compare; if (__x._M_root() != 0) _M_root() = _M_copy(__x, __roan); } return *this; } template #if __cplusplus >= 201103L template #else template #endif typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_insert_(_Base_ptr __x, _Base_ptr __p, #if __cplusplus >= 201103L _Arg&& __v, #else const _Val& __v, #endif _NodeGen& __node_gen) { bool __insert_left = (__x != 0 || __p == _M_end() || _M_impl._M_key_compare(_KeyOfValue()(__v), _S_key(__p))); _Link_type __z = __node_gen(_GLIBCXX_FORWARD(_Arg, __v)); _Rb_tree_insert_and_rebalance(__insert_left, __z, __p, this->_M_impl._M_header); ++_M_impl._M_node_count; return iterator(__z); } template #if __cplusplus >= 201103L template #endif typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: #if __cplusplus >= 201103L _M_insert_lower(_Base_ptr __p, _Arg&& __v) #else _M_insert_lower(_Base_ptr __p, const _Val& __v) #endif { bool __insert_left = (__p == _M_end() || !_M_impl._M_key_compare(_S_key(__p), _KeyOfValue()(__v))); _Link_type __z = _M_create_node(_GLIBCXX_FORWARD(_Arg, __v)); _Rb_tree_insert_and_rebalance(__insert_left, __z, __p, this->_M_impl._M_header); ++_M_impl._M_node_count; return iterator(__z); } template #if __cplusplus >= 201103L template #endif typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: #if __cplusplus >= 201103L _M_insert_equal_lower(_Arg&& __v) #else _M_insert_equal_lower(const _Val& __v) #endif { _Link_type __x = _M_begin(); _Base_ptr __y = _M_end(); while (__x != 0) { __y = __x; __x = !_M_impl._M_key_compare(_S_key(__x), _KeyOfValue()(__v)) ? _S_left(__x) : _S_right(__x); } return _M_insert_lower(__y, _GLIBCXX_FORWARD(_Arg, __v)); } template template typename _Rb_tree<_Key, _Val, _KoV, _Compare, _Alloc>::_Link_type _Rb_tree<_Key, _Val, _KoV, _Compare, _Alloc>:: _M_copy(_Const_Link_type __x, _Base_ptr __p, _NodeGen& __node_gen) { // Structural copy. __x and __p must be non-null. _Link_type __top = _M_clone_node(__x, __node_gen); __top->_M_parent = __p; __try { if (__x->_M_right) __top->_M_right = _M_copy(_S_right(__x), __top, __node_gen); __p = __top; __x = _S_left(__x); while (__x != 0) { _Link_type __y = _M_clone_node(__x, __node_gen); __p->_M_left = __y; __y->_M_parent = __p; if (__x->_M_right) __y->_M_right = _M_copy(_S_right(__x), __y, __node_gen); __p = __y; __x = _S_left(__x); } } __catch(...) { _M_erase(__top); __throw_exception_again; } return __top; } template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_erase(_Link_type __x) { // Erase without rebalancing. while (__x != 0) { _M_erase(_S_right(__x)); _Link_type __y = _S_left(__x); _M_drop_node(__x); __x = __y; } } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_lower_bound(_Link_type __x, _Base_ptr __y, const _Key& __k) { while (__x != 0) if (!_M_impl._M_key_compare(_S_key(__x), __k)) __y = __x, __x = _S_left(__x); else __x = _S_right(__x); return iterator(__y); } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_lower_bound(_Const_Link_type __x, _Const_Base_ptr __y, const _Key& __k) const { while (__x != 0) if (!_M_impl._M_key_compare(_S_key(__x), __k)) __y = __x, __x = _S_left(__x); else __x = _S_right(__x); return const_iterator(__y); } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_upper_bound(_Link_type __x, _Base_ptr __y, const _Key& __k) { while (__x != 0) if (_M_impl._M_key_compare(__k, _S_key(__x))) __y = __x, __x = _S_left(__x); else __x = _S_right(__x); return iterator(__y); } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_upper_bound(_Const_Link_type __x, _Const_Base_ptr __y, const _Key& __k) const { while (__x != 0) if (_M_impl._M_key_compare(__k, _S_key(__x))) __y = __x, __x = _S_left(__x); else __x = _S_right(__x); return const_iterator(__y); } template pair::iterator, typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: equal_range(const _Key& __k) { _Link_type __x = _M_begin(); _Base_ptr __y = _M_end(); while (__x != 0) { if (_M_impl._M_key_compare(_S_key(__x), __k)) __x = _S_right(__x); else if (_M_impl._M_key_compare(__k, _S_key(__x))) __y = __x, __x = _S_left(__x); else { _Link_type __xu(__x); _Base_ptr __yu(__y); __y = __x, __x = _S_left(__x); __xu = _S_right(__xu); return pair(_M_lower_bound(__x, __y, __k), _M_upper_bound(__xu, __yu, __k)); } } return pair(iterator(__y), iterator(__y)); } template pair::const_iterator, typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: equal_range(const _Key& __k) const { _Const_Link_type __x = _M_begin(); _Const_Base_ptr __y = _M_end(); while (__x != 0) { if (_M_impl._M_key_compare(_S_key(__x), __k)) __x = _S_right(__x); else if (_M_impl._M_key_compare(__k, _S_key(__x))) __y = __x, __x = _S_left(__x); else { _Const_Link_type __xu(__x); _Const_Base_ptr __yu(__y); __y = __x, __x = _S_left(__x); __xu = _S_right(__xu); return pair(_M_lower_bound(__x, __y, __k), _M_upper_bound(__xu, __yu, __k)); } } return pair(const_iterator(__y), const_iterator(__y)); } template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: swap(_Rb_tree& __t) _GLIBCXX_NOEXCEPT_IF(__is_nothrow_swappable<_Compare>::value) { if (_M_root() == 0) { if (__t._M_root() != 0) _M_impl._M_move_data(__t._M_impl); } else if (__t._M_root() == 0) __t._M_impl._M_move_data(_M_impl); else { std::swap(_M_root(),__t._M_root()); std::swap(_M_leftmost(),__t._M_leftmost()); std::swap(_M_rightmost(),__t._M_rightmost()); _M_root()->_M_parent = _M_end(); __t._M_root()->_M_parent = __t._M_end(); std::swap(this->_M_impl._M_node_count, __t._M_impl._M_node_count); } // No need to swap header's color as it does not change. std::swap(this->_M_impl._M_key_compare, __t._M_impl._M_key_compare); _Alloc_traits::_S_on_swap(_M_get_Node_allocator(), __t._M_get_Node_allocator()); } template pair::_Base_ptr, typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_get_insert_unique_pos(const key_type& __k) { typedef pair<_Base_ptr, _Base_ptr> _Res; _Link_type __x = _M_begin(); _Base_ptr __y = _M_end(); bool __comp = true; while (__x != 0) { __y = __x; __comp = _M_impl._M_key_compare(__k, _S_key(__x)); __x = __comp ? _S_left(__x) : _S_right(__x); } iterator __j = iterator(__y); if (__comp) { if (__j == begin()) return _Res(__x, __y); else --__j; } if (_M_impl._M_key_compare(_S_key(__j._M_node), __k)) return _Res(__x, __y); return _Res(__j._M_node, 0); } template pair::_Base_ptr, typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_get_insert_equal_pos(const key_type& __k) { typedef pair<_Base_ptr, _Base_ptr> _Res; _Link_type __x = _M_begin(); _Base_ptr __y = _M_end(); while (__x != 0) { __y = __x; __x = _M_impl._M_key_compare(__k, _S_key(__x)) ? _S_left(__x) : _S_right(__x); } return _Res(__x, __y); } template #if __cplusplus >= 201103L template #endif pair::iterator, bool> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: #if __cplusplus >= 201103L _M_insert_unique(_Arg&& __v) #else _M_insert_unique(const _Val& __v) #endif { typedef pair _Res; pair<_Base_ptr, _Base_ptr> __res = _M_get_insert_unique_pos(_KeyOfValue()(__v)); if (__res.second) { _Alloc_node __an(*this); return _Res(_M_insert_(__res.first, __res.second, _GLIBCXX_FORWARD(_Arg, __v), __an), true); } return _Res(iterator(__res.first), false); } template #if __cplusplus >= 201103L template #endif typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: #if __cplusplus >= 201103L _M_insert_equal(_Arg&& __v) #else _M_insert_equal(const _Val& __v) #endif { pair<_Base_ptr, _Base_ptr> __res = _M_get_insert_equal_pos(_KeyOfValue()(__v)); _Alloc_node __an(*this); return _M_insert_(__res.first, __res.second, _GLIBCXX_FORWARD(_Arg, __v), __an); } template pair::_Base_ptr, typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_get_insert_hint_unique_pos(const_iterator __position, const key_type& __k) { iterator __pos = __position._M_const_cast(); typedef pair<_Base_ptr, _Base_ptr> _Res; // end() if (__pos._M_node == _M_end()) { if (size() > 0 && _M_impl._M_key_compare(_S_key(_M_rightmost()), __k)) return _Res(0, _M_rightmost()); else return _M_get_insert_unique_pos(__k); } else if (_M_impl._M_key_compare(__k, _S_key(__pos._M_node))) { // First, try before... iterator __before = __pos; if (__pos._M_node == _M_leftmost()) // begin() return _Res(_M_leftmost(), _M_leftmost()); else if (_M_impl._M_key_compare(_S_key((--__before)._M_node), __k)) { if (_S_right(__before._M_node) == 0) return _Res(0, __before._M_node); else return _Res(__pos._M_node, __pos._M_node); } else return _M_get_insert_unique_pos(__k); } else if (_M_impl._M_key_compare(_S_key(__pos._M_node), __k)) { // ... then try after. iterator __after = __pos; if (__pos._M_node == _M_rightmost()) return _Res(0, _M_rightmost()); else if (_M_impl._M_key_compare(__k, _S_key((++__after)._M_node))) { if (_S_right(__pos._M_node) == 0) return _Res(0, __pos._M_node); else return _Res(__after._M_node, __after._M_node); } else return _M_get_insert_unique_pos(__k); } else // Equivalent keys. return _Res(__pos._M_node, 0); } template #if __cplusplus >= 201103L template #else template #endif typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_insert_unique_(const_iterator __position, #if __cplusplus >= 201103L _Arg&& __v, #else const _Val& __v, #endif _NodeGen& __node_gen) { pair<_Base_ptr, _Base_ptr> __res = _M_get_insert_hint_unique_pos(__position, _KeyOfValue()(__v)); if (__res.second) return _M_insert_(__res.first, __res.second, _GLIBCXX_FORWARD(_Arg, __v), __node_gen); return iterator(__res.first); } template pair::_Base_ptr, typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_get_insert_hint_equal_pos(const_iterator __position, const key_type& __k) { iterator __pos = __position._M_const_cast(); typedef pair<_Base_ptr, _Base_ptr> _Res; // end() if (__pos._M_node == _M_end()) { if (size() > 0 && !_M_impl._M_key_compare(__k, _S_key(_M_rightmost()))) return _Res(0, _M_rightmost()); else return _M_get_insert_equal_pos(__k); } else if (!_M_impl._M_key_compare(_S_key(__pos._M_node), __k)) { // First, try before... iterator __before = __pos; if (__pos._M_node == _M_leftmost()) // begin() return _Res(_M_leftmost(), _M_leftmost()); else if (!_M_impl._M_key_compare(__k, _S_key((--__before)._M_node))) { if (_S_right(__before._M_node) == 0) return _Res(0, __before._M_node); else return _Res(__pos._M_node, __pos._M_node); } else return _M_get_insert_equal_pos(__k); } else { // ... then try after. iterator __after = __pos; if (__pos._M_node == _M_rightmost()) return _Res(0, _M_rightmost()); else if (!_M_impl._M_key_compare(_S_key((++__after)._M_node), __k)) { if (_S_right(__pos._M_node) == 0) return _Res(0, __pos._M_node); else return _Res(__after._M_node, __after._M_node); } else return _Res(0, 0); } } template #if __cplusplus >= 201103L template #else template #endif typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_insert_equal_(const_iterator __position, #if __cplusplus >= 201103L _Arg&& __v, #else const _Val& __v, #endif _NodeGen& __node_gen) { pair<_Base_ptr, _Base_ptr> __res = _M_get_insert_hint_equal_pos(__position, _KeyOfValue()(__v)); if (__res.second) return _M_insert_(__res.first, __res.second, _GLIBCXX_FORWARD(_Arg, __v), __node_gen); return _M_insert_equal_lower(_GLIBCXX_FORWARD(_Arg, __v)); } #if __cplusplus >= 201103L template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_insert_node(_Base_ptr __x, _Base_ptr __p, _Link_type __z) { bool __insert_left = (__x != 0 || __p == _M_end() || _M_impl._M_key_compare(_S_key(__z), _S_key(__p))); _Rb_tree_insert_and_rebalance(__insert_left, __z, __p, this->_M_impl._M_header); ++_M_impl._M_node_count; return iterator(__z); } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_insert_lower_node(_Base_ptr __p, _Link_type __z) { bool __insert_left = (__p == _M_end() || !_M_impl._M_key_compare(_S_key(__p), _S_key(__z))); _Rb_tree_insert_and_rebalance(__insert_left, __z, __p, this->_M_impl._M_header); ++_M_impl._M_node_count; return iterator(__z); } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_insert_equal_lower_node(_Link_type __z) { _Link_type __x = _M_begin(); _Base_ptr __y = _M_end(); while (__x != 0) { __y = __x; __x = !_M_impl._M_key_compare(_S_key(__x), _S_key(__z)) ? _S_left(__x) : _S_right(__x); } return _M_insert_lower_node(__y, __z); } template template pair::iterator, bool> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_emplace_unique(_Args&&... __args) { _Link_type __z = _M_create_node(std::forward<_Args>(__args)...); __try { typedef pair _Res; auto __res = _M_get_insert_unique_pos(_S_key(__z)); if (__res.second) return _Res(_M_insert_node(__res.first, __res.second, __z), true); _M_drop_node(__z); return _Res(iterator(__res.first), false); } __catch(...) { _M_drop_node(__z); __throw_exception_again; } } template template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_emplace_equal(_Args&&... __args) { _Link_type __z = _M_create_node(std::forward<_Args>(__args)...); __try { auto __res = _M_get_insert_equal_pos(_S_key(__z)); return _M_insert_node(__res.first, __res.second, __z); } __catch(...) { _M_drop_node(__z); __throw_exception_again; } } template template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_emplace_hint_unique(const_iterator __pos, _Args&&... __args) { _Link_type __z = _M_create_node(std::forward<_Args>(__args)...); __try { auto __res = _M_get_insert_hint_unique_pos(__pos, _S_key(__z)); if (__res.second) return _M_insert_node(__res.first, __res.second, __z); _M_drop_node(__z); return iterator(__res.first); } __catch(...) { _M_drop_node(__z); __throw_exception_again; } } template template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_emplace_hint_equal(const_iterator __pos, _Args&&... __args) { _Link_type __z = _M_create_node(std::forward<_Args>(__args)...); __try { auto __res = _M_get_insert_hint_equal_pos(__pos, _S_key(__z)); if (__res.second) return _M_insert_node(__res.first, __res.second, __z); return _M_insert_equal_lower_node(__z); } __catch(...) { _M_drop_node(__z); __throw_exception_again; } } #endif template template void _Rb_tree<_Key, _Val, _KoV, _Cmp, _Alloc>:: _M_insert_unique(_II __first, _II __last) { _Alloc_node __an(*this); for (; __first != __last; ++__first) _M_insert_unique_(end(), *__first, __an); } template template void _Rb_tree<_Key, _Val, _KoV, _Cmp, _Alloc>:: _M_insert_equal(_II __first, _II __last) { _Alloc_node __an(*this); for (; __first != __last; ++__first) _M_insert_equal_(end(), *__first, __an); } template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_erase_aux(const_iterator __position) { _Link_type __y = static_cast<_Link_type>(_Rb_tree_rebalance_for_erase (const_cast<_Base_ptr>(__position._M_node), this->_M_impl._M_header)); _M_drop_node(__y); --_M_impl._M_node_count; } template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_erase_aux(const_iterator __first, const_iterator __last) { if (__first == begin() && __last == end()) clear(); else while (__first != __last) _M_erase_aux(__first++); } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::size_type _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: erase(const _Key& __x) { pair __p = equal_range(__x); const size_type __old_size = size(); _M_erase_aux(__p.first, __p.second); return __old_size - size(); } template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: erase(const _Key* __first, const _Key* __last) { while (__first != __last) erase(*__first++); } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: find(const _Key& __k) { iterator __j = _M_lower_bound(_M_begin(), _M_end(), __k); return (__j == end() || _M_impl._M_key_compare(__k, _S_key(__j._M_node))) ? end() : __j; } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: find(const _Key& __k) const { const_iterator __j = _M_lower_bound(_M_begin(), _M_end(), __k); return (__j == end() || _M_impl._M_key_compare(__k, _S_key(__j._M_node))) ? end() : __j; } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::size_type _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: count(const _Key& __k) const { pair __p = equal_range(__k); const size_type __n = std::distance(__p.first, __p.second); return __n; } _GLIBCXX_PURE unsigned int _Rb_tree_black_count(const _Rb_tree_node_base* __node, const _Rb_tree_node_base* __root) throw (); template bool _Rb_tree<_Key,_Val,_KeyOfValue,_Compare,_Alloc>::__rb_verify() const { if (_M_impl._M_node_count == 0 || begin() == end()) return _M_impl._M_node_count == 0 && begin() == end() && this->_M_impl._M_header._M_left == _M_end() && this->_M_impl._M_header._M_right == _M_end(); unsigned int __len = _Rb_tree_black_count(_M_leftmost(), _M_root()); for (const_iterator __it = begin(); __it != end(); ++__it) { _Const_Link_type __x = static_cast<_Const_Link_type>(__it._M_node); _Const_Link_type __L = _S_left(__x); _Const_Link_type __R = _S_right(__x); if (__x->_M_color == _S_red) if ((__L && __L->_M_color == _S_red) || (__R && __R->_M_color == _S_red)) return false; if (__L && _M_impl._M_key_compare(_S_key(__x), _S_key(__L))) return false; if (__R && _M_impl._M_key_compare(_S_key(__R), _S_key(__x))) return false; if (!__L && !__R && _Rb_tree_black_count(__x, _M_root()) != __len) return false; } if (_M_leftmost() != _Rb_tree_node_base::_S_minimum(_M_root())) return false; if (_M_rightmost() != _Rb_tree_node_base::_S_maximum(_M_root())) return false; return true; } #if __cplusplus > 201402L // Allow access to internals of compatible _Rb_tree specializations. template struct _Rb_tree_merge_helper<_Rb_tree<_Key, _Val, _Sel, _Cmp1, _Alloc>, _Cmp2> { private: friend class _Rb_tree<_Key, _Val, _Sel, _Cmp1, _Alloc>; static auto& _S_get_impl(_Rb_tree<_Key, _Val, _Sel, _Cmp2, _Alloc>& __tree) { return __tree._M_impl; } }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!X=l=l8/bits/stl_uninitialized.hnu[// Raw memory manipulators -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_uninitialized.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _STL_UNINITIALIZED_H #define _STL_UNINITIALIZED_H 1 #if __cplusplus > 201402L #include #endif #if __cplusplus >= 201103L #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template struct __uninitialized_copy { template static _ForwardIterator __uninit_copy(_InputIterator __first, _InputIterator __last, _ForwardIterator __result) { _ForwardIterator __cur = __result; __try { for (; __first != __last; ++__first, (void)++__cur) std::_Construct(std::__addressof(*__cur), *__first); return __cur; } __catch(...) { std::_Destroy(__result, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_copy { template static _ForwardIterator __uninit_copy(_InputIterator __first, _InputIterator __last, _ForwardIterator __result) { return std::copy(__first, __last, __result); } }; /** * @brief Copies the range [first,last) into result. * @param __first An input iterator. * @param __last An input iterator. * @param __result An output iterator. * @return __result + (__first - __last) * * Like copy(), but does not require an initialized output range. */ template inline _ForwardIterator uninitialized_copy(_InputIterator __first, _InputIterator __last, _ForwardIterator __result) { typedef typename iterator_traits<_InputIterator>::value_type _ValueType1; typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType2; #if __cplusplus < 201103L const bool __assignable = true; #else // trivial types can have deleted assignment typedef typename iterator_traits<_InputIterator>::reference _RefType1; typedef typename iterator_traits<_ForwardIterator>::reference _RefType2; const bool __assignable = is_assignable<_RefType2, _RefType1>::value; #endif return std::__uninitialized_copy<__is_trivial(_ValueType1) && __is_trivial(_ValueType2) && __assignable>:: __uninit_copy(__first, __last, __result); } template struct __uninitialized_fill { template static void __uninit_fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __x) { _ForwardIterator __cur = __first; __try { for (; __cur != __last; ++__cur) std::_Construct(std::__addressof(*__cur), __x); } __catch(...) { std::_Destroy(__first, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_fill { template static void __uninit_fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __x) { std::fill(__first, __last, __x); } }; /** * @brief Copies the value x into the range [first,last). * @param __first An input iterator. * @param __last An input iterator. * @param __x The source value. * @return Nothing. * * Like fill(), but does not require an initialized output range. */ template inline void uninitialized_fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __x) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; #if __cplusplus < 201103L const bool __assignable = true; #else // trivial types can have deleted assignment const bool __assignable = is_copy_assignable<_ValueType>::value; #endif std::__uninitialized_fill<__is_trivial(_ValueType) && __assignable>:: __uninit_fill(__first, __last, __x); } template struct __uninitialized_fill_n { template static _ForwardIterator __uninit_fill_n(_ForwardIterator __first, _Size __n, const _Tp& __x) { _ForwardIterator __cur = __first; __try { for (; __n > 0; --__n, (void) ++__cur) std::_Construct(std::__addressof(*__cur), __x); return __cur; } __catch(...) { std::_Destroy(__first, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_fill_n { template static _ForwardIterator __uninit_fill_n(_ForwardIterator __first, _Size __n, const _Tp& __x) { return std::fill_n(__first, __n, __x); } }; // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 1339. uninitialized_fill_n should return the end of its range /** * @brief Copies the value x into the range [first,first+n). * @param __first An input iterator. * @param __n The number of copies to make. * @param __x The source value. * @return Nothing. * * Like fill_n(), but does not require an initialized output range. */ template inline _ForwardIterator uninitialized_fill_n(_ForwardIterator __first, _Size __n, const _Tp& __x) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; #if __cplusplus < 201103L const bool __assignable = true; #else // trivial types can have deleted assignment const bool __assignable = is_copy_assignable<_ValueType>::value; #endif return __uninitialized_fill_n<__is_trivial(_ValueType) && __assignable>:: __uninit_fill_n(__first, __n, __x); } // Extensions: versions of uninitialized_copy, uninitialized_fill, // and uninitialized_fill_n that take an allocator parameter. // We dispatch back to the standard versions when we're given the // default allocator. For nondefault allocators we do not use // any of the POD optimizations. template _ForwardIterator __uninitialized_copy_a(_InputIterator __first, _InputIterator __last, _ForwardIterator __result, _Allocator& __alloc) { _ForwardIterator __cur = __result; __try { typedef __gnu_cxx::__alloc_traits<_Allocator> __traits; for (; __first != __last; ++__first, (void)++__cur) __traits::construct(__alloc, std::__addressof(*__cur), *__first); return __cur; } __catch(...) { std::_Destroy(__result, __cur, __alloc); __throw_exception_again; } } template inline _ForwardIterator __uninitialized_copy_a(_InputIterator __first, _InputIterator __last, _ForwardIterator __result, allocator<_Tp>&) { return std::uninitialized_copy(__first, __last, __result); } template inline _ForwardIterator __uninitialized_move_a(_InputIterator __first, _InputIterator __last, _ForwardIterator __result, _Allocator& __alloc) { return std::__uninitialized_copy_a(_GLIBCXX_MAKE_MOVE_ITERATOR(__first), _GLIBCXX_MAKE_MOVE_ITERATOR(__last), __result, __alloc); } template inline _ForwardIterator __uninitialized_move_if_noexcept_a(_InputIterator __first, _InputIterator __last, _ForwardIterator __result, _Allocator& __alloc) { return std::__uninitialized_copy_a (_GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(__first), _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(__last), __result, __alloc); } template void __uninitialized_fill_a(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __x, _Allocator& __alloc) { _ForwardIterator __cur = __first; __try { typedef __gnu_cxx::__alloc_traits<_Allocator> __traits; for (; __cur != __last; ++__cur) __traits::construct(__alloc, std::__addressof(*__cur), __x); } __catch(...) { std::_Destroy(__first, __cur, __alloc); __throw_exception_again; } } template inline void __uninitialized_fill_a(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __x, allocator<_Tp2>&) { std::uninitialized_fill(__first, __last, __x); } template _ForwardIterator __uninitialized_fill_n_a(_ForwardIterator __first, _Size __n, const _Tp& __x, _Allocator& __alloc) { _ForwardIterator __cur = __first; __try { typedef __gnu_cxx::__alloc_traits<_Allocator> __traits; for (; __n > 0; --__n, (void) ++__cur) __traits::construct(__alloc, std::__addressof(*__cur), __x); return __cur; } __catch(...) { std::_Destroy(__first, __cur, __alloc); __throw_exception_again; } } template inline _ForwardIterator __uninitialized_fill_n_a(_ForwardIterator __first, _Size __n, const _Tp& __x, allocator<_Tp2>&) { return std::uninitialized_fill_n(__first, __n, __x); } // Extensions: __uninitialized_copy_move, __uninitialized_move_copy, // __uninitialized_fill_move, __uninitialized_move_fill. // All of these algorithms take a user-supplied allocator, which is used // for construction and destruction. // __uninitialized_copy_move // Copies [first1, last1) into [result, result + (last1 - first1)), and // move [first2, last2) into // [result, result + (last1 - first1) + (last2 - first2)). template inline _ForwardIterator __uninitialized_copy_move(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _ForwardIterator __result, _Allocator& __alloc) { _ForwardIterator __mid = std::__uninitialized_copy_a(__first1, __last1, __result, __alloc); __try { return std::__uninitialized_move_a(__first2, __last2, __mid, __alloc); } __catch(...) { std::_Destroy(__result, __mid, __alloc); __throw_exception_again; } } // __uninitialized_move_copy // Moves [first1, last1) into [result, result + (last1 - first1)), and // copies [first2, last2) into // [result, result + (last1 - first1) + (last2 - first2)). template inline _ForwardIterator __uninitialized_move_copy(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _ForwardIterator __result, _Allocator& __alloc) { _ForwardIterator __mid = std::__uninitialized_move_a(__first1, __last1, __result, __alloc); __try { return std::__uninitialized_copy_a(__first2, __last2, __mid, __alloc); } __catch(...) { std::_Destroy(__result, __mid, __alloc); __throw_exception_again; } } // __uninitialized_fill_move // Fills [result, mid) with x, and moves [first, last) into // [mid, mid + (last - first)). template inline _ForwardIterator __uninitialized_fill_move(_ForwardIterator __result, _ForwardIterator __mid, const _Tp& __x, _InputIterator __first, _InputIterator __last, _Allocator& __alloc) { std::__uninitialized_fill_a(__result, __mid, __x, __alloc); __try { return std::__uninitialized_move_a(__first, __last, __mid, __alloc); } __catch(...) { std::_Destroy(__result, __mid, __alloc); __throw_exception_again; } } // __uninitialized_move_fill // Moves [first1, last1) into [first2, first2 + (last1 - first1)), and // fills [first2 + (last1 - first1), last2) with x. template inline void __uninitialized_move_fill(_InputIterator __first1, _InputIterator __last1, _ForwardIterator __first2, _ForwardIterator __last2, const _Tp& __x, _Allocator& __alloc) { _ForwardIterator __mid2 = std::__uninitialized_move_a(__first1, __last1, __first2, __alloc); __try { std::__uninitialized_fill_a(__mid2, __last2, __x, __alloc); } __catch(...) { std::_Destroy(__first2, __mid2, __alloc); __throw_exception_again; } } #if __cplusplus >= 201103L // Extensions: __uninitialized_default, __uninitialized_default_n, // __uninitialized_default_a, __uninitialized_default_n_a. template struct __uninitialized_default_1 { template static void __uninit_default(_ForwardIterator __first, _ForwardIterator __last) { _ForwardIterator __cur = __first; __try { for (; __cur != __last; ++__cur) std::_Construct(std::__addressof(*__cur)); } __catch(...) { std::_Destroy(__first, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_default_1 { template static void __uninit_default(_ForwardIterator __first, _ForwardIterator __last) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; std::fill(__first, __last, _ValueType()); } }; template struct __uninitialized_default_n_1 { template static _ForwardIterator __uninit_default_n(_ForwardIterator __first, _Size __n) { _ForwardIterator __cur = __first; __try { for (; __n > 0; --__n, (void) ++__cur) std::_Construct(std::__addressof(*__cur)); return __cur; } __catch(...) { std::_Destroy(__first, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_default_n_1 { template static _ForwardIterator __uninit_default_n(_ForwardIterator __first, _Size __n) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; return std::fill_n(__first, __n, _ValueType()); } }; // __uninitialized_default // Fills [first, last) with std::distance(first, last) default // constructed value_types(s). template inline void __uninitialized_default(_ForwardIterator __first, _ForwardIterator __last) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; // trivial types can have deleted assignment const bool __assignable = is_copy_assignable<_ValueType>::value; std::__uninitialized_default_1<__is_trivial(_ValueType) && __assignable>:: __uninit_default(__first, __last); } // __uninitialized_default_n // Fills [first, first + n) with n default constructed value_type(s). template inline _ForwardIterator __uninitialized_default_n(_ForwardIterator __first, _Size __n) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; // trivial types can have deleted assignment const bool __assignable = is_copy_assignable<_ValueType>::value; return __uninitialized_default_n_1<__is_trivial(_ValueType) && __assignable>:: __uninit_default_n(__first, __n); } // __uninitialized_default_a // Fills [first, last) with std::distance(first, last) default // constructed value_types(s), constructed with the allocator alloc. template void __uninitialized_default_a(_ForwardIterator __first, _ForwardIterator __last, _Allocator& __alloc) { _ForwardIterator __cur = __first; __try { typedef __gnu_cxx::__alloc_traits<_Allocator> __traits; for (; __cur != __last; ++__cur) __traits::construct(__alloc, std::__addressof(*__cur)); } __catch(...) { std::_Destroy(__first, __cur, __alloc); __throw_exception_again; } } template inline void __uninitialized_default_a(_ForwardIterator __first, _ForwardIterator __last, allocator<_Tp>&) { std::__uninitialized_default(__first, __last); } // __uninitialized_default_n_a // Fills [first, first + n) with n default constructed value_types(s), // constructed with the allocator alloc. template _ForwardIterator __uninitialized_default_n_a(_ForwardIterator __first, _Size __n, _Allocator& __alloc) { _ForwardIterator __cur = __first; __try { typedef __gnu_cxx::__alloc_traits<_Allocator> __traits; for (; __n > 0; --__n, (void) ++__cur) __traits::construct(__alloc, std::__addressof(*__cur)); return __cur; } __catch(...) { std::_Destroy(__first, __cur, __alloc); __throw_exception_again; } } template inline _ForwardIterator __uninitialized_default_n_a(_ForwardIterator __first, _Size __n, allocator<_Tp>&) { return std::__uninitialized_default_n(__first, __n); } template struct __uninitialized_default_novalue_1 { template static void __uninit_default_novalue(_ForwardIterator __first, _ForwardIterator __last) { _ForwardIterator __cur = __first; __try { for (; __cur != __last; ++__cur) std::_Construct_novalue(std::__addressof(*__cur)); } __catch(...) { std::_Destroy(__first, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_default_novalue_1 { template static void __uninit_default_novalue(_ForwardIterator __first, _ForwardIterator __last) { } }; template struct __uninitialized_default_novalue_n_1 { template static _ForwardIterator __uninit_default_novalue_n(_ForwardIterator __first, _Size __n) { _ForwardIterator __cur = __first; __try { for (; __n > 0; --__n, (void) ++__cur) std::_Construct_novalue(std::__addressof(*__cur)); return __cur; } __catch(...) { std::_Destroy(__first, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_default_novalue_n_1 { template static _ForwardIterator __uninit_default_novalue_n(_ForwardIterator __first, _Size __n) { return std::next(__first, __n); } }; // __uninitialized_default_novalue // Fills [first, last) with std::distance(first, last) default-initialized // value_types(s). template inline void __uninitialized_default_novalue(_ForwardIterator __first, _ForwardIterator __last) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; std::__uninitialized_default_novalue_1< is_trivially_default_constructible<_ValueType>::value>:: __uninit_default_novalue(__first, __last); } // __uninitialized_default_n // Fills [first, first + n) with n default-initialized value_type(s). template inline _ForwardIterator __uninitialized_default_novalue_n(_ForwardIterator __first, _Size __n) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; return __uninitialized_default_novalue_n_1< is_trivially_default_constructible<_ValueType>::value>:: __uninit_default_novalue_n(__first, __n); } template _ForwardIterator __uninitialized_copy_n(_InputIterator __first, _Size __n, _ForwardIterator __result, input_iterator_tag) { _ForwardIterator __cur = __result; __try { for (; __n > 0; --__n, (void) ++__first, ++__cur) std::_Construct(std::__addressof(*__cur), *__first); return __cur; } __catch(...) { std::_Destroy(__result, __cur); __throw_exception_again; } } template inline _ForwardIterator __uninitialized_copy_n(_RandomAccessIterator __first, _Size __n, _ForwardIterator __result, random_access_iterator_tag) { return std::uninitialized_copy(__first, __first + __n, __result); } template pair<_InputIterator, _ForwardIterator> __uninitialized_copy_n_pair(_InputIterator __first, _Size __n, _ForwardIterator __result, input_iterator_tag) { _ForwardIterator __cur = __result; __try { for (; __n > 0; --__n, (void) ++__first, ++__cur) std::_Construct(std::__addressof(*__cur), *__first); return {__first, __cur}; } __catch(...) { std::_Destroy(__result, __cur); __throw_exception_again; } } template inline pair<_RandomAccessIterator, _ForwardIterator> __uninitialized_copy_n_pair(_RandomAccessIterator __first, _Size __n, _ForwardIterator __result, random_access_iterator_tag) { auto __second_res = uninitialized_copy(__first, __first + __n, __result); auto __first_res = std::next(__first, __n); return {__first_res, __second_res}; } /** * @brief Copies the range [first,first+n) into result. * @param __first An input iterator. * @param __n The number of elements to copy. * @param __result An output iterator. * @return __result + __n * * Like copy_n(), but does not require an initialized output range. */ template inline _ForwardIterator uninitialized_copy_n(_InputIterator __first, _Size __n, _ForwardIterator __result) { return std::__uninitialized_copy_n(__first, __n, __result, std::__iterator_category(__first)); } template inline pair<_InputIterator, _ForwardIterator> __uninitialized_copy_n_pair(_InputIterator __first, _Size __n, _ForwardIterator __result) { return std::__uninitialized_copy_n_pair(__first, __n, __result, std::__iterator_category(__first)); } #endif #if __cplusplus >= 201703L # define __cpp_lib_raw_memory_algorithms 201606L template inline void uninitialized_default_construct(_ForwardIterator __first, _ForwardIterator __last) { __uninitialized_default_novalue(__first, __last); } template inline _ForwardIterator uninitialized_default_construct_n(_ForwardIterator __first, _Size __count) { return __uninitialized_default_novalue_n(__first, __count); } template inline void uninitialized_value_construct(_ForwardIterator __first, _ForwardIterator __last) { return __uninitialized_default(__first, __last); } template inline _ForwardIterator uninitialized_value_construct_n(_ForwardIterator __first, _Size __count) { return __uninitialized_default_n(__first, __count); } template inline _ForwardIterator uninitialized_move(_InputIterator __first, _InputIterator __last, _ForwardIterator __result) { return std::uninitialized_copy (_GLIBCXX_MAKE_MOVE_ITERATOR(__first), _GLIBCXX_MAKE_MOVE_ITERATOR(__last), __result); } template inline pair<_InputIterator, _ForwardIterator> uninitialized_move_n(_InputIterator __first, _Size __count, _ForwardIterator __result) { auto __res = std::__uninitialized_copy_n_pair (_GLIBCXX_MAKE_MOVE_ITERATOR(__first), __count, __result); return {__res.first.base(), __res.second}; } #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _STL_UNINITIALIZED_H */ PK!:qtvv8/bits/stl_vector.hnu[// Vector implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_vector.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{vector} */ #ifndef _STL_VECTOR_H #define _STL_VECTOR_H 1 #include #include #include #if __cplusplus >= 201103L #include #endif #include #if _GLIBCXX_SANITIZE_STD_ALLOCATOR && _GLIBCXX_SANITIZE_VECTOR extern "C" void __sanitizer_annotate_contiguous_container(const void*, const void*, const void*, const void*); #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER /// See bits/stl_deque.h's _Deque_base for an explanation. template struct _Vector_base { typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Tp>::other _Tp_alloc_type; typedef typename __gnu_cxx::__alloc_traits<_Tp_alloc_type>::pointer pointer; struct _Vector_impl : public _Tp_alloc_type { pointer _M_start; pointer _M_finish; pointer _M_end_of_storage; _Vector_impl() : _Tp_alloc_type(), _M_start(), _M_finish(), _M_end_of_storage() { } _Vector_impl(_Tp_alloc_type const& __a) _GLIBCXX_NOEXCEPT : _Tp_alloc_type(__a), _M_start(), _M_finish(), _M_end_of_storage() { } #if __cplusplus >= 201103L _Vector_impl(_Tp_alloc_type&& __a) noexcept : _Tp_alloc_type(std::move(__a)), _M_start(), _M_finish(), _M_end_of_storage() { } #endif void _M_swap_data(_Vector_impl& __x) _GLIBCXX_NOEXCEPT { std::swap(_M_start, __x._M_start); std::swap(_M_finish, __x._M_finish); std::swap(_M_end_of_storage, __x._M_end_of_storage); } #if _GLIBCXX_SANITIZE_STD_ALLOCATOR && _GLIBCXX_SANITIZE_VECTOR template struct _Asan { typedef typename __gnu_cxx::__alloc_traits<_Tp_alloc_type> ::size_type size_type; static void _S_shrink(_Vector_impl&, size_type) { } static void _S_on_dealloc(_Vector_impl&) { } typedef _Vector_impl& _Reinit; struct _Grow { _Grow(_Vector_impl&, size_type) { } void _M_grew(size_type) { } }; }; // Enable ASan annotations for memory obtained from std::allocator. template struct _Asan > { typedef typename __gnu_cxx::__alloc_traits<_Tp_alloc_type> ::size_type size_type; // Adjust ASan annotation for [_M_start, _M_end_of_storage) to // mark end of valid region as __curr instead of __prev. static void _S_adjust(_Vector_impl& __impl, pointer __prev, pointer __curr) { __sanitizer_annotate_contiguous_container(__impl._M_start, __impl._M_end_of_storage, __prev, __curr); } static void _S_grow(_Vector_impl& __impl, size_type __n) { _S_adjust(__impl, __impl._M_finish, __impl._M_finish + __n); } static void _S_shrink(_Vector_impl& __impl, size_type __n) { _S_adjust(__impl, __impl._M_finish + __n, __impl._M_finish); } static void _S_on_dealloc(_Vector_impl& __impl) { if (__impl._M_start) _S_adjust(__impl, __impl._M_finish, __impl._M_end_of_storage); } // Used on reallocation to tell ASan unused capacity is invalid. struct _Reinit { explicit _Reinit(_Vector_impl& __impl) : _M_impl(__impl) { // Mark unused capacity as valid again before deallocating it. _S_on_dealloc(_M_impl); } ~_Reinit() { // Mark unused capacity as invalid after reallocation. if (_M_impl._M_start) _S_adjust(_M_impl, _M_impl._M_end_of_storage, _M_impl._M_finish); } _Vector_impl& _M_impl; #if __cplusplus >= 201103L _Reinit(const _Reinit&) = delete; _Reinit& operator=(const _Reinit&) = delete; #endif }; // Tell ASan when unused capacity is initialized to be valid. struct _Grow { _Grow(_Vector_impl& __impl, size_type __n) : _M_impl(__impl), _M_n(__n) { _S_grow(_M_impl, __n); } ~_Grow() { if (_M_n) _S_shrink(_M_impl, _M_n); } void _M_grew(size_type __n) { _M_n -= __n; } #if __cplusplus >= 201103L _Grow(const _Grow&) = delete; _Grow& operator=(const _Grow&) = delete; #endif private: _Vector_impl& _M_impl; size_type _M_n; }; }; #define _GLIBCXX_ASAN_ANNOTATE_REINIT \ typename _Base::_Vector_impl::template _Asan<>::_Reinit const \ __attribute__((__unused__)) __reinit_guard(this->_M_impl) #define _GLIBCXX_ASAN_ANNOTATE_GROW(n) \ typename _Base::_Vector_impl::template _Asan<>::_Grow \ __attribute__((__unused__)) __grow_guard(this->_M_impl, (n)) #define _GLIBCXX_ASAN_ANNOTATE_GREW(n) __grow_guard._M_grew(n) #define _GLIBCXX_ASAN_ANNOTATE_SHRINK(n) \ _Base::_Vector_impl::template _Asan<>::_S_shrink(this->_M_impl, n) #define _GLIBCXX_ASAN_ANNOTATE_BEFORE_DEALLOC \ _Base::_Vector_impl::template _Asan<>::_S_on_dealloc(this->_M_impl) #else // ! (_GLIBCXX_SANITIZE_STD_ALLOCATOR && _GLIBCXX_SANITIZE_VECTOR) #define _GLIBCXX_ASAN_ANNOTATE_REINIT #define _GLIBCXX_ASAN_ANNOTATE_GROW(n) #define _GLIBCXX_ASAN_ANNOTATE_GREW(n) #define _GLIBCXX_ASAN_ANNOTATE_SHRINK(n) #define _GLIBCXX_ASAN_ANNOTATE_BEFORE_DEALLOC #endif // _GLIBCXX_SANITIZE_STD_ALLOCATOR && _GLIBCXX_SANITIZE_VECTOR }; public: typedef _Alloc allocator_type; _Tp_alloc_type& _M_get_Tp_allocator() _GLIBCXX_NOEXCEPT { return *static_cast<_Tp_alloc_type*>(&this->_M_impl); } const _Tp_alloc_type& _M_get_Tp_allocator() const _GLIBCXX_NOEXCEPT { return *static_cast(&this->_M_impl); } allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_get_Tp_allocator()); } _Vector_base() : _M_impl() { } _Vector_base(const allocator_type& __a) _GLIBCXX_NOEXCEPT : _M_impl(__a) { } _Vector_base(size_t __n) : _M_impl() { _M_create_storage(__n); } _Vector_base(size_t __n, const allocator_type& __a) : _M_impl(__a) { _M_create_storage(__n); } #if __cplusplus >= 201103L _Vector_base(_Tp_alloc_type&& __a) noexcept : _M_impl(std::move(__a)) { } _Vector_base(_Vector_base&& __x) noexcept : _M_impl(std::move(__x._M_get_Tp_allocator())) { this->_M_impl._M_swap_data(__x._M_impl); } _Vector_base(_Vector_base&& __x, const allocator_type& __a) : _M_impl(__a) { if (__x.get_allocator() == __a) this->_M_impl._M_swap_data(__x._M_impl); else { size_t __n = __x._M_impl._M_finish - __x._M_impl._M_start; _M_create_storage(__n); } } #endif ~_Vector_base() _GLIBCXX_NOEXCEPT { _M_deallocate(_M_impl._M_start, _M_impl._M_end_of_storage - _M_impl._M_start); } public: _Vector_impl _M_impl; pointer _M_allocate(size_t __n) { typedef __gnu_cxx::__alloc_traits<_Tp_alloc_type> _Tr; return __n != 0 ? _Tr::allocate(_M_impl, __n) : pointer(); } void _M_deallocate(pointer __p, size_t __n) { typedef __gnu_cxx::__alloc_traits<_Tp_alloc_type> _Tr; if (__p) _Tr::deallocate(_M_impl, __p, __n); } private: void _M_create_storage(size_t __n) { this->_M_impl._M_start = this->_M_allocate(__n); this->_M_impl._M_finish = this->_M_impl._M_start; this->_M_impl._M_end_of_storage = this->_M_impl._M_start + __n; } }; /** * @brief A standard container which offers fixed time access to * individual elements in any order. * * @ingroup sequences * * @tparam _Tp Type of element. * @tparam _Alloc Allocator type, defaults to allocator<_Tp>. * * Meets the requirements of a container, a * reversible container, and a * sequence, including the * optional sequence requirements with the * %exception of @c push_front and @c pop_front. * * In some terminology a %vector can be described as a dynamic * C-style array, it offers fast and efficient access to individual * elements in any order and saves the user from worrying about * memory and size allocation. Subscripting ( @c [] ) access is * also provided as with C-style arrays. */ template > class vector : protected _Vector_base<_Tp, _Alloc> { #ifdef _GLIBCXX_CONCEPT_CHECKS // Concept requirements. typedef typename _Alloc::value_type _Alloc_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) # endif __glibcxx_class_requires2(_Tp, _Alloc_value_type, _SameTypeConcept) #endif #if __cplusplus >= 201103L static_assert(is_same::type, _Tp>::value, "std::vector must have a non-const, non-volatile value_type"); # ifdef __STRICT_ANSI__ static_assert(is_same::value, "std::vector must have the same value_type as its allocator"); # endif #endif typedef _Vector_base<_Tp, _Alloc> _Base; typedef typename _Base::_Tp_alloc_type _Tp_alloc_type; typedef __gnu_cxx::__alloc_traits<_Tp_alloc_type> _Alloc_traits; public: typedef _Tp value_type; typedef typename _Base::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef typename _Alloc_traits::reference reference; typedef typename _Alloc_traits::const_reference const_reference; typedef __gnu_cxx::__normal_iterator iterator; typedef __gnu_cxx::__normal_iterator const_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Alloc allocator_type; protected: using _Base::_M_allocate; using _Base::_M_deallocate; using _Base::_M_impl; using _Base::_M_get_Tp_allocator; public: // [23.2.4.1] construct/copy/destroy // (assign() and get_allocator() are also listed in this section) /** * @brief Creates a %vector with no elements. */ vector() #if __cplusplus >= 201103L noexcept(is_nothrow_default_constructible<_Alloc>::value) #endif : _Base() { } /** * @brief Creates a %vector with no elements. * @param __a An allocator object. */ explicit vector(const allocator_type& __a) _GLIBCXX_NOEXCEPT : _Base(__a) { } #if __cplusplus >= 201103L /** * @brief Creates a %vector with default constructed elements. * @param __n The number of elements to initially create. * @param __a An allocator. * * This constructor fills the %vector with @a __n default * constructed elements. */ explicit vector(size_type __n, const allocator_type& __a = allocator_type()) : _Base(__n, __a) { _M_default_initialize(__n); } /** * @brief Creates a %vector with copies of an exemplar element. * @param __n The number of elements to initially create. * @param __value An element to copy. * @param __a An allocator. * * This constructor fills the %vector with @a __n copies of @a __value. */ vector(size_type __n, const value_type& __value, const allocator_type& __a = allocator_type()) : _Base(__n, __a) { _M_fill_initialize(__n, __value); } #else /** * @brief Creates a %vector with copies of an exemplar element. * @param __n The number of elements to initially create. * @param __value An element to copy. * @param __a An allocator. * * This constructor fills the %vector with @a __n copies of @a __value. */ explicit vector(size_type __n, const value_type& __value = value_type(), const allocator_type& __a = allocator_type()) : _Base(__n, __a) { _M_fill_initialize(__n, __value); } #endif /** * @brief %Vector copy constructor. * @param __x A %vector of identical element and allocator types. * * All the elements of @a __x are copied, but any unused capacity in * @a __x will not be copied * (i.e. capacity() == size() in the new %vector). * * The newly-created %vector uses a copy of the allocator object used * by @a __x (unless the allocator traits dictate a different object). */ vector(const vector& __x) : _Base(__x.size(), _Alloc_traits::_S_select_on_copy(__x._M_get_Tp_allocator())) { this->_M_impl._M_finish = std::__uninitialized_copy_a(__x.begin(), __x.end(), this->_M_impl._M_start, _M_get_Tp_allocator()); } #if __cplusplus >= 201103L /** * @brief %Vector move constructor. * @param __x A %vector of identical element and allocator types. * * The newly-created %vector contains the exact contents of @a __x. * The contents of @a __x are a valid, but unspecified %vector. */ vector(vector&& __x) noexcept : _Base(std::move(__x)) { } /// Copy constructor with alternative allocator vector(const vector& __x, const allocator_type& __a) : _Base(__x.size(), __a) { this->_M_impl._M_finish = std::__uninitialized_copy_a(__x.begin(), __x.end(), this->_M_impl._M_start, _M_get_Tp_allocator()); } /// Move constructor with alternative allocator vector(vector&& __rv, const allocator_type& __m) noexcept(_Alloc_traits::_S_always_equal()) : _Base(std::move(__rv), __m) { if (__rv.get_allocator() != __m) { this->_M_impl._M_finish = std::__uninitialized_move_a(__rv.begin(), __rv.end(), this->_M_impl._M_start, _M_get_Tp_allocator()); __rv.clear(); } } /** * @brief Builds a %vector from an initializer list. * @param __l An initializer_list. * @param __a An allocator. * * Create a %vector consisting of copies of the elements in the * initializer_list @a __l. * * This will call the element type's copy constructor N times * (where N is @a __l.size()) and do no memory reallocation. */ vector(initializer_list __l, const allocator_type& __a = allocator_type()) : _Base(__a) { _M_range_initialize(__l.begin(), __l.end(), random_access_iterator_tag()); } #endif /** * @brief Builds a %vector from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __a An allocator. * * Create a %vector consisting of copies of the elements from * [first,last). * * If the iterators are forward, bidirectional, or * random-access, then this will call the elements' copy * constructor N times (where N is distance(first,last)) and do * no memory reallocation. But if only input iterators are * used, then this will do at most 2N calls to the copy * constructor, and logN memory reallocations. */ #if __cplusplus >= 201103L template> vector(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(__a) { _M_initialize_dispatch(__first, __last, __false_type()); } #else template vector(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(__a) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_initialize_dispatch(__first, __last, _Integral()); } #endif /** * The dtor only erases the elements, and note that if the * elements themselves are pointers, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibility. */ ~vector() _GLIBCXX_NOEXCEPT { std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish, _M_get_Tp_allocator()); _GLIBCXX_ASAN_ANNOTATE_BEFORE_DEALLOC; } /** * @brief %Vector assignment operator. * @param __x A %vector of identical element and allocator types. * * All the elements of @a __x are copied, but any unused capacity in * @a __x will not be copied. * * Whether the allocator is copied depends on the allocator traits. */ vector& operator=(const vector& __x); #if __cplusplus >= 201103L /** * @brief %Vector move assignment operator. * @param __x A %vector of identical element and allocator types. * * The contents of @a __x are moved into this %vector (without copying, * if the allocators permit it). * Afterwards @a __x is a valid, but unspecified %vector. * * Whether the allocator is moved depends on the allocator traits. */ vector& operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move()) { constexpr bool __move_storage = _Alloc_traits::_S_propagate_on_move_assign() || _Alloc_traits::_S_always_equal(); _M_move_assign(std::move(__x), __bool_constant<__move_storage>()); return *this; } /** * @brief %Vector list assignment operator. * @param __l An initializer_list. * * This function fills a %vector with copies of the elements in the * initializer list @a __l. * * Note that the assignment completely changes the %vector and * that the resulting %vector's size is the same as the number * of elements assigned. */ vector& operator=(initializer_list __l) { this->_M_assign_aux(__l.begin(), __l.end(), random_access_iterator_tag()); return *this; } #endif /** * @brief Assigns a given value to a %vector. * @param __n Number of elements to be assigned. * @param __val Value to be assigned. * * This function fills a %vector with @a __n copies of the given * value. Note that the assignment completely changes the * %vector and that the resulting %vector's size is the same as * the number of elements assigned. */ void assign(size_type __n, const value_type& __val) { _M_fill_assign(__n, __val); } /** * @brief Assigns a range to a %vector. * @param __first An input iterator. * @param __last An input iterator. * * This function fills a %vector with copies of the elements in the * range [__first,__last). * * Note that the assignment completely changes the %vector and * that the resulting %vector's size is the same as the number * of elements assigned. */ #if __cplusplus >= 201103L template> void assign(_InputIterator __first, _InputIterator __last) { _M_assign_dispatch(__first, __last, __false_type()); } #else template void assign(_InputIterator __first, _InputIterator __last) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_assign_dispatch(__first, __last, _Integral()); } #endif #if __cplusplus >= 201103L /** * @brief Assigns an initializer list to a %vector. * @param __l An initializer_list. * * This function fills a %vector with copies of the elements in the * initializer list @a __l. * * Note that the assignment completely changes the %vector and * that the resulting %vector's size is the same as the number * of elements assigned. */ void assign(initializer_list __l) { this->_M_assign_aux(__l.begin(), __l.end(), random_access_iterator_tag()); } #endif /// Get a copy of the memory allocation object. using _Base::get_allocator; // iterators /** * Returns a read/write iterator that points to the first * element in the %vector. Iteration is done in ordinary * element order. */ iterator begin() _GLIBCXX_NOEXCEPT { return iterator(this->_M_impl._M_start); } /** * Returns a read-only (constant) iterator that points to the * first element in the %vector. Iteration is done in ordinary * element order. */ const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(this->_M_impl._M_start); } /** * Returns a read/write iterator that points one past the last * element in the %vector. Iteration is done in ordinary * element order. */ iterator end() _GLIBCXX_NOEXCEPT { return iterator(this->_M_impl._M_finish); } /** * Returns a read-only (constant) iterator that points one past * the last element in the %vector. Iteration is done in * ordinary element order. */ const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(this->_M_impl._M_finish); } /** * Returns a read/write reverse iterator that points to the * last element in the %vector. Iteration is done in reverse * element order. */ reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } /** * Returns a read-only (constant) reverse iterator that points * to the last element in the %vector. Iteration is done in * reverse element order. */ const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } /** * Returns a read/write reverse iterator that points to one * before the first element in the %vector. Iteration is done * in reverse element order. */ reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first element in the %vector. Iteration * is done in reverse element order. */ const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the * first element in the %vector. Iteration is done in ordinary * element order. */ const_iterator cbegin() const noexcept { return const_iterator(this->_M_impl._M_start); } /** * Returns a read-only (constant) iterator that points one past * the last element in the %vector. Iteration is done in * ordinary element order. */ const_iterator cend() const noexcept { return const_iterator(this->_M_impl._M_finish); } /** * Returns a read-only (constant) reverse iterator that points * to the last element in the %vector. Iteration is done in * reverse element order. */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first element in the %vector. Iteration * is done in reverse element order. */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // [23.2.4.2] capacity /** Returns the number of elements in the %vector. */ size_type size() const _GLIBCXX_NOEXCEPT { return size_type(this->_M_impl._M_finish - this->_M_impl._M_start); } /** Returns the size() of the largest possible %vector. */ size_type max_size() const _GLIBCXX_NOEXCEPT { return _Alloc_traits::max_size(_M_get_Tp_allocator()); } #if __cplusplus >= 201103L /** * @brief Resizes the %vector to the specified number of elements. * @param __new_size Number of elements the %vector should contain. * * This function will %resize the %vector to the specified * number of elements. If the number is smaller than the * %vector's current size the %vector is truncated, otherwise * default constructed elements are appended. */ void resize(size_type __new_size) { if (__new_size > size()) _M_default_append(__new_size - size()); else if (__new_size < size()) _M_erase_at_end(this->_M_impl._M_start + __new_size); } /** * @brief Resizes the %vector to the specified number of elements. * @param __new_size Number of elements the %vector should contain. * @param __x Data with which new elements should be populated. * * This function will %resize the %vector to the specified * number of elements. If the number is smaller than the * %vector's current size the %vector is truncated, otherwise * the %vector is extended and new elements are populated with * given data. */ void resize(size_type __new_size, const value_type& __x) { if (__new_size > size()) _M_fill_insert(end(), __new_size - size(), __x); else if (__new_size < size()) _M_erase_at_end(this->_M_impl._M_start + __new_size); } #else /** * @brief Resizes the %vector to the specified number of elements. * @param __new_size Number of elements the %vector should contain. * @param __x Data with which new elements should be populated. * * This function will %resize the %vector to the specified * number of elements. If the number is smaller than the * %vector's current size the %vector is truncated, otherwise * the %vector is extended and new elements are populated with * given data. */ void resize(size_type __new_size, value_type __x = value_type()) { if (__new_size > size()) _M_fill_insert(end(), __new_size - size(), __x); else if (__new_size < size()) _M_erase_at_end(this->_M_impl._M_start + __new_size); } #endif #if __cplusplus >= 201103L /** A non-binding request to reduce capacity() to size(). */ void shrink_to_fit() { _M_shrink_to_fit(); } #endif /** * Returns the total number of elements that the %vector can * hold before needing to allocate more memory. */ size_type capacity() const _GLIBCXX_NOEXCEPT { return size_type(this->_M_impl._M_end_of_storage - this->_M_impl._M_start); } /** * Returns true if the %vector is empty. (Thus begin() would * equal end().) */ bool empty() const _GLIBCXX_NOEXCEPT { return begin() == end(); } /** * @brief Attempt to preallocate enough memory for specified number of * elements. * @param __n Number of elements required. * @throw std::length_error If @a n exceeds @c max_size(). * * This function attempts to reserve enough memory for the * %vector to hold the specified number of elements. If the * number requested is more than max_size(), length_error is * thrown. * * The advantage of this function is that if optimal code is a * necessity and the user can determine the number of elements * that will be required, the user can reserve the memory in * %advance, and thus prevent a possible reallocation of memory * and copying of %vector data. */ void reserve(size_type __n); // element access /** * @brief Subscript access to the data contained in the %vector. * @param __n The index of the element for which data should be * accessed. * @return Read/write reference to data. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ reference operator[](size_type __n) _GLIBCXX_NOEXCEPT { __glibcxx_requires_subscript(__n); return *(this->_M_impl._M_start + __n); } /** * @brief Subscript access to the data contained in the %vector. * @param __n The index of the element for which data should be * accessed. * @return Read-only (constant) reference to data. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ const_reference operator[](size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_subscript(__n); return *(this->_M_impl._M_start + __n); } protected: /// Safety check used only from at(). void _M_range_check(size_type __n) const { if (__n >= this->size()) __throw_out_of_range_fmt(__N("vector::_M_range_check: __n " "(which is %zu) >= this->size() " "(which is %zu)"), __n, this->size()); } public: /** * @brief Provides access to the data contained in the %vector. * @param __n The index of the element for which data should be * accessed. * @return Read/write reference to data. * @throw std::out_of_range If @a __n is an invalid index. * * This function provides for safer data access. The parameter * is first checked that it is in the range of the vector. The * function throws out_of_range if the check fails. */ reference at(size_type __n) { _M_range_check(__n); return (*this)[__n]; } /** * @brief Provides access to the data contained in the %vector. * @param __n The index of the element for which data should be * accessed. * @return Read-only (constant) reference to data. * @throw std::out_of_range If @a __n is an invalid index. * * This function provides for safer data access. The parameter * is first checked that it is in the range of the vector. The * function throws out_of_range if the check fails. */ const_reference at(size_type __n) const { _M_range_check(__n); return (*this)[__n]; } /** * Returns a read/write reference to the data at the first * element of the %vector. */ reference front() _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); return *begin(); } /** * Returns a read-only (constant) reference to the data at the first * element of the %vector. */ const_reference front() const _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); return *begin(); } /** * Returns a read/write reference to the data at the last * element of the %vector. */ reference back() _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); return *(end() - 1); } /** * Returns a read-only (constant) reference to the data at the * last element of the %vector. */ const_reference back() const _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); return *(end() - 1); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 464. Suggestion for new member functions in standard containers. // data access /** * Returns a pointer such that [data(), data() + size()) is a valid * range. For a non-empty %vector, data() == &front(). */ _Tp* data() _GLIBCXX_NOEXCEPT { return _M_data_ptr(this->_M_impl._M_start); } const _Tp* data() const _GLIBCXX_NOEXCEPT { return _M_data_ptr(this->_M_impl._M_start); } // [23.2.4.3] modifiers /** * @brief Add data to the end of the %vector. * @param __x Data to be added. * * This is a typical stack operation. The function creates an * element at the end of the %vector and assigns the given data * to it. Due to the nature of a %vector this operation can be * done in constant time if the %vector has preallocated space * available. */ void push_back(const value_type& __x) { if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) { _GLIBCXX_ASAN_ANNOTATE_GROW(1); _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, __x); ++this->_M_impl._M_finish; _GLIBCXX_ASAN_ANNOTATE_GREW(1); } else _M_realloc_insert(end(), __x); } #if __cplusplus >= 201103L void push_back(value_type&& __x) { emplace_back(std::move(__x)); } template #if __cplusplus > 201402L reference #else void #endif emplace_back(_Args&&... __args); #endif /** * @brief Removes last element. * * This is a typical stack operation. It shrinks the %vector by one. * * Note that no data is returned, and if the last element's * data is needed, it should be retrieved before pop_back() is * called. */ void pop_back() _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); --this->_M_impl._M_finish; _Alloc_traits::destroy(this->_M_impl, this->_M_impl._M_finish); _GLIBCXX_ASAN_ANNOTATE_SHRINK(1); } #if __cplusplus >= 201103L /** * @brief Inserts an object in %vector before specified iterator. * @param __position A const_iterator into the %vector. * @param __args Arguments. * @return An iterator that points to the inserted data. * * This function will insert an object of type T constructed * with T(std::forward(args)...) before the specified location. * Note that this kind of operation could be expensive for a %vector * and if it is frequently used the user should consider using * std::list. */ template iterator emplace(const_iterator __position, _Args&&... __args) { return _M_emplace_aux(__position, std::forward<_Args>(__args)...); } /** * @brief Inserts given value into %vector before specified iterator. * @param __position A const_iterator into the %vector. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value before * the specified location. Note that this kind of operation * could be expensive for a %vector and if it is frequently * used the user should consider using std::list. */ iterator insert(const_iterator __position, const value_type& __x); #else /** * @brief Inserts given value into %vector before specified iterator. * @param __position An iterator into the %vector. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value before * the specified location. Note that this kind of operation * could be expensive for a %vector and if it is frequently * used the user should consider using std::list. */ iterator insert(iterator __position, const value_type& __x); #endif #if __cplusplus >= 201103L /** * @brief Inserts given rvalue into %vector before specified iterator. * @param __position A const_iterator into the %vector. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given rvalue before * the specified location. Note that this kind of operation * could be expensive for a %vector and if it is frequently * used the user should consider using std::list. */ iterator insert(const_iterator __position, value_type&& __x) { return _M_insert_rval(__position, std::move(__x)); } /** * @brief Inserts an initializer_list into the %vector. * @param __position An iterator into the %vector. * @param __l An initializer_list. * * This function will insert copies of the data in the * initializer_list @a l into the %vector before the location * specified by @a position. * * Note that this kind of operation could be expensive for a * %vector and if it is frequently used the user should * consider using std::list. */ iterator insert(const_iterator __position, initializer_list __l) { auto __offset = __position - cbegin(); _M_range_insert(begin() + __offset, __l.begin(), __l.end(), std::random_access_iterator_tag()); return begin() + __offset; } #endif #if __cplusplus >= 201103L /** * @brief Inserts a number of copies of given data into the %vector. * @param __position A const_iterator into the %vector. * @param __n Number of elements to be inserted. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a specified number of copies of * the given data before the location specified by @a position. * * Note that this kind of operation could be expensive for a * %vector and if it is frequently used the user should * consider using std::list. */ iterator insert(const_iterator __position, size_type __n, const value_type& __x) { difference_type __offset = __position - cbegin(); _M_fill_insert(begin() + __offset, __n, __x); return begin() + __offset; } #else /** * @brief Inserts a number of copies of given data into the %vector. * @param __position An iterator into the %vector. * @param __n Number of elements to be inserted. * @param __x Data to be inserted. * * This function will insert a specified number of copies of * the given data before the location specified by @a position. * * Note that this kind of operation could be expensive for a * %vector and if it is frequently used the user should * consider using std::list. */ void insert(iterator __position, size_type __n, const value_type& __x) { _M_fill_insert(__position, __n, __x); } #endif #if __cplusplus >= 201103L /** * @brief Inserts a range into the %vector. * @param __position A const_iterator into the %vector. * @param __first An input iterator. * @param __last An input iterator. * @return An iterator that points to the inserted data. * * This function will insert copies of the data in the range * [__first,__last) into the %vector before the location specified * by @a pos. * * Note that this kind of operation could be expensive for a * %vector and if it is frequently used the user should * consider using std::list. */ template> iterator insert(const_iterator __position, _InputIterator __first, _InputIterator __last) { difference_type __offset = __position - cbegin(); _M_insert_dispatch(begin() + __offset, __first, __last, __false_type()); return begin() + __offset; } #else /** * @brief Inserts a range into the %vector. * @param __position An iterator into the %vector. * @param __first An input iterator. * @param __last An input iterator. * * This function will insert copies of the data in the range * [__first,__last) into the %vector before the location specified * by @a pos. * * Note that this kind of operation could be expensive for a * %vector and if it is frequently used the user should * consider using std::list. */ template void insert(iterator __position, _InputIterator __first, _InputIterator __last) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_insert_dispatch(__position, __first, __last, _Integral()); } #endif /** * @brief Remove element at given position. * @param __position Iterator pointing to element to be erased. * @return An iterator pointing to the next element (or end()). * * This function will erase the element at the given position and thus * shorten the %vector by one. * * Note This operation could be expensive and if it is * frequently used the user should consider using std::list. * The user is also cautioned that this function only erases * the element, and that if the element is itself a pointer, * the pointed-to memory is not touched in any way. Managing * the pointer is the user's responsibility. */ iterator #if __cplusplus >= 201103L erase(const_iterator __position) { return _M_erase(begin() + (__position - cbegin())); } #else erase(iterator __position) { return _M_erase(__position); } #endif /** * @brief Remove a range of elements. * @param __first Iterator pointing to the first element to be erased. * @param __last Iterator pointing to one past the last element to be * erased. * @return An iterator pointing to the element pointed to by @a __last * prior to erasing (or end()). * * This function will erase the elements in the range * [__first,__last) and shorten the %vector accordingly. * * Note This operation could be expensive and if it is * frequently used the user should consider using std::list. * The user is also cautioned that this function only erases * the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibility. */ iterator #if __cplusplus >= 201103L erase(const_iterator __first, const_iterator __last) { const auto __beg = begin(); const auto __cbeg = cbegin(); return _M_erase(__beg + (__first - __cbeg), __beg + (__last - __cbeg)); } #else erase(iterator __first, iterator __last) { return _M_erase(__first, __last); } #endif /** * @brief Swaps data with another %vector. * @param __x A %vector of the same element and allocator types. * * This exchanges the elements between two vectors in constant time. * (Three pointers, so it should be quite fast.) * Note that the global std::swap() function is specialized such that * std::swap(v1,v2) will feed to this function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(vector& __x) _GLIBCXX_NOEXCEPT { #if __cplusplus >= 201103L __glibcxx_assert(_Alloc_traits::propagate_on_container_swap::value || _M_get_Tp_allocator() == __x._M_get_Tp_allocator()); #endif this->_M_impl._M_swap_data(__x._M_impl); _Alloc_traits::_S_on_swap(_M_get_Tp_allocator(), __x._M_get_Tp_allocator()); } /** * Erases all the elements. Note that this function only erases the * elements, and that if the elements themselves are pointers, the * pointed-to memory is not touched in any way. Managing the pointer is * the user's responsibility. */ void clear() _GLIBCXX_NOEXCEPT { _M_erase_at_end(this->_M_impl._M_start); } protected: /** * Memory expansion handler. Uses the member allocation function to * obtain @a n bytes of memory, and then copies [first,last) into it. */ template pointer _M_allocate_and_copy(size_type __n, _ForwardIterator __first, _ForwardIterator __last) { pointer __result = this->_M_allocate(__n); __try { std::__uninitialized_copy_a(__first, __last, __result, _M_get_Tp_allocator()); return __result; } __catch(...) { _M_deallocate(__result, __n); __throw_exception_again; } } // Internal constructor functions follow. // Called by the range constructor to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_initialize_dispatch(_Integer __n, _Integer __value, __true_type) { this->_M_impl._M_start = _M_allocate(static_cast(__n)); this->_M_impl._M_end_of_storage = this->_M_impl._M_start + static_cast(__n); _M_fill_initialize(static_cast(__n), __value); } // Called by the range constructor to implement [23.1.1]/9 template void _M_initialize_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { typedef typename std::iterator_traits<_InputIterator>:: iterator_category _IterCategory; _M_range_initialize(__first, __last, _IterCategory()); } // Called by the second initialize_dispatch above template void _M_range_initialize(_InputIterator __first, _InputIterator __last, std::input_iterator_tag) { __try { for (; __first != __last; ++__first) #if __cplusplus >= 201103L emplace_back(*__first); #else push_back(*__first); #endif } __catch(...) { clear(); __throw_exception_again; } } // Called by the second initialize_dispatch above template void _M_range_initialize(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { const size_type __n = std::distance(__first, __last); this->_M_impl._M_start = this->_M_allocate(__n); this->_M_impl._M_end_of_storage = this->_M_impl._M_start + __n; this->_M_impl._M_finish = std::__uninitialized_copy_a(__first, __last, this->_M_impl._M_start, _M_get_Tp_allocator()); } // Called by the first initialize_dispatch above and by the // vector(n,value,a) constructor. void _M_fill_initialize(size_type __n, const value_type& __value) { this->_M_impl._M_finish = std::__uninitialized_fill_n_a(this->_M_impl._M_start, __n, __value, _M_get_Tp_allocator()); } #if __cplusplus >= 201103L // Called by the vector(n) constructor. void _M_default_initialize(size_type __n) { this->_M_impl._M_finish = std::__uninitialized_default_n_a(this->_M_impl._M_start, __n, _M_get_Tp_allocator()); } #endif // Internal assign functions follow. The *_aux functions do the actual // assignment work for the range versions. // Called by the range assign to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_assign_dispatch(_Integer __n, _Integer __val, __true_type) { _M_fill_assign(__n, __val); } // Called by the range assign to implement [23.1.1]/9 template void _M_assign_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { _M_assign_aux(__first, __last, std::__iterator_category(__first)); } // Called by the second assign_dispatch above template void _M_assign_aux(_InputIterator __first, _InputIterator __last, std::input_iterator_tag); // Called by the second assign_dispatch above template void _M_assign_aux(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag); // Called by assign(n,t), and the range assign when it turns out // to be the same thing. void _M_fill_assign(size_type __n, const value_type& __val); // Internal insert functions follow. // Called by the range insert to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_insert_dispatch(iterator __pos, _Integer __n, _Integer __val, __true_type) { _M_fill_insert(__pos, __n, __val); } // Called by the range insert to implement [23.1.1]/9 template void _M_insert_dispatch(iterator __pos, _InputIterator __first, _InputIterator __last, __false_type) { _M_range_insert(__pos, __first, __last, std::__iterator_category(__first)); } // Called by the second insert_dispatch above template void _M_range_insert(iterator __pos, _InputIterator __first, _InputIterator __last, std::input_iterator_tag); // Called by the second insert_dispatch above template void _M_range_insert(iterator __pos, _ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag); // Called by insert(p,n,x), and the range insert when it turns out to be // the same thing. void _M_fill_insert(iterator __pos, size_type __n, const value_type& __x); #if __cplusplus >= 201103L // Called by resize(n). void _M_default_append(size_type __n); bool _M_shrink_to_fit(); #endif #if __cplusplus < 201103L // Called by insert(p,x) void _M_insert_aux(iterator __position, const value_type& __x); void _M_realloc_insert(iterator __position, const value_type& __x); #else // A value_type object constructed with _Alloc_traits::construct() // and destroyed with _Alloc_traits::destroy(). struct _Temporary_value { template explicit _Temporary_value(vector* __vec, _Args&&... __args) : _M_this(__vec) { _Alloc_traits::construct(_M_this->_M_impl, _M_ptr(), std::forward<_Args>(__args)...); } ~_Temporary_value() { _Alloc_traits::destroy(_M_this->_M_impl, _M_ptr()); } value_type& _M_val() { return *_M_ptr(); } private: _Tp* _M_ptr() { return reinterpret_cast<_Tp*>(&__buf); } vector* _M_this; typename aligned_storage::type __buf; }; // Called by insert(p,x) and other functions when insertion needs to // reallocate or move existing elements. _Arg is either _Tp& or _Tp. template void _M_insert_aux(iterator __position, _Arg&& __arg); template void _M_realloc_insert(iterator __position, _Args&&... __args); // Either move-construct at the end, or forward to _M_insert_aux. iterator _M_insert_rval(const_iterator __position, value_type&& __v); // Try to emplace at the end, otherwise forward to _M_insert_aux. template iterator _M_emplace_aux(const_iterator __position, _Args&&... __args); // Emplacing an rvalue of the correct type can use _M_insert_rval. iterator _M_emplace_aux(const_iterator __position, value_type&& __v) { return _M_insert_rval(__position, std::move(__v)); } #endif // Called by _M_fill_insert, _M_insert_aux etc. size_type _M_check_len(size_type __n, const char* __s) const { if (max_size() - size() < __n) __throw_length_error(__N(__s)); const size_type __len = size() + std::max(size(), __n); return (__len < size() || __len > max_size()) ? max_size() : __len; } // Internal erase functions follow. // Called by erase(q1,q2), clear(), resize(), _M_fill_assign, // _M_assign_aux. void _M_erase_at_end(pointer __pos) _GLIBCXX_NOEXCEPT { if (size_type __n = this->_M_impl._M_finish - __pos) { std::_Destroy(__pos, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish = __pos; _GLIBCXX_ASAN_ANNOTATE_SHRINK(__n); } } iterator _M_erase(iterator __position); iterator _M_erase(iterator __first, iterator __last); #if __cplusplus >= 201103L private: // Constant-time move assignment when source object's memory can be // moved, either because the source's allocator will move too // or because the allocators are equal. void _M_move_assign(vector&& __x, std::true_type) noexcept { vector __tmp(get_allocator()); this->_M_impl._M_swap_data(__tmp._M_impl); this->_M_impl._M_swap_data(__x._M_impl); std::__alloc_on_move(_M_get_Tp_allocator(), __x._M_get_Tp_allocator()); } // Do move assignment when it might not be possible to move source // object's memory, resulting in a linear-time operation. void _M_move_assign(vector&& __x, std::false_type) { if (__x._M_get_Tp_allocator() == this->_M_get_Tp_allocator()) _M_move_assign(std::move(__x), std::true_type()); else { // The rvalue's allocator cannot be moved and is not equal, // so we need to individually move each element. this->assign(std::__make_move_if_noexcept_iterator(__x.begin()), std::__make_move_if_noexcept_iterator(__x.end())); __x.clear(); } } #endif template _Up* _M_data_ptr(_Up* __ptr) const _GLIBCXX_NOEXCEPT { return __ptr; } #if __cplusplus >= 201103L template typename std::pointer_traits<_Ptr>::element_type* _M_data_ptr(_Ptr __ptr) const { return empty() ? nullptr : std::__to_address(__ptr); } #else template _Up* _M_data_ptr(_Up* __ptr) _GLIBCXX_NOEXCEPT { return __ptr; } template value_type* _M_data_ptr(_Ptr __ptr) { return empty() ? (value_type*)0 : __ptr.operator->(); } template const value_type* _M_data_ptr(_Ptr __ptr) const { return empty() ? (const value_type*)0 : __ptr.operator->(); } #endif }; #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> vector(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> vector<_ValT, _Allocator>; #endif /** * @brief Vector equality comparison. * @param __x A %vector. * @param __y A %vector of the same type as @a __x. * @return True iff the size and elements of the vectors are equal. * * This is an equivalence relation. It is linear in the size of the * vectors. Vectors are considered equivalent if their sizes are equal, * and if corresponding elements compare equal. */ template inline bool operator==(const vector<_Tp, _Alloc>& __x, const vector<_Tp, _Alloc>& __y) { return (__x.size() == __y.size() && std::equal(__x.begin(), __x.end(), __y.begin())); } /** * @brief Vector ordering relation. * @param __x A %vector. * @param __y A %vector of the same type as @a __x. * @return True iff @a __x is lexicographically less than @a __y. * * This is a total ordering relation. It is linear in the size of the * vectors. The elements must be comparable with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const vector<_Tp, _Alloc>& __x, const vector<_Tp, _Alloc>& __y) { return std::lexicographical_compare(__x.begin(), __x.end(), __y.begin(), __y.end()); } /// Based on operator== template inline bool operator!=(const vector<_Tp, _Alloc>& __x, const vector<_Tp, _Alloc>& __y) { return !(__x == __y); } /// Based on operator< template inline bool operator>(const vector<_Tp, _Alloc>& __x, const vector<_Tp, _Alloc>& __y) { return __y < __x; } /// Based on operator< template inline bool operator<=(const vector<_Tp, _Alloc>& __x, const vector<_Tp, _Alloc>& __y) { return !(__y < __x); } /// Based on operator< template inline bool operator>=(const vector<_Tp, _Alloc>& __x, const vector<_Tp, _Alloc>& __y) { return !(__x < __y); } /// See std::vector::swap(). template inline void swap(vector<_Tp, _Alloc>& __x, vector<_Tp, _Alloc>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { __x.swap(__y); } _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_VECTOR_H */ PK!A8/bits/stream_iterator.hnu[// Stream iterators // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/stream_iterator.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iterator} */ #ifndef _STREAM_ITERATOR_H #define _STREAM_ITERATOR_H 1 #pragma GCC system_header #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup iterators * @{ */ /// Provides input iterator semantics for streams. template, typename _Dist = ptrdiff_t> class istream_iterator : public iterator { public: typedef _CharT char_type; typedef _Traits traits_type; typedef basic_istream<_CharT, _Traits> istream_type; private: istream_type* _M_stream; _Tp _M_value; bool _M_ok; public: /// Construct end of input stream iterator. _GLIBCXX_CONSTEXPR istream_iterator() : _M_stream(0), _M_value(), _M_ok(false) {} /// Construct start of input stream iterator. istream_iterator(istream_type& __s) : _M_stream(std::__addressof(__s)) { _M_read(); } istream_iterator(const istream_iterator& __obj) : _M_stream(__obj._M_stream), _M_value(__obj._M_value), _M_ok(__obj._M_ok) { } const _Tp& operator*() const { __glibcxx_requires_cond(_M_ok, _M_message(__gnu_debug::__msg_deref_istream) ._M_iterator(*this)); return _M_value; } const _Tp* operator->() const { return std::__addressof((operator*())); } istream_iterator& operator++() { __glibcxx_requires_cond(_M_ok, _M_message(__gnu_debug::__msg_inc_istream) ._M_iterator(*this)); _M_read(); return *this; } istream_iterator operator++(int) { __glibcxx_requires_cond(_M_ok, _M_message(__gnu_debug::__msg_inc_istream) ._M_iterator(*this)); istream_iterator __tmp = *this; _M_read(); return __tmp; } bool _M_equal(const istream_iterator& __x) const { return (_M_ok == __x._M_ok) && (!_M_ok || _M_stream == __x._M_stream); } private: void _M_read() { _M_ok = (_M_stream && *_M_stream) ? true : false; if (_M_ok) { *_M_stream >> _M_value; _M_ok = *_M_stream ? true : false; } } }; /// Return true if x and y are both end or not end, or x and y are the same. template inline bool operator==(const istream_iterator<_Tp, _CharT, _Traits, _Dist>& __x, const istream_iterator<_Tp, _CharT, _Traits, _Dist>& __y) { return __x._M_equal(__y); } /// Return false if x and y are both end or not end, or x and y are the same. template inline bool operator!=(const istream_iterator<_Tp, _CharT, _Traits, _Dist>& __x, const istream_iterator<_Tp, _CharT, _Traits, _Dist>& __y) { return !__x._M_equal(__y); } /** * @brief Provides output iterator semantics for streams. * * This class provides an iterator to write to an ostream. The type Tp is * the only type written by this iterator and there must be an * operator<<(Tp) defined. * * @tparam _Tp The type to write to the ostream. * @tparam _CharT The ostream char_type. * @tparam _Traits The ostream char_traits. */ template > class ostream_iterator : public iterator { public: //@{ /// Public typedef typedef _CharT char_type; typedef _Traits traits_type; typedef basic_ostream<_CharT, _Traits> ostream_type; //@} private: ostream_type* _M_stream; const _CharT* _M_string; public: /// Construct from an ostream. ostream_iterator(ostream_type& __s) : _M_stream(std::__addressof(__s)), _M_string(0) {} /** * Construct from an ostream. * * The delimiter string @a c is written to the stream after every Tp * written to the stream. The delimiter is not copied, and thus must * not be destroyed while this iterator is in use. * * @param __s Underlying ostream to write to. * @param __c CharT delimiter string to insert. */ ostream_iterator(ostream_type& __s, const _CharT* __c) : _M_stream(&__s), _M_string(__c) { } /// Copy constructor. ostream_iterator(const ostream_iterator& __obj) : _M_stream(__obj._M_stream), _M_string(__obj._M_string) { } /// Writes @a value to underlying ostream using operator<<. If /// constructed with delimiter string, writes delimiter to ostream. ostream_iterator& operator=(const _Tp& __value) { __glibcxx_requires_cond(_M_stream != 0, _M_message(__gnu_debug::__msg_output_ostream) ._M_iterator(*this)); *_M_stream << __value; if (_M_string) *_M_stream << _M_string; return *this; } ostream_iterator& operator*() { return *this; } ostream_iterator& operator++() { return *this; } ostream_iterator& operator++(int) { return *this; } }; // @} group iterators _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!ŕAA8/bits/streambuf.tccnu[// Stream buffer classes -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/streambuf.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{streambuf} */ // // ISO C++ 14882: 27.5 Stream buffers // #ifndef _STREAMBUF_TCC #define _STREAMBUF_TCC 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template streamsize basic_streambuf<_CharT, _Traits>:: xsgetn(char_type* __s, streamsize __n) { streamsize __ret = 0; while (__ret < __n) { const streamsize __buf_len = this->egptr() - this->gptr(); if (__buf_len) { const streamsize __remaining = __n - __ret; const streamsize __len = std::min(__buf_len, __remaining); traits_type::copy(__s, this->gptr(), __len); __ret += __len; __s += __len; this->__safe_gbump(__len); } if (__ret < __n) { const int_type __c = this->uflow(); if (!traits_type::eq_int_type(__c, traits_type::eof())) { traits_type::assign(*__s++, traits_type::to_char_type(__c)); ++__ret; } else break; } } return __ret; } template streamsize basic_streambuf<_CharT, _Traits>:: xsputn(const char_type* __s, streamsize __n) { streamsize __ret = 0; while (__ret < __n) { const streamsize __buf_len = this->epptr() - this->pptr(); if (__buf_len) { const streamsize __remaining = __n - __ret; const streamsize __len = std::min(__buf_len, __remaining); traits_type::copy(this->pptr(), __s, __len); __ret += __len; __s += __len; this->__safe_pbump(__len); } if (__ret < __n) { int_type __c = this->overflow(traits_type::to_int_type(*__s)); if (!traits_type::eq_int_type(__c, traits_type::eof())) { ++__ret; ++__s; } else break; } } return __ret; } // Conceivably, this could be used to implement buffer-to-buffer // copies, if this was ever desired in an un-ambiguous way by the // standard. template streamsize __copy_streambufs_eof(basic_streambuf<_CharT, _Traits>* __sbin, basic_streambuf<_CharT, _Traits>* __sbout, bool& __ineof) { streamsize __ret = 0; __ineof = true; typename _Traits::int_type __c = __sbin->sgetc(); while (!_Traits::eq_int_type(__c, _Traits::eof())) { __c = __sbout->sputc(_Traits::to_char_type(__c)); if (_Traits::eq_int_type(__c, _Traits::eof())) { __ineof = false; break; } ++__ret; __c = __sbin->snextc(); } return __ret; } template inline streamsize __copy_streambufs(basic_streambuf<_CharT, _Traits>* __sbin, basic_streambuf<_CharT, _Traits>* __sbout) { bool __ineof; return __copy_streambufs_eof(__sbin, __sbout, __ineof); } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class basic_streambuf; extern template streamsize __copy_streambufs(basic_streambuf*, basic_streambuf*); extern template streamsize __copy_streambufs_eof(basic_streambuf*, basic_streambuf*, bool&); #ifdef _GLIBCXX_USE_WCHAR_T extern template class basic_streambuf; extern template streamsize __copy_streambufs(basic_streambuf*, basic_streambuf*); extern template streamsize __copy_streambufs_eof(basic_streambuf*, basic_streambuf*, bool&); #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK!y558/bits/streambuf_iterator.hnu[// Streambuf iterators // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/streambuf_iterator.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iterator} */ #ifndef _STREAMBUF_ITERATOR_H #define _STREAMBUF_ITERATOR_H 1 #pragma GCC system_header #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup iterators * @{ */ // 24.5.3 Template class istreambuf_iterator /// Provides input iterator semantics for streambufs. template class istreambuf_iterator : public iterator= 201103L // LWG 445. _CharT> #else _CharT&> #endif { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef _Traits traits_type; typedef typename _Traits::int_type int_type; typedef basic_streambuf<_CharT, _Traits> streambuf_type; typedef basic_istream<_CharT, _Traits> istream_type; //@} template friend typename __gnu_cxx::__enable_if<__is_char<_CharT2>::__value, ostreambuf_iterator<_CharT2> >::__type copy(istreambuf_iterator<_CharT2>, istreambuf_iterator<_CharT2>, ostreambuf_iterator<_CharT2>); template friend typename __gnu_cxx::__enable_if<__is_char<_CharT2>::__value, _CharT2*>::__type __copy_move_a2(istreambuf_iterator<_CharT2>, istreambuf_iterator<_CharT2>, _CharT2*); template friend typename __gnu_cxx::__enable_if<__is_char<_CharT2>::__value, istreambuf_iterator<_CharT2> >::__type find(istreambuf_iterator<_CharT2>, istreambuf_iterator<_CharT2>, const _CharT2&); template friend typename __gnu_cxx::__enable_if<__is_char<_CharT2>::__value, void>::__type advance(istreambuf_iterator<_CharT2>&, _Distance); private: // 24.5.3 istreambuf_iterator // p 1 // If the end of stream is reached (streambuf_type::sgetc() // returns traits_type::eof()), the iterator becomes equal to // the "end of stream" iterator value. // NB: This implementation assumes the "end of stream" value // is EOF, or -1. mutable streambuf_type* _M_sbuf; int_type _M_c; public: /// Construct end of input stream iterator. _GLIBCXX_CONSTEXPR istreambuf_iterator() _GLIBCXX_USE_NOEXCEPT : _M_sbuf(0), _M_c(traits_type::eof()) { } #if __cplusplus >= 201103L istreambuf_iterator(const istreambuf_iterator&) noexcept = default; ~istreambuf_iterator() = default; #endif /// Construct start of input stream iterator. istreambuf_iterator(istream_type& __s) _GLIBCXX_USE_NOEXCEPT : _M_sbuf(__s.rdbuf()), _M_c(traits_type::eof()) { } /// Construct start of streambuf iterator. istreambuf_iterator(streambuf_type* __s) _GLIBCXX_USE_NOEXCEPT : _M_sbuf(__s), _M_c(traits_type::eof()) { } /// Return the current character pointed to by iterator. This returns /// streambuf.sgetc(). It cannot be assigned. NB: The result of /// operator*() on an end of stream is undefined. char_type operator*() const { int_type __c = _M_get(); #ifdef _GLIBCXX_DEBUG_PEDANTIC // Dereferencing a past-the-end istreambuf_iterator is a // libstdc++ extension __glibcxx_requires_cond(!_S_is_eof(__c), _M_message(__gnu_debug::__msg_deref_istreambuf) ._M_iterator(*this)); #endif return traits_type::to_char_type(__c); } /// Advance the iterator. Calls streambuf.sbumpc(). istreambuf_iterator& operator++() { __glibcxx_requires_cond(_M_sbuf && (!_S_is_eof(_M_c) || !_S_is_eof(_M_sbuf->sgetc())), _M_message(__gnu_debug::__msg_inc_istreambuf) ._M_iterator(*this)); _M_sbuf->sbumpc(); _M_c = traits_type::eof(); return *this; } /// Advance the iterator. Calls streambuf.sbumpc(). istreambuf_iterator operator++(int) { __glibcxx_requires_cond(_M_sbuf && (!_S_is_eof(_M_c) || !_S_is_eof(_M_sbuf->sgetc())), _M_message(__gnu_debug::__msg_inc_istreambuf) ._M_iterator(*this)); istreambuf_iterator __old = *this; __old._M_c = _M_sbuf->sbumpc(); _M_c = traits_type::eof(); return __old; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 110 istreambuf_iterator::equal not const // NB: there is also number 111 (NAD) relevant to this function. /// Return true both iterators are end or both are not end. bool equal(const istreambuf_iterator& __b) const { return _M_at_eof() == __b._M_at_eof(); } private: int_type _M_get() const { int_type __ret = _M_c; if (_M_sbuf && _S_is_eof(__ret) && _S_is_eof(__ret = _M_sbuf->sgetc())) _M_sbuf = 0; return __ret; } bool _M_at_eof() const { return _S_is_eof(_M_get()); } static bool _S_is_eof(int_type __c) { const int_type __eof = traits_type::eof(); return traits_type::eq_int_type(__c, __eof); } }; template inline bool operator==(const istreambuf_iterator<_CharT, _Traits>& __a, const istreambuf_iterator<_CharT, _Traits>& __b) { return __a.equal(__b); } template inline bool operator!=(const istreambuf_iterator<_CharT, _Traits>& __a, const istreambuf_iterator<_CharT, _Traits>& __b) { return !__a.equal(__b); } /// Provides output iterator semantics for streambufs. template class ostreambuf_iterator : public iterator { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef _Traits traits_type; typedef basic_streambuf<_CharT, _Traits> streambuf_type; typedef basic_ostream<_CharT, _Traits> ostream_type; //@} template friend typename __gnu_cxx::__enable_if<__is_char<_CharT2>::__value, ostreambuf_iterator<_CharT2> >::__type copy(istreambuf_iterator<_CharT2>, istreambuf_iterator<_CharT2>, ostreambuf_iterator<_CharT2>); private: streambuf_type* _M_sbuf; bool _M_failed; public: /// Construct output iterator from ostream. ostreambuf_iterator(ostream_type& __s) _GLIBCXX_USE_NOEXCEPT : _M_sbuf(__s.rdbuf()), _M_failed(!_M_sbuf) { } /// Construct output iterator from streambuf. ostreambuf_iterator(streambuf_type* __s) _GLIBCXX_USE_NOEXCEPT : _M_sbuf(__s), _M_failed(!_M_sbuf) { } /// Write character to streambuf. Calls streambuf.sputc(). ostreambuf_iterator& operator=(_CharT __c) { if (!_M_failed && _Traits::eq_int_type(_M_sbuf->sputc(__c), _Traits::eof())) _M_failed = true; return *this; } /// Return *this. ostreambuf_iterator& operator*() { return *this; } /// Return *this. ostreambuf_iterator& operator++(int) { return *this; } /// Return *this. ostreambuf_iterator& operator++() { return *this; } /// Return true if previous operator=() failed. bool failed() const _GLIBCXX_USE_NOEXCEPT { return _M_failed; } ostreambuf_iterator& _M_put(const _CharT* __ws, streamsize __len) { if (__builtin_expect(!_M_failed, true) && __builtin_expect(this->_M_sbuf->sputn(__ws, __len) != __len, false)) _M_failed = true; return *this; } }; // Overloads for streambuf iterators. template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, ostreambuf_iterator<_CharT> >::__type copy(istreambuf_iterator<_CharT> __first, istreambuf_iterator<_CharT> __last, ostreambuf_iterator<_CharT> __result) { if (__first._M_sbuf && !__last._M_sbuf && !__result._M_failed) { bool __ineof; __copy_streambufs_eof(__first._M_sbuf, __result._M_sbuf, __ineof); if (!__ineof) __result._M_failed = true; } return __result; } template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, ostreambuf_iterator<_CharT> >::__type __copy_move_a2(_CharT* __first, _CharT* __last, ostreambuf_iterator<_CharT> __result) { const streamsize __num = __last - __first; if (__num > 0) __result._M_put(__first, __num); return __result; } template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, ostreambuf_iterator<_CharT> >::__type __copy_move_a2(const _CharT* __first, const _CharT* __last, ostreambuf_iterator<_CharT> __result) { const streamsize __num = __last - __first; if (__num > 0) __result._M_put(__first, __num); return __result; } template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, _CharT*>::__type __copy_move_a2(istreambuf_iterator<_CharT> __first, istreambuf_iterator<_CharT> __last, _CharT* __result) { typedef istreambuf_iterator<_CharT> __is_iterator_type; typedef typename __is_iterator_type::traits_type traits_type; typedef typename __is_iterator_type::streambuf_type streambuf_type; typedef typename traits_type::int_type int_type; if (__first._M_sbuf && !__last._M_sbuf) { streambuf_type* __sb = __first._M_sbuf; int_type __c = __sb->sgetc(); while (!traits_type::eq_int_type(__c, traits_type::eof())) { const streamsize __n = __sb->egptr() - __sb->gptr(); if (__n > 1) { traits_type::copy(__result, __sb->gptr(), __n); __sb->__safe_gbump(__n); __result += __n; __c = __sb->underflow(); } else { *__result++ = traits_type::to_char_type(__c); __c = __sb->snextc(); } } } return __result; } template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, istreambuf_iterator<_CharT> >::__type find(istreambuf_iterator<_CharT> __first, istreambuf_iterator<_CharT> __last, const _CharT& __val) { typedef istreambuf_iterator<_CharT> __is_iterator_type; typedef typename __is_iterator_type::traits_type traits_type; typedef typename __is_iterator_type::streambuf_type streambuf_type; typedef typename traits_type::int_type int_type; const int_type __eof = traits_type::eof(); if (__first._M_sbuf && !__last._M_sbuf) { const int_type __ival = traits_type::to_int_type(__val); streambuf_type* __sb = __first._M_sbuf; int_type __c = __sb->sgetc(); while (!traits_type::eq_int_type(__c, __eof) && !traits_type::eq_int_type(__c, __ival)) { streamsize __n = __sb->egptr() - __sb->gptr(); if (__n > 1) { const _CharT* __p = traits_type::find(__sb->gptr(), __n, __val); if (__p) __n = __p - __sb->gptr(); __sb->__safe_gbump(__n); __c = __sb->sgetc(); } else __c = __sb->snextc(); } __first._M_c = __eof; } return __first; } template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, void>::__type advance(istreambuf_iterator<_CharT>& __i, _Distance __n) { if (__n == 0) return; __glibcxx_assert(__n > 0); __glibcxx_requires_cond(!__i._M_at_eof(), _M_message(__gnu_debug::__msg_inc_istreambuf) ._M_iterator(__i)); typedef istreambuf_iterator<_CharT> __is_iterator_type; typedef typename __is_iterator_type::traits_type traits_type; typedef typename __is_iterator_type::streambuf_type streambuf_type; typedef typename traits_type::int_type int_type; const int_type __eof = traits_type::eof(); streambuf_type* __sb = __i._M_sbuf; while (__n > 0) { streamsize __size = __sb->egptr() - __sb->gptr(); if (__size > __n) { __sb->__safe_gbump(__n); break; } __sb->__safe_gbump(__size); __n -= __size; if (traits_type::eq_int_type(__sb->underflow(), __eof)) { __glibcxx_requires_cond(__n == 0, _M_message(__gnu_debug::__msg_inc_istreambuf) ._M_iterator(__i)); break; } } __i._M_c = __eof; } // @} group iterators _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!LԿ**8/bits/string_view.tccnu[// Components for manipulating non-owning sequences of characters -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/string_view.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{string_view} */ // // N3762 basic_string_view library // #ifndef _GLIBCXX_STRING_VIEW_TCC #define _GLIBCXX_STRING_VIEW_TCC 1 #pragma GCC system_header #if __cplusplus >= 201703L namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find(const _CharT* __str, size_type __pos, size_type __n) const noexcept { __glibcxx_requires_string_len(__str, __n); if (__n == 0) return __pos <= this->_M_len ? __pos : npos; if (__n <= this->_M_len) { for (; __pos <= this->_M_len - __n; ++__pos) if (traits_type::eq(this->_M_str[__pos], __str[0]) && traits_type::compare(this->_M_str + __pos + 1, __str + 1, __n - 1) == 0) return __pos; } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find(_CharT __c, size_type __pos) const noexcept { size_type __ret = npos; if (__pos < this->_M_len) { const size_type __n = this->_M_len - __pos; const _CharT* __p = traits_type::find(this->_M_str + __pos, __n, __c); if (__p) __ret = __p - this->_M_str; } return __ret; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: rfind(const _CharT* __str, size_type __pos, size_type __n) const noexcept { __glibcxx_requires_string_len(__str, __n); if (__n <= this->_M_len) { __pos = std::min(size_type(this->_M_len - __n), __pos); do { if (traits_type::compare(this->_M_str + __pos, __str, __n) == 0) return __pos; } while (__pos-- > 0); } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: rfind(_CharT __c, size_type __pos) const noexcept { size_type __size = this->_M_len; if (__size > 0) { if (--__size > __pos) __size = __pos; for (++__size; __size-- > 0; ) if (traits_type::eq(this->_M_str[__size], __c)) return __size; } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_first_of(const _CharT* __str, size_type __pos, size_type __n) const noexcept { __glibcxx_requires_string_len(__str, __n); for (; __n && __pos < this->_M_len; ++__pos) { const _CharT* __p = traits_type::find(__str, __n, this->_M_str[__pos]); if (__p) return __pos; } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_last_of(const _CharT* __str, size_type __pos, size_type __n) const noexcept { __glibcxx_requires_string_len(__str, __n); size_type __size = this->size(); if (__size && __n) { if (--__size > __pos) __size = __pos; do { if (traits_type::find(__str, __n, this->_M_str[__size])) return __size; } while (__size-- != 0); } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_first_not_of(const _CharT* __str, size_type __pos, size_type __n) const noexcept { __glibcxx_requires_string_len(__str, __n); for (; __pos < this->_M_len; ++__pos) if (!traits_type::find(__str, __n, this->_M_str[__pos])) return __pos; return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_first_not_of(_CharT __c, size_type __pos) const noexcept { for (; __pos < this->_M_len; ++__pos) if (!traits_type::eq(this->_M_str[__pos], __c)) return __pos; return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_last_not_of(const _CharT* __str, size_type __pos, size_type __n) const noexcept { __glibcxx_requires_string_len(__str, __n); size_type __size = this->_M_len; if (__size) { if (--__size > __pos) __size = __pos; do { if (!traits_type::find(__str, __n, this->_M_str[__size])) return __size; } while (__size--); } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_last_not_of(_CharT __c, size_type __pos) const noexcept { size_type __size = this->_M_len; if (__size) { if (--__size > __pos) __size = __pos; do { if (!traits_type::eq(this->_M_str[__size], __c)) return __size; } while (__size--); } return npos; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // __cplusplus <= 201402L #endif // _GLIBCXX_STRING_VIEW_TCC PK!櫋C/ / 8/bits/stringfwd.hnu[// Forward declarations -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/stringfwd.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{string} */ // // ISO C++ 14882: 21 Strings library // #ifndef _STRINGFWD_H #define _STRINGFWD_H 1 #pragma GCC system_header #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup strings Strings * * @{ */ template struct char_traits; template<> struct char_traits; #ifdef _GLIBCXX_USE_WCHAR_T template<> struct char_traits; #endif #if ((__cplusplus >= 201103L) \ && defined(_GLIBCXX_USE_C99_STDINT_TR1)) template<> struct char_traits; template<> struct char_traits; #endif _GLIBCXX_BEGIN_NAMESPACE_CXX11 template, typename _Alloc = allocator<_CharT> > class basic_string; /// A string of @c char typedef basic_string string; #ifdef _GLIBCXX_USE_WCHAR_T /// A string of @c wchar_t typedef basic_string wstring; #endif #if ((__cplusplus >= 201103L) \ && defined(_GLIBCXX_USE_C99_STDINT_TR1)) /// A string of @c char16_t typedef basic_string u16string; /// A string of @c char32_t typedef basic_string u32string; #endif _GLIBCXX_END_NAMESPACE_CXX11 /** @} */ _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _STRINGFWD_H PK!hZa'a'8/bits/uniform_int_dist.hnu[// Class template uniform_int_distribution -*- C++ -*- // Copyright (C) 2009-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/uniform_int_dist.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{random} */ #ifndef _GLIBCXX_BITS_UNIFORM_INT_DIST_H #define _GLIBCXX_BITS_UNIFORM_INT_DIST_H #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { /* Determine whether number is a power of 2. */ template inline bool _Power_of_2(_Tp __x) { return ((__x - 1) & __x) == 0; } } /** * @brief Uniform discrete distribution for random numbers. * A discrete random distribution on the range @f$[min, max]@f$ with equal * probability throughout the range. */ template class uniform_int_distribution { static_assert(std::is_integral<_IntType>::value, "template argument must be an integral type"); public: /** The type of the range of the distribution. */ typedef _IntType result_type; /** Parameter type. */ struct param_type { typedef uniform_int_distribution<_IntType> distribution_type; explicit param_type(_IntType __a = 0, _IntType __b = std::numeric_limits<_IntType>::max()) : _M_a(__a), _M_b(__b) { __glibcxx_assert(_M_a <= _M_b); } result_type a() const { return _M_a; } result_type b() const { return _M_b; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _IntType _M_a; _IntType _M_b; }; public: /** * @brief Constructs a uniform distribution object. */ explicit uniform_int_distribution(_IntType __a = 0, _IntType __b = std::numeric_limits<_IntType>::max()) : _M_param(__a, __b) { } explicit uniform_int_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. * * Does nothing for the uniform integer distribution. */ void reset() { } result_type a() const { return _M_param.a(); } result_type b() const { return _M_param.b(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the inclusive lower bound of the distribution range. */ result_type min() const { return this->a(); } /** * @brief Returns the inclusive upper bound of the distribution range. */ result_type max() const { return this->b(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two uniform integer distributions have * the same parameters. */ friend bool operator==(const uniform_int_distribution& __d1, const uniform_int_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; template template typename uniform_int_distribution<_IntType>::result_type uniform_int_distribution<_IntType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { typedef typename _UniformRandomNumberGenerator::result_type _Gresult_type; typedef typename std::make_unsigned::type __utype; typedef typename std::common_type<_Gresult_type, __utype>::type __uctype; const __uctype __urngmin = __urng.min(); const __uctype __urngmax = __urng.max(); const __uctype __urngrange = __urngmax - __urngmin; const __uctype __urange = __uctype(__param.b()) - __uctype(__param.a()); __uctype __ret; if (__urngrange > __urange) { // downscaling const __uctype __uerange = __urange + 1; // __urange can be zero const __uctype __scaling = __urngrange / __uerange; const __uctype __past = __uerange * __scaling; do __ret = __uctype(__urng()) - __urngmin; while (__ret >= __past); __ret /= __scaling; } else if (__urngrange < __urange) { // upscaling /* Note that every value in [0, urange] can be written uniquely as (urngrange + 1) * high + low where high in [0, urange / (urngrange + 1)] and low in [0, urngrange]. */ __uctype __tmp; // wraparound control do { const __uctype __uerngrange = __urngrange + 1; __tmp = (__uerngrange * operator() (__urng, param_type(0, __urange / __uerngrange))); __ret = __tmp + (__uctype(__urng()) - __urngmin); } while (__ret > __urange || __ret < __tmp); } else __ret = __uctype(__urng()) - __urngmin; return __ret + __param.a(); } template template void uniform_int_distribution<_IntType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) typedef typename _UniformRandomNumberGenerator::result_type _Gresult_type; typedef typename std::make_unsigned::type __utype; typedef typename std::common_type<_Gresult_type, __utype>::type __uctype; const __uctype __urngmin = __urng.min(); const __uctype __urngmax = __urng.max(); const __uctype __urngrange = __urngmax - __urngmin; const __uctype __urange = __uctype(__param.b()) - __uctype(__param.a()); __uctype __ret; if (__urngrange > __urange) { if (__detail::_Power_of_2(__urngrange + 1) && __detail::_Power_of_2(__urange + 1)) { while (__f != __t) { __ret = __uctype(__urng()) - __urngmin; *__f++ = (__ret & __urange) + __param.a(); } } else { // downscaling const __uctype __uerange = __urange + 1; // __urange can be zero const __uctype __scaling = __urngrange / __uerange; const __uctype __past = __uerange * __scaling; while (__f != __t) { do __ret = __uctype(__urng()) - __urngmin; while (__ret >= __past); *__f++ = __ret / __scaling + __param.a(); } } } else if (__urngrange < __urange) { // upscaling /* Note that every value in [0, urange] can be written uniquely as (urngrange + 1) * high + low where high in [0, urange / (urngrange + 1)] and low in [0, urngrange]. */ __uctype __tmp; // wraparound control while (__f != __t) { do { const __uctype __uerngrange = __urngrange + 1; __tmp = (__uerngrange * operator() (__urng, param_type(0, __urange / __uerngrange))); __ret = __tmp + (__uctype(__urng()) - __urngmin); } while (__ret > __urange || __ret < __tmp); *__f++ = __ret; } } else while (__f != __t) *__f++ = __uctype(__urng()) - __urngmin + __param.a(); } // operator!= and operator<< and operator>> are defined in _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif PK! ̀ee8/bits/unique_ptr.hnu[// unique_ptr implementation -*- C++ -*- // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/unique_ptr.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _UNIQUE_PTR_H #define _UNIQUE_PTR_H 1 #include #include #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup pointer_abstractions * @{ */ #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" template class auto_ptr; #pragma GCC diagnostic pop #endif /// Primary template of default_delete, used by unique_ptr template struct default_delete { /// Default constructor constexpr default_delete() noexcept = default; /** @brief Converting constructor. * * Allows conversion from a deleter for arrays of another type, @p _Up, * only if @p _Up* is convertible to @p _Tp*. */ template::value>::type> default_delete(const default_delete<_Up>&) noexcept { } /// Calls @c delete @p __ptr void operator()(_Tp* __ptr) const { static_assert(!is_void<_Tp>::value, "can't delete pointer to incomplete type"); static_assert(sizeof(_Tp)>0, "can't delete pointer to incomplete type"); delete __ptr; } }; // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 740 - omit specialization for array objects with a compile time length /// Specialization for arrays, default_delete. template struct default_delete<_Tp[]> { public: /// Default constructor constexpr default_delete() noexcept = default; /** @brief Converting constructor. * * Allows conversion from a deleter for arrays of another type, such as * a const-qualified version of @p _Tp. * * Conversions from types derived from @c _Tp are not allowed because * it is unsafe to @c delete[] an array of derived types through a * pointer to the base type. */ template::value>::type> default_delete(const default_delete<_Up[]>&) noexcept { } /// Calls @c delete[] @p __ptr template typename enable_if::value>::type operator()(_Up* __ptr) const { static_assert(sizeof(_Tp)>0, "can't delete pointer to incomplete type"); delete [] __ptr; } }; template class __uniq_ptr_impl { template struct _Ptr { using type = _Up*; }; template struct _Ptr<_Up, _Ep, __void_t::type::pointer>> { using type = typename remove_reference<_Ep>::type::pointer; }; public: using _DeleterConstraint = enable_if< __and_<__not_>, is_default_constructible<_Dp>>::value>; using pointer = typename _Ptr<_Tp, _Dp>::type; __uniq_ptr_impl() = default; __uniq_ptr_impl(pointer __p) : _M_t() { _M_ptr() = __p; } template __uniq_ptr_impl(pointer __p, _Del&& __d) : _M_t(__p, std::forward<_Del>(__d)) { } pointer& _M_ptr() { return std::get<0>(_M_t); } pointer _M_ptr() const { return std::get<0>(_M_t); } _Dp& _M_deleter() { return std::get<1>(_M_t); } const _Dp& _M_deleter() const { return std::get<1>(_M_t); } void swap(__uniq_ptr_impl& __rhs) noexcept { using std::swap; swap(this->_M_ptr(), __rhs._M_ptr()); swap(this->_M_deleter(), __rhs._M_deleter()); } private: tuple _M_t; }; /// 20.7.1.2 unique_ptr for single objects. template > class unique_ptr { template using _DeleterConstraint = typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type; __uniq_ptr_impl<_Tp, _Dp> _M_t; public: using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer; using element_type = _Tp; using deleter_type = _Dp; // helper template for detecting a safe conversion from another // unique_ptr template using __safe_conversion_up = __and_< is_convertible::pointer, pointer>, __not_> >; // Constructors. /// Default constructor, creates a unique_ptr that owns nothing. template > constexpr unique_ptr() noexcept : _M_t() { } /** Takes ownership of a pointer. * * @param __p A pointer to an object of @c element_type * * The deleter will be value-initialized. */ template > explicit unique_ptr(pointer __p) noexcept : _M_t(__p) { } /** Takes ownership of a pointer. * * @param __p A pointer to an object of @c element_type * @param __d A reference to a deleter. * * The deleter will be initialized with @p __d */ unique_ptr(pointer __p, typename conditional::value, deleter_type, const deleter_type&>::type __d) noexcept : _M_t(__p, __d) { } /** Takes ownership of a pointer. * * @param __p A pointer to an object of @c element_type * @param __d An rvalue reference to a deleter. * * The deleter will be initialized with @p std::move(__d) */ unique_ptr(pointer __p, typename remove_reference::type&& __d) noexcept : _M_t(std::move(__p), std::move(__d)) { static_assert(!std::is_reference::value, "rvalue deleter bound to reference"); } /// Creates a unique_ptr that owns nothing. template > constexpr unique_ptr(nullptr_t) noexcept : _M_t() { } // Move constructors. /// Move constructor. unique_ptr(unique_ptr&& __u) noexcept : _M_t(__u.release(), std::forward(__u.get_deleter())) { } /** @brief Converting constructor from another type * * Requires that the pointer owned by @p __u is convertible to the * type of pointer owned by this object, @p __u does not own an array, * and @p __u has a compatible deleter type. */ template, typename conditional::value, is_same<_Ep, _Dp>, is_convertible<_Ep, _Dp>>::type>> unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter())) { } #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" /// Converting constructor from @c auto_ptr template, is_same<_Dp, default_delete<_Tp>>>> unique_ptr(auto_ptr<_Up>&& __u) noexcept; #pragma GCC diagnostic pop #endif /// Destructor, invokes the deleter if the stored pointer is not null. ~unique_ptr() noexcept { auto& __ptr = _M_t._M_ptr(); if (__ptr != nullptr) get_deleter()(__ptr); __ptr = pointer(); } // Assignment. /** @brief Move assignment operator. * * @param __u The object to transfer ownership from. * * Invokes the deleter first if this object owns a pointer. */ unique_ptr& operator=(unique_ptr&& __u) noexcept { reset(__u.release()); get_deleter() = std::forward(__u.get_deleter()); return *this; } /** @brief Assignment from another type. * * @param __u The object to transfer ownership from, which owns a * convertible pointer to a non-array object. * * Invokes the deleter first if this object owns a pointer. */ template typename enable_if< __and_< __safe_conversion_up<_Up, _Ep>, is_assignable >::value, unique_ptr&>::type operator=(unique_ptr<_Up, _Ep>&& __u) noexcept { reset(__u.release()); get_deleter() = std::forward<_Ep>(__u.get_deleter()); return *this; } /// Reset the %unique_ptr to empty, invoking the deleter if necessary. unique_ptr& operator=(nullptr_t) noexcept { reset(); return *this; } // Observers. /// Dereference the stored pointer. typename add_lvalue_reference::type operator*() const { __glibcxx_assert(get() != pointer()); return *get(); } /// Return the stored pointer. pointer operator->() const noexcept { _GLIBCXX_DEBUG_PEDASSERT(get() != pointer()); return get(); } /// Return the stored pointer. pointer get() const noexcept { return _M_t._M_ptr(); } /// Return a reference to the stored deleter. deleter_type& get_deleter() noexcept { return _M_t._M_deleter(); } /// Return a reference to the stored deleter. const deleter_type& get_deleter() const noexcept { return _M_t._M_deleter(); } /// Return @c true if the stored pointer is not null. explicit operator bool() const noexcept { return get() == pointer() ? false : true; } // Modifiers. /// Release ownership of any stored pointer. pointer release() noexcept { pointer __p = get(); _M_t._M_ptr() = pointer(); return __p; } /** @brief Replace the stored pointer. * * @param __p The new pointer to store. * * The deleter will be invoked if a pointer is already owned. */ void reset(pointer __p = pointer()) noexcept { using std::swap; swap(_M_t._M_ptr(), __p); if (__p != pointer()) get_deleter()(__p); } /// Exchange the pointer and deleter with another object. void swap(unique_ptr& __u) noexcept { static_assert(__is_swappable<_Dp>::value, "deleter must be swappable"); _M_t.swap(__u._M_t); } // Disable copy from lvalue. unique_ptr(const unique_ptr&) = delete; unique_ptr& operator=(const unique_ptr&) = delete; }; /// 20.7.1.3 unique_ptr for array objects with a runtime length // [unique.ptr.runtime] // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 740 - omit specialization for array objects with a compile time length template class unique_ptr<_Tp[], _Dp> { template using _DeleterConstraint = typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type; __uniq_ptr_impl<_Tp, _Dp> _M_t; template using __remove_cv = typename remove_cv<_Up>::type; // like is_base_of<_Tp, _Up> but false if unqualified types are the same template using __is_derived_Tp = __and_< is_base_of<_Tp, _Up>, __not_, __remove_cv<_Up>>> >; public: using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer; using element_type = _Tp; using deleter_type = _Dp; // helper template for detecting a safe conversion from another // unique_ptr template, typename _UP_pointer = typename _UPtr::pointer, typename _UP_element_type = typename _UPtr::element_type> using __safe_conversion_up = __and_< is_array<_Up>, is_same, is_same<_UP_pointer, _UP_element_type*>, is_convertible<_UP_element_type(*)[], element_type(*)[]> >; // helper template for detecting a safe conversion from a raw pointer template using __safe_conversion_raw = __and_< __or_<__or_, is_same<_Up, nullptr_t>>, __and_, is_same, is_convertible< typename remove_pointer<_Up>::type(*)[], element_type(*)[]> > > >; // Constructors. /// Default constructor, creates a unique_ptr that owns nothing. template > constexpr unique_ptr() noexcept : _M_t() { } /** Takes ownership of a pointer. * * @param __p A pointer to an array of a type safely convertible * to an array of @c element_type * * The deleter will be value-initialized. */ template, typename = typename enable_if< __safe_conversion_raw<_Up>::value, bool>::type> explicit unique_ptr(_Up __p) noexcept : _M_t(__p) { } /** Takes ownership of a pointer. * * @param __p A pointer to an array of a type safely convertible * to an array of @c element_type * @param __d A reference to a deleter. * * The deleter will be initialized with @p __d */ template::value, bool>::type> unique_ptr(_Up __p, typename conditional::value, deleter_type, const deleter_type&>::type __d) noexcept : _M_t(__p, __d) { } /** Takes ownership of a pointer. * * @param __p A pointer to an array of a type safely convertible * to an array of @c element_type * @param __d A reference to a deleter. * * The deleter will be initialized with @p std::move(__d) */ template::value, bool>::type> unique_ptr(_Up __p, typename remove_reference::type&& __d) noexcept : _M_t(std::move(__p), std::move(__d)) { static_assert(!is_reference::value, "rvalue deleter bound to reference"); } /// Move constructor. unique_ptr(unique_ptr&& __u) noexcept : _M_t(__u.release(), std::forward(__u.get_deleter())) { } /// Creates a unique_ptr that owns nothing. template > constexpr unique_ptr(nullptr_t) noexcept : _M_t() { } template, typename conditional::value, is_same<_Ep, _Dp>, is_convertible<_Ep, _Dp>>::type>> unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter())) { } /// Destructor, invokes the deleter if the stored pointer is not null. ~unique_ptr() { auto& __ptr = _M_t._M_ptr(); if (__ptr != nullptr) get_deleter()(__ptr); __ptr = pointer(); } // Assignment. /** @brief Move assignment operator. * * @param __u The object to transfer ownership from. * * Invokes the deleter first if this object owns a pointer. */ unique_ptr& operator=(unique_ptr&& __u) noexcept { reset(__u.release()); get_deleter() = std::forward(__u.get_deleter()); return *this; } /** @brief Assignment from another type. * * @param __u The object to transfer ownership from, which owns a * convertible pointer to an array object. * * Invokes the deleter first if this object owns a pointer. */ template typename enable_if<__and_<__safe_conversion_up<_Up, _Ep>, is_assignable >::value, unique_ptr&>::type operator=(unique_ptr<_Up, _Ep>&& __u) noexcept { reset(__u.release()); get_deleter() = std::forward<_Ep>(__u.get_deleter()); return *this; } /// Reset the %unique_ptr to empty, invoking the deleter if necessary. unique_ptr& operator=(nullptr_t) noexcept { reset(); return *this; } // Observers. /// Access an element of owned array. typename std::add_lvalue_reference::type operator[](size_t __i) const { __glibcxx_assert(get() != pointer()); return get()[__i]; } /// Return the stored pointer. pointer get() const noexcept { return _M_t._M_ptr(); } /// Return a reference to the stored deleter. deleter_type& get_deleter() noexcept { return _M_t._M_deleter(); } /// Return a reference to the stored deleter. const deleter_type& get_deleter() const noexcept { return _M_t._M_deleter(); } /// Return @c true if the stored pointer is not null. explicit operator bool() const noexcept { return get() == pointer() ? false : true; } // Modifiers. /// Release ownership of any stored pointer. pointer release() noexcept { pointer __p = get(); _M_t._M_ptr() = pointer(); return __p; } /** @brief Replace the stored pointer. * * @param __p The new pointer to store. * * The deleter will be invoked if a pointer is already owned. */ template , __and_, is_pointer<_Up>, is_convertible< typename remove_pointer<_Up>::type(*)[], element_type(*)[] > > > >> void reset(_Up __p) noexcept { pointer __ptr = __p; using std::swap; swap(_M_t._M_ptr(), __ptr); if (__ptr != nullptr) get_deleter()(__ptr); } void reset(nullptr_t = nullptr) noexcept { reset(pointer()); } /// Exchange the pointer and deleter with another object. void swap(unique_ptr& __u) noexcept { static_assert(__is_swappable<_Dp>::value, "deleter must be swappable"); _M_t.swap(__u._M_t); } // Disable copy from lvalue. unique_ptr(const unique_ptr&) = delete; unique_ptr& operator=(const unique_ptr&) = delete; }; template inline #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 // Constrained free swap overload, see p0185r1 typename enable_if<__is_swappable<_Dp>::value>::type #else void #endif swap(unique_ptr<_Tp, _Dp>& __x, unique_ptr<_Tp, _Dp>& __y) noexcept { __x.swap(__y); } #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 template typename enable_if::value>::type swap(unique_ptr<_Tp, _Dp>&, unique_ptr<_Tp, _Dp>&) = delete; #endif template inline bool operator==(const unique_ptr<_Tp, _Dp>& __x, const unique_ptr<_Up, _Ep>& __y) { return __x.get() == __y.get(); } template inline bool operator==(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept { return !__x; } template inline bool operator==(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept { return !__x; } template inline bool operator!=(const unique_ptr<_Tp, _Dp>& __x, const unique_ptr<_Up, _Ep>& __y) { return __x.get() != __y.get(); } template inline bool operator!=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept { return (bool)__x; } template inline bool operator!=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept { return (bool)__x; } template inline bool operator<(const unique_ptr<_Tp, _Dp>& __x, const unique_ptr<_Up, _Ep>& __y) { typedef typename std::common_type::pointer, typename unique_ptr<_Up, _Ep>::pointer>::type _CT; return std::less<_CT>()(__x.get(), __y.get()); } template inline bool operator<(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) { return std::less::pointer>()(__x.get(), nullptr); } template inline bool operator<(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) { return std::less::pointer>()(nullptr, __x.get()); } template inline bool operator<=(const unique_ptr<_Tp, _Dp>& __x, const unique_ptr<_Up, _Ep>& __y) { return !(__y < __x); } template inline bool operator<=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) { return !(nullptr < __x); } template inline bool operator<=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) { return !(__x < nullptr); } template inline bool operator>(const unique_ptr<_Tp, _Dp>& __x, const unique_ptr<_Up, _Ep>& __y) { return (__y < __x); } template inline bool operator>(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) { return std::less::pointer>()(nullptr, __x.get()); } template inline bool operator>(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) { return std::less::pointer>()(__x.get(), nullptr); } template inline bool operator>=(const unique_ptr<_Tp, _Dp>& __x, const unique_ptr<_Up, _Ep>& __y) { return !(__x < __y); } template inline bool operator>=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) { return !(__x < nullptr); } template inline bool operator>=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) { return !(nullptr < __x); } /// std::hash specialization for unique_ptr. template struct hash> : public __hash_base>, private __poison_hash::pointer> { size_t operator()(const unique_ptr<_Tp, _Dp>& __u) const noexcept { typedef unique_ptr<_Tp, _Dp> _UP; return std::hash()(__u.get()); } }; #if __cplusplus > 201103L #define __cpp_lib_make_unique 201304 template struct _MakeUniq { typedef unique_ptr<_Tp> __single_object; }; template struct _MakeUniq<_Tp[]> { typedef unique_ptr<_Tp[]> __array; }; template struct _MakeUniq<_Tp[_Bound]> { struct __invalid_type { }; }; /// std::make_unique for single objects template inline typename _MakeUniq<_Tp>::__single_object make_unique(_Args&&... __args) { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); } /// std::make_unique for arrays of unknown bound template inline typename _MakeUniq<_Tp>::__array make_unique(size_t __num) { return unique_ptr<_Tp>(new remove_extent_t<_Tp>[__num]()); } /// Disable std::make_unique for arrays of known bound template inline typename _MakeUniq<_Tp>::__invalid_type make_unique(_Args&&...) = delete; #endif // @} group pointer_abstractions _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _UNIQUE_PTR_H */ PK!NԐM&M&8/bits/unordered_map.hnu[// unordered_map implementation -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/unordered_map.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{unordered_map} */ #ifndef _UNORDERED_MAP_H #define _UNORDERED_MAP_H namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER /// Base types for unordered_map. template using __umap_traits = __detail::_Hashtable_traits<_Cache, false, true>; template, typename _Pred = std::equal_to<_Key>, typename _Alloc = std::allocator >, typename _Tr = __umap_traits<__cache_default<_Key, _Hash>::value>> using __umap_hashtable = _Hashtable<_Key, std::pair, _Alloc, __detail::_Select1st, _Pred, _Hash, __detail::_Mod_range_hashing, __detail::_Default_ranged_hash, __detail::_Prime_rehash_policy, _Tr>; /// Base types for unordered_multimap. template using __ummap_traits = __detail::_Hashtable_traits<_Cache, false, false>; template, typename _Pred = std::equal_to<_Key>, typename _Alloc = std::allocator >, typename _Tr = __ummap_traits<__cache_default<_Key, _Hash>::value>> using __ummap_hashtable = _Hashtable<_Key, std::pair, _Alloc, __detail::_Select1st, _Pred, _Hash, __detail::_Mod_range_hashing, __detail::_Default_ranged_hash, __detail::_Prime_rehash_policy, _Tr>; template class unordered_multimap; /** * @brief A standard container composed of unique keys (containing * at most one of each key value) that associates values of another type * with the keys. * * @ingroup unordered_associative_containers * * @tparam _Key Type of key objects. * @tparam _Tp Type of mapped objects. * @tparam _Hash Hashing function object type, defaults to hash<_Value>. * @tparam _Pred Predicate function object type, defaults * to equal_to<_Value>. * @tparam _Alloc Allocator type, defaults to * std::allocator>. * * Meets the requirements of a container, and * unordered associative container * * The resulting value type of the container is std::pair. * * Base is _Hashtable, dispatched at compile time via template * alias __umap_hashtable. */ template, typename _Pred = equal_to<_Key>, typename _Alloc = allocator>> class unordered_map { typedef __umap_hashtable<_Key, _Tp, _Hash, _Pred, _Alloc> _Hashtable; _Hashtable _M_h; public: // typedefs: //@{ /// Public typedefs. typedef typename _Hashtable::key_type key_type; typedef typename _Hashtable::value_type value_type; typedef typename _Hashtable::mapped_type mapped_type; typedef typename _Hashtable::hasher hasher; typedef typename _Hashtable::key_equal key_equal; typedef typename _Hashtable::allocator_type allocator_type; //@} //@{ /// Iterator-related typedefs. typedef typename _Hashtable::pointer pointer; typedef typename _Hashtable::const_pointer const_pointer; typedef typename _Hashtable::reference reference; typedef typename _Hashtable::const_reference const_reference; typedef typename _Hashtable::iterator iterator; typedef typename _Hashtable::const_iterator const_iterator; typedef typename _Hashtable::local_iterator local_iterator; typedef typename _Hashtable::const_local_iterator const_local_iterator; typedef typename _Hashtable::size_type size_type; typedef typename _Hashtable::difference_type difference_type; //@} #if __cplusplus > 201402L using node_type = typename _Hashtable::node_type; using insert_return_type = typename _Hashtable::insert_return_type; #endif //construct/destroy/copy /// Default constructor. unordered_map() = default; /** * @brief Default constructor creates no elements. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. */ explicit unordered_map(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__n, __hf, __eql, __a) { } /** * @brief Builds an %unordered_map from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_map consisting of copies of the elements from * [__first,__last). This is linear in N (where N is * distance(__first,__last)). */ template unordered_map(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__first, __last, __n, __hf, __eql, __a) { } /// Copy constructor. unordered_map(const unordered_map&) = default; /// Move constructor. unordered_map(unordered_map&&) = default; /** * @brief Creates an %unordered_map with no elements. * @param __a An allocator object. */ explicit unordered_map(const allocator_type& __a) : _M_h(__a) { } /* * @brief Copy constructor with allocator argument. * @param __uset Input %unordered_map to copy. * @param __a An allocator object. */ unordered_map(const unordered_map& __umap, const allocator_type& __a) : _M_h(__umap._M_h, __a) { } /* * @brief Move constructor with allocator argument. * @param __uset Input %unordered_map to move. * @param __a An allocator object. */ unordered_map(unordered_map&& __umap, const allocator_type& __a) : _M_h(std::move(__umap._M_h), __a) { } /** * @brief Builds an %unordered_map from an initializer_list. * @param __l An initializer_list. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_map consisting of copies of the elements in the * list. This is linear in N (where N is @a __l.size()). */ unordered_map(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__l, __n, __hf, __eql, __a) { } unordered_map(size_type __n, const allocator_type& __a) : unordered_map(__n, hasher(), key_equal(), __a) { } unordered_map(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_map(__n, __hf, key_equal(), __a) { } template unordered_map(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_map(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_map(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_map(__first, __last, __n, __hf, key_equal(), __a) { } unordered_map(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_map(__l, __n, hasher(), key_equal(), __a) { } unordered_map(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_map(__l, __n, __hf, key_equal(), __a) { } /// Copy assignment operator. unordered_map& operator=(const unordered_map&) = default; /// Move assignment operator. unordered_map& operator=(unordered_map&&) = default; /** * @brief %Unordered_map list assignment operator. * @param __l An initializer_list. * * This function fills an %unordered_map with copies of the elements in * the initializer list @a __l. * * Note that the assignment completely changes the %unordered_map and * that the resulting %unordered_map's size is the same as the number * of elements assigned. */ unordered_map& operator=(initializer_list __l) { _M_h = __l; return *this; } /// Returns the allocator object used by the %unordered_map. allocator_type get_allocator() const noexcept { return _M_h.get_allocator(); } // size and capacity: /// Returns true if the %unordered_map is empty. bool empty() const noexcept { return _M_h.empty(); } /// Returns the size of the %unordered_map. size_type size() const noexcept { return _M_h.size(); } /// Returns the maximum size of the %unordered_map. size_type max_size() const noexcept { return _M_h.max_size(); } // iterators. /** * Returns a read/write iterator that points to the first element in the * %unordered_map. */ iterator begin() noexcept { return _M_h.begin(); } //@{ /** * Returns a read-only (constant) iterator that points to the first * element in the %unordered_map. */ const_iterator begin() const noexcept { return _M_h.begin(); } const_iterator cbegin() const noexcept { return _M_h.begin(); } //@} /** * Returns a read/write iterator that points one past the last element in * the %unordered_map. */ iterator end() noexcept { return _M_h.end(); } //@{ /** * Returns a read-only (constant) iterator that points one past the last * element in the %unordered_map. */ const_iterator end() const noexcept { return _M_h.end(); } const_iterator cend() const noexcept { return _M_h.end(); } //@} // modifiers. /** * @brief Attempts to build and insert a std::pair into the * %unordered_map. * * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * * @return A pair, of which the first element is an iterator that points * to the possibly inserted pair, and the second is a bool that * is true if the pair was actually inserted. * * This function attempts to build and insert a (key, value) %pair into * the %unordered_map. * An %unordered_map relies on unique keys and thus a %pair is only * inserted if its first element (the key) is not already present in the * %unordered_map. * * Insertion requires amortized constant time. */ template std::pair emplace(_Args&&... __args) { return _M_h.emplace(std::forward<_Args>(__args)...); } /** * @brief Attempts to build and insert a std::pair into the * %unordered_map. * * @param __pos An iterator that serves as a hint as to where the pair * should be inserted. * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * @return An iterator that points to the element with key of the * std::pair built from @a __args (may or may not be that * std::pair). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument emplace() * does. * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires amortized constant time. */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_h.emplace_hint(__pos, std::forward<_Args>(__args)...); } #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_h.extract(__pos); } /// Extract a node. node_type extract(const key_type& __key) { return _M_h.extract(__key); } /// Re-insert an extracted node. insert_return_type insert(node_type&& __nh) { return _M_h._M_reinsert_node(std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator, node_type&& __nh) { return _M_h._M_reinsert_node(std::move(__nh)).position; } #define __cpp_lib_unordered_map_try_emplace 201411 /** * @brief Attempts to build and insert a std::pair into the * %unordered_map. * * @param __k Key to use for finding a possibly existing pair in * the unordered_map. * @param __args Arguments used to generate the .second for a * new pair instance. * * @return A pair, of which the first element is an iterator that points * to the possibly inserted pair, and the second is a bool that * is true if the pair was actually inserted. * * This function attempts to build and insert a (key, value) %pair into * the %unordered_map. * An %unordered_map relies on unique keys and thus a %pair is only * inserted if its first element (the key) is not already present in the * %unordered_map. * If a %pair is not inserted, this function has no effect. * * Insertion requires amortized constant time. */ template pair try_emplace(const key_type& __k, _Args&&... __args) { iterator __i = find(__k); if (__i == end()) { __i = emplace(std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple( std::forward<_Args>(__args)...)) .first; return {__i, true}; } return {__i, false}; } // move-capable overload template pair try_emplace(key_type&& __k, _Args&&... __args) { iterator __i = find(__k); if (__i == end()) { __i = emplace(std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple( std::forward<_Args>(__args)...)) .first; return {__i, true}; } return {__i, false}; } /** * @brief Attempts to build and insert a std::pair into the * %unordered_map. * * @param __hint An iterator that serves as a hint as to where the pair * should be inserted. * @param __k Key to use for finding a possibly existing pair in * the unordered_map. * @param __args Arguments used to generate the .second for a * new pair instance. * @return An iterator that points to the element with key of the * std::pair built from @a __args (may or may not be that * std::pair). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument emplace() * does. However, if insertion did not take place, * this function has no effect. * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires amortized constant time. */ template iterator try_emplace(const_iterator __hint, const key_type& __k, _Args&&... __args) { iterator __i = find(__k); if (__i == end()) __i = emplace_hint(__hint, std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple( std::forward<_Args>(__args)...)); return __i; } // move-capable overload template iterator try_emplace(const_iterator __hint, key_type&& __k, _Args&&... __args) { iterator __i = find(__k); if (__i == end()) __i = emplace_hint(__hint, std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple( std::forward<_Args>(__args)...)); return __i; } #endif // C++17 //@{ /** * @brief Attempts to insert a std::pair into the %unordered_map. * @param __x Pair to be inserted (see std::make_pair for easy * creation of pairs). * * @return A pair, of which the first element is an iterator that * points to the possibly inserted pair, and the second is * a bool that is true if the pair was actually inserted. * * This function attempts to insert a (key, value) %pair into the * %unordered_map. An %unordered_map relies on unique keys and thus a * %pair is only inserted if its first element (the key) is not already * present in the %unordered_map. * * Insertion requires amortized constant time. */ std::pair insert(const value_type& __x) { return _M_h.insert(__x); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init std::pair insert(value_type&& __x) { return _M_h.insert(std::move(__x)); } template __enable_if_t::value, pair> insert(_Pair&& __x) { return _M_h.emplace(std::forward<_Pair>(__x)); } //@} //@{ /** * @brief Attempts to insert a std::pair into the %unordered_map. * @param __hint An iterator that serves as a hint as to where the * pair should be inserted. * @param __x Pair to be inserted (see std::make_pair for easy creation * of pairs). * @return An iterator that points to the element with key of * @a __x (may or may not be the %pair passed in). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument insert() * does. Note that the first parameter is only a hint and can * potentially improve the performance of the insertion process. A bad * hint would cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires amortized constant time. */ iterator insert(const_iterator __hint, const value_type& __x) { return _M_h.insert(__hint, __x); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __hint, value_type&& __x) { return _M_h.insert(__hint, std::move(__x)); } template __enable_if_t::value, iterator> insert(const_iterator __hint, _Pair&& __x) { return _M_h.emplace_hint(__hint, std::forward<_Pair>(__x)); } //@} /** * @brief A template function that attempts to insert a range of * elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_h.insert(__first, __last); } /** * @brief Attempts to insert a list of elements into the %unordered_map. * @param __l A std::initializer_list of elements * to be inserted. * * Complexity similar to that of the range constructor. */ void insert(initializer_list __l) { _M_h.insert(__l); } #if __cplusplus > 201402L #define __cpp_lib_unordered_map_insertion 201411 /** * @brief Attempts to insert a std::pair into the %unordered_map. * @param __k Key to use for finding a possibly existing pair in * the map. * @param __obj Argument used to generate the .second for a pair * instance. * * @return A pair, of which the first element is an iterator that * points to the possibly inserted pair, and the second is * a bool that is true if the pair was actually inserted. * * This function attempts to insert a (key, value) %pair into the * %unordered_map. An %unordered_map relies on unique keys and thus a * %pair is only inserted if its first element (the key) is not already * present in the %unordered_map. * If the %pair was already in the %unordered_map, the .second of * the %pair is assigned from __obj. * * Insertion requires amortized constant time. */ template pair insert_or_assign(const key_type& __k, _Obj&& __obj) { iterator __i = find(__k); if (__i == end()) { __i = emplace(std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple(std::forward<_Obj>(__obj))) .first; return {__i, true}; } (*__i).second = std::forward<_Obj>(__obj); return {__i, false}; } // move-capable overload template pair insert_or_assign(key_type&& __k, _Obj&& __obj) { iterator __i = find(__k); if (__i == end()) { __i = emplace(std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple(std::forward<_Obj>(__obj))) .first; return {__i, true}; } (*__i).second = std::forward<_Obj>(__obj); return {__i, false}; } /** * @brief Attempts to insert a std::pair into the %unordered_map. * @param __hint An iterator that serves as a hint as to where the * pair should be inserted. * @param __k Key to use for finding a possibly existing pair in * the unordered_map. * @param __obj Argument used to generate the .second for a pair * instance. * @return An iterator that points to the element with key of * @a __x (may or may not be the %pair passed in). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument insert() * does. * If the %pair was already in the %unordered map, the .second of * the %pair is assigned from __obj. * Note that the first parameter is only a hint and can * potentially improve the performance of the insertion process. A bad * hint would cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires amortized constant time. */ template iterator insert_or_assign(const_iterator __hint, const key_type& __k, _Obj&& __obj) { iterator __i = find(__k); if (__i == end()) { return emplace_hint(__hint, std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple( std::forward<_Obj>(__obj))); } (*__i).second = std::forward<_Obj>(__obj); return __i; } // move-capable overload template iterator insert_or_assign(const_iterator __hint, key_type&& __k, _Obj&& __obj) { iterator __i = find(__k); if (__i == end()) { return emplace_hint(__hint, std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple( std::forward<_Obj>(__obj))); } (*__i).second = std::forward<_Obj>(__obj); return __i; } #endif //@{ /** * @brief Erases an element from an %unordered_map. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a __position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given iterator, * from an %unordered_map. * Note that this function only erases the element, and that if the * element is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __position) { return _M_h.erase(__position); } // LWG 2059. iterator erase(iterator __position) { return _M_h.erase(__position); } //@} /** * @brief Erases elements according to the provided key. * @param __x Key of element to be erased. * @return The number of elements erased. * * This function erases all the elements located by the given key from * an %unordered_map. For an %unordered_map the result of this function * can only be 0 (not present) or 1 (present). * Note that this function only erases the element, and that if the * element is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_h.erase(__x); } /** * @brief Erases a [__first,__last) range of elements from an * %unordered_map. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * @return The iterator @a __last. * * This function erases a sequence of elements from an %unordered_map. * Note that this function only erases the elements, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __first, const_iterator __last) { return _M_h.erase(__first, __last); } /** * Erases all elements in an %unordered_map. * Note that this function only erases the elements, and that if the * elements themselves are pointers, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ void clear() noexcept { _M_h.clear(); } /** * @brief Swaps data with another %unordered_map. * @param __x An %unordered_map of the same element and allocator * types. * * This exchanges the elements between two %unordered_map in constant * time. * Note that the global std::swap() function is specialized such that * std::swap(m1,m2) will feed to this function. */ void swap(unordered_map& __x) noexcept( noexcept(_M_h.swap(__x._M_h)) ) { _M_h.swap(__x._M_h); } #if __cplusplus > 201402L template friend class std::_Hash_merge_helper; template void merge(unordered_map<_Key, _Tp, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_unique(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_map<_Key, _Tp, _H2, _P2, _Alloc>&& __source) { merge(__source); } template void merge(unordered_multimap<_Key, _Tp, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_unique(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_multimap<_Key, _Tp, _H2, _P2, _Alloc>&& __source) { merge(__source); } #endif // C++17 // observers. /// Returns the hash functor object with which the %unordered_map was /// constructed. hasher hash_function() const { return _M_h.hash_function(); } /// Returns the key comparison object with which the %unordered_map was /// constructed. key_equal key_eq() const { return _M_h.key_eq(); } // lookup. //@{ /** * @brief Tries to locate an element in an %unordered_map. * @param __x Key to be located. * @return Iterator pointing to sought-after element, or end() if not * found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after element. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_h.find(__x); } const_iterator find(const key_type& __x) const { return _M_h.find(__x); } //@} /** * @brief Finds the number of elements. * @param __x Key to count. * @return Number of elements with specified key. * * This function only makes sense for %unordered_multimap; for * %unordered_map the result will either be 0 (not present) or 1 * (present). */ size_type count(const key_type& __x) const { return _M_h.count(__x); } //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. * * This function probably only makes sense for %unordered_multimap. */ std::pair equal_range(const key_type& __x) { return _M_h.equal_range(__x); } std::pair equal_range(const key_type& __x) const { return _M_h.equal_range(__x); } //@} //@{ /** * @brief Subscript ( @c [] ) access to %unordered_map data. * @param __k The key for which data should be retrieved. * @return A reference to the data of the (key,data) %pair. * * Allows for easy lookup with the subscript ( @c [] )operator. Returns * data associated with the key specified in subscript. If the key does * not exist, a pair with that key is created using default values, which * is then returned. * * Lookup requires constant time. */ mapped_type& operator[](const key_type& __k) { return _M_h[__k]; } mapped_type& operator[](key_type&& __k) { return _M_h[std::move(__k)]; } //@} //@{ /** * @brief Access to %unordered_map data. * @param __k The key for which data should be retrieved. * @return A reference to the data whose key is equal to @a __k, if * such a data is present in the %unordered_map. * @throw std::out_of_range If no such data is present. */ mapped_type& at(const key_type& __k) { return _M_h.at(__k); } const mapped_type& at(const key_type& __k) const { return _M_h.at(__k); } //@} // bucket interface. /// Returns the number of buckets of the %unordered_map. size_type bucket_count() const noexcept { return _M_h.bucket_count(); } /// Returns the maximum number of buckets of the %unordered_map. size_type max_bucket_count() const noexcept { return _M_h.max_bucket_count(); } /* * @brief Returns the number of elements in a given bucket. * @param __n A bucket index. * @return The number of elements in the bucket. */ size_type bucket_size(size_type __n) const { return _M_h.bucket_size(__n); } /* * @brief Returns the bucket index of a given element. * @param __key A key instance. * @return The key bucket index. */ size_type bucket(const key_type& __key) const { return _M_h.bucket(__key); } /** * @brief Returns a read/write iterator pointing to the first bucket * element. * @param __n The bucket index. * @return A read/write local iterator. */ local_iterator begin(size_type __n) { return _M_h.begin(__n); } //@{ /** * @brief Returns a read-only (constant) iterator pointing to the first * bucket element. * @param __n The bucket index. * @return A read-only local iterator. */ const_local_iterator begin(size_type __n) const { return _M_h.begin(__n); } const_local_iterator cbegin(size_type __n) const { return _M_h.cbegin(__n); } //@} /** * @brief Returns a read/write iterator pointing to one past the last * bucket elements. * @param __n The bucket index. * @return A read/write local iterator. */ local_iterator end(size_type __n) { return _M_h.end(__n); } //@{ /** * @brief Returns a read-only (constant) iterator pointing to one past * the last bucket elements. * @param __n The bucket index. * @return A read-only local iterator. */ const_local_iterator end(size_type __n) const { return _M_h.end(__n); } const_local_iterator cend(size_type __n) const { return _M_h.cend(__n); } //@} // hash policy. /// Returns the average number of elements per bucket. float load_factor() const noexcept { return _M_h.load_factor(); } /// Returns a positive number that the %unordered_map tries to keep the /// load factor less than or equal to. float max_load_factor() const noexcept { return _M_h.max_load_factor(); } /** * @brief Change the %unordered_map maximum load factor. * @param __z The new maximum load factor. */ void max_load_factor(float __z) { _M_h.max_load_factor(__z); } /** * @brief May rehash the %unordered_map. * @param __n The new number of buckets. * * Rehash will occur only if the new number of buckets respect the * %unordered_map maximum load factor. */ void rehash(size_type __n) { _M_h.rehash(__n); } /** * @brief Prepare the %unordered_map for a specified number of * elements. * @param __n Number of elements required. * * Same as rehash(ceil(n / max_load_factor())). */ void reserve(size_type __n) { _M_h.reserve(__n); } template friend bool operator==(const unordered_map<_Key1, _Tp1, _Hash1, _Pred1, _Alloc1>&, const unordered_map<_Key1, _Tp1, _Hash1, _Pred1, _Alloc1>&); }; #if __cpp_deduction_guides >= 201606 template>, typename _Pred = equal_to<__iter_key_t<_InputIterator>>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, typename unordered_map::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Key>, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> unordered_map(initializer_list>, typename unordered_map::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_map<_Key, _Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, typename unordered_map::size_type, _Allocator) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, _Allocator) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, typename unordered_map::size_type, _Hash, _Allocator) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template> unordered_map(initializer_list>, typename unordered_map::size_type, _Allocator) -> unordered_map<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_map(initializer_list>, _Allocator) -> unordered_map<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_map(initializer_list>, typename unordered_map::size_type, _Hash, _Allocator) -> unordered_map<_Key, _Tp, _Hash, equal_to<_Key>, _Allocator>; #endif /** * @brief A standard container composed of equivalent keys * (possibly containing multiple of each key value) that associates * values of another type with the keys. * * @ingroup unordered_associative_containers * * @tparam _Key Type of key objects. * @tparam _Tp Type of mapped objects. * @tparam _Hash Hashing function object type, defaults to hash<_Value>. * @tparam _Pred Predicate function object type, defaults * to equal_to<_Value>. * @tparam _Alloc Allocator type, defaults to * std::allocator>. * * Meets the requirements of a container, and * unordered associative container * * The resulting value type of the container is std::pair. * * Base is _Hashtable, dispatched at compile time via template * alias __ummap_hashtable. */ template, typename _Pred = equal_to<_Key>, typename _Alloc = allocator>> class unordered_multimap { typedef __ummap_hashtable<_Key, _Tp, _Hash, _Pred, _Alloc> _Hashtable; _Hashtable _M_h; public: // typedefs: //@{ /// Public typedefs. typedef typename _Hashtable::key_type key_type; typedef typename _Hashtable::value_type value_type; typedef typename _Hashtable::mapped_type mapped_type; typedef typename _Hashtable::hasher hasher; typedef typename _Hashtable::key_equal key_equal; typedef typename _Hashtable::allocator_type allocator_type; //@} //@{ /// Iterator-related typedefs. typedef typename _Hashtable::pointer pointer; typedef typename _Hashtable::const_pointer const_pointer; typedef typename _Hashtable::reference reference; typedef typename _Hashtable::const_reference const_reference; typedef typename _Hashtable::iterator iterator; typedef typename _Hashtable::const_iterator const_iterator; typedef typename _Hashtable::local_iterator local_iterator; typedef typename _Hashtable::const_local_iterator const_local_iterator; typedef typename _Hashtable::size_type size_type; typedef typename _Hashtable::difference_type difference_type; //@} #if __cplusplus > 201402L using node_type = typename _Hashtable::node_type; #endif //construct/destroy/copy /// Default constructor. unordered_multimap() = default; /** * @brief Default constructor creates no elements. * @param __n Mnimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. */ explicit unordered_multimap(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__n, __hf, __eql, __a) { } /** * @brief Builds an %unordered_multimap from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_multimap consisting of copies of the elements * from [__first,__last). This is linear in N (where N is * distance(__first,__last)). */ template unordered_multimap(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__first, __last, __n, __hf, __eql, __a) { } /// Copy constructor. unordered_multimap(const unordered_multimap&) = default; /// Move constructor. unordered_multimap(unordered_multimap&&) = default; /** * @brief Creates an %unordered_multimap with no elements. * @param __a An allocator object. */ explicit unordered_multimap(const allocator_type& __a) : _M_h(__a) { } /* * @brief Copy constructor with allocator argument. * @param __uset Input %unordered_multimap to copy. * @param __a An allocator object. */ unordered_multimap(const unordered_multimap& __ummap, const allocator_type& __a) : _M_h(__ummap._M_h, __a) { } /* * @brief Move constructor with allocator argument. * @param __uset Input %unordered_multimap to move. * @param __a An allocator object. */ unordered_multimap(unordered_multimap&& __ummap, const allocator_type& __a) : _M_h(std::move(__ummap._M_h), __a) { } /** * @brief Builds an %unordered_multimap from an initializer_list. * @param __l An initializer_list. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_multimap consisting of copies of the elements in * the list. This is linear in N (where N is @a __l.size()). */ unordered_multimap(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__l, __n, __hf, __eql, __a) { } unordered_multimap(size_type __n, const allocator_type& __a) : unordered_multimap(__n, hasher(), key_equal(), __a) { } unordered_multimap(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multimap(__n, __hf, key_equal(), __a) { } template unordered_multimap(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_multimap(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_multimap(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multimap(__first, __last, __n, __hf, key_equal(), __a) { } unordered_multimap(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_multimap(__l, __n, hasher(), key_equal(), __a) { } unordered_multimap(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multimap(__l, __n, __hf, key_equal(), __a) { } /// Copy assignment operator. unordered_multimap& operator=(const unordered_multimap&) = default; /// Move assignment operator. unordered_multimap& operator=(unordered_multimap&&) = default; /** * @brief %Unordered_multimap list assignment operator. * @param __l An initializer_list. * * This function fills an %unordered_multimap with copies of the * elements in the initializer list @a __l. * * Note that the assignment completely changes the %unordered_multimap * and that the resulting %unordered_multimap's size is the same as the * number of elements assigned. */ unordered_multimap& operator=(initializer_list __l) { _M_h = __l; return *this; } /// Returns the allocator object used by the %unordered_multimap. allocator_type get_allocator() const noexcept { return _M_h.get_allocator(); } // size and capacity: /// Returns true if the %unordered_multimap is empty. bool empty() const noexcept { return _M_h.empty(); } /// Returns the size of the %unordered_multimap. size_type size() const noexcept { return _M_h.size(); } /// Returns the maximum size of the %unordered_multimap. size_type max_size() const noexcept { return _M_h.max_size(); } // iterators. /** * Returns a read/write iterator that points to the first element in the * %unordered_multimap. */ iterator begin() noexcept { return _M_h.begin(); } //@{ /** * Returns a read-only (constant) iterator that points to the first * element in the %unordered_multimap. */ const_iterator begin() const noexcept { return _M_h.begin(); } const_iterator cbegin() const noexcept { return _M_h.begin(); } //@} /** * Returns a read/write iterator that points one past the last element in * the %unordered_multimap. */ iterator end() noexcept { return _M_h.end(); } //@{ /** * Returns a read-only (constant) iterator that points one past the last * element in the %unordered_multimap. */ const_iterator end() const noexcept { return _M_h.end(); } const_iterator cend() const noexcept { return _M_h.end(); } //@} // modifiers. /** * @brief Attempts to build and insert a std::pair into the * %unordered_multimap. * * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * * @return An iterator that points to the inserted pair. * * This function attempts to build and insert a (key, value) %pair into * the %unordered_multimap. * * Insertion requires amortized constant time. */ template iterator emplace(_Args&&... __args) { return _M_h.emplace(std::forward<_Args>(__args)...); } /** * @brief Attempts to build and insert a std::pair into the * %unordered_multimap. * * @param __pos An iterator that serves as a hint as to where the pair * should be inserted. * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * @return An iterator that points to the element with key of the * std::pair built from @a __args. * * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires amortized constant time. */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_h.emplace_hint(__pos, std::forward<_Args>(__args)...); } //@{ /** * @brief Inserts a std::pair into the %unordered_multimap. * @param __x Pair to be inserted (see std::make_pair for easy * creation of pairs). * * @return An iterator that points to the inserted pair. * * Insertion requires amortized constant time. */ iterator insert(const value_type& __x) { return _M_h.insert(__x); } iterator insert(value_type&& __x) { return _M_h.insert(std::move(__x)); } template __enable_if_t::value, iterator> insert(_Pair&& __x) { return _M_h.emplace(std::forward<_Pair>(__x)); } //@} //@{ /** * @brief Inserts a std::pair into the %unordered_multimap. * @param __hint An iterator that serves as a hint as to where the * pair should be inserted. * @param __x Pair to be inserted (see std::make_pair for easy creation * of pairs). * @return An iterator that points to the element with key of * @a __x (may or may not be the %pair passed in). * * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires amortized constant time. */ iterator insert(const_iterator __hint, const value_type& __x) { return _M_h.insert(__hint, __x); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __hint, value_type&& __x) { return _M_h.insert(__hint, std::move(__x)); } template __enable_if_t::value, iterator> insert(const_iterator __hint, _Pair&& __x) { return _M_h.emplace_hint(__hint, std::forward<_Pair>(__x)); } //@} /** * @brief A template function that attempts to insert a range of * elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_h.insert(__first, __last); } /** * @brief Attempts to insert a list of elements into the * %unordered_multimap. * @param __l A std::initializer_list of elements * to be inserted. * * Complexity similar to that of the range constructor. */ void insert(initializer_list __l) { _M_h.insert(__l); } #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_h.extract(__pos); } /// Extract a node. node_type extract(const key_type& __key) { return _M_h.extract(__key); } /// Re-insert an extracted node. iterator insert(node_type&& __nh) { return _M_h._M_reinsert_node_multi(cend(), std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator __hint, node_type&& __nh) { return _M_h._M_reinsert_node_multi(__hint, std::move(__nh)); } #endif // C++17 //@{ /** * @brief Erases an element from an %unordered_multimap. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a __position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given iterator, * from an %unordered_multimap. * Note that this function only erases the element, and that if the * element is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __position) { return _M_h.erase(__position); } // LWG 2059. iterator erase(iterator __position) { return _M_h.erase(__position); } //@} /** * @brief Erases elements according to the provided key. * @param __x Key of elements to be erased. * @return The number of elements erased. * * This function erases all the elements located by the given key from * an %unordered_multimap. * Note that this function only erases the element, and that if the * element is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_h.erase(__x); } /** * @brief Erases a [__first,__last) range of elements from an * %unordered_multimap. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * @return The iterator @a __last. * * This function erases a sequence of elements from an * %unordered_multimap. * Note that this function only erases the elements, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __first, const_iterator __last) { return _M_h.erase(__first, __last); } /** * Erases all elements in an %unordered_multimap. * Note that this function only erases the elements, and that if the * elements themselves are pointers, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ void clear() noexcept { _M_h.clear(); } /** * @brief Swaps data with another %unordered_multimap. * @param __x An %unordered_multimap of the same element and allocator * types. * * This exchanges the elements between two %unordered_multimap in * constant time. * Note that the global std::swap() function is specialized such that * std::swap(m1,m2) will feed to this function. */ void swap(unordered_multimap& __x) noexcept( noexcept(_M_h.swap(__x._M_h)) ) { _M_h.swap(__x._M_h); } #if __cplusplus > 201402L template friend class std::_Hash_merge_helper; template void merge(unordered_multimap<_Key, _Tp, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_multi(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_multimap<_Key, _Tp, _H2, _P2, _Alloc>&& __source) { merge(__source); } template void merge(unordered_map<_Key, _Tp, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_multi(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_map<_Key, _Tp, _H2, _P2, _Alloc>&& __source) { merge(__source); } #endif // C++17 // observers. /// Returns the hash functor object with which the %unordered_multimap /// was constructed. hasher hash_function() const { return _M_h.hash_function(); } /// Returns the key comparison object with which the %unordered_multimap /// was constructed. key_equal key_eq() const { return _M_h.key_eq(); } // lookup. //@{ /** * @brief Tries to locate an element in an %unordered_multimap. * @param __x Key to be located. * @return Iterator pointing to sought-after element, or end() if not * found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after element. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_h.find(__x); } const_iterator find(const key_type& __x) const { return _M_h.find(__x); } //@} /** * @brief Finds the number of elements. * @param __x Key to count. * @return Number of elements with specified key. */ size_type count(const key_type& __x) const { return _M_h.count(__x); } //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. */ std::pair equal_range(const key_type& __x) { return _M_h.equal_range(__x); } std::pair equal_range(const key_type& __x) const { return _M_h.equal_range(__x); } //@} // bucket interface. /// Returns the number of buckets of the %unordered_multimap. size_type bucket_count() const noexcept { return _M_h.bucket_count(); } /// Returns the maximum number of buckets of the %unordered_multimap. size_type max_bucket_count() const noexcept { return _M_h.max_bucket_count(); } /* * @brief Returns the number of elements in a given bucket. * @param __n A bucket index. * @return The number of elements in the bucket. */ size_type bucket_size(size_type __n) const { return _M_h.bucket_size(__n); } /* * @brief Returns the bucket index of a given element. * @param __key A key instance. * @return The key bucket index. */ size_type bucket(const key_type& __key) const { return _M_h.bucket(__key); } /** * @brief Returns a read/write iterator pointing to the first bucket * element. * @param __n The bucket index. * @return A read/write local iterator. */ local_iterator begin(size_type __n) { return _M_h.begin(__n); } //@{ /** * @brief Returns a read-only (constant) iterator pointing to the first * bucket element. * @param __n The bucket index. * @return A read-only local iterator. */ const_local_iterator begin(size_type __n) const { return _M_h.begin(__n); } const_local_iterator cbegin(size_type __n) const { return _M_h.cbegin(__n); } //@} /** * @brief Returns a read/write iterator pointing to one past the last * bucket elements. * @param __n The bucket index. * @return A read/write local iterator. */ local_iterator end(size_type __n) { return _M_h.end(__n); } //@{ /** * @brief Returns a read-only (constant) iterator pointing to one past * the last bucket elements. * @param __n The bucket index. * @return A read-only local iterator. */ const_local_iterator end(size_type __n) const { return _M_h.end(__n); } const_local_iterator cend(size_type __n) const { return _M_h.cend(__n); } //@} // hash policy. /// Returns the average number of elements per bucket. float load_factor() const noexcept { return _M_h.load_factor(); } /// Returns a positive number that the %unordered_multimap tries to keep /// the load factor less than or equal to. float max_load_factor() const noexcept { return _M_h.max_load_factor(); } /** * @brief Change the %unordered_multimap maximum load factor. * @param __z The new maximum load factor. */ void max_load_factor(float __z) { _M_h.max_load_factor(__z); } /** * @brief May rehash the %unordered_multimap. * @param __n The new number of buckets. * * Rehash will occur only if the new number of buckets respect the * %unordered_multimap maximum load factor. */ void rehash(size_type __n) { _M_h.rehash(__n); } /** * @brief Prepare the %unordered_multimap for a specified number of * elements. * @param __n Number of elements required. * * Same as rehash(ceil(n / max_load_factor())). */ void reserve(size_type __n) { _M_h.reserve(__n); } template friend bool operator==(const unordered_multimap<_Key1, _Tp1, _Hash1, _Pred1, _Alloc1>&, const unordered_multimap<_Key1, _Tp1, _Hash1, _Pred1, _Alloc1>&); }; #if __cpp_deduction_guides >= 201606 template>, typename _Pred = equal_to<__iter_key_t<_InputIterator>>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, unordered_multimap::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Key>, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> unordered_multimap(initializer_list>, unordered_multimap::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multimap<_Key, _Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, unordered_multimap::size_type, _Allocator) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, _Allocator) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, unordered_multimap::size_type, _Hash, _Allocator) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template> unordered_multimap(initializer_list>, unordered_multimap::size_type, _Allocator) -> unordered_multimap<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_multimap(initializer_list>, _Allocator) -> unordered_multimap<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_multimap(initializer_list>, unordered_multimap::size_type, _Hash, _Allocator) -> unordered_multimap<_Key, _Tp, _Hash, equal_to<_Key>, _Allocator>; #endif template inline void swap(unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline void swap(unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline bool operator==(const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return __x._M_h._M_equal(__y._M_h); } template inline bool operator!=(const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } template inline bool operator==(const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return __x._M_h._M_equal(__y._M_h); } template inline bool operator!=(const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } _GLIBCXX_END_NAMESPACE_CONTAINER #if __cplusplus > 201402L // Allow std::unordered_map access to internals of compatible maps. template struct _Hash_merge_helper< _GLIBCXX_STD_C::unordered_map<_Key, _Val, _Hash1, _Eq1, _Alloc>, _Hash2, _Eq2> { private: template using unordered_map = _GLIBCXX_STD_C::unordered_map<_Tp...>; template using unordered_multimap = _GLIBCXX_STD_C::unordered_multimap<_Tp...>; friend unordered_map<_Key, _Val, _Hash1, _Eq1, _Alloc>; static auto& _S_get_table(unordered_map<_Key, _Val, _Hash2, _Eq2, _Alloc>& __map) { return __map._M_h; } static auto& _S_get_table(unordered_multimap<_Key, _Val, _Hash2, _Eq2, _Alloc>& __map) { return __map._M_h; } }; // Allow std::unordered_multimap access to internals of compatible maps. template struct _Hash_merge_helper< _GLIBCXX_STD_C::unordered_multimap<_Key, _Val, _Hash1, _Eq1, _Alloc>, _Hash2, _Eq2> { private: template using unordered_map = _GLIBCXX_STD_C::unordered_map<_Tp...>; template using unordered_multimap = _GLIBCXX_STD_C::unordered_multimap<_Tp...>; friend unordered_multimap<_Key, _Val, _Hash1, _Eq1, _Alloc>; static auto& _S_get_table(unordered_map<_Key, _Val, _Hash2, _Eq2, _Alloc>& __map) { return __map._M_h; } static auto& _S_get_table(unordered_multimap<_Key, _Val, _Hash2, _Eq2, _Alloc>& __map) { return __map._M_h; } }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _UNORDERED_MAP_H */ PK!P 8/bits/unordered_set.hnu[// unordered_set implementation -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/unordered_set.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{unordered_set} */ #ifndef _UNORDERED_SET_H #define _UNORDERED_SET_H namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER /// Base types for unordered_set. template using __uset_traits = __detail::_Hashtable_traits<_Cache, true, true>; template, typename _Pred = std::equal_to<_Value>, typename _Alloc = std::allocator<_Value>, typename _Tr = __uset_traits<__cache_default<_Value, _Hash>::value>> using __uset_hashtable = _Hashtable<_Value, _Value, _Alloc, __detail::_Identity, _Pred, _Hash, __detail::_Mod_range_hashing, __detail::_Default_ranged_hash, __detail::_Prime_rehash_policy, _Tr>; /// Base types for unordered_multiset. template using __umset_traits = __detail::_Hashtable_traits<_Cache, true, false>; template, typename _Pred = std::equal_to<_Value>, typename _Alloc = std::allocator<_Value>, typename _Tr = __umset_traits<__cache_default<_Value, _Hash>::value>> using __umset_hashtable = _Hashtable<_Value, _Value, _Alloc, __detail::_Identity, _Pred, _Hash, __detail::_Mod_range_hashing, __detail::_Default_ranged_hash, __detail::_Prime_rehash_policy, _Tr>; template class unordered_multiset; /** * @brief A standard container composed of unique keys (containing * at most one of each key value) in which the elements' keys are * the elements themselves. * * @ingroup unordered_associative_containers * * @tparam _Value Type of key objects. * @tparam _Hash Hashing function object type, defaults to hash<_Value>. * @tparam _Pred Predicate function object type, defaults to * equal_to<_Value>. * * @tparam _Alloc Allocator type, defaults to allocator<_Key>. * * Meets the requirements of a container, and * unordered associative container * * Base is _Hashtable, dispatched at compile time via template * alias __uset_hashtable. */ template, typename _Pred = equal_to<_Value>, typename _Alloc = allocator<_Value>> class unordered_set { typedef __uset_hashtable<_Value, _Hash, _Pred, _Alloc> _Hashtable; _Hashtable _M_h; public: // typedefs: //@{ /// Public typedefs. typedef typename _Hashtable::key_type key_type; typedef typename _Hashtable::value_type value_type; typedef typename _Hashtable::hasher hasher; typedef typename _Hashtable::key_equal key_equal; typedef typename _Hashtable::allocator_type allocator_type; //@} //@{ /// Iterator-related typedefs. typedef typename _Hashtable::pointer pointer; typedef typename _Hashtable::const_pointer const_pointer; typedef typename _Hashtable::reference reference; typedef typename _Hashtable::const_reference const_reference; typedef typename _Hashtable::iterator iterator; typedef typename _Hashtable::const_iterator const_iterator; typedef typename _Hashtable::local_iterator local_iterator; typedef typename _Hashtable::const_local_iterator const_local_iterator; typedef typename _Hashtable::size_type size_type; typedef typename _Hashtable::difference_type difference_type; //@} #if __cplusplus > 201402L using node_type = typename _Hashtable::node_type; using insert_return_type = typename _Hashtable::insert_return_type; #endif // construct/destroy/copy /// Default constructor. unordered_set() = default; /** * @brief Default constructor creates no elements. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. */ explicit unordered_set(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__n, __hf, __eql, __a) { } /** * @brief Builds an %unordered_set from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_set consisting of copies of the elements from * [__first,__last). This is linear in N (where N is * distance(__first,__last)). */ template unordered_set(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__first, __last, __n, __hf, __eql, __a) { } /// Copy constructor. unordered_set(const unordered_set&) = default; /// Move constructor. unordered_set(unordered_set&&) = default; /** * @brief Creates an %unordered_set with no elements. * @param __a An allocator object. */ explicit unordered_set(const allocator_type& __a) : _M_h(__a) { } /* * @brief Copy constructor with allocator argument. * @param __uset Input %unordered_set to copy. * @param __a An allocator object. */ unordered_set(const unordered_set& __uset, const allocator_type& __a) : _M_h(__uset._M_h, __a) { } /* * @brief Move constructor with allocator argument. * @param __uset Input %unordered_set to move. * @param __a An allocator object. */ unordered_set(unordered_set&& __uset, const allocator_type& __a) : _M_h(std::move(__uset._M_h), __a) { } /** * @brief Builds an %unordered_set from an initializer_list. * @param __l An initializer_list. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_set consisting of copies of the elements in the * list. This is linear in N (where N is @a __l.size()). */ unordered_set(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__l, __n, __hf, __eql, __a) { } unordered_set(size_type __n, const allocator_type& __a) : unordered_set(__n, hasher(), key_equal(), __a) { } unordered_set(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_set(__n, __hf, key_equal(), __a) { } template unordered_set(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_set(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_set(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_set(__first, __last, __n, __hf, key_equal(), __a) { } unordered_set(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_set(__l, __n, hasher(), key_equal(), __a) { } unordered_set(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_set(__l, __n, __hf, key_equal(), __a) { } /// Copy assignment operator. unordered_set& operator=(const unordered_set&) = default; /// Move assignment operator. unordered_set& operator=(unordered_set&&) = default; /** * @brief %Unordered_set list assignment operator. * @param __l An initializer_list. * * This function fills an %unordered_set with copies of the elements in * the initializer list @a __l. * * Note that the assignment completely changes the %unordered_set and * that the resulting %unordered_set's size is the same as the number * of elements assigned. */ unordered_set& operator=(initializer_list __l) { _M_h = __l; return *this; } /// Returns the allocator object used by the %unordered_set. allocator_type get_allocator() const noexcept { return _M_h.get_allocator(); } // size and capacity: /// Returns true if the %unordered_set is empty. bool empty() const noexcept { return _M_h.empty(); } /// Returns the size of the %unordered_set. size_type size() const noexcept { return _M_h.size(); } /// Returns the maximum size of the %unordered_set. size_type max_size() const noexcept { return _M_h.max_size(); } // iterators. //@{ /** * Returns a read-only (constant) iterator that points to the first * element in the %unordered_set. */ iterator begin() noexcept { return _M_h.begin(); } const_iterator begin() const noexcept { return _M_h.begin(); } //@} //@{ /** * Returns a read-only (constant) iterator that points one past the last * element in the %unordered_set. */ iterator end() noexcept { return _M_h.end(); } const_iterator end() const noexcept { return _M_h.end(); } //@} /** * Returns a read-only (constant) iterator that points to the first * element in the %unordered_set. */ const_iterator cbegin() const noexcept { return _M_h.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * element in the %unordered_set. */ const_iterator cend() const noexcept { return _M_h.end(); } // modifiers. /** * @brief Attempts to build and insert an element into the * %unordered_set. * @param __args Arguments used to generate an element. * @return A pair, of which the first element is an iterator that points * to the possibly inserted element, and the second is a bool * that is true if the element was actually inserted. * * This function attempts to build and insert an element into the * %unordered_set. An %unordered_set relies on unique keys and thus an * element is only inserted if it is not already present in the * %unordered_set. * * Insertion requires amortized constant time. */ template std::pair emplace(_Args&&... __args) { return _M_h.emplace(std::forward<_Args>(__args)...); } /** * @brief Attempts to insert an element into the %unordered_set. * @param __pos An iterator that serves as a hint as to where the * element should be inserted. * @param __args Arguments used to generate the element to be * inserted. * @return An iterator that points to the element with key equivalent to * the one generated from @a __args (may or may not be the * element itself). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument emplace() * does. Note that the first parameter is only a hint and can * potentially improve the performance of the insertion process. A bad * hint would cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires amortized constant time. */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_h.emplace_hint(__pos, std::forward<_Args>(__args)...); } //@{ /** * @brief Attempts to insert an element into the %unordered_set. * @param __x Element to be inserted. * @return A pair, of which the first element is an iterator that points * to the possibly inserted element, and the second is a bool * that is true if the element was actually inserted. * * This function attempts to insert an element into the %unordered_set. * An %unordered_set relies on unique keys and thus an element is only * inserted if it is not already present in the %unordered_set. * * Insertion requires amortized constant time. */ std::pair insert(const value_type& __x) { return _M_h.insert(__x); } std::pair insert(value_type&& __x) { return _M_h.insert(std::move(__x)); } //@} //@{ /** * @brief Attempts to insert an element into the %unordered_set. * @param __hint An iterator that serves as a hint as to where the * element should be inserted. * @param __x Element to be inserted. * @return An iterator that points to the element with key of * @a __x (may or may not be the element passed in). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument insert() * does. Note that the first parameter is only a hint and can * potentially improve the performance of the insertion process. A bad * hint would cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires amortized constant. */ iterator insert(const_iterator __hint, const value_type& __x) { return _M_h.insert(__hint, __x); } iterator insert(const_iterator __hint, value_type&& __x) { return _M_h.insert(__hint, std::move(__x)); } //@} /** * @brief A template function that attempts to insert a range of * elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_h.insert(__first, __last); } /** * @brief Attempts to insert a list of elements into the %unordered_set. * @param __l A std::initializer_list of elements * to be inserted. * * Complexity similar to that of the range constructor. */ void insert(initializer_list __l) { _M_h.insert(__l); } #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_h.extract(__pos); } /// Extract a node. node_type extract(const key_type& __key) { return _M_h.extract(__key); } /// Re-insert an extracted node. insert_return_type insert(node_type&& __nh) { return _M_h._M_reinsert_node(std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator, node_type&& __nh) { return _M_h._M_reinsert_node(std::move(__nh)).position; } #endif // C++17 //@{ /** * @brief Erases an element from an %unordered_set. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a __position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given iterator, * from an %unordered_set. Note that this function only erases the * element, and that if the element is itself a pointer, the pointed-to * memory is not touched in any way. Managing the pointer is the user's * responsibility. */ iterator erase(const_iterator __position) { return _M_h.erase(__position); } // LWG 2059. iterator erase(iterator __position) { return _M_h.erase(__position); } //@} /** * @brief Erases elements according to the provided key. * @param __x Key of element to be erased. * @return The number of elements erased. * * This function erases all the elements located by the given key from * an %unordered_set. For an %unordered_set the result of this function * can only be 0 (not present) or 1 (present). * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_h.erase(__x); } /** * @brief Erases a [__first,__last) range of elements from an * %unordered_set. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * @return The iterator @a __last. * * This function erases a sequence of elements from an %unordered_set. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __first, const_iterator __last) { return _M_h.erase(__first, __last); } /** * Erases all elements in an %unordered_set. Note that this function only * erases the elements, and that if the elements themselves are pointers, * the pointed-to memory is not touched in any way. Managing the pointer * is the user's responsibility. */ void clear() noexcept { _M_h.clear(); } /** * @brief Swaps data with another %unordered_set. * @param __x An %unordered_set of the same element and allocator * types. * * This exchanges the elements between two sets in constant time. * Note that the global std::swap() function is specialized such that * std::swap(s1,s2) will feed to this function. */ void swap(unordered_set& __x) noexcept( noexcept(_M_h.swap(__x._M_h)) ) { _M_h.swap(__x._M_h); } #if __cplusplus > 201402L template friend class std::_Hash_merge_helper; template void merge(unordered_set<_Value, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_unique(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_set<_Value, _H2, _P2, _Alloc>&& __source) { merge(__source); } template void merge(unordered_multiset<_Value, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_unique(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_multiset<_Value, _H2, _P2, _Alloc>&& __source) { merge(__source); } #endif // C++17 // observers. /// Returns the hash functor object with which the %unordered_set was /// constructed. hasher hash_function() const { return _M_h.hash_function(); } /// Returns the key comparison object with which the %unordered_set was /// constructed. key_equal key_eq() const { return _M_h.key_eq(); } // lookup. //@{ /** * @brief Tries to locate an element in an %unordered_set. * @param __x Element to be located. * @return Iterator pointing to sought-after element, or end() if not * found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after element. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_h.find(__x); } const_iterator find(const key_type& __x) const { return _M_h.find(__x); } //@} /** * @brief Finds the number of elements. * @param __x Element to located. * @return Number of elements with specified key. * * This function only makes sense for unordered_multisets; for * unordered_set the result will either be 0 (not present) or 1 * (present). */ size_type count(const key_type& __x) const { return _M_h.count(__x); } //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. * * This function probably only makes sense for multisets. */ std::pair equal_range(const key_type& __x) { return _M_h.equal_range(__x); } std::pair equal_range(const key_type& __x) const { return _M_h.equal_range(__x); } //@} // bucket interface. /// Returns the number of buckets of the %unordered_set. size_type bucket_count() const noexcept { return _M_h.bucket_count(); } /// Returns the maximum number of buckets of the %unordered_set. size_type max_bucket_count() const noexcept { return _M_h.max_bucket_count(); } /* * @brief Returns the number of elements in a given bucket. * @param __n A bucket index. * @return The number of elements in the bucket. */ size_type bucket_size(size_type __n) const { return _M_h.bucket_size(__n); } /* * @brief Returns the bucket index of a given element. * @param __key A key instance. * @return The key bucket index. */ size_type bucket(const key_type& __key) const { return _M_h.bucket(__key); } //@{ /** * @brief Returns a read-only (constant) iterator pointing to the first * bucket element. * @param __n The bucket index. * @return A read-only local iterator. */ local_iterator begin(size_type __n) { return _M_h.begin(__n); } const_local_iterator begin(size_type __n) const { return _M_h.begin(__n); } const_local_iterator cbegin(size_type __n) const { return _M_h.cbegin(__n); } //@} //@{ /** * @brief Returns a read-only (constant) iterator pointing to one past * the last bucket elements. * @param __n The bucket index. * @return A read-only local iterator. */ local_iterator end(size_type __n) { return _M_h.end(__n); } const_local_iterator end(size_type __n) const { return _M_h.end(__n); } const_local_iterator cend(size_type __n) const { return _M_h.cend(__n); } //@} // hash policy. /// Returns the average number of elements per bucket. float load_factor() const noexcept { return _M_h.load_factor(); } /// Returns a positive number that the %unordered_set tries to keep the /// load factor less than or equal to. float max_load_factor() const noexcept { return _M_h.max_load_factor(); } /** * @brief Change the %unordered_set maximum load factor. * @param __z The new maximum load factor. */ void max_load_factor(float __z) { _M_h.max_load_factor(__z); } /** * @brief May rehash the %unordered_set. * @param __n The new number of buckets. * * Rehash will occur only if the new number of buckets respect the * %unordered_set maximum load factor. */ void rehash(size_type __n) { _M_h.rehash(__n); } /** * @brief Prepare the %unordered_set for a specified number of * elements. * @param __n Number of elements required. * * Same as rehash(ceil(n / max_load_factor())). */ void reserve(size_type __n) { _M_h.reserve(__n); } template friend bool operator==(const unordered_set<_Value1, _Hash1, _Pred1, _Alloc1>&, const unordered_set<_Value1, _Hash1, _Pred1, _Alloc1>&); }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Pred = equal_to::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_set(_InputIterator, _InputIterator, unordered_set::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_set::value_type, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Tp>, typename _Allocator = allocator<_Tp>, typename = _RequireAllocator<_Allocator>> unordered_set(initializer_list<_Tp>, unordered_set::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_set<_Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_set(_InputIterator, _InputIterator, unordered_set::size_type, _Allocator) -> unordered_set::value_type, hash< typename iterator_traits<_InputIterator>::value_type>, equal_to< typename iterator_traits<_InputIterator>::value_type>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_set(_InputIterator, _InputIterator, unordered_set::size_type, _Hash, _Allocator) -> unordered_set::value_type, _Hash, equal_to< typename iterator_traits<_InputIterator>::value_type>, _Allocator>; template> unordered_set(initializer_list<_Tp>, unordered_set::size_type, _Allocator) -> unordered_set<_Tp, hash<_Tp>, equal_to<_Tp>, _Allocator>; template> unordered_set(initializer_list<_Tp>, unordered_set::size_type, _Hash, _Allocator) -> unordered_set<_Tp, _Hash, equal_to<_Tp>, _Allocator>; #endif /** * @brief A standard container composed of equivalent keys * (possibly containing multiple of each key value) in which the * elements' keys are the elements themselves. * * @ingroup unordered_associative_containers * * @tparam _Value Type of key objects. * @tparam _Hash Hashing function object type, defaults to hash<_Value>. * @tparam _Pred Predicate function object type, defaults * to equal_to<_Value>. * @tparam _Alloc Allocator type, defaults to allocator<_Key>. * * Meets the requirements of a container, and * unordered associative container * * Base is _Hashtable, dispatched at compile time via template * alias __umset_hashtable. */ template, typename _Pred = equal_to<_Value>, typename _Alloc = allocator<_Value>> class unordered_multiset { typedef __umset_hashtable<_Value, _Hash, _Pred, _Alloc> _Hashtable; _Hashtable _M_h; public: // typedefs: //@{ /// Public typedefs. typedef typename _Hashtable::key_type key_type; typedef typename _Hashtable::value_type value_type; typedef typename _Hashtable::hasher hasher; typedef typename _Hashtable::key_equal key_equal; typedef typename _Hashtable::allocator_type allocator_type; //@} //@{ /// Iterator-related typedefs. typedef typename _Hashtable::pointer pointer; typedef typename _Hashtable::const_pointer const_pointer; typedef typename _Hashtable::reference reference; typedef typename _Hashtable::const_reference const_reference; typedef typename _Hashtable::iterator iterator; typedef typename _Hashtable::const_iterator const_iterator; typedef typename _Hashtable::local_iterator local_iterator; typedef typename _Hashtable::const_local_iterator const_local_iterator; typedef typename _Hashtable::size_type size_type; typedef typename _Hashtable::difference_type difference_type; //@} #if __cplusplus > 201402L using node_type = typename _Hashtable::node_type; #endif // construct/destroy/copy /// Default constructor. unordered_multiset() = default; /** * @brief Default constructor creates no elements. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. */ explicit unordered_multiset(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__n, __hf, __eql, __a) { } /** * @brief Builds an %unordered_multiset from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_multiset consisting of copies of the elements * from [__first,__last). This is linear in N (where N is * distance(__first,__last)). */ template unordered_multiset(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__first, __last, __n, __hf, __eql, __a) { } /// Copy constructor. unordered_multiset(const unordered_multiset&) = default; /// Move constructor. unordered_multiset(unordered_multiset&&) = default; /** * @brief Builds an %unordered_multiset from an initializer_list. * @param __l An initializer_list. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_multiset consisting of copies of the elements in * the list. This is linear in N (where N is @a __l.size()). */ unordered_multiset(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__l, __n, __hf, __eql, __a) { } /// Copy assignment operator. unordered_multiset& operator=(const unordered_multiset&) = default; /// Move assignment operator. unordered_multiset& operator=(unordered_multiset&&) = default; /** * @brief Creates an %unordered_multiset with no elements. * @param __a An allocator object. */ explicit unordered_multiset(const allocator_type& __a) : _M_h(__a) { } /* * @brief Copy constructor with allocator argument. * @param __uset Input %unordered_multiset to copy. * @param __a An allocator object. */ unordered_multiset(const unordered_multiset& __umset, const allocator_type& __a) : _M_h(__umset._M_h, __a) { } /* * @brief Move constructor with allocator argument. * @param __umset Input %unordered_multiset to move. * @param __a An allocator object. */ unordered_multiset(unordered_multiset&& __umset, const allocator_type& __a) : _M_h(std::move(__umset._M_h), __a) { } unordered_multiset(size_type __n, const allocator_type& __a) : unordered_multiset(__n, hasher(), key_equal(), __a) { } unordered_multiset(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multiset(__n, __hf, key_equal(), __a) { } template unordered_multiset(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_multiset(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_multiset(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multiset(__first, __last, __n, __hf, key_equal(), __a) { } unordered_multiset(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_multiset(__l, __n, hasher(), key_equal(), __a) { } unordered_multiset(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multiset(__l, __n, __hf, key_equal(), __a) { } /** * @brief %Unordered_multiset list assignment operator. * @param __l An initializer_list. * * This function fills an %unordered_multiset with copies of the elements * in the initializer list @a __l. * * Note that the assignment completely changes the %unordered_multiset * and that the resulting %unordered_multiset's size is the same as the * number of elements assigned. */ unordered_multiset& operator=(initializer_list __l) { _M_h = __l; return *this; } /// Returns the allocator object used by the %unordered_multiset. allocator_type get_allocator() const noexcept { return _M_h.get_allocator(); } // size and capacity: /// Returns true if the %unordered_multiset is empty. bool empty() const noexcept { return _M_h.empty(); } /// Returns the size of the %unordered_multiset. size_type size() const noexcept { return _M_h.size(); } /// Returns the maximum size of the %unordered_multiset. size_type max_size() const noexcept { return _M_h.max_size(); } // iterators. //@{ /** * Returns a read-only (constant) iterator that points to the first * element in the %unordered_multiset. */ iterator begin() noexcept { return _M_h.begin(); } const_iterator begin() const noexcept { return _M_h.begin(); } //@} //@{ /** * Returns a read-only (constant) iterator that points one past the last * element in the %unordered_multiset. */ iterator end() noexcept { return _M_h.end(); } const_iterator end() const noexcept { return _M_h.end(); } //@} /** * Returns a read-only (constant) iterator that points to the first * element in the %unordered_multiset. */ const_iterator cbegin() const noexcept { return _M_h.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * element in the %unordered_multiset. */ const_iterator cend() const noexcept { return _M_h.end(); } // modifiers. /** * @brief Builds and insert an element into the %unordered_multiset. * @param __args Arguments used to generate an element. * @return An iterator that points to the inserted element. * * Insertion requires amortized constant time. */ template iterator emplace(_Args&&... __args) { return _M_h.emplace(std::forward<_Args>(__args)...); } /** * @brief Inserts an element into the %unordered_multiset. * @param __pos An iterator that serves as a hint as to where the * element should be inserted. * @param __args Arguments used to generate the element to be * inserted. * @return An iterator that points to the inserted element. * * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires amortized constant time. */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_h.emplace_hint(__pos, std::forward<_Args>(__args)...); } //@{ /** * @brief Inserts an element into the %unordered_multiset. * @param __x Element to be inserted. * @return An iterator that points to the inserted element. * * Insertion requires amortized constant time. */ iterator insert(const value_type& __x) { return _M_h.insert(__x); } iterator insert(value_type&& __x) { return _M_h.insert(std::move(__x)); } //@} //@{ /** * @brief Inserts an element into the %unordered_multiset. * @param __hint An iterator that serves as a hint as to where the * element should be inserted. * @param __x Element to be inserted. * @return An iterator that points to the inserted element. * * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires amortized constant. */ iterator insert(const_iterator __hint, const value_type& __x) { return _M_h.insert(__hint, __x); } iterator insert(const_iterator __hint, value_type&& __x) { return _M_h.insert(__hint, std::move(__x)); } //@} /** * @brief A template function that inserts a range of elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_h.insert(__first, __last); } /** * @brief Inserts a list of elements into the %unordered_multiset. * @param __l A std::initializer_list of elements to be * inserted. * * Complexity similar to that of the range constructor. */ void insert(initializer_list __l) { _M_h.insert(__l); } #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_h.extract(__pos); } /// Extract a node. node_type extract(const key_type& __key) { return _M_h.extract(__key); } /// Re-insert an extracted node. iterator insert(node_type&& __nh) { return _M_h._M_reinsert_node_multi(cend(), std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator __hint, node_type&& __nh) { return _M_h._M_reinsert_node_multi(__hint, std::move(__nh)); } #endif // C++17 //@{ /** * @brief Erases an element from an %unordered_multiset. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a __position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given iterator, * from an %unordered_multiset. * * Note that this function only erases the element, and that if the * element is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __position) { return _M_h.erase(__position); } // LWG 2059. iterator erase(iterator __position) { return _M_h.erase(__position); } //@} /** * @brief Erases elements according to the provided key. * @param __x Key of element to be erased. * @return The number of elements erased. * * This function erases all the elements located by the given key from * an %unordered_multiset. * * Note that this function only erases the element, and that if the * element is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_h.erase(__x); } /** * @brief Erases a [__first,__last) range of elements from an * %unordered_multiset. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * @return The iterator @a __last. * * This function erases a sequence of elements from an * %unordered_multiset. * * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __first, const_iterator __last) { return _M_h.erase(__first, __last); } /** * Erases all elements in an %unordered_multiset. * * Note that this function only erases the elements, and that if the * elements themselves are pointers, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ void clear() noexcept { _M_h.clear(); } /** * @brief Swaps data with another %unordered_multiset. * @param __x An %unordered_multiset of the same element and allocator * types. * * This exchanges the elements between two sets in constant time. * Note that the global std::swap() function is specialized such that * std::swap(s1,s2) will feed to this function. */ void swap(unordered_multiset& __x) noexcept( noexcept(_M_h.swap(__x._M_h)) ) { _M_h.swap(__x._M_h); } #if __cplusplus > 201402L template friend class std::_Hash_merge_helper; template void merge(unordered_multiset<_Value, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_multi(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_multiset<_Value, _H2, _P2, _Alloc>&& __source) { merge(__source); } template void merge(unordered_set<_Value, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_multi(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_set<_Value, _H2, _P2, _Alloc>&& __source) { merge(__source); } #endif // C++17 // observers. /// Returns the hash functor object with which the %unordered_multiset /// was constructed. hasher hash_function() const { return _M_h.hash_function(); } /// Returns the key comparison object with which the %unordered_multiset /// was constructed. key_equal key_eq() const { return _M_h.key_eq(); } // lookup. //@{ /** * @brief Tries to locate an element in an %unordered_multiset. * @param __x Element to be located. * @return Iterator pointing to sought-after element, or end() if not * found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after element. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_h.find(__x); } const_iterator find(const key_type& __x) const { return _M_h.find(__x); } //@} /** * @brief Finds the number of elements. * @param __x Element to located. * @return Number of elements with specified key. */ size_type count(const key_type& __x) const { return _M_h.count(__x); } //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. */ std::pair equal_range(const key_type& __x) { return _M_h.equal_range(__x); } std::pair equal_range(const key_type& __x) const { return _M_h.equal_range(__x); } //@} // bucket interface. /// Returns the number of buckets of the %unordered_multiset. size_type bucket_count() const noexcept { return _M_h.bucket_count(); } /// Returns the maximum number of buckets of the %unordered_multiset. size_type max_bucket_count() const noexcept { return _M_h.max_bucket_count(); } /* * @brief Returns the number of elements in a given bucket. * @param __n A bucket index. * @return The number of elements in the bucket. */ size_type bucket_size(size_type __n) const { return _M_h.bucket_size(__n); } /* * @brief Returns the bucket index of a given element. * @param __key A key instance. * @return The key bucket index. */ size_type bucket(const key_type& __key) const { return _M_h.bucket(__key); } //@{ /** * @brief Returns a read-only (constant) iterator pointing to the first * bucket element. * @param __n The bucket index. * @return A read-only local iterator. */ local_iterator begin(size_type __n) { return _M_h.begin(__n); } const_local_iterator begin(size_type __n) const { return _M_h.begin(__n); } const_local_iterator cbegin(size_type __n) const { return _M_h.cbegin(__n); } //@} //@{ /** * @brief Returns a read-only (constant) iterator pointing to one past * the last bucket elements. * @param __n The bucket index. * @return A read-only local iterator. */ local_iterator end(size_type __n) { return _M_h.end(__n); } const_local_iterator end(size_type __n) const { return _M_h.end(__n); } const_local_iterator cend(size_type __n) const { return _M_h.cend(__n); } //@} // hash policy. /// Returns the average number of elements per bucket. float load_factor() const noexcept { return _M_h.load_factor(); } /// Returns a positive number that the %unordered_multiset tries to keep the /// load factor less than or equal to. float max_load_factor() const noexcept { return _M_h.max_load_factor(); } /** * @brief Change the %unordered_multiset maximum load factor. * @param __z The new maximum load factor. */ void max_load_factor(float __z) { _M_h.max_load_factor(__z); } /** * @brief May rehash the %unordered_multiset. * @param __n The new number of buckets. * * Rehash will occur only if the new number of buckets respect the * %unordered_multiset maximum load factor. */ void rehash(size_type __n) { _M_h.rehash(__n); } /** * @brief Prepare the %unordered_multiset for a specified number of * elements. * @param __n Number of elements required. * * Same as rehash(ceil(n / max_load_factor())). */ void reserve(size_type __n) { _M_h.reserve(__n); } template friend bool operator==(const unordered_multiset<_Value1, _Hash1, _Pred1, _Alloc1>&, const unordered_multiset<_Value1, _Hash1, _Pred1, _Alloc1>&); }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Pred = equal_to::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_multiset(_InputIterator, _InputIterator, unordered_multiset::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multiset::value_type, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Tp>, typename _Allocator = allocator<_Tp>, typename = _RequireAllocator<_Allocator>> unordered_multiset(initializer_list<_Tp>, unordered_multiset::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multiset<_Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multiset(_InputIterator, _InputIterator, unordered_multiset::size_type, _Allocator) -> unordered_multiset::value_type, hash::value_type>, equal_to::value_type>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multiset(_InputIterator, _InputIterator, unordered_multiset::size_type, _Hash, _Allocator) -> unordered_multiset::value_type, _Hash, equal_to< typename iterator_traits<_InputIterator>::value_type>, _Allocator>; template> unordered_multiset(initializer_list<_Tp>, unordered_multiset::size_type, _Allocator) -> unordered_multiset<_Tp, hash<_Tp>, equal_to<_Tp>, _Allocator>; template> unordered_multiset(initializer_list<_Tp>, unordered_multiset::size_type, _Hash, _Allocator) -> unordered_multiset<_Tp, _Hash, equal_to<_Tp>, _Allocator>; #endif template inline void swap(unordered_set<_Value, _Hash, _Pred, _Alloc>& __x, unordered_set<_Value, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline void swap(unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x, unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline bool operator==(const unordered_set<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_set<_Value, _Hash, _Pred, _Alloc>& __y) { return __x._M_h._M_equal(__y._M_h); } template inline bool operator!=(const unordered_set<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_set<_Value, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } template inline bool operator==(const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y) { return __x._M_h._M_equal(__y._M_h); } template inline bool operator!=(const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } _GLIBCXX_END_NAMESPACE_CONTAINER #if __cplusplus > 201402L // Allow std::unordered_set access to internals of compatible sets. template struct _Hash_merge_helper< _GLIBCXX_STD_C::unordered_set<_Val, _Hash1, _Eq1, _Alloc>, _Hash2, _Eq2> { private: template using unordered_set = _GLIBCXX_STD_C::unordered_set<_Tp...>; template using unordered_multiset = _GLIBCXX_STD_C::unordered_multiset<_Tp...>; friend unordered_set<_Val, _Hash1, _Eq1, _Alloc>; static auto& _S_get_table(unordered_set<_Val, _Hash2, _Eq2, _Alloc>& __set) { return __set._M_h; } static auto& _S_get_table(unordered_multiset<_Val, _Hash2, _Eq2, _Alloc>& __set) { return __set._M_h; } }; // Allow std::unordered_multiset access to internals of compatible sets. template struct _Hash_merge_helper< _GLIBCXX_STD_C::unordered_multiset<_Val, _Hash1, _Eq1, _Alloc>, _Hash2, _Eq2> { private: template using unordered_set = _GLIBCXX_STD_C::unordered_set<_Tp...>; template using unordered_multiset = _GLIBCXX_STD_C::unordered_multiset<_Tp...>; friend unordered_multiset<_Val, _Hash1, _Eq1, _Alloc>; static auto& _S_get_table(unordered_set<_Val, _Hash2, _Eq2, _Alloc>& __set) { return __set._M_h; } static auto& _S_get_table(unordered_multiset<_Val, _Hash2, _Eq2, _Alloc>& __set) { return __set._M_h; } }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _UNORDERED_SET_H */ PK!KF}}8/bits/uses_allocator.hnu[// Uses-allocator Construction -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . #ifndef _USES_ALLOCATOR_H #define _USES_ALLOCATOR_H 1 #if __cplusplus < 201103L # include #else #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION struct __erased_type { }; template using __is_erased_or_convertible = __or_, is_convertible<_Alloc, _Tp>>; /// [allocator.tag] struct allocator_arg_t { explicit allocator_arg_t() = default; }; _GLIBCXX17_INLINE constexpr allocator_arg_t allocator_arg = allocator_arg_t(); template> struct __uses_allocator_helper : false_type { }; template struct __uses_allocator_helper<_Tp, _Alloc, __void_t> : __is_erased_or_convertible<_Alloc, typename _Tp::allocator_type>::type { }; /// [allocator.uses.trait] template struct uses_allocator : __uses_allocator_helper<_Tp, _Alloc>::type { }; struct __uses_alloc_base { }; struct __uses_alloc0 : __uses_alloc_base { struct _Sink { void operator=(const void*) { } } _M_a; }; template struct __uses_alloc1 : __uses_alloc_base { const _Alloc* _M_a; }; template struct __uses_alloc2 : __uses_alloc_base { const _Alloc* _M_a; }; template struct __uses_alloc; template struct __uses_alloc : conditional< is_constructible<_Tp, allocator_arg_t, const _Alloc&, _Args...>::value, __uses_alloc1<_Alloc>, __uses_alloc2<_Alloc>>::type { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2586. Wrong value category used in scoped_allocator_adaptor::construct static_assert(__or_< is_constructible<_Tp, allocator_arg_t, const _Alloc&, _Args...>, is_constructible<_Tp, _Args..., const _Alloc&>>::value, "construction with an allocator must be possible" " if uses_allocator is true"); }; template struct __uses_alloc : __uses_alloc0 { }; template using __uses_alloc_t = __uses_alloc::value, _Tp, _Alloc, _Args...>; template inline __uses_alloc_t<_Tp, _Alloc, _Args...> __use_alloc(const _Alloc& __a) { __uses_alloc_t<_Tp, _Alloc, _Args...> __ret; __ret._M_a = std::__addressof(__a); return __ret; } template void __use_alloc(const _Alloc&&) = delete; #if __cplusplus > 201402L template inline constexpr bool uses_allocator_v = uses_allocator<_Tp, _Alloc>::value; #endif // C++17 template class _Predicate, typename _Tp, typename _Alloc, typename... _Args> struct __is_uses_allocator_predicate : conditional::value, __or_<_Predicate<_Tp, allocator_arg_t, _Alloc, _Args...>, _Predicate<_Tp, _Args..., _Alloc>>, _Predicate<_Tp, _Args...>>::type { }; template struct __is_uses_allocator_constructible : __is_uses_allocator_predicate { }; #if __cplusplus >= 201402L template _GLIBCXX17_INLINE constexpr bool __is_uses_allocator_constructible_v = __is_uses_allocator_constructible<_Tp, _Alloc, _Args...>::value; #endif // C++14 template struct __is_nothrow_uses_allocator_constructible : __is_uses_allocator_predicate { }; #if __cplusplus >= 201402L template _GLIBCXX17_INLINE constexpr bool __is_nothrow_uses_allocator_constructible_v = __is_nothrow_uses_allocator_constructible<_Tp, _Alloc, _Args...>::value; #endif // C++14 template void __uses_allocator_construct_impl(__uses_alloc0 __a, _Tp* __ptr, _Args&&... __args) { ::new ((void*)__ptr) _Tp(std::forward<_Args>(__args)...); } template void __uses_allocator_construct_impl(__uses_alloc1<_Alloc> __a, _Tp* __ptr, _Args&&... __args) { ::new ((void*)__ptr) _Tp(allocator_arg, *__a._M_a, std::forward<_Args>(__args)...); } template void __uses_allocator_construct_impl(__uses_alloc2<_Alloc> __a, _Tp* __ptr, _Args&&... __args) { ::new ((void*)__ptr) _Tp(std::forward<_Args>(__args)..., *__a._M_a); } template void __uses_allocator_construct(const _Alloc& __a, _Tp* __ptr, _Args&&... __args) { __uses_allocator_construct_impl(__use_alloc<_Tp, _Alloc, _Args...>(__a), __ptr, std::forward<_Args>(__args)...); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif #endif PK!hM>XX8/bits/valarray_after.hnu[// The template and inlines for the -*- C++ -*- internal _Meta class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/valarray_after.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _VALARRAY_AFTER_H #define _VALARRAY_AFTER_H 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // // gslice_array closure. // template class _GBase { public: typedef typename _Dom::value_type value_type; _GBase (const _Dom& __e, const valarray& __i) : _M_expr (__e), _M_index(__i) {} value_type operator[] (size_t __i) const { return _M_expr[_M_index[__i]]; } size_t size () const { return _M_index.size(); } private: const _Dom& _M_expr; const valarray& _M_index; }; template class _GBase<_Array<_Tp> > { public: typedef _Tp value_type; _GBase (_Array<_Tp> __a, const valarray& __i) : _M_array (__a), _M_index(__i) {} value_type operator[] (size_t __i) const { return _M_array._M_data[_M_index[__i]]; } size_t size () const { return _M_index.size(); } private: const _Array<_Tp> _M_array; const valarray& _M_index; }; template struct _GClos<_Expr, _Dom> : _GBase<_Dom> { typedef _GBase<_Dom> _Base; typedef typename _Base::value_type value_type; _GClos (const _Dom& __e, const valarray& __i) : _Base (__e, __i) {} }; template struct _GClos<_ValArray, _Tp> : _GBase<_Array<_Tp> > { typedef _GBase<_Array<_Tp> > _Base; typedef typename _Base::value_type value_type; _GClos (_Array<_Tp> __a, const valarray& __i) : _Base (__a, __i) {} }; // // indirect_array closure // template class _IBase { public: typedef typename _Dom::value_type value_type; _IBase (const _Dom& __e, const valarray& __i) : _M_expr (__e), _M_index (__i) {} value_type operator[] (size_t __i) const { return _M_expr[_M_index[__i]]; } size_t size() const { return _M_index.size(); } private: const _Dom& _M_expr; const valarray& _M_index; }; template struct _IClos<_Expr, _Dom> : _IBase<_Dom> { typedef _IBase<_Dom> _Base; typedef typename _Base::value_type value_type; _IClos (const _Dom& __e, const valarray& __i) : _Base (__e, __i) {} }; template struct _IClos<_ValArray, _Tp> : _IBase > { typedef _IBase > _Base; typedef _Tp value_type; _IClos (const valarray<_Tp>& __a, const valarray& __i) : _Base (__a, __i) {} }; // // class _Expr // template class _Expr { public: typedef _Tp value_type; _Expr(const _Clos&); const _Clos& operator()() const; value_type operator[](size_t) const; valarray operator[](slice) const; valarray operator[](const gslice&) const; valarray operator[](const valarray&) const; valarray operator[](const valarray&) const; _Expr<_UnClos<__unary_plus, std::_Expr, _Clos>, value_type> operator+() const; _Expr<_UnClos<__negate, std::_Expr, _Clos>, value_type> operator-() const; _Expr<_UnClos<__bitwise_not, std::_Expr, _Clos>, value_type> operator~() const; _Expr<_UnClos<__logical_not, std::_Expr, _Clos>, bool> operator!() const; size_t size() const; value_type sum() const; valarray shift(int) const; valarray cshift(int) const; value_type min() const; value_type max() const; valarray apply(value_type (*)(const value_type&)) const; valarray apply(value_type (*)(value_type)) const; private: const _Clos _M_closure; }; template inline _Expr<_Clos, _Tp>::_Expr(const _Clos& __c) : _M_closure(__c) {} template inline const _Clos& _Expr<_Clos, _Tp>::operator()() const { return _M_closure; } template inline _Tp _Expr<_Clos, _Tp>::operator[](size_t __i) const { return _M_closure[__i]; } template inline valarray<_Tp> _Expr<_Clos, _Tp>::operator[](slice __s) const { valarray<_Tp> __v = valarray<_Tp>(*this)[__s]; return __v; } template inline valarray<_Tp> _Expr<_Clos, _Tp>::operator[](const gslice& __gs) const { valarray<_Tp> __v = valarray<_Tp>(*this)[__gs]; return __v; } template inline valarray<_Tp> _Expr<_Clos, _Tp>::operator[](const valarray& __m) const { valarray<_Tp> __v = valarray<_Tp>(*this)[__m]; return __v; } template inline valarray<_Tp> _Expr<_Clos, _Tp>::operator[](const valarray& __i) const { valarray<_Tp> __v = valarray<_Tp>(*this)[__i]; return __v; } template inline size_t _Expr<_Clos, _Tp>::size() const { return _M_closure.size(); } template inline valarray<_Tp> _Expr<_Clos, _Tp>::shift(int __n) const { valarray<_Tp> __v = valarray<_Tp>(*this).shift(__n); return __v; } template inline valarray<_Tp> _Expr<_Clos, _Tp>::cshift(int __n) const { valarray<_Tp> __v = valarray<_Tp>(*this).cshift(__n); return __v; } template inline valarray<_Tp> _Expr<_Clos, _Tp>::apply(_Tp __f(const _Tp&)) const { valarray<_Tp> __v = valarray<_Tp>(*this).apply(__f); return __v; } template inline valarray<_Tp> _Expr<_Clos, _Tp>::apply(_Tp __f(_Tp)) const { valarray<_Tp> __v = valarray<_Tp>(*this).apply(__f); return __v; } // XXX: replace this with a more robust summation algorithm. template inline _Tp _Expr<_Clos, _Tp>::sum() const { size_t __n = _M_closure.size(); if (__n == 0) return _Tp(); else { _Tp __s = _M_closure[--__n]; while (__n != 0) __s += _M_closure[--__n]; return __s; } } template inline _Tp _Expr<_Clos, _Tp>::min() const { return __valarray_min(_M_closure); } template inline _Tp _Expr<_Clos, _Tp>::max() const { return __valarray_max(_M_closure); } template inline _Expr<_UnClos<__logical_not, _Expr, _Dom>, bool> _Expr<_Dom, _Tp>::operator!() const { typedef _UnClos<__logical_not, std::_Expr, _Dom> _Closure; return _Expr<_Closure, bool>(_Closure(this->_M_closure)); } #define _DEFINE_EXPR_UNARY_OPERATOR(_Op, _Name) \ template \ inline _Expr<_UnClos<_Name, std::_Expr, _Dom>, _Tp> \ _Expr<_Dom, _Tp>::operator _Op() const \ { \ typedef _UnClos<_Name, std::_Expr, _Dom> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(this->_M_closure)); \ } _DEFINE_EXPR_UNARY_OPERATOR(+, __unary_plus) _DEFINE_EXPR_UNARY_OPERATOR(-, __negate) _DEFINE_EXPR_UNARY_OPERATOR(~, __bitwise_not) #undef _DEFINE_EXPR_UNARY_OPERATOR #define _DEFINE_EXPR_BINARY_OPERATOR(_Op, _Name) \ template \ inline _Expr<_BinClos<_Name, _Expr, _Expr, _Dom1, _Dom2>, \ typename __fun<_Name, typename _Dom1::value_type>::result_type> \ operator _Op(const _Expr<_Dom1, typename _Dom1::value_type>& __v, \ const _Expr<_Dom2, typename _Dom2::value_type>& __w) \ { \ typedef typename _Dom1::value_type _Arg; \ typedef typename __fun<_Name, _Arg>::result_type _Value; \ typedef _BinClos<_Name, _Expr, _Expr, _Dom1, _Dom2> _Closure; \ return _Expr<_Closure, _Value>(_Closure(__v(), __w())); \ } \ \ template \ inline _Expr<_BinClos<_Name, _Expr, _Constant, _Dom, \ typename _Dom::value_type>, \ typename __fun<_Name, typename _Dom::value_type>::result_type> \ operator _Op(const _Expr<_Dom, typename _Dom::value_type>& __v, \ const typename _Dom::value_type& __t) \ { \ typedef typename _Dom::value_type _Arg; \ typedef typename __fun<_Name, _Arg>::result_type _Value; \ typedef _BinClos<_Name, _Expr, _Constant, _Dom, _Arg> _Closure; \ return _Expr<_Closure, _Value>(_Closure(__v(), __t)); \ } \ \ template \ inline _Expr<_BinClos<_Name, _Constant, _Expr, \ typename _Dom::value_type, _Dom>, \ typename __fun<_Name, typename _Dom::value_type>::result_type> \ operator _Op(const typename _Dom::value_type& __t, \ const _Expr<_Dom, typename _Dom::value_type>& __v) \ { \ typedef typename _Dom::value_type _Arg; \ typedef typename __fun<_Name, _Arg>::result_type _Value; \ typedef _BinClos<_Name, _Constant, _Expr, _Arg, _Dom> _Closure; \ return _Expr<_Closure, _Value>(_Closure(__t, __v())); \ } \ \ template \ inline _Expr<_BinClos<_Name, _Expr, _ValArray, \ _Dom, typename _Dom::value_type>, \ typename __fun<_Name, typename _Dom::value_type>::result_type> \ operator _Op(const _Expr<_Dom,typename _Dom::value_type>& __e, \ const valarray& __v) \ { \ typedef typename _Dom::value_type _Arg; \ typedef typename __fun<_Name, _Arg>::result_type _Value; \ typedef _BinClos<_Name, _Expr, _ValArray, _Dom, _Arg> _Closure; \ return _Expr<_Closure, _Value>(_Closure(__e(), __v)); \ } \ \ template \ inline _Expr<_BinClos<_Name, _ValArray, _Expr, \ typename _Dom::value_type, _Dom>, \ typename __fun<_Name, typename _Dom::value_type>::result_type> \ operator _Op(const valarray& __v, \ const _Expr<_Dom, typename _Dom::value_type>& __e) \ { \ typedef typename _Dom::value_type _Tp; \ typedef typename __fun<_Name, _Tp>::result_type _Value; \ typedef _BinClos<_Name, _ValArray, _Expr, _Tp, _Dom> _Closure; \ return _Expr<_Closure, _Value>(_Closure(__v, __e ())); \ } _DEFINE_EXPR_BINARY_OPERATOR(+, __plus) _DEFINE_EXPR_BINARY_OPERATOR(-, __minus) _DEFINE_EXPR_BINARY_OPERATOR(*, __multiplies) _DEFINE_EXPR_BINARY_OPERATOR(/, __divides) _DEFINE_EXPR_BINARY_OPERATOR(%, __modulus) _DEFINE_EXPR_BINARY_OPERATOR(^, __bitwise_xor) _DEFINE_EXPR_BINARY_OPERATOR(&, __bitwise_and) _DEFINE_EXPR_BINARY_OPERATOR(|, __bitwise_or) _DEFINE_EXPR_BINARY_OPERATOR(<<, __shift_left) _DEFINE_EXPR_BINARY_OPERATOR(>>, __shift_right) _DEFINE_EXPR_BINARY_OPERATOR(&&, __logical_and) _DEFINE_EXPR_BINARY_OPERATOR(||, __logical_or) _DEFINE_EXPR_BINARY_OPERATOR(==, __equal_to) _DEFINE_EXPR_BINARY_OPERATOR(!=, __not_equal_to) _DEFINE_EXPR_BINARY_OPERATOR(<, __less) _DEFINE_EXPR_BINARY_OPERATOR(>, __greater) _DEFINE_EXPR_BINARY_OPERATOR(<=, __less_equal) _DEFINE_EXPR_BINARY_OPERATOR(>=, __greater_equal) #undef _DEFINE_EXPR_BINARY_OPERATOR #define _DEFINE_EXPR_UNARY_FUNCTION(_Name, _UName) \ template \ inline _Expr<_UnClos<_UName, _Expr, _Dom>, \ typename _Dom::value_type> \ _Name(const _Expr<_Dom, typename _Dom::value_type>& __e) \ { \ typedef typename _Dom::value_type _Tp; \ typedef _UnClos<_UName, _Expr, _Dom> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(__e())); \ } \ \ template \ inline _Expr<_UnClos<_UName, _ValArray, _Tp>, _Tp> \ _Name(const valarray<_Tp>& __v) \ { \ typedef _UnClos<_UName, _ValArray, _Tp> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(__v)); \ } _DEFINE_EXPR_UNARY_FUNCTION(abs, _Abs) _DEFINE_EXPR_UNARY_FUNCTION(cos, _Cos) _DEFINE_EXPR_UNARY_FUNCTION(acos, _Acos) _DEFINE_EXPR_UNARY_FUNCTION(cosh, _Cosh) _DEFINE_EXPR_UNARY_FUNCTION(sin, _Sin) _DEFINE_EXPR_UNARY_FUNCTION(asin, _Asin) _DEFINE_EXPR_UNARY_FUNCTION(sinh, _Sinh) _DEFINE_EXPR_UNARY_FUNCTION(tan, _Tan) _DEFINE_EXPR_UNARY_FUNCTION(tanh, _Tanh) _DEFINE_EXPR_UNARY_FUNCTION(atan, _Atan) _DEFINE_EXPR_UNARY_FUNCTION(exp, _Exp) _DEFINE_EXPR_UNARY_FUNCTION(log, _Log) _DEFINE_EXPR_UNARY_FUNCTION(log10, _Log10) _DEFINE_EXPR_UNARY_FUNCTION(sqrt, _Sqrt) #undef _DEFINE_EXPR_UNARY_FUNCTION #define _DEFINE_EXPR_BINARY_FUNCTION(_Fun, _UFun) \ template \ inline _Expr<_BinClos<_UFun, _Expr, _Expr, _Dom1, _Dom2>, \ typename _Dom1::value_type> \ _Fun(const _Expr<_Dom1, typename _Dom1::value_type>& __e1, \ const _Expr<_Dom2, typename _Dom2::value_type>& __e2) \ { \ typedef typename _Dom1::value_type _Tp; \ typedef _BinClos<_UFun, _Expr, _Expr, _Dom1, _Dom2> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(__e1(), __e2())); \ } \ \ template \ inline _Expr<_BinClos<_UFun, _Expr, _ValArray, _Dom, \ typename _Dom::value_type>, \ typename _Dom::value_type> \ _Fun(const _Expr<_Dom, typename _Dom::value_type>& __e, \ const valarray& __v) \ { \ typedef typename _Dom::value_type _Tp; \ typedef _BinClos<_UFun, _Expr, _ValArray, _Dom, _Tp> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(__e(), __v)); \ } \ \ template \ inline _Expr<_BinClos<_UFun, _ValArray, _Expr, \ typename _Dom::value_type, _Dom>, \ typename _Dom::value_type> \ _Fun(const valarray& __v, \ const _Expr<_Dom, typename _Dom::value_type>& __e) \ { \ typedef typename _Dom::value_type _Tp; \ typedef _BinClos<_UFun, _ValArray, _Expr, _Tp, _Dom> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(__v, __e())); \ } \ \ template \ inline _Expr<_BinClos<_UFun, _Expr, _Constant, _Dom, \ typename _Dom::value_type>, \ typename _Dom::value_type> \ _Fun(const _Expr<_Dom, typename _Dom::value_type>& __e, \ const typename _Dom::value_type& __t) \ { \ typedef typename _Dom::value_type _Tp; \ typedef _BinClos<_UFun, _Expr, _Constant, _Dom, _Tp> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(__e(), __t)); \ } \ \ template \ inline _Expr<_BinClos<_UFun, _Constant, _Expr, \ typename _Dom::value_type, _Dom>, \ typename _Dom::value_type> \ _Fun(const typename _Dom::value_type& __t, \ const _Expr<_Dom, typename _Dom::value_type>& __e) \ { \ typedef typename _Dom::value_type _Tp; \ typedef _BinClos<_UFun, _Constant, _Expr, _Tp, _Dom> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(__t, __e())); \ } \ \ template \ inline _Expr<_BinClos<_UFun, _ValArray, _ValArray, _Tp, _Tp>, _Tp> \ _Fun(const valarray<_Tp>& __v, const valarray<_Tp>& __w) \ { \ typedef _BinClos<_UFun, _ValArray, _ValArray, _Tp, _Tp> _Closure;\ return _Expr<_Closure, _Tp>(_Closure(__v, __w)); \ } \ \ template \ inline _Expr<_BinClos<_UFun, _ValArray, _Constant, _Tp, _Tp>, _Tp> \ _Fun(const valarray<_Tp>& __v, const _Tp& __t) \ { \ typedef _BinClos<_UFun, _ValArray, _Constant, _Tp, _Tp> _Closure;\ return _Expr<_Closure, _Tp>(_Closure(__v, __t)); \ } \ \ template \ inline _Expr<_BinClos<_UFun, _Constant, _ValArray, _Tp, _Tp>, _Tp> \ _Fun(const _Tp& __t, const valarray<_Tp>& __v) \ { \ typedef _BinClos<_UFun, _Constant, _ValArray, _Tp, _Tp> _Closure;\ return _Expr<_Closure, _Tp>(_Closure(__t, __v)); \ } _DEFINE_EXPR_BINARY_FUNCTION(atan2, _Atan2) _DEFINE_EXPR_BINARY_FUNCTION(pow, _Pow) #undef _DEFINE_EXPR_BINARY_FUNCTION _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _CPP_VALARRAY_AFTER_H */ PK!p/U/U8/bits/valarray_array.hnu[// The template and inlines for the -*- C++ -*- internal _Array helper class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/valarray_array.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _VALARRAY_ARRAY_H #define _VALARRAY_ARRAY_H 1 #pragma GCC system_header #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // // Helper functions on raw pointers // // We get memory by the old fashion way inline void* __valarray_get_memory(size_t __n) { return operator new(__n); } template inline _Tp*__restrict__ __valarray_get_storage(size_t __n) { return static_cast<_Tp*__restrict__> (std::__valarray_get_memory(__n * sizeof(_Tp))); } // Return memory to the system inline void __valarray_release_memory(void* __p) { operator delete(__p); } // Turn a raw-memory into an array of _Tp filled with _Tp() // This is required in 'valarray v(n);' template struct _Array_default_ctor { // Please note that this isn't exception safe. But // valarrays aren't required to be exception safe. inline static void _S_do_it(_Tp* __b, _Tp* __e) { while (__b != __e) new(__b++) _Tp(); } }; template struct _Array_default_ctor<_Tp, true> { // For fundamental types, it suffices to say 'memset()' inline static void _S_do_it(_Tp* __b, _Tp* __e) { __builtin_memset(__b, 0, (__e - __b) * sizeof(_Tp)); } }; template inline void __valarray_default_construct(_Tp* __b, _Tp* __e) { _Array_default_ctor<_Tp, __is_scalar<_Tp>::__value>::_S_do_it(__b, __e); } // Turn a raw-memory into an array of _Tp filled with __t // This is the required in valarray v(n, t). Also // used in valarray<>::resize(). template struct _Array_init_ctor { // Please note that this isn't exception safe. But // valarrays aren't required to be exception safe. inline static void _S_do_it(_Tp* __b, _Tp* __e, const _Tp __t) { while (__b != __e) new(__b++) _Tp(__t); } }; template struct _Array_init_ctor<_Tp, true> { inline static void _S_do_it(_Tp* __b, _Tp* __e, const _Tp __t) { while (__b != __e) *__b++ = __t; } }; template inline void __valarray_fill_construct(_Tp* __b, _Tp* __e, const _Tp __t) { _Array_init_ctor<_Tp, __is_trivial(_Tp)>::_S_do_it(__b, __e, __t); } // // copy-construct raw array [__o, *) from plain array [__b, __e) // We can't just say 'memcpy()' // template struct _Array_copy_ctor { // Please note that this isn't exception safe. But // valarrays aren't required to be exception safe. inline static void _S_do_it(const _Tp* __b, const _Tp* __e, _Tp* __restrict__ __o) { while (__b != __e) new(__o++) _Tp(*__b++); } }; template struct _Array_copy_ctor<_Tp, true> { inline static void _S_do_it(const _Tp* __b, const _Tp* __e, _Tp* __restrict__ __o) { if (__b) __builtin_memcpy(__o, __b, (__e - __b) * sizeof(_Tp)); } }; template inline void __valarray_copy_construct(const _Tp* __b, const _Tp* __e, _Tp* __restrict__ __o) { _Array_copy_ctor<_Tp, __is_trivial(_Tp)>::_S_do_it(__b, __e, __o); } // copy-construct raw array [__o, *) from strided array __a[<__n : __s>] template inline void __valarray_copy_construct (const _Tp* __restrict__ __a, size_t __n, size_t __s, _Tp* __restrict__ __o) { if (__is_trivial(_Tp)) while (__n--) { *__o++ = *__a; __a += __s; } else while (__n--) { new(__o++) _Tp(*__a); __a += __s; } } // copy-construct raw array [__o, *) from indexed array __a[__i[<__n>]] template inline void __valarray_copy_construct (const _Tp* __restrict__ __a, const size_t* __restrict__ __i, _Tp* __restrict__ __o, size_t __n) { if (__is_trivial(_Tp)) while (__n--) *__o++ = __a[*__i++]; else while (__n--) new (__o++) _Tp(__a[*__i++]); } // Do the necessary cleanup when we're done with arrays. template inline void __valarray_destroy_elements(_Tp* __b, _Tp* __e) { if (!__is_trivial(_Tp)) while (__b != __e) { __b->~_Tp(); ++__b; } } // Fill a plain array __a[<__n>] with __t template inline void __valarray_fill(_Tp* __restrict__ __a, size_t __n, const _Tp& __t) { while (__n--) *__a++ = __t; } // fill strided array __a[<__n-1 : __s>] with __t template inline void __valarray_fill(_Tp* __restrict__ __a, size_t __n, size_t __s, const _Tp& __t) { for (size_t __i = 0; __i < __n; ++__i, __a += __s) *__a = __t; } // fill indirect array __a[__i[<__n>]] with __i template inline void __valarray_fill(_Tp* __restrict__ __a, const size_t* __restrict__ __i, size_t __n, const _Tp& __t) { for (size_t __j = 0; __j < __n; ++__j, ++__i) __a[*__i] = __t; } // copy plain array __a[<__n>] in __b[<__n>] // For non-fundamental types, it is wrong to say 'memcpy()' template struct _Array_copier { inline static void _S_do_it(const _Tp* __restrict__ __a, size_t __n, _Tp* __restrict__ __b) { while(__n--) *__b++ = *__a++; } }; template struct _Array_copier<_Tp, true> { inline static void _S_do_it(const _Tp* __restrict__ __a, size_t __n, _Tp* __restrict__ __b) { if (__n != 0) __builtin_memcpy(__b, __a, __n * sizeof (_Tp)); } }; // Copy a plain array __a[<__n>] into a play array __b[<>] template inline void __valarray_copy(const _Tp* __restrict__ __a, size_t __n, _Tp* __restrict__ __b) { _Array_copier<_Tp, __is_trivial(_Tp)>::_S_do_it(__a, __n, __b); } // Copy strided array __a[<__n : __s>] in plain __b[<__n>] template inline void __valarray_copy(const _Tp* __restrict__ __a, size_t __n, size_t __s, _Tp* __restrict__ __b) { for (size_t __i = 0; __i < __n; ++__i, ++__b, __a += __s) *__b = *__a; } // Copy a plain array __a[<__n>] into a strided array __b[<__n : __s>] template inline void __valarray_copy(const _Tp* __restrict__ __a, _Tp* __restrict__ __b, size_t __n, size_t __s) { for (size_t __i = 0; __i < __n; ++__i, ++__a, __b += __s) *__b = *__a; } // Copy strided array __src[<__n : __s1>] into another // strided array __dst[< : __s2>]. Their sizes must match. template inline void __valarray_copy(const _Tp* __restrict__ __src, size_t __n, size_t __s1, _Tp* __restrict__ __dst, size_t __s2) { for (size_t __i = 0; __i < __n; ++__i) __dst[__i * __s2] = __src[__i * __s1]; } // Copy an indexed array __a[__i[<__n>]] in plain array __b[<__n>] template inline void __valarray_copy(const _Tp* __restrict__ __a, const size_t* __restrict__ __i, _Tp* __restrict__ __b, size_t __n) { for (size_t __j = 0; __j < __n; ++__j, ++__b, ++__i) *__b = __a[*__i]; } // Copy a plain array __a[<__n>] in an indexed array __b[__i[<__n>]] template inline void __valarray_copy(const _Tp* __restrict__ __a, size_t __n, _Tp* __restrict__ __b, const size_t* __restrict__ __i) { for (size_t __j = 0; __j < __n; ++__j, ++__a, ++__i) __b[*__i] = *__a; } // Copy the __n first elements of an indexed array __src[<__i>] into // another indexed array __dst[<__j>]. template inline void __valarray_copy(const _Tp* __restrict__ __src, size_t __n, const size_t* __restrict__ __i, _Tp* __restrict__ __dst, const size_t* __restrict__ __j) { for (size_t __k = 0; __k < __n; ++__k) __dst[*__j++] = __src[*__i++]; } // // Compute the sum of elements in range [__f, __l) which must not be empty. // This is a naive algorithm. It suffers from cancelling. // In the future try to specialize for _Tp = float, double, long double // using a more accurate algorithm. // template inline _Tp __valarray_sum(const _Tp* __f, const _Tp* __l) { _Tp __r = *__f++; while (__f != __l) __r += *__f++; return __r; } // Compute the product of all elements in range [__f, __l) template inline _Tp __valarray_product(const _Tp* __f, const _Tp* __l) { _Tp __r = _Tp(1); while (__f != __l) __r = __r * *__f++; return __r; } // Compute the min/max of an array-expression template inline typename _Ta::value_type __valarray_min(const _Ta& __a) { size_t __s = __a.size(); typedef typename _Ta::value_type _Value_type; _Value_type __r = __s == 0 ? _Value_type() : __a[0]; for (size_t __i = 1; __i < __s; ++__i) { _Value_type __t = __a[__i]; if (__t < __r) __r = __t; } return __r; } template inline typename _Ta::value_type __valarray_max(const _Ta& __a) { size_t __s = __a.size(); typedef typename _Ta::value_type _Value_type; _Value_type __r = __s == 0 ? _Value_type() : __a[0]; for (size_t __i = 1; __i < __s; ++__i) { _Value_type __t = __a[__i]; if (__t > __r) __r = __t; } return __r; } // // Helper class _Array, first layer of valarray abstraction. // All operations on valarray should be forwarded to this class // whenever possible. -- gdr // template struct _Array { explicit _Array(size_t); explicit _Array(_Tp* const __restrict__); explicit _Array(const valarray<_Tp>&); _Array(const _Tp* __restrict__, size_t); _Tp* begin() const; _Tp* const __restrict__ _M_data; }; // Copy-construct plain array __b[<__n>] from indexed array __a[__i[<__n>]] template inline void __valarray_copy_construct(_Array<_Tp> __a, _Array __i, _Array<_Tp> __b, size_t __n) { std::__valarray_copy_construct(__a._M_data, __i._M_data, __b._M_data, __n); } // Copy-construct plain array __b[<__n>] from strided array __a[<__n : __s>] template inline void __valarray_copy_construct(_Array<_Tp> __a, size_t __n, size_t __s, _Array<_Tp> __b) { std::__valarray_copy_construct(__a._M_data, __n, __s, __b._M_data); } template inline void __valarray_fill (_Array<_Tp> __a, size_t __n, const _Tp& __t) { std::__valarray_fill(__a._M_data, __n, __t); } template inline void __valarray_fill(_Array<_Tp> __a, size_t __n, size_t __s, const _Tp& __t) { std::__valarray_fill(__a._M_data, __n, __s, __t); } template inline void __valarray_fill(_Array<_Tp> __a, _Array __i, size_t __n, const _Tp& __t) { std::__valarray_fill(__a._M_data, __i._M_data, __n, __t); } // Copy a plain array __a[<__n>] into a play array __b[<>] template inline void __valarray_copy(_Array<_Tp> __a, size_t __n, _Array<_Tp> __b) { std::__valarray_copy(__a._M_data, __n, __b._M_data); } // Copy strided array __a[<__n : __s>] in plain __b[<__n>] template inline void __valarray_copy(_Array<_Tp> __a, size_t __n, size_t __s, _Array<_Tp> __b) { std::__valarray_copy(__a._M_data, __n, __s, __b._M_data); } // Copy a plain array __a[<__n>] into a strided array __b[<__n : __s>] template inline void __valarray_copy(_Array<_Tp> __a, _Array<_Tp> __b, size_t __n, size_t __s) { __valarray_copy(__a._M_data, __b._M_data, __n, __s); } // Copy strided array __src[<__n : __s1>] into another // strided array __dst[< : __s2>]. Their sizes must match. template inline void __valarray_copy(_Array<_Tp> __a, size_t __n, size_t __s1, _Array<_Tp> __b, size_t __s2) { std::__valarray_copy(__a._M_data, __n, __s1, __b._M_data, __s2); } // Copy an indexed array __a[__i[<__n>]] in plain array __b[<__n>] template inline void __valarray_copy(_Array<_Tp> __a, _Array __i, _Array<_Tp> __b, size_t __n) { std::__valarray_copy(__a._M_data, __i._M_data, __b._M_data, __n); } // Copy a plain array __a[<__n>] in an indexed array __b[__i[<__n>]] template inline void __valarray_copy(_Array<_Tp> __a, size_t __n, _Array<_Tp> __b, _Array __i) { std::__valarray_copy(__a._M_data, __n, __b._M_data, __i._M_data); } // Copy the __n first elements of an indexed array __src[<__i>] into // another indexed array __dst[<__j>]. template inline void __valarray_copy(_Array<_Tp> __src, size_t __n, _Array __i, _Array<_Tp> __dst, _Array __j) { std::__valarray_copy(__src._M_data, __n, __i._M_data, __dst._M_data, __j._M_data); } template inline _Array<_Tp>::_Array(size_t __n) : _M_data(__valarray_get_storage<_Tp>(__n)) { std::__valarray_default_construct(_M_data, _M_data + __n); } template inline _Array<_Tp>::_Array(_Tp* const __restrict__ __p) : _M_data (__p) {} template inline _Array<_Tp>::_Array(const valarray<_Tp>& __v) : _M_data (__v._M_data) {} template inline _Array<_Tp>::_Array(const _Tp* __restrict__ __b, size_t __s) : _M_data(__valarray_get_storage<_Tp>(__s)) { std::__valarray_copy_construct(__b, __s, _M_data); } template inline _Tp* _Array<_Tp>::begin () const { return _M_data; } #define _DEFINE_ARRAY_FUNCTION(_Op, _Name) \ template \ inline void \ _Array_augmented_##_Name(_Array<_Tp> __a, size_t __n, const _Tp& __t) \ { \ for (_Tp* __p = __a._M_data; __p < __a._M_data + __n; ++__p) \ *__p _Op##= __t; \ } \ \ template \ inline void \ _Array_augmented_##_Name(_Array<_Tp> __a, size_t __n, _Array<_Tp> __b) \ { \ _Tp* __p = __a._M_data; \ for (_Tp* __q = __b._M_data; __q < __b._M_data + __n; ++__p, ++__q) \ *__p _Op##= *__q; \ } \ \ template \ void \ _Array_augmented_##_Name(_Array<_Tp> __a, \ const _Expr<_Dom, _Tp>& __e, size_t __n) \ { \ _Tp* __p(__a._M_data); \ for (size_t __i = 0; __i < __n; ++__i, ++__p) \ *__p _Op##= __e[__i]; \ } \ \ template \ inline void \ _Array_augmented_##_Name(_Array<_Tp> __a, size_t __n, size_t __s, \ _Array<_Tp> __b) \ { \ _Tp* __q(__b._M_data); \ for (_Tp* __p = __a._M_data; __p < __a._M_data + __s * __n; \ __p += __s, ++__q) \ *__p _Op##= *__q; \ } \ \ template \ inline void \ _Array_augmented_##_Name(_Array<_Tp> __a, _Array<_Tp> __b, \ size_t __n, size_t __s) \ { \ _Tp* __q(__b._M_data); \ for (_Tp* __p = __a._M_data; __p < __a._M_data + __n; \ ++__p, __q += __s) \ *__p _Op##= *__q; \ } \ \ template \ void \ _Array_augmented_##_Name(_Array<_Tp> __a, size_t __s, \ const _Expr<_Dom, _Tp>& __e, size_t __n) \ { \ _Tp* __p(__a._M_data); \ for (size_t __i = 0; __i < __n; ++__i, __p += __s) \ *__p _Op##= __e[__i]; \ } \ \ template \ inline void \ _Array_augmented_##_Name(_Array<_Tp> __a, _Array __i, \ _Array<_Tp> __b, size_t __n) \ { \ _Tp* __q(__b._M_data); \ for (size_t* __j = __i._M_data; __j < __i._M_data + __n; \ ++__j, ++__q) \ __a._M_data[*__j] _Op##= *__q; \ } \ \ template \ inline void \ _Array_augmented_##_Name(_Array<_Tp> __a, size_t __n, \ _Array<_Tp> __b, _Array __i) \ { \ _Tp* __p(__a._M_data); \ for (size_t* __j = __i._M_data; __j<__i._M_data + __n; \ ++__j, ++__p) \ *__p _Op##= __b._M_data[*__j]; \ } \ \ template \ void \ _Array_augmented_##_Name(_Array<_Tp> __a, _Array __i, \ const _Expr<_Dom, _Tp>& __e, size_t __n) \ { \ size_t* __j(__i._M_data); \ for (size_t __k = 0; __k<__n; ++__k, ++__j) \ __a._M_data[*__j] _Op##= __e[__k]; \ } \ \ template \ void \ _Array_augmented_##_Name(_Array<_Tp> __a, _Array __m, \ _Array<_Tp> __b, size_t __n) \ { \ bool* __ok(__m._M_data); \ _Tp* __p(__a._M_data); \ for (_Tp* __q = __b._M_data; __q < __b._M_data + __n; \ ++__q, ++__ok, ++__p) \ { \ while (! *__ok) \ { \ ++__ok; \ ++__p; \ } \ *__p _Op##= *__q; \ } \ } \ \ template \ void \ _Array_augmented_##_Name(_Array<_Tp> __a, size_t __n, \ _Array<_Tp> __b, _Array __m) \ { \ bool* __ok(__m._M_data); \ _Tp* __q(__b._M_data); \ for (_Tp* __p = __a._M_data; __p < __a._M_data + __n; \ ++__p, ++__ok, ++__q) \ { \ while (! *__ok) \ { \ ++__ok; \ ++__q; \ } \ *__p _Op##= *__q; \ } \ } \ \ template \ void \ _Array_augmented_##_Name(_Array<_Tp> __a, _Array __m, \ const _Expr<_Dom, _Tp>& __e, size_t __n) \ { \ bool* __ok(__m._M_data); \ _Tp* __p(__a._M_data); \ for (size_t __i = 0; __i < __n; ++__i, ++__ok, ++__p) \ { \ while (! *__ok) \ { \ ++__ok; \ ++__p; \ } \ *__p _Op##= __e[__i]; \ } \ } _DEFINE_ARRAY_FUNCTION(+, __plus) _DEFINE_ARRAY_FUNCTION(-, __minus) _DEFINE_ARRAY_FUNCTION(*, __multiplies) _DEFINE_ARRAY_FUNCTION(/, __divides) _DEFINE_ARRAY_FUNCTION(%, __modulus) _DEFINE_ARRAY_FUNCTION(^, __bitwise_xor) _DEFINE_ARRAY_FUNCTION(|, __bitwise_or) _DEFINE_ARRAY_FUNCTION(&, __bitwise_and) _DEFINE_ARRAY_FUNCTION(<<, __shift_left) _DEFINE_ARRAY_FUNCTION(>>, __shift_right) #undef _DEFINE_ARRAY_FUNCTION _GLIBCXX_END_NAMESPACE_VERSION } // namespace # include #endif /* _ARRAY_H */ PK!mVV8/bits/valarray_array.tccnu[// The template and inlines for the -*- C++ -*- internal _Array helper class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/valarray_array.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _VALARRAY_ARRAY_TCC #define _VALARRAY_ARRAY_TCC 1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template void __valarray_fill(_Array<_Tp> __a, size_t __n, _Array __m, const _Tp& __t) { _Tp* __p = __a._M_data; bool* __ok (__m._M_data); for (size_t __i=0; __i < __n; ++__i, ++__ok, ++__p) { while (!*__ok) { ++__ok; ++__p; } *__p = __t; } } // Copy n elements of a into consecutive elements of b. When m is // false, the corresponding element of a is skipped. m must contain // at least n true elements. a must contain at least n elements and // enough elements to match up with m through the nth true element // of m. I.e. if n is 10, m has 15 elements with 5 false followed // by 10 true, a must have 15 elements. template void __valarray_copy(_Array<_Tp> __a, _Array __m, _Array<_Tp> __b, size_t __n) { _Tp* __p (__a._M_data); bool* __ok (__m._M_data); for (_Tp* __q = __b._M_data; __q < __b._M_data + __n; ++__q, ++__ok, ++__p) { while (! *__ok) { ++__ok; ++__p; } *__q = *__p; } } // Copy n consecutive elements from a into elements of b. Elements // of b are skipped if the corresponding element of m is false. m // must contain at least n true elements. b must have at least as // many elements as the index of the nth true element of m. I.e. if // m has 15 elements with 5 false followed by 10 true, b must have // at least 15 elements. template void __valarray_copy(_Array<_Tp> __a, size_t __n, _Array<_Tp> __b, _Array __m) { _Tp* __q (__b._M_data); bool* __ok (__m._M_data); for (_Tp* __p = __a._M_data; __p < __a._M_data+__n; ++__p, ++__ok, ++__q) { while (! *__ok) { ++__ok; ++__q; } *__q = *__p; } } // Copy n elements from a into elements of b. Elements of a are // skipped if the corresponding element of m is false. Elements of // b are skipped if the corresponding element of k is false. m and // k must contain at least n true elements. a and b must have at // least as many elements as the index of the nth true element of m. template void __valarray_copy(_Array<_Tp> __a, _Array __m, size_t __n, _Array<_Tp> __b, _Array __k) { _Tp* __p (__a._M_data); _Tp* __q (__b._M_data); bool* __srcok (__m._M_data); bool* __dstok (__k._M_data); for (size_t __i = 0; __i < __n; ++__srcok, ++__p, ++__dstok, ++__q, ++__i) { while (! *__srcok) { ++__srcok; ++__p; } while (! *__dstok) { ++__dstok; ++__q; } *__q = *__p; } } // Copy n consecutive elements of e into consecutive elements of a. // I.e. a[i] = e[i]. template void __valarray_copy(const _Expr<_Dom, _Tp>& __e, size_t __n, _Array<_Tp> __a) { _Tp* __p (__a._M_data); for (size_t __i = 0; __i < __n; ++__i, ++__p) *__p = __e[__i]; } // Copy n consecutive elements of e into elements of a using stride // s. I.e., a[0] = e[0], a[s] = e[1], a[2*s] = e[2]. template void __valarray_copy(const _Expr<_Dom, _Tp>& __e, size_t __n, _Array<_Tp> __a, size_t __s) { _Tp* __p (__a._M_data); for (size_t __i = 0; __i < __n; ++__i, __p += __s) *__p = __e[__i]; } // Copy n consecutive elements of e into elements of a indexed by // contents of i. I.e., a[i[0]] = e[0]. template void __valarray_copy(const _Expr<_Dom, _Tp>& __e, size_t __n, _Array<_Tp> __a, _Array __i) { size_t* __j (__i._M_data); for (size_t __k = 0; __k < __n; ++__k, ++__j) __a._M_data[*__j] = __e[__k]; } // Copy n elements of e indexed by contents of f into elements of a // indexed by contents of i. I.e., a[i[0]] = e[f[0]]. template void __valarray_copy(_Array<_Tp> __e, _Array __f, size_t __n, _Array<_Tp> __a, _Array __i) { size_t* __g (__f._M_data); size_t* __j (__i._M_data); for (size_t __k = 0; __k < __n; ++__k, ++__j, ++__g) __a._M_data[*__j] = __e._M_data[*__g]; } // Copy n consecutive elements of e into elements of a. Elements of // a are skipped if the corresponding element of m is false. m must // have at least n true elements and a must have at least as many // elements as the index of the nth true element of m. I.e. if m // has 5 false followed by 10 true elements and n == 10, a must have // at least 15 elements. template void __valarray_copy(const _Expr<_Dom, _Tp>& __e, size_t __n, _Array<_Tp> __a, _Array __m) { bool* __ok (__m._M_data); _Tp* __p (__a._M_data); for (size_t __i = 0; __i < __n; ++__i, ++__ok, ++__p) { while (! *__ok) { ++__ok; ++__p; } *__p = __e[__i]; } } template void __valarray_copy_construct(const _Expr<_Dom, _Tp>& __e, size_t __n, _Array<_Tp> __a) { _Tp* __p (__a._M_data); for (size_t __i = 0; __i < __n; ++__i, ++__p) new (__p) _Tp(__e[__i]); } template void __valarray_copy_construct(_Array<_Tp> __a, _Array __m, _Array<_Tp> __b, size_t __n) { _Tp* __p (__a._M_data); bool* __ok (__m._M_data); for (_Tp* __q = __b._M_data; __q < __b._M_data+__n; ++__q, ++__ok, ++__p) { while (! *__ok) { ++__ok; ++__p; } new (__q) _Tp(*__p); } } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _VALARRAY_ARRAY_TCC */ PK!_QHQH8/bits/valarray_before.hnu[// The template and inlines for the -*- C++ -*- internal _Meta class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/valarray_before.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _VALARRAY_BEFORE_H #define _VALARRAY_BEFORE_H 1 #pragma GCC system_header #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // // Implementing a loosened valarray return value is tricky. // First we need to meet 26.3.1/3: we should not add more than // two levels of template nesting. Therefore we resort to template // template to "flatten" loosened return value types. // At some point we use partial specialization to remove one level // template nesting due to _Expr<> // // This class is NOT defined. It doesn't need to. template class _Constant; // Implementations of unary functions applied to valarray<>s. // I use hard-coded object functions here instead of a generic // approach like pointers to function: // 1) correctness: some functions take references, others values. // we can't deduce the correct type afterwards. // 2) efficiency -- object functions can be easily inlined // 3) be Koenig-lookup-friendly struct _Abs { template _Tp operator()(const _Tp& __t) const { return abs(__t); } }; struct _Cos { template _Tp operator()(const _Tp& __t) const { return cos(__t); } }; struct _Acos { template _Tp operator()(const _Tp& __t) const { return acos(__t); } }; struct _Cosh { template _Tp operator()(const _Tp& __t) const { return cosh(__t); } }; struct _Sin { template _Tp operator()(const _Tp& __t) const { return sin(__t); } }; struct _Asin { template _Tp operator()(const _Tp& __t) const { return asin(__t); } }; struct _Sinh { template _Tp operator()(const _Tp& __t) const { return sinh(__t); } }; struct _Tan { template _Tp operator()(const _Tp& __t) const { return tan(__t); } }; struct _Atan { template _Tp operator()(const _Tp& __t) const { return atan(__t); } }; struct _Tanh { template _Tp operator()(const _Tp& __t) const { return tanh(__t); } }; struct _Exp { template _Tp operator()(const _Tp& __t) const { return exp(__t); } }; struct _Log { template _Tp operator()(const _Tp& __t) const { return log(__t); } }; struct _Log10 { template _Tp operator()(const _Tp& __t) const { return log10(__t); } }; struct _Sqrt { template _Tp operator()(const _Tp& __t) const { return sqrt(__t); } }; // In the past, we used to tailor operator applications semantics // to the specialization of standard function objects (i.e. plus<>, etc.) // That is incorrect. Therefore we provide our own surrogates. struct __unary_plus { template _Tp operator()(const _Tp& __t) const { return +__t; } }; struct __negate { template _Tp operator()(const _Tp& __t) const { return -__t; } }; struct __bitwise_not { template _Tp operator()(const _Tp& __t) const { return ~__t; } }; struct __plus { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x + __y; } }; struct __minus { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x - __y; } }; struct __multiplies { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x * __y; } }; struct __divides { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x / __y; } }; struct __modulus { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x % __y; } }; struct __bitwise_xor { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x ^ __y; } }; struct __bitwise_and { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x & __y; } }; struct __bitwise_or { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x | __y; } }; struct __shift_left { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x << __y; } }; struct __shift_right { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x >> __y; } }; struct __logical_and { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x && __y; } }; struct __logical_or { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x || __y; } }; struct __logical_not { template bool operator()(const _Tp& __x) const { return !__x; } }; struct __equal_to { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x == __y; } }; struct __not_equal_to { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x != __y; } }; struct __less { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x < __y; } }; struct __greater { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x > __y; } }; struct __less_equal { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x <= __y; } }; struct __greater_equal { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x >= __y; } }; // The few binary functions we miss. struct _Atan2 { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return atan2(__x, __y); } }; struct _Pow { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return pow(__x, __y); } }; template struct __fun_with_valarray { typedef _Tp result_type; }; template struct __fun_with_valarray<_Tp, false> { // No result type defined for invalid value types. }; // We need these bits in order to recover the return type of // some functions/operators now that we're no longer using // function templates. template struct __fun : __fun_with_valarray<_Tp> { }; // several specializations for relational operators. template struct __fun<__logical_not, _Tp> { typedef bool result_type; }; template struct __fun<__logical_and, _Tp> { typedef bool result_type; }; template struct __fun<__logical_or, _Tp> { typedef bool result_type; }; template struct __fun<__less, _Tp> { typedef bool result_type; }; template struct __fun<__greater, _Tp> { typedef bool result_type; }; template struct __fun<__less_equal, _Tp> { typedef bool result_type; }; template struct __fun<__greater_equal, _Tp> { typedef bool result_type; }; template struct __fun<__equal_to, _Tp> { typedef bool result_type; }; template struct __fun<__not_equal_to, _Tp> { typedef bool result_type; }; // // Apply function taking a value/const reference closure // template class _FunBase { public: typedef typename _Dom::value_type value_type; _FunBase(const _Dom& __e, value_type __f(_Arg)) : _M_expr(__e), _M_func(__f) {} value_type operator[](size_t __i) const { return _M_func (_M_expr[__i]); } size_t size() const { return _M_expr.size ();} private: const _Dom& _M_expr; value_type (*_M_func)(_Arg); }; template struct _ValFunClos<_Expr,_Dom> : _FunBase<_Dom, typename _Dom::value_type> { typedef _FunBase<_Dom, typename _Dom::value_type> _Base; typedef typename _Base::value_type value_type; typedef value_type _Tp; _ValFunClos(const _Dom& __e, _Tp __f(_Tp)) : _Base(__e, __f) {} }; template struct _ValFunClos<_ValArray,_Tp> : _FunBase, _Tp> { typedef _FunBase, _Tp> _Base; typedef _Tp value_type; _ValFunClos(const valarray<_Tp>& __v, _Tp __f(_Tp)) : _Base(__v, __f) {} }; template struct _RefFunClos<_Expr, _Dom> : _FunBase<_Dom, const typename _Dom::value_type&> { typedef _FunBase<_Dom, const typename _Dom::value_type&> _Base; typedef typename _Base::value_type value_type; typedef value_type _Tp; _RefFunClos(const _Dom& __e, _Tp __f(const _Tp&)) : _Base(__e, __f) {} }; template struct _RefFunClos<_ValArray, _Tp> : _FunBase, const _Tp&> { typedef _FunBase, const _Tp&> _Base; typedef _Tp value_type; _RefFunClos(const valarray<_Tp>& __v, _Tp __f(const _Tp&)) : _Base(__v, __f) {} }; // // Unary expression closure. // template class _UnBase { public: typedef typename _Arg::value_type _Vt; typedef typename __fun<_Oper, _Vt>::result_type value_type; _UnBase(const _Arg& __e) : _M_expr(__e) {} value_type operator[](size_t __i) const { return _Oper()(_M_expr[__i]); } size_t size() const { return _M_expr.size(); } private: const _Arg& _M_expr; }; template struct _UnClos<_Oper, _Expr, _Dom> : _UnBase<_Oper, _Dom> { typedef _Dom _Arg; typedef _UnBase<_Oper, _Dom> _Base; typedef typename _Base::value_type value_type; _UnClos(const _Arg& __e) : _Base(__e) {} }; template struct _UnClos<_Oper, _ValArray, _Tp> : _UnBase<_Oper, valarray<_Tp> > { typedef valarray<_Tp> _Arg; typedef _UnBase<_Oper, valarray<_Tp> > _Base; typedef typename _Base::value_type value_type; _UnClos(const _Arg& __e) : _Base(__e) {} }; // // Binary expression closure. // template class _BinBase { public: typedef typename _FirstArg::value_type _Vt; typedef typename __fun<_Oper, _Vt>::result_type value_type; _BinBase(const _FirstArg& __e1, const _SecondArg& __e2) : _M_expr1(__e1), _M_expr2(__e2) {} value_type operator[](size_t __i) const { return _Oper()(_M_expr1[__i], _M_expr2[__i]); } size_t size() const { return _M_expr1.size(); } private: const _FirstArg& _M_expr1; const _SecondArg& _M_expr2; }; template class _BinBase2 { public: typedef typename _Clos::value_type _Vt; typedef typename __fun<_Oper, _Vt>::result_type value_type; _BinBase2(const _Clos& __e, const _Vt& __t) : _M_expr1(__e), _M_expr2(__t) {} value_type operator[](size_t __i) const { return _Oper()(_M_expr1[__i], _M_expr2); } size_t size() const { return _M_expr1.size(); } private: const _Clos& _M_expr1; const _Vt& _M_expr2; }; template class _BinBase1 { public: typedef typename _Clos::value_type _Vt; typedef typename __fun<_Oper, _Vt>::result_type value_type; _BinBase1(const _Vt& __t, const _Clos& __e) : _M_expr1(__t), _M_expr2(__e) {} value_type operator[](size_t __i) const { return _Oper()(_M_expr1, _M_expr2[__i]); } size_t size() const { return _M_expr2.size(); } private: const _Vt& _M_expr1; const _Clos& _M_expr2; }; template struct _BinClos<_Oper, _Expr, _Expr, _Dom1, _Dom2> : _BinBase<_Oper, _Dom1, _Dom2> { typedef _BinBase<_Oper, _Dom1, _Dom2> _Base; typedef typename _Base::value_type value_type; _BinClos(const _Dom1& __e1, const _Dom2& __e2) : _Base(__e1, __e2) {} }; template struct _BinClos<_Oper,_ValArray, _ValArray, _Tp, _Tp> : _BinBase<_Oper, valarray<_Tp>, valarray<_Tp> > { typedef _BinBase<_Oper, valarray<_Tp>, valarray<_Tp> > _Base; typedef typename _Base::value_type value_type; _BinClos(const valarray<_Tp>& __v, const valarray<_Tp>& __w) : _Base(__v, __w) {} }; template struct _BinClos<_Oper, _Expr, _ValArray, _Dom, typename _Dom::value_type> : _BinBase<_Oper, _Dom, valarray > { typedef typename _Dom::value_type _Tp; typedef _BinBase<_Oper,_Dom,valarray<_Tp> > _Base; typedef typename _Base::value_type value_type; _BinClos(const _Dom& __e1, const valarray<_Tp>& __e2) : _Base(__e1, __e2) {} }; template struct _BinClos<_Oper, _ValArray, _Expr, typename _Dom::value_type, _Dom> : _BinBase<_Oper, valarray,_Dom> { typedef typename _Dom::value_type _Tp; typedef _BinBase<_Oper, valarray<_Tp>, _Dom> _Base; typedef typename _Base::value_type value_type; _BinClos(const valarray<_Tp>& __e1, const _Dom& __e2) : _Base(__e1, __e2) {} }; template struct _BinClos<_Oper, _Expr, _Constant, _Dom, typename _Dom::value_type> : _BinBase2<_Oper, _Dom> { typedef typename _Dom::value_type _Tp; typedef _BinBase2<_Oper,_Dom> _Base; typedef typename _Base::value_type value_type; _BinClos(const _Dom& __e1, const _Tp& __e2) : _Base(__e1, __e2) {} }; template struct _BinClos<_Oper, _Constant, _Expr, typename _Dom::value_type, _Dom> : _BinBase1<_Oper, _Dom> { typedef typename _Dom::value_type _Tp; typedef _BinBase1<_Oper, _Dom> _Base; typedef typename _Base::value_type value_type; _BinClos(const _Tp& __e1, const _Dom& __e2) : _Base(__e1, __e2) {} }; template struct _BinClos<_Oper, _ValArray, _Constant, _Tp, _Tp> : _BinBase2<_Oper, valarray<_Tp> > { typedef _BinBase2<_Oper,valarray<_Tp> > _Base; typedef typename _Base::value_type value_type; _BinClos(const valarray<_Tp>& __v, const _Tp& __t) : _Base(__v, __t) {} }; template struct _BinClos<_Oper, _Constant, _ValArray, _Tp, _Tp> : _BinBase1<_Oper, valarray<_Tp> > { typedef _BinBase1<_Oper, valarray<_Tp> > _Base; typedef typename _Base::value_type value_type; _BinClos(const _Tp& __t, const valarray<_Tp>& __v) : _Base(__t, __v) {} }; // // slice_array closure. // template class _SBase { public: typedef typename _Dom::value_type value_type; _SBase (const _Dom& __e, const slice& __s) : _M_expr (__e), _M_slice (__s) {} value_type operator[] (size_t __i) const { return _M_expr[_M_slice.start () + __i * _M_slice.stride ()]; } size_t size() const { return _M_slice.size (); } private: const _Dom& _M_expr; const slice& _M_slice; }; template class _SBase<_Array<_Tp> > { public: typedef _Tp value_type; _SBase (_Array<_Tp> __a, const slice& __s) : _M_array (__a._M_data+__s.start()), _M_size (__s.size()), _M_stride (__s.stride()) {} value_type operator[] (size_t __i) const { return _M_array._M_data[__i * _M_stride]; } size_t size() const { return _M_size; } private: const _Array<_Tp> _M_array; const size_t _M_size; const size_t _M_stride; }; template struct _SClos<_Expr, _Dom> : _SBase<_Dom> { typedef _SBase<_Dom> _Base; typedef typename _Base::value_type value_type; _SClos (const _Dom& __e, const slice& __s) : _Base (__e, __s) {} }; template struct _SClos<_ValArray, _Tp> : _SBase<_Array<_Tp> > { typedef _SBase<_Array<_Tp> > _Base; typedef _Tp value_type; _SClos (_Array<_Tp> __a, const slice& __s) : _Base (__a, __s) {} }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _CPP_VALARRAY_BEFORE_H */ PK!?css8/bits/vector.tccnu[// Vector implementation (out of line) -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/vector.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{vector} */ #ifndef _VECTOR_TCC #define _VECTOR_TCC 1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER template void vector<_Tp, _Alloc>:: reserve(size_type __n) { if (__n > this->max_size()) __throw_length_error(__N("vector::reserve")); if (this->capacity() < __n) { const size_type __old_size = size(); pointer __tmp = _M_allocate_and_copy(__n, _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(this->_M_impl._M_start), _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(this->_M_impl._M_finish)); _GLIBCXX_ASAN_ANNOTATE_REINIT; std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish, _M_get_Tp_allocator()); _M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage - this->_M_impl._M_start); this->_M_impl._M_start = __tmp; this->_M_impl._M_finish = __tmp + __old_size; this->_M_impl._M_end_of_storage = this->_M_impl._M_start + __n; } } #if __cplusplus >= 201103L template template #if __cplusplus > 201402L typename vector<_Tp, _Alloc>::reference #else void #endif vector<_Tp, _Alloc>:: emplace_back(_Args&&... __args) { if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) { _GLIBCXX_ASAN_ANNOTATE_GROW(1); _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, std::forward<_Args>(__args)...); ++this->_M_impl._M_finish; _GLIBCXX_ASAN_ANNOTATE_GREW(1); } else _M_realloc_insert(end(), std::forward<_Args>(__args)...); #if __cplusplus > 201402L return back(); #endif } #endif template typename vector<_Tp, _Alloc>::iterator vector<_Tp, _Alloc>:: #if __cplusplus >= 201103L insert(const_iterator __position, const value_type& __x) #else insert(iterator __position, const value_type& __x) #endif { const size_type __n = __position - begin(); if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) if (__position == end()) { _GLIBCXX_ASAN_ANNOTATE_GROW(1); _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, __x); ++this->_M_impl._M_finish; _GLIBCXX_ASAN_ANNOTATE_GREW(1); } else { #if __cplusplus >= 201103L const auto __pos = begin() + (__position - cbegin()); // __x could be an existing element of this vector, so make a // copy of it before _M_insert_aux moves elements around. _Temporary_value __x_copy(this, __x); _M_insert_aux(__pos, std::move(__x_copy._M_val())); #else _M_insert_aux(__position, __x); #endif } else #if __cplusplus >= 201103L _M_realloc_insert(begin() + (__position - cbegin()), __x); #else _M_realloc_insert(__position, __x); #endif return iterator(this->_M_impl._M_start + __n); } template typename vector<_Tp, _Alloc>::iterator vector<_Tp, _Alloc>:: _M_erase(iterator __position) { if (__position + 1 != end()) _GLIBCXX_MOVE3(__position + 1, end(), __position); --this->_M_impl._M_finish; _Alloc_traits::destroy(this->_M_impl, this->_M_impl._M_finish); _GLIBCXX_ASAN_ANNOTATE_SHRINK(1); return __position; } template typename vector<_Tp, _Alloc>::iterator vector<_Tp, _Alloc>:: _M_erase(iterator __first, iterator __last) { if (__first != __last) { if (__last != end()) _GLIBCXX_MOVE3(__last, end(), __first); _M_erase_at_end(__first.base() + (end() - __last)); } return __first; } template vector<_Tp, _Alloc>& vector<_Tp, _Alloc>:: operator=(const vector<_Tp, _Alloc>& __x) { if (&__x != this) { _GLIBCXX_ASAN_ANNOTATE_REINIT; #if __cplusplus >= 201103L if (_Alloc_traits::_S_propagate_on_copy_assign()) { if (!_Alloc_traits::_S_always_equal() && _M_get_Tp_allocator() != __x._M_get_Tp_allocator()) { // replacement allocator cannot free existing storage this->clear(); _M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage - this->_M_impl._M_start); this->_M_impl._M_start = nullptr; this->_M_impl._M_finish = nullptr; this->_M_impl._M_end_of_storage = nullptr; } std::__alloc_on_copy(_M_get_Tp_allocator(), __x._M_get_Tp_allocator()); } #endif const size_type __xlen = __x.size(); if (__xlen > capacity()) { pointer __tmp = _M_allocate_and_copy(__xlen, __x.begin(), __x.end()); std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish, _M_get_Tp_allocator()); _M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage - this->_M_impl._M_start); this->_M_impl._M_start = __tmp; this->_M_impl._M_end_of_storage = this->_M_impl._M_start + __xlen; } else if (size() >= __xlen) { std::_Destroy(std::copy(__x.begin(), __x.end(), begin()), end(), _M_get_Tp_allocator()); } else { std::copy(__x._M_impl._M_start, __x._M_impl._M_start + size(), this->_M_impl._M_start); std::__uninitialized_copy_a(__x._M_impl._M_start + size(), __x._M_impl._M_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); } this->_M_impl._M_finish = this->_M_impl._M_start + __xlen; } return *this; } template void vector<_Tp, _Alloc>:: _M_fill_assign(size_t __n, const value_type& __val) { if (__n > capacity()) { vector __tmp(__n, __val, _M_get_Tp_allocator()); __tmp._M_impl._M_swap_data(this->_M_impl); } else if (__n > size()) { std::fill(begin(), end(), __val); const size_type __add = __n - size(); _GLIBCXX_ASAN_ANNOTATE_GROW(__add); this->_M_impl._M_finish = std::__uninitialized_fill_n_a(this->_M_impl._M_finish, __add, __val, _M_get_Tp_allocator()); _GLIBCXX_ASAN_ANNOTATE_GREW(__add); } else _M_erase_at_end(std::fill_n(this->_M_impl._M_start, __n, __val)); } template template void vector<_Tp, _Alloc>:: _M_assign_aux(_InputIterator __first, _InputIterator __last, std::input_iterator_tag) { pointer __cur(this->_M_impl._M_start); for (; __first != __last && __cur != this->_M_impl._M_finish; ++__cur, ++__first) *__cur = *__first; if (__first == __last) _M_erase_at_end(__cur); else _M_range_insert(end(), __first, __last, std::__iterator_category(__first)); } template template void vector<_Tp, _Alloc>:: _M_assign_aux(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { const size_type __len = std::distance(__first, __last); if (__len > capacity()) { pointer __tmp(_M_allocate_and_copy(__len, __first, __last)); _GLIBCXX_ASAN_ANNOTATE_REINIT; std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish, _M_get_Tp_allocator()); _M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage - this->_M_impl._M_start); this->_M_impl._M_start = __tmp; this->_M_impl._M_finish = this->_M_impl._M_start + __len; this->_M_impl._M_end_of_storage = this->_M_impl._M_finish; } else if (size() >= __len) _M_erase_at_end(std::copy(__first, __last, this->_M_impl._M_start)); else { _ForwardIterator __mid = __first; std::advance(__mid, size()); std::copy(__first, __mid, this->_M_impl._M_start); const size_type __attribute__((__unused__)) __n = __len - size(); _GLIBCXX_ASAN_ANNOTATE_GROW(__n); this->_M_impl._M_finish = std::__uninitialized_copy_a(__mid, __last, this->_M_impl._M_finish, _M_get_Tp_allocator()); _GLIBCXX_ASAN_ANNOTATE_GREW(__n); } } #if __cplusplus >= 201103L template auto vector<_Tp, _Alloc>:: _M_insert_rval(const_iterator __position, value_type&& __v) -> iterator { const auto __n = __position - cbegin(); if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) if (__position == cend()) { _GLIBCXX_ASAN_ANNOTATE_GROW(1); _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, std::move(__v)); ++this->_M_impl._M_finish; _GLIBCXX_ASAN_ANNOTATE_GREW(1); } else _M_insert_aux(begin() + __n, std::move(__v)); else _M_realloc_insert(begin() + __n, std::move(__v)); return iterator(this->_M_impl._M_start + __n); } template template auto vector<_Tp, _Alloc>:: _M_emplace_aux(const_iterator __position, _Args&&... __args) -> iterator { const auto __n = __position - cbegin(); if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) if (__position == cend()) { _GLIBCXX_ASAN_ANNOTATE_GROW(1); _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, std::forward<_Args>(__args)...); ++this->_M_impl._M_finish; _GLIBCXX_ASAN_ANNOTATE_GREW(1); } else { // We need to construct a temporary because something in __args... // could alias one of the elements of the container and so we // need to use it before _M_insert_aux moves elements around. _Temporary_value __tmp(this, std::forward<_Args>(__args)...); _M_insert_aux(begin() + __n, std::move(__tmp._M_val())); } else _M_realloc_insert(begin() + __n, std::forward<_Args>(__args)...); return iterator(this->_M_impl._M_start + __n); } template template void vector<_Tp, _Alloc>:: _M_insert_aux(iterator __position, _Arg&& __arg) #else template void vector<_Tp, _Alloc>:: _M_insert_aux(iterator __position, const _Tp& __x) #endif { _GLIBCXX_ASAN_ANNOTATE_GROW(1); _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, _GLIBCXX_MOVE(*(this->_M_impl._M_finish - 1))); ++this->_M_impl._M_finish; _GLIBCXX_ASAN_ANNOTATE_GREW(1); #if __cplusplus < 201103L _Tp __x_copy = __x; #endif _GLIBCXX_MOVE_BACKWARD3(__position.base(), this->_M_impl._M_finish - 2, this->_M_impl._M_finish - 1); #if __cplusplus < 201103L *__position = __x_copy; #else *__position = std::forward<_Arg>(__arg); #endif } #if __cplusplus >= 201103L template template void vector<_Tp, _Alloc>:: _M_realloc_insert(iterator __position, _Args&&... __args) #else template void vector<_Tp, _Alloc>:: _M_realloc_insert(iterator __position, const _Tp& __x) #endif { const size_type __len = _M_check_len(size_type(1), "vector::_M_realloc_insert"); pointer __old_start = this->_M_impl._M_start; pointer __old_finish = this->_M_impl._M_finish; const size_type __elems_before = __position - begin(); pointer __new_start(this->_M_allocate(__len)); pointer __new_finish(__new_start); __try { // The order of the three operations is dictated by the C++11 // case, where the moves could alter a new element belonging // to the existing vector. This is an issue only for callers // taking the element by lvalue ref (see last bullet of C++11 // [res.on.arguments]). _Alloc_traits::construct(this->_M_impl, __new_start + __elems_before, #if __cplusplus >= 201103L std::forward<_Args>(__args)...); #else __x); #endif __new_finish = pointer(); __new_finish = std::__uninitialized_move_if_noexcept_a (__old_start, __position.base(), __new_start, _M_get_Tp_allocator()); ++__new_finish; __new_finish = std::__uninitialized_move_if_noexcept_a (__position.base(), __old_finish, __new_finish, _M_get_Tp_allocator()); } __catch(...) { if (!__new_finish) _Alloc_traits::destroy(this->_M_impl, __new_start + __elems_before); else std::_Destroy(__new_start, __new_finish, _M_get_Tp_allocator()); _M_deallocate(__new_start, __len); __throw_exception_again; } _GLIBCXX_ASAN_ANNOTATE_REINIT; std::_Destroy(__old_start, __old_finish, _M_get_Tp_allocator()); _M_deallocate(__old_start, this->_M_impl._M_end_of_storage - __old_start); this->_M_impl._M_start = __new_start; this->_M_impl._M_finish = __new_finish; this->_M_impl._M_end_of_storage = __new_start + __len; } template void vector<_Tp, _Alloc>:: _M_fill_insert(iterator __position, size_type __n, const value_type& __x) { if (__n != 0) { if (size_type(this->_M_impl._M_end_of_storage - this->_M_impl._M_finish) >= __n) { #if __cplusplus < 201103L value_type __x_copy = __x; #else _Temporary_value __tmp(this, __x); value_type& __x_copy = __tmp._M_val(); #endif const size_type __elems_after = end() - __position; pointer __old_finish(this->_M_impl._M_finish); if (__elems_after > __n) { _GLIBCXX_ASAN_ANNOTATE_GROW(__n); std::__uninitialized_move_a(this->_M_impl._M_finish - __n, this->_M_impl._M_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish += __n; _GLIBCXX_ASAN_ANNOTATE_GREW(__n); _GLIBCXX_MOVE_BACKWARD3(__position.base(), __old_finish - __n, __old_finish); std::fill(__position.base(), __position.base() + __n, __x_copy); } else { _GLIBCXX_ASAN_ANNOTATE_GROW(__n); this->_M_impl._M_finish = std::__uninitialized_fill_n_a(this->_M_impl._M_finish, __n - __elems_after, __x_copy, _M_get_Tp_allocator()); _GLIBCXX_ASAN_ANNOTATE_GREW(__n - __elems_after); std::__uninitialized_move_a(__position.base(), __old_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish += __elems_after; _GLIBCXX_ASAN_ANNOTATE_GREW(__elems_after); std::fill(__position.base(), __old_finish, __x_copy); } } else { const size_type __len = _M_check_len(__n, "vector::_M_fill_insert"); const size_type __elems_before = __position - begin(); pointer __new_start(this->_M_allocate(__len)); pointer __new_finish(__new_start); __try { // See _M_realloc_insert above. std::__uninitialized_fill_n_a(__new_start + __elems_before, __n, __x, _M_get_Tp_allocator()); __new_finish = pointer(); __new_finish = std::__uninitialized_move_if_noexcept_a (this->_M_impl._M_start, __position.base(), __new_start, _M_get_Tp_allocator()); __new_finish += __n; __new_finish = std::__uninitialized_move_if_noexcept_a (__position.base(), this->_M_impl._M_finish, __new_finish, _M_get_Tp_allocator()); } __catch(...) { if (!__new_finish) std::_Destroy(__new_start + __elems_before, __new_start + __elems_before + __n, _M_get_Tp_allocator()); else std::_Destroy(__new_start, __new_finish, _M_get_Tp_allocator()); _M_deallocate(__new_start, __len); __throw_exception_again; } _GLIBCXX_ASAN_ANNOTATE_REINIT; std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish, _M_get_Tp_allocator()); _M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage - this->_M_impl._M_start); this->_M_impl._M_start = __new_start; this->_M_impl._M_finish = __new_finish; this->_M_impl._M_end_of_storage = __new_start + __len; } } } #if __cplusplus >= 201103L template void vector<_Tp, _Alloc>:: _M_default_append(size_type __n) { if (__n != 0) { const size_type __size = size(); size_type __navail = size_type(this->_M_impl._M_end_of_storage - this->_M_impl._M_finish); if (__size > max_size() || __navail > max_size() - __size) __builtin_unreachable(); if (__navail >= __n) { _GLIBCXX_ASAN_ANNOTATE_GROW(__n); this->_M_impl._M_finish = std::__uninitialized_default_n_a(this->_M_impl._M_finish, __n, _M_get_Tp_allocator()); _GLIBCXX_ASAN_ANNOTATE_GREW(__n); } else { const size_type __len = _M_check_len(__n, "vector::_M_default_append"); pointer __new_start(this->_M_allocate(__len)); pointer __destroy_from = pointer(); __try { std::__uninitialized_default_n_a(__new_start + __size, __n, _M_get_Tp_allocator()); __destroy_from = __new_start + __size; std::__uninitialized_move_if_noexcept_a( this->_M_impl._M_start, this->_M_impl._M_finish, __new_start, _M_get_Tp_allocator()); } __catch(...) { if (__destroy_from) std::_Destroy(__destroy_from, __destroy_from + __n, _M_get_Tp_allocator()); _M_deallocate(__new_start, __len); __throw_exception_again; } _GLIBCXX_ASAN_ANNOTATE_REINIT; std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish, _M_get_Tp_allocator()); _M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage - this->_M_impl._M_start); this->_M_impl._M_start = __new_start; this->_M_impl._M_finish = __new_start + __size + __n; this->_M_impl._M_end_of_storage = __new_start + __len; } } } template bool vector<_Tp, _Alloc>:: _M_shrink_to_fit() { if (capacity() == size()) return false; _GLIBCXX_ASAN_ANNOTATE_REINIT; return std::__shrink_to_fit_aux::_S_do_it(*this); } #endif template template void vector<_Tp, _Alloc>:: _M_range_insert(iterator __pos, _InputIterator __first, _InputIterator __last, std::input_iterator_tag) { if (__pos == end()) { for (; __first != __last; ++__first) insert(end(), *__first); } else if (__first != __last) { vector __tmp(__first, __last, _M_get_Tp_allocator()); insert(__pos, _GLIBCXX_MAKE_MOVE_ITERATOR(__tmp.begin()), _GLIBCXX_MAKE_MOVE_ITERATOR(__tmp.end())); } } template template void vector<_Tp, _Alloc>:: _M_range_insert(iterator __position, _ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { if (__first != __last) { const size_type __n = std::distance(__first, __last); if (size_type(this->_M_impl._M_end_of_storage - this->_M_impl._M_finish) >= __n) { const size_type __elems_after = end() - __position; pointer __old_finish(this->_M_impl._M_finish); if (__elems_after > __n) { _GLIBCXX_ASAN_ANNOTATE_GROW(__n); std::__uninitialized_move_a(this->_M_impl._M_finish - __n, this->_M_impl._M_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish += __n; _GLIBCXX_ASAN_ANNOTATE_GREW(__n); _GLIBCXX_MOVE_BACKWARD3(__position.base(), __old_finish - __n, __old_finish); std::copy(__first, __last, __position); } else { _ForwardIterator __mid = __first; std::advance(__mid, __elems_after); _GLIBCXX_ASAN_ANNOTATE_GROW(__n); std::__uninitialized_copy_a(__mid, __last, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish += __n - __elems_after; _GLIBCXX_ASAN_ANNOTATE_GREW(__n - __elems_after); std::__uninitialized_move_a(__position.base(), __old_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish += __elems_after; _GLIBCXX_ASAN_ANNOTATE_GREW(__elems_after); std::copy(__first, __mid, __position); } } else { const size_type __len = _M_check_len(__n, "vector::_M_range_insert"); pointer __new_start(this->_M_allocate(__len)); pointer __new_finish(__new_start); __try { __new_finish = std::__uninitialized_move_if_noexcept_a (this->_M_impl._M_start, __position.base(), __new_start, _M_get_Tp_allocator()); __new_finish = std::__uninitialized_copy_a(__first, __last, __new_finish, _M_get_Tp_allocator()); __new_finish = std::__uninitialized_move_if_noexcept_a (__position.base(), this->_M_impl._M_finish, __new_finish, _M_get_Tp_allocator()); } __catch(...) { std::_Destroy(__new_start, __new_finish, _M_get_Tp_allocator()); _M_deallocate(__new_start, __len); __throw_exception_again; } _GLIBCXX_ASAN_ANNOTATE_REINIT; std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish, _M_get_Tp_allocator()); _M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage - this->_M_impl._M_start); this->_M_impl._M_start = __new_start; this->_M_impl._M_finish = __new_finish; this->_M_impl._M_end_of_storage = __new_start + __len; } } } // vector template void vector:: _M_reallocate(size_type __n) { _Bit_pointer __q = this->_M_allocate(__n); iterator __start(std::__addressof(*__q), 0); iterator __finish(_M_copy_aligned(begin(), end(), __start)); this->_M_deallocate(); this->_M_impl._M_start = __start; this->_M_impl._M_finish = __finish; this->_M_impl._M_end_of_storage = __q + _S_nword(__n); } template void vector:: _M_fill_insert(iterator __position, size_type __n, bool __x) { if (__n == 0) return; if (capacity() - size() >= __n) { std::copy_backward(__position, end(), this->_M_impl._M_finish + difference_type(__n)); std::fill(__position, __position + difference_type(__n), __x); this->_M_impl._M_finish += difference_type(__n); } else { const size_type __len = _M_check_len(__n, "vector::_M_fill_insert"); _Bit_pointer __q = this->_M_allocate(__len); iterator __start(std::__addressof(*__q), 0); iterator __i = _M_copy_aligned(begin(), __position, __start); std::fill(__i, __i + difference_type(__n), __x); iterator __finish = std::copy(__position, end(), __i + difference_type(__n)); this->_M_deallocate(); this->_M_impl._M_end_of_storage = __q + _S_nword(__len); this->_M_impl._M_start = __start; this->_M_impl._M_finish = __finish; } } template template void vector:: _M_insert_range(iterator __position, _ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { if (__first != __last) { size_type __n = std::distance(__first, __last); if (capacity() - size() >= __n) { std::copy_backward(__position, end(), this->_M_impl._M_finish + difference_type(__n)); std::copy(__first, __last, __position); this->_M_impl._M_finish += difference_type(__n); } else { const size_type __len = _M_check_len(__n, "vector::_M_insert_range"); _Bit_pointer __q = this->_M_allocate(__len); iterator __start(std::__addressof(*__q), 0); iterator __i = _M_copy_aligned(begin(), __position, __start); __i = std::copy(__first, __last, __i); iterator __finish = std::copy(__position, end(), __i); this->_M_deallocate(); this->_M_impl._M_end_of_storage = __q + _S_nword(__len); this->_M_impl._M_start = __start; this->_M_impl._M_finish = __finish; } } } template void vector:: _M_insert_aux(iterator __position, bool __x) { if (this->_M_impl._M_finish._M_p != this->_M_impl._M_end_addr()) { std::copy_backward(__position, this->_M_impl._M_finish, this->_M_impl._M_finish + 1); *__position = __x; ++this->_M_impl._M_finish; } else { const size_type __len = _M_check_len(size_type(1), "vector::_M_insert_aux"); _Bit_pointer __q = this->_M_allocate(__len); iterator __start(std::__addressof(*__q), 0); iterator __i = _M_copy_aligned(begin(), __position, __start); *__i++ = __x; iterator __finish = std::copy(__position, end(), __i); this->_M_deallocate(); this->_M_impl._M_end_of_storage = __q + _S_nword(__len); this->_M_impl._M_start = __start; this->_M_impl._M_finish = __finish; } } template typename vector::iterator vector:: _M_erase(iterator __position) { if (__position + 1 != end()) std::copy(__position + 1, end(), __position); --this->_M_impl._M_finish; return __position; } template typename vector::iterator vector:: _M_erase(iterator __first, iterator __last) { if (__first != __last) _M_erase_at_end(std::copy(__last, end(), __first)); return __first; } #if __cplusplus >= 201103L template bool vector:: _M_shrink_to_fit() { if (capacity() - size() < int(_S_word_bit)) return false; __try { _M_reallocate(size()); return true; } __catch(...) { return false; } } #endif _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #if __cplusplus >= 201103L namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template size_t hash<_GLIBCXX_STD_C::vector>:: operator()(const _GLIBCXX_STD_C::vector& __b) const noexcept { size_t __hash = 0; using _GLIBCXX_STD_C::_S_word_bit; using _GLIBCXX_STD_C::_Bit_type; const size_t __words = __b.size() / _S_word_bit; if (__words) { const size_t __clength = __words * sizeof(_Bit_type); __hash = std::_Hash_impl::hash(__b._M_impl._M_start._M_p, __clength); } const size_t __extrabits = __b.size() % _S_word_bit; if (__extrabits) { _Bit_type __hiword = *__b._M_impl._M_finish._M_p; __hiword &= ~((~static_cast<_Bit_type>(0)) << __extrabits); const size_t __clength = (__extrabits + __CHAR_BIT__ - 1) / __CHAR_BIT__; if (__words) __hash = std::_Hash_impl::hash(&__hiword, __clength, __hash); else __hash = std::_Hash_impl::hash(&__hiword, __clength); } return __hash; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #undef _GLIBCXX_ASAN_ANNOTATE_REINIT #undef _GLIBCXX_ASAN_ANNOTATE_GROW #undef _GLIBCXX_ASAN_ANNOTATE_GREW #undef _GLIBCXX_ASAN_ANNOTATE_SHRINK #endif /* _VECTOR_TCC */ PK!'BTT8/bits/algorithmfwd.hnu[// Forward declarations -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/algorithmfwd.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{algorithm} */ #ifndef _GLIBCXX_ALGORITHMFWD_H #define _GLIBCXX_ALGORITHMFWD_H 1 #pragma GCC system_header #include #include #include #if __cplusplus >= 201103L #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /* adjacent_find all_of (C++11) any_of (C++11) binary_search clamp (C++17) copy copy_backward copy_if (C++11) copy_n (C++11) count count_if equal equal_range fill fill_n find find_end find_first_of find_if find_if_not (C++11) for_each generate generate_n includes inplace_merge is_heap (C++11) is_heap_until (C++11) is_partitioned (C++11) is_sorted (C++11) is_sorted_until (C++11) iter_swap lexicographical_compare lower_bound make_heap max max_element merge min min_element minmax (C++11) minmax_element (C++11) mismatch next_permutation none_of (C++11) nth_element partial_sort partial_sort_copy partition partition_copy (C++11) partition_point (C++11) pop_heap prev_permutation push_heap random_shuffle remove remove_copy remove_copy_if remove_if replace replace_copy replace_copy_if replace_if reverse reverse_copy rotate rotate_copy search search_n set_difference set_intersection set_symmetric_difference set_union shuffle (C++11) sort sort_heap stable_partition stable_sort swap swap_ranges transform unique unique_copy upper_bound */ /** * @defgroup algorithms Algorithms * * Components for performing algorithmic operations. Includes * non-modifying sequence, modifying (mutating) sequence, sorting, * searching, merge, partition, heap, set, minima, maxima, and * permutation operations. */ /** * @defgroup mutating_algorithms Mutating * @ingroup algorithms */ /** * @defgroup non_mutating_algorithms Non-Mutating * @ingroup algorithms */ /** * @defgroup sorting_algorithms Sorting * @ingroup algorithms */ /** * @defgroup set_algorithms Set Operation * @ingroup sorting_algorithms * * These algorithms are common set operations performed on sequences * that are already sorted. The number of comparisons will be * linear. */ /** * @defgroup binary_search_algorithms Binary Search * @ingroup sorting_algorithms * * These algorithms are variations of a classic binary search, and * all assume that the sequence being searched is already sorted. * * The number of comparisons will be logarithmic (and as few as * possible). The number of steps through the sequence will be * logarithmic for random-access iterators (e.g., pointers), and * linear otherwise. * * The LWG has passed Defect Report 270, which notes: The * proposed resolution reinterprets binary search. Instead of * thinking about searching for a value in a sorted range, we view * that as an important special case of a more general algorithm: * searching for the partition point in a partitioned range. We * also add a guarantee that the old wording did not: we ensure that * the upper bound is no earlier than the lower bound, that the pair * returned by equal_range is a valid range, and that the first part * of that pair is the lower bound. * * The actual effect of the first sentence is that a comparison * functor passed by the user doesn't necessarily need to induce a * strict weak ordering relation. Rather, it partitions the range. */ // adjacent_find #if __cplusplus >= 201103L template bool all_of(_IIter, _IIter, _Predicate); template bool any_of(_IIter, _IIter, _Predicate); #endif template bool binary_search(_FIter, _FIter, const _Tp&); template bool binary_search(_FIter, _FIter, const _Tp&, _Compare); #if __cplusplus > 201402L template _GLIBCXX14_CONSTEXPR const _Tp& clamp(const _Tp&, const _Tp&, const _Tp&); template _GLIBCXX14_CONSTEXPR const _Tp& clamp(const _Tp&, const _Tp&, const _Tp&, _Compare); #endif template _OIter copy(_IIter, _IIter, _OIter); template _BIter2 copy_backward(_BIter1, _BIter1, _BIter2); #if __cplusplus >= 201103L template _OIter copy_if(_IIter, _IIter, _OIter, _Predicate); template _OIter copy_n(_IIter, _Size, _OIter); #endif // count // count_if template pair<_FIter, _FIter> equal_range(_FIter, _FIter, const _Tp&); template pair<_FIter, _FIter> equal_range(_FIter, _FIter, const _Tp&, _Compare); template void fill(_FIter, _FIter, const _Tp&); template _OIter fill_n(_OIter, _Size, const _Tp&); // find template _FIter1 find_end(_FIter1, _FIter1, _FIter2, _FIter2); template _FIter1 find_end(_FIter1, _FIter1, _FIter2, _FIter2, _BinaryPredicate); // find_first_of // find_if #if __cplusplus >= 201103L template _IIter find_if_not(_IIter, _IIter, _Predicate); #endif // for_each // generate // generate_n template bool includes(_IIter1, _IIter1, _IIter2, _IIter2); template bool includes(_IIter1, _IIter1, _IIter2, _IIter2, _Compare); template void inplace_merge(_BIter, _BIter, _BIter); template void inplace_merge(_BIter, _BIter, _BIter, _Compare); #if __cplusplus >= 201103L template bool is_heap(_RAIter, _RAIter); template bool is_heap(_RAIter, _RAIter, _Compare); template _RAIter is_heap_until(_RAIter, _RAIter); template _RAIter is_heap_until(_RAIter, _RAIter, _Compare); template bool is_partitioned(_IIter, _IIter, _Predicate); template bool is_permutation(_FIter1, _FIter1, _FIter2); template bool is_permutation(_FIter1, _FIter1, _FIter2, _BinaryPredicate); template bool is_sorted(_FIter, _FIter); template bool is_sorted(_FIter, _FIter, _Compare); template _FIter is_sorted_until(_FIter, _FIter); template _FIter is_sorted_until(_FIter, _FIter, _Compare); #endif template void iter_swap(_FIter1, _FIter2); template _FIter lower_bound(_FIter, _FIter, const _Tp&); template _FIter lower_bound(_FIter, _FIter, const _Tp&, _Compare); template void make_heap(_RAIter, _RAIter); template void make_heap(_RAIter, _RAIter, _Compare); template _GLIBCXX14_CONSTEXPR const _Tp& max(const _Tp&, const _Tp&); template _GLIBCXX14_CONSTEXPR const _Tp& max(const _Tp&, const _Tp&, _Compare); // max_element // merge template _GLIBCXX14_CONSTEXPR const _Tp& min(const _Tp&, const _Tp&); template _GLIBCXX14_CONSTEXPR const _Tp& min(const _Tp&, const _Tp&, _Compare); // min_element #if __cplusplus >= 201103L template _GLIBCXX14_CONSTEXPR pair minmax(const _Tp&, const _Tp&); template _GLIBCXX14_CONSTEXPR pair minmax(const _Tp&, const _Tp&, _Compare); template _GLIBCXX14_CONSTEXPR pair<_FIter, _FIter> minmax_element(_FIter, _FIter); template _GLIBCXX14_CONSTEXPR pair<_FIter, _FIter> minmax_element(_FIter, _FIter, _Compare); template _GLIBCXX14_CONSTEXPR _Tp min(initializer_list<_Tp>); template _GLIBCXX14_CONSTEXPR _Tp min(initializer_list<_Tp>, _Compare); template _GLIBCXX14_CONSTEXPR _Tp max(initializer_list<_Tp>); template _GLIBCXX14_CONSTEXPR _Tp max(initializer_list<_Tp>, _Compare); template _GLIBCXX14_CONSTEXPR pair<_Tp, _Tp> minmax(initializer_list<_Tp>); template _GLIBCXX14_CONSTEXPR pair<_Tp, _Tp> minmax(initializer_list<_Tp>, _Compare); #endif // mismatch template bool next_permutation(_BIter, _BIter); template bool next_permutation(_BIter, _BIter, _Compare); #if __cplusplus >= 201103L template bool none_of(_IIter, _IIter, _Predicate); #endif // nth_element // partial_sort template _RAIter partial_sort_copy(_IIter, _IIter, _RAIter, _RAIter); template _RAIter partial_sort_copy(_IIter, _IIter, _RAIter, _RAIter, _Compare); // partition #if __cplusplus >= 201103L template pair<_OIter1, _OIter2> partition_copy(_IIter, _IIter, _OIter1, _OIter2, _Predicate); template _FIter partition_point(_FIter, _FIter, _Predicate); #endif template void pop_heap(_RAIter, _RAIter); template void pop_heap(_RAIter, _RAIter, _Compare); template bool prev_permutation(_BIter, _BIter); template bool prev_permutation(_BIter, _BIter, _Compare); template void push_heap(_RAIter, _RAIter); template void push_heap(_RAIter, _RAIter, _Compare); // random_shuffle template _FIter remove(_FIter, _FIter, const _Tp&); template _FIter remove_if(_FIter, _FIter, _Predicate); template _OIter remove_copy(_IIter, _IIter, _OIter, const _Tp&); template _OIter remove_copy_if(_IIter, _IIter, _OIter, _Predicate); // replace template _OIter replace_copy(_IIter, _IIter, _OIter, const _Tp&, const _Tp&); template _OIter replace_copy_if(_Iter, _Iter, _OIter, _Predicate, const _Tp&); // replace_if template void reverse(_BIter, _BIter); template _OIter reverse_copy(_BIter, _BIter, _OIter); inline namespace _V2 { template _FIter rotate(_FIter, _FIter, _FIter); } template _OIter rotate_copy(_FIter, _FIter, _FIter, _OIter); // search // search_n // set_difference // set_intersection // set_symmetric_difference // set_union #if (__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99_STDINT_TR1) template void shuffle(_RAIter, _RAIter, _UGenerator&&); #endif template void sort_heap(_RAIter, _RAIter); template void sort_heap(_RAIter, _RAIter, _Compare); template _BIter stable_partition(_BIter, _BIter, _Predicate); #if __cplusplus < 201103L // For C++11 swap() is declared in . template inline void swap(_Tp& __a, _Tp& __b); template inline void swap(_Tp (&__a)[_Nm], _Tp (&__b)[_Nm]); #endif template _FIter2 swap_ranges(_FIter1, _FIter1, _FIter2); // transform template _FIter unique(_FIter, _FIter); template _FIter unique(_FIter, _FIter, _BinaryPredicate); // unique_copy template _FIter upper_bound(_FIter, _FIter, const _Tp&); template _FIter upper_bound(_FIter, _FIter, const _Tp&, _Compare); _GLIBCXX_BEGIN_NAMESPACE_ALGO template _FIter adjacent_find(_FIter, _FIter); template _FIter adjacent_find(_FIter, _FIter, _BinaryPredicate); template typename iterator_traits<_IIter>::difference_type count(_IIter, _IIter, const _Tp&); template typename iterator_traits<_IIter>::difference_type count_if(_IIter, _IIter, _Predicate); template bool equal(_IIter1, _IIter1, _IIter2); template bool equal(_IIter1, _IIter1, _IIter2, _BinaryPredicate); template _IIter find(_IIter, _IIter, const _Tp&); template _FIter1 find_first_of(_FIter1, _FIter1, _FIter2, _FIter2); template _FIter1 find_first_of(_FIter1, _FIter1, _FIter2, _FIter2, _BinaryPredicate); template _IIter find_if(_IIter, _IIter, _Predicate); template _Funct for_each(_IIter, _IIter, _Funct); template void generate(_FIter, _FIter, _Generator); template _OIter generate_n(_OIter, _Size, _Generator); template bool lexicographical_compare(_IIter1, _IIter1, _IIter2, _IIter2); template bool lexicographical_compare(_IIter1, _IIter1, _IIter2, _IIter2, _Compare); template _GLIBCXX14_CONSTEXPR _FIter max_element(_FIter, _FIter); template _GLIBCXX14_CONSTEXPR _FIter max_element(_FIter, _FIter, _Compare); template _OIter merge(_IIter1, _IIter1, _IIter2, _IIter2, _OIter); template _OIter merge(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Compare); template _GLIBCXX14_CONSTEXPR _FIter min_element(_FIter, _FIter); template _GLIBCXX14_CONSTEXPR _FIter min_element(_FIter, _FIter, _Compare); template pair<_IIter1, _IIter2> mismatch(_IIter1, _IIter1, _IIter2); template pair<_IIter1, _IIter2> mismatch(_IIter1, _IIter1, _IIter2, _BinaryPredicate); template void nth_element(_RAIter, _RAIter, _RAIter); template void nth_element(_RAIter, _RAIter, _RAIter, _Compare); template void partial_sort(_RAIter, _RAIter, _RAIter); template void partial_sort(_RAIter, _RAIter, _RAIter, _Compare); template _BIter partition(_BIter, _BIter, _Predicate); template void random_shuffle(_RAIter, _RAIter); template void random_shuffle(_RAIter, _RAIter, #if __cplusplus >= 201103L _Generator&&); #else _Generator&); #endif template void replace(_FIter, _FIter, const _Tp&, const _Tp&); template void replace_if(_FIter, _FIter, _Predicate, const _Tp&); template _FIter1 search(_FIter1, _FIter1, _FIter2, _FIter2); template _FIter1 search(_FIter1, _FIter1, _FIter2, _FIter2, _BinaryPredicate); template _FIter search_n(_FIter, _FIter, _Size, const _Tp&); template _FIter search_n(_FIter, _FIter, _Size, const _Tp&, _BinaryPredicate); template _OIter set_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter); template _OIter set_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Compare); template _OIter set_intersection(_IIter1, _IIter1, _IIter2, _IIter2, _OIter); template _OIter set_intersection(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Compare); template _OIter set_symmetric_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter); template _OIter set_symmetric_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Compare); template _OIter set_union(_IIter1, _IIter1, _IIter2, _IIter2, _OIter); template _OIter set_union(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Compare); template void sort(_RAIter, _RAIter); template void sort(_RAIter, _RAIter, _Compare); template void stable_sort(_RAIter, _RAIter); template void stable_sort(_RAIter, _RAIter, _Compare); template _OIter transform(_IIter, _IIter, _OIter, _UnaryOperation); template _OIter transform(_IIter1, _IIter1, _IIter2, _OIter, _BinaryOperation); template _OIter unique_copy(_IIter, _IIter, _OIter); template _OIter unique_copy(_IIter, _IIter, _OIter, _BinaryPredicate); _GLIBCXX_END_NAMESPACE_ALGO _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #ifdef _GLIBCXX_PARALLEL # include #endif #endif PK!l 8/codecvtnu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // ISO C++ 14882: 22.5 Standard code conversion facets /** @file include/codecvt * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_CODECVT #define _GLIBCXX_CODECVT 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #ifdef _GLIBCXX_USE_C99_STDINT_TR1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION enum codecvt_mode { consume_header = 4, generate_header = 2, little_endian = 1 }; template class codecvt_utf8 : public codecvt<_Elem, char, mbstate_t> { public: explicit codecvt_utf8(size_t __refs = 0); ~codecvt_utf8(); }; template class codecvt_utf16 : public codecvt<_Elem, char, mbstate_t> { public: explicit codecvt_utf16(size_t __refs = 0); ~codecvt_utf16(); }; template class codecvt_utf8_utf16 : public codecvt<_Elem, char, mbstate_t> { public: explicit codecvt_utf8_utf16(size_t __refs = 0); ~codecvt_utf8_utf16(); }; #define _GLIBCXX_CODECVT_SPECIALIZATION2(_NAME, _ELEM) \ template<> \ class _NAME<_ELEM> \ : public codecvt<_ELEM, char, mbstate_t> \ { \ public: \ typedef _ELEM intern_type; \ typedef char extern_type; \ typedef mbstate_t state_type; \ \ protected: \ _NAME(unsigned long __maxcode, codecvt_mode __mode, size_t __refs) \ : codecvt(__refs), _M_maxcode(__maxcode), _M_mode(__mode) { } \ \ virtual \ ~_NAME(); \ \ virtual result \ do_out(state_type& __state, const intern_type* __from, \ const intern_type* __from_end, const intern_type*& __from_next, \ extern_type* __to, extern_type* __to_end, \ extern_type*& __to_next) const; \ \ virtual result \ do_unshift(state_type& __state, \ extern_type* __to, extern_type* __to_end, \ extern_type*& __to_next) const; \ \ virtual result \ do_in(state_type& __state, \ const extern_type* __from, const extern_type* __from_end, \ const extern_type*& __from_next, \ intern_type* __to, intern_type* __to_end, \ intern_type*& __to_next) const; \ \ virtual \ int do_encoding() const throw(); \ \ virtual \ bool do_always_noconv() const throw(); \ \ virtual \ int do_length(state_type&, const extern_type* __from, \ const extern_type* __end, size_t __max) const; \ \ virtual int \ do_max_length() const throw(); \ \ private: \ unsigned long _M_maxcode; \ codecvt_mode _M_mode; \ } #define _GLIBCXX_CODECVT_SPECIALIZATION(_NAME, _ELEM) \ _GLIBCXX_CODECVT_SPECIALIZATION2(__ ## _NAME ## _base, _ELEM); \ template \ class _NAME<_ELEM, _Maxcode, _Mode> \ : public __ ## _NAME ## _base<_ELEM> \ { \ public: \ explicit \ _NAME(size_t __refs = 0) \ : __ ## _NAME ## _base<_ELEM>(std::min(_Maxcode, 0x10fffful), \ _Mode, __refs) \ { } \ } template class __codecvt_utf8_base; template class __codecvt_utf16_base; template class __codecvt_utf8_utf16_base; _GLIBCXX_CODECVT_SPECIALIZATION(codecvt_utf8, char16_t); _GLIBCXX_CODECVT_SPECIALIZATION(codecvt_utf16, char16_t); _GLIBCXX_CODECVT_SPECIALIZATION(codecvt_utf8_utf16, char16_t); _GLIBCXX_CODECVT_SPECIALIZATION(codecvt_utf8, char32_t); _GLIBCXX_CODECVT_SPECIALIZATION(codecvt_utf16, char32_t); _GLIBCXX_CODECVT_SPECIALIZATION(codecvt_utf8_utf16, char32_t); #ifdef _GLIBCXX_USE_WCHAR_T _GLIBCXX_CODECVT_SPECIALIZATION(codecvt_utf8, wchar_t); _GLIBCXX_CODECVT_SPECIALIZATION(codecvt_utf16, wchar_t); _GLIBCXX_CODECVT_SPECIALIZATION(codecvt_utf8_utf16, wchar_t); #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _GLIBCXX_USE_C99_STDINT_TR1 #endif #endif /* _GLIBCXX_CODECVT */ PK!A؁ 8/complexnu[// The template and inlines for the -*- C++ -*- complex number classes. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/complex * This is a Standard C++ Library header. */ // // ISO C++ 14882: 26.2 Complex Numbers // Note: this is not a conforming implementation. // Initially implemented by Ulrich Drepper // Improved by Gabriel Dos Reis // #ifndef _GLIBCXX_COMPLEX #define _GLIBCXX_COMPLEX 1 #pragma GCC system_header #include #include #include #include #include // Get rid of a macro possibly defined in #undef complex namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup complex_numbers Complex Numbers * @ingroup numerics * * Classes and functions for complex numbers. * @{ */ // Forward declarations. template class complex; template<> class complex; template<> class complex; template<> class complex; /// Return magnitude of @a z. template _Tp abs(const complex<_Tp>&); /// Return phase angle of @a z. template _Tp arg(const complex<_Tp>&); /// Return @a z magnitude squared. template _Tp norm(const complex<_Tp>&); /// Return complex conjugate of @a z. template complex<_Tp> conj(const complex<_Tp>&); /// Return complex with magnitude @a rho and angle @a theta. template complex<_Tp> polar(const _Tp&, const _Tp& = 0); // Transcendentals: /// Return complex cosine of @a z. template complex<_Tp> cos(const complex<_Tp>&); /// Return complex hyperbolic cosine of @a z. template complex<_Tp> cosh(const complex<_Tp>&); /// Return complex base e exponential of @a z. template complex<_Tp> exp(const complex<_Tp>&); /// Return complex natural logarithm of @a z. template complex<_Tp> log(const complex<_Tp>&); /// Return complex base 10 logarithm of @a z. template complex<_Tp> log10(const complex<_Tp>&); /// Return @a x to the @a y'th power. template complex<_Tp> pow(const complex<_Tp>&, int); /// Return @a x to the @a y'th power. template complex<_Tp> pow(const complex<_Tp>&, const _Tp&); /// Return @a x to the @a y'th power. template complex<_Tp> pow(const complex<_Tp>&, const complex<_Tp>&); /// Return @a x to the @a y'th power. template complex<_Tp> pow(const _Tp&, const complex<_Tp>&); /// Return complex sine of @a z. template complex<_Tp> sin(const complex<_Tp>&); /// Return complex hyperbolic sine of @a z. template complex<_Tp> sinh(const complex<_Tp>&); /// Return complex square root of @a z. template complex<_Tp> sqrt(const complex<_Tp>&); /// Return complex tangent of @a z. template complex<_Tp> tan(const complex<_Tp>&); /// Return complex hyperbolic tangent of @a z. template complex<_Tp> tanh(const complex<_Tp>&); // 26.2.2 Primary template class complex /** * Template to represent complex numbers. * * Specializations for float, double, and long double are part of the * library. Results with any other type are not guaranteed. * * @param Tp Type of real and imaginary values. */ template struct complex { /// Value typedef. typedef _Tp value_type; /// Default constructor. First parameter is x, second parameter is y. /// Unspecified parameters default to 0. _GLIBCXX_CONSTEXPR complex(const _Tp& __r = _Tp(), const _Tp& __i = _Tp()) : _M_real(__r), _M_imag(__i) { } // Let the compiler synthesize the copy constructor #if __cplusplus >= 201103L constexpr complex(const complex&) = default; #endif /// Converting constructor. template _GLIBCXX_CONSTEXPR complex(const complex<_Up>& __z) : _M_real(__z.real()), _M_imag(__z.imag()) { } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. _GLIBCXX_ABI_TAG_CXX11 constexpr _Tp real() const { return _M_real; } _GLIBCXX_ABI_TAG_CXX11 constexpr _Tp imag() const { return _M_imag; } #else /// Return real part of complex number. _Tp& real() { return _M_real; } /// Return real part of complex number. const _Tp& real() const { return _M_real; } /// Return imaginary part of complex number. _Tp& imag() { return _M_imag; } /// Return imaginary part of complex number. const _Tp& imag() const { return _M_imag; } #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. void real(_Tp __val) { _M_real = __val; } void imag(_Tp __val) { _M_imag = __val; } /// Assign a scalar to this complex number. complex<_Tp>& operator=(const _Tp&); /// Add a scalar to this complex number. // 26.2.5/1 complex<_Tp>& operator+=(const _Tp& __t) { _M_real += __t; return *this; } /// Subtract a scalar from this complex number. // 26.2.5/3 complex<_Tp>& operator-=(const _Tp& __t) { _M_real -= __t; return *this; } /// Multiply this complex number by a scalar. complex<_Tp>& operator*=(const _Tp&); /// Divide this complex number by a scalar. complex<_Tp>& operator/=(const _Tp&); // Let the compiler synthesize the copy assignment operator #if __cplusplus >= 201103L complex& operator=(const complex&) = default; #endif /// Assign another complex number to this one. template complex<_Tp>& operator=(const complex<_Up>&); /// Add another complex number to this one. template complex<_Tp>& operator+=(const complex<_Up>&); /// Subtract another complex number from this one. template complex<_Tp>& operator-=(const complex<_Up>&); /// Multiply this complex number by another. template complex<_Tp>& operator*=(const complex<_Up>&); /// Divide this complex number by another. template complex<_Tp>& operator/=(const complex<_Up>&); _GLIBCXX_CONSTEXPR complex __rep() const { return *this; } private: _Tp _M_real; _Tp _M_imag; }; template complex<_Tp>& complex<_Tp>::operator=(const _Tp& __t) { _M_real = __t; _M_imag = _Tp(); return *this; } // 26.2.5/5 template complex<_Tp>& complex<_Tp>::operator*=(const _Tp& __t) { _M_real *= __t; _M_imag *= __t; return *this; } // 26.2.5/7 template complex<_Tp>& complex<_Tp>::operator/=(const _Tp& __t) { _M_real /= __t; _M_imag /= __t; return *this; } template template complex<_Tp>& complex<_Tp>::operator=(const complex<_Up>& __z) { _M_real = __z.real(); _M_imag = __z.imag(); return *this; } // 26.2.5/9 template template complex<_Tp>& complex<_Tp>::operator+=(const complex<_Up>& __z) { _M_real += __z.real(); _M_imag += __z.imag(); return *this; } // 26.2.5/11 template template complex<_Tp>& complex<_Tp>::operator-=(const complex<_Up>& __z) { _M_real -= __z.real(); _M_imag -= __z.imag(); return *this; } // 26.2.5/13 // XXX: This is a grammar school implementation. template template complex<_Tp>& complex<_Tp>::operator*=(const complex<_Up>& __z) { const _Tp __r = _M_real * __z.real() - _M_imag * __z.imag(); _M_imag = _M_real * __z.imag() + _M_imag * __z.real(); _M_real = __r; return *this; } // 26.2.5/15 // XXX: This is a grammar school implementation. template template complex<_Tp>& complex<_Tp>::operator/=(const complex<_Up>& __z) { const _Tp __r = _M_real * __z.real() + _M_imag * __z.imag(); const _Tp __n = std::norm(__z); _M_imag = (_M_imag * __z.real() - _M_real * __z.imag()) / __n; _M_real = __r / __n; return *this; } // Operators: //@{ /// Return new complex value @a x plus @a y. template inline complex<_Tp> operator+(const complex<_Tp>& __x, const complex<_Tp>& __y) { complex<_Tp> __r = __x; __r += __y; return __r; } template inline complex<_Tp> operator+(const complex<_Tp>& __x, const _Tp& __y) { complex<_Tp> __r = __x; __r += __y; return __r; } template inline complex<_Tp> operator+(const _Tp& __x, const complex<_Tp>& __y) { complex<_Tp> __r = __y; __r += __x; return __r; } //@} //@{ /// Return new complex value @a x minus @a y. template inline complex<_Tp> operator-(const complex<_Tp>& __x, const complex<_Tp>& __y) { complex<_Tp> __r = __x; __r -= __y; return __r; } template inline complex<_Tp> operator-(const complex<_Tp>& __x, const _Tp& __y) { complex<_Tp> __r = __x; __r -= __y; return __r; } template inline complex<_Tp> operator-(const _Tp& __x, const complex<_Tp>& __y) { complex<_Tp> __r(__x, -__y.imag()); __r -= __y.real(); return __r; } //@} //@{ /// Return new complex value @a x times @a y. template inline complex<_Tp> operator*(const complex<_Tp>& __x, const complex<_Tp>& __y) { complex<_Tp> __r = __x; __r *= __y; return __r; } template inline complex<_Tp> operator*(const complex<_Tp>& __x, const _Tp& __y) { complex<_Tp> __r = __x; __r *= __y; return __r; } template inline complex<_Tp> operator*(const _Tp& __x, const complex<_Tp>& __y) { complex<_Tp> __r = __y; __r *= __x; return __r; } //@} //@{ /// Return new complex value @a x divided by @a y. template inline complex<_Tp> operator/(const complex<_Tp>& __x, const complex<_Tp>& __y) { complex<_Tp> __r = __x; __r /= __y; return __r; } template inline complex<_Tp> operator/(const complex<_Tp>& __x, const _Tp& __y) { complex<_Tp> __r = __x; __r /= __y; return __r; } template inline complex<_Tp> operator/(const _Tp& __x, const complex<_Tp>& __y) { complex<_Tp> __r = __x; __r /= __y; return __r; } //@} /// Return @a x. template inline complex<_Tp> operator+(const complex<_Tp>& __x) { return __x; } /// Return complex negation of @a x. template inline complex<_Tp> operator-(const complex<_Tp>& __x) { return complex<_Tp>(-__x.real(), -__x.imag()); } //@{ /// Return true if @a x is equal to @a y. template inline _GLIBCXX_CONSTEXPR bool operator==(const complex<_Tp>& __x, const complex<_Tp>& __y) { return __x.real() == __y.real() && __x.imag() == __y.imag(); } template inline _GLIBCXX_CONSTEXPR bool operator==(const complex<_Tp>& __x, const _Tp& __y) { return __x.real() == __y && __x.imag() == _Tp(); } template inline _GLIBCXX_CONSTEXPR bool operator==(const _Tp& __x, const complex<_Tp>& __y) { return __x == __y.real() && _Tp() == __y.imag(); } //@} //@{ /// Return false if @a x is equal to @a y. template inline _GLIBCXX_CONSTEXPR bool operator!=(const complex<_Tp>& __x, const complex<_Tp>& __y) { return __x.real() != __y.real() || __x.imag() != __y.imag(); } template inline _GLIBCXX_CONSTEXPR bool operator!=(const complex<_Tp>& __x, const _Tp& __y) { return __x.real() != __y || __x.imag() != _Tp(); } template inline _GLIBCXX_CONSTEXPR bool operator!=(const _Tp& __x, const complex<_Tp>& __y) { return __x != __y.real() || _Tp() != __y.imag(); } //@} /// Extraction operator for complex values. template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __is, complex<_Tp>& __x) { bool __fail = true; _CharT __ch; if (__is >> __ch) { if (_Traits::eq(__ch, __is.widen('('))) { _Tp __u; if (__is >> __u >> __ch) { const _CharT __rparen = __is.widen(')'); if (_Traits::eq(__ch, __rparen)) { __x = __u; __fail = false; } else if (_Traits::eq(__ch, __is.widen(','))) { _Tp __v; if (__is >> __v >> __ch) { if (_Traits::eq(__ch, __rparen)) { __x = complex<_Tp>(__u, __v); __fail = false; } else __is.putback(__ch); } } else __is.putback(__ch); } } else { __is.putback(__ch); _Tp __u; if (__is >> __u) { __x = __u; __fail = false; } } } if (__fail) __is.setstate(ios_base::failbit); return __is; } /// Insertion operator for complex values. template basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, const complex<_Tp>& __x) { basic_ostringstream<_CharT, _Traits> __s; __s.flags(__os.flags()); __s.imbue(__os.getloc()); __s.precision(__os.precision()); __s << '(' << __x.real() << ',' << __x.imag() << ')'; return __os << __s.str(); } // Values #if __cplusplus >= 201103L template constexpr _Tp real(const complex<_Tp>& __z) { return __z.real(); } template constexpr _Tp imag(const complex<_Tp>& __z) { return __z.imag(); } #else template inline _Tp& real(complex<_Tp>& __z) { return __z.real(); } template inline const _Tp& real(const complex<_Tp>& __z) { return __z.real(); } template inline _Tp& imag(complex<_Tp>& __z) { return __z.imag(); } template inline const _Tp& imag(const complex<_Tp>& __z) { return __z.imag(); } #endif // 26.2.7/3 abs(__z): Returns the magnitude of __z. template inline _Tp __complex_abs(const complex<_Tp>& __z) { _Tp __x = __z.real(); _Tp __y = __z.imag(); const _Tp __s = std::max(abs(__x), abs(__y)); if (__s == _Tp()) // well ... return __s; __x /= __s; __y /= __s; return __s * sqrt(__x * __x + __y * __y); } #if _GLIBCXX_USE_C99_COMPLEX inline float __complex_abs(__complex__ float __z) { return __builtin_cabsf(__z); } inline double __complex_abs(__complex__ double __z) { return __builtin_cabs(__z); } inline long double __complex_abs(const __complex__ long double& __z) { return __builtin_cabsl(__z); } template inline _Tp abs(const complex<_Tp>& __z) { return __complex_abs(__z.__rep()); } #else template inline _Tp abs(const complex<_Tp>& __z) { return __complex_abs(__z); } #endif // 26.2.7/4: arg(__z): Returns the phase angle of __z. template inline _Tp __complex_arg(const complex<_Tp>& __z) { return atan2(__z.imag(), __z.real()); } #if _GLIBCXX_USE_C99_COMPLEX inline float __complex_arg(__complex__ float __z) { return __builtin_cargf(__z); } inline double __complex_arg(__complex__ double __z) { return __builtin_carg(__z); } inline long double __complex_arg(const __complex__ long double& __z) { return __builtin_cargl(__z); } template inline _Tp arg(const complex<_Tp>& __z) { return __complex_arg(__z.__rep()); } #else template inline _Tp arg(const complex<_Tp>& __z) { return __complex_arg(__z); } #endif // 26.2.7/5: norm(__z) returns the squared magnitude of __z. // As defined, norm() is -not- a norm is the common mathematical // sense used in numerics. The helper class _Norm_helper<> tries to // distinguish between builtin floating point and the rest, so as // to deliver an answer as close as possible to the real value. template struct _Norm_helper { template static inline _Tp _S_do_it(const complex<_Tp>& __z) { const _Tp __x = __z.real(); const _Tp __y = __z.imag(); return __x * __x + __y * __y; } }; template<> struct _Norm_helper { template static inline _Tp _S_do_it(const complex<_Tp>& __z) { _Tp __res = std::abs(__z); return __res * __res; } }; template inline _Tp norm(const complex<_Tp>& __z) { return _Norm_helper<__is_floating<_Tp>::__value && !_GLIBCXX_FAST_MATH>::_S_do_it(__z); } template inline complex<_Tp> polar(const _Tp& __rho, const _Tp& __theta) { __glibcxx_assert( __rho >= 0 ); return complex<_Tp>(__rho * cos(__theta), __rho * sin(__theta)); } template inline complex<_Tp> conj(const complex<_Tp>& __z) { return complex<_Tp>(__z.real(), -__z.imag()); } // Transcendentals // 26.2.8/1 cos(__z): Returns the cosine of __z. template inline complex<_Tp> __complex_cos(const complex<_Tp>& __z) { const _Tp __x = __z.real(); const _Tp __y = __z.imag(); return complex<_Tp>(cos(__x) * cosh(__y), -sin(__x) * sinh(__y)); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_cos(__complex__ float __z) { return __builtin_ccosf(__z); } inline __complex__ double __complex_cos(__complex__ double __z) { return __builtin_ccos(__z); } inline __complex__ long double __complex_cos(const __complex__ long double& __z) { return __builtin_ccosl(__z); } template inline complex<_Tp> cos(const complex<_Tp>& __z) { return __complex_cos(__z.__rep()); } #else template inline complex<_Tp> cos(const complex<_Tp>& __z) { return __complex_cos(__z); } #endif // 26.2.8/2 cosh(__z): Returns the hyperbolic cosine of __z. template inline complex<_Tp> __complex_cosh(const complex<_Tp>& __z) { const _Tp __x = __z.real(); const _Tp __y = __z.imag(); return complex<_Tp>(cosh(__x) * cos(__y), sinh(__x) * sin(__y)); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_cosh(__complex__ float __z) { return __builtin_ccoshf(__z); } inline __complex__ double __complex_cosh(__complex__ double __z) { return __builtin_ccosh(__z); } inline __complex__ long double __complex_cosh(const __complex__ long double& __z) { return __builtin_ccoshl(__z); } template inline complex<_Tp> cosh(const complex<_Tp>& __z) { return __complex_cosh(__z.__rep()); } #else template inline complex<_Tp> cosh(const complex<_Tp>& __z) { return __complex_cosh(__z); } #endif // 26.2.8/3 exp(__z): Returns the complex base e exponential of x template inline complex<_Tp> __complex_exp(const complex<_Tp>& __z) { return std::polar<_Tp>(exp(__z.real()), __z.imag()); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_exp(__complex__ float __z) { return __builtin_cexpf(__z); } inline __complex__ double __complex_exp(__complex__ double __z) { return __builtin_cexp(__z); } inline __complex__ long double __complex_exp(const __complex__ long double& __z) { return __builtin_cexpl(__z); } template inline complex<_Tp> exp(const complex<_Tp>& __z) { return __complex_exp(__z.__rep()); } #else template inline complex<_Tp> exp(const complex<_Tp>& __z) { return __complex_exp(__z); } #endif // 26.2.8/5 log(__z): Returns the natural complex logarithm of __z. // The branch cut is along the negative axis. template inline complex<_Tp> __complex_log(const complex<_Tp>& __z) { return complex<_Tp>(log(std::abs(__z)), std::arg(__z)); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_log(__complex__ float __z) { return __builtin_clogf(__z); } inline __complex__ double __complex_log(__complex__ double __z) { return __builtin_clog(__z); } inline __complex__ long double __complex_log(const __complex__ long double& __z) { return __builtin_clogl(__z); } template inline complex<_Tp> log(const complex<_Tp>& __z) { return __complex_log(__z.__rep()); } #else template inline complex<_Tp> log(const complex<_Tp>& __z) { return __complex_log(__z); } #endif template inline complex<_Tp> log10(const complex<_Tp>& __z) { return std::log(__z) / log(_Tp(10.0)); } // 26.2.8/10 sin(__z): Returns the sine of __z. template inline complex<_Tp> __complex_sin(const complex<_Tp>& __z) { const _Tp __x = __z.real(); const _Tp __y = __z.imag(); return complex<_Tp>(sin(__x) * cosh(__y), cos(__x) * sinh(__y)); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_sin(__complex__ float __z) { return __builtin_csinf(__z); } inline __complex__ double __complex_sin(__complex__ double __z) { return __builtin_csin(__z); } inline __complex__ long double __complex_sin(const __complex__ long double& __z) { return __builtin_csinl(__z); } template inline complex<_Tp> sin(const complex<_Tp>& __z) { return __complex_sin(__z.__rep()); } #else template inline complex<_Tp> sin(const complex<_Tp>& __z) { return __complex_sin(__z); } #endif // 26.2.8/11 sinh(__z): Returns the hyperbolic sine of __z. template inline complex<_Tp> __complex_sinh(const complex<_Tp>& __z) { const _Tp __x = __z.real(); const _Tp __y = __z.imag(); return complex<_Tp>(sinh(__x) * cos(__y), cosh(__x) * sin(__y)); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_sinh(__complex__ float __z) { return __builtin_csinhf(__z); } inline __complex__ double __complex_sinh(__complex__ double __z) { return __builtin_csinh(__z); } inline __complex__ long double __complex_sinh(const __complex__ long double& __z) { return __builtin_csinhl(__z); } template inline complex<_Tp> sinh(const complex<_Tp>& __z) { return __complex_sinh(__z.__rep()); } #else template inline complex<_Tp> sinh(const complex<_Tp>& __z) { return __complex_sinh(__z); } #endif // 26.2.8/13 sqrt(__z): Returns the complex square root of __z. // The branch cut is on the negative axis. template complex<_Tp> __complex_sqrt(const complex<_Tp>& __z) { _Tp __x = __z.real(); _Tp __y = __z.imag(); if (__x == _Tp()) { _Tp __t = sqrt(abs(__y) / 2); return complex<_Tp>(__t, __y < _Tp() ? -__t : __t); } else { _Tp __t = sqrt(2 * (std::abs(__z) + abs(__x))); _Tp __u = __t / 2; return __x > _Tp() ? complex<_Tp>(__u, __y / __t) : complex<_Tp>(abs(__y) / __t, __y < _Tp() ? -__u : __u); } } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_sqrt(__complex__ float __z) { return __builtin_csqrtf(__z); } inline __complex__ double __complex_sqrt(__complex__ double __z) { return __builtin_csqrt(__z); } inline __complex__ long double __complex_sqrt(const __complex__ long double& __z) { return __builtin_csqrtl(__z); } template inline complex<_Tp> sqrt(const complex<_Tp>& __z) { return __complex_sqrt(__z.__rep()); } #else template inline complex<_Tp> sqrt(const complex<_Tp>& __z) { return __complex_sqrt(__z); } #endif // 26.2.8/14 tan(__z): Return the complex tangent of __z. template inline complex<_Tp> __complex_tan(const complex<_Tp>& __z) { return std::sin(__z) / std::cos(__z); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_tan(__complex__ float __z) { return __builtin_ctanf(__z); } inline __complex__ double __complex_tan(__complex__ double __z) { return __builtin_ctan(__z); } inline __complex__ long double __complex_tan(const __complex__ long double& __z) { return __builtin_ctanl(__z); } template inline complex<_Tp> tan(const complex<_Tp>& __z) { return __complex_tan(__z.__rep()); } #else template inline complex<_Tp> tan(const complex<_Tp>& __z) { return __complex_tan(__z); } #endif // 26.2.8/15 tanh(__z): Returns the hyperbolic tangent of __z. template inline complex<_Tp> __complex_tanh(const complex<_Tp>& __z) { return std::sinh(__z) / std::cosh(__z); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_tanh(__complex__ float __z) { return __builtin_ctanhf(__z); } inline __complex__ double __complex_tanh(__complex__ double __z) { return __builtin_ctanh(__z); } inline __complex__ long double __complex_tanh(const __complex__ long double& __z) { return __builtin_ctanhl(__z); } template inline complex<_Tp> tanh(const complex<_Tp>& __z) { return __complex_tanh(__z.__rep()); } #else template inline complex<_Tp> tanh(const complex<_Tp>& __z) { return __complex_tanh(__z); } #endif // 26.2.8/9 pow(__x, __y): Returns the complex power base of __x // raised to the __y-th power. The branch // cut is on the negative axis. template complex<_Tp> __complex_pow_unsigned(complex<_Tp> __x, unsigned __n) { complex<_Tp> __y = __n % 2 ? __x : complex<_Tp>(1); while (__n >>= 1) { __x *= __x; if (__n % 2) __y *= __x; } return __y; } // In C++11 mode we used to implement the resolution of // DR 844. complex pow return type is ambiguous. // thus the following overload was disabled in that mode. However, doing // that causes all sorts of issues, see, for example: // http://gcc.gnu.org/ml/libstdc++/2013-01/msg00058.html // and also PR57974. template inline complex<_Tp> pow(const complex<_Tp>& __z, int __n) { return __n < 0 ? complex<_Tp>(1) / std::__complex_pow_unsigned(__z, -(unsigned)__n) : std::__complex_pow_unsigned(__z, __n); } template complex<_Tp> pow(const complex<_Tp>& __x, const _Tp& __y) { #if ! _GLIBCXX_USE_C99_COMPLEX if (__x == _Tp()) return _Tp(); #endif if (__x.imag() == _Tp() && __x.real() > _Tp()) return pow(__x.real(), __y); complex<_Tp> __t = std::log(__x); return std::polar<_Tp>(exp(__y * __t.real()), __y * __t.imag()); } template inline complex<_Tp> __complex_pow(const complex<_Tp>& __x, const complex<_Tp>& __y) { return __x == _Tp() ? _Tp() : std::exp(__y * std::log(__x)); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_pow(__complex__ float __x, __complex__ float __y) { return __builtin_cpowf(__x, __y); } inline __complex__ double __complex_pow(__complex__ double __x, __complex__ double __y) { return __builtin_cpow(__x, __y); } inline __complex__ long double __complex_pow(const __complex__ long double& __x, const __complex__ long double& __y) { return __builtin_cpowl(__x, __y); } template inline complex<_Tp> pow(const complex<_Tp>& __x, const complex<_Tp>& __y) { return __complex_pow(__x.__rep(), __y.__rep()); } #else template inline complex<_Tp> pow(const complex<_Tp>& __x, const complex<_Tp>& __y) { return __complex_pow(__x, __y); } #endif template inline complex<_Tp> pow(const _Tp& __x, const complex<_Tp>& __y) { return __x > _Tp() ? std::polar<_Tp>(pow(__x, __y.real()), __y.imag() * log(__x)) : std::pow(complex<_Tp>(__x), __y); } /// 26.2.3 complex specializations /// complex specialization template<> struct complex { typedef float value_type; typedef __complex__ float _ComplexT; _GLIBCXX_CONSTEXPR complex(_ComplexT __z) : _M_value(__z) { } _GLIBCXX_CONSTEXPR complex(float __r = 0.0f, float __i = 0.0f) #if __cplusplus >= 201103L : _M_value{ __r, __i } { } #else { __real__ _M_value = __r; __imag__ _M_value = __i; } #endif explicit _GLIBCXX_CONSTEXPR complex(const complex&); explicit _GLIBCXX_CONSTEXPR complex(const complex&); #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. __attribute ((__abi_tag__ ("cxx11"))) constexpr float real() const { return __real__ _M_value; } __attribute ((__abi_tag__ ("cxx11"))) constexpr float imag() const { return __imag__ _M_value; } #else float& real() { return __real__ _M_value; } const float& real() const { return __real__ _M_value; } float& imag() { return __imag__ _M_value; } const float& imag() const { return __imag__ _M_value; } #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. void real(float __val) { __real__ _M_value = __val; } void imag(float __val) { __imag__ _M_value = __val; } complex& operator=(float __f) { _M_value = __f; return *this; } complex& operator+=(float __f) { _M_value += __f; return *this; } complex& operator-=(float __f) { _M_value -= __f; return *this; } complex& operator*=(float __f) { _M_value *= __f; return *this; } complex& operator/=(float __f) { _M_value /= __f; return *this; } // Let the compiler synthesize the copy and assignment // operator. It always does a pretty good job. // complex& operator=(const complex&); template complex& operator=(const complex<_Tp>& __z) { __real__ _M_value = __z.real(); __imag__ _M_value = __z.imag(); return *this; } template complex& operator+=(const complex<_Tp>& __z) { __real__ _M_value += __z.real(); __imag__ _M_value += __z.imag(); return *this; } template complex& operator-=(const complex<_Tp>& __z) { __real__ _M_value -= __z.real(); __imag__ _M_value -= __z.imag(); return *this; } template complex& operator*=(const complex<_Tp>& __z) { _ComplexT __t; __real__ __t = __z.real(); __imag__ __t = __z.imag(); _M_value *= __t; return *this; } template complex& operator/=(const complex<_Tp>& __z) { _ComplexT __t; __real__ __t = __z.real(); __imag__ __t = __z.imag(); _M_value /= __t; return *this; } _GLIBCXX_CONSTEXPR _ComplexT __rep() const { return _M_value; } private: _ComplexT _M_value; }; /// 26.2.3 complex specializations /// complex specialization template<> struct complex { typedef double value_type; typedef __complex__ double _ComplexT; _GLIBCXX_CONSTEXPR complex(_ComplexT __z) : _M_value(__z) { } _GLIBCXX_CONSTEXPR complex(double __r = 0.0, double __i = 0.0) #if __cplusplus >= 201103L : _M_value{ __r, __i } { } #else { __real__ _M_value = __r; __imag__ _M_value = __i; } #endif _GLIBCXX_CONSTEXPR complex(const complex& __z) : _M_value(__z.__rep()) { } explicit _GLIBCXX_CONSTEXPR complex(const complex&); #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. __attribute ((__abi_tag__ ("cxx11"))) constexpr double real() const { return __real__ _M_value; } __attribute ((__abi_tag__ ("cxx11"))) constexpr double imag() const { return __imag__ _M_value; } #else double& real() { return __real__ _M_value; } const double& real() const { return __real__ _M_value; } double& imag() { return __imag__ _M_value; } const double& imag() const { return __imag__ _M_value; } #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. void real(double __val) { __real__ _M_value = __val; } void imag(double __val) { __imag__ _M_value = __val; } complex& operator=(double __d) { _M_value = __d; return *this; } complex& operator+=(double __d) { _M_value += __d; return *this; } complex& operator-=(double __d) { _M_value -= __d; return *this; } complex& operator*=(double __d) { _M_value *= __d; return *this; } complex& operator/=(double __d) { _M_value /= __d; return *this; } // The compiler will synthesize this, efficiently. // complex& operator=(const complex&); template complex& operator=(const complex<_Tp>& __z) { __real__ _M_value = __z.real(); __imag__ _M_value = __z.imag(); return *this; } template complex& operator+=(const complex<_Tp>& __z) { __real__ _M_value += __z.real(); __imag__ _M_value += __z.imag(); return *this; } template complex& operator-=(const complex<_Tp>& __z) { __real__ _M_value -= __z.real(); __imag__ _M_value -= __z.imag(); return *this; } template complex& operator*=(const complex<_Tp>& __z) { _ComplexT __t; __real__ __t = __z.real(); __imag__ __t = __z.imag(); _M_value *= __t; return *this; } template complex& operator/=(const complex<_Tp>& __z) { _ComplexT __t; __real__ __t = __z.real(); __imag__ __t = __z.imag(); _M_value /= __t; return *this; } _GLIBCXX_CONSTEXPR _ComplexT __rep() const { return _M_value; } private: _ComplexT _M_value; }; /// 26.2.3 complex specializations /// complex specialization template<> struct complex { typedef long double value_type; typedef __complex__ long double _ComplexT; _GLIBCXX_CONSTEXPR complex(_ComplexT __z) : _M_value(__z) { } _GLIBCXX_CONSTEXPR complex(long double __r = 0.0L, long double __i = 0.0L) #if __cplusplus >= 201103L : _M_value{ __r, __i } { } #else { __real__ _M_value = __r; __imag__ _M_value = __i; } #endif _GLIBCXX_CONSTEXPR complex(const complex& __z) : _M_value(__z.__rep()) { } _GLIBCXX_CONSTEXPR complex(const complex& __z) : _M_value(__z.__rep()) { } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. __attribute ((__abi_tag__ ("cxx11"))) constexpr long double real() const { return __real__ _M_value; } __attribute ((__abi_tag__ ("cxx11"))) constexpr long double imag() const { return __imag__ _M_value; } #else long double& real() { return __real__ _M_value; } const long double& real() const { return __real__ _M_value; } long double& imag() { return __imag__ _M_value; } const long double& imag() const { return __imag__ _M_value; } #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. void real(long double __val) { __real__ _M_value = __val; } void imag(long double __val) { __imag__ _M_value = __val; } complex& operator=(long double __r) { _M_value = __r; return *this; } complex& operator+=(long double __r) { _M_value += __r; return *this; } complex& operator-=(long double __r) { _M_value -= __r; return *this; } complex& operator*=(long double __r) { _M_value *= __r; return *this; } complex& operator/=(long double __r) { _M_value /= __r; return *this; } // The compiler knows how to do this efficiently // complex& operator=(const complex&); template complex& operator=(const complex<_Tp>& __z) { __real__ _M_value = __z.real(); __imag__ _M_value = __z.imag(); return *this; } template complex& operator+=(const complex<_Tp>& __z) { __real__ _M_value += __z.real(); __imag__ _M_value += __z.imag(); return *this; } template complex& operator-=(const complex<_Tp>& __z) { __real__ _M_value -= __z.real(); __imag__ _M_value -= __z.imag(); return *this; } template complex& operator*=(const complex<_Tp>& __z) { _ComplexT __t; __real__ __t = __z.real(); __imag__ __t = __z.imag(); _M_value *= __t; return *this; } template complex& operator/=(const complex<_Tp>& __z) { _ComplexT __t; __real__ __t = __z.real(); __imag__ __t = __z.imag(); _M_value /= __t; return *this; } _GLIBCXX_CONSTEXPR _ComplexT __rep() const { return _M_value; } private: _ComplexT _M_value; }; // These bits have to be at the end of this file, so that the // specializations have all been defined. inline _GLIBCXX_CONSTEXPR complex::complex(const complex& __z) : _M_value(__z.__rep()) { } inline _GLIBCXX_CONSTEXPR complex::complex(const complex& __z) : _M_value(__z.__rep()) { } inline _GLIBCXX_CONSTEXPR complex::complex(const complex& __z) : _M_value(__z.__rep()) { } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. // NB: This syntax is a GNU extension. #if _GLIBCXX_EXTERN_TEMPLATE extern template istream& operator>>(istream&, complex&); extern template ostream& operator<<(ostream&, const complex&); extern template istream& operator>>(istream&, complex&); extern template ostream& operator<<(ostream&, const complex&); extern template istream& operator>>(istream&, complex&); extern template ostream& operator<<(ostream&, const complex&); #ifdef _GLIBCXX_USE_WCHAR_T extern template wistream& operator>>(wistream&, complex&); extern template wostream& operator<<(wostream&, const complex&); extern template wistream& operator>>(wistream&, complex&); extern template wostream& operator<<(wostream&, const complex&); extern template wistream& operator>>(wistream&, complex&); extern template wostream& operator<<(wostream&, const complex&); #endif #endif // @} group complex_numbers _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // See ext/type_traits.h for the primary template. template struct __promote_2, _Up> { public: typedef std::complex::__type> __type; }; template struct __promote_2<_Tp, std::complex<_Up> > { public: typedef std::complex::__type> __type; }; template struct __promote_2, std::complex<_Up> > { public: typedef std::complex::__type> __type; }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #if __cplusplus >= 201103L namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Forward declarations. template std::complex<_Tp> acos(const std::complex<_Tp>&); template std::complex<_Tp> asin(const std::complex<_Tp>&); template std::complex<_Tp> atan(const std::complex<_Tp>&); template std::complex<_Tp> acosh(const std::complex<_Tp>&); template std::complex<_Tp> asinh(const std::complex<_Tp>&); template std::complex<_Tp> atanh(const std::complex<_Tp>&); // DR 595. template _Tp fabs(const std::complex<_Tp>&); template inline std::complex<_Tp> __complex_acos(const std::complex<_Tp>& __z) { const std::complex<_Tp> __t = std::asin(__z); const _Tp __pi_2 = 1.5707963267948966192313216916397514L; return std::complex<_Tp>(__pi_2 - __t.real(), -__t.imag()); } #if _GLIBCXX_USE_C99_COMPLEX_TR1 inline __complex__ float __complex_acos(__complex__ float __z) { return __builtin_cacosf(__z); } inline __complex__ double __complex_acos(__complex__ double __z) { return __builtin_cacos(__z); } inline __complex__ long double __complex_acos(const __complex__ long double& __z) { return __builtin_cacosl(__z); } template inline std::complex<_Tp> acos(const std::complex<_Tp>& __z) { return __complex_acos(__z.__rep()); } #else /// acos(__z) [8.1.2]. // Effects: Behaves the same as C99 function cacos, defined // in subclause 7.3.5.1. template inline std::complex<_Tp> acos(const std::complex<_Tp>& __z) { return __complex_acos(__z); } #endif template inline std::complex<_Tp> __complex_asin(const std::complex<_Tp>& __z) { std::complex<_Tp> __t(-__z.imag(), __z.real()); __t = std::asinh(__t); return std::complex<_Tp>(__t.imag(), -__t.real()); } #if _GLIBCXX_USE_C99_COMPLEX_TR1 inline __complex__ float __complex_asin(__complex__ float __z) { return __builtin_casinf(__z); } inline __complex__ double __complex_asin(__complex__ double __z) { return __builtin_casin(__z); } inline __complex__ long double __complex_asin(const __complex__ long double& __z) { return __builtin_casinl(__z); } template inline std::complex<_Tp> asin(const std::complex<_Tp>& __z) { return __complex_asin(__z.__rep()); } #else /// asin(__z) [8.1.3]. // Effects: Behaves the same as C99 function casin, defined // in subclause 7.3.5.2. template inline std::complex<_Tp> asin(const std::complex<_Tp>& __z) { return __complex_asin(__z); } #endif template std::complex<_Tp> __complex_atan(const std::complex<_Tp>& __z) { const _Tp __r2 = __z.real() * __z.real(); const _Tp __x = _Tp(1.0) - __r2 - __z.imag() * __z.imag(); _Tp __num = __z.imag() + _Tp(1.0); _Tp __den = __z.imag() - _Tp(1.0); __num = __r2 + __num * __num; __den = __r2 + __den * __den; return std::complex<_Tp>(_Tp(0.5) * atan2(_Tp(2.0) * __z.real(), __x), _Tp(0.25) * log(__num / __den)); } #if _GLIBCXX_USE_C99_COMPLEX_TR1 inline __complex__ float __complex_atan(__complex__ float __z) { return __builtin_catanf(__z); } inline __complex__ double __complex_atan(__complex__ double __z) { return __builtin_catan(__z); } inline __complex__ long double __complex_atan(const __complex__ long double& __z) { return __builtin_catanl(__z); } template inline std::complex<_Tp> atan(const std::complex<_Tp>& __z) { return __complex_atan(__z.__rep()); } #else /// atan(__z) [8.1.4]. // Effects: Behaves the same as C99 function catan, defined // in subclause 7.3.5.3. template inline std::complex<_Tp> atan(const std::complex<_Tp>& __z) { return __complex_atan(__z); } #endif template std::complex<_Tp> __complex_acosh(const std::complex<_Tp>& __z) { // Kahan's formula. return _Tp(2.0) * std::log(std::sqrt(_Tp(0.5) * (__z + _Tp(1.0))) + std::sqrt(_Tp(0.5) * (__z - _Tp(1.0)))); } #if _GLIBCXX_USE_C99_COMPLEX_TR1 inline __complex__ float __complex_acosh(__complex__ float __z) { return __builtin_cacoshf(__z); } inline __complex__ double __complex_acosh(__complex__ double __z) { return __builtin_cacosh(__z); } inline __complex__ long double __complex_acosh(const __complex__ long double& __z) { return __builtin_cacoshl(__z); } template inline std::complex<_Tp> acosh(const std::complex<_Tp>& __z) { return __complex_acosh(__z.__rep()); } #else /// acosh(__z) [8.1.5]. // Effects: Behaves the same as C99 function cacosh, defined // in subclause 7.3.6.1. template inline std::complex<_Tp> acosh(const std::complex<_Tp>& __z) { return __complex_acosh(__z); } #endif template std::complex<_Tp> __complex_asinh(const std::complex<_Tp>& __z) { std::complex<_Tp> __t((__z.real() - __z.imag()) * (__z.real() + __z.imag()) + _Tp(1.0), _Tp(2.0) * __z.real() * __z.imag()); __t = std::sqrt(__t); return std::log(__t + __z); } #if _GLIBCXX_USE_C99_COMPLEX_TR1 inline __complex__ float __complex_asinh(__complex__ float __z) { return __builtin_casinhf(__z); } inline __complex__ double __complex_asinh(__complex__ double __z) { return __builtin_casinh(__z); } inline __complex__ long double __complex_asinh(const __complex__ long double& __z) { return __builtin_casinhl(__z); } template inline std::complex<_Tp> asinh(const std::complex<_Tp>& __z) { return __complex_asinh(__z.__rep()); } #else /// asinh(__z) [8.1.6]. // Effects: Behaves the same as C99 function casin, defined // in subclause 7.3.6.2. template inline std::complex<_Tp> asinh(const std::complex<_Tp>& __z) { return __complex_asinh(__z); } #endif template std::complex<_Tp> __complex_atanh(const std::complex<_Tp>& __z) { const _Tp __i2 = __z.imag() * __z.imag(); const _Tp __x = _Tp(1.0) - __i2 - __z.real() * __z.real(); _Tp __num = _Tp(1.0) + __z.real(); _Tp __den = _Tp(1.0) - __z.real(); __num = __i2 + __num * __num; __den = __i2 + __den * __den; return std::complex<_Tp>(_Tp(0.25) * (log(__num) - log(__den)), _Tp(0.5) * atan2(_Tp(2.0) * __z.imag(), __x)); } #if _GLIBCXX_USE_C99_COMPLEX_TR1 inline __complex__ float __complex_atanh(__complex__ float __z) { return __builtin_catanhf(__z); } inline __complex__ double __complex_atanh(__complex__ double __z) { return __builtin_catanh(__z); } inline __complex__ long double __complex_atanh(const __complex__ long double& __z) { return __builtin_catanhl(__z); } template inline std::complex<_Tp> atanh(const std::complex<_Tp>& __z) { return __complex_atanh(__z.__rep()); } #else /// atanh(__z) [8.1.7]. // Effects: Behaves the same as C99 function catanh, defined // in subclause 7.3.6.3. template inline std::complex<_Tp> atanh(const std::complex<_Tp>& __z) { return __complex_atanh(__z); } #endif template inline _Tp /// fabs(__z) [8.1.8]. // Effects: Behaves the same as C99 function cabs, defined // in subclause 7.3.8.1. fabs(const std::complex<_Tp>& __z) { return std::abs(__z); } /// Additional overloads [8.1.9]. template inline typename __gnu_cxx::__promote<_Tp>::__type arg(_Tp __x) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; #if (_GLIBCXX11_USE_C99_MATH && !_GLIBCXX_USE_C99_FP_MACROS_DYNAMIC) return std::signbit(__x) ? __type(3.1415926535897932384626433832795029L) : __type(); #else return std::arg(std::complex<__type>(__x)); #endif } template _GLIBCXX_CONSTEXPR inline typename __gnu_cxx::__promote<_Tp>::__type imag(_Tp) { return _Tp(); } template inline typename __gnu_cxx::__promote<_Tp>::__type norm(_Tp __x) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __type(__x) * __type(__x); } template _GLIBCXX_CONSTEXPR inline typename __gnu_cxx::__promote<_Tp>::__type real(_Tp __x) { return __x; } template inline std::complex::__type> pow(const std::complex<_Tp>& __x, const _Up& __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return std::pow(std::complex<__type>(__x), __type(__y)); } template inline std::complex::__type> pow(const _Tp& __x, const std::complex<_Up>& __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return std::pow(__type(__x), std::complex<__type>(__y)); } template inline std::complex::__type> pow(const std::complex<_Tp>& __x, const std::complex<_Up>& __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return std::pow(std::complex<__type>(__x), std::complex<__type>(__y)); } // Forward declarations. // DR 781. template std::complex<_Tp> proj(const std::complex<_Tp>&); template std::complex<_Tp> __complex_proj(const std::complex<_Tp>& __z) { const _Tp __den = (__z.real() * __z.real() + __z.imag() * __z.imag() + _Tp(1.0)); return std::complex<_Tp>((_Tp(2.0) * __z.real()) / __den, (_Tp(2.0) * __z.imag()) / __den); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_proj(__complex__ float __z) { return __builtin_cprojf(__z); } inline __complex__ double __complex_proj(__complex__ double __z) { return __builtin_cproj(__z); } inline __complex__ long double __complex_proj(const __complex__ long double& __z) { return __builtin_cprojl(__z); } template inline std::complex<_Tp> proj(const std::complex<_Tp>& __z) { return __complex_proj(__z.__rep()); } #else template inline std::complex<_Tp> proj(const std::complex<_Tp>& __z) { return __complex_proj(__z); } #endif template inline std::complex::__type> proj(_Tp __x) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return std::proj(std::complex<__type>(__x)); } template inline std::complex::__type> conj(_Tp __x) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return std::complex<__type>(__x, -__type()); } #if __cplusplus > 201103L inline namespace literals { inline namespace complex_literals { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wliteral-suffix" #define __cpp_lib_complex_udls 201309 constexpr std::complex operator""if(long double __num) { return std::complex{0.0F, static_cast(__num)}; } constexpr std::complex operator""if(unsigned long long __num) { return std::complex{0.0F, static_cast(__num)}; } constexpr std::complex operator""i(long double __num) { return std::complex{0.0, static_cast(__num)}; } constexpr std::complex operator""i(unsigned long long __num) { return std::complex{0.0, static_cast(__num)}; } constexpr std::complex operator""il(long double __num) { return std::complex{0.0L, __num}; } constexpr std::complex operator""il(unsigned long long __num) { return std::complex{0.0L, static_cast(__num)}; } #pragma GCC diagnostic pop } // inline namespace complex_literals } // inline namespace literals #endif // C++14 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // C++11 #endif /* _GLIBCXX_COMPLEX */ PK!M=c<< 8/complex.hnu[// -*- C++ -*- compatibility header. // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file complex.h * This is a Standard C++ Library header. */ #include #if __cplusplus >= 201103L # include #endif #if __cplusplus >= 201103L && defined(__STRICT_ANSI__) // For strict modes do not include the C library's , see PR 82417. #elif _GLIBCXX_HAVE_COMPLEX_H # include_next # ifdef _GLIBCXX_COMPLEX // See PR56111, keep the macro in C++03 if possible. # undef complex # endif #endif #ifndef _GLIBCXX_COMPLEX_H #define _GLIBCXX_COMPLEX_H 1 #endif PK!p""8/condition_variablenu[// -*- C++ -*- // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/condition_variable * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_CONDITION_VARIABLE #define _GLIBCXX_CONDITION_VARIABLE 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #include #include #include #include #include #include #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1) namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup condition_variables Condition Variables * @ingroup concurrency * * Classes for condition_variable support. * @{ */ /// cv_status enum class cv_status { no_timeout, timeout }; /// condition_variable class condition_variable { typedef chrono::system_clock __clock_t; typedef __gthread_cond_t __native_type; #ifdef __GTHREAD_COND_INIT __native_type _M_cond = __GTHREAD_COND_INIT; #else __native_type _M_cond; #endif public: typedef __native_type* native_handle_type; condition_variable() noexcept; ~condition_variable() noexcept; condition_variable(const condition_variable&) = delete; condition_variable& operator=(const condition_variable&) = delete; void notify_one() noexcept; void notify_all() noexcept; void wait(unique_lock& __lock) noexcept; template void wait(unique_lock& __lock, _Predicate __p) { while (!__p()) wait(__lock); } template cv_status wait_until(unique_lock& __lock, const chrono::time_point<__clock_t, _Duration>& __atime) { return __wait_until_impl(__lock, __atime); } template cv_status wait_until(unique_lock& __lock, const chrono::time_point<_Clock, _Duration>& __atime) { // DR 887 - Sync unknown clock to known clock. const typename _Clock::time_point __c_entry = _Clock::now(); const __clock_t::time_point __s_entry = __clock_t::now(); const auto __delta = __atime - __c_entry; const auto __s_atime = __s_entry + __delta; return __wait_until_impl(__lock, __s_atime); } template bool wait_until(unique_lock& __lock, const chrono::time_point<_Clock, _Duration>& __atime, _Predicate __p) { while (!__p()) if (wait_until(__lock, __atime) == cv_status::timeout) return __p(); return true; } template cv_status wait_for(unique_lock& __lock, const chrono::duration<_Rep, _Period>& __rtime) { using __dur = typename __clock_t::duration; auto __reltime = chrono::duration_cast<__dur>(__rtime); if (__reltime < __rtime) ++__reltime; return wait_until(__lock, __clock_t::now() + __reltime); } template bool wait_for(unique_lock& __lock, const chrono::duration<_Rep, _Period>& __rtime, _Predicate __p) { using __dur = typename __clock_t::duration; auto __reltime = chrono::duration_cast<__dur>(__rtime); if (__reltime < __rtime) ++__reltime; return wait_until(__lock, __clock_t::now() + __reltime, std::move(__p)); } native_handle_type native_handle() { return &_M_cond; } private: template cv_status __wait_until_impl(unique_lock& __lock, const chrono::time_point<__clock_t, _Dur>& __atime) { auto __s = chrono::time_point_cast(__atime); auto __ns = chrono::duration_cast(__atime - __s); __gthread_time_t __ts = { static_cast(__s.time_since_epoch().count()), static_cast(__ns.count()) }; __gthread_cond_timedwait(&_M_cond, __lock.mutex()->native_handle(), &__ts); return (__clock_t::now() < __atime ? cv_status::no_timeout : cv_status::timeout); } }; void notify_all_at_thread_exit(condition_variable&, unique_lock); struct __at_thread_exit_elt { __at_thread_exit_elt* _M_next; void (*_M_cb)(void*); }; inline namespace _V2 { /// condition_variable_any // Like above, but mutex is not required to have try_lock. class condition_variable_any { typedef chrono::system_clock __clock_t; condition_variable _M_cond; shared_ptr _M_mutex; // scoped unlock - unlocks in ctor, re-locks in dtor template struct _Unlock { explicit _Unlock(_Lock& __lk) : _M_lock(__lk) { __lk.unlock(); } ~_Unlock() noexcept(false) { if (uncaught_exception()) { __try { _M_lock.lock(); } __catch(const __cxxabiv1::__forced_unwind&) { __throw_exception_again; } __catch(...) { } } else _M_lock.lock(); } _Unlock(const _Unlock&) = delete; _Unlock& operator=(const _Unlock&) = delete; _Lock& _M_lock; }; public: condition_variable_any() : _M_mutex(std::make_shared()) { } ~condition_variable_any() = default; condition_variable_any(const condition_variable_any&) = delete; condition_variable_any& operator=(const condition_variable_any&) = delete; void notify_one() noexcept { lock_guard __lock(*_M_mutex); _M_cond.notify_one(); } void notify_all() noexcept { lock_guard __lock(*_M_mutex); _M_cond.notify_all(); } template void wait(_Lock& __lock) { shared_ptr __mutex = _M_mutex; unique_lock __my_lock(*__mutex); _Unlock<_Lock> __unlock(__lock); // *__mutex must be unlocked before re-locking __lock so move // ownership of *__mutex lock to an object with shorter lifetime. unique_lock __my_lock2(std::move(__my_lock)); _M_cond.wait(__my_lock2); } template void wait(_Lock& __lock, _Predicate __p) { while (!__p()) wait(__lock); } template cv_status wait_until(_Lock& __lock, const chrono::time_point<_Clock, _Duration>& __atime) { shared_ptr __mutex = _M_mutex; unique_lock __my_lock(*__mutex); _Unlock<_Lock> __unlock(__lock); // *__mutex must be unlocked before re-locking __lock so move // ownership of *__mutex lock to an object with shorter lifetime. unique_lock __my_lock2(std::move(__my_lock)); return _M_cond.wait_until(__my_lock2, __atime); } template bool wait_until(_Lock& __lock, const chrono::time_point<_Clock, _Duration>& __atime, _Predicate __p) { while (!__p()) if (wait_until(__lock, __atime) == cv_status::timeout) return __p(); return true; } template cv_status wait_for(_Lock& __lock, const chrono::duration<_Rep, _Period>& __rtime) { return wait_until(__lock, __clock_t::now() + __rtime); } template bool wait_for(_Lock& __lock, const chrono::duration<_Rep, _Period>& __rtime, _Predicate __p) { return wait_until(__lock, __clock_t::now() + __rtime, std::move(__p)); } }; } // end inline namespace // @} group condition_variables _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1 #endif // C++11 #endif // _GLIBCXX_CONDITION_VARIABLE PK!߃ 8/csetjmpnu[// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file csetjmp * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c setjmp.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 20.4.6 C library // #pragma GCC system_header #include #include #ifndef _GLIBCXX_CSETJMP #define _GLIBCXX_CSETJMP 1 // Get rid of those macros defined in in lieu of real functions. #undef longjmp // Adhere to section 17.4.1.2 clause 5 of ISO 14882:1998 #ifndef setjmp #define setjmp(env) setjmp (env) #endif namespace std { using ::jmp_buf; using ::longjmp; } // namespace std #endif PK!?? 8/csignalnu[// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file csignal * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c signal.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 20.4.6 C library // #pragma GCC system_header #include #include #ifndef _GLIBCXX_CSIGNAL #define _GLIBCXX_CSIGNAL 1 // Get rid of those macros defined in in lieu of real functions. #undef raise namespace std { using ::sig_atomic_t; using ::signal; using ::raise; } // namespace std #endif PK!K 8/cstdalignnu[// -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/cstdalign * This is a Standard C++ Library header. */ #pragma GCC system_header #ifndef _GLIBCXX_CSTDALIGN #define _GLIBCXX_CSTDALIGN 1 #if __cplusplus < 201103L # include #else # include # if _GLIBCXX_HAVE_STDALIGN_H # include # endif #endif #endif PK!>LL 8/cstdargnu[// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/cstdarg * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c stdarg.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 20.4.6 C library // #pragma GCC system_header #undef __need___va_list #include #include #ifndef _GLIBCXX_CSTDARG #define _GLIBCXX_CSTDARG 1 // Adhere to section 17.4.1.2 clause 5 of ISO 14882:1998 #ifndef va_end #define va_end(ap) va_end (ap) #endif namespace std { using ::va_list; } // namespace std #endif PK!9yy 8/cstdboolnu[// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/cstdbool * This is a Standard C++ Library header. */ #pragma GCC system_header #ifndef _GLIBCXX_CSTDBOOL #define _GLIBCXX_CSTDBOOL 1 #if __cplusplus < 201103L # include #else # include # if _GLIBCXX_HAVE_STDBOOL_H # include # endif #endif #endif PK!$Y(( 8/cstddefnu[// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file cstddef * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c stddef.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 18.1 Types // #ifndef _GLIBCXX_CSTDDEF #define _GLIBCXX_CSTDDEF 1 #pragma GCC system_header #undef __need_wchar_t #undef __need_ptrdiff_t #undef __need_size_t #undef __need_NULL #undef __need_wint_t #include #include #if __cplusplus >= 201103L namespace std { // We handle size_t, ptrdiff_t, and nullptr_t in c++config.h. using ::max_align_t; } #endif #if __cplusplus >= 201703L namespace std { #define __cpp_lib_byte 201603 /// std::byte enum class byte : unsigned char {}; template struct __byte_operand { }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; #ifdef _GLIBCXX_USE_WCHAR_T template<> struct __byte_operand { using __type = byte; }; #endif template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; #if defined(__GLIBCXX_TYPE_INT_N_0) template<> struct __byte_operand<__GLIBCXX_TYPE_INT_N_0> { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; #endif #if defined(__GLIBCXX_TYPE_INT_N_1) template<> struct __byte_operand<__GLIBCXX_TYPE_INT_N_1> { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; #endif #if defined(__GLIBCXX_TYPE_INT_N_2) template<> struct __byte_operand<__GLIBCXX_TYPE_INT_N_2> { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; #endif template struct __byte_operand : __byte_operand<_IntegerType> { }; template struct __byte_operand : __byte_operand<_IntegerType> { }; template struct __byte_operand : __byte_operand<_IntegerType> { }; template using __byte_op_t = typename __byte_operand<_IntegerType>::__type; template constexpr __byte_op_t<_IntegerType>& operator<<=(byte& __b, _IntegerType __shift) noexcept { return __b = byte(static_cast(__b) << __shift); } template constexpr __byte_op_t<_IntegerType> operator<<(byte __b, _IntegerType __shift) noexcept { return byte(static_cast(__b) << __shift); } template constexpr __byte_op_t<_IntegerType>& operator>>=(byte& __b, _IntegerType __shift) noexcept { return __b = byte(static_cast(__b) >> __shift); } template constexpr __byte_op_t<_IntegerType> operator>>(byte __b, _IntegerType __shift) noexcept { return byte(static_cast(__b) >> __shift); } constexpr byte& operator|=(byte& __l, byte __r) noexcept { return __l = byte(static_cast(__l) | static_cast(__r)); } constexpr byte operator|(byte __l, byte __r) noexcept { return byte(static_cast(__l) | static_cast(__r)); } constexpr byte& operator&=(byte& __l, byte __r) noexcept { return __l = byte(static_cast(__l) & static_cast(__r)); } constexpr byte operator&(byte __l, byte __r) noexcept { return byte(static_cast(__l) & static_cast(__r)); } constexpr byte& operator^=(byte& __l, byte __r) noexcept { return __l = byte(static_cast(__l) ^ static_cast(__r)); } constexpr byte operator^(byte __l, byte __r) noexcept { return byte(static_cast(__l) ^ static_cast(__r)); } constexpr byte operator~(byte __b) noexcept { return byte(~static_cast(__b)); } template constexpr _IntegerType to_integer(__byte_op_t<_IntegerType> __b) noexcept { return _IntegerType(__b); } } // namespace std #endif #endif // _GLIBCXX_CSTDDEF PK!ʼnww 8/cstdintnu[// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/cstdint * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_CSTDINT #define _GLIBCXX_CSTDINT 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #if _GLIBCXX_HAVE_STDINT_H # include #endif #ifdef _GLIBCXX_USE_C99_STDINT_TR1 namespace std { using ::int8_t; using ::int16_t; using ::int32_t; using ::int64_t; using ::int_fast8_t; using ::int_fast16_t; using ::int_fast32_t; using ::int_fast64_t; using ::int_least8_t; using ::int_least16_t; using ::int_least32_t; using ::int_least64_t; using ::intmax_t; using ::intptr_t; using ::uint8_t; using ::uint16_t; using ::uint32_t; using ::uint64_t; using ::uint_fast8_t; using ::uint_fast16_t; using ::uint_fast32_t; using ::uint_fast64_t; using ::uint_least8_t; using ::uint_least16_t; using ::uint_least32_t; using ::uint_least64_t; using ::uintmax_t; using ::uintptr_t; } // namespace std #endif // _GLIBCXX_USE_C99_STDINT_TR1 #endif // C++11 #endif // _GLIBCXX_CSTDINT PK!!WW8/cstdionu[// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/cstdio * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c stdio.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 27.8.2 C Library files // #pragma GCC system_header #include #include #ifndef _GLIBCXX_CSTDIO #define _GLIBCXX_CSTDIO 1 #if __cplusplus <= 201103L && !defined(_GLIBCXX_HAVE_GETS) extern "C" char* gets (char* __s) __attribute__((__deprecated__)); #endif // Get rid of those macros defined in in lieu of real functions. #undef clearerr #undef fclose #undef feof #undef ferror #undef fflush #undef fgetc #undef fgetpos #undef fgets #undef fopen #undef fprintf #undef fputc #undef fputs #undef fread #undef freopen #undef fscanf #undef fseek #undef fsetpos #undef ftell #undef fwrite #undef getc #undef getchar #if __cplusplus <= 201103L # undef gets #endif #undef perror #undef printf #undef putc #undef putchar #undef puts #undef remove #undef rename #undef rewind #undef scanf #undef setbuf #undef setvbuf #undef sprintf #undef sscanf #undef tmpfile #undef tmpnam #undef ungetc #undef vfprintf #undef vprintf #undef vsprintf namespace std { using ::FILE; using ::fpos_t; using ::clearerr; using ::fclose; using ::feof; using ::ferror; using ::fflush; using ::fgetc; using ::fgetpos; using ::fgets; using ::fopen; using ::fprintf; using ::fputc; using ::fputs; using ::fread; using ::freopen; using ::fscanf; using ::fseek; using ::fsetpos; using ::ftell; using ::fwrite; using ::getc; using ::getchar; #if __cplusplus <= 201103L // LWG 2249 using ::gets; #endif using ::perror; using ::printf; using ::putc; using ::putchar; using ::puts; using ::remove; using ::rename; using ::rewind; using ::scanf; using ::setbuf; using ::setvbuf; using ::sprintf; using ::sscanf; using ::tmpfile; #if _GLIBCXX_USE_TMPNAM using ::tmpnam; #endif using ::ungetc; using ::vfprintf; using ::vprintf; using ::vsprintf; } // namespace #if _GLIBCXX_USE_C99_STDIO #undef snprintf #undef vfscanf #undef vscanf #undef vsnprintf #undef vsscanf namespace __gnu_cxx { #if _GLIBCXX_USE_C99_CHECK || _GLIBCXX_USE_C99_DYNAMIC extern "C" int (snprintf)(char * __restrict, std::size_t, const char * __restrict, ...) throw (); extern "C" int (vfscanf)(FILE * __restrict, const char * __restrict, __gnuc_va_list); extern "C" int (vscanf)(const char * __restrict, __gnuc_va_list); extern "C" int (vsnprintf)(char * __restrict, std::size_t, const char * __restrict, __gnuc_va_list) throw (); extern "C" int (vsscanf)(const char * __restrict, const char * __restrict, __gnuc_va_list) throw (); #endif #if !_GLIBCXX_USE_C99_DYNAMIC using ::snprintf; using ::vfscanf; using ::vscanf; using ::vsnprintf; using ::vsscanf; #endif } // namespace __gnu_cxx namespace std { using ::__gnu_cxx::snprintf; using ::__gnu_cxx::vfscanf; using ::__gnu_cxx::vscanf; using ::__gnu_cxx::vsnprintf; using ::__gnu_cxx::vsscanf; } // namespace std #endif // _GLIBCXX_USE_C99_STDIO #endif PK!D@V 8/cstdlibnu[// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/cstdlib * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c stdlib.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 20.4.6 C library // #pragma GCC system_header #include #ifndef _GLIBCXX_CSTDLIB #define _GLIBCXX_CSTDLIB 1 #if !_GLIBCXX_HOSTED // The C standard does not require a freestanding implementation to // provide . However, the C++ standard does still require // -- but only the functionality mentioned in // [lib.support.start.term]. #define EXIT_SUCCESS 0 #define EXIT_FAILURE 1 namespace std { extern "C" void abort(void) throw () _GLIBCXX_NORETURN; extern "C" int atexit(void (*)(void)) throw (); extern "C" void exit(int) throw () _GLIBCXX_NORETURN; #if __cplusplus >= 201103L # ifdef _GLIBCXX_HAVE_AT_QUICK_EXIT extern "C" int at_quick_exit(void (*)(void)) throw (); # endif # ifdef _GLIBCXX_HAVE_QUICK_EXIT extern "C" void quick_exit(int) throw() _GLIBCXX_NORETURN; # endif #endif } // namespace std #else // Need to ensure this finds the C library's not a libstdc++ // wrapper that might already be installed later in the include search path. #define _GLIBCXX_INCLUDE_NEXT_C_HEADERS #include_next #undef _GLIBCXX_INCLUDE_NEXT_C_HEADERS #include // Get rid of those macros defined in in lieu of real functions. #undef abort #if __cplusplus >= 201703L && defined(_GLIBCXX_HAVE_ALIGNED_ALLOC) # undef aligned_alloc #endif #undef atexit #if __cplusplus >= 201103L # ifdef _GLIBCXX_HAVE_AT_QUICK_EXIT # undef at_quick_exit # endif #endif #undef atof #undef atoi #undef atol #undef bsearch #undef calloc #undef div #undef exit #undef free #undef getenv #undef labs #undef ldiv #undef malloc #undef mblen #undef mbstowcs #undef mbtowc #undef qsort #if __cplusplus >= 201103L # ifdef _GLIBCXX_HAVE_QUICK_EXIT # undef quick_exit # endif #endif #undef rand #undef realloc #undef srand #undef strtod #undef strtol #undef strtoul #undef system #undef wcstombs #undef wctomb extern "C++" { namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using ::div_t; using ::ldiv_t; using ::abort; #if __cplusplus >= 201703L && defined(_GLIBCXX_HAVE_ALIGNED_ALLOC) using ::aligned_alloc; #endif using ::atexit; #if __cplusplus >= 201103L # ifdef _GLIBCXX_HAVE_AT_QUICK_EXIT using ::at_quick_exit; # endif #endif using ::atof; using ::atoi; using ::atol; using ::bsearch; using ::calloc; using ::div; using ::exit; using ::free; using ::getenv; using ::labs; using ::ldiv; using ::malloc; #ifdef _GLIBCXX_HAVE_MBSTATE_T using ::mblen; using ::mbstowcs; using ::mbtowc; #endif // _GLIBCXX_HAVE_MBSTATE_T using ::qsort; #if __cplusplus >= 201103L # ifdef _GLIBCXX_HAVE_QUICK_EXIT using ::quick_exit; # endif #endif using ::rand; using ::realloc; using ::srand; using ::strtod; using ::strtol; using ::strtoul; using ::system; #ifdef _GLIBCXX_USE_WCHAR_T using ::wcstombs; using ::wctomb; #endif // _GLIBCXX_USE_WCHAR_T #ifndef __CORRECT_ISO_CPP_STDLIB_H_PROTO inline ldiv_t div(long __i, long __j) { return ldiv(__i, __j); } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #if _GLIBCXX_USE_C99_STDLIB #undef _Exit #undef llabs #undef lldiv #undef atoll #undef strtoll #undef strtoull #undef strtof #undef strtold namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if !_GLIBCXX_USE_C99_LONG_LONG_DYNAMIC using ::lldiv_t; #endif #if _GLIBCXX_USE_C99_CHECK || _GLIBCXX_USE_C99_DYNAMIC extern "C" void (_Exit)(int) throw () _GLIBCXX_NORETURN; #endif #if !_GLIBCXX_USE_C99_DYNAMIC using ::_Exit; #endif #if !_GLIBCXX_USE_C99_LONG_LONG_DYNAMIC using ::llabs; inline lldiv_t div(long long __n, long long __d) { lldiv_t __q; __q.quot = __n / __d; __q.rem = __n % __d; return __q; } using ::lldiv; #endif #if _GLIBCXX_USE_C99_LONG_LONG_CHECK || _GLIBCXX_USE_C99_LONG_LONG_DYNAMIC extern "C" long long int (atoll)(const char *) throw (); extern "C" long long int (strtoll)(const char * __restrict, char ** __restrict, int) throw (); extern "C" unsigned long long int (strtoull)(const char * __restrict, char ** __restrict, int) throw (); #endif #if !_GLIBCXX_USE_C99_LONG_LONG_DYNAMIC using ::atoll; using ::strtoll; using ::strtoull; #endif using ::strtof; using ::strtold; _GLIBCXX_END_NAMESPACE_VERSION } // namespace __gnu_cxx namespace std { #if !_GLIBCXX_USE_C99_LONG_LONG_DYNAMIC using ::__gnu_cxx::lldiv_t; #endif using ::__gnu_cxx::_Exit; #if !_GLIBCXX_USE_C99_LONG_LONG_DYNAMIC using ::__gnu_cxx::llabs; using ::__gnu_cxx::div; using ::__gnu_cxx::lldiv; #endif using ::__gnu_cxx::atoll; using ::__gnu_cxx::strtof; using ::__gnu_cxx::strtoll; using ::__gnu_cxx::strtoull; using ::__gnu_cxx::strtold; } // namespace std #endif // _GLIBCXX_USE_C99_STDLIB } // extern "C++" #endif // !_GLIBCXX_HOSTED #endif PK!3 3 8/cstringnu[// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file cstring * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c string.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 20.4.6 C library // #pragma GCC system_header #include #include #ifndef _GLIBCXX_CSTRING #define _GLIBCXX_CSTRING 1 // Get rid of those macros defined in in lieu of real functions. #undef memchr #undef memcmp #undef memcpy #undef memmove #undef memset #undef strcat #undef strchr #undef strcmp #undef strcoll #undef strcpy #undef strcspn #undef strerror #undef strlen #undef strncat #undef strncmp #undef strncpy #undef strpbrk #undef strrchr #undef strspn #undef strstr #undef strtok #undef strxfrm namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using ::memchr; using ::memcmp; using ::memcpy; using ::memmove; using ::memset; using ::strcat; using ::strcmp; using ::strcoll; using ::strcpy; using ::strcspn; using ::strerror; using ::strlen; using ::strncat; using ::strncmp; using ::strncpy; using ::strspn; using ::strtok; using ::strxfrm; using ::strchr; using ::strpbrk; using ::strrchr; using ::strstr; #ifndef __CORRECT_ISO_CPP_STRING_H_PROTO inline void* memchr(void* __s, int __c, size_t __n) { return __builtin_memchr(__s, __c, __n); } inline char* strchr(char* __s, int __n) { return __builtin_strchr(__s, __n); } inline char* strpbrk(char* __s1, const char* __s2) { return __builtin_strpbrk(__s1, __s2); } inline char* strrchr(char* __s, int __n) { return __builtin_strrchr(__s, __n); } inline char* strstr(char* __s1, const char* __s2) { return __builtin_strstr(__s1, __s2); } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!uPP 8/ctgmathnu[// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/ctgmath * This is a Standard C++ Library header. */ #pragma GCC system_header #ifndef _GLIBCXX_CTGMATH #define _GLIBCXX_CTGMATH 1 #if __cplusplus < 201103L # include #else # include extern "C++" { # include } #endif #endif PK!(BOMM8/ctimenu[// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/ctime * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c time.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 20.5 Date and time // #pragma GCC system_header #include #include #ifndef _GLIBCXX_CTIME #define _GLIBCXX_CTIME 1 // Get rid of those macros defined in in lieu of real functions. #undef clock #undef difftime #undef mktime #undef time #undef asctime #undef ctime #undef gmtime #undef localtime #undef strftime namespace std { using ::clock_t; using ::time_t; using ::tm; using ::clock; using ::difftime; using ::mktime; using ::time; using ::asctime; using ::ctime; using ::gmtime; using ::localtime; using ::strftime; } // namespace #endif PK!8/cucharnu[// -*- C++ -*- forwarding header. // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/cuchar * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c uchar.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882:2011 21.8 // #ifndef _GLIBCXX_CUCHAR #define _GLIBCXX_CUCHAR 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #if _GLIBCXX_USE_C11_UCHAR_CXX11 #include // Get rid of those macros defined in in lieu of real functions. #undef mbrtoc16 #undef c16rtomb #undef mbrtoc32 #undef c32rtomb namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using ::mbrtoc16; using ::c16rtomb; using ::mbrtoc32; using ::c32rtomb; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _GLIBCXX_USE_C11_UCHAR_CXX11 #endif // C++11 #endif // _GLIBCXX_CUCHAR PK!3mm8/cwcharnu[// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/cwchar * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c wchar.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 21.4 // #pragma GCC system_header #include #if _GLIBCXX_HAVE_WCHAR_H #include #endif #ifndef _GLIBCXX_CWCHAR #define _GLIBCXX_CWCHAR 1 // Need to do a bit of trickery here with mbstate_t as char_traits // assumes it is in wchar.h, regardless of wchar_t specializations. #ifndef _GLIBCXX_HAVE_MBSTATE_T extern "C" { typedef struct { int __fill[6]; } mbstate_t; } #endif namespace std { using ::mbstate_t; } // namespace std // Get rid of those macros defined in in lieu of real functions. #undef btowc #undef fgetwc #undef fgetws #undef fputwc #undef fputws #undef fwide #undef fwprintf #undef fwscanf #undef getwc #undef getwchar #undef mbrlen #undef mbrtowc #undef mbsinit #undef mbsrtowcs #undef putwc #undef putwchar #undef swprintf #undef swscanf #undef ungetwc #undef vfwprintf #if _GLIBCXX_HAVE_VFWSCANF # undef vfwscanf #endif #undef vswprintf #if _GLIBCXX_HAVE_VSWSCANF # undef vswscanf #endif #undef vwprintf #if _GLIBCXX_HAVE_VWSCANF # undef vwscanf #endif #undef wcrtomb #undef wcscat #undef wcschr #undef wcscmp #undef wcscoll #undef wcscpy #undef wcscspn #undef wcsftime #undef wcslen #undef wcsncat #undef wcsncmp #undef wcsncpy #undef wcspbrk #undef wcsrchr #undef wcsrtombs #undef wcsspn #undef wcsstr #undef wcstod #if _GLIBCXX_HAVE_WCSTOF # undef wcstof #endif #undef wcstok #undef wcstol #undef wcstoul #undef wcsxfrm #undef wctob #undef wmemchr #undef wmemcmp #undef wmemcpy #undef wmemmove #undef wmemset #undef wprintf #undef wscanf #if _GLIBCXX_USE_WCHAR_T namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using ::wint_t; using ::btowc; using ::fgetwc; using ::fgetws; using ::fputwc; using ::fputws; using ::fwide; using ::fwprintf; using ::fwscanf; using ::getwc; using ::getwchar; using ::mbrlen; using ::mbrtowc; using ::mbsinit; using ::mbsrtowcs; using ::putwc; using ::putwchar; #ifndef _GLIBCXX_HAVE_BROKEN_VSWPRINTF using ::swprintf; #endif using ::swscanf; using ::ungetwc; using ::vfwprintf; #if _GLIBCXX_HAVE_VFWSCANF using ::vfwscanf; #endif #ifndef _GLIBCXX_HAVE_BROKEN_VSWPRINTF using ::vswprintf; #endif #if _GLIBCXX_HAVE_VSWSCANF using ::vswscanf; #endif using ::vwprintf; #if _GLIBCXX_HAVE_VWSCANF using ::vwscanf; #endif using ::wcrtomb; using ::wcscat; using ::wcscmp; using ::wcscoll; using ::wcscpy; using ::wcscspn; using ::wcsftime; using ::wcslen; using ::wcsncat; using ::wcsncmp; using ::wcsncpy; using ::wcsrtombs; using ::wcsspn; using ::wcstod; #if _GLIBCXX_HAVE_WCSTOF using ::wcstof; #endif using ::wcstok; using ::wcstol; using ::wcstoul; using ::wcsxfrm; using ::wctob; using ::wmemcmp; using ::wmemcpy; using ::wmemmove; using ::wmemset; using ::wprintf; using ::wscanf; using ::wcschr; using ::wcspbrk; using ::wcsrchr; using ::wcsstr; using ::wmemchr; #ifndef __CORRECT_ISO_CPP_WCHAR_H_PROTO inline wchar_t* wcschr(wchar_t* __p, wchar_t __c) { return wcschr(const_cast(__p), __c); } inline wchar_t* wcspbrk(wchar_t* __s1, const wchar_t* __s2) { return wcspbrk(const_cast(__s1), __s2); } inline wchar_t* wcsrchr(wchar_t* __p, wchar_t __c) { return wcsrchr(const_cast(__p), __c); } inline wchar_t* wcsstr(wchar_t* __s1, const wchar_t* __s2) { return wcsstr(const_cast(__s1), __s2); } inline wchar_t* wmemchr(wchar_t* __p, wchar_t __c, size_t __n) { return wmemchr(const_cast(__p), __c, __n); } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #if _GLIBCXX_USE_C99_WCHAR #undef wcstold #undef wcstoll #undef wcstoull namespace __gnu_cxx { #if _GLIBCXX_USE_C99_CHECK || _GLIBCXX_USE_C99_DYNAMIC extern "C" long double (wcstold)(const wchar_t * __restrict, wchar_t ** __restrict) throw (); #endif #if !_GLIBCXX_USE_C99_DYNAMIC using ::wcstold; #endif #if _GLIBCXX_USE_C99_LONG_LONG_CHECK || _GLIBCXX_USE_C99_LONG_LONG_DYNAMIC extern "C" long long int (wcstoll)(const wchar_t * __restrict, wchar_t ** __restrict, int) throw (); extern "C" unsigned long long int (wcstoull)(const wchar_t * __restrict, wchar_t ** __restrict, int) throw (); #endif #if !_GLIBCXX_USE_C99_LONG_LONG_DYNAMIC using ::wcstoll; using ::wcstoull; #endif } // namespace __gnu_cxx namespace std { using ::__gnu_cxx::wcstold; using ::__gnu_cxx::wcstoll; using ::__gnu_cxx::wcstoull; } // namespace #endif #endif //_GLIBCXX_USE_WCHAR_T #if __cplusplus >= 201103L #ifdef _GLIBCXX_USE_WCHAR_T namespace std { #if _GLIBCXX_HAVE_WCSTOF using std::wcstof; #endif #if _GLIBCXX_HAVE_VFWSCANF using std::vfwscanf; #endif #if _GLIBCXX_HAVE_VSWSCANF using std::vswscanf; #endif #if _GLIBCXX_HAVE_VWSCANF using std::vwscanf; #endif #if _GLIBCXX_USE_C99_WCHAR using std::wcstold; using std::wcstoll; using std::wcstoull; #endif } // namespace #endif // _GLIBCXX_USE_WCHAR_T #endif // C++11 #endif PK!2)/H 8/cwctypenu[// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/cwctype * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c wctype.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: // #pragma GCC system_header #include #if _GLIBCXX_HAVE_WCTYPE_H #if __GLIBC__ == 2 && __GLIBC_MINOR__ < 10 // Work around glibc BZ 9694 #include #endif #include #endif // _GLIBCXX_HAVE_WCTYPE_H #ifndef _GLIBCXX_CWCTYPE #define _GLIBCXX_CWCTYPE 1 // Get rid of those macros defined in in lieu of real functions. #undef iswalnum #undef iswalpha #if _GLIBCXX_HAVE_ISWBLANK # undef iswblank #endif #undef iswcntrl #undef iswctype #undef iswdigit #undef iswgraph #undef iswlower #undef iswprint #undef iswpunct #undef iswspace #undef iswupper #undef iswxdigit #undef towctrans #undef towlower #undef towupper #undef wctrans #undef wctype #if _GLIBCXX_USE_WCHAR_T namespace std { using ::wctrans_t; using ::wctype_t; using ::wint_t; using ::iswalnum; using ::iswalpha; #if _GLIBCXX_HAVE_ISWBLANK using ::iswblank; #endif using ::iswcntrl; using ::iswctype; using ::iswdigit; using ::iswgraph; using ::iswlower; using ::iswprint; using ::iswpunct; using ::iswspace; using ::iswupper; using ::iswxdigit; using ::towctrans; using ::towlower; using ::towupper; using ::wctrans; using ::wctype; } // namespace #endif //_GLIBCXX_USE_WCHAR_T #endif // _GLIBCXX_CWCTYPE PK!UU 8/cxxabi.hnu[// ABI Support -*- C++ -*- // Copyright (C) 2000-2018 Free Software Foundation, Inc. // // This file is part of GCC. // // GCC is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3, or (at your option) // any later version. // // GCC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Written by Nathan Sidwell, Codesourcery LLC, /* This file declares the new abi entry points into the runtime. It is not normally necessary for user programs to include this header, or use the entry points directly. However, this header is available should that be needed. Some of the entry points are intended for both C and C++, thus this header is includable from both C and C++. Though the C++ specific parts are not available in C, naturally enough. */ /** @file cxxabi.h * The header provides an interface to the C++ ABI. */ #ifndef _CXXABI_H #define _CXXABI_H 1 #pragma GCC system_header #pragma GCC visibility push(default) #include #include #include #include #include #ifdef __cplusplus namespace __cxxabiv1 { extern "C" { #endif typedef __cxa_cdtor_return_type (*__cxa_cdtor_type)(void *); // Allocate array. void* __cxa_vec_new(size_t __element_count, size_t __element_size, size_t __padding_size, __cxa_cdtor_type __constructor, __cxa_cdtor_type __destructor); void* __cxa_vec_new2(size_t __element_count, size_t __element_size, size_t __padding_size, __cxa_cdtor_type __constructor, __cxa_cdtor_type __destructor, void *(*__alloc) (size_t), void (*__dealloc) (void*)); void* __cxa_vec_new3(size_t __element_count, size_t __element_size, size_t __padding_size, __cxa_cdtor_type __constructor, __cxa_cdtor_type __destructor, void *(*__alloc) (size_t), void (*__dealloc) (void*, size_t)); // Construct array. __cxa_vec_ctor_return_type __cxa_vec_ctor(void* __array_address, size_t __element_count, size_t __element_size, __cxa_cdtor_type __constructor, __cxa_cdtor_type __destructor); __cxa_vec_ctor_return_type __cxa_vec_cctor(void* __dest_array, void* __src_array, size_t __element_count, size_t __element_size, __cxa_cdtor_return_type (*__constructor) (void*, void*), __cxa_cdtor_type __destructor); // Destruct array. void __cxa_vec_dtor(void* __array_address, size_t __element_count, size_t __element_size, __cxa_cdtor_type __destructor); void __cxa_vec_cleanup(void* __array_address, size_t __element_count, size_t __s, __cxa_cdtor_type __destructor) _GLIBCXX_NOTHROW; // Destruct and release array. void __cxa_vec_delete(void* __array_address, size_t __element_size, size_t __padding_size, __cxa_cdtor_type __destructor); void __cxa_vec_delete2(void* __array_address, size_t __element_size, size_t __padding_size, __cxa_cdtor_type __destructor, void (*__dealloc) (void*)); void __cxa_vec_delete3(void* __array_address, size_t __element_size, size_t __padding_size, __cxa_cdtor_type __destructor, void (*__dealloc) (void*, size_t)); int __cxa_guard_acquire(__guard*); void __cxa_guard_release(__guard*) _GLIBCXX_NOTHROW; void __cxa_guard_abort(__guard*) _GLIBCXX_NOTHROW; // DSO destruction. int __cxa_atexit(void (*)(void*), void*, void*) _GLIBCXX_NOTHROW; int __cxa_finalize(void*); // TLS destruction. int __cxa_thread_atexit(void (*)(void*), void*, void *) _GLIBCXX_NOTHROW; // Pure virtual functions. void __cxa_pure_virtual(void) __attribute__ ((__noreturn__)); void __cxa_deleted_virtual(void) __attribute__ ((__noreturn__)); // Exception handling auxiliary. void __cxa_bad_cast() __attribute__((__noreturn__)); void __cxa_bad_typeid() __attribute__((__noreturn__)); void __cxa_throw_bad_array_new_length() __attribute__((__noreturn__)); /** * @brief Demangling routine. * ABI-mandated entry point in the C++ runtime library for demangling. * * @param __mangled_name A NUL-terminated character string * containing the name to be demangled. * * @param __output_buffer A region of memory, allocated with * malloc, of @a *__length bytes, into which the demangled name is * stored. If @a __output_buffer is not long enough, it is * expanded using realloc. @a __output_buffer may instead be NULL; * in that case, the demangled name is placed in a region of memory * allocated with malloc. * * @param __length If @a __length is non-NULL, the length of the * buffer containing the demangled name is placed in @a *__length. * * @param __status @a *__status is set to one of the following values: * 0: The demangling operation succeeded. * -1: A memory allocation failure occurred. * -2: @a mangled_name is not a valid name under the C++ ABI mangling rules. * -3: One of the arguments is invalid. * * @return A pointer to the start of the NUL-terminated demangled * name, or NULL if the demangling fails. The caller is * responsible for deallocating this memory using @c free. * * The demangling is performed using the C++ ABI mangling rules, * with GNU extensions. For example, this function is used in * __gnu_cxx::__verbose_terminate_handler. * * See https://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html * for other examples of use. * * @note The same demangling functionality is available via * libiberty (@c and @c libiberty.a) in GCC * 3.1 and later, but that requires explicit installation (@c * --enable-install-libiberty) and uses a different API, although * the ABI is unchanged. */ char* __cxa_demangle(const char* __mangled_name, char* __output_buffer, size_t* __length, int* __status); #ifdef __cplusplus } } // namespace __cxxabiv1 #endif #ifdef __cplusplus #include namespace __cxxabiv1 { // Type information for int, float etc. class __fundamental_type_info : public std::type_info { public: explicit __fundamental_type_info(const char* __n) : std::type_info(__n) { } virtual ~__fundamental_type_info(); }; // Type information for array objects. class __array_type_info : public std::type_info { public: explicit __array_type_info(const char* __n) : std::type_info(__n) { } virtual ~__array_type_info(); }; // Type information for functions (both member and non-member). class __function_type_info : public std::type_info { public: explicit __function_type_info(const char* __n) : std::type_info(__n) { } virtual ~__function_type_info(); protected: // Implementation defined member function. virtual bool __is_function_p() const; }; // Type information for enumerations. class __enum_type_info : public std::type_info { public: explicit __enum_type_info(const char* __n) : std::type_info(__n) { } virtual ~__enum_type_info(); }; // Common type information for simple pointers and pointers to member. class __pbase_type_info : public std::type_info { public: unsigned int __flags; // Qualification of the target object. const std::type_info* __pointee; // Type of pointed to object. explicit __pbase_type_info(const char* __n, int __quals, const std::type_info* __type) : std::type_info(__n), __flags(__quals), __pointee(__type) { } virtual ~__pbase_type_info(); // Implementation defined type. enum __masks { __const_mask = 0x1, __volatile_mask = 0x2, __restrict_mask = 0x4, __incomplete_mask = 0x8, __incomplete_class_mask = 0x10, __transaction_safe_mask = 0x20, __noexcept_mask = 0x40 }; protected: __pbase_type_info(const __pbase_type_info&); __pbase_type_info& operator=(const __pbase_type_info&); // Implementation defined member functions. virtual bool __do_catch(const std::type_info* __thr_type, void** __thr_obj, unsigned int __outer) const; inline virtual bool __pointer_catch(const __pbase_type_info* __thr_type, void** __thr_obj, unsigned __outer) const; }; inline bool __pbase_type_info:: __pointer_catch (const __pbase_type_info *thrown_type, void **thr_obj, unsigned outer) const { return __pointee->__do_catch (thrown_type->__pointee, thr_obj, outer + 2); } // Type information for simple pointers. class __pointer_type_info : public __pbase_type_info { public: explicit __pointer_type_info(const char* __n, int __quals, const std::type_info* __type) : __pbase_type_info (__n, __quals, __type) { } virtual ~__pointer_type_info(); protected: // Implementation defined member functions. virtual bool __is_pointer_p() const; virtual bool __pointer_catch(const __pbase_type_info* __thr_type, void** __thr_obj, unsigned __outer) const; }; class __class_type_info; // Type information for a pointer to member variable. class __pointer_to_member_type_info : public __pbase_type_info { public: __class_type_info* __context; // Class of the member. explicit __pointer_to_member_type_info(const char* __n, int __quals, const std::type_info* __type, __class_type_info* __klass) : __pbase_type_info(__n, __quals, __type), __context(__klass) { } virtual ~__pointer_to_member_type_info(); protected: __pointer_to_member_type_info(const __pointer_to_member_type_info&); __pointer_to_member_type_info& operator=(const __pointer_to_member_type_info&); // Implementation defined member function. virtual bool __pointer_catch(const __pbase_type_info* __thr_type, void** __thr_obj, unsigned __outer) const; }; // Helper class for __vmi_class_type. class __base_class_type_info { public: const __class_type_info* __base_type; // Base class type. #ifdef _GLIBCXX_LLP64 long long __offset_flags; // Offset and info. #else long __offset_flags; // Offset and info. #endif enum __offset_flags_masks { __virtual_mask = 0x1, __public_mask = 0x2, __hwm_bit = 2, __offset_shift = 8 // Bits to shift offset. }; // Implementation defined member functions. bool __is_virtual_p() const { return __offset_flags & __virtual_mask; } bool __is_public_p() const { return __offset_flags & __public_mask; } ptrdiff_t __offset() const { // This shift, being of a signed type, is implementation // defined. GCC implements such shifts as arithmetic, which is // what we want. return static_cast(__offset_flags) >> __offset_shift; } }; // Type information for a class. class __class_type_info : public std::type_info { public: explicit __class_type_info (const char *__n) : type_info(__n) { } virtual ~__class_type_info (); // Implementation defined types. // The type sub_kind tells us about how a base object is contained // within a derived object. We often do this lazily, hence the // UNKNOWN value. At other times we may use NOT_CONTAINED to mean // not publicly contained. enum __sub_kind { // We have no idea. __unknown = 0, // Not contained within us (in some circumstances this might // mean not contained publicly) __not_contained, // Contained ambiguously. __contained_ambig, // Via a virtual path. __contained_virtual_mask = __base_class_type_info::__virtual_mask, // Via a public path. __contained_public_mask = __base_class_type_info::__public_mask, // Contained within us. __contained_mask = 1 << __base_class_type_info::__hwm_bit, __contained_private = __contained_mask, __contained_public = __contained_mask | __contained_public_mask }; struct __upcast_result; struct __dyncast_result; protected: // Implementation defined member functions. virtual bool __do_upcast(const __class_type_info* __dst_type, void**__obj_ptr) const; virtual bool __do_catch(const type_info* __thr_type, void** __thr_obj, unsigned __outer) const; public: // Helper for upcast. See if DST is us, or one of our bases. // Return false if not found, true if found. virtual bool __do_upcast(const __class_type_info* __dst, const void* __obj, __upcast_result& __restrict __result) const; // Indicate whether SRC_PTR of type SRC_TYPE is contained publicly // within OBJ_PTR. OBJ_PTR points to a base object of our type, // which is the destination type. SRC2DST indicates how SRC // objects might be contained within this type. If SRC_PTR is one // of our SRC_TYPE bases, indicate the virtuality. Returns // not_contained for non containment or private containment. inline __sub_kind __find_public_src(ptrdiff_t __src2dst, const void* __obj_ptr, const __class_type_info* __src_type, const void* __src_ptr) const; // Helper for dynamic cast. ACCESS_PATH gives the access from the // most derived object to this base. DST_TYPE indicates the // desired type we want. OBJ_PTR points to a base of our type // within the complete object. SRC_TYPE indicates the static type // started from and SRC_PTR points to that base within the most // derived object. Fill in RESULT with what we find. Return true // if we have located an ambiguous match. virtual bool __do_dyncast(ptrdiff_t __src2dst, __sub_kind __access_path, const __class_type_info* __dst_type, const void* __obj_ptr, const __class_type_info* __src_type, const void* __src_ptr, __dyncast_result& __result) const; // Helper for find_public_subobj. SRC2DST indicates how SRC_TYPE // bases are inherited by the type started from -- which is not // necessarily the current type. The current type will be a base // of the destination type. OBJ_PTR points to the current base. virtual __sub_kind __do_find_public_src(ptrdiff_t __src2dst, const void* __obj_ptr, const __class_type_info* __src_type, const void* __src_ptr) const; }; // Type information for a class with a single non-virtual base. class __si_class_type_info : public __class_type_info { public: const __class_type_info* __base_type; explicit __si_class_type_info(const char *__n, const __class_type_info *__base) : __class_type_info(__n), __base_type(__base) { } virtual ~__si_class_type_info(); protected: __si_class_type_info(const __si_class_type_info&); __si_class_type_info& operator=(const __si_class_type_info&); // Implementation defined member functions. virtual bool __do_dyncast(ptrdiff_t __src2dst, __sub_kind __access_path, const __class_type_info* __dst_type, const void* __obj_ptr, const __class_type_info* __src_type, const void* __src_ptr, __dyncast_result& __result) const; virtual __sub_kind __do_find_public_src(ptrdiff_t __src2dst, const void* __obj_ptr, const __class_type_info* __src_type, const void* __sub_ptr) const; virtual bool __do_upcast(const __class_type_info*__dst, const void*__obj, __upcast_result& __restrict __result) const; }; // Type information for a class with multiple and/or virtual bases. class __vmi_class_type_info : public __class_type_info { public: unsigned int __flags; // Details about the class hierarchy. unsigned int __base_count; // Number of direct bases. // The array of bases uses the trailing array struct hack so this // class is not constructable with a normal constructor. It is // internally generated by the compiler. __base_class_type_info __base_info[1]; // Array of bases. explicit __vmi_class_type_info(const char* __n, int ___flags) : __class_type_info(__n), __flags(___flags), __base_count(0) { } virtual ~__vmi_class_type_info(); // Implementation defined types. enum __flags_masks { __non_diamond_repeat_mask = 0x1, // Distinct instance of repeated base. __diamond_shaped_mask = 0x2, // Diamond shaped multiple inheritance. __flags_unknown_mask = 0x10 }; protected: // Implementation defined member functions. virtual bool __do_dyncast(ptrdiff_t __src2dst, __sub_kind __access_path, const __class_type_info* __dst_type, const void* __obj_ptr, const __class_type_info* __src_type, const void* __src_ptr, __dyncast_result& __result) const; virtual __sub_kind __do_find_public_src(ptrdiff_t __src2dst, const void* __obj_ptr, const __class_type_info* __src_type, const void* __src_ptr) const; virtual bool __do_upcast(const __class_type_info* __dst, const void* __obj, __upcast_result& __restrict __result) const; }; // Exception handling forward declarations. struct __cxa_exception; struct __cxa_refcounted_exception; struct __cxa_dependent_exception; struct __cxa_eh_globals; extern "C" { // Dynamic cast runtime. // src2dst has the following possible values // >-1: src_type is a unique public non-virtual base of dst_type // dst_ptr + src2dst == src_ptr // -1: unspecified relationship // -2: src_type is not a public base of dst_type // -3: src_type is a multiple public non-virtual base of dst_type void* __dynamic_cast(const void* __src_ptr, // Starting object. const __class_type_info* __src_type, // Static type of object. const __class_type_info* __dst_type, // Desired target type. ptrdiff_t __src2dst); // How src and dst are related. // Exception handling runtime. // The __cxa_eh_globals for the current thread can be obtained by using // either of the following functions. The "fast" version assumes at least // one prior call of __cxa_get_globals has been made from the current // thread, so no initialization is necessary. __cxa_eh_globals* __cxa_get_globals() _GLIBCXX_NOTHROW __attribute__ ((__const__)); __cxa_eh_globals* __cxa_get_globals_fast() _GLIBCXX_NOTHROW __attribute__ ((__const__)); // Free the space allocated for the primary exception. void __cxa_free_exception(void*) _GLIBCXX_NOTHROW; // Throw the exception. void __cxa_throw(void*, std::type_info*, void (_GLIBCXX_CDTOR_CALLABI *) (void *)) __attribute__((__noreturn__)); // Used to implement exception handlers. void* __cxa_get_exception_ptr(void*) _GLIBCXX_NOTHROW __attribute__ ((__pure__)); void* __cxa_begin_catch(void*) _GLIBCXX_NOTHROW; void __cxa_end_catch(); void __cxa_rethrow() __attribute__((__noreturn__)); // Returns the type_info for the currently handled exception [15.3/8], or // null if there is none. std::type_info* __cxa_current_exception_type() _GLIBCXX_NOTHROW __attribute__ ((__pure__)); // GNU Extensions. // Allocate memory for a dependent exception. __cxa_dependent_exception* __cxa_allocate_dependent_exception() _GLIBCXX_NOTHROW; // Free the space allocated for the dependent exception. void __cxa_free_dependent_exception(__cxa_dependent_exception*) _GLIBCXX_NOTHROW; } // extern "C" // A magic placeholder class that can be caught by reference // to recognize foreign exceptions. class __foreign_exception { virtual ~__foreign_exception() throw(); virtual void __pure_dummy() = 0; // prevent catch by value }; } // namespace __cxxabiv1 /** @namespace abi * @brief The cross-vendor C++ Application Binary Interface. A * namespace alias to __cxxabiv1, but user programs should use the * alias 'abi'. * * A brief overview of an ABI is given in the libstdc++ FAQ, question * 5.8 (you may have a copy of the FAQ locally, or you can view the online * version at http://gcc.gnu.org/onlinedocs/libstdc++/faq.html#5_8 ). * * GCC subscribes to a cross-vendor ABI for C++, sometimes * called the IA64 ABI because it happens to be the native ABI for that * platform. It is summarized at http://www.codesourcery.com/cxx-abi/ * along with the current specification. * * For users of GCC greater than or equal to 3.x, entry points are * available in , which notes, 'It is not normally * necessary for user programs to include this header, or use the * entry points directly. However, this header is available should * that be needed.' */ namespace abi = __cxxabiv1; namespace __gnu_cxx { /** * @brief Exception thrown by __cxa_guard_acquire. * @ingroup exceptions * * C++ 2011 6.7 [stmt.dcl]/4: If control re-enters the declaration * recursively while the variable is being initialized, the behavior * is undefined. * * Since we already have a library function to handle locking, we might * as well check for this situation and throw an exception. * We use the second byte of the guard variable to remember that we're * in the middle of an initialization. */ class recursive_init_error: public std::exception { public: recursive_init_error() _GLIBCXX_NOTHROW; virtual ~recursive_init_error() _GLIBCXX_NOTHROW; }; } #endif // __cplusplus #pragma GCC visibility pop #endif // __CXXABI_H PK!ui i 8/dequenu[// -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file include/deque * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_DEQUE #define _GLIBCXX_DEQUE 1 #pragma GCC system_header #include #include #include #include #include #include #include #ifdef _GLIBCXX_DEBUG # include #endif #ifdef _GLIBCXX_PROFILE # include #endif #endif /* _GLIBCXX_DEQUE */ PK!ؚ 8/exceptionnu[// Exception Handling support header for -*- C++ -*- // Copyright (C) 1995-2018 Free Software Foundation, Inc. // // This file is part of GCC. // // GCC is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3, or (at your option) // any later version. // // GCC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file exception * This is a Standard C++ Library header. */ #ifndef __EXCEPTION__ #define __EXCEPTION__ #pragma GCC system_header #pragma GCC visibility push(default) #include #include extern "C++" { namespace std { /** If an %exception is thrown which is not listed in a function's * %exception specification, one of these may be thrown. */ class bad_exception : public exception { public: bad_exception() _GLIBCXX_USE_NOEXCEPT { } // This declaration is not useless: // http://gcc.gnu.org/onlinedocs/gcc-3.0.2/gcc_6.html#SEC118 virtual ~bad_exception() _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT; // See comment in eh_exception.cc. virtual const char* what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT; }; /// If you write a replacement %terminate handler, it must be of this type. typedef void (*terminate_handler) (); /// If you write a replacement %unexpected handler, it must be of this type. typedef void (*unexpected_handler) (); /// Takes a new handler function as an argument, returns the old function. terminate_handler set_terminate(terminate_handler) _GLIBCXX_USE_NOEXCEPT; #if __cplusplus >= 201103L /// Return the current terminate handler. terminate_handler get_terminate() noexcept; #endif /** The runtime will call this function if %exception handling must be * abandoned for any reason. It can also be called by the user. */ void terminate() _GLIBCXX_USE_NOEXCEPT __attribute__ ((__noreturn__)); /// Takes a new handler function as an argument, returns the old function. unexpected_handler set_unexpected(unexpected_handler) _GLIBCXX_USE_NOEXCEPT; #if __cplusplus >= 201103L /// Return the current unexpected handler. unexpected_handler get_unexpected() noexcept; #endif /** The runtime will call this function if an %exception is thrown which * violates the function's %exception specification. */ void unexpected() __attribute__ ((__noreturn__)); /** [18.6.4]/1: 'Returns true after completing evaluation of a * throw-expression until either completing initialization of the * exception-declaration in the matching handler or entering @c unexpected() * due to the throw; or after entering @c terminate() for any reason * other than an explicit call to @c terminate(). [Note: This includes * stack unwinding [15.2]. end note]' * * 2: 'When @c uncaught_exception() is true, throwing an * %exception can result in a call of @c terminate() * (15.5.1).' */ _GLIBCXX17_DEPRECATED bool uncaught_exception() _GLIBCXX_USE_NOEXCEPT __attribute__ ((__pure__)); #if __cplusplus >= 201703L || !defined(__STRICT_ANSI__) // c++17 or gnu++98 #define __cpp_lib_uncaught_exceptions 201411L /// The number of uncaught exceptions. int uncaught_exceptions() _GLIBCXX_USE_NOEXCEPT __attribute__ ((__pure__)); #endif // @} group exceptions } // namespace std namespace __gnu_cxx { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief A replacement for the standard terminate_handler which * prints more information about the terminating exception (if any) * on stderr. * * @ingroup exceptions * * Call * @code * std::set_terminate(__gnu_cxx::__verbose_terminate_handler) * @endcode * to use. For more info, see * http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt02ch06s02.html * * In 3.4 and later, this is on by default. */ void __verbose_terminate_handler(); _GLIBCXX_END_NAMESPACE_VERSION } // namespace } // extern "C++" #pragma GCC visibility pop #if (__cplusplus >= 201103L) #include #include #endif #endif PK!=y8/fenv.hnu[// -*- C++ -*- compatibility header. // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file fenv.h * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_FENV_H #define _GLIBCXX_FENV_H 1 #pragma GCC system_header #include #if _GLIBCXX_HAVE_FENV_H # include_next #endif #if __cplusplus >= 201103L #if _GLIBCXX_USE_C99_FENV_TR1 #undef feclearexcept #undef fegetexceptflag #undef feraiseexcept #undef fesetexceptflag #undef fetestexcept #undef fegetround #undef fesetround #undef fegetenv #undef feholdexcept #undef fesetenv #undef feupdateenv namespace std { // types using ::fenv_t; using ::fexcept_t; // functions using ::feclearexcept; using ::fegetexceptflag; using ::feraiseexcept; using ::fesetexceptflag; using ::fetestexcept; using ::fegetround; using ::fesetround; using ::fegetenv; using ::feholdexcept; using ::fesetenv; using ::feupdateenv; } // namespace #endif // _GLIBCXX_USE_C99_FENV_TR1 #endif // C++11 #endif // _GLIBCXX_FENV_H PK! 8/filesystemnu[// -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file filesystem * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_FILESYSTEM #define _GLIBCXX_FILESYSTEM 1 #pragma GCC system_header #if __cplusplus >= 201703L #include #include #include #include #define __cpp_lib_filesystem 201703 #endif // C++17 #endif // _GLIBCXX_FILESYSTEM PK!C [))8/forward_listnu[// -*- C++ -*- // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/forward_list * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_FORWARD_LIST #define _GLIBCXX_FORWARD_LIST 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #include #ifdef _GLIBCXX_DEBUG # include #endif #ifdef _GLIBCXX_PROFILE # include #endif #endif // C++11 #endif // _GLIBCXX_FORWARD_LIST PK!&г 8/fstreamnu[// File based streams -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/fstream * This is a Standard C++ Library header. */ // // ISO C++ 14882: 27.8 File-based streams // #ifndef _GLIBCXX_FSTREAM #define _GLIBCXX_FSTREAM 1 #pragma GCC system_header #include #include #include #include // For BUFSIZ #include // For __basic_file, __c_lock #if __cplusplus >= 201103L #include // For std::string overloads. #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if __cplusplus >= 201703L // Enable if _Path is a filesystem::path or experimental::filesystem::path template().make_preferred().filename())> using _If_fs_path = enable_if_t, _Result>; #endif // C++17 // [27.8.1.1] template class basic_filebuf /** * @brief The actual work of input and output (for files). * @ingroup io * * @tparam _CharT Type of character stream. * @tparam _Traits Traits for character type, defaults to * char_traits<_CharT>. * * This class associates both its input and output sequence with an * external disk file, and maintains a joint file position for both * sequences. Many of its semantics are described in terms of similar * behavior in the Standard C Library's @c FILE streams. * * Requirements on traits_type, specific to this class: * - traits_type::pos_type must be fpos * - traits_type::off_type must be streamoff * - traits_type::state_type must be Assignable and DefaultConstructible, * - traits_type::state_type() must be the initial state for codecvt. */ template class basic_filebuf : public basic_streambuf<_CharT, _Traits> { #if __cplusplus >= 201103L template using __chk_state = __and_, is_copy_constructible<_Tp>, is_default_constructible<_Tp>>; static_assert(__chk_state::value, "state_type must be CopyAssignable, CopyConstructible" " and DefaultConstructible"); static_assert(is_same>::value, "pos_type must be fpos"); #endif public: // Types: typedef _CharT char_type; typedef _Traits traits_type; typedef typename traits_type::int_type int_type; typedef typename traits_type::pos_type pos_type; typedef typename traits_type::off_type off_type; typedef basic_streambuf __streambuf_type; typedef basic_filebuf __filebuf_type; typedef __basic_file __file_type; typedef typename traits_type::state_type __state_type; typedef codecvt __codecvt_type; friend class ios_base; // For sync_with_stdio. protected: // Data Members: // MT lock inherited from libio or other low-level io library. __c_lock _M_lock; // External buffer. __file_type _M_file; /// Place to stash in || out || in | out settings for current filebuf. ios_base::openmode _M_mode; // Beginning state type for codecvt. __state_type _M_state_beg; // During output, the state that corresponds to pptr(), // during input, the state that corresponds to egptr() and // _M_ext_next. __state_type _M_state_cur; // Not used for output. During input, the state that corresponds // to eback() and _M_ext_buf. __state_type _M_state_last; /// Pointer to the beginning of internal buffer. char_type* _M_buf; /** * Actual size of internal buffer. This number is equal to the size * of the put area + 1 position, reserved for the overflow char of * a full area. */ size_t _M_buf_size; // Set iff _M_buf is allocated memory from _M_allocate_internal_buffer. bool _M_buf_allocated; /** * _M_reading == false && _M_writing == false for @b uncommitted mode; * _M_reading == true for @b read mode; * _M_writing == true for @b write mode; * * NB: _M_reading == true && _M_writing == true is unused. */ bool _M_reading; bool _M_writing; //@{ /** * Necessary bits for putback buffer management. * * @note pbacks of over one character are not currently supported. */ char_type _M_pback; char_type* _M_pback_cur_save; char_type* _M_pback_end_save; bool _M_pback_init; //@} // Cached codecvt facet. const __codecvt_type* _M_codecvt; /** * Buffer for external characters. Used for input when * codecvt::always_noconv() == false. When valid, this corresponds * to eback(). */ char* _M_ext_buf; /** * Size of buffer held by _M_ext_buf. */ streamsize _M_ext_buf_size; /** * Pointers into the buffer held by _M_ext_buf that delimit a * subsequence of bytes that have been read but not yet converted. * When valid, _M_ext_next corresponds to egptr(). */ const char* _M_ext_next; char* _M_ext_end; /** * Initializes pback buffers, and moves normal buffers to safety. * Assumptions: * _M_in_cur has already been moved back */ void _M_create_pback() { if (!_M_pback_init) { _M_pback_cur_save = this->gptr(); _M_pback_end_save = this->egptr(); this->setg(&_M_pback, &_M_pback, &_M_pback + 1); _M_pback_init = true; } } /** * Deactivates pback buffer contents, and restores normal buffer. * Assumptions: * The pback buffer has only moved forward. */ void _M_destroy_pback() throw() { if (_M_pback_init) { // Length _M_in_cur moved in the pback buffer. _M_pback_cur_save += this->gptr() != this->eback(); this->setg(_M_buf, _M_pback_cur_save, _M_pback_end_save); _M_pback_init = false; } } public: // Constructors/destructor: /** * @brief Does not open any files. * * The default constructor initializes the parent class using its * own default ctor. */ basic_filebuf(); #if __cplusplus >= 201103L basic_filebuf(const basic_filebuf&) = delete; basic_filebuf(basic_filebuf&&); #endif /** * @brief The destructor closes the file first. */ virtual ~basic_filebuf() { this->close(); } #if __cplusplus >= 201103L basic_filebuf& operator=(const basic_filebuf&) = delete; basic_filebuf& operator=(basic_filebuf&&); void swap(basic_filebuf&); #endif // Members: /** * @brief Returns true if the external file is open. */ bool is_open() const throw() { return _M_file.is_open(); } /** * @brief Opens an external file. * @param __s The name of the file. * @param __mode The open mode flags. * @return @c this on success, NULL on failure * * If a file is already open, this function immediately fails. * Otherwise it tries to open the file named @a __s using the flags * given in @a __mode. * * Table 92, adapted here, gives the relation between openmode * combinations and the equivalent @c fopen() flags. * (NB: lines app, in|out|app, in|app, binary|app, binary|in|out|app, * and binary|in|app per DR 596) *
       *  +---------------------------------------------------------+
       *  | ios_base Flag combination            stdio equivalent   |
       *  |binary  in  out  trunc  app                              |
       *  +---------------------------------------------------------+
       *  |             +                        w                  |
       *  |             +           +            a                  |
       *  |                         +            a                  |
       *  |             +     +                  w                  |
       *  |         +                            r                  |
       *  |         +   +                        r+                 |
       *  |         +   +     +                  w+                 |
       *  |         +   +           +            a+                 |
       *  |         +               +            a+                 |
       *  +---------------------------------------------------------+
       *  |   +         +                        wb                 |
       *  |   +         +           +            ab                 |
       *  |   +                     +            ab                 |
       *  |   +         +     +                  wb                 |
       *  |   +     +                            rb                 |
       *  |   +     +   +                        r+b                |
       *  |   +     +   +     +                  w+b                |
       *  |   +     +   +           +            a+b                |
       *  |   +     +               +            a+b                |
       *  +---------------------------------------------------------+
       *  
*/ __filebuf_type* open(const char* __s, ios_base::openmode __mode); #if __cplusplus >= 201103L /** * @brief Opens an external file. * @param __s The name of the file. * @param __mode The open mode flags. * @return @c this on success, NULL on failure */ __filebuf_type* open(const std::string& __s, ios_base::openmode __mode) { return open(__s.c_str(), __mode); } #if __cplusplus >= 201703L /** * @brief Opens an external file. * @param __s The name of the file, as a filesystem::path. * @param __mode The open mode flags. * @return @c this on success, NULL on failure */ template _If_fs_path<_Path, __filebuf_type*> open(const _Path& __s, ios_base::openmode __mode) { return open(__s.c_str(), __mode); } #endif // C++17 #endif // C++11 /** * @brief Closes the currently associated file. * @return @c this on success, NULL on failure * * If no file is currently open, this function immediately fails. * * If a put buffer area exists, @c overflow(eof) is * called to flush all the characters. The file is then * closed. * * If any operations fail, this function also fails. */ __filebuf_type* close(); protected: void _M_allocate_internal_buffer(); void _M_destroy_internal_buffer() throw(); // [27.8.1.4] overridden virtual functions virtual streamsize showmanyc(); // Stroustrup, 1998, p. 628 // underflow() and uflow() functions are called to get the next // character from the real input source when the buffer is empty. // Buffered input uses underflow() virtual int_type underflow(); virtual int_type pbackfail(int_type __c = _Traits::eof()); // Stroustrup, 1998, p 648 // The overflow() function is called to transfer characters to the // real output destination when the buffer is full. A call to // overflow(c) outputs the contents of the buffer plus the // character c. // 27.5.2.4.5 // Consume some sequence of the characters in the pending sequence. virtual int_type overflow(int_type __c = _Traits::eof()); // Convert internal byte sequence to external, char-based // sequence via codecvt. bool _M_convert_to_external(char_type*, streamsize); /** * @brief Manipulates the buffer. * @param __s Pointer to a buffer area. * @param __n Size of @a __s. * @return @c this * * If no file has been opened, and both @a __s and @a __n are zero, then * the stream becomes unbuffered. Otherwise, @c __s is used as a * buffer; see * https://gcc.gnu.org/onlinedocs/libstdc++/manual/streambufs.html#io.streambuf.buffering * for more. */ virtual __streambuf_type* setbuf(char_type* __s, streamsize __n); virtual pos_type seekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode __mode = ios_base::in | ios_base::out); virtual pos_type seekpos(pos_type __pos, ios_base::openmode __mode = ios_base::in | ios_base::out); // Common code for seekoff, seekpos, and overflow pos_type _M_seek(off_type __off, ios_base::seekdir __way, __state_type __state); int _M_get_ext_pos(__state_type &__state); virtual int sync(); virtual void imbue(const locale& __loc); virtual streamsize xsgetn(char_type* __s, streamsize __n); virtual streamsize xsputn(const char_type* __s, streamsize __n); // Flushes output buffer, then writes unshift sequence. bool _M_terminate_output(); /** * This function sets the pointers of the internal buffer, both get * and put areas. Typically: * * __off == egptr() - eback() upon underflow/uflow (@b read mode); * __off == 0 upon overflow (@b write mode); * __off == -1 upon open, setbuf, seekoff/pos (@b uncommitted mode). * * NB: epptr() - pbase() == _M_buf_size - 1, since _M_buf_size * reflects the actual allocated memory and the last cell is reserved * for the overflow char of a full put area. */ void _M_set_buffer(streamsize __off) { const bool __testin = _M_mode & ios_base::in; const bool __testout = (_M_mode & ios_base::out || _M_mode & ios_base::app); if (__testin && __off > 0) this->setg(_M_buf, _M_buf, _M_buf + __off); else this->setg(_M_buf, _M_buf, _M_buf); if (__testout && __off == 0 && _M_buf_size > 1 ) this->setp(_M_buf, _M_buf + _M_buf_size - 1); else this->setp(0, 0); } }; // [27.8.1.5] Template class basic_ifstream /** * @brief Controlling input for files. * @ingroup io * * @tparam _CharT Type of character stream. * @tparam _Traits Traits for character type, defaults to * char_traits<_CharT>. * * This class supports reading from named files, using the inherited * functions from std::basic_istream. To control the associated * sequence, an instance of std::basic_filebuf is used, which this page * refers to as @c sb. */ template class basic_ifstream : public basic_istream<_CharT, _Traits> { public: // Types: typedef _CharT char_type; typedef _Traits traits_type; typedef typename traits_type::int_type int_type; typedef typename traits_type::pos_type pos_type; typedef typename traits_type::off_type off_type; // Non-standard types: typedef basic_filebuf __filebuf_type; typedef basic_istream __istream_type; private: __filebuf_type _M_filebuf; public: // Constructors/Destructors: /** * @brief Default constructor. * * Initializes @c sb using its default constructor, and passes * @c &sb to the base class initializer. Does not open any files * (you haven't given it a filename to open). */ basic_ifstream() : __istream_type(), _M_filebuf() { this->init(&_M_filebuf); } /** * @brief Create an input file stream. * @param __s Null terminated string specifying the filename. * @param __mode Open file in specified mode (see std::ios_base). * * @c ios_base::in is automatically included in @a __mode. */ explicit basic_ifstream(const char* __s, ios_base::openmode __mode = ios_base::in) : __istream_type(), _M_filebuf() { this->init(&_M_filebuf); this->open(__s, __mode); } #if __cplusplus >= 201103L /** * @brief Create an input file stream. * @param __s std::string specifying the filename. * @param __mode Open file in specified mode (see std::ios_base). * * @c ios_base::in is automatically included in @a __mode. */ explicit basic_ifstream(const std::string& __s, ios_base::openmode __mode = ios_base::in) : __istream_type(), _M_filebuf() { this->init(&_M_filebuf); this->open(__s, __mode); } #if __cplusplus >= 201703L /** * @param Create an input file stream. * @param __s filesystem::path specifying the filename. * @param __mode Open file in specified mode (see std::ios_base). * * @c ios_base::in is automatically included in @a __mode. */ template> basic_ifstream(const _Path& __s, ios_base::openmode __mode = ios_base::in) : basic_ifstream(__s.c_str(), __mode) { } #endif // C++17 basic_ifstream(const basic_ifstream&) = delete; basic_ifstream(basic_ifstream&& __rhs) : __istream_type(std::move(__rhs)), _M_filebuf(std::move(__rhs._M_filebuf)) { __istream_type::set_rdbuf(&_M_filebuf); } #endif // C++11 /** * @brief The destructor does nothing. * * The file is closed by the filebuf object, not the formatting * stream. */ ~basic_ifstream() { } #if __cplusplus >= 201103L // 27.8.3.2 Assign and swap: basic_ifstream& operator=(const basic_ifstream&) = delete; basic_ifstream& operator=(basic_ifstream&& __rhs) { __istream_type::operator=(std::move(__rhs)); _M_filebuf = std::move(__rhs._M_filebuf); return *this; } void swap(basic_ifstream& __rhs) { __istream_type::swap(__rhs); _M_filebuf.swap(__rhs._M_filebuf); } #endif // Members: /** * @brief Accessing the underlying buffer. * @return The current basic_filebuf buffer. * * This hides both signatures of std::basic_ios::rdbuf(). */ __filebuf_type* rdbuf() const { return const_cast<__filebuf_type*>(&_M_filebuf); } /** * @brief Wrapper to test for an open file. * @return @c rdbuf()->is_open() */ bool is_open() { return _M_filebuf.is_open(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 365. Lack of const-qualification in clause 27 bool is_open() const { return _M_filebuf.is_open(); } /** * @brief Opens an external file. * @param __s The name of the file. * @param __mode The open mode flags. * * Calls @c std::basic_filebuf::open(s,__mode|in). If that function * fails, @c failbit is set in the stream's error state. */ void open(const char* __s, ios_base::openmode __mode = ios_base::in) { if (!_M_filebuf.open(__s, __mode | ios_base::in)) this->setstate(ios_base::failbit); else // _GLIBCXX_RESOLVE_LIB_DEFECTS // 409. Closing an fstream should clear error state this->clear(); } #if __cplusplus >= 201103L /** * @brief Opens an external file. * @param __s The name of the file. * @param __mode The open mode flags. * * Calls @c std::basic_filebuf::open(__s,__mode|in). If that function * fails, @c failbit is set in the stream's error state. */ void open(const std::string& __s, ios_base::openmode __mode = ios_base::in) { if (!_M_filebuf.open(__s, __mode | ios_base::in)) this->setstate(ios_base::failbit); else // _GLIBCXX_RESOLVE_LIB_DEFECTS // 409. Closing an fstream should clear error state this->clear(); } #if __cplusplus >= 201703L /** * @brief Opens an external file. * @param __s The name of the file, as a filesystem::path. * @param __mode The open mode flags. * * Calls @c std::basic_filebuf::open(__s,__mode|in). If that function * fails, @c failbit is set in the stream's error state. */ template _If_fs_path<_Path, void> open(const _Path& __s, ios_base::openmode __mode = ios_base::in) { open(__s.c_str(), __mode); } #endif // C++17 #endif // C++11 /** * @brief Close the file. * * Calls @c std::basic_filebuf::close(). If that function * fails, @c failbit is set in the stream's error state. */ void close() { if (!_M_filebuf.close()) this->setstate(ios_base::failbit); } }; // [27.8.1.8] Template class basic_ofstream /** * @brief Controlling output for files. * @ingroup io * * @tparam _CharT Type of character stream. * @tparam _Traits Traits for character type, defaults to * char_traits<_CharT>. * * This class supports reading from named files, using the inherited * functions from std::basic_ostream. To control the associated * sequence, an instance of std::basic_filebuf is used, which this page * refers to as @c sb. */ template class basic_ofstream : public basic_ostream<_CharT,_Traits> { public: // Types: typedef _CharT char_type; typedef _Traits traits_type; typedef typename traits_type::int_type int_type; typedef typename traits_type::pos_type pos_type; typedef typename traits_type::off_type off_type; // Non-standard types: typedef basic_filebuf __filebuf_type; typedef basic_ostream __ostream_type; private: __filebuf_type _M_filebuf; public: // Constructors: /** * @brief Default constructor. * * Initializes @c sb using its default constructor, and passes * @c &sb to the base class initializer. Does not open any files * (you haven't given it a filename to open). */ basic_ofstream(): __ostream_type(), _M_filebuf() { this->init(&_M_filebuf); } /** * @brief Create an output file stream. * @param __s Null terminated string specifying the filename. * @param __mode Open file in specified mode (see std::ios_base). * * @c ios_base::out is automatically included in @a __mode. */ explicit basic_ofstream(const char* __s, ios_base::openmode __mode = ios_base::out) : __ostream_type(), _M_filebuf() { this->init(&_M_filebuf); this->open(__s, __mode); } #if __cplusplus >= 201103L /** * @brief Create an output file stream. * @param __s std::string specifying the filename. * @param __mode Open file in specified mode (see std::ios_base). * * @c ios_base::out is automatically included in @a __mode. */ explicit basic_ofstream(const std::string& __s, ios_base::openmode __mode = ios_base::out) : __ostream_type(), _M_filebuf() { this->init(&_M_filebuf); this->open(__s, __mode); } #if __cplusplus >= 201703L /** * @param Create an output file stream. * @param __s filesystem::path specifying the filename. * @param __mode Open file in specified mode (see std::ios_base). * * @c ios_base::out is automatically included in @a __mode. */ template> basic_ofstream(const _Path& __s, ios_base::openmode __mode = ios_base::out) : basic_ofstream(__s.c_str(), __mode) { } #endif // C++17 basic_ofstream(const basic_ofstream&) = delete; basic_ofstream(basic_ofstream&& __rhs) : __ostream_type(std::move(__rhs)), _M_filebuf(std::move(__rhs._M_filebuf)) { __ostream_type::set_rdbuf(&_M_filebuf); } #endif /** * @brief The destructor does nothing. * * The file is closed by the filebuf object, not the formatting * stream. */ ~basic_ofstream() { } #if __cplusplus >= 201103L // 27.8.3.2 Assign and swap: basic_ofstream& operator=(const basic_ofstream&) = delete; basic_ofstream& operator=(basic_ofstream&& __rhs) { __ostream_type::operator=(std::move(__rhs)); _M_filebuf = std::move(__rhs._M_filebuf); return *this; } void swap(basic_ofstream& __rhs) { __ostream_type::swap(__rhs); _M_filebuf.swap(__rhs._M_filebuf); } #endif // Members: /** * @brief Accessing the underlying buffer. * @return The current basic_filebuf buffer. * * This hides both signatures of std::basic_ios::rdbuf(). */ __filebuf_type* rdbuf() const { return const_cast<__filebuf_type*>(&_M_filebuf); } /** * @brief Wrapper to test for an open file. * @return @c rdbuf()->is_open() */ bool is_open() { return _M_filebuf.is_open(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 365. Lack of const-qualification in clause 27 bool is_open() const { return _M_filebuf.is_open(); } /** * @brief Opens an external file. * @param __s The name of the file. * @param __mode The open mode flags. * * Calls @c std::basic_filebuf::open(__s,__mode|out). If that * function fails, @c failbit is set in the stream's error state. */ void open(const char* __s, ios_base::openmode __mode = ios_base::out) { if (!_M_filebuf.open(__s, __mode | ios_base::out)) this->setstate(ios_base::failbit); else // _GLIBCXX_RESOLVE_LIB_DEFECTS // 409. Closing an fstream should clear error state this->clear(); } #if __cplusplus >= 201103L /** * @brief Opens an external file. * @param __s The name of the file. * @param __mode The open mode flags. * * Calls @c std::basic_filebuf::open(s,mode|out). If that * function fails, @c failbit is set in the stream's error state. */ void open(const std::string& __s, ios_base::openmode __mode = ios_base::out) { if (!_M_filebuf.open(__s, __mode | ios_base::out)) this->setstate(ios_base::failbit); else // _GLIBCXX_RESOLVE_LIB_DEFECTS // 409. Closing an fstream should clear error state this->clear(); } #if __cplusplus >= 201703L /** * @brief Opens an external file. * @param __s The name of the file, as a filesystem::path. * @param __mode The open mode flags. * * Calls @c std::basic_filebuf::open(__s,__mode|out). If that * function fails, @c failbit is set in the stream's error state. */ template _If_fs_path<_Path, void> open(const _Path& __s, ios_base::openmode __mode = ios_base::out) { open(__s.c_str(), __mode); } #endif // C++17 #endif // C++11 /** * @brief Close the file. * * Calls @c std::basic_filebuf::close(). If that function * fails, @c failbit is set in the stream's error state. */ void close() { if (!_M_filebuf.close()) this->setstate(ios_base::failbit); } }; // [27.8.1.11] Template class basic_fstream /** * @brief Controlling input and output for files. * @ingroup io * * @tparam _CharT Type of character stream. * @tparam _Traits Traits for character type, defaults to * char_traits<_CharT>. * * This class supports reading from and writing to named files, using * the inherited functions from std::basic_iostream. To control the * associated sequence, an instance of std::basic_filebuf is used, which * this page refers to as @c sb. */ template class basic_fstream : public basic_iostream<_CharT, _Traits> { public: // Types: typedef _CharT char_type; typedef _Traits traits_type; typedef typename traits_type::int_type int_type; typedef typename traits_type::pos_type pos_type; typedef typename traits_type::off_type off_type; // Non-standard types: typedef basic_filebuf __filebuf_type; typedef basic_ios __ios_type; typedef basic_iostream __iostream_type; private: __filebuf_type _M_filebuf; public: // Constructors/destructor: /** * @brief Default constructor. * * Initializes @c sb using its default constructor, and passes * @c &sb to the base class initializer. Does not open any files * (you haven't given it a filename to open). */ basic_fstream() : __iostream_type(), _M_filebuf() { this->init(&_M_filebuf); } /** * @brief Create an input/output file stream. * @param __s Null terminated string specifying the filename. * @param __mode Open file in specified mode (see std::ios_base). */ explicit basic_fstream(const char* __s, ios_base::openmode __mode = ios_base::in | ios_base::out) : __iostream_type(0), _M_filebuf() { this->init(&_M_filebuf); this->open(__s, __mode); } #if __cplusplus >= 201103L /** * @brief Create an input/output file stream. * @param __s Null terminated string specifying the filename. * @param __mode Open file in specified mode (see std::ios_base). */ explicit basic_fstream(const std::string& __s, ios_base::openmode __mode = ios_base::in | ios_base::out) : __iostream_type(0), _M_filebuf() { this->init(&_M_filebuf); this->open(__s, __mode); } #if __cplusplus >= 201703L /** * @param Create an input/output file stream. * @param __s filesystem::path specifying the filename. * @param __mode Open file in specified mode (see std::ios_base). */ template> basic_fstream(const _Path& __s, ios_base::openmode __mode = ios_base::in | ios_base::out) : basic_fstream(__s.c_str(), __mode) { } #endif // C++17 basic_fstream(const basic_fstream&) = delete; basic_fstream(basic_fstream&& __rhs) : __iostream_type(std::move(__rhs)), _M_filebuf(std::move(__rhs._M_filebuf)) { __iostream_type::set_rdbuf(&_M_filebuf); } #endif /** * @brief The destructor does nothing. * * The file is closed by the filebuf object, not the formatting * stream. */ ~basic_fstream() { } #if __cplusplus >= 201103L // 27.8.3.2 Assign and swap: basic_fstream& operator=(const basic_fstream&) = delete; basic_fstream& operator=(basic_fstream&& __rhs) { __iostream_type::operator=(std::move(__rhs)); _M_filebuf = std::move(__rhs._M_filebuf); return *this; } void swap(basic_fstream& __rhs) { __iostream_type::swap(__rhs); _M_filebuf.swap(__rhs._M_filebuf); } #endif // Members: /** * @brief Accessing the underlying buffer. * @return The current basic_filebuf buffer. * * This hides both signatures of std::basic_ios::rdbuf(). */ __filebuf_type* rdbuf() const { return const_cast<__filebuf_type*>(&_M_filebuf); } /** * @brief Wrapper to test for an open file. * @return @c rdbuf()->is_open() */ bool is_open() { return _M_filebuf.is_open(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 365. Lack of const-qualification in clause 27 bool is_open() const { return _M_filebuf.is_open(); } /** * @brief Opens an external file. * @param __s The name of the file. * @param __mode The open mode flags. * * Calls @c std::basic_filebuf::open(__s,__mode). If that * function fails, @c failbit is set in the stream's error state. */ void open(const char* __s, ios_base::openmode __mode = ios_base::in | ios_base::out) { if (!_M_filebuf.open(__s, __mode)) this->setstate(ios_base::failbit); else // _GLIBCXX_RESOLVE_LIB_DEFECTS // 409. Closing an fstream should clear error state this->clear(); } #if __cplusplus >= 201103L /** * @brief Opens an external file. * @param __s The name of the file. * @param __mode The open mode flags. * * Calls @c std::basic_filebuf::open(__s,__mode). If that * function fails, @c failbit is set in the stream's error state. */ void open(const std::string& __s, ios_base::openmode __mode = ios_base::in | ios_base::out) { if (!_M_filebuf.open(__s, __mode)) this->setstate(ios_base::failbit); else // _GLIBCXX_RESOLVE_LIB_DEFECTS // 409. Closing an fstream should clear error state this->clear(); } #if __cplusplus >= 201703L /** * @brief Opens an external file. * @param __s The name of the file, as a filesystem::path. * @param __mode The open mode flags. * * Calls @c std::basic_filebuf::open(__s,__mode). If that * function fails, @c failbit is set in the stream's error state. */ template _If_fs_path<_Path, void> open(const _Path& __s, ios_base::openmode __mode = ios_base::in | ios_base::out) { open(__s.c_str(), __mode); } #endif // C++17 #endif // C++11 /** * @brief Close the file. * * Calls @c std::basic_filebuf::close(). If that function * fails, @c failbit is set in the stream's error state. */ void close() { if (!_M_filebuf.close()) this->setstate(ios_base::failbit); } }; #if __cplusplus >= 201103L /// Swap specialization for filebufs. template inline void swap(basic_filebuf<_CharT, _Traits>& __x, basic_filebuf<_CharT, _Traits>& __y) { __x.swap(__y); } /// Swap specialization for ifstreams. template inline void swap(basic_ifstream<_CharT, _Traits>& __x, basic_ifstream<_CharT, _Traits>& __y) { __x.swap(__y); } /// Swap specialization for ofstreams. template inline void swap(basic_ofstream<_CharT, _Traits>& __x, basic_ofstream<_CharT, _Traits>& __y) { __x.swap(__y); } /// Swap specialization for fstreams. template inline void swap(basic_fstream<_CharT, _Traits>& __x, basic_fstream<_CharT, _Traits>& __y) { __x.swap(__y); } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #include #endif /* _GLIBCXX_FSTREAM */ PK!8xvv 8/functionalnu[// -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * Copyright (c) 1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * */ /** @file include/functional * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_FUNCTIONAL #define _GLIBCXX_FUNCTIONAL 1 #pragma GCC system_header #include #include #if __cplusplus >= 201103L #include #include #include #include #include #include // std::reference_wrapper and _Mem_fn_traits #include // std::function #if __cplusplus > 201402L # include # include # include # include # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if __cplusplus > 201402L # define __cpp_lib_invoke 201411 /// Invoke a callable object. template inline invoke_result_t<_Callable, _Args...> invoke(_Callable&& __fn, _Args&&... __args) noexcept(is_nothrow_invocable_v<_Callable, _Args...>) { return std::__invoke(std::forward<_Callable>(__fn), std::forward<_Args>(__args)...); } #endif template::value> class _Mem_fn_base : public _Mem_fn_traits<_MemFunPtr>::__maybe_type { using _Traits = _Mem_fn_traits<_MemFunPtr>; using _Arity = typename _Traits::__arity; using _Varargs = typename _Traits::__vararg; template friend struct _Bind_check_arity; _MemFunPtr _M_pmf; public: using result_type = typename _Traits::__result_type; explicit constexpr _Mem_fn_base(_MemFunPtr __pmf) noexcept : _M_pmf(__pmf) { } template auto operator()(_Args&&... __args) const noexcept(noexcept( std::__invoke(_M_pmf, std::forward<_Args>(__args)...))) -> decltype(std::__invoke(_M_pmf, std::forward<_Args>(__args)...)) { return std::__invoke(_M_pmf, std::forward<_Args>(__args)...); } }; // Partial specialization for member object pointers. template class _Mem_fn_base<_MemObjPtr, false> { using _Arity = integral_constant; using _Varargs = false_type; template friend struct _Bind_check_arity; _MemObjPtr _M_pm; public: explicit constexpr _Mem_fn_base(_MemObjPtr __pm) noexcept : _M_pm(__pm) { } template auto operator()(_Tp&& __obj) const noexcept(noexcept(std::__invoke(_M_pm, std::forward<_Tp>(__obj)))) -> decltype(std::__invoke(_M_pm, std::forward<_Tp>(__obj))) { return std::__invoke(_M_pm, std::forward<_Tp>(__obj)); } }; template struct _Mem_fn; // undefined template struct _Mem_fn<_Res _Class::*> : _Mem_fn_base<_Res _Class::*> { using _Mem_fn_base<_Res _Class::*>::_Mem_fn_base; }; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2048. Unnecessary mem_fn overloads /** * @brief Returns a function object that forwards to the member * pointer @a pm. * @ingroup functors */ template inline _Mem_fn<_Tp _Class::*> mem_fn(_Tp _Class::* __pm) noexcept { return _Mem_fn<_Tp _Class::*>(__pm); } /** * @brief Determines if the given type _Tp is a function object that * should be treated as a subexpression when evaluating calls to * function objects returned by bind(). * * C++11 [func.bind.isbind]. * @ingroup binders */ template struct is_bind_expression : public false_type { }; /** * @brief Determines if the given type _Tp is a placeholder in a * bind() expression and, if so, which placeholder it is. * * C++11 [func.bind.isplace]. * @ingroup binders */ template struct is_placeholder : public integral_constant { }; #if __cplusplus > 201402L template inline constexpr bool is_bind_expression_v = is_bind_expression<_Tp>::value; template inline constexpr int is_placeholder_v = is_placeholder<_Tp>::value; #endif // C++17 /** @brief The type of placeholder objects defined by libstdc++. * @ingroup binders */ template struct _Placeholder { }; /** @namespace std::placeholders * @brief ISO C++11 entities sub-namespace for functional. * @ingroup binders */ namespace placeholders { /* Define a large number of placeholders. There is no way to * simplify this with variadic templates, because we're introducing * unique names for each. */ extern const _Placeholder<1> _1; extern const _Placeholder<2> _2; extern const _Placeholder<3> _3; extern const _Placeholder<4> _4; extern const _Placeholder<5> _5; extern const _Placeholder<6> _6; extern const _Placeholder<7> _7; extern const _Placeholder<8> _8; extern const _Placeholder<9> _9; extern const _Placeholder<10> _10; extern const _Placeholder<11> _11; extern const _Placeholder<12> _12; extern const _Placeholder<13> _13; extern const _Placeholder<14> _14; extern const _Placeholder<15> _15; extern const _Placeholder<16> _16; extern const _Placeholder<17> _17; extern const _Placeholder<18> _18; extern const _Placeholder<19> _19; extern const _Placeholder<20> _20; extern const _Placeholder<21> _21; extern const _Placeholder<22> _22; extern const _Placeholder<23> _23; extern const _Placeholder<24> _24; extern const _Placeholder<25> _25; extern const _Placeholder<26> _26; extern const _Placeholder<27> _27; extern const _Placeholder<28> _28; extern const _Placeholder<29> _29; } /** * Partial specialization of is_placeholder that provides the placeholder * number for the placeholder objects defined by libstdc++. * @ingroup binders */ template struct is_placeholder<_Placeholder<_Num> > : public integral_constant { }; template struct is_placeholder > : public integral_constant { }; // Like tuple_element_t but SFINAE-friendly. template using _Safe_tuple_element_t = typename enable_if<(__i < tuple_size<_Tuple>::value), tuple_element<__i, _Tuple>>::type::type; /** * Maps an argument to bind() into an actual argument to the bound * function object [func.bind.bind]/10. Only the first parameter should * be specified: the rest are used to determine among the various * implementations. Note that, although this class is a function * object, it isn't entirely normal because it takes only two * parameters regardless of the number of parameters passed to the * bind expression. The first parameter is the bound argument and * the second parameter is a tuple containing references to the * rest of the arguments. */ template::value, bool _IsPlaceholder = (is_placeholder<_Arg>::value > 0)> class _Mu; /** * If the argument is reference_wrapper<_Tp>, returns the * underlying reference. * C++11 [func.bind.bind] p10 bullet 1. */ template class _Mu, false, false> { public: /* Note: This won't actually work for const volatile * reference_wrappers, because reference_wrapper::get() is const * but not volatile-qualified. This might be a defect in the TR. */ template _Tp& operator()(_CVRef& __arg, _Tuple&) const volatile { return __arg.get(); } }; /** * If the argument is a bind expression, we invoke the underlying * function object with the same cv-qualifiers as we are given and * pass along all of our arguments (unwrapped). * C++11 [func.bind.bind] p10 bullet 2. */ template class _Mu<_Arg, true, false> { public: template auto operator()(_CVArg& __arg, tuple<_Args...>& __tuple) const volatile -> decltype(__arg(declval<_Args>()...)) { // Construct an index tuple and forward to __call typedef typename _Build_index_tuple::__type _Indexes; return this->__call(__arg, __tuple, _Indexes()); } private: // Invokes the underlying function object __arg by unpacking all // of the arguments in the tuple. template auto __call(_CVArg& __arg, tuple<_Args...>& __tuple, const _Index_tuple<_Indexes...>&) const volatile -> decltype(__arg(declval<_Args>()...)) { return __arg(std::get<_Indexes>(std::move(__tuple))...); } }; /** * If the argument is a placeholder for the Nth argument, returns * a reference to the Nth argument to the bind function object. * C++11 [func.bind.bind] p10 bullet 3. */ template class _Mu<_Arg, false, true> { public: template _Safe_tuple_element_t<(is_placeholder<_Arg>::value - 1), _Tuple>&& operator()(const volatile _Arg&, _Tuple& __tuple) const volatile { return ::std::get<(is_placeholder<_Arg>::value - 1)>(std::move(__tuple)); } }; /** * If the argument is just a value, returns a reference to that * value. The cv-qualifiers on the reference are determined by the caller. * C++11 [func.bind.bind] p10 bullet 4. */ template class _Mu<_Arg, false, false> { public: template _CVArg&& operator()(_CVArg&& __arg, _Tuple&) const volatile { return std::forward<_CVArg>(__arg); } }; // std::get for volatile-qualified tuples template inline auto __volget(volatile tuple<_Tp...>& __tuple) -> __tuple_element_t<_Ind, tuple<_Tp...>> volatile& { return std::get<_Ind>(const_cast&>(__tuple)); } // std::get for const-volatile-qualified tuples template inline auto __volget(const volatile tuple<_Tp...>& __tuple) -> __tuple_element_t<_Ind, tuple<_Tp...>> const volatile& { return std::get<_Ind>(const_cast&>(__tuple)); } /// Type of the function object returned from bind(). template struct _Bind; template class _Bind<_Functor(_Bound_args...)> : public _Weak_result_type<_Functor> { typedef typename _Build_index_tuple::__type _Bound_indexes; _Functor _M_f; tuple<_Bound_args...> _M_bound_args; // Call unqualified template _Result __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) { return std::__invoke(_M_f, _Mu<_Bound_args>()(std::get<_Indexes>(_M_bound_args), __args)... ); } // Call as const template _Result __call_c(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) const { return std::__invoke(_M_f, _Mu<_Bound_args>()(std::get<_Indexes>(_M_bound_args), __args)... ); } // Call as volatile template _Result __call_v(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) volatile { return std::__invoke(_M_f, _Mu<_Bound_args>()(__volget<_Indexes>(_M_bound_args), __args)... ); } // Call as const volatile template _Result __call_c_v(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) const volatile { return std::__invoke(_M_f, _Mu<_Bound_args>()(__volget<_Indexes>(_M_bound_args), __args)... ); } template using _Mu_type = decltype( _Mu::type>()( std::declval<_BoundArg&>(), std::declval<_CallArgs&>()) ); template using _Res_type_impl = typename result_of< _Fn&(_Mu_type<_BArgs, _CallArgs>&&...) >::type; template using _Res_type = _Res_type_impl<_Functor, _CallArgs, _Bound_args...>; template using __dependent = typename enable_if::value+1), _Functor>::type; template class __cv_quals> using _Res_type_cv = _Res_type_impl< typename __cv_quals<__dependent<_CallArgs>>::type, _CallArgs, typename __cv_quals<_Bound_args>::type...>; public: template explicit _Bind(const _Functor& __f, _Args&&... __args) : _M_f(__f), _M_bound_args(std::forward<_Args>(__args)...) { } template explicit _Bind(_Functor&& __f, _Args&&... __args) : _M_f(std::move(__f)), _M_bound_args(std::forward<_Args>(__args)...) { } _Bind(const _Bind&) = default; _Bind(_Bind&& __b) : _M_f(std::move(__b._M_f)), _M_bound_args(std::move(__b._M_bound_args)) { } // Call unqualified template>> _Result operator()(_Args&&... __args) { return this->__call<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } // Call as const template, add_const>> _Result operator()(_Args&&... __args) const { return this->__call_c<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } #if __cplusplus > 201402L # define _GLIBCXX_DEPR_BIND \ [[deprecated("std::bind does not support volatile in C++17")]] #else # define _GLIBCXX_DEPR_BIND #endif // Call as volatile template, add_volatile>> _GLIBCXX_DEPR_BIND _Result operator()(_Args&&... __args) volatile { return this->__call_v<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } // Call as const volatile template, add_cv>> _GLIBCXX_DEPR_BIND _Result operator()(_Args&&... __args) const volatile { return this->__call_c_v<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } }; /// Type of the function object returned from bind(). template struct _Bind_result; template class _Bind_result<_Result, _Functor(_Bound_args...)> { typedef typename _Build_index_tuple::__type _Bound_indexes; _Functor _M_f; tuple<_Bound_args...> _M_bound_args; // sfinae types template using __enable_if_void = typename enable_if{}>::type; template using __disable_if_void = typename enable_if{}, _Result>::type; // Call unqualified template __disable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) { return std::__invoke(_M_f, _Mu<_Bound_args>() (std::get<_Indexes>(_M_bound_args), __args)...); } // Call unqualified, return void template __enable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) { std::__invoke(_M_f, _Mu<_Bound_args>() (std::get<_Indexes>(_M_bound_args), __args)...); } // Call as const template __disable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) const { return std::__invoke(_M_f, _Mu<_Bound_args>() (std::get<_Indexes>(_M_bound_args), __args)...); } // Call as const, return void template __enable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) const { std::__invoke(_M_f, _Mu<_Bound_args>() (std::get<_Indexes>(_M_bound_args), __args)...); } // Call as volatile template __disable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) volatile { return std::__invoke(_M_f, _Mu<_Bound_args>() (__volget<_Indexes>(_M_bound_args), __args)...); } // Call as volatile, return void template __enable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) volatile { std::__invoke(_M_f, _Mu<_Bound_args>() (__volget<_Indexes>(_M_bound_args), __args)...); } // Call as const volatile template __disable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) const volatile { return std::__invoke(_M_f, _Mu<_Bound_args>() (__volget<_Indexes>(_M_bound_args), __args)...); } // Call as const volatile, return void template __enable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) const volatile { std::__invoke(_M_f, _Mu<_Bound_args>() (__volget<_Indexes>(_M_bound_args), __args)...); } public: typedef _Result result_type; template explicit _Bind_result(const _Functor& __f, _Args&&... __args) : _M_f(__f), _M_bound_args(std::forward<_Args>(__args)...) { } template explicit _Bind_result(_Functor&& __f, _Args&&... __args) : _M_f(std::move(__f)), _M_bound_args(std::forward<_Args>(__args)...) { } _Bind_result(const _Bind_result&) = default; _Bind_result(_Bind_result&& __b) : _M_f(std::move(__b._M_f)), _M_bound_args(std::move(__b._M_bound_args)) { } // Call unqualified template result_type operator()(_Args&&... __args) { return this->__call<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } // Call as const template result_type operator()(_Args&&... __args) const { return this->__call<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } // Call as volatile template _GLIBCXX_DEPR_BIND result_type operator()(_Args&&... __args) volatile { return this->__call<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } // Call as const volatile template _GLIBCXX_DEPR_BIND result_type operator()(_Args&&... __args) const volatile { return this->__call<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } }; #undef _GLIBCXX_DEPR_BIND /** * @brief Class template _Bind is always a bind expression. * @ingroup binders */ template struct is_bind_expression<_Bind<_Signature> > : public true_type { }; /** * @brief Class template _Bind is always a bind expression. * @ingroup binders */ template struct is_bind_expression > : public true_type { }; /** * @brief Class template _Bind is always a bind expression. * @ingroup binders */ template struct is_bind_expression > : public true_type { }; /** * @brief Class template _Bind is always a bind expression. * @ingroup binders */ template struct is_bind_expression> : public true_type { }; /** * @brief Class template _Bind_result is always a bind expression. * @ingroup binders */ template struct is_bind_expression<_Bind_result<_Result, _Signature>> : public true_type { }; /** * @brief Class template _Bind_result is always a bind expression. * @ingroup binders */ template struct is_bind_expression> : public true_type { }; /** * @brief Class template _Bind_result is always a bind expression. * @ingroup binders */ template struct is_bind_expression> : public true_type { }; /** * @brief Class template _Bind_result is always a bind expression. * @ingroup binders */ template struct is_bind_expression> : public true_type { }; template struct _Bind_check_arity { }; template struct _Bind_check_arity<_Ret (*)(_Args...), _BoundArgs...> { static_assert(sizeof...(_BoundArgs) == sizeof...(_Args), "Wrong number of arguments for function"); }; template struct _Bind_check_arity<_Ret (*)(_Args......), _BoundArgs...> { static_assert(sizeof...(_BoundArgs) >= sizeof...(_Args), "Wrong number of arguments for function"); }; template struct _Bind_check_arity<_Tp _Class::*, _BoundArgs...> { using _Arity = typename _Mem_fn<_Tp _Class::*>::_Arity; using _Varargs = typename _Mem_fn<_Tp _Class::*>::_Varargs; static_assert(_Varargs::value ? sizeof...(_BoundArgs) >= _Arity::value + 1 : sizeof...(_BoundArgs) == _Arity::value + 1, "Wrong number of arguments for pointer-to-member"); }; // Trait type used to remove std::bind() from overload set via SFINAE // when first argument has integer type, so that std::bind() will // not be a better match than ::bind() from the BSD Sockets API. template::type> using __is_socketlike = __or_, is_enum<_Tp2>>; template struct _Bind_helper : _Bind_check_arity::type, _BoundArgs...> { typedef typename decay<_Func>::type __func_type; typedef _Bind<__func_type(typename decay<_BoundArgs>::type...)> type; }; // Partial specialization for is_socketlike == true, does not define // nested type so std::bind() will not participate in overload resolution // when the first argument might be a socket file descriptor. template struct _Bind_helper { }; /** * @brief Function template for std::bind. * @ingroup binders */ template inline typename _Bind_helper<__is_socketlike<_Func>::value, _Func, _BoundArgs...>::type bind(_Func&& __f, _BoundArgs&&... __args) { typedef _Bind_helper __helper_type; return typename __helper_type::type(std::forward<_Func>(__f), std::forward<_BoundArgs>(__args)...); } template struct _Bindres_helper : _Bind_check_arity::type, _BoundArgs...> { typedef typename decay<_Func>::type __functor_type; typedef _Bind_result<_Result, __functor_type(typename decay<_BoundArgs>::type...)> type; }; /** * @brief Function template for std::bind. * @ingroup binders */ template inline typename _Bindres_helper<_Result, _Func, _BoundArgs...>::type bind(_Func&& __f, _BoundArgs&&... __args) { typedef _Bindres_helper<_Result, _Func, _BoundArgs...> __helper_type; return typename __helper_type::type(std::forward<_Func>(__f), std::forward<_BoundArgs>(__args)...); } #if __cplusplus >= 201402L /// Generalized negator. template class _Not_fn { template using __inv_res_t = typename __invoke_result<_Fn2, _Args...>::type; template static decltype(!std::declval<_Tp>()) _S_not() noexcept(noexcept(!std::declval<_Tp>())); public: template _Not_fn(_Fn2&& __fn, int) : _M_fn(std::forward<_Fn2>(__fn)) { } _Not_fn(const _Not_fn& __fn) = default; _Not_fn(_Not_fn&& __fn) = default; ~_Not_fn() = default; // Macro to define operator() with given cv-qualifiers ref-qualifiers, // forwarding _M_fn and the function arguments with the same qualifiers, // and deducing the return type and exception-specification. #define _GLIBCXX_NOT_FN_CALL_OP( _QUALS ) \ template \ decltype(_S_not<__inv_res_t<_Fn _QUALS, _Args...>>()) \ operator()(_Args&&... __args) _QUALS \ noexcept(__is_nothrow_invocable<_Fn _QUALS, _Args...>::value \ && noexcept(_S_not<__inv_res_t<_Fn _QUALS, _Args...>>())) \ { \ return !std::__invoke(std::forward< _Fn _QUALS >(_M_fn), \ std::forward<_Args>(__args)...); \ } _GLIBCXX_NOT_FN_CALL_OP( & ) _GLIBCXX_NOT_FN_CALL_OP( const & ) _GLIBCXX_NOT_FN_CALL_OP( && ) _GLIBCXX_NOT_FN_CALL_OP( const && ) #undef _GLIBCXX_NOT_FN_CALL private: _Fn _M_fn; }; template struct __is_byte_like : false_type { }; template struct __is_byte_like<_Tp, equal_to<_Tp>> : __bool_constant::value> { }; template struct __is_byte_like<_Tp, equal_to> : __bool_constant::value> { }; #if __cplusplus >= 201703L // Declare std::byte (full definition is in ). enum class byte : unsigned char; template<> struct __is_byte_like> : true_type { }; template<> struct __is_byte_like> : true_type { }; #define __cpp_lib_not_fn 201603 /// [func.not_fn] Function template not_fn template inline auto not_fn(_Fn&& __fn) noexcept(std::is_nothrow_constructible, _Fn&&>::value) { return _Not_fn>{std::forward<_Fn>(__fn), 0}; } // Searchers #define __cpp_lib_boyer_moore_searcher 201603 template> class default_searcher { public: default_searcher(_ForwardIterator1 __pat_first, _ForwardIterator1 __pat_last, _BinaryPredicate __pred = _BinaryPredicate()) : _M_m(__pat_first, __pat_last, std::move(__pred)) { } template pair<_ForwardIterator2, _ForwardIterator2> operator()(_ForwardIterator2 __first, _ForwardIterator2 __last) const { _ForwardIterator2 __first_ret = std::search(__first, __last, std::get<0>(_M_m), std::get<1>(_M_m), std::get<2>(_M_m)); auto __ret = std::make_pair(__first_ret, __first_ret); if (__ret.first != __last) std::advance(__ret.second, std::distance(std::get<0>(_M_m), std::get<1>(_M_m))); return __ret; } private: tuple<_ForwardIterator1, _ForwardIterator1, _BinaryPredicate> _M_m; }; template struct __boyer_moore_map_base { template __boyer_moore_map_base(_RAIter __pat, size_t __patlen, _Hash&& __hf, _Pred&& __pred) : _M_bad_char{ __patlen, std::move(__hf), std::move(__pred) } { if (__patlen > 0) for (__diff_type __i = 0; __i < __patlen - 1; ++__i) _M_bad_char[__pat[__i]] = __patlen - 1 - __i; } using __diff_type = _Tp; __diff_type _M_lookup(_Key __key, __diff_type __not_found) const { auto __iter = _M_bad_char.find(__key); if (__iter == _M_bad_char.end()) return __not_found; return __iter->second; } _Pred _M_pred() const { return _M_bad_char.key_eq(); } _GLIBCXX_STD_C::unordered_map<_Key, _Tp, _Hash, _Pred> _M_bad_char; }; template struct __boyer_moore_array_base { template __boyer_moore_array_base(_RAIter __pat, size_t __patlen, _Unused&&, _Pred&& __pred) : _M_bad_char{ _GLIBCXX_STD_C::array<_Tp, _Len>{}, std::move(__pred) } { std::get<0>(_M_bad_char).fill(__patlen); if (__patlen > 0) for (__diff_type __i = 0; __i < __patlen - 1; ++__i) { auto __ch = __pat[__i]; using _UCh = make_unsigned_t; auto __uch = static_cast<_UCh>(__ch); std::get<0>(_M_bad_char)[__uch] = __patlen - 1 - __i; } } using __diff_type = _Tp; template __diff_type _M_lookup(_Key __key, __diff_type __not_found) const { auto __ukey = static_cast>(__key); if (__ukey >= _Len) return __not_found; return std::get<0>(_M_bad_char)[__ukey]; } const _Pred& _M_pred() const { return std::get<1>(_M_bad_char); } tuple<_GLIBCXX_STD_C::array<_Tp, _Len>, _Pred> _M_bad_char; }; // Use __boyer_moore_array_base when pattern consists of narrow characters // (or std::byte) and uses std::equal_to as the predicate. template::value_type, typename _Diff = typename iterator_traits<_RAIter>::difference_type> using __boyer_moore_base_t = conditional_t<__is_byte_like<_Val, _Pred>::value, __boyer_moore_array_base<_Diff, 256, _Pred>, __boyer_moore_map_base<_Val, _Diff, _Hash, _Pred>>; template::value_type>, typename _BinaryPredicate = equal_to<>> class boyer_moore_searcher : __boyer_moore_base_t<_RAIter, _Hash, _BinaryPredicate> { using _Base = __boyer_moore_base_t<_RAIter, _Hash, _BinaryPredicate>; using typename _Base::__diff_type; public: boyer_moore_searcher(_RAIter __pat_first, _RAIter __pat_last, _Hash __hf = _Hash(), _BinaryPredicate __pred = _BinaryPredicate()); template pair<_RandomAccessIterator2, _RandomAccessIterator2> operator()(_RandomAccessIterator2 __first, _RandomAccessIterator2 __last) const; private: bool _M_is_prefix(_RAIter __word, __diff_type __len, __diff_type __pos) { const auto& __pred = this->_M_pred(); __diff_type __suffixlen = __len - __pos; for (__diff_type __i = 0; __i < __suffixlen; ++__i) if (!__pred(__word[__i], __word[__pos + __i])) return false; return true; } __diff_type _M_suffix_length(_RAIter __word, __diff_type __len, __diff_type __pos) { const auto& __pred = this->_M_pred(); __diff_type __i = 0; while (__pred(__word[__pos - __i], __word[__len - 1 - __i]) && __i < __pos) { ++__i; } return __i; } template __diff_type _M_bad_char_shift(_Tp __c) const { return this->_M_lookup(__c, _M_pat_end - _M_pat); } _RAIter _M_pat; _RAIter _M_pat_end; _GLIBCXX_STD_C::vector<__diff_type> _M_good_suffix; }; template::value_type>, typename _BinaryPredicate = equal_to<>> class boyer_moore_horspool_searcher : __boyer_moore_base_t<_RAIter, _Hash, _BinaryPredicate> { using _Base = __boyer_moore_base_t<_RAIter, _Hash, _BinaryPredicate>; using typename _Base::__diff_type; public: boyer_moore_horspool_searcher(_RAIter __pat, _RAIter __pat_end, _Hash __hf = _Hash(), _BinaryPredicate __pred = _BinaryPredicate()) : _Base(__pat, __pat_end - __pat, std::move(__hf), std::move(__pred)), _M_pat(__pat), _M_pat_end(__pat_end) { } template pair<_RandomAccessIterator2, _RandomAccessIterator2> operator()(_RandomAccessIterator2 __first, _RandomAccessIterator2 __last) const { const auto& __pred = this->_M_pred(); auto __patlen = _M_pat_end - _M_pat; if (__patlen == 0) return std::make_pair(__first, __first); auto __len = __last - __first; while (__len >= __patlen) { for (auto __scan = __patlen - 1; __pred(__first[__scan], _M_pat[__scan]); --__scan) if (__scan == 0) return std::make_pair(__first, __first + __patlen); auto __shift = _M_bad_char_shift(__first[__patlen - 1]); __len -= __shift; __first += __shift; } return std::make_pair(__last, __last); } private: template __diff_type _M_bad_char_shift(_Tp __c) const { return this->_M_lookup(__c, _M_pat_end - _M_pat); } _RAIter _M_pat; _RAIter _M_pat_end; }; template boyer_moore_searcher<_RAIter, _Hash, _BinaryPredicate>:: boyer_moore_searcher(_RAIter __pat, _RAIter __pat_end, _Hash __hf, _BinaryPredicate __pred) : _Base(__pat, __pat_end - __pat, std::move(__hf), std::move(__pred)), _M_pat(__pat), _M_pat_end(__pat_end), _M_good_suffix(__pat_end - __pat) { auto __patlen = __pat_end - __pat; if (__patlen == 0) return; __diff_type __last_prefix = __patlen - 1; for (__diff_type __p = __patlen - 1; __p >= 0; --__p) { if (_M_is_prefix(__pat, __patlen, __p + 1)) __last_prefix = __p + 1; _M_good_suffix[__p] = __last_prefix + (__patlen - 1 - __p); } for (__diff_type __p = 0; __p < __patlen - 1; ++__p) { auto __slen = _M_suffix_length(__pat, __patlen, __p); auto __pos = __patlen - 1 - __slen; if (!__pred(__pat[__p - __slen], __pat[__pos])) _M_good_suffix[__pos] = __patlen - 1 - __p + __slen; } } template template pair<_RandomAccessIterator2, _RandomAccessIterator2> boyer_moore_searcher<_RAIter, _Hash, _BinaryPredicate>:: operator()(_RandomAccessIterator2 __first, _RandomAccessIterator2 __last) const { auto __patlen = _M_pat_end - _M_pat; if (__patlen == 0) return std::make_pair(__first, __first); const auto& __pred = this->_M_pred(); __diff_type __i = __patlen - 1; auto __stringlen = __last - __first; while (__i < __stringlen) { __diff_type __j = __patlen - 1; while (__j >= 0 && __pred(__first[__i], _M_pat[__j])) { --__i; --__j; } if (__j < 0) { const auto __match = __first + __i + 1; return std::make_pair(__match, __match + __patlen); } __i += std::max(_M_bad_char_shift(__first[__i]), _M_good_suffix[__j]); } return std::make_pair(__last, __last); } #endif // C++17 #endif // C++14 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif // _GLIBCXX_FUNCTIONAL PK! 8/futurenu[// -*- C++ -*- // Copyright (C) 2009-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/future * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_FUTURE #define _GLIBCXX_FUTURE 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup futures Futures * @ingroup concurrency * * Classes for futures support. * @{ */ /// Error code for futures enum class future_errc { future_already_retrieved = 1, promise_already_satisfied, no_state, broken_promise }; /// Specialization. template<> struct is_error_code_enum : public true_type { }; /// Points to a statically-allocated object derived from error_category. const error_category& future_category() noexcept; /// Overload for make_error_code. inline error_code make_error_code(future_errc __errc) noexcept { return error_code(static_cast(__errc), future_category()); } /// Overload for make_error_condition. inline error_condition make_error_condition(future_errc __errc) noexcept { return error_condition(static_cast(__errc), future_category()); } /** * @brief Exception type thrown by futures. * @ingroup exceptions */ class future_error : public logic_error { public: explicit future_error(future_errc __errc) : future_error(std::make_error_code(__errc)) { } virtual ~future_error() noexcept; virtual const char* what() const noexcept; const error_code& code() const noexcept { return _M_code; } private: explicit future_error(error_code __ec) : logic_error("std::future_error: " + __ec.message()), _M_code(__ec) { } friend void __throw_future_error(int); error_code _M_code; }; // Forward declarations. template class future; template class shared_future; template class packaged_task; template class promise; /// Launch code for futures enum class launch { async = 1, deferred = 2 }; constexpr launch operator&(launch __x, launch __y) { return static_cast( static_cast(__x) & static_cast(__y)); } constexpr launch operator|(launch __x, launch __y) { return static_cast( static_cast(__x) | static_cast(__y)); } constexpr launch operator^(launch __x, launch __y) { return static_cast( static_cast(__x) ^ static_cast(__y)); } constexpr launch operator~(launch __x) { return static_cast(~static_cast(__x)); } inline launch& operator&=(launch& __x, launch __y) { return __x = __x & __y; } inline launch& operator|=(launch& __x, launch __y) { return __x = __x | __y; } inline launch& operator^=(launch& __x, launch __y) { return __x = __x ^ __y; } /// Status code for futures enum class future_status { ready, timeout, deferred }; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2021. Further incorrect usages of result_of template using __async_result_of = typename result_of< typename decay<_Fn>::type(typename decay<_Args>::type...)>::type; template future<__async_result_of<_Fn, _Args...>> async(launch __policy, _Fn&& __fn, _Args&&... __args); template future<__async_result_of<_Fn, _Args...>> async(_Fn&& __fn, _Args&&... __args); #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1) /// Base class and enclosing scope. struct __future_base { /// Base class for results. struct _Result_base { exception_ptr _M_error; _Result_base(const _Result_base&) = delete; _Result_base& operator=(const _Result_base&) = delete; // _M_destroy() allows derived classes to control deallocation virtual void _M_destroy() = 0; struct _Deleter { void operator()(_Result_base* __fr) const { __fr->_M_destroy(); } }; protected: _Result_base(); virtual ~_Result_base(); }; /// A unique_ptr for result objects. template using _Ptr = unique_ptr<_Res, _Result_base::_Deleter>; /// A result object that has storage for an object of type _Res. template struct _Result : _Result_base { private: __gnu_cxx::__aligned_buffer<_Res> _M_storage; bool _M_initialized; public: typedef _Res result_type; _Result() noexcept : _M_initialized() { } ~_Result() { if (_M_initialized) _M_value().~_Res(); } // Return lvalue, future will add const or rvalue-reference _Res& _M_value() noexcept { return *_M_storage._M_ptr(); } void _M_set(const _Res& __res) { ::new (_M_storage._M_addr()) _Res(__res); _M_initialized = true; } void _M_set(_Res&& __res) { ::new (_M_storage._M_addr()) _Res(std::move(__res)); _M_initialized = true; } private: void _M_destroy() { delete this; } }; /// A result object that uses an allocator. template struct _Result_alloc final : _Result<_Res>, _Alloc { using __allocator_type = __alloc_rebind<_Alloc, _Result_alloc>; explicit _Result_alloc(const _Alloc& __a) : _Result<_Res>(), _Alloc(__a) { } private: void _M_destroy() { __allocator_type __a(*this); __allocated_ptr<__allocator_type> __guard_ptr{ __a, this }; this->~_Result_alloc(); } }; // Create a result object that uses an allocator. template static _Ptr<_Result_alloc<_Res, _Allocator>> _S_allocate_result(const _Allocator& __a) { using __result_type = _Result_alloc<_Res, _Allocator>; typename __result_type::__allocator_type __a2(__a); auto __guard = std::__allocate_guarded(__a2); __result_type* __p = ::new((void*)__guard.get()) __result_type{__a}; __guard = nullptr; return _Ptr<__result_type>(__p); } // Keep it simple for std::allocator. template static _Ptr<_Result<_Res>> _S_allocate_result(const std::allocator<_Tp>& __a) { return _Ptr<_Result<_Res>>(new _Result<_Res>); } // Base class for various types of shared state created by an // asynchronous provider (such as a std::promise) and shared with one // or more associated futures. class _State_baseV2 { typedef _Ptr<_Result_base> _Ptr_type; enum _Status : unsigned { __not_ready, __ready }; _Ptr_type _M_result; __atomic_futex_unsigned<> _M_status; atomic_flag _M_retrieved = ATOMIC_FLAG_INIT; once_flag _M_once; public: _State_baseV2() noexcept : _M_result(), _M_status(_Status::__not_ready) { } _State_baseV2(const _State_baseV2&) = delete; _State_baseV2& operator=(const _State_baseV2&) = delete; virtual ~_State_baseV2() = default; _Result_base& wait() { // Run any deferred function or join any asynchronous thread: _M_complete_async(); // Acquire MO makes sure this synchronizes with the thread that made // the future ready. _M_status._M_load_when_equal(_Status::__ready, memory_order_acquire); return *_M_result; } template future_status wait_for(const chrono::duration<_Rep, _Period>& __rel) { // First, check if the future has been made ready. Use acquire MO // to synchronize with the thread that made it ready. if (_M_status._M_load(memory_order_acquire) == _Status::__ready) return future_status::ready; if (_M_is_deferred_future()) return future_status::deferred; if (_M_status._M_load_when_equal_for(_Status::__ready, memory_order_acquire, __rel)) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2100. timed waiting functions must also join // This call is a no-op by default except on an async future, // in which case the async thread is joined. It's also not a // no-op for a deferred future, but such a future will never // reach this point because it returns future_status::deferred // instead of waiting for the future to become ready (see // above). Async futures synchronize in this call, so we need // no further synchronization here. _M_complete_async(); return future_status::ready; } return future_status::timeout; } template future_status wait_until(const chrono::time_point<_Clock, _Duration>& __abs) { // First, check if the future has been made ready. Use acquire MO // to synchronize with the thread that made it ready. if (_M_status._M_load(memory_order_acquire) == _Status::__ready) return future_status::ready; if (_M_is_deferred_future()) return future_status::deferred; if (_M_status._M_load_when_equal_until(_Status::__ready, memory_order_acquire, __abs)) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2100. timed waiting functions must also join // See wait_for(...) above. _M_complete_async(); return future_status::ready; } return future_status::timeout; } // Provide a result to the shared state and make it ready. // Calls at most once: _M_result = __res(); void _M_set_result(function<_Ptr_type()> __res, bool __ignore_failure = false) { bool __did_set = false; // all calls to this function are serialized, // side-effects of invoking __res only happen once call_once(_M_once, &_State_baseV2::_M_do_set, this, std::__addressof(__res), std::__addressof(__did_set)); if (__did_set) // Use release MO to synchronize with observers of the ready state. _M_status._M_store_notify_all(_Status::__ready, memory_order_release); else if (!__ignore_failure) __throw_future_error(int(future_errc::promise_already_satisfied)); } // Provide a result to the shared state but delay making it ready // until the calling thread exits. // Calls at most once: _M_result = __res(); void _M_set_delayed_result(function<_Ptr_type()> __res, weak_ptr<_State_baseV2> __self) { bool __did_set = false; unique_ptr<_Make_ready> __mr{new _Make_ready}; // all calls to this function are serialized, // side-effects of invoking __res only happen once call_once(_M_once, &_State_baseV2::_M_do_set, this, std::__addressof(__res), std::__addressof(__did_set)); if (!__did_set) __throw_future_error(int(future_errc::promise_already_satisfied)); __mr->_M_shared_state = std::move(__self); __mr->_M_set(); __mr.release(); } // Abandon this shared state. void _M_break_promise(_Ptr_type __res) { if (static_cast(__res)) { __res->_M_error = make_exception_ptr(future_error(future_errc::broken_promise)); // This function is only called when the last asynchronous result // provider is abandoning this shared state, so noone can be // trying to make the shared state ready at the same time, and // we can access _M_result directly instead of through call_once. _M_result.swap(__res); // Use release MO to synchronize with observers of the ready state. _M_status._M_store_notify_all(_Status::__ready, memory_order_release); } } // Called when this object is first passed to a future. void _M_set_retrieved_flag() { if (_M_retrieved.test_and_set()) __throw_future_error(int(future_errc::future_already_retrieved)); } template struct _Setter; // set lvalues template struct _Setter<_Res, _Arg&> { // check this is only used by promise::set_value(const R&) // or promise::set_value(R&) static_assert(is_same<_Res, _Arg&>::value // promise || is_same::value, // promise "Invalid specialisation"); // Used by std::promise to copy construct the result. typename promise<_Res>::_Ptr_type operator()() const { _M_promise->_M_storage->_M_set(*_M_arg); return std::move(_M_promise->_M_storage); } promise<_Res>* _M_promise; _Arg* _M_arg; }; // set rvalues template struct _Setter<_Res, _Res&&> { // Used by std::promise to move construct the result. typename promise<_Res>::_Ptr_type operator()() const { _M_promise->_M_storage->_M_set(std::move(*_M_arg)); return std::move(_M_promise->_M_storage); } promise<_Res>* _M_promise; _Res* _M_arg; }; // set void template struct _Setter<_Res, void> { static_assert(is_void<_Res>::value, "Only used for promise"); typename promise<_Res>::_Ptr_type operator()() const { return std::move(_M_promise->_M_storage); } promise<_Res>* _M_promise; }; struct __exception_ptr_tag { }; // set exceptions template struct _Setter<_Res, __exception_ptr_tag> { // Used by std::promise to store an exception as the result. typename promise<_Res>::_Ptr_type operator()() const { _M_promise->_M_storage->_M_error = *_M_ex; return std::move(_M_promise->_M_storage); } promise<_Res>* _M_promise; exception_ptr* _M_ex; }; template static _Setter<_Res, _Arg&&> __setter(promise<_Res>* __prom, _Arg&& __arg) { _S_check(__prom->_M_future); return _Setter<_Res, _Arg&&>{ __prom, std::__addressof(__arg) }; } template static _Setter<_Res, __exception_ptr_tag> __setter(exception_ptr& __ex, promise<_Res>* __prom) { _S_check(__prom->_M_future); return _Setter<_Res, __exception_ptr_tag>{ __prom, &__ex }; } template static _Setter<_Res, void> __setter(promise<_Res>* __prom) { _S_check(__prom->_M_future); return _Setter<_Res, void>{ __prom }; } template static void _S_check(const shared_ptr<_Tp>& __p) { if (!static_cast(__p)) __throw_future_error((int)future_errc::no_state); } private: // The function invoked with std::call_once(_M_once, ...). void _M_do_set(function<_Ptr_type()>* __f, bool* __did_set) { _Ptr_type __res = (*__f)(); // Notify the caller that we did try to set; if we do not throw an // exception, the caller will be aware that it did set (e.g., see // _M_set_result). *__did_set = true; _M_result.swap(__res); // nothrow } // Wait for completion of async function. virtual void _M_complete_async() { } // Return true if state corresponds to a deferred function. virtual bool _M_is_deferred_future() const { return false; } struct _Make_ready final : __at_thread_exit_elt { weak_ptr<_State_baseV2> _M_shared_state; static void _S_run(void*); void _M_set(); }; }; #ifdef _GLIBCXX_ASYNC_ABI_COMPAT class _State_base; class _Async_state_common; #else using _State_base = _State_baseV2; class _Async_state_commonV2; #endif template()())> class _Deferred_state; template()())> class _Async_state_impl; template class _Task_state_base; template class _Task_state; template static std::shared_ptr<_State_base> _S_make_deferred_state(_BoundFn&& __fn); template static std::shared_ptr<_State_base> _S_make_async_state(_BoundFn&& __fn); template struct _Task_setter; template static _Task_setter<_Res_ptr, _BoundFn> _S_task_setter(_Res_ptr& __ptr, _BoundFn& __call) { return { std::__addressof(__ptr), std::__addressof(__call) }; } }; /// Partial specialization for reference types. template struct __future_base::_Result<_Res&> : __future_base::_Result_base { typedef _Res& result_type; _Result() noexcept : _M_value_ptr() { } void _M_set(_Res& __res) noexcept { _M_value_ptr = std::addressof(__res); } _Res& _M_get() noexcept { return *_M_value_ptr; } private: _Res* _M_value_ptr; void _M_destroy() { delete this; } }; /// Explicit specialization for void. template<> struct __future_base::_Result : __future_base::_Result_base { typedef void result_type; private: void _M_destroy() { delete this; } }; #ifndef _GLIBCXX_ASYNC_ABI_COMPAT // Allow _Setter objects to be stored locally in std::function template struct __is_location_invariant <__future_base::_State_base::_Setter<_Res, _Arg>> : true_type { }; // Allow _Task_setter objects to be stored locally in std::function template struct __is_location_invariant <__future_base::_Task_setter<_Res_ptr, _Fn, _Res>> : true_type { }; /// Common implementation for future and shared_future. template class __basic_future : public __future_base { protected: typedef shared_ptr<_State_base> __state_type; typedef __future_base::_Result<_Res>& __result_type; private: __state_type _M_state; public: // Disable copying. __basic_future(const __basic_future&) = delete; __basic_future& operator=(const __basic_future&) = delete; bool valid() const noexcept { return static_cast(_M_state); } void wait() const { _State_base::_S_check(_M_state); _M_state->wait(); } template future_status wait_for(const chrono::duration<_Rep, _Period>& __rel) const { _State_base::_S_check(_M_state); return _M_state->wait_for(__rel); } template future_status wait_until(const chrono::time_point<_Clock, _Duration>& __abs) const { _State_base::_S_check(_M_state); return _M_state->wait_until(__abs); } protected: /// Wait for the state to be ready and rethrow any stored exception __result_type _M_get_result() const { _State_base::_S_check(_M_state); _Result_base& __res = _M_state->wait(); if (!(__res._M_error == 0)) rethrow_exception(__res._M_error); return static_cast<__result_type>(__res); } void _M_swap(__basic_future& __that) noexcept { _M_state.swap(__that._M_state); } // Construction of a future by promise::get_future() explicit __basic_future(const __state_type& __state) : _M_state(__state) { _State_base::_S_check(_M_state); _M_state->_M_set_retrieved_flag(); } // Copy construction from a shared_future explicit __basic_future(const shared_future<_Res>&) noexcept; // Move construction from a shared_future explicit __basic_future(shared_future<_Res>&&) noexcept; // Move construction from a future explicit __basic_future(future<_Res>&&) noexcept; constexpr __basic_future() noexcept : _M_state() { } struct _Reset { explicit _Reset(__basic_future& __fut) noexcept : _M_fut(__fut) { } ~_Reset() { _M_fut._M_state.reset(); } __basic_future& _M_fut; }; }; /// Primary template for future. template class future : public __basic_future<_Res> { friend class promise<_Res>; template friend class packaged_task; template friend future<__async_result_of<_Fn, _Args...>> async(launch, _Fn&&, _Args&&...); typedef __basic_future<_Res> _Base_type; typedef typename _Base_type::__state_type __state_type; explicit future(const __state_type& __state) : _Base_type(__state) { } public: constexpr future() noexcept : _Base_type() { } /// Move constructor future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { } // Disable copying future(const future&) = delete; future& operator=(const future&) = delete; future& operator=(future&& __fut) noexcept { future(std::move(__fut))._M_swap(*this); return *this; } /// Retrieving the value _Res get() { typename _Base_type::_Reset __reset(*this); return std::move(this->_M_get_result()._M_value()); } shared_future<_Res> share() noexcept; }; /// Partial specialization for future template class future<_Res&> : public __basic_future<_Res&> { friend class promise<_Res&>; template friend class packaged_task; template friend future<__async_result_of<_Fn, _Args...>> async(launch, _Fn&&, _Args&&...); typedef __basic_future<_Res&> _Base_type; typedef typename _Base_type::__state_type __state_type; explicit future(const __state_type& __state) : _Base_type(__state) { } public: constexpr future() noexcept : _Base_type() { } /// Move constructor future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { } // Disable copying future(const future&) = delete; future& operator=(const future&) = delete; future& operator=(future&& __fut) noexcept { future(std::move(__fut))._M_swap(*this); return *this; } /// Retrieving the value _Res& get() { typename _Base_type::_Reset __reset(*this); return this->_M_get_result()._M_get(); } shared_future<_Res&> share() noexcept; }; /// Explicit specialization for future template<> class future : public __basic_future { friend class promise; template friend class packaged_task; template friend future<__async_result_of<_Fn, _Args...>> async(launch, _Fn&&, _Args&&...); typedef __basic_future _Base_type; typedef typename _Base_type::__state_type __state_type; explicit future(const __state_type& __state) : _Base_type(__state) { } public: constexpr future() noexcept : _Base_type() { } /// Move constructor future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { } // Disable copying future(const future&) = delete; future& operator=(const future&) = delete; future& operator=(future&& __fut) noexcept { future(std::move(__fut))._M_swap(*this); return *this; } /// Retrieving the value void get() { typename _Base_type::_Reset __reset(*this); this->_M_get_result(); } shared_future share() noexcept; }; /// Primary template for shared_future. template class shared_future : public __basic_future<_Res> { typedef __basic_future<_Res> _Base_type; public: constexpr shared_future() noexcept : _Base_type() { } /// Copy constructor shared_future(const shared_future& __sf) noexcept : _Base_type(__sf) { } /// Construct from a future rvalue shared_future(future<_Res>&& __uf) noexcept : _Base_type(std::move(__uf)) { } /// Construct from a shared_future rvalue shared_future(shared_future&& __sf) noexcept : _Base_type(std::move(__sf)) { } shared_future& operator=(const shared_future& __sf) noexcept { shared_future(__sf)._M_swap(*this); return *this; } shared_future& operator=(shared_future&& __sf) noexcept { shared_future(std::move(__sf))._M_swap(*this); return *this; } /// Retrieving the value const _Res& get() const { return this->_M_get_result()._M_value(); } }; /// Partial specialization for shared_future template class shared_future<_Res&> : public __basic_future<_Res&> { typedef __basic_future<_Res&> _Base_type; public: constexpr shared_future() noexcept : _Base_type() { } /// Copy constructor shared_future(const shared_future& __sf) : _Base_type(__sf) { } /// Construct from a future rvalue shared_future(future<_Res&>&& __uf) noexcept : _Base_type(std::move(__uf)) { } /// Construct from a shared_future rvalue shared_future(shared_future&& __sf) noexcept : _Base_type(std::move(__sf)) { } shared_future& operator=(const shared_future& __sf) { shared_future(__sf)._M_swap(*this); return *this; } shared_future& operator=(shared_future&& __sf) noexcept { shared_future(std::move(__sf))._M_swap(*this); return *this; } /// Retrieving the value _Res& get() const { return this->_M_get_result()._M_get(); } }; /// Explicit specialization for shared_future template<> class shared_future : public __basic_future { typedef __basic_future _Base_type; public: constexpr shared_future() noexcept : _Base_type() { } /// Copy constructor shared_future(const shared_future& __sf) : _Base_type(__sf) { } /// Construct from a future rvalue shared_future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { } /// Construct from a shared_future rvalue shared_future(shared_future&& __sf) noexcept : _Base_type(std::move(__sf)) { } shared_future& operator=(const shared_future& __sf) { shared_future(__sf)._M_swap(*this); return *this; } shared_future& operator=(shared_future&& __sf) noexcept { shared_future(std::move(__sf))._M_swap(*this); return *this; } // Retrieving the value void get() const { this->_M_get_result(); } }; // Now we can define the protected __basic_future constructors. template inline __basic_future<_Res>:: __basic_future(const shared_future<_Res>& __sf) noexcept : _M_state(__sf._M_state) { } template inline __basic_future<_Res>:: __basic_future(shared_future<_Res>&& __sf) noexcept : _M_state(std::move(__sf._M_state)) { } template inline __basic_future<_Res>:: __basic_future(future<_Res>&& __uf) noexcept : _M_state(std::move(__uf._M_state)) { } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2556. Wide contract for future::share() template inline shared_future<_Res> future<_Res>::share() noexcept { return shared_future<_Res>(std::move(*this)); } template inline shared_future<_Res&> future<_Res&>::share() noexcept { return shared_future<_Res&>(std::move(*this)); } inline shared_future future::share() noexcept { return shared_future(std::move(*this)); } /// Primary template for promise template class promise { typedef __future_base::_State_base _State; typedef __future_base::_Result<_Res> _Res_type; typedef __future_base::_Ptr<_Res_type> _Ptr_type; template friend class _State::_Setter; friend _State; shared_ptr<_State> _M_future; _Ptr_type _M_storage; public: promise() : _M_future(std::make_shared<_State>()), _M_storage(new _Res_type()) { } promise(promise&& __rhs) noexcept : _M_future(std::move(__rhs._M_future)), _M_storage(std::move(__rhs._M_storage)) { } template promise(allocator_arg_t, const _Allocator& __a) : _M_future(std::allocate_shared<_State>(__a)), _M_storage(__future_base::_S_allocate_result<_Res>(__a)) { } template promise(allocator_arg_t, const _Allocator&, promise&& __rhs) : _M_future(std::move(__rhs._M_future)), _M_storage(std::move(__rhs._M_storage)) { } promise(const promise&) = delete; ~promise() { if (static_cast(_M_future) && !_M_future.unique()) _M_future->_M_break_promise(std::move(_M_storage)); } // Assignment promise& operator=(promise&& __rhs) noexcept { promise(std::move(__rhs)).swap(*this); return *this; } promise& operator=(const promise&) = delete; void swap(promise& __rhs) noexcept { _M_future.swap(__rhs._M_future); _M_storage.swap(__rhs._M_storage); } // Retrieving the result future<_Res> get_future() { return future<_Res>(_M_future); } // Setting the result void set_value(const _Res& __r) { _M_future->_M_set_result(_State::__setter(this, __r)); } void set_value(_Res&& __r) { _M_future->_M_set_result(_State::__setter(this, std::move(__r))); } void set_exception(exception_ptr __p) { _M_future->_M_set_result(_State::__setter(__p, this)); } void set_value_at_thread_exit(const _Res& __r) { _M_future->_M_set_delayed_result(_State::__setter(this, __r), _M_future); } void set_value_at_thread_exit(_Res&& __r) { _M_future->_M_set_delayed_result( _State::__setter(this, std::move(__r)), _M_future); } void set_exception_at_thread_exit(exception_ptr __p) { _M_future->_M_set_delayed_result(_State::__setter(__p, this), _M_future); } }; template inline void swap(promise<_Res>& __x, promise<_Res>& __y) noexcept { __x.swap(__y); } template struct uses_allocator, _Alloc> : public true_type { }; /// Partial specialization for promise template class promise<_Res&> { typedef __future_base::_State_base _State; typedef __future_base::_Result<_Res&> _Res_type; typedef __future_base::_Ptr<_Res_type> _Ptr_type; template friend class _State::_Setter; friend _State; shared_ptr<_State> _M_future; _Ptr_type _M_storage; public: promise() : _M_future(std::make_shared<_State>()), _M_storage(new _Res_type()) { } promise(promise&& __rhs) noexcept : _M_future(std::move(__rhs._M_future)), _M_storage(std::move(__rhs._M_storage)) { } template promise(allocator_arg_t, const _Allocator& __a) : _M_future(std::allocate_shared<_State>(__a)), _M_storage(__future_base::_S_allocate_result<_Res&>(__a)) { } template promise(allocator_arg_t, const _Allocator&, promise&& __rhs) : _M_future(std::move(__rhs._M_future)), _M_storage(std::move(__rhs._M_storage)) { } promise(const promise&) = delete; ~promise() { if (static_cast(_M_future) && !_M_future.unique()) _M_future->_M_break_promise(std::move(_M_storage)); } // Assignment promise& operator=(promise&& __rhs) noexcept { promise(std::move(__rhs)).swap(*this); return *this; } promise& operator=(const promise&) = delete; void swap(promise& __rhs) noexcept { _M_future.swap(__rhs._M_future); _M_storage.swap(__rhs._M_storage); } // Retrieving the result future<_Res&> get_future() { return future<_Res&>(_M_future); } // Setting the result void set_value(_Res& __r) { _M_future->_M_set_result(_State::__setter(this, __r)); } void set_exception(exception_ptr __p) { _M_future->_M_set_result(_State::__setter(__p, this)); } void set_value_at_thread_exit(_Res& __r) { _M_future->_M_set_delayed_result(_State::__setter(this, __r), _M_future); } void set_exception_at_thread_exit(exception_ptr __p) { _M_future->_M_set_delayed_result(_State::__setter(__p, this), _M_future); } }; /// Explicit specialization for promise template<> class promise { typedef __future_base::_State_base _State; typedef __future_base::_Result _Res_type; typedef __future_base::_Ptr<_Res_type> _Ptr_type; template friend class _State::_Setter; friend _State; shared_ptr<_State> _M_future; _Ptr_type _M_storage; public: promise() : _M_future(std::make_shared<_State>()), _M_storage(new _Res_type()) { } promise(promise&& __rhs) noexcept : _M_future(std::move(__rhs._M_future)), _M_storage(std::move(__rhs._M_storage)) { } template promise(allocator_arg_t, const _Allocator& __a) : _M_future(std::allocate_shared<_State>(__a)), _M_storage(__future_base::_S_allocate_result(__a)) { } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2095. missing constructors needed for uses-allocator construction template promise(allocator_arg_t, const _Allocator&, promise&& __rhs) : _M_future(std::move(__rhs._M_future)), _M_storage(std::move(__rhs._M_storage)) { } promise(const promise&) = delete; ~promise() { if (static_cast(_M_future) && !_M_future.unique()) _M_future->_M_break_promise(std::move(_M_storage)); } // Assignment promise& operator=(promise&& __rhs) noexcept { promise(std::move(__rhs)).swap(*this); return *this; } promise& operator=(const promise&) = delete; void swap(promise& __rhs) noexcept { _M_future.swap(__rhs._M_future); _M_storage.swap(__rhs._M_storage); } // Retrieving the result future get_future() { return future(_M_future); } // Setting the result void set_value() { _M_future->_M_set_result(_State::__setter(this)); } void set_exception(exception_ptr __p) { _M_future->_M_set_result(_State::__setter(__p, this)); } void set_value_at_thread_exit() { _M_future->_M_set_delayed_result(_State::__setter(this), _M_future); } void set_exception_at_thread_exit(exception_ptr __p) { _M_future->_M_set_delayed_result(_State::__setter(__p, this), _M_future); } }; template struct __future_base::_Task_setter { // Invoke the function and provide the result to the caller. _Ptr_type operator()() const { __try { (*_M_result)->_M_set((*_M_fn)()); } __catch(const __cxxabiv1::__forced_unwind&) { __throw_exception_again; // will cause broken_promise } __catch(...) { (*_M_result)->_M_error = current_exception(); } return std::move(*_M_result); } _Ptr_type* _M_result; _Fn* _M_fn; }; template struct __future_base::_Task_setter<_Ptr_type, _Fn, void> { _Ptr_type operator()() const { __try { (*_M_fn)(); } __catch(const __cxxabiv1::__forced_unwind&) { __throw_exception_again; // will cause broken_promise } __catch(...) { (*_M_result)->_M_error = current_exception(); } return std::move(*_M_result); } _Ptr_type* _M_result; _Fn* _M_fn; }; // Holds storage for a packaged_task's result. template struct __future_base::_Task_state_base<_Res(_Args...)> : __future_base::_State_base { typedef _Res _Res_type; template _Task_state_base(const _Alloc& __a) : _M_result(_S_allocate_result<_Res>(__a)) { } // Invoke the stored task and make the state ready. virtual void _M_run(_Args&&... __args) = 0; // Invoke the stored task and make the state ready at thread exit. virtual void _M_run_delayed(_Args&&... __args, weak_ptr<_State_base>) = 0; virtual shared_ptr<_Task_state_base> _M_reset() = 0; typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type; _Ptr_type _M_result; }; // Holds a packaged_task's stored task. template struct __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)> final : __future_base::_Task_state_base<_Res(_Args...)> { template _Task_state(_Fn2&& __fn, const _Alloc& __a) : _Task_state_base<_Res(_Args...)>(__a), _M_impl(std::forward<_Fn2>(__fn), __a) { } private: virtual void _M_run(_Args&&... __args) { auto __boundfn = [&] () -> typename result_of<_Fn&(_Args&&...)>::type { return std::__invoke(_M_impl._M_fn, std::forward<_Args>(__args)...); }; this->_M_set_result(_S_task_setter(this->_M_result, __boundfn)); } virtual void _M_run_delayed(_Args&&... __args, weak_ptr<_State_base> __self) { auto __boundfn = [&] () -> typename result_of<_Fn&(_Args&&...)>::type { return std::__invoke(_M_impl._M_fn, std::forward<_Args>(__args)...); }; this->_M_set_delayed_result(_S_task_setter(this->_M_result, __boundfn), std::move(__self)); } virtual shared_ptr<_Task_state_base<_Res(_Args...)>> _M_reset(); struct _Impl : _Alloc { template _Impl(_Fn2&& __fn, const _Alloc& __a) : _Alloc(__a), _M_fn(std::forward<_Fn2>(__fn)) { } _Fn _M_fn; } _M_impl; }; template static shared_ptr<__future_base::_Task_state_base<_Signature>> __create_task_state(_Fn&& __fn, const _Alloc& __a) { typedef typename decay<_Fn>::type _Fn2; typedef __future_base::_Task_state<_Fn2, _Alloc, _Signature> _State; return std::allocate_shared<_State>(__a, std::forward<_Fn>(__fn), __a); } template shared_ptr<__future_base::_Task_state_base<_Res(_Args...)>> __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)>::_M_reset() { return __create_task_state<_Res(_Args...)>(std::move(_M_impl._M_fn), static_cast<_Alloc&>(_M_impl)); } template::type>::value> struct __constrain_pkgdtask { typedef void __type; }; template struct __constrain_pkgdtask<_Task, _Fn, true> { }; /// packaged_task template class packaged_task<_Res(_ArgTypes...)> { typedef __future_base::_Task_state_base<_Res(_ArgTypes...)> _State_type; shared_ptr<_State_type> _M_state; public: // Construction and destruction packaged_task() noexcept { } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2095. missing constructors needed for uses-allocator construction template packaged_task(allocator_arg_t, const _Allocator& __a) noexcept { } template::__type> explicit packaged_task(_Fn&& __fn) : packaged_task(allocator_arg, std::allocator(), std::forward<_Fn>(__fn)) { } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2097. packaged_task constructors should be constrained // 2407. [this constructor should not be] explicit template::__type> packaged_task(allocator_arg_t, const _Alloc& __a, _Fn&& __fn) : _M_state(__create_task_state<_Res(_ArgTypes...)>( std::forward<_Fn>(__fn), __a)) { } ~packaged_task() { if (static_cast(_M_state) && !_M_state.unique()) _M_state->_M_break_promise(std::move(_M_state->_M_result)); } // No copy packaged_task(const packaged_task&) = delete; packaged_task& operator=(const packaged_task&) = delete; template packaged_task(allocator_arg_t, const _Allocator&, const packaged_task&) = delete; // Move support packaged_task(packaged_task&& __other) noexcept { this->swap(__other); } template packaged_task(allocator_arg_t, const _Allocator&, packaged_task&& __other) noexcept { this->swap(__other); } packaged_task& operator=(packaged_task&& __other) noexcept { packaged_task(std::move(__other)).swap(*this); return *this; } void swap(packaged_task& __other) noexcept { _M_state.swap(__other._M_state); } bool valid() const noexcept { return static_cast(_M_state); } // Result retrieval future<_Res> get_future() { return future<_Res>(_M_state); } // Execution void operator()(_ArgTypes... __args) { __future_base::_State_base::_S_check(_M_state); _M_state->_M_run(std::forward<_ArgTypes>(__args)...); } void make_ready_at_thread_exit(_ArgTypes... __args) { __future_base::_State_base::_S_check(_M_state); _M_state->_M_run_delayed(std::forward<_ArgTypes>(__args)..., _M_state); } void reset() { __future_base::_State_base::_S_check(_M_state); packaged_task __tmp; __tmp._M_state = _M_state; _M_state = _M_state->_M_reset(); } }; /// swap template inline void swap(packaged_task<_Res(_ArgTypes...)>& __x, packaged_task<_Res(_ArgTypes...)>& __y) noexcept { __x.swap(__y); } template struct uses_allocator, _Alloc> : public true_type { }; // Shared state created by std::async(). // Holds a deferred function and storage for its result. template class __future_base::_Deferred_state final : public __future_base::_State_base { public: explicit _Deferred_state(_BoundFn&& __fn) : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn)) { } private: typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type; _Ptr_type _M_result; _BoundFn _M_fn; // Run the deferred function. virtual void _M_complete_async() { // Multiple threads can call a waiting function on the future and // reach this point at the same time. The call_once in _M_set_result // ensures only the first one run the deferred function, stores the // result in _M_result, swaps that with the base _M_result and makes // the state ready. Tell _M_set_result to ignore failure so all later // calls do nothing. _M_set_result(_S_task_setter(_M_result, _M_fn), true); } // Caller should check whether the state is ready first, because this // function will return true even after the deferred function has run. virtual bool _M_is_deferred_future() const { return true; } }; // Common functionality hoisted out of the _Async_state_impl template. class __future_base::_Async_state_commonV2 : public __future_base::_State_base { protected: ~_Async_state_commonV2() = default; // Make waiting functions block until the thread completes, as if joined. // // This function is used by wait() to satisfy the first requirement below // and by wait_for() / wait_until() to satisfy the second. // // [futures.async]: // // — a call to a waiting function on an asynchronous return object that // shares the shared state created by this async call shall block until // the associated thread has completed, as if joined, or else time out. // // — the associated thread completion synchronizes with the return from // the first function that successfully detects the ready status of the // shared state or with the return from the last function that releases // the shared state, whichever happens first. virtual void _M_complete_async() { _M_join(); } void _M_join() { std::call_once(_M_once, &thread::join, &_M_thread); } thread _M_thread; once_flag _M_once; }; // Shared state created by std::async(). // Starts a new thread that runs a function and makes the shared state ready. template class __future_base::_Async_state_impl final : public __future_base::_Async_state_commonV2 { public: explicit _Async_state_impl(_BoundFn&& __fn) : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn)) { _M_thread = std::thread{ [this] { __try { _M_set_result(_S_task_setter(_M_result, _M_fn)); } __catch (const __cxxabiv1::__forced_unwind&) { // make the shared state ready on thread cancellation if (static_cast(_M_result)) this->_M_break_promise(std::move(_M_result)); __throw_exception_again; } } }; } // Must not destroy _M_result and _M_fn until the thread finishes. // Call join() directly rather than through _M_join() because no other // thread can be referring to this state if it is being destroyed. ~_Async_state_impl() { if (_M_thread.joinable()) _M_thread.join(); } private: typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type; _Ptr_type _M_result; _BoundFn _M_fn; }; template inline std::shared_ptr<__future_base::_State_base> __future_base::_S_make_deferred_state(_BoundFn&& __fn) { typedef typename remove_reference<_BoundFn>::type __fn_type; typedef _Deferred_state<__fn_type> __state_type; return std::make_shared<__state_type>(std::move(__fn)); } template inline std::shared_ptr<__future_base::_State_base> __future_base::_S_make_async_state(_BoundFn&& __fn) { typedef typename remove_reference<_BoundFn>::type __fn_type; typedef _Async_state_impl<__fn_type> __state_type; return std::make_shared<__state_type>(std::move(__fn)); } /// async template future<__async_result_of<_Fn, _Args...>> async(launch __policy, _Fn&& __fn, _Args&&... __args) { std::shared_ptr<__future_base::_State_base> __state; if ((__policy & launch::async) == launch::async) { __try { __state = __future_base::_S_make_async_state( std::thread::__make_invoker(std::forward<_Fn>(__fn), std::forward<_Args>(__args)...) ); } #if __cpp_exceptions catch(const system_error& __e) { if (__e.code() != errc::resource_unavailable_try_again || (__policy & launch::deferred) != launch::deferred) throw; } #endif } if (!__state) { __state = __future_base::_S_make_deferred_state( std::thread::__make_invoker(std::forward<_Fn>(__fn), std::forward<_Args>(__args)...)); } return future<__async_result_of<_Fn, _Args...>>(__state); } /// async, potential overload template inline future<__async_result_of<_Fn, _Args...>> async(_Fn&& __fn, _Args&&... __args) { return std::async(launch::async|launch::deferred, std::forward<_Fn>(__fn), std::forward<_Args>(__args)...); } #endif // _GLIBCXX_ASYNC_ABI_COMPAT #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1 // @} group futures _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // C++11 #endif // _GLIBCXX_FUTURE PK!| 8/initializer_listnu[// std::initializer_list support -*- C++ -*- // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of GCC. // // GCC is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3, or (at your option) // any later version. // // GCC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file initializer_list * This is a Standard C++ Library header. */ #ifndef _INITIALIZER_LIST #define _INITIALIZER_LIST #pragma GCC system_header #if __cplusplus < 201103L # include #else // C++0x #pragma GCC visibility push(default) #include namespace std { /// initializer_list template class initializer_list { public: typedef _E value_type; typedef const _E& reference; typedef const _E& const_reference; typedef size_t size_type; typedef const _E* iterator; typedef const _E* const_iterator; private: iterator _M_array; size_type _M_len; // The compiler can call a private constructor. constexpr initializer_list(const_iterator __a, size_type __l) : _M_array(__a), _M_len(__l) { } public: constexpr initializer_list() noexcept : _M_array(0), _M_len(0) { } // Number of elements. constexpr size_type size() const noexcept { return _M_len; } // First element. constexpr const_iterator begin() const noexcept { return _M_array; } // One past the last element. constexpr const_iterator end() const noexcept { return begin() + size(); } }; /** * @brief Return an iterator pointing to the first element of * the initializer_list. * @param __ils Initializer list. */ template constexpr const _Tp* begin(initializer_list<_Tp> __ils) noexcept { return __ils.begin(); } /** * @brief Return an iterator pointing to one past the last element * of the initializer_list. * @param __ils Initializer list. */ template constexpr const _Tp* end(initializer_list<_Tp> __ils) noexcept { return __ils.end(); } } #pragma GCC visibility pop #endif // C++11 #endif // _INITIALIZER_LIST PK!8AA8/iosnu[// Iostreams base classes -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/ios * This is a Standard C++ Library header. */ // // ISO C++ 14882: 27.4 Iostreams base classes // #ifndef _GLIBCXX_IOS #define _GLIBCXX_IOS 1 #pragma GCC system_header #include #include // For ios_base::failure #include // For char_traits, streamoff, streamsize, fpos #include // For class locale #include // For ios_base declarations. #include #include #endif /* _GLIBCXX_IOS */ PK!z7y 8/iostreamnu[// Standard iostream objects -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/iostream * This is a Standard C++ Library header. */ // // ISO C++ 14882: 27.3 Standard iostream objects // #ifndef _GLIBCXX_IOSTREAM #define _GLIBCXX_IOSTREAM 1 #pragma GCC system_header #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @name Standard Stream Objects * * The <iostream> header declares the eight standard stream * objects. For other declarations, see * http://gcc.gnu.org/onlinedocs/libstdc++/manual/io.html * and the @link iosfwd I/O forward declarations @endlink * * They are required by default to cooperate with the global C * library's @c FILE streams, and to be available during program * startup and termination. For more information, see the section of the * manual linked to above. */ //@{ extern istream cin; /// Linked to standard input extern ostream cout; /// Linked to standard output extern ostream cerr; /// Linked to standard error (unbuffered) extern ostream clog; /// Linked to standard error (buffered) #ifdef _GLIBCXX_USE_WCHAR_T extern wistream wcin; /// Linked to standard input extern wostream wcout; /// Linked to standard output extern wostream wcerr; /// Linked to standard error (unbuffered) extern wostream wclog; /// Linked to standard error (buffered) #endif //@} // For construction of filebuffers for cout, cin, cerr, clog et. al. static ios_base::Init __ioinit; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _GLIBCXX_IOSTREAM */ PK!@KK8/shared_mutexnu[// -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/shared_mutex * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_SHARED_MUTEX #define _GLIBCXX_SHARED_MUTEX 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @ingroup mutexes * @{ */ #ifdef _GLIBCXX_USE_C99_STDINT_TR1 #ifdef _GLIBCXX_HAS_GTHREADS #if __cplusplus >= 201703L #define __cpp_lib_shared_mutex 201505 class shared_mutex; #endif #define __cpp_lib_shared_timed_mutex 201402 class shared_timed_mutex; #if _GLIBCXX_USE_PTHREAD_RWLOCK_T /// A shared mutex type implemented using pthread_rwlock_t. class __shared_mutex_pthread { friend class shared_timed_mutex; #ifdef PTHREAD_RWLOCK_INITIALIZER pthread_rwlock_t _M_rwlock = PTHREAD_RWLOCK_INITIALIZER; public: __shared_mutex_pthread() = default; ~__shared_mutex_pthread() = default; #else pthread_rwlock_t _M_rwlock; public: __shared_mutex_pthread() { int __ret = pthread_rwlock_init(&_M_rwlock, NULL); if (__ret == ENOMEM) __throw_bad_alloc(); else if (__ret == EAGAIN) __throw_system_error(int(errc::resource_unavailable_try_again)); else if (__ret == EPERM) __throw_system_error(int(errc::operation_not_permitted)); // Errors not handled: EBUSY, EINVAL __glibcxx_assert(__ret == 0); } ~__shared_mutex_pthread() { int __ret __attribute((__unused__)) = pthread_rwlock_destroy(&_M_rwlock); // Errors not handled: EBUSY, EINVAL __glibcxx_assert(__ret == 0); } #endif __shared_mutex_pthread(const __shared_mutex_pthread&) = delete; __shared_mutex_pthread& operator=(const __shared_mutex_pthread&) = delete; void lock() { int __ret = pthread_rwlock_wrlock(&_M_rwlock); if (__ret == EDEADLK) __throw_system_error(int(errc::resource_deadlock_would_occur)); // Errors not handled: EINVAL __glibcxx_assert(__ret == 0); } bool try_lock() { int __ret = pthread_rwlock_trywrlock(&_M_rwlock); if (__ret == EBUSY) return false; // Errors not handled: EINVAL __glibcxx_assert(__ret == 0); return true; } void unlock() { int __ret __attribute((__unused__)) = pthread_rwlock_unlock(&_M_rwlock); // Errors not handled: EPERM, EBUSY, EINVAL __glibcxx_assert(__ret == 0); } // Shared ownership void lock_shared() { int __ret; // We retry if we exceeded the maximum number of read locks supported by // the POSIX implementation; this can result in busy-waiting, but this // is okay based on the current specification of forward progress // guarantees by the standard. do __ret = pthread_rwlock_rdlock(&_M_rwlock); while (__ret == EAGAIN); if (__ret == EDEADLK) __throw_system_error(int(errc::resource_deadlock_would_occur)); // Errors not handled: EINVAL __glibcxx_assert(__ret == 0); } bool try_lock_shared() { int __ret = pthread_rwlock_tryrdlock(&_M_rwlock); // If the maximum number of read locks has been exceeded, we just fail // to acquire the lock. Unlike for lock(), we are not allowed to throw // an exception. if (__ret == EBUSY || __ret == EAGAIN) return false; // Errors not handled: EINVAL __glibcxx_assert(__ret == 0); return true; } void unlock_shared() { unlock(); } void* native_handle() { return &_M_rwlock; } }; #endif #if ! (_GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK) /// A shared mutex type implemented using std::condition_variable. class __shared_mutex_cv { friend class shared_timed_mutex; // Based on Howard Hinnant's reference implementation from N2406. // The high bit of _M_state is the write-entered flag which is set to // indicate a writer has taken the lock or is queuing to take the lock. // The remaining bits are the count of reader locks. // // To take a reader lock, block on gate1 while the write-entered flag is // set or the maximum number of reader locks is held, then increment the // reader lock count. // To release, decrement the count, then if the write-entered flag is set // and the count is zero then signal gate2 to wake a queued writer, // otherwise if the maximum number of reader locks was held signal gate1 // to wake a reader. // // To take a writer lock, block on gate1 while the write-entered flag is // set, then set the write-entered flag to start queueing, then block on // gate2 while the number of reader locks is non-zero. // To release, unset the write-entered flag and signal gate1 to wake all // blocked readers and writers. // // This means that when no reader locks are held readers and writers get // equal priority. When one or more reader locks is held a writer gets // priority and no more reader locks can be taken while the writer is // queued. // Only locked when accessing _M_state or waiting on condition variables. mutex _M_mut; // Used to block while write-entered is set or reader count at maximum. condition_variable _M_gate1; // Used to block queued writers while reader count is non-zero. condition_variable _M_gate2; // The write-entered flag and reader count. unsigned _M_state; static constexpr unsigned _S_write_entered = 1U << (sizeof(unsigned)*__CHAR_BIT__ - 1); static constexpr unsigned _S_max_readers = ~_S_write_entered; // Test whether the write-entered flag is set. _M_mut must be locked. bool _M_write_entered() const { return _M_state & _S_write_entered; } // The number of reader locks currently held. _M_mut must be locked. unsigned _M_readers() const { return _M_state & _S_max_readers; } public: __shared_mutex_cv() : _M_state(0) {} ~__shared_mutex_cv() { __glibcxx_assert( _M_state == 0 ); } __shared_mutex_cv(const __shared_mutex_cv&) = delete; __shared_mutex_cv& operator=(const __shared_mutex_cv&) = delete; // Exclusive ownership void lock() { unique_lock __lk(_M_mut); // Wait until we can set the write-entered flag. _M_gate1.wait(__lk, [=]{ return !_M_write_entered(); }); _M_state |= _S_write_entered; // Then wait until there are no more readers. _M_gate2.wait(__lk, [=]{ return _M_readers() == 0; }); } bool try_lock() { unique_lock __lk(_M_mut, try_to_lock); if (__lk.owns_lock() && _M_state == 0) { _M_state = _S_write_entered; return true; } return false; } void unlock() { lock_guard __lk(_M_mut); __glibcxx_assert( _M_write_entered() ); _M_state = 0; // call notify_all() while mutex is held so that another thread can't // lock and unlock the mutex then destroy *this before we make the call. _M_gate1.notify_all(); } // Shared ownership void lock_shared() { unique_lock __lk(_M_mut); _M_gate1.wait(__lk, [=]{ return _M_state < _S_max_readers; }); ++_M_state; } bool try_lock_shared() { unique_lock __lk(_M_mut, try_to_lock); if (!__lk.owns_lock()) return false; if (_M_state < _S_max_readers) { ++_M_state; return true; } return false; } void unlock_shared() { lock_guard __lk(_M_mut); __glibcxx_assert( _M_readers() > 0 ); auto __prev = _M_state--; if (_M_write_entered()) { // Wake the queued writer if there are no more readers. if (_M_readers() == 0) _M_gate2.notify_one(); // No need to notify gate1 because we give priority to the queued // writer, and that writer will eventually notify gate1 after it // clears the write-entered flag. } else { // Wake any thread that was blocked on reader overflow. if (__prev == _S_max_readers) _M_gate1.notify_one(); } } }; #endif #if __cplusplus > 201402L /// The standard shared mutex type. class shared_mutex { public: shared_mutex() = default; ~shared_mutex() = default; shared_mutex(const shared_mutex&) = delete; shared_mutex& operator=(const shared_mutex&) = delete; // Exclusive ownership void lock() { _M_impl.lock(); } bool try_lock() { return _M_impl.try_lock(); } void unlock() { _M_impl.unlock(); } // Shared ownership void lock_shared() { _M_impl.lock_shared(); } bool try_lock_shared() { return _M_impl.try_lock_shared(); } void unlock_shared() { _M_impl.unlock_shared(); } #if _GLIBCXX_USE_PTHREAD_RWLOCK_T typedef void* native_handle_type; native_handle_type native_handle() { return _M_impl.native_handle(); } private: __shared_mutex_pthread _M_impl; #else private: __shared_mutex_cv _M_impl; #endif }; #endif // C++17 #if _GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK using __shared_timed_mutex_base = __shared_mutex_pthread; #else using __shared_timed_mutex_base = __shared_mutex_cv; #endif /// The standard shared timed mutex type. class shared_timed_mutex : private __shared_timed_mutex_base { using _Base = __shared_timed_mutex_base; // Must use the same clock as condition_variable for __shared_mutex_cv. typedef chrono::system_clock __clock_t; public: shared_timed_mutex() = default; ~shared_timed_mutex() = default; shared_timed_mutex(const shared_timed_mutex&) = delete; shared_timed_mutex& operator=(const shared_timed_mutex&) = delete; // Exclusive ownership void lock() { _Base::lock(); } bool try_lock() { return _Base::try_lock(); } void unlock() { _Base::unlock(); } template bool try_lock_for(const chrono::duration<_Rep, _Period>& __rel_time) { return try_lock_until(__clock_t::now() + __rel_time); } // Shared ownership void lock_shared() { _Base::lock_shared(); } bool try_lock_shared() { return _Base::try_lock_shared(); } void unlock_shared() { _Base::unlock_shared(); } template bool try_lock_shared_for(const chrono::duration<_Rep, _Period>& __rel_time) { return try_lock_shared_until(__clock_t::now() + __rel_time); } #if _GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK // Exclusive ownership template bool try_lock_until(const chrono::time_point<__clock_t, _Duration>& __atime) { auto __s = chrono::time_point_cast(__atime); auto __ns = chrono::duration_cast(__atime - __s); __gthread_time_t __ts = { static_cast(__s.time_since_epoch().count()), static_cast(__ns.count()) }; int __ret = pthread_rwlock_timedwrlock(&_M_rwlock, &__ts); // On self-deadlock, we just fail to acquire the lock. Technically, // the program violated the precondition. if (__ret == ETIMEDOUT || __ret == EDEADLK) return false; // Errors not handled: EINVAL __glibcxx_assert(__ret == 0); return true; } template bool try_lock_until(const chrono::time_point<_Clock, _Duration>& __abs_time) { // DR 887 - Sync unknown clock to known clock. const typename _Clock::time_point __c_entry = _Clock::now(); const __clock_t::time_point __s_entry = __clock_t::now(); const auto __delta = __abs_time - __c_entry; const auto __s_atime = __s_entry + __delta; return try_lock_until(__s_atime); } // Shared ownership template bool try_lock_shared_until(const chrono::time_point<__clock_t, _Duration>& __atime) { auto __s = chrono::time_point_cast(__atime); auto __ns = chrono::duration_cast(__atime - __s); __gthread_time_t __ts = { static_cast(__s.time_since_epoch().count()), static_cast(__ns.count()) }; int __ret; // Unlike for lock(), we are not allowed to throw an exception so if // the maximum number of read locks has been exceeded, or we would // deadlock, we just try to acquire the lock again (and will time out // eventually). // In cases where we would exceed the maximum number of read locks // throughout the whole time until the timeout, we will fail to // acquire the lock even if it would be logically free; however, this // is allowed by the standard, and we made a "strong effort" // (see C++14 30.4.1.4p26). // For cases where the implementation detects a deadlock we // intentionally block and timeout so that an early return isn't // mistaken for a spurious failure, which might help users realise // there is a deadlock. do __ret = pthread_rwlock_timedrdlock(&_M_rwlock, &__ts); while (__ret == EAGAIN || __ret == EDEADLK); if (__ret == ETIMEDOUT) return false; // Errors not handled: EINVAL __glibcxx_assert(__ret == 0); return true; } template bool try_lock_shared_until(const chrono::time_point<_Clock, _Duration>& __abs_time) { // DR 887 - Sync unknown clock to known clock. const typename _Clock::time_point __c_entry = _Clock::now(); const __clock_t::time_point __s_entry = __clock_t::now(); const auto __delta = __abs_time - __c_entry; const auto __s_atime = __s_entry + __delta; return try_lock_shared_until(__s_atime); } #else // ! (_GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK) // Exclusive ownership template bool try_lock_until(const chrono::time_point<_Clock, _Duration>& __abs_time) { unique_lock __lk(_M_mut); if (!_M_gate1.wait_until(__lk, __abs_time, [=]{ return !_M_write_entered(); })) { return false; } _M_state |= _S_write_entered; if (!_M_gate2.wait_until(__lk, __abs_time, [=]{ return _M_readers() == 0; })) { _M_state ^= _S_write_entered; // Wake all threads blocked while the write-entered flag was set. _M_gate1.notify_all(); return false; } return true; } // Shared ownership template bool try_lock_shared_until(const chrono::time_point<_Clock, _Duration>& __abs_time) { unique_lock __lk(_M_mut); if (!_M_gate1.wait_until(__lk, __abs_time, [=]{ return _M_state < _S_max_readers; })) { return false; } ++_M_state; return true; } #endif // _GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK }; #endif // _GLIBCXX_HAS_GTHREADS /// shared_lock template class shared_lock { public: typedef _Mutex mutex_type; // Shared locking shared_lock() noexcept : _M_pm(nullptr), _M_owns(false) { } explicit shared_lock(mutex_type& __m) : _M_pm(std::__addressof(__m)), _M_owns(true) { __m.lock_shared(); } shared_lock(mutex_type& __m, defer_lock_t) noexcept : _M_pm(std::__addressof(__m)), _M_owns(false) { } shared_lock(mutex_type& __m, try_to_lock_t) : _M_pm(std::__addressof(__m)), _M_owns(__m.try_lock_shared()) { } shared_lock(mutex_type& __m, adopt_lock_t) : _M_pm(std::__addressof(__m)), _M_owns(true) { } template shared_lock(mutex_type& __m, const chrono::time_point<_Clock, _Duration>& __abs_time) : _M_pm(std::__addressof(__m)), _M_owns(__m.try_lock_shared_until(__abs_time)) { } template shared_lock(mutex_type& __m, const chrono::duration<_Rep, _Period>& __rel_time) : _M_pm(std::__addressof(__m)), _M_owns(__m.try_lock_shared_for(__rel_time)) { } ~shared_lock() { if (_M_owns) _M_pm->unlock_shared(); } shared_lock(shared_lock const&) = delete; shared_lock& operator=(shared_lock const&) = delete; shared_lock(shared_lock&& __sl) noexcept : shared_lock() { swap(__sl); } shared_lock& operator=(shared_lock&& __sl) noexcept { shared_lock(std::move(__sl)).swap(*this); return *this; } void lock() { _M_lockable(); _M_pm->lock_shared(); _M_owns = true; } bool try_lock() { _M_lockable(); return _M_owns = _M_pm->try_lock_shared(); } template bool try_lock_for(const chrono::duration<_Rep, _Period>& __rel_time) { _M_lockable(); return _M_owns = _M_pm->try_lock_shared_for(__rel_time); } template bool try_lock_until(const chrono::time_point<_Clock, _Duration>& __abs_time) { _M_lockable(); return _M_owns = _M_pm->try_lock_shared_until(__abs_time); } void unlock() { if (!_M_owns) __throw_system_error(int(errc::resource_deadlock_would_occur)); _M_pm->unlock_shared(); _M_owns = false; } // Setters void swap(shared_lock& __u) noexcept { std::swap(_M_pm, __u._M_pm); std::swap(_M_owns, __u._M_owns); } mutex_type* release() noexcept { _M_owns = false; return std::exchange(_M_pm, nullptr); } // Getters bool owns_lock() const noexcept { return _M_owns; } explicit operator bool() const noexcept { return _M_owns; } mutex_type* mutex() const noexcept { return _M_pm; } private: void _M_lockable() const { if (_M_pm == nullptr) __throw_system_error(int(errc::operation_not_permitted)); if (_M_owns) __throw_system_error(int(errc::resource_deadlock_would_occur)); } mutex_type* _M_pm; bool _M_owns; }; /// Swap specialization for shared_lock template void swap(shared_lock<_Mutex>& __x, shared_lock<_Mutex>& __y) noexcept { __x.swap(__y); } #endif // _GLIBCXX_USE_C99_STDINT_TR1 // @} group mutexes _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // C++14 #endif // _GLIBCXX_SHARED_MUTEX PK!N'' 8/stdexceptnu[// Standard exception classes -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/stdexcept * This is a Standard C++ Library header. */ // // ISO C++ 19.1 Exception classes // #ifndef _GLIBCXX_STDEXCEPT #define _GLIBCXX_STDEXCEPT 1 #pragma GCC system_header #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if _GLIBCXX_USE_DUAL_ABI #if _GLIBCXX_USE_CXX11_ABI // Emulates an old COW string when the new std::string is in use. struct __cow_string { union { const char* _M_p; char _M_bytes[sizeof(const char*)]; }; __cow_string(); __cow_string(const std::string&); __cow_string(const char*, size_t); __cow_string(const __cow_string&) _GLIBCXX_USE_NOEXCEPT; __cow_string& operator=(const __cow_string&) _GLIBCXX_USE_NOEXCEPT; ~__cow_string(); #if __cplusplus >= 201103L __cow_string(__cow_string&&) noexcept; __cow_string& operator=(__cow_string&&) noexcept; #endif }; typedef basic_string __sso_string; #else // _GLIBCXX_USE_CXX11_ABI typedef basic_string __cow_string; // Emulates a new SSO string when the old std::string is in use. struct __sso_string { struct __str { const char* _M_p; size_t _M_string_length; char _M_local_buf[16]; }; union { __str _M_s; char _M_bytes[sizeof(__str)]; }; __sso_string() _GLIBCXX_USE_NOEXCEPT; __sso_string(const std::string&); __sso_string(const char*, size_t); __sso_string(const __sso_string&); __sso_string& operator=(const __sso_string&); ~__sso_string(); #if __cplusplus >= 201103L __sso_string(__sso_string&&) noexcept; __sso_string& operator=(__sso_string&&) noexcept; #endif }; #endif // _GLIBCXX_USE_CXX11_ABI #else // _GLIBCXX_USE_DUAL_ABI typedef basic_string __sso_string; typedef basic_string __cow_string; #endif /** * @addtogroup exceptions * @{ */ /** Logic errors represent problems in the internal logic of a program; * in theory, these are preventable, and even detectable before the * program runs (e.g., violations of class invariants). * @brief One of two subclasses of exception. */ class logic_error : public exception { __cow_string _M_msg; public: /** Takes a character string describing the error. */ explicit logic_error(const string& __arg) _GLIBCXX_TXN_SAFE; #if __cplusplus >= 201103L explicit logic_error(const char*) _GLIBCXX_TXN_SAFE; #endif #if _GLIBCXX_USE_CXX11_ABI || _GLIBCXX_DEFINE_STDEXCEPT_COPY_OPS logic_error(const logic_error&) _GLIBCXX_USE_NOEXCEPT; logic_error& operator=(const logic_error&) _GLIBCXX_USE_NOEXCEPT; #endif virtual ~logic_error() _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT; /** Returns a C-style character string describing the general cause of * the current error (the same string passed to the ctor). */ virtual const char* what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT; # ifdef _GLIBCXX_TM_TS_INTERNAL friend void* ::_txnal_logic_error_get_msg(void* e); # endif }; /** Thrown by the library, or by you, to report domain errors (domain in * the mathematical sense). */ class domain_error : public logic_error { public: explicit domain_error(const string& __arg) _GLIBCXX_TXN_SAFE; #if __cplusplus >= 201103L explicit domain_error(const char*) _GLIBCXX_TXN_SAFE; #endif virtual ~domain_error() _GLIBCXX_USE_NOEXCEPT; }; /** Thrown to report invalid arguments to functions. */ class invalid_argument : public logic_error { public: explicit invalid_argument(const string& __arg) _GLIBCXX_TXN_SAFE; #if __cplusplus >= 201103L explicit invalid_argument(const char*) _GLIBCXX_TXN_SAFE; #endif virtual ~invalid_argument() _GLIBCXX_USE_NOEXCEPT; }; /** Thrown when an object is constructed that would exceed its maximum * permitted size (e.g., a basic_string instance). */ class length_error : public logic_error { public: explicit length_error(const string& __arg) _GLIBCXX_TXN_SAFE; #if __cplusplus >= 201103L explicit length_error(const char*) _GLIBCXX_TXN_SAFE; #endif virtual ~length_error() _GLIBCXX_USE_NOEXCEPT; }; /** This represents an argument whose value is not within the expected * range (e.g., boundary checks in basic_string). */ class out_of_range : public logic_error { public: explicit out_of_range(const string& __arg) _GLIBCXX_TXN_SAFE; #if __cplusplus >= 201103L explicit out_of_range(const char*) _GLIBCXX_TXN_SAFE; #endif virtual ~out_of_range() _GLIBCXX_USE_NOEXCEPT; }; /** Runtime errors represent problems outside the scope of a program; * they cannot be easily predicted and can generally only be caught as * the program executes. * @brief One of two subclasses of exception. */ class runtime_error : public exception { __cow_string _M_msg; public: /** Takes a character string describing the error. */ explicit runtime_error(const string& __arg) _GLIBCXX_TXN_SAFE; #if __cplusplus >= 201103L explicit runtime_error(const char*) _GLIBCXX_TXN_SAFE; #endif #if _GLIBCXX_USE_CXX11_ABI || _GLIBCXX_DEFINE_STDEXCEPT_COPY_OPS runtime_error(const runtime_error&) _GLIBCXX_USE_NOEXCEPT; runtime_error& operator=(const runtime_error&) _GLIBCXX_USE_NOEXCEPT; #endif virtual ~runtime_error() _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT; /** Returns a C-style character string describing the general cause of * the current error (the same string passed to the ctor). */ virtual const char* what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT; # ifdef _GLIBCXX_TM_TS_INTERNAL friend void* ::_txnal_runtime_error_get_msg(void* e); # endif }; /** Thrown to indicate range errors in internal computations. */ class range_error : public runtime_error { public: explicit range_error(const string& __arg) _GLIBCXX_TXN_SAFE; #if __cplusplus >= 201103L explicit range_error(const char*) _GLIBCXX_TXN_SAFE; #endif virtual ~range_error() _GLIBCXX_USE_NOEXCEPT; }; /** Thrown to indicate arithmetic overflow. */ class overflow_error : public runtime_error { public: explicit overflow_error(const string& __arg) _GLIBCXX_TXN_SAFE; #if __cplusplus >= 201103L explicit overflow_error(const char*) _GLIBCXX_TXN_SAFE; #endif virtual ~overflow_error() _GLIBCXX_USE_NOEXCEPT; }; /** Thrown to indicate arithmetic underflow. */ class underflow_error : public runtime_error { public: explicit underflow_error(const string& __arg) _GLIBCXX_TXN_SAFE; #if __cplusplus >= 201103L explicit underflow_error(const char*) _GLIBCXX_TXN_SAFE; #endif virtual ~underflow_error() _GLIBCXX_USE_NOEXCEPT; }; // @} group exceptions _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _GLIBCXX_STDEXCEPT */ PK!tS00 8/utilitynu[// -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file include/utility * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_UTILITY #define _GLIBCXX_UTILITY 1 #pragma GCC system_header /** * @defgroup utilities Utilities * * Components deemed generally useful. Includes pair, tuple, * forward/move helpers, ratio, function object, metaprogramming and * type traits, time, date, and memory functions. */ #include #include #include #if __cplusplus >= 201103L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /// Finds the size of a given tuple type. template struct tuple_size; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2313. tuple_size should always derive from integral_constant // 2770. tuple_size specialization is not SFINAE compatible template::type, typename = typename enable_if::value>::type, size_t = tuple_size<_Tp>::value> using __enable_if_has_tuple_size = _Tp; template struct tuple_size> : public tuple_size<_Tp> { }; template struct tuple_size> : public tuple_size<_Tp> { }; template struct tuple_size> : public tuple_size<_Tp> { }; /// Gives the type of the ith element of a given tuple type. template struct tuple_element; // Duplicate of C++14's tuple_element_t for internal use in C++11 mode template using __tuple_element_t = typename tuple_element<__i, _Tp>::type; template struct tuple_element<__i, const _Tp> { typedef typename add_const<__tuple_element_t<__i, _Tp>>::type type; }; template struct tuple_element<__i, volatile _Tp> { typedef typename add_volatile<__tuple_element_t<__i, _Tp>>::type type; }; template struct tuple_element<__i, const volatile _Tp> { typedef typename add_cv<__tuple_element_t<__i, _Tp>>::type type; }; #if __cplusplus > 201103L #define __cpp_lib_tuple_element_t 201402 template using tuple_element_t = typename tuple_element<__i, _Tp>::type; #endif // Various functions which give std::pair a tuple-like interface. /// Partial specialization for std::pair template struct __is_tuple_like_impl> : true_type { }; /// Partial specialization for std::pair template struct tuple_size> : public integral_constant { }; /// Partial specialization for std::pair template struct tuple_element<0, std::pair<_Tp1, _Tp2>> { typedef _Tp1 type; }; /// Partial specialization for std::pair template struct tuple_element<1, std::pair<_Tp1, _Tp2>> { typedef _Tp2 type; }; template struct __pair_get; template<> struct __pair_get<0> { template static constexpr _Tp1& __get(std::pair<_Tp1, _Tp2>& __pair) noexcept { return __pair.first; } template static constexpr _Tp1&& __move_get(std::pair<_Tp1, _Tp2>&& __pair) noexcept { return std::forward<_Tp1>(__pair.first); } template static constexpr const _Tp1& __const_get(const std::pair<_Tp1, _Tp2>& __pair) noexcept { return __pair.first; } template static constexpr const _Tp1&& __const_move_get(const std::pair<_Tp1, _Tp2>&& __pair) noexcept { return std::forward(__pair.first); } }; template<> struct __pair_get<1> { template static constexpr _Tp2& __get(std::pair<_Tp1, _Tp2>& __pair) noexcept { return __pair.second; } template static constexpr _Tp2&& __move_get(std::pair<_Tp1, _Tp2>&& __pair) noexcept { return std::forward<_Tp2>(__pair.second); } template static constexpr const _Tp2& __const_get(const std::pair<_Tp1, _Tp2>& __pair) noexcept { return __pair.second; } template static constexpr const _Tp2&& __const_move_get(const std::pair<_Tp1, _Tp2>&& __pair) noexcept { return std::forward(__pair.second); } }; template constexpr typename tuple_element<_Int, std::pair<_Tp1, _Tp2>>::type& get(std::pair<_Tp1, _Tp2>& __in) noexcept { return __pair_get<_Int>::__get(__in); } template constexpr typename tuple_element<_Int, std::pair<_Tp1, _Tp2>>::type&& get(std::pair<_Tp1, _Tp2>&& __in) noexcept { return __pair_get<_Int>::__move_get(std::move(__in)); } template constexpr const typename tuple_element<_Int, std::pair<_Tp1, _Tp2>>::type& get(const std::pair<_Tp1, _Tp2>& __in) noexcept { return __pair_get<_Int>::__const_get(__in); } template constexpr const typename tuple_element<_Int, std::pair<_Tp1, _Tp2>>::type&& get(const std::pair<_Tp1, _Tp2>&& __in) noexcept { return __pair_get<_Int>::__const_move_get(std::move(__in)); } #if __cplusplus > 201103L #define __cpp_lib_tuples_by_type 201304 template constexpr _Tp& get(pair<_Tp, _Up>& __p) noexcept { return __p.first; } template constexpr const _Tp& get(const pair<_Tp, _Up>& __p) noexcept { return __p.first; } template constexpr _Tp&& get(pair<_Tp, _Up>&& __p) noexcept { return std::move(__p.first); } template constexpr const _Tp&& get(const pair<_Tp, _Up>&& __p) noexcept { return std::move(__p.first); } template constexpr _Tp& get(pair<_Up, _Tp>& __p) noexcept { return __p.second; } template constexpr const _Tp& get(const pair<_Up, _Tp>& __p) noexcept { return __p.second; } template constexpr _Tp&& get(pair<_Up, _Tp>&& __p) noexcept { return std::move(__p.second); } template constexpr const _Tp&& get(const pair<_Up, _Tp>&& __p) noexcept { return std::move(__p.second); } #define __cpp_lib_exchange_function 201304 /// Assign @p __new_val to @p __obj and return its previous value. template inline _Tp exchange(_Tp& __obj, _Up&& __new_val) { return std::__exchange(__obj, std::forward<_Up>(__new_val)); } #endif // Stores a tuple of indices. Used by tuple and pair, and by bind() to // extract the elements in a tuple. template struct _Index_tuple { }; #ifdef __has_builtin # if __has_builtin(__make_integer_seq) # define _GLIBCXX_USE_MAKE_INTEGER_SEQ 1 # endif #endif // Builds an _Index_tuple<0, 1, 2, ..., _Num-1>. template struct _Build_index_tuple { #if _GLIBCXX_USE_MAKE_INTEGER_SEQ template using _IdxTuple = _Index_tuple<_Indices...>; using __type = __make_integer_seq<_IdxTuple, size_t, _Num>; #else using __type = _Index_tuple<__integer_pack(_Num)...>; #endif }; #if __cplusplus > 201103L #define __cpp_lib_integer_sequence 201304 /// Class template integer_sequence template struct integer_sequence { typedef _Tp value_type; static constexpr size_t size() noexcept { return sizeof...(_Idx); } }; /// Alias template make_integer_sequence template using make_integer_sequence #if _GLIBCXX_USE_MAKE_INTEGER_SEQ = __make_integer_seq; #else = integer_sequence<_Tp, __integer_pack(_Num)...>; #endif #undef _GLIBCXX_USE_MAKE_INTEGER_SEQ /// Alias template index_sequence template using index_sequence = integer_sequence; /// Alias template make_index_sequence template using make_index_sequence = make_integer_sequence; /// Alias template index_sequence_for template using index_sequence_for = make_index_sequence; #endif #if __cplusplus > 201402L struct in_place_t { explicit in_place_t() = default; }; inline constexpr in_place_t in_place{}; template struct in_place_type_t { explicit in_place_type_t() = default; }; template inline constexpr in_place_type_t<_Tp> in_place_type{}; template struct in_place_index_t { explicit in_place_index_t() = default; }; template inline constexpr in_place_index_t<_Idx> in_place_index{}; template struct __is_in_place_type_impl : false_type { }; template struct __is_in_place_type_impl> : true_type { }; template struct __is_in_place_type : public __is_in_place_type_impl<_Tp> { }; #define __cpp_lib_as_const 201510 template constexpr add_const_t<_Tp>& as_const(_Tp& __t) noexcept { return __t; } template void as_const(const _Tp&&) = delete; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif #endif /* _GLIBCXX_UTILITY */ PK!|;&J(( 8/debug/arraynu[// Debugging array implementation -*- C++ -*- // Copyright (C) 2012-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/array * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_DEBUG_ARRAY #define _GLIBCXX_DEBUG_ARRAY 1 #pragma GCC system_header #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { template struct array { typedef _Tp value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef value_type* iterator; typedef const value_type* const_iterator; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // Support for zero-sized arrays mandatory. typedef _GLIBCXX_STD_C::__array_traits<_Tp, _Nm> _AT_Type; typename _AT_Type::_Type _M_elems; template struct _Array_check_subscript { std::size_t size() { return _Size; } _Array_check_subscript(std::size_t __index) { __glibcxx_check_subscript(__index); } }; template struct _Array_check_nonempty { bool empty() { return _Size == 0; } _Array_check_nonempty() { __glibcxx_check_nonempty(); } }; // No explicit construct/copy/destroy for aggregate type. // DR 776. void fill(const value_type& __u) { std::fill_n(begin(), size(), __u); } void swap(array& __other) noexcept(_AT_Type::_Is_nothrow_swappable::value) { std::swap_ranges(begin(), end(), __other.begin()); } // Iterators. _GLIBCXX17_CONSTEXPR iterator begin() noexcept { return iterator(data()); } _GLIBCXX17_CONSTEXPR const_iterator begin() const noexcept { return const_iterator(data()); } _GLIBCXX17_CONSTEXPR iterator end() noexcept { return iterator(data() + _Nm); } _GLIBCXX17_CONSTEXPR const_iterator end() const noexcept { return const_iterator(data() + _Nm); } _GLIBCXX17_CONSTEXPR reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } _GLIBCXX17_CONSTEXPR const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); } _GLIBCXX17_CONSTEXPR reverse_iterator rend() noexcept { return reverse_iterator(begin()); } _GLIBCXX17_CONSTEXPR const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); } _GLIBCXX17_CONSTEXPR const_iterator cbegin() const noexcept { return const_iterator(data()); } _GLIBCXX17_CONSTEXPR const_iterator cend() const noexcept { return const_iterator(data() + _Nm); } _GLIBCXX17_CONSTEXPR const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } _GLIBCXX17_CONSTEXPR const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } // Capacity. constexpr size_type size() const noexcept { return _Nm; } constexpr size_type max_size() const noexcept { return _Nm; } constexpr bool empty() const noexcept { return size() == 0; } // Element access. _GLIBCXX17_CONSTEXPR reference operator[](size_type __n) noexcept { __glibcxx_check_subscript(__n); return _AT_Type::_S_ref(_M_elems, __n); } constexpr const_reference operator[](size_type __n) const noexcept { return __n < _Nm ? _AT_Type::_S_ref(_M_elems, __n) : (_GLIBCXX_THROW_OR_ABORT(_Array_check_subscript<_Nm>(__n)), _AT_Type::_S_ref(_M_elems, 0)); } _GLIBCXX17_CONSTEXPR reference at(size_type __n) { if (__n >= _Nm) std::__throw_out_of_range_fmt(__N("array::at: __n (which is %zu) " ">= _Nm (which is %zu)"), __n, _Nm); return _AT_Type::_S_ref(_M_elems, __n); } constexpr const_reference at(size_type __n) const { // Result of conditional expression must be an lvalue so use // boolean ? lvalue : (throw-expr, lvalue) return __n < _Nm ? _AT_Type::_S_ref(_M_elems, __n) : (std::__throw_out_of_range_fmt(__N("array::at: __n (which is %zu) " ">= _Nm (which is %zu)"), __n, _Nm), _AT_Type::_S_ref(_M_elems, 0)); } _GLIBCXX17_CONSTEXPR reference front() noexcept { __glibcxx_check_nonempty(); return *begin(); } constexpr const_reference front() const noexcept { return _Nm ? _AT_Type::_S_ref(_M_elems, 0) : (_GLIBCXX_THROW_OR_ABORT(_Array_check_nonempty<_Nm>()), _AT_Type::_S_ref(_M_elems, 0)); } _GLIBCXX17_CONSTEXPR reference back() noexcept { __glibcxx_check_nonempty(); return _Nm ? *(end() - 1) : *end(); } constexpr const_reference back() const noexcept { return _Nm ? _AT_Type::_S_ref(_M_elems, _Nm - 1) : (_GLIBCXX_THROW_OR_ABORT(_Array_check_nonempty<_Nm>()), _AT_Type::_S_ref(_M_elems, 0)); } _GLIBCXX17_CONSTEXPR pointer data() noexcept { return _AT_Type::_S_ptr(_M_elems); } _GLIBCXX17_CONSTEXPR const_pointer data() const noexcept { return _AT_Type::_S_ptr(_M_elems); } }; #if __cpp_deduction_guides >= 201606 template array(_Tp, _Up...) -> array && ...), _Tp>, 1 + sizeof...(_Up)>; #endif // Array comparisons. template inline bool operator==(const array<_Tp, _Nm>& __one, const array<_Tp, _Nm>& __two) { return std::equal(__one.begin(), __one.end(), __two.begin()); } template inline bool operator!=(const array<_Tp, _Nm>& __one, const array<_Tp, _Nm>& __two) { return !(__one == __two); } template inline bool operator<(const array<_Tp, _Nm>& __a, const array<_Tp, _Nm>& __b) { return std::lexicographical_compare(__a.begin(), __a.end(), __b.begin(), __b.end()); } template inline bool operator>(const array<_Tp, _Nm>& __one, const array<_Tp, _Nm>& __two) { return __two < __one; } template inline bool operator<=(const array<_Tp, _Nm>& __one, const array<_Tp, _Nm>& __two) { return !(__one > __two); } template inline bool operator>=(const array<_Tp, _Nm>& __one, const array<_Tp, _Nm>& __two) { return !(__one < __two); } // Specialized algorithms. #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 template typename enable_if< !_GLIBCXX_STD_C::__array_traits<_Tp, _Nm>::_Is_swappable::value>::type swap(array<_Tp, _Nm>&, array<_Tp, _Nm>&) = delete; #endif template inline void swap(array<_Tp, _Nm>& __one, array<_Tp, _Nm>& __two) noexcept(noexcept(__one.swap(__two))) { __one.swap(__two); } template constexpr _Tp& get(array<_Tp, _Nm>& __arr) noexcept { static_assert(_Int < _Nm, "index is out of bounds"); return _GLIBCXX_STD_C::__array_traits<_Tp, _Nm>:: _S_ref(__arr._M_elems, _Int); } template constexpr _Tp&& get(array<_Tp, _Nm>&& __arr) noexcept { static_assert(_Int < _Nm, "index is out of bounds"); return std::move(__debug::get<_Int>(__arr)); } template constexpr const _Tp& get(const array<_Tp, _Nm>& __arr) noexcept { static_assert(_Int < _Nm, "index is out of bounds"); return _GLIBCXX_STD_C::__array_traits<_Tp, _Nm>:: _S_ref(__arr._M_elems, _Int); } template constexpr const _Tp&& get(const array<_Tp, _Nm>&& __arr) noexcept { static_assert(_Int < _Nm, "index is out of bounds"); return std::move(__debug::get<_Int>(__arr)); } } // namespace __debug _GLIBCXX_BEGIN_NAMESPACE_VERSION // Tuple interface to class template array. /// tuple_size template struct tuple_size> : public integral_constant { }; /// tuple_element template struct tuple_element<_Int, std::__debug::array<_Tp, _Nm>> { static_assert(_Int < _Nm, "index is out of bounds"); typedef _Tp type; }; template struct __is_tuple_like_impl> : true_type { }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _GLIBCXX_DEBUG_ARRAY PK!vk k 8/debug/assertions.hnu[// Debugging support implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/assertions.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_ASSERTIONS_H #define _GLIBCXX_DEBUG_ASSERTIONS_H 1 #ifndef _GLIBCXX_DEBUG # define _GLIBCXX_DEBUG_ASSERT(_Condition) # define _GLIBCXX_DEBUG_PEDASSERT(_Condition) # define _GLIBCXX_DEBUG_ONLY(_Statement) #endif #ifndef _GLIBCXX_ASSERTIONS # define __glibcxx_requires_non_empty_range(_First,_Last) # define __glibcxx_requires_nonempty() # define __glibcxx_requires_subscript(_N) #else // Verify that [_First, _Last) forms a non-empty iterator range. # define __glibcxx_requires_non_empty_range(_First,_Last) \ __glibcxx_assert(__builtin_expect(_First != _Last, true)) # define __glibcxx_requires_subscript(_N) \ __glibcxx_assert(__builtin_expect(_N < this->size(), true)) // Verify that the container is nonempty # define __glibcxx_requires_nonempty() \ __glibcxx_assert(__builtin_expect(!this->empty(), true)) #endif #ifdef _GLIBCXX_DEBUG # define _GLIBCXX_DEBUG_ASSERT(_Condition) __glibcxx_assert(_Condition) # ifdef _GLIBCXX_DEBUG_PEDANTIC # define _GLIBCXX_DEBUG_PEDASSERT(_Condition) _GLIBCXX_DEBUG_ASSERT(_Condition) # else # define _GLIBCXX_DEBUG_PEDASSERT(_Condition) # endif # define _GLIBCXX_DEBUG_ONLY(_Statement) _Statement #endif #endif // _GLIBCXX_DEBUG_ASSERTIONS PK!..8/debug/bitsetnu[// Debugging bitset implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/bitset * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_BITSET #define _GLIBCXX_DEBUG_BITSET #pragma GCC system_header #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::bitset with additional safety/checking/debug instrumentation. template class bitset : public _GLIBCXX_STD_C::bitset<_Nb> #if __cplusplus < 201103L , public __gnu_debug::_Safe_sequence_base #endif { typedef _GLIBCXX_STD_C::bitset<_Nb> _Base; public: // In C++11 we rely on normal reference type to preserve the property // of bitset to be use as a literal. // TODO: Find another solution. #if __cplusplus >= 201103L typedef typename _Base::reference reference; #else // bit reference: class reference : private _Base::reference , public __gnu_debug::_Safe_iterator_base { typedef typename _Base::reference _Base_ref; friend class bitset; reference(); reference(const _Base_ref& __base, bitset* __seq) _GLIBCXX_NOEXCEPT : _Base_ref(__base) , _Safe_iterator_base(__seq, false) { } public: reference(const reference& __x) _GLIBCXX_NOEXCEPT : _Base_ref(__x) , _Safe_iterator_base(__x, false) { } reference& operator=(bool __x) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(!this->_M_singular(), _M_message(__gnu_debug::__msg_bad_bitset_write) ._M_iterator(*this)); *static_cast<_Base_ref*>(this) = __x; return *this; } reference& operator=(const reference& __x) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(!__x._M_singular(), _M_message(__gnu_debug::__msg_bad_bitset_read) ._M_iterator(__x)); _GLIBCXX_DEBUG_VERIFY(!this->_M_singular(), _M_message(__gnu_debug::__msg_bad_bitset_write) ._M_iterator(*this)); *static_cast<_Base_ref*>(this) = __x; return *this; } bool operator~() const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(!this->_M_singular(), _M_message(__gnu_debug::__msg_bad_bitset_read) ._M_iterator(*this)); return ~(*static_cast(this)); } operator bool() const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(!this->_M_singular(), _M_message(__gnu_debug::__msg_bad_bitset_read) ._M_iterator(*this)); return *static_cast(this); } reference& flip() _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(!this->_M_singular(), _M_message(__gnu_debug::__msg_bad_bitset_flip) ._M_iterator(*this)); _Base_ref::flip(); return *this; } }; #endif // 23.3.5.1 constructors: _GLIBCXX_CONSTEXPR bitset() _GLIBCXX_NOEXCEPT : _Base() { } #if __cplusplus >= 201103L constexpr bitset(unsigned long long __val) noexcept #else bitset(unsigned long __val) #endif : _Base(__val) { } template explicit bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __str, typename std::basic_string<_CharT, _Traits, _Alloc>::size_type __pos = 0, typename std::basic_string<_CharT, _Traits, _Alloc>::size_type __n = (std::basic_string<_CharT, _Traits, _Alloc>::npos)) : _Base(__str, __pos, __n) { } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 396. what are characters zero and one. template bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __str, typename std::basic_string<_CharT, _Traits, _Alloc>::size_type __pos, typename std::basic_string<_CharT, _Traits, _Alloc>::size_type __n, _CharT __zero, _CharT __one = _CharT('1')) : _Base(__str, __pos, __n, __zero, __one) { } bitset(const _Base& __x) : _Base(__x) { } #if __cplusplus >= 201103L template explicit bitset(const _CharT* __str, typename std::basic_string<_CharT>::size_type __n = std::basic_string<_CharT>::npos, _CharT __zero = _CharT('0'), _CharT __one = _CharT('1')) : _Base(__str, __n, __zero, __one) { } #endif // 23.3.5.2 bitset operations: bitset<_Nb>& operator&=(const bitset<_Nb>& __rhs) _GLIBCXX_NOEXCEPT { _M_base() &= __rhs; return *this; } bitset<_Nb>& operator|=(const bitset<_Nb>& __rhs) _GLIBCXX_NOEXCEPT { _M_base() |= __rhs; return *this; } bitset<_Nb>& operator^=(const bitset<_Nb>& __rhs) _GLIBCXX_NOEXCEPT { _M_base() ^= __rhs; return *this; } bitset<_Nb>& operator<<=(size_t __pos) _GLIBCXX_NOEXCEPT { _M_base() <<= __pos; return *this; } bitset<_Nb>& operator>>=(size_t __pos) _GLIBCXX_NOEXCEPT { _M_base() >>= __pos; return *this; } bitset<_Nb>& set() _GLIBCXX_NOEXCEPT { _Base::set(); return *this; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 186. bitset::set() second parameter should be bool bitset<_Nb>& set(size_t __pos, bool __val = true) { _Base::set(__pos, __val); return *this; } bitset<_Nb>& reset() _GLIBCXX_NOEXCEPT { _Base::reset(); return *this; } bitset<_Nb>& reset(size_t __pos) { _Base::reset(__pos); return *this; } bitset<_Nb> operator~() const _GLIBCXX_NOEXCEPT { return bitset(~_M_base()); } bitset<_Nb>& flip() _GLIBCXX_NOEXCEPT { _Base::flip(); return *this; } bitset<_Nb>& flip(size_t __pos) { _Base::flip(__pos); return *this; } // element access: // _GLIBCXX_RESOLVE_LIB_DEFECTS // 11. Bitset minor problems reference operator[](size_t __pos) { __glibcxx_check_subscript(__pos); #if __cplusplus >= 201103L return _M_base()[__pos]; #else return reference(_M_base()[__pos], this); #endif } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 11. Bitset minor problems _GLIBCXX_CONSTEXPR bool operator[](size_t __pos) const { #if __cplusplus < 201103L // TODO: Check in debug-mode too. __glibcxx_check_subscript(__pos); #endif return _Base::operator[](__pos); } using _Base::to_ulong; #if __cplusplus >= 201103L using _Base::to_ullong; #endif template std::basic_string<_CharT, _Traits, _Alloc> to_string() const { return _M_base().template to_string<_CharT, _Traits, _Alloc>(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 396. what are characters zero and one. template std::basic_string<_CharT, _Traits, _Alloc> to_string(_CharT __zero, _CharT __one = _CharT('1')) const { return _M_base().template to_string<_CharT, _Traits, _Alloc>(__zero, __one); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 434. bitset::to_string() hard to use. template std::basic_string<_CharT, _Traits, std::allocator<_CharT> > to_string() const { return to_string<_CharT, _Traits, std::allocator<_CharT> >(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 853. to_string needs updating with zero and one. template std::basic_string<_CharT, _Traits, std::allocator<_CharT> > to_string(_CharT __zero, _CharT __one = _CharT('1')) const { return to_string<_CharT, _Traits, std::allocator<_CharT> >(__zero, __one); } template std::basic_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> > to_string() const { return to_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> >(); } template std::basic_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> > to_string(_CharT __zero, _CharT __one = _CharT('1')) const { return to_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> >(__zero, __one); } std::basic_string, std::allocator > to_string() const { return to_string,std::allocator >(); } std::basic_string, std::allocator > to_string(char __zero, char __one = '1') const { return to_string, std::allocator >(__zero, __one); } using _Base::count; using _Base::size; bool operator==(const bitset<_Nb>& __rhs) const _GLIBCXX_NOEXCEPT { return _M_base() == __rhs; } bool operator!=(const bitset<_Nb>& __rhs) const _GLIBCXX_NOEXCEPT { return _M_base() != __rhs; } using _Base::test; using _Base::all; using _Base::any; using _Base::none; bitset<_Nb> operator<<(size_t __pos) const _GLIBCXX_NOEXCEPT { return bitset<_Nb>(_M_base() << __pos); } bitset<_Nb> operator>>(size_t __pos) const _GLIBCXX_NOEXCEPT { return bitset<_Nb>(_M_base() >> __pos); } _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } }; template bitset<_Nb> operator&(const bitset<_Nb>& __x, const bitset<_Nb>& __y) _GLIBCXX_NOEXCEPT { return bitset<_Nb>(__x) &= __y; } template bitset<_Nb> operator|(const bitset<_Nb>& __x, const bitset<_Nb>& __y) _GLIBCXX_NOEXCEPT { return bitset<_Nb>(__x) |= __y; } template bitset<_Nb> operator^(const bitset<_Nb>& __x, const bitset<_Nb>& __y) _GLIBCXX_NOEXCEPT { return bitset<_Nb>(__x) ^= __y; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, bitset<_Nb>& __x) { return __is >> __x._M_base(); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const bitset<_Nb>& __x) { return __os << __x._M_base(); } } // namespace __debug #if __cplusplus >= 201103L // DR 1182. /// std::hash specialization for bitset. template struct hash<__debug::bitset<_Nb>> : public __hash_base> { size_t operator()(const __debug::bitset<_Nb>& __b) const noexcept { return std::hash<_GLIBCXX_STD_C::bitset<_Nb>>()(__b._M_base()); } }; #endif } // namespace std #endif PK!Aľee8/debug/debug.hnu[// Debugging support implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/debug.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_MACRO_SWITCH_H #define _GLIBCXX_DEBUG_MACRO_SWITCH_H 1 /** Macros and namespaces used by the implementation outside of debug * wrappers to verify certain properties. The __glibcxx_requires_xxx * macros are merely wrappers around the __glibcxx_check_xxx wrappers * when we are compiling with debug mode, but disappear when we are * in release mode so that there is no checking performed in, e.g., * the standard library algorithms. */ #include // Debug mode namespaces. /** * @namespace std::__debug * @brief GNU debug code, replaces standard behavior with debug behavior. */ namespace std { namespace __debug { } } /** @namespace __gnu_debug * @brief GNU debug classes for public use. */ namespace __gnu_debug { using namespace std::__debug; } #ifndef _GLIBCXX_DEBUG # define __glibcxx_requires_cond(_Cond,_Msg) # define __glibcxx_requires_valid_range(_First,_Last) # define __glibcxx_requires_sorted(_First,_Last) # define __glibcxx_requires_sorted_pred(_First,_Last,_Pred) # define __glibcxx_requires_sorted_set(_First1,_Last1,_First2) # define __glibcxx_requires_sorted_set_pred(_First1,_Last1,_First2,_Pred) # define __glibcxx_requires_partitioned_lower(_First,_Last,_Value) # define __glibcxx_requires_partitioned_upper(_First,_Last,_Value) # define __glibcxx_requires_partitioned_lower_pred(_First,_Last,_Value,_Pred) # define __glibcxx_requires_partitioned_upper_pred(_First,_Last,_Value,_Pred) # define __glibcxx_requires_heap(_First,_Last) # define __glibcxx_requires_heap_pred(_First,_Last,_Pred) # define __glibcxx_requires_string(_String) # define __glibcxx_requires_string_len(_String,_Len) # define __glibcxx_requires_irreflexive(_First,_Last) # define __glibcxx_requires_irreflexive2(_First,_Last) # define __glibcxx_requires_irreflexive_pred(_First,_Last,_Pred) # define __glibcxx_requires_irreflexive_pred2(_First,_Last,_Pred) #else # include # define __glibcxx_requires_cond(_Cond,_Msg) _GLIBCXX_DEBUG_VERIFY(_Cond,_Msg) # define __glibcxx_requires_valid_range(_First,_Last) \ __glibcxx_check_valid_range(_First,_Last) # define __glibcxx_requires_sorted(_First,_Last) \ __glibcxx_check_sorted(_First,_Last) # define __glibcxx_requires_sorted_pred(_First,_Last,_Pred) \ __glibcxx_check_sorted_pred(_First,_Last,_Pred) # define __glibcxx_requires_sorted_set(_First1,_Last1,_First2) \ __glibcxx_check_sorted_set(_First1,_Last1,_First2) # define __glibcxx_requires_sorted_set_pred(_First1,_Last1,_First2,_Pred) \ __glibcxx_check_sorted_set_pred(_First1,_Last1,_First2,_Pred) # define __glibcxx_requires_partitioned_lower(_First,_Last,_Value) \ __glibcxx_check_partitioned_lower(_First,_Last,_Value) # define __glibcxx_requires_partitioned_upper(_First,_Last,_Value) \ __glibcxx_check_partitioned_upper(_First,_Last,_Value) # define __glibcxx_requires_partitioned_lower_pred(_First,_Last,_Value,_Pred) \ __glibcxx_check_partitioned_lower_pred(_First,_Last,_Value,_Pred) # define __glibcxx_requires_partitioned_upper_pred(_First,_Last,_Value,_Pred) \ __glibcxx_check_partitioned_upper_pred(_First,_Last,_Value,_Pred) # define __glibcxx_requires_heap(_First,_Last) \ __glibcxx_check_heap(_First,_Last) # define __glibcxx_requires_heap_pred(_First,_Last,_Pred) \ __glibcxx_check_heap_pred(_First,_Last,_Pred) # define __glibcxx_requires_string(_String) __glibcxx_check_string(_String) # define __glibcxx_requires_string_len(_String,_Len) \ __glibcxx_check_string_len(_String,_Len) # define __glibcxx_requires_irreflexive(_First,_Last) \ __glibcxx_check_irreflexive(_First,_Last) # define __glibcxx_requires_irreflexive2(_First,_Last) \ __glibcxx_check_irreflexive2(_First,_Last) # define __glibcxx_requires_irreflexive_pred(_First,_Last,_Pred) \ __glibcxx_check_irreflexive_pred(_First,_Last,_Pred) # define __glibcxx_requires_irreflexive_pred2(_First,_Last,_Pred) \ __glibcxx_check_irreflexive_pred2(_First,_Last,_Pred) # include #endif #endif // _GLIBCXX_DEBUG_MACRO_SWITCH_H PK!6CC 8/debug/dequenu[// Debugging deque implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/deque * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_DEQUE #define _GLIBCXX_DEBUG_DEQUE 1 #pragma GCC system_header #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::deque with safety/checking/debug instrumentation. template > class deque : public __gnu_debug::_Safe_container< deque<_Tp, _Allocator>, _Allocator, __gnu_debug::_Safe_sequence>, public _GLIBCXX_STD_C::deque<_Tp, _Allocator> { typedef _GLIBCXX_STD_C::deque<_Tp, _Allocator> _Base; typedef __gnu_debug::_Safe_container< deque, _Allocator, __gnu_debug::_Safe_sequence> _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef __gnu_debug::_Equal_to<_Base_const_iterator> _Equal; public: typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator<_Base_iterator, deque> iterator; typedef __gnu_debug::_Safe_iterator<_Base_const_iterator, deque> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef _Tp value_type; typedef _Allocator allocator_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // 23.2.1.1 construct/copy/destroy: #if __cplusplus < 201103L deque() : _Base() { } deque(const deque& __x) : _Base(__x) { } ~deque() { } #else deque() = default; deque(const deque&) = default; deque(deque&&) = default; deque(const deque& __d, const _Allocator& __a) : _Base(__d, __a) { } deque(deque&& __d, const _Allocator& __a) : _Safe(std::move(__d)), _Base(std::move(__d), __a) { } deque(initializer_list __l, const allocator_type& __a = allocator_type()) : _Base(__l, __a) { } ~deque() = default; #endif explicit deque(const _Allocator& __a) : _Base(__a) { } #if __cplusplus >= 201103L explicit deque(size_type __n, const _Allocator& __a = _Allocator()) : _Base(__n, __a) { } deque(size_type __n, const _Tp& __value, const _Allocator& __a = _Allocator()) : _Base(__n, __value, __a) { } #else explicit deque(size_type __n, const _Tp& __value = _Tp(), const _Allocator& __a = _Allocator()) : _Base(__n, __value, __a) { } #endif #if __cplusplus >= 201103L template> #else template #endif deque(_InputIterator __first, _InputIterator __last, const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __a) { } deque(const _Base& __x) : _Base(__x) { } #if __cplusplus < 201103L deque& operator=(const deque& __x) { this->_M_safe() = __x; _M_base() = __x; return *this; } #else deque& operator=(const deque&) = default; deque& operator=(deque&&) = default; deque& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } #endif #if __cplusplus >= 201103L template> #else template #endif void assign(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::assign(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::assign(__first, __last); this->_M_invalidate_all(); } void assign(size_type __n, const _Tp& __t) { _Base::assign(__n, __t); this->_M_invalidate_all(); } #if __cplusplus >= 201103L void assign(initializer_list __l) { _Base::assign(__l); this->_M_invalidate_all(); } #endif using _Base::get_allocator; // iterators: iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif private: void _M_invalidate_after_nth(difference_type __n) { typedef __gnu_debug::_After_nth_from<_Base_const_iterator> _After_nth; this->_M_invalidate_if(_After_nth(__n, _Base::begin())); } public: // 23.2.1.2 capacity: using _Base::size; using _Base::max_size; #if __cplusplus >= 201103L void resize(size_type __sz) { bool __invalidate_all = __sz > this->size(); if (__sz < this->size()) this->_M_invalidate_after_nth(__sz); _Base::resize(__sz); if (__invalidate_all) this->_M_invalidate_all(); } void resize(size_type __sz, const _Tp& __c) { bool __invalidate_all = __sz > this->size(); if (__sz < this->size()) this->_M_invalidate_after_nth(__sz); _Base::resize(__sz, __c); if (__invalidate_all) this->_M_invalidate_all(); } #else void resize(size_type __sz, _Tp __c = _Tp()) { bool __invalidate_all = __sz > this->size(); if (__sz < this->size()) this->_M_invalidate_after_nth(__sz); _Base::resize(__sz, __c); if (__invalidate_all) this->_M_invalidate_all(); } #endif #if __cplusplus >= 201103L void shrink_to_fit() noexcept { if (_Base::_M_shrink_to_fit()) this->_M_invalidate_all(); } #endif using _Base::empty; // element access: reference operator[](size_type __n) _GLIBCXX_NOEXCEPT { __glibcxx_check_subscript(__n); return _M_base()[__n]; } const_reference operator[](size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_check_subscript(__n); return _M_base()[__n]; } using _Base::at; reference front() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::front(); } const_reference front() const _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::front(); } reference back() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::back(); } const_reference back() const _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::back(); } // 23.2.1.3 modifiers: void push_front(const _Tp& __x) { _Base::push_front(__x); this->_M_invalidate_all(); } void push_back(const _Tp& __x) { _Base::push_back(__x); this->_M_invalidate_all(); } #if __cplusplus >= 201103L void push_front(_Tp&& __x) { emplace_front(std::move(__x)); } void push_back(_Tp&& __x) { emplace_back(std::move(__x)); } template #if __cplusplus > 201402L reference #else void #endif emplace_front(_Args&&... __args) { _Base::emplace_front(std::forward<_Args>(__args)...); this->_M_invalidate_all(); #if __cplusplus > 201402L return front(); #endif } template #if __cplusplus > 201402L reference #else void #endif emplace_back(_Args&&... __args) { _Base::emplace_back(std::forward<_Args>(__args)...); this->_M_invalidate_all(); #if __cplusplus > 201402L return back(); #endif } template iterator emplace(const_iterator __position, _Args&&... __args) { __glibcxx_check_insert(__position); _Base_iterator __res = _Base::emplace(__position.base(), std::forward<_Args>(__args)...); this->_M_invalidate_all(); return iterator(__res, this); } #endif iterator #if __cplusplus >= 201103L insert(const_iterator __position, const _Tp& __x) #else insert(iterator __position, const _Tp& __x) #endif { __glibcxx_check_insert(__position); _Base_iterator __res = _Base::insert(__position.base(), __x); this->_M_invalidate_all(); return iterator(__res, this); } #if __cplusplus >= 201103L iterator insert(const_iterator __position, _Tp&& __x) { return emplace(__position, std::move(__x)); } iterator insert(const_iterator __position, initializer_list __l) { __glibcxx_check_insert(__position); _Base_iterator __res = _Base::insert(__position.base(), __l); this->_M_invalidate_all(); return iterator(__res, this); } #endif #if __cplusplus >= 201103L iterator insert(const_iterator __position, size_type __n, const _Tp& __x) { __glibcxx_check_insert(__position); _Base_iterator __res = _Base::insert(__position.base(), __n, __x); this->_M_invalidate_all(); return iterator(__res, this); } #else void insert(iterator __position, size_type __n, const _Tp& __x) { __glibcxx_check_insert(__position); _Base::insert(__position.base(), __n, __x); this->_M_invalidate_all(); } #endif #if __cplusplus >= 201103L template> iterator insert(const_iterator __position, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range(__position, __first, __last, __dist); _Base_iterator __res; if (__dist.second >= __gnu_debug::__dp_sign) __res = _Base::insert(__position.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else __res = _Base::insert(__position.base(), __first, __last); this->_M_invalidate_all(); return iterator(__res, this); } #else template void insert(iterator __position, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range(__position, __first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__position.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__position.base(), __first, __last); this->_M_invalidate_all(); } #endif void pop_front() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); this->_M_invalidate_if(_Equal(_Base::begin())); _Base::pop_front(); } void pop_back() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); this->_M_invalidate_if(_Equal(--_Base::end())); _Base::pop_back(); } iterator #if __cplusplus >= 201103L erase(const_iterator __position) #else erase(iterator __position) #endif { __glibcxx_check_erase(__position); #if __cplusplus >= 201103L _Base_const_iterator __victim = __position.base(); #else _Base_iterator __victim = __position.base(); #endif if (__victim == _Base::begin() || __victim == _Base::end() - 1) { this->_M_invalidate_if(_Equal(__victim)); return iterator(_Base::erase(__victim), this); } else { _Base_iterator __res = _Base::erase(__victim); this->_M_invalidate_all(); return iterator(__res, this); } } iterator #if __cplusplus >= 201103L erase(const_iterator __first, const_iterator __last) #else erase(iterator __first, iterator __last) #endif { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); if (__first.base() == __last.base()) #if __cplusplus >= 201103L return iterator(__first.base()._M_const_cast(), this); #else return __first; #endif else if (__first.base() == _Base::begin() || __last.base() == _Base::end()) { this->_M_detach_singular(); for (_Base_const_iterator __position = __first.base(); __position != __last.base(); ++__position) { this->_M_invalidate_if(_Equal(__position)); } __try { return iterator(_Base::erase(__first.base(), __last.base()), this); } __catch(...) { this->_M_revalidate_singular(); __throw_exception_again; } } else { _Base_iterator __res = _Base::erase(__first.base(), __last.base()); this->_M_invalidate_all(); return iterator(__res, this); } } void swap(deque& __x) _GLIBCXX_NOEXCEPT_IF( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() _GLIBCXX_NOEXCEPT { _Base::clear(); this->_M_invalidate_all(); } _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } }; #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> deque(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> deque<_ValT, _Allocator>; #endif template inline bool operator==(const deque<_Tp, _Alloc>& __lhs, const deque<_Tp, _Alloc>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator!=(const deque<_Tp, _Alloc>& __lhs, const deque<_Tp, _Alloc>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator<(const deque<_Tp, _Alloc>& __lhs, const deque<_Tp, _Alloc>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<=(const deque<_Tp, _Alloc>& __lhs, const deque<_Tp, _Alloc>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator>=(const deque<_Tp, _Alloc>& __lhs, const deque<_Tp, _Alloc>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>(const deque<_Tp, _Alloc>& __lhs, const deque<_Tp, _Alloc>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template inline void swap(deque<_Tp, _Alloc>& __lhs, deque<_Tp, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT_IF(noexcept(__lhs.swap(__rhs))) { __lhs.swap(__rhs); } } // namespace __debug } // namespace std #endif PK!AU778/debug/formatter.hnu[// Debug-mode error formatting implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/formatter.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_FORMATTER_H #define _GLIBCXX_DEBUG_FORMATTER_H 1 #include #include #if __cpp_rtti # include # define _GLIBCXX_TYPEID(_Type) &typeid(_Type) #else namespace std { class type_info; } # define _GLIBCXX_TYPEID(_Type) 0 #endif namespace __gnu_debug { using std::type_info; template bool __check_singular(const _Iterator&); class _Safe_sequence_base; template class _Safe_iterator; template class _Safe_local_iterator; template class _Safe_sequence; enum _Debug_msg_id { // General checks __msg_valid_range, __msg_insert_singular, __msg_insert_different, __msg_erase_bad, __msg_erase_different, __msg_subscript_oob, __msg_empty, __msg_unpartitioned, __msg_unpartitioned_pred, __msg_unsorted, __msg_unsorted_pred, __msg_not_heap, __msg_not_heap_pred, // std::bitset checks __msg_bad_bitset_write, __msg_bad_bitset_read, __msg_bad_bitset_flip, // std::list checks __msg_self_splice, __msg_splice_alloc, __msg_splice_bad, __msg_splice_other, __msg_splice_overlap, // iterator checks __msg_init_singular, __msg_init_copy_singular, __msg_init_const_singular, __msg_copy_singular, __msg_bad_deref, __msg_bad_inc, __msg_bad_dec, __msg_iter_subscript_oob, __msg_advance_oob, __msg_retreat_oob, __msg_iter_compare_bad, __msg_compare_different, __msg_iter_order_bad, __msg_order_different, __msg_distance_bad, __msg_distance_different, // istream_iterator __msg_deref_istream, __msg_inc_istream, // ostream_iterator __msg_output_ostream, // istreambuf_iterator __msg_deref_istreambuf, __msg_inc_istreambuf, // forward_list __msg_insert_after_end, __msg_erase_after_bad, __msg_valid_range2, // unordered container local iterators __msg_local_iter_compare_bad, __msg_non_empty_range, // self move assign __msg_self_move_assign, // unordered container buckets __msg_bucket_index_oob, __msg_valid_load_factor, // others __msg_equal_allocs, __msg_insert_range_from_self, __msg_irreflexive_ordering }; class _Error_formatter { // Tags denoting the type of parameter for construction struct _Is_iterator { }; struct _Is_iterator_value_type { }; struct _Is_sequence { }; struct _Is_instance { }; public: /// Whether an iterator is constant, mutable, or unknown enum _Constness { __unknown_constness, __const_iterator, __mutable_iterator, __last_constness }; // The state of the iterator (fine-grained), if we know it. enum _Iterator_state { __unknown_state, __singular, // singular, may still be attached to a sequence __begin, // dereferenceable, and at the beginning __middle, // dereferenceable, not at the beginning __end, // past-the-end, may be at beginning if sequence empty __before_begin, // before begin __last_state }; // A parameter that may be referenced by an error message struct _Parameter { enum { __unused_param, __iterator, __sequence, __integer, __string, __instance, __iterator_value_type } _M_kind; struct _Type { const char* _M_name; const type_info* _M_type; }; struct _Instance : _Type { const void* _M_address; }; union { // When _M_kind == __iterator struct : _Instance { _Constness _M_constness; _Iterator_state _M_state; const void* _M_sequence; const type_info* _M_seq_type; } _M_iterator; // When _M_kind == __sequence _Instance _M_sequence; // When _M_kind == __integer struct { const char* _M_name; long _M_value; } _M_integer; // When _M_kind == __string struct { const char* _M_name; const char* _M_value; } _M_string; // When _M_kind == __instance _Instance _M_instance; // When _M_kind == __iterator_value_type _Type _M_iterator_value_type; } _M_variant; _Parameter() : _M_kind(__unused_param), _M_variant() { } _Parameter(long __value, const char* __name) : _M_kind(__integer), _M_variant() { _M_variant._M_integer._M_name = __name; _M_variant._M_integer._M_value = __value; } _Parameter(const char* __value, const char* __name) : _M_kind(__string), _M_variant() { _M_variant._M_string._M_name = __name; _M_variant._M_string._M_value = __value; } template _Parameter(_Safe_iterator<_Iterator, _Sequence> const& __it, const char* __name, _Is_iterator) : _M_kind(__iterator), _M_variant() { _M_variant._M_iterator._M_name = __name; _M_variant._M_iterator._M_address = std::__addressof(__it); _M_variant._M_iterator._M_type = _GLIBCXX_TYPEID(__it); _M_variant._M_iterator._M_constness = std::__are_same<_Safe_iterator<_Iterator, _Sequence>, typename _Sequence::iterator>:: __value ? __mutable_iterator : __const_iterator; _M_variant._M_iterator._M_sequence = __it._M_get_sequence(); _M_variant._M_iterator._M_seq_type = _GLIBCXX_TYPEID(_Sequence); if (__it._M_singular()) _M_variant._M_iterator._M_state = __singular; else { if (__it._M_is_before_begin()) _M_variant._M_iterator._M_state = __before_begin; else if (__it._M_is_end()) _M_variant._M_iterator._M_state = __end; else if (__it._M_is_begin()) _M_variant._M_iterator._M_state = __begin; else _M_variant._M_iterator._M_state = __middle; } } template _Parameter(_Safe_local_iterator<_Iterator, _Sequence> const& __it, const char* __name, _Is_iterator) : _M_kind(__iterator), _M_variant() { _M_variant._M_iterator._M_name = __name; _M_variant._M_iterator._M_address = std::__addressof(__it); _M_variant._M_iterator._M_type = _GLIBCXX_TYPEID(__it); _M_variant._M_iterator._M_constness = std::__are_same<_Safe_local_iterator<_Iterator, _Sequence>, typename _Sequence::local_iterator>:: __value ? __mutable_iterator : __const_iterator; _M_variant._M_iterator._M_sequence = __it._M_get_sequence(); _M_variant._M_iterator._M_seq_type = _GLIBCXX_TYPEID(_Sequence); if (__it._M_singular()) _M_variant._M_iterator._M_state = __singular; else { if (__it._M_is_end()) _M_variant._M_iterator._M_state = __end; else if (__it._M_is_begin()) _M_variant._M_iterator._M_state = __begin; else _M_variant._M_iterator._M_state = __middle; } } template _Parameter(const _Type* const& __it, const char* __name, _Is_iterator) : _M_kind(__iterator), _M_variant() { _M_variant._M_iterator._M_name = __name; _M_variant._M_iterator._M_address = std::__addressof(__it); _M_variant._M_iterator._M_type = _GLIBCXX_TYPEID(__it); _M_variant._M_iterator._M_constness = __const_iterator; _M_variant._M_iterator._M_state = __it ? __unknown_state : __singular; _M_variant._M_iterator._M_sequence = 0; _M_variant._M_iterator._M_seq_type = 0; } template _Parameter(_Type* const& __it, const char* __name, _Is_iterator) : _M_kind(__iterator), _M_variant() { _M_variant._M_iterator._M_name = __name; _M_variant._M_iterator._M_address = std::__addressof(__it); _M_variant._M_iterator._M_type = _GLIBCXX_TYPEID(__it); _M_variant._M_iterator._M_constness = __mutable_iterator; _M_variant._M_iterator._M_state = __it ? __unknown_state : __singular; _M_variant._M_iterator._M_sequence = 0; _M_variant._M_iterator._M_seq_type = 0; } template _Parameter(_Iterator const& __it, const char* __name, _Is_iterator) : _M_kind(__iterator), _M_variant() { _M_variant._M_iterator._M_name = __name; _M_variant._M_iterator._M_address = std::__addressof(__it); _M_variant._M_iterator._M_type = _GLIBCXX_TYPEID(__it); _M_variant._M_iterator._M_constness = __unknown_constness; _M_variant._M_iterator._M_state = __gnu_debug::__check_singular(__it) ? __singular : __unknown_state; _M_variant._M_iterator._M_sequence = 0; _M_variant._M_iterator._M_seq_type = 0; } template _Parameter(const _Safe_sequence<_Sequence>& __seq, const char* __name, _Is_sequence) : _M_kind(__sequence), _M_variant() { _M_variant._M_sequence._M_name = __name; _M_variant._M_sequence._M_address = static_cast(std::__addressof(__seq)); _M_variant._M_sequence._M_type = _GLIBCXX_TYPEID(_Sequence); } template _Parameter(const _Sequence& __seq, const char* __name, _Is_sequence) : _M_kind(__sequence), _M_variant() { _M_variant._M_sequence._M_name = __name; _M_variant._M_sequence._M_address = std::__addressof(__seq); _M_variant._M_sequence._M_type = _GLIBCXX_TYPEID(_Sequence); } template _Parameter(const _Iterator& __it, const char* __name, _Is_iterator_value_type) : _M_kind(__iterator_value_type), _M_variant() { _M_variant._M_iterator_value_type._M_name = __name; _M_variant._M_iterator_value_type._M_type = _GLIBCXX_TYPEID(typename std::iterator_traits<_Iterator>::value_type); } template _Parameter(const _Type& __inst, const char* __name, _Is_instance) : _M_kind(__instance), _M_variant() { _M_variant._M_instance._M_name = __name; _M_variant._M_instance._M_address = &__inst; _M_variant._M_instance._M_type = _GLIBCXX_TYPEID(_Type); } #if !_GLIBCXX_INLINE_VERSION void _M_print_field(const _Error_formatter* __formatter, const char* __name) const _GLIBCXX_DEPRECATED; void _M_print_description(const _Error_formatter* __formatter) const _GLIBCXX_DEPRECATED; #endif }; template _Error_formatter& _M_iterator(const _Iterator& __it, const char* __name = 0) { if (_M_num_parameters < std::size_t(__max_parameters)) _M_parameters[_M_num_parameters++] = _Parameter(__it, __name, _Is_iterator()); return *this; } template _Error_formatter& _M_iterator_value_type(const _Iterator& __it, const char* __name = 0) { if (_M_num_parameters < __max_parameters) _M_parameters[_M_num_parameters++] = _Parameter(__it, __name, _Is_iterator_value_type()); return *this; } _Error_formatter& _M_integer(long __value, const char* __name = 0) { if (_M_num_parameters < __max_parameters) _M_parameters[_M_num_parameters++] = _Parameter(__value, __name); return *this; } _Error_formatter& _M_string(const char* __value, const char* __name = 0) { if (_M_num_parameters < __max_parameters) _M_parameters[_M_num_parameters++] = _Parameter(__value, __name); return *this; } template _Error_formatter& _M_sequence(const _Sequence& __seq, const char* __name = 0) { if (_M_num_parameters < __max_parameters) _M_parameters[_M_num_parameters++] = _Parameter(__seq, __name, _Is_sequence()); return *this; } template _Error_formatter& _M_instance(const _Type& __inst, const char* __name = 0) { if (_M_num_parameters < __max_parameters) _M_parameters[_M_num_parameters++] = _Parameter(__inst, __name, _Is_instance()); return *this; } _Error_formatter& _M_message(const char* __text) { _M_text = __text; return *this; } // Kept const qualifier for backward compatibility, to keep the same // exported symbol. _Error_formatter& _M_message(_Debug_msg_id __id) const throw (); _GLIBCXX_NORETURN void _M_error() const; #if !_GLIBCXX_INLINE_VERSION template void _M_format_word(char*, int, const char*, _Tp) const throw () _GLIBCXX_DEPRECATED; void _M_print_word(const char* __word) const _GLIBCXX_DEPRECATED; void _M_print_string(const char* __string) const _GLIBCXX_DEPRECATED; #endif private: _Error_formatter(const char* __file, unsigned int __line) : _M_file(__file), _M_line(__line), _M_num_parameters(0), _M_text(0) { } #if !_GLIBCXX_INLINE_VERSION void _M_get_max_length() const throw () _GLIBCXX_DEPRECATED; #endif enum { __max_parameters = 9 }; const char* _M_file; unsigned int _M_line; _Parameter _M_parameters[__max_parameters]; unsigned int _M_num_parameters; const char* _M_text; public: static _Error_formatter& _M_at(const char* __file, unsigned int __line) { static _Error_formatter __formatter(__file, __line); return __formatter; } }; } // namespace __gnu_debug #undef _GLIBCXX_TYPEID #endif PK!QEdEd8/debug/forward_listnu[// -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/forward_list * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_FORWARD_LIST #define _GLIBCXX_DEBUG_FORWARD_LIST 1 #pragma GCC system_header #include #include #include #include // Special validity check for forward_list ranges. #define __glibcxx_check_valid_fl_range(_First,_Last,_Dist) \ _GLIBCXX_DEBUG_VERIFY(_First._M_valid_range(_Last, _Dist, false), \ _M_message(__gnu_debug::__msg_valid_range) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) namespace __gnu_debug { /// Special iterators swap and invalidation for forward_list because of the /// before_begin iterator. template class _Safe_forward_list : public _Safe_sequence<_SafeSequence> { _SafeSequence& _M_this() noexcept { return *static_cast<_SafeSequence*>(this); } static void _M_swap_aux(_Safe_sequence_base& __lhs, _Safe_iterator_base*& __lhs_iterators, _Safe_sequence_base& __rhs, _Safe_iterator_base*& __rhs_iterators); void _M_swap_single(_Safe_sequence_base&) noexcept; protected: void _M_invalidate_all() { using _Base_const_iterator = __decltype(_M_this()._M_base().cend()); this->_M_invalidate_if([this](_Base_const_iterator __it) { return __it != _M_this()._M_base().cbefore_begin() && __it != _M_this()._M_base().cend(); }); } void _M_swap(_Safe_sequence_base&) noexcept; }; template void _Safe_forward_list<_SafeSequence>:: _M_swap_aux(_Safe_sequence_base& __lhs, _Safe_iterator_base*& __lhs_iterators, _Safe_sequence_base& __rhs, _Safe_iterator_base*& __rhs_iterators) { using const_iterator = typename _SafeSequence::const_iterator; _Safe_iterator_base* __bbegin_its = 0; _Safe_iterator_base* __last_bbegin = 0; _SafeSequence& __rseq = static_cast<_SafeSequence&>(__rhs); for (_Safe_iterator_base* __iter = __lhs_iterators; __iter;) { // Even iterator is cast to const_iterator, not a problem. _Safe_iterator_base* __victim_base = __iter; const_iterator* __victim = static_cast(__victim_base); __iter = __iter->_M_next; if (__victim->base() == __rseq._M_base().cbefore_begin()) { __victim->_M_unlink(); if (__lhs_iterators == __victim_base) __lhs_iterators = __victim_base->_M_next; if (__bbegin_its) { __victim_base->_M_next = __bbegin_its; __bbegin_its->_M_prior = __victim_base; } else __last_bbegin = __victim_base; __bbegin_its = __victim_base; } else __victim_base->_M_sequence = std::__addressof(__lhs); } if (__bbegin_its) { if (__rhs_iterators) { __rhs_iterators->_M_prior = __last_bbegin; __last_bbegin->_M_next = __rhs_iterators; } __rhs_iterators = __bbegin_its; } } template void _Safe_forward_list<_SafeSequence>:: _M_swap_single(_Safe_sequence_base& __other) noexcept { std::swap(_M_this()._M_iterators, __other._M_iterators); std::swap(_M_this()._M_const_iterators, __other._M_const_iterators); // Useless, always 1 on forward_list //std::swap(_M_this()_M_version, __other._M_version); _Safe_iterator_base* __this_its = _M_this()._M_iterators; _M_swap_aux(__other, __other._M_iterators, _M_this(), _M_this()._M_iterators); _Safe_iterator_base* __this_const_its = _M_this()._M_const_iterators; _M_swap_aux(__other, __other._M_const_iterators, _M_this(), _M_this()._M_const_iterators); _M_swap_aux(_M_this(), __this_its, __other, __other._M_iterators); _M_swap_aux(_M_this(), __this_const_its, __other, __other._M_const_iterators); } /* Special forward_list _M_swap version that does not swap the * before-begin ownership.*/ template void _Safe_forward_list<_SafeSequence>:: _M_swap(_Safe_sequence_base& __other) noexcept { // We need to lock both sequences to swap using namespace __gnu_cxx; __mutex *__this_mutex = &_M_this()._M_get_mutex(); __mutex *__other_mutex = &static_cast<_SafeSequence&>(__other)._M_get_mutex(); if (__this_mutex == __other_mutex) { __scoped_lock __lock(*__this_mutex); _M_swap_single(__other); } else { __scoped_lock __l1(__this_mutex < __other_mutex ? *__this_mutex : *__other_mutex); __scoped_lock __l2(__this_mutex < __other_mutex ? *__other_mutex : *__this_mutex); _M_swap_single(__other); } } } namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::forward_list with safety/checking/debug instrumentation. template > class forward_list : public __gnu_debug::_Safe_container< forward_list<_Tp, _Alloc>, _Alloc, __gnu_debug::_Safe_forward_list>, public _GLIBCXX_STD_C::forward_list<_Tp, _Alloc> { typedef _GLIBCXX_STD_C::forward_list<_Tp, _Alloc> _Base; typedef __gnu_debug::_Safe_container< forward_list, _Alloc, __gnu_debug::_Safe_forward_list> _Safe; typedef typename _Base::iterator _Base_iterator; typedef typename _Base::const_iterator _Base_const_iterator; public: typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator< _Base_iterator, forward_list> iterator; typedef __gnu_debug::_Safe_iterator< _Base_const_iterator, forward_list> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef _Tp value_type; typedef typename _Base::allocator_type allocator_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; // 23.2.3.1 construct/copy/destroy: forward_list() = default; explicit forward_list(const allocator_type& __al) noexcept : _Base(__al) { } forward_list(const forward_list& __list, const allocator_type& __al) : _Base(__list, __al) { } forward_list(forward_list&& __list, const allocator_type& __al) : _Safe(std::move(__list._M_safe()), __al), _Base(std::move(__list._M_base()), __al) { } explicit forward_list(size_type __n, const allocator_type& __al = allocator_type()) : _Base(__n, __al) { } forward_list(size_type __n, const _Tp& __value, const allocator_type& __al = allocator_type()) : _Base(__n, __value, __al) { } template> forward_list(_InputIterator __first, _InputIterator __last, const allocator_type& __al = allocator_type()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __al) { } forward_list(const forward_list&) = default; forward_list(forward_list&&) = default; forward_list(std::initializer_list<_Tp> __il, const allocator_type& __al = allocator_type()) : _Base(__il, __al) { } ~forward_list() = default; forward_list& operator=(const forward_list&) = default; forward_list& operator=(forward_list&&) = default; forward_list& operator=(std::initializer_list<_Tp> __il) { _M_base() = __il; this->_M_invalidate_all(); return *this; } template> void assign(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::assign(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::assign(__first, __last); this->_M_invalidate_all(); } void assign(size_type __n, const _Tp& __val) { _Base::assign(__n, __val); this->_M_invalidate_all(); } void assign(std::initializer_list<_Tp> __il) { _Base::assign(__il); this->_M_invalidate_all(); } using _Base::get_allocator; // iterators: iterator before_begin() noexcept { return iterator(_Base::before_begin(), this); } const_iterator before_begin() const noexcept { return const_iterator(_Base::before_begin(), this); } iterator begin() noexcept { return iterator(_Base::begin(), this); } const_iterator begin() const noexcept { return const_iterator(_Base::begin(), this); } iterator end() noexcept { return iterator(_Base::end(), this); } const_iterator end() const noexcept { return const_iterator(_Base::end(), this); } const_iterator cbegin() const noexcept { return const_iterator(_Base::cbegin(), this); } const_iterator cbefore_begin() const noexcept { return const_iterator(_Base::cbefore_begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::cend(), this); } using _Base::empty; using _Base::max_size; // element access: reference front() { __glibcxx_check_nonempty(); return _Base::front(); } const_reference front() const { __glibcxx_check_nonempty(); return _Base::front(); } // modifiers: using _Base::emplace_front; using _Base::push_front; void pop_front() { __glibcxx_check_nonempty(); this->_M_invalidate_if([this](_Base_const_iterator __it) { return __it == this->_M_base().cbegin(); }); _Base::pop_front(); } template iterator emplace_after(const_iterator __pos, _Args&&... __args) { __glibcxx_check_insert_after(__pos); return iterator(_Base::emplace_after(__pos.base(), std::forward<_Args>(__args)...), this); } iterator insert_after(const_iterator __pos, const _Tp& __val) { __glibcxx_check_insert_after(__pos); return iterator(_Base::insert_after(__pos.base(), __val), this); } iterator insert_after(const_iterator __pos, _Tp&& __val) { __glibcxx_check_insert_after(__pos); return iterator(_Base::insert_after(__pos.base(), std::move(__val)), this); } iterator insert_after(const_iterator __pos, size_type __n, const _Tp& __val) { __glibcxx_check_insert_after(__pos); return iterator(_Base::insert_after(__pos.base(), __n, __val), this); } template> iterator insert_after(const_iterator __pos, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range_after(__pos, __first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) return { _Base::insert_after(__pos.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)), this }; else return { _Base::insert_after(__pos.base(), __first, __last), this }; } iterator insert_after(const_iterator __pos, std::initializer_list<_Tp> __il) { __glibcxx_check_insert_after(__pos); return iterator(_Base::insert_after(__pos.base(), __il), this); } private: _Base_iterator _M_erase_after(_Base_const_iterator __pos) { _Base_const_iterator __next = std::next(__pos); this->_M_invalidate_if([__next](_Base_const_iterator __it) { return __it == __next; }); return _Base::erase_after(__pos); } public: iterator erase_after(const_iterator __pos) { __glibcxx_check_erase_after(__pos); return iterator(_M_erase_after(__pos.base()), this); } iterator erase_after(const_iterator __pos, const_iterator __last) { __glibcxx_check_erase_range_after(__pos, __last); for (_Base_const_iterator __victim = std::next(__pos.base()); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range2) ._M_sequence(*this, "this") ._M_iterator(__pos, "pos") ._M_iterator(__last, "last")); this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); } return iterator(_Base::erase_after(__pos.base(), __last.base()), this); } void swap(forward_list& __list) noexcept( noexcept(declval<_Base&>().swap(__list)) ) { _Safe::_M_swap(__list); _Base::swap(__list); } void resize(size_type __sz) { this->_M_detach_singular(); // if __sz < size(), invalidate all iterators in [begin+__sz, end() _Base_iterator __victim = _Base::begin(); _Base_iterator __end = _Base::end(); for (size_type __i = __sz; __victim != __end && __i > 0; --__i) ++__victim; for (; __victim != __end; ++__victim) { this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); } __try { _Base::resize(__sz); } __catch(...) { this->_M_revalidate_singular(); __throw_exception_again; } } void resize(size_type __sz, const value_type& __val) { this->_M_detach_singular(); // if __sz < size(), invalidate all iterators in [begin+__sz, end()) _Base_iterator __victim = _Base::begin(); _Base_iterator __end = _Base::end(); for (size_type __i = __sz; __victim != __end && __i > 0; --__i) ++__victim; for (; __victim != __end; ++__victim) { this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); } __try { _Base::resize(__sz, __val); } __catch(...) { this->_M_revalidate_singular(); __throw_exception_again; } } void clear() noexcept { _Base::clear(); this->_M_invalidate_all(); } // 23.2.3.5 forward_list operations: void splice_after(const_iterator __pos, forward_list&& __list) { __glibcxx_check_insert_after(__pos); _GLIBCXX_DEBUG_VERIFY(std::__addressof(__list) != this, _M_message(__gnu_debug::__msg_self_splice) ._M_sequence(*this, "this")); _GLIBCXX_DEBUG_VERIFY(__list.get_allocator() == this->get_allocator(), _M_message(__gnu_debug::__msg_splice_alloc) ._M_sequence(*this) ._M_sequence(__list, "__list")); this->_M_transfer_from_if(__list, [&__list](_Base_const_iterator __it) { return __it != __list._M_base().cbefore_begin() && __it != __list._M_base().end(); }); _Base::splice_after(__pos.base(), std::move(__list._M_base())); } void splice_after(const_iterator __pos, forward_list& __list) { splice_after(__pos, std::move(__list)); } void splice_after(const_iterator __pos, forward_list&& __list, const_iterator __i) { __glibcxx_check_insert_after(__pos); _GLIBCXX_DEBUG_VERIFY(__i._M_before_dereferenceable(), _M_message(__gnu_debug::__msg_splice_bad) ._M_iterator(__i, "__i")); _GLIBCXX_DEBUG_VERIFY(__i._M_attached_to(std::__addressof(__list)), _M_message(__gnu_debug::__msg_splice_other) ._M_iterator(__i, "__i") ._M_sequence(__list, "__list")); _GLIBCXX_DEBUG_VERIFY(__list.get_allocator() == this->get_allocator(), _M_message(__gnu_debug::__msg_splice_alloc) ._M_sequence(*this) ._M_sequence(__list, "__list")); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 250. splicing invalidates iterators _Base_const_iterator __next = std::next(__i.base()); this->_M_transfer_from_if(__list, [__next](_Base_const_iterator __it) { return __it == __next; }); _Base::splice_after(__pos.base(), std::move(__list._M_base()), __i.base()); } void splice_after(const_iterator __pos, forward_list& __list, const_iterator __i) { splice_after(__pos, std::move(__list), __i); } void splice_after(const_iterator __pos, forward_list&& __list, const_iterator __before, const_iterator __last) { typename __gnu_debug::_Distance_traits::__type __dist; auto __listptr = std::__addressof(__list); __glibcxx_check_insert_after(__pos); __glibcxx_check_valid_fl_range(__before, __last, __dist); _GLIBCXX_DEBUG_VERIFY(__before._M_attached_to(__listptr), _M_message(__gnu_debug::__msg_splice_other) ._M_sequence(__list, "list") ._M_iterator(__before, "before")); _GLIBCXX_DEBUG_VERIFY(__before._M_dereferenceable() || __before._M_is_before_begin(), _M_message(__gnu_debug::__msg_valid_range2) ._M_sequence(__list, "list") ._M_iterator(__before, "before") ._M_iterator(__last, "last")); _GLIBCXX_DEBUG_VERIFY(__before != __last, _M_message(__gnu_debug::__msg_valid_range2) ._M_sequence(__list, "list") ._M_iterator(__before, "before") ._M_iterator(__last, "last")); _GLIBCXX_DEBUG_VERIFY(__list.get_allocator() == this->get_allocator(), _M_message(__gnu_debug::__msg_splice_alloc) ._M_sequence(*this) ._M_sequence(__list, "__list")); for (_Base_const_iterator __tmp = std::next(__before.base()); __tmp != __last.base(); ++__tmp) { _GLIBCXX_DEBUG_VERIFY(__tmp != __list._M_base().end(), _M_message(__gnu_debug::__msg_valid_range2) ._M_sequence(__list, "list") ._M_iterator(__before, "before") ._M_iterator(__last, "last")); _GLIBCXX_DEBUG_VERIFY(__listptr != this || __tmp != __pos.base(), _M_message(__gnu_debug::__msg_splice_overlap) ._M_iterator(__tmp, "position") ._M_iterator(__before, "before") ._M_iterator(__last, "last")); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 250. splicing invalidates iterators this->_M_transfer_from_if(__list, [__tmp](_Base_const_iterator __it) { return __it == __tmp; }); } _Base::splice_after(__pos.base(), std::move(__list._M_base()), __before.base(), __last.base()); } void splice_after(const_iterator __pos, forward_list& __list, const_iterator __before, const_iterator __last) { splice_after(__pos, std::move(__list), __before, __last); } void remove(const _Tp& __val) { _Base_iterator __x = _Base::before_begin(); _Base_iterator __old = __x++; while (__x != _Base::end()) { if (*__x == __val) __x = _M_erase_after(__old); else __old = __x++; } } template void remove_if(_Pred __pred) { _Base_iterator __x = _Base::before_begin(); _Base_iterator __old = __x++; while (__x != _Base::end()) { if (__pred(*__x)) __x = _M_erase_after(__old); else __old = __x++; } } void unique() { _Base_iterator __first = _Base::begin(); _Base_iterator __last = _Base::end(); if (__first == __last) return; _Base_iterator __next = std::next(__first); while (__next != __last) { if (*__first == *__next) __next = _M_erase_after(__first); else __first = __next++; } } template void unique(_BinPred __binary_pred) { _Base_iterator __first = _Base::begin(); _Base_iterator __last = _Base::end(); if (__first == __last) return; _Base_iterator __next = std::next(__first); while (__next != __last) { if (__binary_pred(*__first, *__next)) __next = _M_erase_after(__first); else __first = __next++; } } void merge(forward_list&& __list) { if (this != std::__addressof(__list)) { __glibcxx_check_sorted(_Base::begin(), _Base::end()); __glibcxx_check_sorted(__list._M_base().begin(), __list._M_base().end()); this->_M_transfer_from_if(__list, [&__list](_Base_const_iterator __it) { return __it != __list._M_base().cbefore_begin() && __it != __list._M_base().cend(); }); _Base::merge(std::move(__list._M_base())); } } void merge(forward_list& __list) { merge(std::move(__list)); } template void merge(forward_list&& __list, _Comp __comp) { if (this != std::__addressof(__list)) { __glibcxx_check_sorted_pred(_Base::begin(), _Base::end(), __comp); __glibcxx_check_sorted_pred(__list._M_base().begin(), __list._M_base().end(), __comp); this->_M_transfer_from_if(__list, [&__list](_Base_const_iterator __it) { return __it != __list._M_base().cbefore_begin() && __it != __list._M_base().cend(); }); _Base::merge(std::move(__list._M_base()), __comp); } } template void merge(forward_list& __list, _Comp __comp) { merge(std::move(__list), __comp); } using _Base::sort; using _Base::reverse; _Base& _M_base() noexcept { return *this; } const _Base& _M_base() const noexcept { return *this; } }; #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> forward_list(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> forward_list<_ValT, _Allocator>; #endif template bool operator==(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return __lx._M_base() == __ly._M_base(); } template inline bool operator<(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return __lx._M_base() < __ly._M_base(); } template inline bool operator!=(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return !(__lx == __ly); } /// Based on operator< template inline bool operator>(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return (__ly < __lx); } /// Based on operator< template inline bool operator>=(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return !(__lx < __ly); } /// Based on operator< template inline bool operator<=(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return !(__ly < __lx); } /// See std::forward_list::swap(). template inline void swap(forward_list<_Tp, _Alloc>& __lx, forward_list<_Tp, _Alloc>& __ly) noexcept(noexcept(__lx.swap(__ly))) { __lx.swap(__ly); } } // namespace __debug } // namespace std namespace __gnu_debug { template struct _BeforeBeginHelper > { typedef std::__debug::forward_list<_Tp, _Alloc> _Sequence; template static bool _S_Is(const _Safe_iterator<_Iterator, _Sequence>& __it) { return __it.base() == __it._M_get_sequence()->_M_base().before_begin(); } template static bool _S_Is_Beginnest(const _Safe_iterator<_Iterator, _Sequence>& __it) { return _S_Is(__it); } }; template struct _Sequence_traits > { typedef typename std::__debug::forward_list<_Tp, _Alloc>::iterator _It; static typename _Distance_traits<_It>::__type _S_size(const std::__debug::forward_list<_Tp, _Alloc>& __seq) { return __seq.empty() ? std::make_pair(0, __dp_exact) : std::make_pair(1, __dp_equality); } }; #ifndef _GLIBCXX_DEBUG_PEDANTIC template struct _Insert_range_from_self_is_safe< std::__debug::forward_list<_Tp, _Alloc> > { enum { __value = 1 }; }; #endif } #endif PK!Q/@@8/debug/functions.hnu[// Debugging support implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/functions.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_FUNCTIONS_H #define _GLIBCXX_DEBUG_FUNCTIONS_H 1 #include // for __addressof #include // for less #if __cplusplus >= 201103L # include // for is_lvalue_reference and conditional. #endif #include #include namespace __gnu_debug { template class _Safe_iterator; template struct _Insert_range_from_self_is_safe { enum { __value = 0 }; }; template struct _Is_contiguous_sequence : std::__false_type { }; // An arbitrary iterator pointer is not singular. inline bool __check_singular_aux(const void*) { return false; } // We may have an iterator that derives from _Safe_iterator_base but isn't // a _Safe_iterator. template inline bool __check_singular(const _Iterator& __x) { return __check_singular_aux(std::__addressof(__x)); } /** Non-NULL pointers are nonsingular. */ template inline bool __check_singular(const _Tp* __ptr) { return __ptr == 0; } /** Assume that some arbitrary iterator is dereferenceable, because we can't prove that it isn't. */ template inline bool __check_dereferenceable(const _Iterator&) { return true; } /** Non-NULL pointers are dereferenceable. */ template inline bool __check_dereferenceable(const _Tp* __ptr) { return __ptr; } /* Checks that [first, last) is a valid range, and then returns * __first. This routine is useful when we can't use a separate * assertion statement because, e.g., we are in a constructor. */ template inline _InputIterator __check_valid_range(const _InputIterator& __first, const _InputIterator& __last __attribute__((__unused__))) { __glibcxx_check_valid_range(__first, __last); return __first; } /* Handle the case where __other is a pointer to _Sequence::value_type. */ template inline bool __foreign_iterator_aux4(const _Safe_iterator<_Iterator, _Sequence>& __it, const typename _Sequence::value_type* __other) { typedef const typename _Sequence::value_type* _PointerType; typedef std::less<_PointerType> _Less; #if __cplusplus >= 201103L constexpr _Less __l{}; #else const _Less __l = _Less(); #endif const _Sequence* __seq = __it._M_get_sequence(); const _PointerType __begin = std::__addressof(*__seq->_M_base().begin()); const _PointerType __end = std::__addressof(*(__seq->_M_base().end()-1)); // Check whether __other points within the contiguous storage. return __l(__other, __begin) || __l(__end, __other); } /* Fallback overload for when we can't tell, assume it is valid. */ template inline bool __foreign_iterator_aux4(const _Safe_iterator<_Iterator, _Sequence>&, ...) { return true; } /* Handle sequences with contiguous storage */ template inline bool __foreign_iterator_aux3(const _Safe_iterator<_Iterator, _Sequence>& __it, const _InputIterator& __other, const _InputIterator& __other_end, std::__true_type) { if (__other == __other_end) return true; // inserting nothing is safe even if not foreign iters if (__it._M_get_sequence()->begin() == __it._M_get_sequence()->end()) return true; // can't be self-inserting if self is empty return __foreign_iterator_aux4(__it, std::__addressof(*__other)); } /* Handle non-contiguous containers, assume it is valid. */ template inline bool __foreign_iterator_aux3(const _Safe_iterator<_Iterator, _Sequence>&, const _InputIterator&, const _InputIterator&, std::__false_type) { return true; } /** Handle debug iterators from the same type of container. */ template inline bool __foreign_iterator_aux2(const _Safe_iterator<_Iterator, _Sequence>& __it, const _Safe_iterator<_OtherIterator, _Sequence>& __other, const _Safe_iterator<_OtherIterator, _Sequence>&) { return __it._M_get_sequence() != __other._M_get_sequence(); } /** Handle debug iterators from different types of container. */ template inline bool __foreign_iterator_aux2(const _Safe_iterator<_Iterator, _Sequence>& __it, const _Safe_iterator<_OtherIterator, _OtherSequence>&, const _Safe_iterator<_OtherIterator, _OtherSequence>&) { return true; } /* Handle non-debug iterators. */ template inline bool __foreign_iterator_aux2(const _Safe_iterator<_Iterator, _Sequence>& __it, const _InputIterator& __other, const _InputIterator& __other_end) { #if __cplusplus < 201103L typedef _Is_contiguous_sequence<_Sequence> __tag; #else using __lvalref = std::is_lvalue_reference< typename std::iterator_traits<_InputIterator>::reference>; using __contiguous = _Is_contiguous_sequence<_Sequence>; using __tag = typename std::conditional<__lvalref::value, __contiguous, std::__false_type>::type; #endif return __foreign_iterator_aux3(__it, __other, __other_end, __tag()); } /* Handle the case where we aren't really inserting a range after all */ template inline bool __foreign_iterator_aux(const _Safe_iterator<_Iterator, _Sequence>&, _Integral, _Integral, std::__true_type) { return true; } /* Handle all iterators. */ template inline bool __foreign_iterator_aux(const _Safe_iterator<_Iterator, _Sequence>& __it, _InputIterator __other, _InputIterator __other_end, std::__false_type) { return _Insert_range_from_self_is_safe<_Sequence>::__value || __foreign_iterator_aux2(__it, std::__miter_base(__other), std::__miter_base(__other_end)); } template inline bool __foreign_iterator(const _Safe_iterator<_Iterator, _Sequence>& __it, _InputIterator __other, _InputIterator __other_end) { typedef typename std::__is_integer<_InputIterator>::__type _Integral; return __foreign_iterator_aux(__it, __other, __other_end, _Integral()); } /** Checks that __s is non-NULL or __n == 0, and then returns __s. */ template inline const _CharT* __check_string(const _CharT* __s, const _Integer& __n __attribute__((__unused__))) { #ifdef _GLIBCXX_DEBUG_PEDANTIC __glibcxx_assert(__s != 0 || __n == 0); #endif return __s; } /** Checks that __s is non-NULL and then returns __s. */ template inline const _CharT* __check_string(const _CharT* __s) { #ifdef _GLIBCXX_DEBUG_PEDANTIC __glibcxx_assert(__s != 0); #endif return __s; } // Can't check if an input iterator sequence is sorted, because we // can't step through the sequence. template inline bool __check_sorted_aux(const _InputIterator&, const _InputIterator&, std::input_iterator_tag) { return true; } // Can verify if a forward iterator sequence is in fact sorted using // std::__is_sorted template inline bool __check_sorted_aux(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { if (__first == __last) return true; _ForwardIterator __next = __first; for (++__next; __next != __last; __first = __next, (void)++__next) if (*__next < *__first) return false; return true; } // Can't check if an input iterator sequence is sorted, because we can't step // through the sequence. template inline bool __check_sorted_aux(const _InputIterator&, const _InputIterator&, _Predicate, std::input_iterator_tag) { return true; } // Can verify if a forward iterator sequence is in fact sorted using // std::__is_sorted template inline bool __check_sorted_aux(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred, std::forward_iterator_tag) { if (__first == __last) return true; _ForwardIterator __next = __first; for (++__next; __next != __last; __first = __next, (void)++__next) if (__pred(*__next, *__first)) return false; return true; } // Determine if a sequence is sorted. template inline bool __check_sorted(const _InputIterator& __first, const _InputIterator& __last) { // Verify that the < operator for elements in the sequence is a // StrictWeakOrdering by checking that it is irreflexive. __glibcxx_assert(__first == __last || !(*__first < *__first)); return __check_sorted_aux(__first, __last, std::__iterator_category(__first)); } template inline bool __check_sorted(const _InputIterator& __first, const _InputIterator& __last, _Predicate __pred) { // Verify that the predicate is StrictWeakOrdering by checking that it // is irreflexive. __glibcxx_assert(__first == __last || !__pred(*__first, *__first)); return __check_sorted_aux(__first, __last, __pred, std::__iterator_category(__first)); } template inline bool __check_sorted_set_aux(const _InputIterator& __first, const _InputIterator& __last, std::__true_type) { return __check_sorted(__first, __last); } template inline bool __check_sorted_set_aux(const _InputIterator&, const _InputIterator&, std::__false_type) { return true; } template inline bool __check_sorted_set_aux(const _InputIterator& __first, const _InputIterator& __last, _Predicate __pred, std::__true_type) { return __check_sorted(__first, __last, __pred); } template inline bool __check_sorted_set_aux(const _InputIterator&, const _InputIterator&, _Predicate, std::__false_type) { return true; } // ... special variant used in std::merge, std::includes, std::set_*. template inline bool __check_sorted_set(const _InputIterator1& __first, const _InputIterator1& __last, const _InputIterator2&) { typedef typename std::iterator_traits<_InputIterator1>::value_type _ValueType1; typedef typename std::iterator_traits<_InputIterator2>::value_type _ValueType2; typedef typename std::__are_same<_ValueType1, _ValueType2>::__type _SameType; return __check_sorted_set_aux(__first, __last, _SameType()); } template inline bool __check_sorted_set(const _InputIterator1& __first, const _InputIterator1& __last, const _InputIterator2&, _Predicate __pred) { typedef typename std::iterator_traits<_InputIterator1>::value_type _ValueType1; typedef typename std::iterator_traits<_InputIterator2>::value_type _ValueType2; typedef typename std::__are_same<_ValueType1, _ValueType2>::__type _SameType; return __check_sorted_set_aux(__first, __last, __pred, _SameType()); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 270. Binary search requirements overly strict // Determine if a sequence is partitioned w.r.t. this element. template inline bool __check_partitioned_lower(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { while (__first != __last && *__first < __value) ++__first; if (__first != __last) { ++__first; while (__first != __last && !(*__first < __value)) ++__first; } return __first == __last; } template inline bool __check_partitioned_upper(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { while (__first != __last && !(__value < *__first)) ++__first; if (__first != __last) { ++__first; while (__first != __last && __value < *__first) ++__first; } return __first == __last; } // Determine if a sequence is partitioned w.r.t. this element. template inline bool __check_partitioned_lower(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value, _Pred __pred) { while (__first != __last && bool(__pred(*__first, __value))) ++__first; if (__first != __last) { ++__first; while (__first != __last && !bool(__pred(*__first, __value))) ++__first; } return __first == __last; } template inline bool __check_partitioned_upper(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value, _Pred __pred) { while (__first != __last && !bool(__pred(__value, *__first))) ++__first; if (__first != __last) { ++__first; while (__first != __last && bool(__pred(__value, *__first))) ++__first; } return __first == __last; } #if __cplusplus >= 201103L struct _Irreflexive_checker { template static typename std::iterator_traits<_It>::reference __ref(); template() < __ref<_It>())> static bool _S_is_valid(_It __it) { return !(*__it < *__it); } // Fallback method if operator doesn't exist. template static bool _S_is_valid(_Args...) { return true; } template()(__ref<_It>(), __ref<_It>()))> static bool _S_is_valid_pred(_It __it, _Pred __pred) { return !__pred(*__it, *__it); } // Fallback method if predicate can't be invoked. template static bool _S_is_valid_pred(_Args...) { return true; } }; template inline bool __is_irreflexive(_Iterator __it) { return _Irreflexive_checker::_S_is_valid(__it); } template inline bool __is_irreflexive_pred(_Iterator __it, _Pred __pred) { return _Irreflexive_checker::_S_is_valid_pred(__it, __pred); } #endif } // namespace __gnu_debug #endif PK! LՍ8/debug/helper_functions.hnu[// Debugging support implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/helper_functions.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_HELPER_FUNCTIONS_H #define _GLIBCXX_DEBUG_HELPER_FUNCTIONS_H 1 #include // for iterator_traits, // categories and _Iter_base #include // for __is_integer #include // for pair namespace __gnu_debug { /** The precision to which we can calculate the distance between * two iterators. */ enum _Distance_precision { __dp_none, // Not even an iterator type __dp_equality, //< Can compare iterator equality, only __dp_sign, //< Can determine equality and ordering __dp_exact //< Can determine distance precisely }; template::__type> struct _Distance_traits { private: typedef typename std::iterator_traits<_Iterator>::difference_type _ItDiffType; template::__type> struct _DiffTraits { typedef _DiffType __type; }; template struct _DiffTraits<_DiffType, std::__true_type> { typedef std::ptrdiff_t __type; }; typedef typename _DiffTraits<_ItDiffType>::__type _DiffType; public: typedef std::pair<_DiffType, _Distance_precision> __type; }; template struct _Distance_traits<_Integral, std::__true_type> { typedef std::pair __type; }; /** Determine the distance between two iterators with some known * precision. */ template inline typename _Distance_traits<_Iterator>::__type __get_distance(const _Iterator& __lhs, const _Iterator& __rhs, std::random_access_iterator_tag) { return std::make_pair(__rhs - __lhs, __dp_exact); } template inline typename _Distance_traits<_Iterator>::__type __get_distance(const _Iterator& __lhs, const _Iterator& __rhs, std::input_iterator_tag) { if (__lhs == __rhs) return std::make_pair(0, __dp_exact); return std::make_pair(1, __dp_equality); } template inline typename _Distance_traits<_Iterator>::__type __get_distance(const _Iterator& __lhs, const _Iterator& __rhs) { return __get_distance(__lhs, __rhs, std::__iterator_category(__lhs)); } /** We say that integral types for a valid range, and defer to other * routines to realize what to do with integral types instead of * iterators. */ template inline bool __valid_range_aux(const _Integral&, const _Integral&, typename _Distance_traits<_Integral>::__type& __dist, std::__true_type) { __dist = std::make_pair(0, __dp_none); return true; } /** We have iterators, so figure out what kind of iterators that are * to see if we can check the range ahead of time. */ template inline bool __valid_range_aux(const _InputIterator& __first, const _InputIterator& __last, typename _Distance_traits<_InputIterator>::__type& __dist, std::__false_type) { __dist = __get_distance(__first, __last); switch (__dist.second) { case __dp_none: break; case __dp_equality: if (__dist.first == 0) return true; break; case __dp_sign: case __dp_exact: return __dist.first >= 0; } // Can't tell so assume it is fine. return true; } /** Don't know what these iterators are, or if they are even * iterators (we may get an integral type for InputIterator), so * see if they are integral and pass them on to the next phase * otherwise. */ template inline bool __valid_range(const _InputIterator& __first, const _InputIterator& __last, typename _Distance_traits<_InputIterator>::__type& __dist) { typedef typename std::__is_integer<_InputIterator>::__type _Integral; return __valid_range_aux(__first, __last, __dist, _Integral()); } template inline bool __valid_range(const _InputIterator& __first, const _InputIterator& __last) { typename _Distance_traits<_InputIterator>::__type __dist; return __valid_range(__first, __last, __dist); } #if __cplusplus < 201103L // Helper struct to detect random access safe iterators. template struct __is_safe_random_iterator { enum { __value = 0 }; typedef std::__false_type __type; }; template struct _Siter_base : std::_Iter_base<_Iterator, __is_safe_random_iterator<_Iterator>::__value> { }; /** Helper function to extract base iterator of random access safe iterator in order to reduce performance impact of debug mode. Limited to random access iterator because it is the only category for which it is possible to check for correct iterators order in the __valid_range function thanks to the < operator. */ template inline typename _Siter_base<_Iterator>::iterator_type __base(_Iterator __it) { return _Siter_base<_Iterator>::_S_base(__it); } #else template inline _Iterator __base(_Iterator __it) { return __it; } #endif #if __cplusplus < 201103L template struct _Unsafe_type { typedef _Iterator _Type; }; #endif /* Remove debug mode safe iterator layer, if any. */ template inline _Iterator __unsafe(_Iterator __it) { return __it; } } #endif PK!^ }YY 8/debug/listnu[// Debugging list implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/list * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_LIST #define _GLIBCXX_DEBUG_LIST 1 #pragma GCC system_header #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::list with safety/checking/debug instrumentation. template > class list : public __gnu_debug::_Safe_container< list<_Tp, _Allocator>, _Allocator, __gnu_debug::_Safe_node_sequence>, public _GLIBCXX_STD_C::list<_Tp, _Allocator> { typedef _GLIBCXX_STD_C::list<_Tp, _Allocator> _Base; typedef __gnu_debug::_Safe_container< list, _Allocator, __gnu_debug::_Safe_node_sequence> _Safe; typedef typename _Base::iterator _Base_iterator; typedef typename _Base::const_iterator _Base_const_iterator; typedef __gnu_debug::_Equal_to<_Base_const_iterator> _Equal; typedef __gnu_debug::_Not_equal_to<_Base_const_iterator> _Not_equal; public: typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator<_Base_iterator, list> iterator; typedef __gnu_debug::_Safe_iterator<_Base_const_iterator, list> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef _Tp value_type; typedef _Allocator allocator_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // 23.2.2.1 construct/copy/destroy: #if __cplusplus < 201103L list() : _Base() { } list(const list& __x) : _Base(__x) { } ~list() { } #else list() = default; list(const list&) = default; list(list&&) = default; list(initializer_list __l, const allocator_type& __a = allocator_type()) : _Base(__l, __a) { } ~list() = default; list(const list& __x, const allocator_type& __a) : _Base(__x, __a) { } list(list&& __x, const allocator_type& __a) : _Base(std::move(__x), __a) { } #endif explicit list(const _Allocator& __a) _GLIBCXX_NOEXCEPT : _Base(__a) { } #if __cplusplus >= 201103L explicit list(size_type __n, const allocator_type& __a = allocator_type()) : _Base(__n, __a) { } list(size_type __n, const _Tp& __value, const _Allocator& __a = _Allocator()) : _Base(__n, __value, __a) { } #else explicit list(size_type __n, const _Tp& __value = _Tp(), const _Allocator& __a = _Allocator()) : _Base(__n, __value, __a) { } #endif #if __cplusplus >= 201103L template> #else template #endif list(_InputIterator __first, _InputIterator __last, const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __a) { } list(const _Base& __x) : _Base(__x) { } #if __cplusplus < 201103L list& operator=(const list& __x) { this->_M_safe() = __x; _M_base() = __x; return *this; } #else list& operator=(const list&) = default; list& operator=(list&&) = default; list& operator=(initializer_list __l) { this->_M_invalidate_all(); _M_base() = __l; return *this; } void assign(initializer_list __l) { _Base::assign(__l); this->_M_invalidate_all(); } #endif #if __cplusplus >= 201103L template> #else template #endif void assign(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::assign(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::assign(__first, __last); this->_M_invalidate_all(); } void assign(size_type __n, const _Tp& __t) { _Base::assign(__n, __t); this->_M_invalidate_all(); } using _Base::get_allocator; // iterators: iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // 23.2.2.2 capacity: using _Base::empty; using _Base::size; using _Base::max_size; #if __cplusplus >= 201103L void resize(size_type __sz) { this->_M_detach_singular(); // if __sz < size(), invalidate all iterators in [begin + __sz, end()) _Base_iterator __victim = _Base::begin(); _Base_iterator __end = _Base::end(); for (size_type __i = __sz; __victim != __end && __i > 0; --__i) ++__victim; for (; __victim != __end; ++__victim) this->_M_invalidate_if(_Equal(__victim)); __try { _Base::resize(__sz); } __catch(...) { this->_M_revalidate_singular(); __throw_exception_again; } } void resize(size_type __sz, const _Tp& __c) { this->_M_detach_singular(); // if __sz < size(), invalidate all iterators in [begin + __sz, end()) _Base_iterator __victim = _Base::begin(); _Base_iterator __end = _Base::end(); for (size_type __i = __sz; __victim != __end && __i > 0; --__i) ++__victim; for (; __victim != __end; ++__victim) this->_M_invalidate_if(_Equal(__victim)); __try { _Base::resize(__sz, __c); } __catch(...) { this->_M_revalidate_singular(); __throw_exception_again; } } #else void resize(size_type __sz, _Tp __c = _Tp()) { this->_M_detach_singular(); // if __sz < size(), invalidate all iterators in [begin + __sz, end()) _Base_iterator __victim = _Base::begin(); _Base_iterator __end = _Base::end(); for (size_type __i = __sz; __victim != __end && __i > 0; --__i) ++__victim; for (; __victim != __end; ++__victim) this->_M_invalidate_if(_Equal(__victim)); __try { _Base::resize(__sz, __c); } __catch(...) { this->_M_revalidate_singular(); __throw_exception_again; } } #endif // element access: reference front() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::front(); } const_reference front() const _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::front(); } reference back() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::back(); } const_reference back() const _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::back(); } // 23.2.2.3 modifiers: using _Base::push_front; #if __cplusplus >= 201103L using _Base::emplace_front; #endif void pop_front() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); this->_M_invalidate_if(_Equal(_Base::begin())); _Base::pop_front(); } using _Base::push_back; #if __cplusplus >= 201103L using _Base::emplace_back; #endif void pop_back() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); this->_M_invalidate_if(_Equal(--_Base::end())); _Base::pop_back(); } #if __cplusplus >= 201103L template iterator emplace(const_iterator __position, _Args&&... __args) { __glibcxx_check_insert(__position); return iterator(_Base::emplace(__position.base(), std::forward<_Args>(__args)...), this); } #endif iterator #if __cplusplus >= 201103L insert(const_iterator __position, const _Tp& __x) #else insert(iterator __position, const _Tp& __x) #endif { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), __x), this); } #if __cplusplus >= 201103L iterator insert(const_iterator __position, _Tp&& __x) { return emplace(__position, std::move(__x)); } iterator insert(const_iterator __p, initializer_list __l) { __glibcxx_check_insert(__p); return iterator(_Base::insert(__p.base(), __l), this); } #endif #if __cplusplus >= 201103L iterator insert(const_iterator __position, size_type __n, const _Tp& __x) { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), __n, __x), this); } #else void insert(iterator __position, size_type __n, const _Tp& __x) { __glibcxx_check_insert(__position); _Base::insert(__position.base(), __n, __x); } #endif #if __cplusplus >= 201103L template> iterator insert(const_iterator __position, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range(__position, __first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) return { _Base::insert(__position.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)), this }; else return { _Base::insert(__position.base(), __first, __last), this }; } #else template void insert(iterator __position, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range(__position, __first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__position.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__position.base(), __first, __last); } #endif private: _Base_iterator #if __cplusplus >= 201103L _M_erase(_Base_const_iterator __position) noexcept #else _M_erase(_Base_iterator __position) #endif { this->_M_invalidate_if(_Equal(__position)); return _Base::erase(__position); } public: iterator #if __cplusplus >= 201103L erase(const_iterator __position) noexcept #else erase(iterator __position) #endif { __glibcxx_check_erase(__position); return iterator(_M_erase(__position.base()), this); } iterator #if __cplusplus >= 201103L erase(const_iterator __first, const_iterator __last) noexcept #else erase(iterator __first, iterator __last) #endif { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "position") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } return iterator(_Base::erase(__first.base(), __last.base()), this); } void swap(list& __x) _GLIBCXX_NOEXCEPT_IF( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() _GLIBCXX_NOEXCEPT { _Base::clear(); this->_M_invalidate_all(); } // 23.2.2.4 list operations: void #if __cplusplus >= 201103L splice(const_iterator __position, list&& __x) noexcept #else splice(iterator __position, list& __x) #endif { _GLIBCXX_DEBUG_VERIFY(std::__addressof(__x) != this, _M_message(__gnu_debug::__msg_self_splice) ._M_sequence(*this, "this")); this->_M_transfer_from_if(__x, _Not_equal(__x._M_base().end())); _Base::splice(__position.base(), _GLIBCXX_MOVE(__x._M_base())); } #if __cplusplus >= 201103L void splice(const_iterator __position, list& __x) noexcept { splice(__position, std::move(__x)); } #endif void #if __cplusplus >= 201103L splice(const_iterator __position, list&& __x, const_iterator __i) noexcept #else splice(iterator __position, list& __x, iterator __i) #endif { __glibcxx_check_insert(__position); // We used to perform the splice_alloc check: not anymore, redundant // after implementing the relevant bits of N1599. _GLIBCXX_DEBUG_VERIFY(__i._M_dereferenceable(), _M_message(__gnu_debug::__msg_splice_bad) ._M_iterator(__i, "__i")); _GLIBCXX_DEBUG_VERIFY(__i._M_attached_to(std::__addressof(__x)), _M_message(__gnu_debug::__msg_splice_other) ._M_iterator(__i, "__i")._M_sequence(__x, "__x")); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 250. splicing invalidates iterators this->_M_transfer_from_if(__x, _Equal(__i.base())); _Base::splice(__position.base(), _GLIBCXX_MOVE(__x._M_base()), __i.base()); } #if __cplusplus >= 201103L void splice(const_iterator __position, list& __x, const_iterator __i) noexcept { splice(__position, std::move(__x), __i); } #endif void #if __cplusplus >= 201103L splice(const_iterator __position, list&& __x, const_iterator __first, const_iterator __last) noexcept #else splice(iterator __position, list& __x, iterator __first, iterator __last) #endif { __glibcxx_check_insert(__position); __glibcxx_check_valid_range(__first, __last); _GLIBCXX_DEBUG_VERIFY(__first._M_attached_to(std::__addressof(__x)), _M_message(__gnu_debug::__msg_splice_other) ._M_sequence(__x, "x") ._M_iterator(__first, "first")); // We used to perform the splice_alloc check: not anymore, redundant // after implementing the relevant bits of N1599. for (_Base_const_iterator __tmp = __first.base(); __tmp != __last.base(); ++__tmp) { _GLIBCXX_DEBUG_VERIFY(__tmp != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); _GLIBCXX_DEBUG_VERIFY(std::__addressof(__x) != this || __tmp != __position.base(), _M_message(__gnu_debug::__msg_splice_overlap) ._M_iterator(__tmp, "position") ._M_iterator(__first, "first") ._M_iterator(__last, "last")); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 250. splicing invalidates iterators this->_M_transfer_from_if(__x, _Equal(__tmp)); } _Base::splice(__position.base(), _GLIBCXX_MOVE(__x._M_base()), __first.base(), __last.base()); } #if __cplusplus >= 201103L void splice(const_iterator __position, list& __x, const_iterator __first, const_iterator __last) noexcept { splice(__position, std::move(__x), __first, __last); } #endif void remove(const _Tp& __value) { for (_Base_iterator __x = _Base::begin(); __x != _Base::end(); ) { if (*__x == __value) __x = _M_erase(__x); else ++__x; } } template void remove_if(_Predicate __pred) { for (_Base_iterator __x = _Base::begin(); __x != _Base::end(); ) { if (__pred(*__x)) __x = _M_erase(__x); else ++__x; } } void unique() { _Base_iterator __first = _Base::begin(); _Base_iterator __last = _Base::end(); if (__first == __last) return; _Base_iterator __next = __first; ++__next; while (__next != __last) { if (*__first == *__next) __next = _M_erase(__next); else __first = __next++; } } template void unique(_BinaryPredicate __binary_pred) { _Base_iterator __first = _Base::begin(); _Base_iterator __last = _Base::end(); if (__first == __last) return; _Base_iterator __next = __first; ++__next; while (__next != __last) { if (__binary_pred(*__first, *__next)) __next = _M_erase(__next); else __first = __next++; } } void #if __cplusplus >= 201103L merge(list&& __x) #else merge(list& __x) #endif { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 300. list::merge() specification incomplete if (this != std::__addressof(__x)) { __glibcxx_check_sorted(_Base::begin(), _Base::end()); __glibcxx_check_sorted(__x.begin().base(), __x.end().base()); this->_M_transfer_from_if(__x, _Not_equal(__x._M_base().end())); _Base::merge(_GLIBCXX_MOVE(__x._M_base())); } } #if __cplusplus >= 201103L void merge(list& __x) { merge(std::move(__x)); } #endif template void #if __cplusplus >= 201103L merge(list&& __x, _Compare __comp) #else merge(list& __x, _Compare __comp) #endif { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 300. list::merge() specification incomplete if (this != std::__addressof(__x)) { __glibcxx_check_sorted_pred(_Base::begin(), _Base::end(), __comp); __glibcxx_check_sorted_pred(__x.begin().base(), __x.end().base(), __comp); this->_M_transfer_from_if(__x, _Not_equal(__x._M_base().end())); _Base::merge(_GLIBCXX_MOVE(__x._M_base()), __comp); } } #if __cplusplus >= 201103L template void merge(list& __x, _Compare __comp) { merge(std::move(__x), __comp); } #endif void sort() { _Base::sort(); } template void sort(_StrictWeakOrdering __pred) { _Base::sort(__pred); } using _Base::reverse; _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } }; #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> list(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> list<_ValT, _Allocator>; #endif template inline bool operator==(const list<_Tp, _Alloc>& __lhs, const list<_Tp, _Alloc>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator!=(const list<_Tp, _Alloc>& __lhs, const list<_Tp, _Alloc>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator<(const list<_Tp, _Alloc>& __lhs, const list<_Tp, _Alloc>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<=(const list<_Tp, _Alloc>& __lhs, const list<_Tp, _Alloc>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator>=(const list<_Tp, _Alloc>& __lhs, const list<_Tp, _Alloc>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>(const list<_Tp, _Alloc>& __lhs, const list<_Tp, _Alloc>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template inline void swap(list<_Tp, _Alloc>& __lhs, list<_Tp, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT_IF(noexcept(__lhs.swap(__rhs))) { __lhs.swap(__rhs); } } // namespace __debug } // namespace std namespace __gnu_debug { #ifndef _GLIBCXX_USE_CXX11_ABI // If not using C++11 list::size() is not in O(1) so we do not use it. template struct _Sequence_traits > { typedef typename std::__debug::list<_Tp, _Alloc>::iterator _It; static typename _Distance_traits<_It>::__type _S_size(const std::__debug::list<_Tp, _Alloc>& __seq) { return __seq.empty() ? std::make_pair(0, __dp_exact) : std::make_pair(1, __dp_equality); } }; #endif #ifndef _GLIBCXX_DEBUG_PEDANTIC template struct _Insert_range_from_self_is_safe > { enum { __value = 1 }; }; #endif } #endif PK!dlEE8/debug/macros.hnu[// Debugging support implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/macros.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_MACROS_H #define _GLIBCXX_DEBUG_MACROS_H 1 /** * Macros used by the implementation to verify certain * properties. These macros may only be used directly by the debug * wrappers. Note that these are macros (instead of the more obviously * @a correct choice of making them functions) because we need line and * file information at the call site, to minimize the distance between * the user error and where the error is reported. * */ #define _GLIBCXX_DEBUG_VERIFY_AT(_Condition,_ErrorMessage,_File,_Line) \ do \ { \ if (! (_Condition)) \ __gnu_debug::_Error_formatter::_M_at(_File, _Line) \ ._ErrorMessage._M_error(); \ } while (false) #define _GLIBCXX_DEBUG_VERIFY(_Condition,_ErrorMessage) \ _GLIBCXX_DEBUG_VERIFY_AT(_Condition,_ErrorMessage,__FILE__,__LINE__) // Verify that [_First, _Last) forms a valid iterator range. #define __glibcxx_check_valid_range(_First,_Last) \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__valid_range(_First, _Last), \ _M_message(__gnu_debug::__msg_valid_range) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) #define __glibcxx_check_valid_range2(_First,_Last,_Dist) \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__valid_range(_First, _Last, _Dist), \ _M_message(__gnu_debug::__msg_valid_range) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) // Verify that [_First, _Last) forms a non-empty iterator range. #define __glibcxx_check_non_empty_range(_First,_Last) \ _GLIBCXX_DEBUG_VERIFY(_First != _Last, \ _M_message(__gnu_debug::__msg_non_empty_range) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) /** Verify that we can insert into *this with the iterator _Position. * Insertion into a container at a specific position requires that * the iterator be nonsingular, either dereferenceable or past-the-end, * and that it reference the sequence we are inserting into. Note that * this macro is only valid when the container is a_Safe_sequence and * the iterator is a _Safe_iterator. */ #define __glibcxx_check_insert(_Position) \ _GLIBCXX_DEBUG_VERIFY(!_Position._M_singular(), \ _M_message(__gnu_debug::__msg_insert_singular) \ ._M_sequence(*this, "this") \ ._M_iterator(_Position, #_Position)); \ _GLIBCXX_DEBUG_VERIFY(_Position._M_attached_to(this), \ _M_message(__gnu_debug::__msg_insert_different) \ ._M_sequence(*this, "this") \ ._M_iterator(_Position, #_Position)) /** Verify that we can insert into *this after the iterator _Position. * Insertion into a container after a specific position requires that * the iterator be nonsingular, either dereferenceable or before-begin, * and that it reference the sequence we are inserting into. Note that * this macro is only valid when the container is a_Safe_sequence and * the iterator is a _Safe_iterator. */ #define __glibcxx_check_insert_after(_Position) \ __glibcxx_check_insert(_Position); \ _GLIBCXX_DEBUG_VERIFY(!_Position._M_is_end(), \ _M_message(__gnu_debug::__msg_insert_after_end) \ ._M_sequence(*this, "this") \ ._M_iterator(_Position, #_Position)) /** Verify that we can insert the values in the iterator range * [_First, _Last) into *this with the iterator _Position. Insertion * into a container at a specific position requires that the iterator * be nonsingular (i.e., either dereferenceable or past-the-end), * that it reference the sequence we are inserting into, and that the * iterator range [_First, _Last) is a valid (possibly empty) * range which does not reference the sequence we are inserting into. * Note that this macro is only valid when the container is a * _Safe_sequence and the _Position iterator is a _Safe_iterator. */ #define __glibcxx_check_insert_range(_Position,_First,_Last,_Dist) \ __glibcxx_check_valid_range2(_First,_Last,_Dist); \ __glibcxx_check_insert(_Position); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__foreign_iterator(_Position,_First,_Last),\ _M_message(__gnu_debug::__msg_insert_range_from_self)\ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_sequence(*this, "this")) /** Verify that we can insert the values in the iterator range * [_First, _Last) into *this after the iterator _Position. Insertion * into a container after a specific position requires that the iterator * be nonsingular (i.e., either dereferenceable or past-the-end), * that it reference the sequence we are inserting into, and that the * iterator range [_First, _Last) is a valid (possibly empty) * range which does not reference the sequence we are inserting into. * Note that this macro is only valid when the container is a * _Safe_sequence and the _Position iterator is a _Safe_iterator. */ #define __glibcxx_check_insert_range_after(_Position,_First,_Last,_Dist)\ __glibcxx_check_valid_range2(_First,_Last,_Dist); \ __glibcxx_check_insert_after(_Position); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__foreign_iterator(_Position,_First,_Last),\ _M_message(__gnu_debug::__msg_insert_range_from_self)\ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_sequence(*this, "this")) /** Verify that we can erase the element referenced by the iterator * _Position. We can erase the element if the _Position iterator is * dereferenceable and references this sequence. */ #define __glibcxx_check_erase(_Position) \ _GLIBCXX_DEBUG_VERIFY(_Position._M_dereferenceable(), \ _M_message(__gnu_debug::__msg_erase_bad) \ ._M_sequence(*this, "this") \ ._M_iterator(_Position, #_Position)); \ _GLIBCXX_DEBUG_VERIFY(_Position._M_attached_to(this), \ _M_message(__gnu_debug::__msg_erase_different) \ ._M_sequence(*this, "this") \ ._M_iterator(_Position, #_Position)) /** Verify that we can erase the element after the iterator * _Position. We can erase the element if the _Position iterator is * before a dereferenceable one and references this sequence. */ #define __glibcxx_check_erase_after(_Position) \ _GLIBCXX_DEBUG_VERIFY(_Position._M_before_dereferenceable(), \ _M_message(__gnu_debug::__msg_erase_after_bad) \ ._M_sequence(*this, "this") \ ._M_iterator(_Position, #_Position)); \ _GLIBCXX_DEBUG_VERIFY(_Position._M_attached_to(this), \ _M_message(__gnu_debug::__msg_erase_different) \ ._M_sequence(*this, "this") \ ._M_iterator(_Position, #_Position)) /** Verify that we can erase the elements in the iterator range * [_First, _Last). We can erase the elements if [_First, _Last) is a * valid iterator range within this sequence. */ #define __glibcxx_check_erase_range(_First,_Last) \ __glibcxx_check_valid_range(_First,_Last); \ _GLIBCXX_DEBUG_VERIFY(_First._M_attached_to(this), \ _M_message(__gnu_debug::__msg_erase_different) \ ._M_sequence(*this, "this") \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) /** Verify that we can erase the elements in the iterator range * (_First, _Last). We can erase the elements if (_First, _Last) is a * valid iterator range within this sequence. */ #define __glibcxx_check_erase_range_after(_First,_Last) \ _GLIBCXX_DEBUG_VERIFY(_First._M_can_compare(_Last), \ _M_message(__gnu_debug::__msg_erase_different) \ ._M_sequence(*this, "this") \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)); \ _GLIBCXX_DEBUG_VERIFY(_First._M_attached_to(this), \ _M_message(__gnu_debug::__msg_erase_different) \ ._M_sequence(*this, "this") \ ._M_iterator(_First, #_First)); \ _GLIBCXX_DEBUG_VERIFY(_First != _Last, \ _M_message(__gnu_debug::__msg_valid_range2) \ ._M_sequence(*this, "this") \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)); \ _GLIBCXX_DEBUG_VERIFY(_First._M_incrementable(), \ _M_message(__gnu_debug::__msg_valid_range2) \ ._M_sequence(*this, "this") \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)); \ _GLIBCXX_DEBUG_VERIFY(!_Last._M_is_before_begin(), \ _M_message(__gnu_debug::__msg_valid_range2) \ ._M_sequence(*this, "this") \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) \ // Verify that the subscript _N is less than the container's size. #define __glibcxx_check_subscript(_N) \ _GLIBCXX_DEBUG_VERIFY(_N < this->size(), \ _M_message(__gnu_debug::__msg_subscript_oob) \ ._M_sequence(*this, "this") \ ._M_integer(_N, #_N) \ ._M_integer(this->size(), "size")) // Verify that the bucket _N is less than the container's buckets count. #define __glibcxx_check_bucket_index(_N) \ _GLIBCXX_DEBUG_VERIFY(_N < this->bucket_count(), \ _M_message(__gnu_debug::__msg_bucket_index_oob) \ ._M_sequence(*this, "this") \ ._M_integer(_N, #_N) \ ._M_integer(this->bucket_count(), "size")) // Verify that the container is nonempty #define __glibcxx_check_nonempty() \ _GLIBCXX_DEBUG_VERIFY(! this->empty(), \ _M_message(__gnu_debug::__msg_empty) \ ._M_sequence(*this, "this")) // Verify that the iterator range [_First, _Last) is sorted #define __glibcxx_check_sorted(_First,_Last) \ __glibcxx_check_valid_range(_First,_Last); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__check_sorted( \ __gnu_debug::__base(_First), \ __gnu_debug::__base(_Last)), \ _M_message(__gnu_debug::__msg_unsorted) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) /** Verify that the iterator range [_First, _Last) is sorted by the predicate _Pred. */ #define __glibcxx_check_sorted_pred(_First,_Last,_Pred) \ __glibcxx_check_valid_range(_First,_Last); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__check_sorted( \ __gnu_debug::__base(_First), \ __gnu_debug::__base(_Last), _Pred), \ _M_message(__gnu_debug::__msg_unsorted_pred) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_string(#_Pred)) // Special variant for std::merge, std::includes, std::set_* #define __glibcxx_check_sorted_set(_First1,_Last1,_First2) \ __glibcxx_check_valid_range(_First1,_Last1); \ _GLIBCXX_DEBUG_VERIFY( \ __gnu_debug::__check_sorted_set(__gnu_debug::__base(_First1), \ __gnu_debug::__base(_Last1), _First2),\ _M_message(__gnu_debug::__msg_unsorted) \ ._M_iterator(_First1, #_First1) \ ._M_iterator(_Last1, #_Last1)) // Likewise with a _Pred. #define __glibcxx_check_sorted_set_pred(_First1,_Last1,_First2,_Pred) \ __glibcxx_check_valid_range(_First1,_Last1); \ _GLIBCXX_DEBUG_VERIFY( \ __gnu_debug::__check_sorted_set(__gnu_debug::__base(_First1), \ __gnu_debug::__base(_Last1), \ _First2, _Pred), \ _M_message(__gnu_debug::__msg_unsorted_pred) \ ._M_iterator(_First1, #_First1) \ ._M_iterator(_Last1, #_Last1) \ ._M_string(#_Pred)) /** Verify that the iterator range [_First, _Last) is partitioned w.r.t. the value _Value. */ #define __glibcxx_check_partitioned_lower(_First,_Last,_Value) \ __glibcxx_check_valid_range(_First,_Last); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__check_partitioned_lower( \ __gnu_debug::__base(_First), \ __gnu_debug::__base(_Last), _Value), \ _M_message(__gnu_debug::__msg_unpartitioned) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_string(#_Value)) #define __glibcxx_check_partitioned_upper(_First,_Last,_Value) \ __glibcxx_check_valid_range(_First,_Last); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__check_partitioned_upper( \ __gnu_debug::__base(_First), \ __gnu_debug::__base(_Last), _Value), \ _M_message(__gnu_debug::__msg_unpartitioned) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_string(#_Value)) /** Verify that the iterator range [_First, _Last) is partitioned w.r.t. the value _Value and predicate _Pred. */ #define __glibcxx_check_partitioned_lower_pred(_First,_Last,_Value,_Pred) \ __glibcxx_check_valid_range(_First,_Last); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__check_partitioned_lower( \ __gnu_debug::__base(_First), \ __gnu_debug::__base(_Last), _Value, _Pred), \ _M_message(__gnu_debug::__msg_unpartitioned_pred) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_string(#_Pred) \ ._M_string(#_Value)) /** Verify that the iterator range [_First, _Last) is partitioned w.r.t. the value _Value and predicate _Pred. */ #define __glibcxx_check_partitioned_upper_pred(_First,_Last,_Value,_Pred) \ __glibcxx_check_valid_range(_First,_Last); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__check_partitioned_upper( \ __gnu_debug::__base(_First), \ __gnu_debug::__base(_Last), _Value, _Pred), \ _M_message(__gnu_debug::__msg_unpartitioned_pred) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_string(#_Pred) \ ._M_string(#_Value)) // Verify that the iterator range [_First, _Last) is a heap #define __glibcxx_check_heap(_First,_Last) \ _GLIBCXX_DEBUG_VERIFY(std::__is_heap(__gnu_debug::__base(_First), \ __gnu_debug::__base(_Last)), \ _M_message(__gnu_debug::__msg_not_heap) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) /** Verify that the iterator range [_First, _Last) is a heap w.r.t. the predicate _Pred. */ #define __glibcxx_check_heap_pred(_First,_Last,_Pred) \ _GLIBCXX_DEBUG_VERIFY(std::__is_heap(__gnu_debug::__base(_First), \ __gnu_debug::__base(_Last), \ _Pred), \ _M_message(__gnu_debug::__msg_not_heap_pred) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_string(#_Pred)) // Verify that the container is not self move assigned #define __glibcxx_check_self_move_assign(_Other) \ _GLIBCXX_DEBUG_VERIFY(this != &_Other, \ _M_message(__gnu_debug::__msg_self_move_assign) \ ._M_sequence(*this, "this")) // Verify that load factor is positive #define __glibcxx_check_max_load_factor(_F) \ _GLIBCXX_DEBUG_VERIFY(_F > 0.0f, \ _M_message(__gnu_debug::__msg_valid_load_factor) \ ._M_sequence(*this, "this")) #define __glibcxx_check_equal_allocs(_This, _Other) \ _GLIBCXX_DEBUG_VERIFY(_This.get_allocator() == _Other.get_allocator(), \ _M_message(__gnu_debug::__msg_equal_allocs) \ ._M_sequence(_This, "this")) #define __glibcxx_check_string(_String) _GLIBCXX_DEBUG_PEDASSERT(_String != 0) #define __glibcxx_check_string_len(_String,_Len) \ _GLIBCXX_DEBUG_PEDASSERT(_String != 0 || _Len == 0) // Verify that a predicate is irreflexive #define __glibcxx_check_irreflexive(_First,_Last) \ _GLIBCXX_DEBUG_VERIFY(_First == _Last || !(*_First < *_First), \ _M_message(__gnu_debug::__msg_irreflexive_ordering) \ ._M_iterator_value_type(_First, "< operator type")) #if __cplusplus >= 201103L # define __glibcxx_check_irreflexive2(_First,_Last) \ _GLIBCXX_DEBUG_VERIFY(_First == _Last \ || __gnu_debug::__is_irreflexive(_First), \ _M_message(__gnu_debug::__msg_irreflexive_ordering) \ ._M_iterator_value_type(_First, "< operator type")) #else # define __glibcxx_check_irreflexive2(_First,_Last) #endif #define __glibcxx_check_irreflexive_pred(_First,_Last,_Pred) \ _GLIBCXX_DEBUG_VERIFY(_First == _Last || !_Pred(*_First, *_First), \ _M_message(__gnu_debug::__msg_irreflexive_ordering) \ ._M_instance(_Pred, "functor") \ ._M_iterator_value_type(_First, "ordered type")) #if __cplusplus >= 201103L # define __glibcxx_check_irreflexive_pred2(_First,_Last,_Pred) \ _GLIBCXX_DEBUG_VERIFY(_First == _Last \ ||__gnu_debug::__is_irreflexive_pred(_First, _Pred), \ _M_message(__gnu_debug::__msg_irreflexive_ordering) \ ._M_instance(_Pred, "functor") \ ._M_iterator_value_type(_First, "ordered type")) #else # define __glibcxx_check_irreflexive_pred2(_First,_Last,_Pred) #endif #endif PK!!AA 8/debug/mapnu[// Debugging map/multimap implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/map * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_MAP #define _GLIBCXX_DEBUG_MAP 1 #pragma GCC system_header #include #include #include #endif PK!']XX 8/debug/map.hnu[// Debugging map implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/map.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_MAP_H #define _GLIBCXX_DEBUG_MAP_H 1 #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::map with safety/checking/debug instrumentation. template, typename _Allocator = std::allocator > > class map : public __gnu_debug::_Safe_container< map<_Key, _Tp, _Compare, _Allocator>, _Allocator, __gnu_debug::_Safe_node_sequence>, public _GLIBCXX_STD_C::map<_Key, _Tp, _Compare, _Allocator> { typedef _GLIBCXX_STD_C::map< _Key, _Tp, _Compare, _Allocator> _Base; typedef __gnu_debug::_Safe_container< map, _Allocator, __gnu_debug::_Safe_node_sequence> _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef __gnu_debug::_Equal_to<_Base_const_iterator> _Equal; public: // types: typedef _Key key_type; typedef _Tp mapped_type; typedef std::pair value_type; typedef _Compare key_compare; typedef _Allocator allocator_type; typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator<_Base_iterator, map> iterator; typedef __gnu_debug::_Safe_iterator<_Base_const_iterator, map> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // 23.3.1.1 construct/copy/destroy: #if __cplusplus < 201103L map() : _Base() { } map(const map& __x) : _Base(__x) { } ~map() { } #else map() = default; map(const map&) = default; map(map&&) = default; map(initializer_list __l, const _Compare& __c = _Compare(), const allocator_type& __a = allocator_type()) : _Base(__l, __c, __a) { } explicit map(const allocator_type& __a) : _Base(__a) { } map(const map& __m, const allocator_type& __a) : _Base(__m, __a) { } map(map&& __m, const allocator_type& __a) noexcept( noexcept(_Base(std::move(__m._M_base()), __a)) ) : _Safe(std::move(__m._M_safe()), __a), _Base(std::move(__m._M_base()), __a) { } map(initializer_list __l, const allocator_type& __a) : _Base(__l, __a) { } template map(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __a) { } ~map() = default; #endif map(const _Base& __x) : _Base(__x) { } explicit map(const _Compare& __comp, const _Allocator& __a = _Allocator()) : _Base(__comp, __a) { } template map(_InputIterator __first, _InputIterator __last, const _Compare& __comp = _Compare(), const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __comp, __a) { } #if __cplusplus < 201103L map& operator=(const map& __x) { this->_M_safe() = __x; _M_base() = __x; return *this; } #else map& operator=(const map&) = default; map& operator=(map&&) = default; map& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // 133. map missing get_allocator() using _Base::get_allocator; // iterators: iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // capacity: using _Base::empty; using _Base::size; using _Base::max_size; // 23.3.1.2 element access: using _Base::operator[]; // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 464. Suggestion for new member functions in standard containers. using _Base::at; // modifiers: #if __cplusplus >= 201103L template std::pair emplace(_Args&&... __args) { auto __res = _Base::emplace(std::forward<_Args>(__args)...); return std::pair(iterator(__res.first, this), __res.second); } template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { __glibcxx_check_insert(__pos); return iterator(_Base::emplace_hint(__pos.base(), std::forward<_Args>(__args)...), this); } #endif std::pair insert(const value_type& __x) { std::pair<_Base_iterator, bool> __res = _Base::insert(__x); return std::pair(iterator(__res.first, this), __res.second); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init std::pair insert(value_type&& __x) { auto __res = _Base::insert(std::move(__x)); return { iterator(__res.first, this), __res.second }; } template::value>::type> std::pair insert(_Pair&& __x) { std::pair<_Base_iterator, bool> __res = _Base::insert(std::forward<_Pair>(__x)); return std::pair(iterator(__res.first, this), __res.second); } #endif #if __cplusplus >= 201103L void insert(std::initializer_list __list) { _Base::insert(__list); } #endif iterator #if __cplusplus >= 201103L insert(const_iterator __position, const value_type& __x) #else insert(iterator __position, const value_type& __x) #endif { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), __x), this); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __position, value_type&& __x) { __glibcxx_check_insert(__position); return { _Base::insert(__position.base(), std::move(__x)), this }; } template::value>::type> iterator insert(const_iterator __position, _Pair&& __x) { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), std::forward<_Pair>(__x)), this); } #endif template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); } #if __cplusplus > 201402L template pair try_emplace(const key_type& __k, _Args&&... __args) { auto __res = _Base::try_emplace(__k, std::forward<_Args>(__args)...); return { iterator(__res.first, this), __res.second }; } template pair try_emplace(key_type&& __k, _Args&&... __args) { auto __res = _Base::try_emplace(std::move(__k), std::forward<_Args>(__args)...); return { iterator(__res.first, this), __res.second }; } template iterator try_emplace(const_iterator __hint, const key_type& __k, _Args&&... __args) { __glibcxx_check_insert(__hint); return iterator(_Base::try_emplace(__hint.base(), __k, std::forward<_Args>(__args)...), this); } template iterator try_emplace(const_iterator __hint, key_type&& __k, _Args&&... __args) { __glibcxx_check_insert(__hint); return iterator(_Base::try_emplace(__hint.base(), std::move(__k), std::forward<_Args>(__args)...), this); } template std::pair insert_or_assign(const key_type& __k, _Obj&& __obj) { auto __res = _Base::insert_or_assign(__k, std::forward<_Obj>(__obj)); return { iterator(__res.first, this), __res.second }; } template std::pair insert_or_assign(key_type&& __k, _Obj&& __obj) { auto __res = _Base::insert_or_assign(std::move(__k), std::forward<_Obj>(__obj)); return { iterator(__res.first, this), __res.second }; } template iterator insert_or_assign(const_iterator __hint, const key_type& __k, _Obj&& __obj) { __glibcxx_check_insert(__hint); return iterator(_Base::insert_or_assign(__hint.base(), __k, std::forward<_Obj>(__obj)), this); } template iterator insert_or_assign(const_iterator __hint, key_type&& __k, _Obj&& __obj) { __glibcxx_check_insert(__hint); return iterator(_Base::insert_or_assign(__hint.base(), std::move(__k), std::forward<_Obj>(__obj)), this); } #endif // C++17 #if __cplusplus > 201402L using node_type = typename _Base::node_type; using insert_return_type = _Node_insert_return; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } insert_return_type insert(node_type&& __nh) { auto __ret = _Base::insert(std::move(__nh)); iterator __pos = iterator(__ret.position, this); return { __pos, __ret.inserted, std::move(__ret.node) }; } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 #if __cplusplus >= 201103L iterator erase(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return iterator(_Base::erase(__position.base()), this); } iterator erase(iterator __position) { return erase(const_iterator(__position)); } #else void erase(iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); _Base::erase(__position.base()); } #endif size_type erase(const key_type& __x) { _Base_iterator __victim = _Base::find(__x); if (__victim == _Base::end()) return 0; else { this->_M_invalidate_if(_Equal(__victim)); _Base::erase(__victim); return 1; } } #if __cplusplus >= 201103L iterator erase(const_iterator __first, const_iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } return iterator(_Base::erase(__first.base(), __last.base()), this); } #else void erase(iterator __first, iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } _Base::erase(__first.base(), __last.base()); } #endif void swap(map& __x) _GLIBCXX_NOEXCEPT_IF( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() _GLIBCXX_NOEXCEPT { this->_M_invalidate_all(); _Base::clear(); } // observers: using _Base::key_comp; using _Base::value_comp; // 23.3.1.3 map operations: iterator find(const key_type& __x) { return iterator(_Base::find(__x), this); } #if __cplusplus > 201103L template::type> iterator find(const _Kt& __x) { return { _Base::find(__x), this }; } #endif const_iterator find(const key_type& __x) const { return const_iterator(_Base::find(__x), this); } #if __cplusplus > 201103L template::type> const_iterator find(const _Kt& __x) const { return { _Base::find(__x), this }; } #endif using _Base::count; iterator lower_bound(const key_type& __x) { return iterator(_Base::lower_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator lower_bound(const _Kt& __x) { return { _Base::lower_bound(__x), this }; } #endif const_iterator lower_bound(const key_type& __x) const { return const_iterator(_Base::lower_bound(__x), this); } #if __cplusplus > 201103L template::type> const_iterator lower_bound(const _Kt& __x) const { return { _Base::lower_bound(__x), this }; } #endif iterator upper_bound(const key_type& __x) { return iterator(_Base::upper_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator upper_bound(const _Kt& __x) { return { _Base::upper_bound(__x), this }; } #endif const_iterator upper_bound(const key_type& __x) const { return const_iterator(_Base::upper_bound(__x), this); } #if __cplusplus > 201103L template::type> const_iterator upper_bound(const _Kt& __x) const { return { _Base::upper_bound(__x), this }; } #endif std::pair equal_range(const key_type& __x) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__x); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } #if __cplusplus > 201103L template::type> std::pair equal_range(const _Kt& __x) { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } #endif std::pair equal_range(const key_type& __x) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__x); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } #if __cplusplus > 201103L template::type> std::pair equal_range(const _Kt& __x) const { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } #endif _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } }; #if __cpp_deduction_guides >= 201606 template>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> map(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Compare, _Allocator>; template, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> map(initializer_list>, _Compare = _Compare(), _Allocator = _Allocator()) -> map<_Key, _Tp, _Compare, _Allocator>; template , typename = _RequireAllocator<_Allocator>> map(_InputIterator, _InputIterator, _Allocator) -> map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, less<__iter_key_t<_InputIterator>>, _Allocator>; template> map(initializer_list>, _Allocator) -> map<_Key, _Tp, less<_Key>, _Allocator>; #endif template inline bool operator==(const map<_Key, _Tp, _Compare, _Allocator>& __lhs, const map<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator!=(const map<_Key, _Tp, _Compare, _Allocator>& __lhs, const map<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator<(const map<_Key, _Tp, _Compare, _Allocator>& __lhs, const map<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<=(const map<_Key, _Tp, _Compare, _Allocator>& __lhs, const map<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator>=(const map<_Key, _Tp, _Compare, _Allocator>& __lhs, const map<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>(const map<_Key, _Tp, _Compare, _Allocator>& __lhs, const map<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template inline void swap(map<_Key, _Tp, _Compare, _Allocator>& __lhs, map<_Key, _Tp, _Compare, _Allocator>& __rhs) _GLIBCXX_NOEXCEPT_IF(noexcept(__lhs.swap(__rhs))) { __lhs.swap(__rhs); } } // namespace __debug } // namespace std #endif PK!|MM8/debug/multimap.hnu[// Debugging multimap implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/multimap.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_MULTIMAP_H #define _GLIBCXX_DEBUG_MULTIMAP_H 1 #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::multimap with safety/checking/debug instrumentation. template, typename _Allocator = std::allocator > > class multimap : public __gnu_debug::_Safe_container< multimap<_Key, _Tp, _Compare, _Allocator>, _Allocator, __gnu_debug::_Safe_node_sequence>, public _GLIBCXX_STD_C::multimap<_Key, _Tp, _Compare, _Allocator> { typedef _GLIBCXX_STD_C::multimap< _Key, _Tp, _Compare, _Allocator> _Base; typedef __gnu_debug::_Safe_container< multimap, _Allocator, __gnu_debug::_Safe_node_sequence> _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef __gnu_debug::_Equal_to<_Base_const_iterator> _Equal; public: // types: typedef _Key key_type; typedef _Tp mapped_type; typedef std::pair value_type; typedef _Compare key_compare; typedef _Allocator allocator_type; typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator<_Base_iterator, multimap> iterator; typedef __gnu_debug::_Safe_iterator<_Base_const_iterator, multimap> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // 23.3.1.1 construct/copy/destroy: #if __cplusplus < 201103L multimap() : _Base() { } multimap(const multimap& __x) : _Base(__x) { } ~multimap() { } #else multimap() = default; multimap(const multimap&) = default; multimap(multimap&&) = default; multimap(initializer_list __l, const _Compare& __c = _Compare(), const allocator_type& __a = allocator_type()) : _Base(__l, __c, __a) { } explicit multimap(const allocator_type& __a) : _Base(__a) { } multimap(const multimap& __m, const allocator_type& __a) : _Base(__m, __a) { } multimap(multimap&& __m, const allocator_type& __a) noexcept( noexcept(_Base(std::move(__m._M_base()), __a)) ) : _Safe(std::move(__m._M_safe()), __a), _Base(std::move(__m._M_base()), __a) { } multimap(initializer_list __l, const allocator_type& __a) : _Base(__l, __a) { } template multimap(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __a) { } ~multimap() = default; #endif explicit multimap(const _Compare& __comp, const _Allocator& __a = _Allocator()) : _Base(__comp, __a) { } template multimap(_InputIterator __first, _InputIterator __last, const _Compare& __comp = _Compare(), const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __comp, __a) { } multimap(const _Base& __x) : _Base(__x) { } #if __cplusplus < 201103L multimap& operator=(const multimap& __x) { this->_M_safe() = __x; _M_base() = __x; return *this; } #else multimap& operator=(const multimap&) = default; multimap& operator=(multimap&&) = default; multimap& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } #endif using _Base::get_allocator; // iterators: iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // capacity: using _Base::empty; using _Base::size; using _Base::max_size; // modifiers: #if __cplusplus >= 201103L template iterator emplace(_Args&&... __args) { return iterator(_Base::emplace(std::forward<_Args>(__args)...), this); } template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { __glibcxx_check_insert(__pos); return iterator(_Base::emplace_hint(__pos.base(), std::forward<_Args>(__args)...), this); } #endif iterator insert(const value_type& __x) { return iterator(_Base::insert(__x), this); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(value_type&& __x) { return { _Base::insert(std::move(__x)), this }; } template::value>::type> iterator insert(_Pair&& __x) { return iterator(_Base::insert(std::forward<_Pair>(__x)), this); } #endif #if __cplusplus >= 201103L void insert(std::initializer_list __list) { _Base::insert(__list); } #endif iterator #if __cplusplus >= 201103L insert(const_iterator __position, const value_type& __x) #else insert(iterator __position, const value_type& __x) #endif { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), __x), this); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __position, value_type&& __x) { __glibcxx_check_insert(__position); return { _Base::insert(__position.base(), std::move(__x)), this }; } template::value>::type> iterator insert(const_iterator __position, _Pair&& __x) { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), std::forward<_Pair>(__x)), this); } #endif template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); } #if __cplusplus > 201402L using node_type = typename _Base::node_type; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } iterator insert(node_type&& __nh) { return iterator(_Base::insert(std::move(__nh)), this); } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 #if __cplusplus >= 201103L iterator erase(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return iterator(_Base::erase(__position.base()), this); } iterator erase(iterator __position) { return erase(const_iterator(__position)); } #else void erase(iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); _Base::erase(__position.base()); } #endif size_type erase(const key_type& __x) { std::pair<_Base_iterator, _Base_iterator> __victims = _Base::equal_range(__x); size_type __count = 0; _Base_iterator __victim = __victims.first; while (__victim != __victims.second) { this->_M_invalidate_if(_Equal(__victim)); _Base::erase(__victim++); ++__count; } return __count; } #if __cplusplus >= 201103L iterator erase(const_iterator __first, const_iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } return iterator(_Base::erase(__first.base(), __last.base()), this); } #else void erase(iterator __first, iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } _Base::erase(__first.base(), __last.base()); } #endif void swap(multimap& __x) _GLIBCXX_NOEXCEPT_IF( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() _GLIBCXX_NOEXCEPT { this->_M_invalidate_all(); _Base::clear(); } // observers: using _Base::key_comp; using _Base::value_comp; // 23.3.1.3 multimap operations: iterator find(const key_type& __x) { return iterator(_Base::find(__x), this); } #if __cplusplus > 201103L template::type> iterator find(const _Kt& __x) { return { _Base::find(__x), this }; } #endif const_iterator find(const key_type& __x) const { return const_iterator(_Base::find(__x), this); } #if __cplusplus > 201103L template::type> const_iterator find(const _Kt& __x) const { return { _Base::find(__x), this }; } #endif using _Base::count; iterator lower_bound(const key_type& __x) { return iterator(_Base::lower_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator lower_bound(const _Kt& __x) { return { _Base::lower_bound(__x), this }; } #endif const_iterator lower_bound(const key_type& __x) const { return const_iterator(_Base::lower_bound(__x), this); } #if __cplusplus > 201103L template::type> const_iterator lower_bound(const _Kt& __x) const { return { _Base::lower_bound(__x), this }; } #endif iterator upper_bound(const key_type& __x) { return iterator(_Base::upper_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator upper_bound(const _Kt& __x) { return { _Base::upper_bound(__x), this }; } #endif const_iterator upper_bound(const key_type& __x) const { return const_iterator(_Base::upper_bound(__x), this); } #if __cplusplus > 201103L template::type> const_iterator upper_bound(const _Kt& __x) const { return { _Base::upper_bound(__x), this }; } #endif std::pair equal_range(const key_type& __x) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__x); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } #if __cplusplus > 201103L template::type> std::pair equal_range(const _Kt& __x) { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } #endif std::pair equal_range(const key_type& __x) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__x); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } #if __cplusplus > 201103L template::type> std::pair equal_range(const _Kt& __x) const { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } #endif _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } }; #if __cpp_deduction_guides >= 201606 template>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> multimap(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Compare, _Allocator>; template, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> multimap(initializer_list>, _Compare = _Compare(), _Allocator = _Allocator()) -> multimap<_Key, _Tp, _Compare, _Allocator>; template, typename = _RequireAllocator<_Allocator>> multimap(_InputIterator, _InputIterator, _Allocator) -> multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, less<__iter_key_t<_InputIterator>>, _Allocator>; template> multimap(initializer_list>, _Allocator) -> multimap<_Key, _Tp, less<_Key>, _Allocator>; #endif template inline bool operator==(const multimap<_Key, _Tp, _Compare, _Allocator>& __lhs, const multimap<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator!=(const multimap<_Key, _Tp, _Compare, _Allocator>& __lhs, const multimap<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator<(const multimap<_Key, _Tp, _Compare, _Allocator>& __lhs, const multimap<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<=(const multimap<_Key, _Tp, _Compare, _Allocator>& __lhs, const multimap<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator>=(const multimap<_Key, _Tp, _Compare, _Allocator>& __lhs, const multimap<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>(const multimap<_Key, _Tp, _Compare, _Allocator>& __lhs, const multimap<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template inline void swap(multimap<_Key, _Tp, _Compare, _Allocator>& __lhs, multimap<_Key, _Tp, _Compare, _Allocator>& __rhs) _GLIBCXX_NOEXCEPT_IF(noexcept(__lhs.swap(__rhs))) { __lhs.swap(__rhs); } } // namespace __debug } // namespace std #endif PK!t HH8/debug/multiset.hnu[// Debugging multiset implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/multiset.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_MULTISET_H #define _GLIBCXX_DEBUG_MULTISET_H 1 #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::multiset with safety/checking/debug instrumentation. template, typename _Allocator = std::allocator<_Key> > class multiset : public __gnu_debug::_Safe_container< multiset<_Key, _Compare, _Allocator>, _Allocator, __gnu_debug::_Safe_node_sequence>, public _GLIBCXX_STD_C::multiset<_Key, _Compare, _Allocator> { typedef _GLIBCXX_STD_C::multiset<_Key, _Compare, _Allocator> _Base; typedef __gnu_debug::_Safe_container< multiset, _Allocator, __gnu_debug::_Safe_node_sequence> _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef __gnu_debug::_Equal_to<_Base_const_iterator> _Equal; public: // types: typedef _Key key_type; typedef _Key value_type; typedef _Compare key_compare; typedef _Compare value_compare; typedef _Allocator allocator_type; typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator<_Base_iterator, multiset> iterator; typedef __gnu_debug::_Safe_iterator<_Base_const_iterator, multiset> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // 23.3.3.1 construct/copy/destroy: #if __cplusplus < 201103L multiset() : _Base() { } multiset(const multiset& __x) : _Base(__x) { } ~multiset() { } #else multiset() = default; multiset(const multiset&) = default; multiset(multiset&&) = default; multiset(initializer_list __l, const _Compare& __comp = _Compare(), const allocator_type& __a = allocator_type()) : _Base(__l, __comp, __a) { } explicit multiset(const allocator_type& __a) : _Base(__a) { } multiset(const multiset& __m, const allocator_type& __a) : _Base(__m, __a) { } multiset(multiset&& __m, const allocator_type& __a) noexcept( noexcept(_Base(std::move(__m._M_base()), __a)) ) : _Safe(std::move(__m._M_safe()), __a), _Base(std::move(__m._M_base()), __a) { } multiset(initializer_list __l, const allocator_type& __a) : _Base(__l, __a) { } template multiset(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __a) { } ~multiset() = default; #endif explicit multiset(const _Compare& __comp, const _Allocator& __a = _Allocator()) : _Base(__comp, __a) { } template multiset(_InputIterator __first, _InputIterator __last, const _Compare& __comp = _Compare(), const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __comp, __a) { } multiset(const _Base& __x) : _Base(__x) { } #if __cplusplus < 201103L multiset& operator=(const multiset& __x) { this->_M_safe() = __x; _M_base() = __x; return *this; } #else multiset& operator=(const multiset&) = default; multiset& operator=(multiset&&) = default; multiset& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } #endif using _Base::get_allocator; // iterators: iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // capacity: using _Base::empty; using _Base::size; using _Base::max_size; // modifiers: #if __cplusplus >= 201103L template iterator emplace(_Args&&... __args) { return iterator(_Base::emplace(std::forward<_Args>(__args)...), this); } template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { __glibcxx_check_insert(__pos); return iterator(_Base::emplace_hint(__pos.base(), std::forward<_Args>(__args)...), this); } #endif iterator insert(const value_type& __x) { return iterator(_Base::insert(__x), this); } #if __cplusplus >= 201103L iterator insert(value_type&& __x) { return iterator(_Base::insert(std::move(__x)), this); } #endif iterator insert(const_iterator __position, const value_type& __x) { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), __x), this); } #if __cplusplus >= 201103L iterator insert(const_iterator __position, value_type&& __x) { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), std::move(__x)), this); } #endif template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); } #if __cplusplus >= 201103L void insert(initializer_list __l) { _Base::insert(__l); } #endif #if __cplusplus > 201402L using node_type = typename _Base::node_type; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } iterator insert(node_type&& __nh) { return iterator(_Base::insert(std::move(__nh)), this); } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 #if __cplusplus >= 201103L iterator erase(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return iterator(_Base::erase(__position.base()), this); } #else void erase(iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); _Base::erase(__position.base()); } #endif size_type erase(const key_type& __x) { std::pair<_Base_iterator, _Base_iterator> __victims = _Base::equal_range(__x); size_type __count = 0; _Base_iterator __victim = __victims.first; while (__victim != __victims.second) { this->_M_invalidate_if(_Equal(__victim)); _Base::erase(__victim++); ++__count; } return __count; } #if __cplusplus >= 201103L iterator erase(const_iterator __first, const_iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } return iterator(_Base::erase(__first.base(), __last.base()), this); } #else void erase(iterator __first, iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } _Base::erase(__first.base(), __last.base()); } #endif void swap(multiset& __x) _GLIBCXX_NOEXCEPT_IF( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() _GLIBCXX_NOEXCEPT { this->_M_invalidate_all(); _Base::clear(); } // observers: using _Base::key_comp; using _Base::value_comp; // multiset operations: iterator find(const key_type& __x) { return iterator(_Base::find(__x), this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload const_iterator find(const key_type& __x) const { return const_iterator(_Base::find(__x), this); } #if __cplusplus > 201103L template::type> iterator find(const _Kt& __x) { return { _Base::find(__x), this }; } template::type> const_iterator find(const _Kt& __x) const { return { _Base::find(__x), this }; } #endif using _Base::count; iterator lower_bound(const key_type& __x) { return iterator(_Base::lower_bound(__x), this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload const_iterator lower_bound(const key_type& __x) const { return const_iterator(_Base::lower_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator lower_bound(const _Kt& __x) { return { _Base::lower_bound(__x), this }; } template::type> const_iterator lower_bound(const _Kt& __x) const { return { _Base::lower_bound(__x), this }; } #endif iterator upper_bound(const key_type& __x) { return iterator(_Base::upper_bound(__x), this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload const_iterator upper_bound(const key_type& __x) const { return const_iterator(_Base::upper_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator upper_bound(const _Kt& __x) { return { _Base::upper_bound(__x), this }; } template::type> const_iterator upper_bound(const _Kt& __x) const { return { _Base::upper_bound(__x), this }; } #endif std::pair equal_range(const key_type& __x) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__x); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload std::pair equal_range(const key_type& __x) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__x); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } #if __cplusplus > 201103L template::type> std::pair equal_range(const _Kt& __x) { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } template::type> std::pair equal_range(const _Kt& __x) const { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } #endif _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> multiset(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> multiset::value_type, _Compare, _Allocator>; template, typename _Allocator = allocator<_Key>, typename = _RequireAllocator<_Allocator>> multiset(initializer_list<_Key>, _Compare = _Compare(), _Allocator = _Allocator()) -> multiset<_Key, _Compare, _Allocator>; template, typename = _RequireAllocator<_Allocator>> multiset(_InputIterator, _InputIterator, _Allocator) -> multiset::value_type, less::value_type>, _Allocator>; template> multiset(initializer_list<_Key>, _Allocator) -> multiset<_Key, less<_Key>, _Allocator>; #endif template inline bool operator==(const multiset<_Key, _Compare, _Allocator>& __lhs, const multiset<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator!=(const multiset<_Key, _Compare, _Allocator>& __lhs, const multiset<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator<(const multiset<_Key, _Compare, _Allocator>& __lhs, const multiset<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<=(const multiset<_Key, _Compare, _Allocator>& __lhs, const multiset<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator>=(const multiset<_Key, _Compare, _Allocator>& __lhs, const multiset<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>(const multiset<_Key, _Compare, _Allocator>& __lhs, const multiset<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template void swap(multiset<_Key, _Compare, _Allocator>& __x, multiset<_Key, _Compare, _Allocator>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { return __x.swap(__y); } } // namespace __debug } // namespace std #endif PK!t$?$?$8/debug/safe_base.hnu[// Safe sequence/iterator base implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_base.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_BASE_H #define _GLIBCXX_DEBUG_SAFE_BASE_H 1 #include namespace __gnu_debug { class _Safe_sequence_base; /** \brief Basic functionality for a @a safe iterator. * * The %_Safe_iterator_base base class implements the functionality * of a safe iterator that is not specific to a particular iterator * type. It contains a pointer back to the sequence it references * along with iterator version information and pointers to form a * doubly-linked list of iterators referenced by the container. * * This class must not perform any operations that can throw an * exception, or the exception guarantees of derived iterators will * be broken. */ class _Safe_iterator_base { friend class _Safe_sequence_base; public: /** The sequence this iterator references; may be NULL to indicate a singular iterator. */ _Safe_sequence_base* _M_sequence; /** The version number of this iterator. The sentinel value 0 is * used to indicate an invalidated iterator (i.e., one that is * singular because of an operation on the container). This * version number must equal the version number in the sequence * referenced by _M_sequence for the iterator to be * non-singular. */ unsigned int _M_version; /** Pointer to the previous iterator in the sequence's list of iterators. Only valid when _M_sequence != NULL. */ _Safe_iterator_base* _M_prior; /** Pointer to the next iterator in the sequence's list of iterators. Only valid when _M_sequence != NULL. */ _Safe_iterator_base* _M_next; protected: /** Initializes the iterator and makes it singular. */ _Safe_iterator_base() : _M_sequence(0), _M_version(0), _M_prior(0), _M_next(0) { } /** Initialize the iterator to reference the sequence pointed to * by @p __seq. @p __constant is true when we are initializing a * constant iterator, and false if it is a mutable iterator. Note * that @p __seq may be NULL, in which case the iterator will be * singular. Otherwise, the iterator will reference @p __seq and * be nonsingular. */ _Safe_iterator_base(const _Safe_sequence_base* __seq, bool __constant) : _M_sequence(0), _M_version(0), _M_prior(0), _M_next(0) { this->_M_attach(const_cast<_Safe_sequence_base*>(__seq), __constant); } /** Initializes the iterator to reference the same sequence that @p __x does. @p __constant is true if this is a constant iterator, and false if it is mutable. */ _Safe_iterator_base(const _Safe_iterator_base& __x, bool __constant) : _M_sequence(0), _M_version(0), _M_prior(0), _M_next(0) { this->_M_attach(__x._M_sequence, __constant); } ~_Safe_iterator_base() { this->_M_detach(); } /** For use in _Safe_iterator. */ __gnu_cxx::__mutex& _M_get_mutex() throw (); /** Attaches this iterator to the given sequence, detaching it * from whatever sequence it was attached to originally. If the * new sequence is the NULL pointer, the iterator is left * unattached. */ void _M_attach(_Safe_sequence_base* __seq, bool __constant); /** Likewise, but not thread-safe. */ void _M_attach_single(_Safe_sequence_base* __seq, bool __constant) throw (); /** Detach the iterator for whatever sequence it is attached to, * if any. */ void _M_detach(); public: /** Likewise, but not thread-safe. */ void _M_detach_single() throw (); /** Determines if we are attached to the given sequence. */ bool _M_attached_to(const _Safe_sequence_base* __seq) const { return _M_sequence == __seq; } /** Is this iterator singular? */ _GLIBCXX_PURE bool _M_singular() const throw (); /** Can we compare this iterator to the given iterator @p __x? Returns true if both iterators are nonsingular and reference the same sequence. */ _GLIBCXX_PURE bool _M_can_compare(const _Safe_iterator_base& __x) const throw (); /** Invalidate the iterator, making it singular. */ void _M_invalidate() { _M_version = 0; } /** Reset all member variables */ void _M_reset() throw (); /** Unlink itself */ void _M_unlink() throw () { if (_M_prior) _M_prior->_M_next = _M_next; if (_M_next) _M_next->_M_prior = _M_prior; } }; /** Iterators that derive from _Safe_iterator_base can be determined singular * or non-singular. **/ inline bool __check_singular_aux(const _Safe_iterator_base* __x) { return __x->_M_singular(); } /** * @brief Base class that supports tracking of iterators that * reference a sequence. * * The %_Safe_sequence_base class provides basic support for * tracking iterators into a sequence. Sequences that track * iterators must derived from %_Safe_sequence_base publicly, so * that safe iterators (which inherit _Safe_iterator_base) can * attach to them. This class contains two linked lists of * iterators, one for constant iterators and one for mutable * iterators, and a version number that allows very fast * invalidation of all iterators that reference the container. * * This class must ensure that no operation on it may throw an * exception, otherwise @a safe sequences may fail to provide the * exception-safety guarantees required by the C++ standard. */ class _Safe_sequence_base { friend class _Safe_iterator_base; public: /// The list of mutable iterators that reference this container _Safe_iterator_base* _M_iterators; /// The list of constant iterators that reference this container _Safe_iterator_base* _M_const_iterators; /// The container version number. This number may never be 0. mutable unsigned int _M_version; protected: // Initialize with a version number of 1 and no iterators _Safe_sequence_base() _GLIBCXX_NOEXCEPT : _M_iterators(0), _M_const_iterators(0), _M_version(1) { } #if __cplusplus >= 201103L _Safe_sequence_base(const _Safe_sequence_base&) noexcept : _Safe_sequence_base() { } // Move constructor swap iterators. _Safe_sequence_base(_Safe_sequence_base&& __seq) noexcept : _Safe_sequence_base() { _M_swap(__seq); } #endif /** Notify all iterators that reference this sequence that the sequence is being destroyed. */ ~_Safe_sequence_base() { this->_M_detach_all(); } /** Detach all iterators, leaving them singular. */ void _M_detach_all(); /** Detach all singular iterators. * @post for all iterators i attached to this sequence, * i->_M_version == _M_version. */ void _M_detach_singular(); /** Revalidates all attached singular iterators. This method may * be used to validate iterators that were invalidated before * (but for some reason, such as an exception, need to become * valid again). */ void _M_revalidate_singular(); /** Swap this sequence with the given sequence. This operation * also swaps ownership of the iterators, so that when the * operation is complete all iterators that originally referenced * one container now reference the other container. */ void _M_swap(_Safe_sequence_base& __x) _GLIBCXX_USE_NOEXCEPT; /** For use in _Safe_sequence. */ __gnu_cxx::__mutex& _M_get_mutex() throw (); /** Invalidates all iterators. */ void _M_invalidate_all() const { if (++_M_version == 0) _M_version = 1; } private: /** Attach an iterator to this sequence. */ void _M_attach(_Safe_iterator_base* __it, bool __constant); /** Likewise but not thread safe. */ void _M_attach_single(_Safe_iterator_base* __it, bool __constant) throw (); /** Detach an iterator from this sequence */ void _M_detach(_Safe_iterator_base* __it); /** Likewise but not thread safe. */ void _M_detach_single(_Safe_iterator_base* __it) throw (); }; } // namespace __gnu_debug #endif PK!԰. /** @file debug/safe_container.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_CONTAINER_H #define _GLIBCXX_DEBUG_SAFE_CONTAINER_H 1 #include namespace __gnu_debug { /// Safe class dealing with some allocator dependent operations. template class _SafeBase, bool _IsCxx11AllocatorAware = true> class _Safe_container : public _SafeBase<_SafeContainer> { typedef _SafeBase<_SafeContainer> _Base; _SafeContainer& _M_cont() _GLIBCXX_NOEXCEPT { return *static_cast<_SafeContainer*>(this); } protected: _Safe_container& _M_safe() _GLIBCXX_NOEXCEPT { return *this; } #if __cplusplus >= 201103L _Safe_container() = default; _Safe_container(const _Safe_container&) = default; _Safe_container(_Safe_container&&) = default; _Safe_container(_Safe_container&& __x, const _Alloc& __a) : _Safe_container() { if (__x._M_cont().get_allocator() == __a) _Base::_M_swap(__x); else __x._M_invalidate_all(); } #endif public: // Copy assignment invalidate all iterators. _Safe_container& operator=(const _Safe_container&) _GLIBCXX_NOEXCEPT { this->_M_invalidate_all(); return *this; } #if __cplusplus >= 201103L _Safe_container& operator=(_Safe_container&& __x) noexcept { __glibcxx_check_self_move_assign(__x); if (_IsCxx11AllocatorAware) { typedef __gnu_cxx::__alloc_traits<_Alloc> _Alloc_traits; bool __xfer_memory = _Alloc_traits::_S_propagate_on_move_assign() || _M_cont().get_allocator() == __x._M_cont().get_allocator(); if (__xfer_memory) _Base::_M_swap(__x); else this->_M_invalidate_all(); } else _Base::_M_swap(__x); __x._M_invalidate_all(); return *this; } void _M_swap(_Safe_container& __x) noexcept { if (_IsCxx11AllocatorAware) { typedef __gnu_cxx::__alloc_traits<_Alloc> _Alloc_traits; if (!_Alloc_traits::_S_propagate_on_swap()) __glibcxx_check_equal_allocs(this->_M_cont()._M_base(), __x._M_cont()._M_base()); } _Base::_M_swap(__x); } #endif }; } // namespace __gnu_debug #endif PK!(v(v8/debug/safe_iterator.hnu[// Safe iterator implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_iterator.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_ITERATOR_H #define _GLIBCXX_DEBUG_SAFE_ITERATOR_H 1 #include #include #include #include #include #include namespace __gnu_debug { /** Helper struct to deal with sequence offering a before_begin * iterator. **/ template struct _BeforeBeginHelper { template static bool _S_Is(const _Safe_iterator<_Iterator, _Sequence>&) { return false; } template static bool _S_Is_Beginnest(const _Safe_iterator<_Iterator, _Sequence>& __it) { return __it.base() == __it._M_get_sequence()->_M_base().begin(); } }; /** Sequence traits giving the size of a container if possible. */ template struct _Sequence_traits { typedef _Distance_traits _DistTraits; static typename _DistTraits::__type _S_size(const _Sequence& __seq) { return std::make_pair(__seq.size(), __dp_exact); } }; /** \brief Safe iterator wrapper. * * The class template %_Safe_iterator is a wrapper around an * iterator that tracks the iterator's movement among sequences and * checks that operations performed on the "safe" iterator are * legal. In additional to the basic iterator operations (which are * validated, and then passed to the underlying iterator), * %_Safe_iterator has member functions for iterator invalidation, * attaching/detaching the iterator from sequences, and querying * the iterator's state. * * Note that _Iterator must be the first base class so that it gets * initialized before the iterator is being attached to the container's list * of iterators and it is being detached before _Iterator get * destroyed. Otherwise it would result in a data race. */ template class _Safe_iterator : private _Iterator, public _Safe_iterator_base { typedef _Iterator _Iter_base; typedef _Safe_iterator_base _Safe_base; typedef typename _Sequence::const_iterator _Const_iterator; /// Determine if this is a constant iterator. bool _M_constant() const { return std::__are_same<_Const_iterator, _Safe_iterator>::__value; } typedef std::iterator_traits<_Iterator> _Traits; struct _Attach_single { }; _Safe_iterator(const _Iterator& __i, _Safe_sequence_base* __seq, _Attach_single) _GLIBCXX_NOEXCEPT : _Iter_base(__i) { _M_attach_single(__seq); } public: typedef _Iterator iterator_type; typedef typename _Traits::iterator_category iterator_category; typedef typename _Traits::value_type value_type; typedef typename _Traits::difference_type difference_type; typedef typename _Traits::reference reference; typedef typename _Traits::pointer pointer; /// @post the iterator is singular and unattached _Safe_iterator() _GLIBCXX_NOEXCEPT : _Iter_base() { } /** * @brief Safe iterator construction from an unsafe iterator and * its sequence. * * @pre @p seq is not NULL * @post this is not singular */ _Safe_iterator(const _Iterator& __i, const _Safe_sequence_base* __seq) _GLIBCXX_NOEXCEPT : _Iter_base(__i), _Safe_base(__seq, _M_constant()) { _GLIBCXX_DEBUG_VERIFY(!this->_M_singular(), _M_message(__msg_init_singular) ._M_iterator(*this, "this")); } /** * @brief Copy construction. */ _Safe_iterator(const _Safe_iterator& __x) _GLIBCXX_NOEXCEPT : _Iter_base(__x.base()) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 408. Is vector > forbidden? _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_init_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); _M_attach(__x._M_sequence); } #if __cplusplus >= 201103L /** * @brief Move construction. * @post __x is singular and unattached */ _Safe_iterator(_Safe_iterator&& __x) noexcept : _Iter_base() { _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_init_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); _Safe_sequence_base* __seq = __x._M_sequence; __x._M_detach(); std::swap(base(), __x.base()); _M_attach(__seq); } #endif /** * @brief Converting constructor from a mutable iterator to a * constant iterator. */ template _Safe_iterator( const _Safe_iterator<_MutableIterator, typename __gnu_cxx::__enable_if<(std::__are_same<_MutableIterator, typename _Sequence::iterator::iterator_type>::__value), _Sequence>::__type>& __x) _GLIBCXX_NOEXCEPT : _Iter_base(__x.base()) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 408. Is vector > forbidden? _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_init_const_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); _M_attach(__x._M_sequence); } /** * @brief Copy assignment. */ _Safe_iterator& operator=(const _Safe_iterator& __x) _GLIBCXX_NOEXCEPT { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 408. Is vector > forbidden? _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); if (this->_M_sequence && this->_M_sequence == __x._M_sequence) { __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); base() = __x.base(); _M_version = __x._M_sequence->_M_version; } else { _M_detach(); base() = __x.base(); _M_attach(__x._M_sequence); } return *this; } #if __cplusplus >= 201103L /** * @brief Move assignment. * @post __x is singular and unattached */ _Safe_iterator& operator=(_Safe_iterator&& __x) noexcept { _GLIBCXX_DEBUG_VERIFY(this != &__x, _M_message(__msg_self_move_assign) ._M_iterator(*this, "this")); _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); if (this->_M_sequence && this->_M_sequence == __x._M_sequence) { __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); base() = __x.base(); _M_version = __x._M_sequence->_M_version; } else { _M_detach(); base() = __x.base(); _M_attach(__x._M_sequence); } __x._M_detach(); __x.base() = _Iterator(); return *this; } #endif /** * @brief Iterator dereference. * @pre iterator is dereferenceable */ reference operator*() const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_dereferenceable(), _M_message(__msg_bad_deref) ._M_iterator(*this, "this")); return *base(); } /** * @brief Iterator dereference. * @pre iterator is dereferenceable */ pointer operator->() const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_dereferenceable(), _M_message(__msg_bad_deref) ._M_iterator(*this, "this")); return base().operator->(); } // ------ Input iterator requirements ------ /** * @brief Iterator preincrement * @pre iterator is incrementable */ _Safe_iterator& operator++() _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_incrementable(), _M_message(__msg_bad_inc) ._M_iterator(*this, "this")); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); ++base(); return *this; } /** * @brief Iterator postincrement * @pre iterator is incrementable */ _Safe_iterator operator++(int) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_incrementable(), _M_message(__msg_bad_inc) ._M_iterator(*this, "this")); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); return _Safe_iterator(base()++, this->_M_sequence, _Attach_single()); } // ------ Bidirectional iterator requirements ------ /** * @brief Iterator predecrement * @pre iterator is decrementable */ _Safe_iterator& operator--() _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_decrementable(), _M_message(__msg_bad_dec) ._M_iterator(*this, "this")); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); --base(); return *this; } /** * @brief Iterator postdecrement * @pre iterator is decrementable */ _Safe_iterator operator--(int) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_decrementable(), _M_message(__msg_bad_dec) ._M_iterator(*this, "this")); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); return _Safe_iterator(base()--, this->_M_sequence, _Attach_single()); } // ------ Random access iterator requirements ------ reference operator[](const difference_type& __n) const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_can_advance(__n) && this->_M_can_advance(__n+1), _M_message(__msg_iter_subscript_oob) ._M_iterator(*this)._M_integer(__n)); return base()[__n]; } _Safe_iterator& operator+=(const difference_type& __n) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_can_advance(__n), _M_message(__msg_advance_oob) ._M_iterator(*this)._M_integer(__n)); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); base() += __n; return *this; } _Safe_iterator operator+(const difference_type& __n) const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_can_advance(__n), _M_message(__msg_advance_oob) ._M_iterator(*this)._M_integer(__n)); return _Safe_iterator(base() + __n, this->_M_sequence); } _Safe_iterator& operator-=(const difference_type& __n) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_can_advance(-__n), _M_message(__msg_retreat_oob) ._M_iterator(*this)._M_integer(__n)); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); base() -= __n; return *this; } _Safe_iterator operator-(const difference_type& __n) const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_can_advance(-__n), _M_message(__msg_retreat_oob) ._M_iterator(*this)._M_integer(__n)); return _Safe_iterator(base() - __n, this->_M_sequence); } // ------ Utilities ------ /** * @brief Return the underlying iterator */ _Iterator& base() _GLIBCXX_NOEXCEPT { return *this; } const _Iterator& base() const _GLIBCXX_NOEXCEPT { return *this; } /** * @brief Conversion to underlying non-debug iterator to allow * better interaction with non-debug containers. */ operator _Iterator() const _GLIBCXX_NOEXCEPT { return *this; } /** Attach iterator to the given sequence. */ void _M_attach(_Safe_sequence_base* __seq) { _Safe_base::_M_attach(__seq, _M_constant()); } /** Likewise, but not thread-safe. */ void _M_attach_single(_Safe_sequence_base* __seq) { _Safe_base::_M_attach_single(__seq, _M_constant()); } /// Is the iterator dereferenceable? bool _M_dereferenceable() const { return !this->_M_singular() && !_M_is_end() && !_M_is_before_begin(); } /// Is the iterator before a dereferenceable one? bool _M_before_dereferenceable() const { if (this->_M_incrementable()) { _Iterator __base = base(); return ++__base != _M_get_sequence()->_M_base().end(); } return false; } /// Is the iterator incrementable? bool _M_incrementable() const { return !this->_M_singular() && !_M_is_end(); } // Is the iterator decrementable? bool _M_decrementable() const { return !_M_singular() && !_M_is_begin(); } // Can we advance the iterator @p __n steps (@p __n may be negative) bool _M_can_advance(const difference_type& __n) const; // Is the iterator range [*this, __rhs) valid? bool _M_valid_range(const _Safe_iterator& __rhs, std::pair& __dist, bool __check_dereferenceable = true) const; // The sequence this iterator references. typename __gnu_cxx::__conditional_type::__value, const _Sequence*, _Sequence*>::__type _M_get_sequence() const { return static_cast<_Sequence*>(_M_sequence); } /// Is this iterator equal to the sequence's begin() iterator? bool _M_is_begin() const { return base() == _M_get_sequence()->_M_base().begin(); } /// Is this iterator equal to the sequence's end() iterator? bool _M_is_end() const { return base() == _M_get_sequence()->_M_base().end(); } /// Is this iterator equal to the sequence's before_begin() iterator if /// any? bool _M_is_before_begin() const { return _BeforeBeginHelper<_Sequence>::_S_Is(*this); } /// Is this iterator equal to the sequence's before_begin() iterator if /// any or begin() otherwise? bool _M_is_beginnest() const { return _BeforeBeginHelper<_Sequence>::_S_Is_Beginnest(*this); } }; template inline bool operator==(const _Safe_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_iterator<_IteratorR, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() == __rhs.base(); } template inline bool operator==(const _Safe_iterator<_Iterator, _Sequence>& __lhs, const _Safe_iterator<_Iterator, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() == __rhs.base(); } template inline bool operator!=(const _Safe_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_iterator<_IteratorR, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() != __rhs.base(); } template inline bool operator!=(const _Safe_iterator<_Iterator, _Sequence>& __lhs, const _Safe_iterator<_Iterator, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() != __rhs.base(); } template inline bool operator<(const _Safe_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_iterator<_IteratorR, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() < __rhs.base(); } template inline bool operator<(const _Safe_iterator<_Iterator, _Sequence>& __lhs, const _Safe_iterator<_Iterator, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() < __rhs.base(); } template inline bool operator<=(const _Safe_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_iterator<_IteratorR, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() <= __rhs.base(); } template inline bool operator<=(const _Safe_iterator<_Iterator, _Sequence>& __lhs, const _Safe_iterator<_Iterator, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() <= __rhs.base(); } template inline bool operator>(const _Safe_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_iterator<_IteratorR, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() > __rhs.base(); } template inline bool operator>(const _Safe_iterator<_Iterator, _Sequence>& __lhs, const _Safe_iterator<_Iterator, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() > __rhs.base(); } template inline bool operator>=(const _Safe_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_iterator<_IteratorR, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() >= __rhs.base(); } template inline bool operator>=(const _Safe_iterator<_Iterator, _Sequence>& __lhs, const _Safe_iterator<_Iterator, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() >= __rhs.base(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // According to the resolution of DR179 not only the various comparison // operators but also operator- must accept mixed iterator/const_iterator // parameters. template inline typename _Safe_iterator<_IteratorL, _Sequence>::difference_type operator-(const _Safe_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_iterator<_IteratorR, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_distance_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_distance_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() - __rhs.base(); } template inline typename _Safe_iterator<_Iterator, _Sequence>::difference_type operator-(const _Safe_iterator<_Iterator, _Sequence>& __lhs, const _Safe_iterator<_Iterator, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_distance_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_distance_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() - __rhs.base(); } template inline _Safe_iterator<_Iterator, _Sequence> operator+(typename _Safe_iterator<_Iterator,_Sequence>::difference_type __n, const _Safe_iterator<_Iterator, _Sequence>& __i) _GLIBCXX_NOEXCEPT { return __i + __n; } /** Safe iterators know if they are dereferenceable. */ template inline bool __check_dereferenceable(const _Safe_iterator<_Iterator, _Sequence>& __x) { return __x._M_dereferenceable(); } /** Safe iterators know how to check if they form a valid range. */ template inline bool __valid_range(const _Safe_iterator<_Iterator, _Sequence>& __first, const _Safe_iterator<_Iterator, _Sequence>& __last, typename _Distance_traits<_Iterator>::__type& __dist) { return __first._M_valid_range(__last, __dist); } /** Safe iterators can help to get better distance knowledge. */ template inline typename _Distance_traits<_Iterator>::__type __get_distance(const _Safe_iterator<_Iterator, _Sequence>& __first, const _Safe_iterator<_Iterator, _Sequence>& __last, std::random_access_iterator_tag) { return std::make_pair(__last.base() - __first.base(), __dp_exact); } template inline typename _Distance_traits<_Iterator>::__type __get_distance(const _Safe_iterator<_Iterator, _Sequence>& __first, const _Safe_iterator<_Iterator, _Sequence>& __last, std::input_iterator_tag) { typedef typename _Distance_traits<_Iterator>::__type _Diff; typedef _Sequence_traits<_Sequence> _SeqTraits; if (__first.base() == __last.base()) return std::make_pair(0, __dp_exact); if (__first._M_is_before_begin()) { if (__last._M_is_begin()) return std::make_pair(1, __dp_exact); return std::make_pair(1, __dp_sign); } if (__first._M_is_begin()) { if (__last._M_is_before_begin()) return std::make_pair(-1, __dp_exact); if (__last._M_is_end()) return _SeqTraits::_S_size(*__first._M_get_sequence()); return std::make_pair(1, __dp_sign); } if (__first._M_is_end()) { if (__last._M_is_before_begin()) return std::make_pair(-1, __dp_exact); if (__last._M_is_begin()) { _Diff __diff = _SeqTraits::_S_size(*__first._M_get_sequence()); return std::make_pair(-__diff.first, __diff.second); } return std::make_pair(-1, __dp_sign); } if (__last._M_is_before_begin() || __last._M_is_begin()) return std::make_pair(-1, __dp_sign); if (__last._M_is_end()) return std::make_pair(1, __dp_sign); return std::make_pair(1, __dp_equality); } // Get distance from sequence begin to specified iterator. template inline typename _Distance_traits<_Iterator>::__type __get_distance_from_begin(const _Safe_iterator<_Iterator, _Sequence>& __it) { typedef _Sequence_traits<_Sequence> _SeqTraits; // No need to consider before_begin as this function is only used in // _M_can_advance which won't be used for forward_list iterators. if (__it._M_is_begin()) return std::make_pair(0, __dp_exact); if (__it._M_is_end()) return _SeqTraits::_S_size(*__it._M_get_sequence()); typename _Distance_traits<_Iterator>::__type __res = __get_distance(__it._M_get_sequence()->_M_base().begin(), __it.base()); if (__res.second == __dp_equality) return std::make_pair(1, __dp_sign); return __res; } // Get distance from specified iterator to sequence end. template inline typename _Distance_traits<_Iterator>::__type __get_distance_to_end(const _Safe_iterator<_Iterator, _Sequence>& __it) { typedef _Sequence_traits<_Sequence> _SeqTraits; // No need to consider before_begin as this function is only used in // _M_can_advance which won't be used for forward_list iterators. if (__it._M_is_begin()) return _SeqTraits::_S_size(*__it._M_get_sequence()); if (__it._M_is_end()) return std::make_pair(0, __dp_exact); typename _Distance_traits<_Iterator>::__type __res = __get_distance(__it.base(), __it._M_get_sequence()->_M_base().end()); if (__res.second == __dp_equality) return std::make_pair(1, __dp_sign); return __res; } #if __cplusplus < 201103L template struct __is_safe_random_iterator<_Safe_iterator<_Iterator, _Sequence> > : std::__are_same:: iterator_category> { }; #else template _Iterator __base(const _Safe_iterator<_Iterator, _Sequence>& __it, std::random_access_iterator_tag) { return __it.base(); } template const _Safe_iterator<_Iterator, _Sequence>& __base(const _Safe_iterator<_Iterator, _Sequence>& __it, std::input_iterator_tag) { return __it; } template auto __base(const _Safe_iterator<_Iterator, _Sequence>& __it) -> decltype(__base(__it, std::__iterator_category(__it))) { return __base(__it, std::__iterator_category(__it)); } #endif #if __cplusplus < 201103L template struct _Unsafe_type<_Safe_iterator<_Iterator, _Sequence> > { typedef _Iterator _Type; }; #endif template inline _Iterator __unsafe(const _Safe_iterator<_Iterator, _Sequence>& __it) { return __it.base(); } } // namespace __gnu_debug #include #endif PK!Ƹএ 8/debug/safe_iterator.tccnu[// Debugging iterator implementation (out of line) -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_iterator.tcc * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_ITERATOR_TCC #define _GLIBCXX_DEBUG_SAFE_ITERATOR_TCC 1 namespace __gnu_debug { template bool _Safe_iterator<_Iterator, _Sequence>:: _M_can_advance(const difference_type& __n) const { if (this->_M_singular()) return false; if (__n == 0) return true; if (__n < 0) { std::pair __dist = __get_distance_from_begin(*this); bool __ok = ((__dist.second == __dp_exact && __dist.first >= -__n) || (__dist.second != __dp_exact && __dist.first > 0)); return __ok; } else { std::pair __dist = __get_distance_to_end(*this); bool __ok = ((__dist.second == __dp_exact && __dist.first >= __n) || (__dist.second != __dp_exact && __dist.first > 0)); return __ok; } } template bool _Safe_iterator<_Iterator, _Sequence>:: _M_valid_range(const _Safe_iterator& __rhs, std::pair& __dist, bool __check_dereferenceable) const { if (!_M_can_compare(__rhs)) return false; /* Determine iterators order */ __dist = __get_distance(*this, __rhs); switch (__dist.second) { case __dp_equality: if (__dist.first == 0) return true; break; case __dp_sign: case __dp_exact: // If range is not empty first iterator must be dereferenceable. if (__dist.first > 0) return !__check_dereferenceable || _M_dereferenceable(); return __dist.first == 0; } // Assume that this is a valid range; we can't check anything else. return true; } } // namespace __gnu_debug #endif PK!Ye?e?8/debug/safe_local_iterator.hnu[// Safe iterator implementation -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_local_iterator.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_LOCAL_ITERATOR_H #define _GLIBCXX_DEBUG_SAFE_LOCAL_ITERATOR_H 1 #include namespace __gnu_debug { /** \brief Safe iterator wrapper. * * The class template %_Safe_local_iterator is a wrapper around an * iterator that tracks the iterator's movement among sequences and * checks that operations performed on the "safe" iterator are * legal. In additional to the basic iterator operations (which are * validated, and then passed to the underlying iterator), * %_Safe_local_iterator has member functions for iterator invalidation, * attaching/detaching the iterator from sequences, and querying * the iterator's state. */ template class _Safe_local_iterator : private _Iterator , public _Safe_local_iterator_base { typedef _Iterator _Iter_base; typedef _Safe_local_iterator_base _Safe_base; typedef typename _Sequence::const_local_iterator _Const_local_iterator; typedef typename _Sequence::size_type size_type; /// Determine if this is a constant iterator. bool _M_constant() const { return std::__are_same<_Const_local_iterator, _Safe_local_iterator>::__value; } typedef std::iterator_traits<_Iterator> _Traits; struct _Attach_single { }; _Safe_local_iterator(const _Iterator& __i, _Safe_sequence_base* __cont, _Attach_single) noexcept : _Iter_base(__i) { _M_attach_single(__cont); } public: typedef _Iterator iterator_type; typedef typename _Traits::iterator_category iterator_category; typedef typename _Traits::value_type value_type; typedef typename _Traits::difference_type difference_type; typedef typename _Traits::reference reference; typedef typename _Traits::pointer pointer; /// @post the iterator is singular and unattached _Safe_local_iterator() noexcept : _Iter_base() { } /** * @brief Safe iterator construction from an unsafe iterator and * its sequence. * * @pre @p seq is not NULL * @post this is not singular */ _Safe_local_iterator(const _Iterator& __i, const _Safe_sequence_base* __cont) : _Iter_base(__i), _Safe_base(__cont, _M_constant()) { _GLIBCXX_DEBUG_VERIFY(!this->_M_singular(), _M_message(__msg_init_singular) ._M_iterator(*this, "this")); } /** * @brief Copy construction. */ _Safe_local_iterator(const _Safe_local_iterator& __x) noexcept : _Iter_base(__x.base()) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 408. Is vector > forbidden? _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_init_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); _M_attach(__x._M_sequence); } /** * @brief Move construction. * @post __x is singular and unattached */ _Safe_local_iterator(_Safe_local_iterator&& __x) noexcept : _Iter_base() { _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_init_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); auto __cont = __x._M_sequence; __x._M_detach(); std::swap(base(), __x.base()); _M_attach(__cont); } /** * @brief Converting constructor from a mutable iterator to a * constant iterator. */ template _Safe_local_iterator( const _Safe_local_iterator<_MutableIterator, typename __gnu_cxx::__enable_if::__value, _Sequence>::__type>& __x) : _Iter_base(__x.base()) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 408. Is vector > forbidden? _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_init_const_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); _M_attach(__x._M_sequence); } /** * @brief Copy assignment. */ _Safe_local_iterator& operator=(const _Safe_local_iterator& __x) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 408. Is vector > forbidden? _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); if (this->_M_sequence && this->_M_sequence == __x._M_sequence) { __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); base() = __x.base(); _M_version = __x._M_sequence->_M_version; } else { _M_detach(); base() = __x.base(); _M_attach(__x._M_sequence); } return *this; } /** * @brief Move assignment. * @post __x is singular and unattached */ _Safe_local_iterator& operator=(_Safe_local_iterator&& __x) noexcept { _GLIBCXX_DEBUG_VERIFY(this != &__x, _M_message(__msg_self_move_assign) ._M_iterator(*this, "this")); _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); if (this->_M_sequence && this->_M_sequence == __x._M_sequence) { __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); base() = __x.base(); _M_version = __x._M_sequence->_M_version; } else { _M_detach(); base() = __x.base(); _M_attach(__x._M_sequence); } __x._M_detach(); __x.base() = _Iterator(); return *this; } /** * @brief Iterator dereference. * @pre iterator is dereferenceable */ reference operator*() const { _GLIBCXX_DEBUG_VERIFY(this->_M_dereferenceable(), _M_message(__msg_bad_deref) ._M_iterator(*this, "this")); return *base(); } /** * @brief Iterator dereference. * @pre iterator is dereferenceable */ pointer operator->() const { _GLIBCXX_DEBUG_VERIFY(this->_M_dereferenceable(), _M_message(__msg_bad_deref) ._M_iterator(*this, "this")); return base().operator->(); } // ------ Input iterator requirements ------ /** * @brief Iterator preincrement * @pre iterator is incrementable */ _Safe_local_iterator& operator++() { _GLIBCXX_DEBUG_VERIFY(this->_M_incrementable(), _M_message(__msg_bad_inc) ._M_iterator(*this, "this")); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); ++base(); return *this; } /** * @brief Iterator postincrement * @pre iterator is incrementable */ _Safe_local_iterator operator++(int) { _GLIBCXX_DEBUG_VERIFY(this->_M_incrementable(), _M_message(__msg_bad_inc) ._M_iterator(*this, "this")); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); return _Safe_local_iterator(base()++, this->_M_sequence, _Attach_single()); } // ------ Utilities ------ /** * @brief Return the underlying iterator */ _Iterator& base() noexcept { return *this; } const _Iterator& base() const noexcept { return *this; } /** * @brief Return the bucket */ size_type bucket() const { return base()._M_get_bucket(); } /** * @brief Conversion to underlying non-debug iterator to allow * better interaction with non-debug containers. */ operator _Iterator() const { return *this; } /** Attach iterator to the given sequence. */ void _M_attach(_Safe_sequence_base* __seq) { _Safe_base::_M_attach(__seq, _M_constant()); } /** Likewise, but not thread-safe. */ void _M_attach_single(_Safe_sequence_base* __seq) { _Safe_base::_M_attach_single(__seq, _M_constant()); } /// Is the iterator dereferenceable? bool _M_dereferenceable() const { return !this->_M_singular() && !_M_is_end(); } /// Is the iterator incrementable? bool _M_incrementable() const { return !this->_M_singular() && !_M_is_end(); } // Is the iterator range [*this, __rhs) valid? bool _M_valid_range(const _Safe_local_iterator& __rhs, std::pair& __dist_info) const; // The sequence this iterator references. typename __gnu_cxx::__conditional_type::__value, const _Sequence*, _Sequence*>::__type _M_get_sequence() const { return static_cast<_Sequence*>(_M_sequence); } /// Is this iterator equal to the sequence's begin(bucket) iterator? bool _M_is_begin() const { return base() == _M_get_sequence()->_M_base().begin(bucket()); } /// Is this iterator equal to the sequence's end(bucket) iterator? bool _M_is_end() const { return base() == _M_get_sequence()->_M_base().end(bucket()); } /// Is this iterator part of the same bucket as the other one? template bool _M_in_same_bucket(const _Safe_local_iterator<_Other, _Sequence>& __other) const { return bucket() == __other.bucket(); } }; template inline bool operator==(const _Safe_local_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_local_iterator<_IteratorR, _Sequence>& __rhs) { _GLIBCXX_DEBUG_VERIFY(!__lhs._M_singular() && !__rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_in_same_bucket(__rhs), _M_message(__msg_local_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() == __rhs.base(); } template inline bool operator==(const _Safe_local_iterator<_Iterator, _Sequence>& __lhs, const _Safe_local_iterator<_Iterator, _Sequence>& __rhs) { _GLIBCXX_DEBUG_VERIFY(!__lhs._M_singular() && !__rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_in_same_bucket(__rhs), _M_message(__msg_local_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() == __rhs.base(); } template inline bool operator!=(const _Safe_local_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_local_iterator<_IteratorR, _Sequence>& __rhs) { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_in_same_bucket(__rhs), _M_message(__msg_local_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() != __rhs.base(); } template inline bool operator!=(const _Safe_local_iterator<_Iterator, _Sequence>& __lhs, const _Safe_local_iterator<_Iterator, _Sequence>& __rhs) { _GLIBCXX_DEBUG_VERIFY(!__lhs._M_singular() && !__rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_in_same_bucket(__rhs), _M_message(__msg_local_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() != __rhs.base(); } /** Safe local iterators know if they are dereferenceable. */ template inline bool __check_dereferenceable(const _Safe_local_iterator<_Iterator, _Sequence>& __x) { return __x._M_dereferenceable(); } /** Safe local iterators know how to check if they form a valid range. */ template inline bool __valid_range(const _Safe_local_iterator<_Iterator, _Sequence>& __first, const _Safe_local_iterator<_Iterator, _Sequence>& __last, typename _Distance_traits<_Iterator>::__type& __dist_info) { return __first._M_valid_range(__last, __dist_info); } /** Safe local iterators need a special method to get distance between each other. */ template inline std::pair::difference_type, _Distance_precision> __get_distance(const _Safe_local_iterator<_Iterator, _Sequence>& __first, const _Safe_local_iterator<_Iterator, _Sequence>& __last, std::input_iterator_tag) { if (__first.base() == __last.base()) return { 0, __dp_exact }; if (__first._M_is_begin()) { if (__last._M_is_end()) return { __first._M_get_sequence()->bucket_size(__first.bucket()), __dp_exact }; return { 1, __dp_sign }; } if (__first._M_is_end()) { if (__last._M_is_begin()) return { -__first._M_get_sequence()->bucket_size(__first.bucket()), __dp_exact }; return { -1, __dp_sign }; } if (__last._M_is_begin()) return { -1, __dp_sign }; if (__last._M_is_end()) return { 1, __dp_sign }; return { 1, __dp_equality }; } #if __cplusplus < 201103L template struct _Unsafe_type<_Safe_local_iterator<_Iterator, _Sequence> > { typedef _Iterator _Type; }; #endif template inline _Iterator __unsafe(const _Safe_local_iterator<_Iterator, _Sequence>& __it) { return __it.base(); } } // namespace __gnu_debug #include #endif PK!0EFF8/debug/safe_local_iterator.tccnu[// Debugging iterator implementation (out of line) -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_local_iterator.tcc * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_LOCAL_ITERATOR_TCC #define _GLIBCXX_DEBUG_SAFE_LOCAL_ITERATOR_TCC 1 namespace __gnu_debug { template bool _Safe_local_iterator<_Iterator, _Sequence>:: _M_valid_range(const _Safe_local_iterator& __rhs, std::pair& __dist) const { if (!_M_can_compare(__rhs)) return false; if (bucket() != __rhs.bucket()) return false; /* Determine if we can order the iterators without the help of the container */ __dist = __get_distance(*this, __rhs); switch (__dist.second) { case __dp_equality: if (__dist.first == 0) return true; break; case __dp_sign: case __dp_exact: return __dist.first >= 0; } // Assume that this is a valid range; we can't check anything else return true; } } // namespace __gnu_debug #endif PK!8/debug/safe_sequence.hnu[// Safe sequence implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_sequence.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_SEQUENCE_H #define _GLIBCXX_DEBUG_SAFE_SEQUENCE_H 1 #include #include #include #include namespace __gnu_debug { /** A simple function object that returns true if the passed-in * value is not equal to the stored value. It saves typing over * using both bind1st and not_equal. */ template class _Not_equal_to { _Type __value; public: explicit _Not_equal_to(const _Type& __v) : __value(__v) { } bool operator()(const _Type& __x) const { return __value != __x; } }; /** A simple function object that returns true if the passed-in * value is equal to the stored value. */ template class _Equal_to { _Type __value; public: explicit _Equal_to(const _Type& __v) : __value(__v) { } bool operator()(const _Type& __x) const { return __value == __x; } }; /** A function object that returns true when the given random access iterator is at least @c n steps away from the given iterator. */ template class _After_nth_from { typedef typename std::iterator_traits<_Iterator>::difference_type difference_type; _Iterator _M_base; difference_type _M_n; public: _After_nth_from(const difference_type& __n, const _Iterator& __base) : _M_base(__base), _M_n(__n) { } bool operator()(const _Iterator& __x) const { return __x - _M_base >= _M_n; } }; /** * @brief Base class for constructing a @a safe sequence type that * tracks iterators that reference it. * * The class template %_Safe_sequence simplifies the construction of * @a safe sequences that track the iterators that reference the * sequence, so that the iterators are notified of changes in the * sequence that may affect their operation, e.g., if the container * invalidates its iterators or is destructed. This class template * may only be used by deriving from it and passing the name of the * derived class as its template parameter via the curiously * recurring template pattern. The derived class must have @c * iterator and @c const_iterator types that are instantiations of * class template _Safe_iterator for this sequence. Iterators will * then be tracked automatically. */ template class _Safe_sequence : public _Safe_sequence_base { public: /** Invalidates all iterators @c x that reference this sequence, are not singular, and for which @c __pred(x) returns @c true. @c __pred will be invoked with the normal iterators nested in the safe ones. */ template void _M_invalidate_if(_Predicate __pred); /** Transfers all iterators @c x that reference @c from sequence, are not singular, and for which @c __pred(x) returns @c true. @c __pred will be invoked with the normal iterators nested in the safe ones. */ template void _M_transfer_from_if(_Safe_sequence& __from, _Predicate __pred); }; /// Like _Safe_sequence but with a special _M_invalidate_all implementation /// not invalidating past-the-end iterators. Used by node based sequence. template class _Safe_node_sequence : public _Safe_sequence<_Sequence> { protected: void _M_invalidate_all() { typedef typename _Sequence::const_iterator _Const_iterator; typedef typename _Const_iterator::iterator_type _Base_const_iterator; typedef __gnu_debug::_Not_equal_to<_Base_const_iterator> _Not_equal; const _Sequence& __seq = *static_cast<_Sequence*>(this); this->_M_invalidate_if(_Not_equal(__seq._M_base().end())); } }; } // namespace __gnu_debug #include #endif PK!>}}8/debug/safe_sequence.tccnu[// Safe sequence implementation -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_sequence.tcc * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_SEQUENCE_TCC #define _GLIBCXX_DEBUG_SAFE_SEQUENCE_TCC 1 namespace __gnu_debug { template template void _Safe_sequence<_Sequence>:: _M_invalidate_if(_Predicate __pred) { typedef typename _Sequence::iterator iterator; typedef typename _Sequence::const_iterator const_iterator; __gnu_cxx::__scoped_lock sentry(this->_M_get_mutex()); for (_Safe_iterator_base* __iter = _M_iterators; __iter;) { iterator* __victim = static_cast(__iter); __iter = __iter->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_invalidate(); } } for (_Safe_iterator_base* __iter2 = _M_const_iterators; __iter2;) { const_iterator* __victim = static_cast(__iter2); __iter2 = __iter2->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_invalidate(); } } } template template void _Safe_sequence<_Sequence>:: _M_transfer_from_if(_Safe_sequence& __from, _Predicate __pred) { typedef typename _Sequence::iterator iterator; typedef typename _Sequence::const_iterator const_iterator; _Safe_iterator_base* __transfered_iterators = 0; _Safe_iterator_base* __transfered_const_iterators = 0; _Safe_iterator_base* __last_iterator = 0; _Safe_iterator_base* __last_const_iterator = 0; { // We lock __from first and detach iterator(s) to transfer __gnu_cxx::__scoped_lock sentry(__from._M_get_mutex()); for (_Safe_iterator_base* __iter = __from._M_iterators; __iter;) { _Safe_iterator_base* __victim_base = __iter; iterator* __victim = static_cast(__victim_base); __iter = __iter->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_detach_single(); if (__transfered_iterators) { __victim_base->_M_next = __transfered_iterators; __transfered_iterators->_M_prior = __victim_base; } else __last_iterator = __victim_base; __victim_base->_M_sequence = this; __victim_base->_M_version = this->_M_version; __transfered_iterators = __victim_base; } } for (_Safe_iterator_base* __iter2 = __from._M_const_iterators; __iter2;) { _Safe_iterator_base* __victim_base = __iter2; const_iterator* __victim = static_cast(__victim_base); __iter2 = __iter2->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_detach_single(); if (__transfered_const_iterators) { __victim_base->_M_next = __transfered_const_iterators; __transfered_const_iterators->_M_prior = __victim_base; } else __last_const_iterator = __victim; __victim_base->_M_sequence = this; __victim_base->_M_version = this->_M_version; __transfered_const_iterators = __victim_base; } } } // Now we can lock *this and add the transfered iterators if any if (__last_iterator || __last_const_iterator) { __gnu_cxx::__scoped_lock sentry(this->_M_get_mutex()); if (__last_iterator) { if (this->_M_iterators) { this->_M_iterators->_M_prior = __last_iterator; __last_iterator->_M_next = this->_M_iterators; } this->_M_iterators = __transfered_iterators; } if (__last_const_iterator) { if (this->_M_const_iterators) { this->_M_const_iterators->_M_prior = __last_const_iterator; __last_const_iterator->_M_next = this->_M_const_iterators; } this->_M_const_iterators = __transfered_const_iterators; } } } } // namespace __gnu_debug #endif PK!B8/debug/safe_unordered_base.hnu[// Safe container/iterator base implementation -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_unordered_base.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_UNORDERED_BASE_H #define _GLIBCXX_DEBUG_SAFE_UNORDERED_BASE_H 1 #include namespace __gnu_debug { class _Safe_unordered_container_base; /** \brief Basic functionality for a @a safe iterator. * * The %_Safe_local_iterator_base base class implements the functionality * of a safe local iterator that is not specific to a particular iterator * type. It contains a pointer back to the container it references * along with iterator version information and pointers to form a * doubly-linked list of local iterators referenced by the container. * * This class must not perform any operations that can throw an * exception, or the exception guarantees of derived iterators will * be broken. */ class _Safe_local_iterator_base : public _Safe_iterator_base { protected: /** Initializes the iterator and makes it singular. */ _Safe_local_iterator_base() { } /** Initialize the iterator to reference the container pointed to * by @p __seq. @p __constant is true when we are initializing a * constant local iterator, and false if it is a mutable local iterator. * Note that @p __seq may be NULL, in which case the iterator will be * singular. Otherwise, the iterator will reference @p __seq and * be nonsingular. */ _Safe_local_iterator_base(const _Safe_sequence_base* __seq, bool __constant) { this->_M_attach(const_cast<_Safe_sequence_base*>(__seq), __constant); } /** Initializes the iterator to reference the same container that @p __x does. @p __constant is true if this is a constant iterator, and false if it is mutable. */ _Safe_local_iterator_base(const _Safe_local_iterator_base& __x, bool __constant) { this->_M_attach(__x._M_sequence, __constant); } ~_Safe_local_iterator_base() { this->_M_detach(); } _Safe_unordered_container_base* _M_get_container() const noexcept; /** Attaches this iterator to the given container, detaching it * from whatever container it was attached to originally. If the * new container is the NULL pointer, the iterator is left * unattached. */ void _M_attach(_Safe_sequence_base* __seq, bool __constant); /** Likewise, but not thread-safe. */ void _M_attach_single(_Safe_sequence_base* __seq, bool __constant) throw (); /** Detach the iterator for whatever container it is attached to, * if any. */ void _M_detach(); /** Likewise, but not thread-safe. */ void _M_detach_single() throw (); }; /** * @brief Base class that supports tracking of local iterators that * reference an unordered container. * * The %_Safe_unordered_container_base class provides basic support for * tracking iterators into an unordered container. Containers that track * iterators must derived from %_Safe_unordered_container_base publicly, so * that safe iterators (which inherit _Safe_iterator_base) can * attach to them. This class contains four linked lists of * iterators, one for constant iterators, one for mutable * iterators, one for constant local iterators, one for mutable local * iterators and a version number that allows very fast * invalidation of all iterators that reference the container. * * This class must ensure that no operation on it may throw an * exception, otherwise @a safe containers may fail to provide the * exception-safety guarantees required by the C++ standard. */ class _Safe_unordered_container_base : public _Safe_sequence_base { friend class _Safe_local_iterator_base; typedef _Safe_sequence_base _Base; public: /// The list of mutable local iterators that reference this container _Safe_iterator_base* _M_local_iterators; /// The list of constant local iterators that reference this container _Safe_iterator_base* _M_const_local_iterators; protected: // Initialize with a version number of 1 and no iterators _Safe_unordered_container_base() noexcept : _M_local_iterators(nullptr), _M_const_local_iterators(nullptr) { } // Copy constructor does not copy iterators. _Safe_unordered_container_base(const _Safe_unordered_container_base&) noexcept : _Safe_unordered_container_base() { } // When moved unordered containers iterators are swapped. _Safe_unordered_container_base(_Safe_unordered_container_base&& __x) noexcept : _Safe_unordered_container_base() { this->_M_swap(__x); } /** Notify all iterators that reference this container that the container is being destroyed. */ ~_Safe_unordered_container_base() noexcept { this->_M_detach_all(); } /** Detach all iterators, leaving them singular. */ void _M_detach_all(); /** Swap this container with the given container. This operation * also swaps ownership of the iterators, so that when the * operation is complete all iterators that originally referenced * one container now reference the other container. */ void _M_swap(_Safe_unordered_container_base& __x) noexcept; private: /** Attach an iterator to this container. */ void _M_attach_local(_Safe_iterator_base* __it, bool __constant); /** Likewise but not thread safe. */ void _M_attach_local_single(_Safe_iterator_base* __it, bool __constant) throw (); /** Detach an iterator from this container */ void _M_detach_local(_Safe_iterator_base* __it); /** Likewise but not thread safe. */ void _M_detach_local_single(_Safe_iterator_base* __it) throw (); }; } // namespace __gnu_debug #endif PK!֟299"8/debug/safe_unordered_container.hnu[// Safe container implementation -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_unordered_container.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_UNORDERED_CONTAINER_H #define _GLIBCXX_DEBUG_SAFE_UNORDERED_CONTAINER_H 1 #include #include #include #include namespace __gnu_debug { /** * @brief Base class for constructing a @a safe unordered container type * that tracks iterators that reference it. * * The class template %_Safe_unordered_container simplifies the * construction of @a safe unordered containers that track the iterators * that reference the container, so that the iterators are notified of * changes in the container that may affect their operation, e.g., if * the container invalidates its iterators or is destructed. This class * template may only be used by deriving from it and passing the name * of the derived class as its template parameter via the curiously * recurring template pattern. The derived class must have @c * iterator and @c const_iterator types that are instantiations of * class template _Safe_iterator for this container and @c local_iterator * and @c const_local_iterator types that are instantiations of class * template _Safe_local_iterator for this container. Iterators will * then be tracked automatically. */ template class _Safe_unordered_container : public _Safe_unordered_container_base { private: _Container& _M_cont() noexcept { return *static_cast<_Container*>(this); } protected: void _M_invalidate_locals() { auto __local_end = _M_cont()._M_base().end(0); this->_M_invalidate_local_if( [__local_end](__decltype(_M_cont()._M_base().cend(0)) __it) { return __it != __local_end; }); } void _M_invalidate_all() { auto __end = _M_cont()._M_base().end(); this->_M_invalidate_if( [__end](__decltype(_M_cont()._M_base().cend()) __it) { return __it != __end; }); _M_invalidate_locals(); } /** Invalidates all iterators @c x that reference this container, are not singular, and for which @c __pred(x) returns @c true. @c __pred will be invoked with the normal iterators nested in the safe ones. */ template void _M_invalidate_if(_Predicate __pred); /** Invalidates all local iterators @c x that reference this container, are not singular, and for which @c __pred(x) returns @c true. @c __pred will be invoked with the normal ilocal iterators nested in the safe ones. */ template void _M_invalidate_local_if(_Predicate __pred); }; } // namespace __gnu_debug #include #endif PK!퍎 $8/debug/safe_unordered_container.tccnu[// Safe container implementation -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_unordered_container.tcc * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_UNORDERED_CONTAINER_TCC #define _GLIBCXX_DEBUG_SAFE_UNORDERED_CONTAINER_TCC 1 namespace __gnu_debug { template template void _Safe_unordered_container<_Container>:: _M_invalidate_if(_Predicate __pred) { typedef typename _Container::iterator iterator; typedef typename _Container::const_iterator const_iterator; __gnu_cxx::__scoped_lock sentry(this->_M_get_mutex()); for (_Safe_iterator_base* __iter = _M_iterators; __iter;) { iterator* __victim = static_cast(__iter); __iter = __iter->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_invalidate(); } } for (_Safe_iterator_base* __iter2 = _M_const_iterators; __iter2;) { const_iterator* __victim = static_cast(__iter2); __iter2 = __iter2->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_invalidate(); } } } template template void _Safe_unordered_container<_Container>:: _M_invalidate_local_if(_Predicate __pred) { typedef typename _Container::local_iterator local_iterator; typedef typename _Container::const_local_iterator const_local_iterator; __gnu_cxx::__scoped_lock sentry(this->_M_get_mutex()); for (_Safe_iterator_base* __iter = _M_local_iterators; __iter;) { local_iterator* __victim = static_cast(__iter); __iter = __iter->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_invalidate(); } } for (_Safe_iterator_base* __iter2 = _M_const_local_iterators; __iter2;) { const_local_iterator* __victim = static_cast(__iter2); __iter2 = __iter2->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_invalidate(); } } } } // namespace __gnu_debug #endif PK!5*]AA 8/debug/setnu[// Debugging set/multiset implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/set * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SET #define _GLIBCXX_DEBUG_SET 1 #pragma GCC system_header #include #include #include #endif PK! II 8/debug/set.hnu[// Debugging set implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/set.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SET_H #define _GLIBCXX_DEBUG_SET_H 1 #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::set with safety/checking/debug instrumentation. template, typename _Allocator = std::allocator<_Key> > class set : public __gnu_debug::_Safe_container< set<_Key, _Compare, _Allocator>, _Allocator, __gnu_debug::_Safe_node_sequence>, public _GLIBCXX_STD_C::set<_Key,_Compare,_Allocator> { typedef _GLIBCXX_STD_C::set<_Key, _Compare, _Allocator> _Base; typedef __gnu_debug::_Safe_container< set, _Allocator, __gnu_debug::_Safe_node_sequence> _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef __gnu_debug::_Equal_to<_Base_const_iterator> _Equal; public: // types: typedef _Key key_type; typedef _Key value_type; typedef _Compare key_compare; typedef _Compare value_compare; typedef _Allocator allocator_type; typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator<_Base_iterator, set> iterator; typedef __gnu_debug::_Safe_iterator<_Base_const_iterator, set> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // 23.3.3.1 construct/copy/destroy: #if __cplusplus < 201103L set() : _Base() { } set(const set& __x) : _Base(__x) { } ~set() { } #else set() = default; set(const set&) = default; set(set&&) = default; set(initializer_list __l, const _Compare& __comp = _Compare(), const allocator_type& __a = allocator_type()) : _Base(__l, __comp, __a) { } explicit set(const allocator_type& __a) : _Base(__a) { } set(const set& __x, const allocator_type& __a) : _Base(__x, __a) { } set(set&& __x, const allocator_type& __a) noexcept( noexcept(_Base(std::move(__x._M_base()), __a)) ) : _Safe(std::move(__x._M_safe()), __a), _Base(std::move(__x._M_base()), __a) { } set(initializer_list __l, const allocator_type& __a) : _Base(__l, __a) { } template set(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __a) { } ~set() = default; #endif explicit set(const _Compare& __comp, const _Allocator& __a = _Allocator()) : _Base(__comp, __a) { } template set(_InputIterator __first, _InputIterator __last, const _Compare& __comp = _Compare(), const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __comp, __a) { } set(const _Base& __x) : _Base(__x) { } #if __cplusplus < 201103L set& operator=(const set& __x) { this->_M_safe() = __x; _M_base() = __x; return *this; } #else set& operator=(const set&) = default; set& operator=(set&&) = default; set& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } #endif using _Base::get_allocator; // iterators: iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // capacity: using _Base::empty; using _Base::size; using _Base::max_size; // modifiers: #if __cplusplus >= 201103L template std::pair emplace(_Args&&... __args) { auto __res = _Base::emplace(std::forward<_Args>(__args)...); return std::pair(iterator(__res.first, this), __res.second); } template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { __glibcxx_check_insert(__pos); return iterator(_Base::emplace_hint(__pos.base(), std::forward<_Args>(__args)...), this); } #endif std::pair insert(const value_type& __x) { std::pair<_Base_iterator, bool> __res = _Base::insert(__x); return std::pair(iterator(__res.first, this), __res.second); } #if __cplusplus >= 201103L std::pair insert(value_type&& __x) { std::pair<_Base_iterator, bool> __res = _Base::insert(std::move(__x)); return std::pair(iterator(__res.first, this), __res.second); } #endif iterator insert(const_iterator __position, const value_type& __x) { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), __x), this); } #if __cplusplus >= 201103L iterator insert(const_iterator __position, value_type&& __x) { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), std::move(__x)), this); } #endif template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); } #if __cplusplus >= 201103L void insert(initializer_list __l) { _Base::insert(__l); } #endif #if __cplusplus > 201402L using node_type = typename _Base::node_type; using insert_return_type = _Node_insert_return; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } insert_return_type insert(node_type&& __nh) { auto __ret = _Base::insert(std::move(__nh)); iterator __pos = iterator(__ret.position, this); return { __pos, __ret.inserted, std::move(__ret.node) }; } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 #if __cplusplus >= 201103L iterator erase(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return iterator(_Base::erase(__position.base()), this); } #else void erase(iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); _Base::erase(__position.base()); } #endif size_type erase(const key_type& __x) { _Base_iterator __victim = _Base::find(__x); if (__victim == _Base::end()) return 0; else { this->_M_invalidate_if(_Equal(__victim)); _Base::erase(__victim); return 1; } } #if __cplusplus >= 201103L iterator erase(const_iterator __first, const_iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } return iterator(_Base::erase(__first.base(), __last.base()), this); } #else void erase(iterator __first, iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } _Base::erase(__first.base(), __last.base()); } #endif void swap(set& __x) _GLIBCXX_NOEXCEPT_IF( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() _GLIBCXX_NOEXCEPT { this->_M_invalidate_all(); _Base::clear(); } // observers: using _Base::key_comp; using _Base::value_comp; // set operations: iterator find(const key_type& __x) { return iterator(_Base::find(__x), this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload const_iterator find(const key_type& __x) const { return const_iterator(_Base::find(__x), this); } #if __cplusplus > 201103L template::type> iterator find(const _Kt& __x) { return { _Base::find(__x), this }; } template::type> const_iterator find(const _Kt& __x) const { return { _Base::find(__x), this }; } #endif using _Base::count; iterator lower_bound(const key_type& __x) { return iterator(_Base::lower_bound(__x), this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload const_iterator lower_bound(const key_type& __x) const { return const_iterator(_Base::lower_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator lower_bound(const _Kt& __x) { return { _Base::lower_bound(__x), this }; } template::type> const_iterator lower_bound(const _Kt& __x) const { return { _Base::lower_bound(__x), this }; } #endif iterator upper_bound(const key_type& __x) { return iterator(_Base::upper_bound(__x), this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload const_iterator upper_bound(const key_type& __x) const { return const_iterator(_Base::upper_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator upper_bound(const _Kt& __x) { return { _Base::upper_bound(__x), this }; } template::type> const_iterator upper_bound(const _Kt& __x) const { return { _Base::upper_bound(__x), this }; } #endif std::pair equal_range(const key_type& __x) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__x); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload std::pair equal_range(const key_type& __x) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__x); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } #if __cplusplus > 201103L template::type> std::pair equal_range(const _Kt& __x) { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } template::type> std::pair equal_range(const _Kt& __x) const { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } #endif _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> set(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> set::value_type, _Compare, _Allocator>; template, typename _Allocator = allocator<_Key>, typename = _RequireAllocator<_Allocator>> set(initializer_list<_Key>, _Compare = _Compare(), _Allocator = _Allocator()) -> set<_Key, _Compare, _Allocator>; template, typename = _RequireAllocator<_Allocator>> set(_InputIterator, _InputIterator, _Allocator) -> set::value_type, less::value_type>, _Allocator>; template> set(initializer_list<_Key>, _Allocator) -> set<_Key, less<_Key>, _Allocator>; #endif template inline bool operator==(const set<_Key, _Compare, _Allocator>& __lhs, const set<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator!=(const set<_Key, _Compare, _Allocator>& __lhs, const set<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator<(const set<_Key, _Compare, _Allocator>& __lhs, const set<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<=(const set<_Key, _Compare, _Allocator>& __lhs, const set<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator>=(const set<_Key, _Compare, _Allocator>& __lhs, const set<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>(const set<_Key, _Compare, _Allocator>& __lhs, const set<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template void swap(set<_Key, _Compare, _Allocator>& __x, set<_Key, _Compare, _Allocator>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { return __x.swap(__y); } } // namespace __debug } // namespace std #endif PK!xI8/debug/stl_iterator.hnu[// Debugging support implementation -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/stl_iterator.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_STL_ITERATOR_H #define _GLIBCXX_DEBUG_STL_ITERATOR_H 1 #include namespace __gnu_debug { // Help Debug mode to see through reverse_iterator. template inline bool __valid_range(const std::reverse_iterator<_Iterator>& __first, const std::reverse_iterator<_Iterator>& __last, typename _Distance_traits<_Iterator>::__type& __dist) { return __valid_range(__last.base(), __first.base(), __dist); } template inline typename _Distance_traits<_Iterator>::__type __get_distance(const std::reverse_iterator<_Iterator>& __first, const std::reverse_iterator<_Iterator>& __last) { return __get_distance(__last.base(), __first.base()); } #if __cplusplus < 201103L template struct __is_safe_random_iterator > : __is_safe_random_iterator<_Iterator> { }; template struct _Unsafe_type > { typedef typename _Unsafe_type<_Iterator>::_Type _UnsafeType; typedef std::reverse_iterator<_UnsafeType> _Type; }; template inline std::reverse_iterator::_Type> __unsafe(const std::reverse_iterator<_Iterator>& __it) { typedef typename _Unsafe_type<_Iterator>::_Type _UnsafeType; return std::reverse_iterator<_UnsafeType>(__unsafe(__it.base())); } #else template inline auto __base(const std::reverse_iterator<_Iterator>& __it) -> decltype(std::__make_reverse_iterator(__base(__it.base()))) { return std::__make_reverse_iterator(__base(__it.base())); } template inline auto __unsafe(const std::reverse_iterator<_Iterator>& __it) -> decltype(std::__make_reverse_iterator(__unsafe(__it.base()))) { return std::__make_reverse_iterator(__unsafe(__it.base())); } #endif #if __cplusplus >= 201103L // Help Debug mode to see through move_iterator. template inline bool __valid_range(const std::move_iterator<_Iterator>& __first, const std::move_iterator<_Iterator>& __last, typename _Distance_traits<_Iterator>::__type& __dist) { return __valid_range(__first.base(), __last.base(), __dist); } template inline typename _Distance_traits<_Iterator>::__type __get_distance(const std::move_iterator<_Iterator>& __first, const std::move_iterator<_Iterator>& __last) { return __get_distance(__first.base(), __last.base()); } template inline auto __unsafe(const std::move_iterator<_Iterator>& __it) -> decltype(std::make_move_iterator(__unsafe(__it.base()))) { return std::make_move_iterator(__unsafe(__it.base())); } template inline auto __base(const std::move_iterator<_Iterator>& __it) -> decltype(std::make_move_iterator(__base(__it.base()))) { return std::make_move_iterator(__base(__it.base())); } #endif } #endif PK!V]uu8/debug/stringnu[// Debugging string implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/string * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_STRING #define _GLIBCXX_DEBUG_STRING 1 #pragma GCC system_header #include #include #include #include namespace __gnu_debug { /// Class std::basic_string with safety/checking/debug instrumentation. template, typename _Allocator = std::allocator<_CharT> > class basic_string : public __gnu_debug::_Safe_container< basic_string<_CharT, _Traits, _Allocator>, _Allocator, _Safe_sequence, bool(_GLIBCXX_USE_CXX11_ABI)>, public std::basic_string<_CharT, _Traits, _Allocator> { typedef std::basic_string<_CharT, _Traits, _Allocator> _Base; typedef __gnu_debug::_Safe_container< basic_string, _Allocator, _Safe_sequence, bool(_GLIBCXX_USE_CXX11_ABI)> _Safe; public: // types: typedef _Traits traits_type; typedef typename _Traits::char_type value_type; typedef _Allocator allocator_type; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef __gnu_debug::_Safe_iterator< typename _Base::iterator, basic_string> iterator; typedef __gnu_debug::_Safe_iterator< typename _Base::const_iterator, basic_string> const_iterator; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; using _Base::npos; basic_string() _GLIBCXX_NOEXCEPT_IF(std::is_nothrow_default_constructible<_Base>::value) : _Base() { } // 21.3.1 construct/copy/destroy: explicit basic_string(const _Allocator& __a) _GLIBCXX_NOEXCEPT : _Base(__a) { } #if __cplusplus < 201103L basic_string(const basic_string& __str) : _Base(__str) { } ~basic_string() { } #else basic_string(const basic_string&) = default; basic_string(basic_string&&) = default; basic_string(std::initializer_list<_CharT> __l, const _Allocator& __a = _Allocator()) : _Base(__l, __a) { } #if _GLIBCXX_USE_CXX11_ABI basic_string(const basic_string& __s, const _Allocator& __a) : _Base(__s, __a) { } basic_string(basic_string&& __s, const _Allocator& __a) : _Base(std::move(__s), __a) { } #endif ~basic_string() = default; // Provides conversion from a normal-mode string to a debug-mode string basic_string(_Base&& __base) noexcept : _Base(std::move(__base)) { } #endif // C++11 // Provides conversion from a normal-mode string to a debug-mode string basic_string(const _Base& __base) : _Base(__base) { } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 42. string ctors specify wrong default allocator basic_string(const basic_string& __str, size_type __pos, size_type __n = _Base::npos, const _Allocator& __a = _Allocator()) : _Base(__str, __pos, __n, __a) { } basic_string(const _CharT* __s, size_type __n, const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__check_string(__s, __n), __n, __a) { } basic_string(const _CharT* __s, const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__check_string(__s), __a) { this->assign(__s); } basic_string(size_type __n, _CharT __c, const _Allocator& __a = _Allocator()) : _Base(__n, __c, __a) { } template basic_string(_InputIterator __begin, _InputIterator __end, const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__begin, __end)), __gnu_debug::__base(__end), __a) { } #if __cplusplus < 201103L basic_string& operator=(const basic_string& __str) { this->_M_safe() = __str; _M_base() = __str; return *this; } #else basic_string& operator=(const basic_string&) = default; basic_string& operator=(basic_string&&) = default; #endif basic_string& operator=(const _CharT* __s) { __glibcxx_check_string(__s); _M_base() = __s; this->_M_invalidate_all(); return *this; } basic_string& operator=(_CharT __c) { _M_base() = __c; this->_M_invalidate_all(); return *this; } #if __cplusplus >= 201103L basic_string& operator=(std::initializer_list<_CharT> __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } #endif // C++11 // 21.3.2 iterators: iterator begin() // _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() // _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() // _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() // _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // 21.3.3 capacity: using _Base::size; using _Base::length; using _Base::max_size; void resize(size_type __n, _CharT __c) { _Base::resize(__n, __c); this->_M_invalidate_all(); } void resize(size_type __n) { this->resize(__n, _CharT()); } #if __cplusplus >= 201103L void shrink_to_fit() noexcept { if (capacity() > size()) { __try { reserve(0); this->_M_invalidate_all(); } __catch(...) { } } } #endif using _Base::capacity; using _Base::reserve; void clear() // _GLIBCXX_NOEXCEPT { _Base::clear(); this->_M_invalidate_all(); } using _Base::empty; // 21.3.4 element access: const_reference operator[](size_type __pos) const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(__pos <= this->size(), _M_message(__gnu_debug::__msg_subscript_oob) ._M_sequence(*this, "this") ._M_integer(__pos, "__pos") ._M_integer(this->size(), "size")); return _M_base()[__pos]; } reference operator[](size_type __pos) // _GLIBCXX_NOEXCEPT { #if __cplusplus < 201103L && defined(_GLIBCXX_DEBUG_PEDANTIC) __glibcxx_check_subscript(__pos); #else // as an extension v3 allows s[s.size()] when s is non-const. _GLIBCXX_DEBUG_VERIFY(__pos <= this->size(), _M_message(__gnu_debug::__msg_subscript_oob) ._M_sequence(*this, "this") ._M_integer(__pos, "__pos") ._M_integer(this->size(), "size")); #endif return _M_base()[__pos]; } using _Base::at; #if __cplusplus >= 201103L using _Base::front; using _Base::back; #endif // 21.3.5 modifiers: basic_string& operator+=(const basic_string& __str) { _M_base() += __str; this->_M_invalidate_all(); return *this; } basic_string& operator+=(const _CharT* __s) { __glibcxx_check_string(__s); _M_base() += __s; this->_M_invalidate_all(); return *this; } basic_string& operator+=(_CharT __c) { _M_base() += __c; this->_M_invalidate_all(); return *this; } #if __cplusplus >= 201103L basic_string& operator+=(std::initializer_list<_CharT> __l) { _M_base() += __l; this->_M_invalidate_all(); return *this; } #endif // C++11 basic_string& append(const basic_string& __str) { _Base::append(__str); this->_M_invalidate_all(); return *this; } basic_string& append(const basic_string& __str, size_type __pos, size_type __n) { _Base::append(__str, __pos, __n); this->_M_invalidate_all(); return *this; } basic_string& append(const _CharT* __s, size_type __n) { __glibcxx_check_string_len(__s, __n); _Base::append(__s, __n); this->_M_invalidate_all(); return *this; } basic_string& append(const _CharT* __s) { __glibcxx_check_string(__s); _Base::append(__s); this->_M_invalidate_all(); return *this; } basic_string& append(size_type __n, _CharT __c) { _Base::append(__n, __c); this->_M_invalidate_all(); return *this; } template basic_string& append(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __dp_sign) _Base::append(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::append(__first, __last); this->_M_invalidate_all(); return *this; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 7. string clause minor problems void push_back(_CharT __c) { _Base::push_back(__c); this->_M_invalidate_all(); } basic_string& assign(const basic_string& __x) { _Base::assign(__x); this->_M_invalidate_all(); return *this; } #if __cplusplus >= 201103L basic_string& assign(basic_string&& __x) noexcept(noexcept(std::declval<_Base&>().assign(std::move(__x)))) { _Base::assign(std::move(__x)); this->_M_invalidate_all(); return *this; } #endif // C++11 basic_string& assign(const basic_string& __str, size_type __pos, size_type __n) { _Base::assign(__str, __pos, __n); this->_M_invalidate_all(); return *this; } basic_string& assign(const _CharT* __s, size_type __n) { __glibcxx_check_string_len(__s, __n); _Base::assign(__s, __n); this->_M_invalidate_all(); return *this; } basic_string& assign(const _CharT* __s) { __glibcxx_check_string(__s); _Base::assign(__s); this->_M_invalidate_all(); return *this; } basic_string& assign(size_type __n, _CharT __c) { _Base::assign(__n, __c); this->_M_invalidate_all(); return *this; } template basic_string& assign(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __dp_sign) _Base::assign(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::assign(__first, __last); this->_M_invalidate_all(); return *this; } #if __cplusplus >= 201103L basic_string& assign(std::initializer_list<_CharT> __l) { _Base::assign(__l); this->_M_invalidate_all(); return *this; } #endif // C++11 basic_string& insert(size_type __pos1, const basic_string& __str) { _Base::insert(__pos1, __str); this->_M_invalidate_all(); return *this; } basic_string& insert(size_type __pos1, const basic_string& __str, size_type __pos2, size_type __n) { _Base::insert(__pos1, __str, __pos2, __n); this->_M_invalidate_all(); return *this; } basic_string& insert(size_type __pos, const _CharT* __s, size_type __n) { __glibcxx_check_string(__s); _Base::insert(__pos, __s, __n); this->_M_invalidate_all(); return *this; } basic_string& insert(size_type __pos, const _CharT* __s) { __glibcxx_check_string(__s); _Base::insert(__pos, __s); this->_M_invalidate_all(); return *this; } basic_string& insert(size_type __pos, size_type __n, _CharT __c) { _Base::insert(__pos, __n, __c); this->_M_invalidate_all(); return *this; } iterator insert(iterator __p, _CharT __c) { __glibcxx_check_insert(__p); typename _Base::iterator __res = _Base::insert(__p.base(), __c); this->_M_invalidate_all(); return iterator(__res, this); } void insert(iterator __p, size_type __n, _CharT __c) { __glibcxx_check_insert(__p); _Base::insert(__p.base(), __n, __c); this->_M_invalidate_all(); } template void insert(iterator __p, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range(__p, __first, __last, __dist); if (__dist.second >= __dp_sign) _Base::insert(__p.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__p.base(), __first, __last); this->_M_invalidate_all(); } #if __cplusplus >= 201103L void insert(iterator __p, std::initializer_list<_CharT> __l) { __glibcxx_check_insert(__p); _Base::insert(__p.base(), __l); this->_M_invalidate_all(); } #endif // C++11 basic_string& erase(size_type __pos = 0, size_type __n = _Base::npos) { _Base::erase(__pos, __n); this->_M_invalidate_all(); return *this; } iterator erase(iterator __position) { __glibcxx_check_erase(__position); typename _Base::iterator __res = _Base::erase(__position.base()); this->_M_invalidate_all(); return iterator(__res, this); } iterator erase(iterator __first, iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); typename _Base::iterator __res = _Base::erase(__first.base(), __last.base()); this->_M_invalidate_all(); return iterator(__res, this); } #if __cplusplus >= 201103L void pop_back() // noexcept { __glibcxx_check_nonempty(); _Base::pop_back(); this->_M_invalidate_all(); } #endif // C++11 basic_string& replace(size_type __pos1, size_type __n1, const basic_string& __str) { _Base::replace(__pos1, __n1, __str); this->_M_invalidate_all(); return *this; } basic_string& replace(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2) { _Base::replace(__pos1, __n1, __str, __pos2, __n2); this->_M_invalidate_all(); return *this; } basic_string& replace(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2) { __glibcxx_check_string_len(__s, __n2); _Base::replace(__pos, __n1, __s, __n2); this->_M_invalidate_all(); return *this; } basic_string& replace(size_type __pos, size_type __n1, const _CharT* __s) { __glibcxx_check_string(__s); _Base::replace(__pos, __n1, __s); this->_M_invalidate_all(); return *this; } basic_string& replace(size_type __pos, size_type __n1, size_type __n2, _CharT __c) { _Base::replace(__pos, __n1, __n2, __c); this->_M_invalidate_all(); return *this; } basic_string& replace(iterator __i1, iterator __i2, const basic_string& __str) { __glibcxx_check_erase_range(__i1, __i2); _Base::replace(__i1.base(), __i2.base(), __str); this->_M_invalidate_all(); return *this; } basic_string& replace(iterator __i1, iterator __i2, const _CharT* __s, size_type __n) { __glibcxx_check_erase_range(__i1, __i2); __glibcxx_check_string_len(__s, __n); _Base::replace(__i1.base(), __i2.base(), __s, __n); this->_M_invalidate_all(); return *this; } basic_string& replace(iterator __i1, iterator __i2, const _CharT* __s) { __glibcxx_check_erase_range(__i1, __i2); __glibcxx_check_string(__s); _Base::replace(__i1.base(), __i2.base(), __s); this->_M_invalidate_all(); return *this; } basic_string& replace(iterator __i1, iterator __i2, size_type __n, _CharT __c) { __glibcxx_check_erase_range(__i1, __i2); _Base::replace(__i1.base(), __i2.base(), __n, __c); this->_M_invalidate_all(); return *this; } template basic_string& replace(iterator __i1, iterator __i2, _InputIterator __j1, _InputIterator __j2) { __glibcxx_check_erase_range(__i1, __i2); typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__j1, __j2, __dist); if (__dist.second >= __dp_sign) _Base::replace(__i1.base(), __i2.base(), __gnu_debug::__unsafe(__j1), __gnu_debug::__unsafe(__j2)); else _Base::replace(__i1.base(), __i2.base(), __j1, __j2); this->_M_invalidate_all(); return *this; } #if __cplusplus >= 201103L basic_string& replace(iterator __i1, iterator __i2, std::initializer_list<_CharT> __l) { __glibcxx_check_erase_range(__i1, __i2); _Base::replace(__i1.base(), __i2.base(), __l); this->_M_invalidate_all(); return *this; } #endif // C++11 size_type copy(_CharT* __s, size_type __n, size_type __pos = 0) const { __glibcxx_check_string_len(__s, __n); return _Base::copy(__s, __n, __pos); } void swap(basic_string& __x) _GLIBCXX_NOEXCEPT_IF(std::__is_nothrow_swappable<_Base>::value) { _Safe::_M_swap(__x); _Base::swap(__x); } // 21.3.6 string operations: const _CharT* c_str() const _GLIBCXX_NOEXCEPT { const _CharT* __res = _Base::c_str(); this->_M_invalidate_all(); return __res; } const _CharT* data() const _GLIBCXX_NOEXCEPT { const _CharT* __res = _Base::data(); this->_M_invalidate_all(); return __res; } using _Base::get_allocator; size_type find(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return _Base::find(__str, __pos); } size_type find(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_check_string(__s); return _Base::find(__s, __pos, __n); } size_type find(const _CharT* __s, size_type __pos = 0) const { __glibcxx_check_string(__s); return _Base::find(__s, __pos); } size_type find(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return _Base::find(__c, __pos); } size_type rfind(const basic_string& __str, size_type __pos = _Base::npos) const _GLIBCXX_NOEXCEPT { return _Base::rfind(__str, __pos); } size_type rfind(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_check_string_len(__s, __n); return _Base::rfind(__s, __pos, __n); } size_type rfind(const _CharT* __s, size_type __pos = _Base::npos) const { __glibcxx_check_string(__s); return _Base::rfind(__s, __pos); } size_type rfind(_CharT __c, size_type __pos = _Base::npos) const _GLIBCXX_NOEXCEPT { return _Base::rfind(__c, __pos); } size_type find_first_of(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return _Base::find_first_of(__str, __pos); } size_type find_first_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_check_string(__s); return _Base::find_first_of(__s, __pos, __n); } size_type find_first_of(const _CharT* __s, size_type __pos = 0) const { __glibcxx_check_string(__s); return _Base::find_first_of(__s, __pos); } size_type find_first_of(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return _Base::find_first_of(__c, __pos); } size_type find_last_of(const basic_string& __str, size_type __pos = _Base::npos) const _GLIBCXX_NOEXCEPT { return _Base::find_last_of(__str, __pos); } size_type find_last_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_check_string(__s); return _Base::find_last_of(__s, __pos, __n); } size_type find_last_of(const _CharT* __s, size_type __pos = _Base::npos) const { __glibcxx_check_string(__s); return _Base::find_last_of(__s, __pos); } size_type find_last_of(_CharT __c, size_type __pos = _Base::npos) const _GLIBCXX_NOEXCEPT { return _Base::find_last_of(__c, __pos); } size_type find_first_not_of(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return _Base::find_first_not_of(__str, __pos); } size_type find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_check_string_len(__s, __n); return _Base::find_first_not_of(__s, __pos, __n); } size_type find_first_not_of(const _CharT* __s, size_type __pos = 0) const { __glibcxx_check_string(__s); return _Base::find_first_not_of(__s, __pos); } size_type find_first_not_of(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return _Base::find_first_not_of(__c, __pos); } size_type find_last_not_of(const basic_string& __str, size_type __pos = _Base::npos) const _GLIBCXX_NOEXCEPT { return _Base::find_last_not_of(__str, __pos); } size_type find_last_not_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_check_string(__s); return _Base::find_last_not_of(__s, __pos, __n); } size_type find_last_not_of(const _CharT* __s, size_type __pos = _Base::npos) const { __glibcxx_check_string(__s); return _Base::find_last_not_of(__s, __pos); } size_type find_last_not_of(_CharT __c, size_type __pos = _Base::npos) const _GLIBCXX_NOEXCEPT { return _Base::find_last_not_of(__c, __pos); } basic_string substr(size_type __pos = 0, size_type __n = _Base::npos) const { return basic_string(_Base::substr(__pos, __n)); } int compare(const basic_string& __str) const { return _Base::compare(__str); } int compare(size_type __pos1, size_type __n1, const basic_string& __str) const { return _Base::compare(__pos1, __n1, __str); } int compare(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2) const { return _Base::compare(__pos1, __n1, __str, __pos2, __n2); } int compare(const _CharT* __s) const { __glibcxx_check_string(__s); return _Base::compare(__s); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 5. string::compare specification questionable int compare(size_type __pos1, size_type __n1, const _CharT* __s) const { __glibcxx_check_string(__s); return _Base::compare(__pos1, __n1, __s); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 5. string::compare specification questionable int compare(size_type __pos1, size_type __n1,const _CharT* __s, size_type __n2) const { __glibcxx_check_string_len(__s, __n2); return _Base::compare(__pos1, __n1, __s, __n2); } _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } using _Safe::_M_invalidate_all; }; template inline basic_string<_CharT,_Traits,_Allocator> operator+(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return basic_string<_CharT,_Traits,_Allocator>(__lhs) += __rhs; } template inline basic_string<_CharT,_Traits,_Allocator> operator+(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { __glibcxx_check_string(__lhs); return basic_string<_CharT,_Traits,_Allocator>(__lhs) += __rhs; } template inline basic_string<_CharT,_Traits,_Allocator> operator+(_CharT __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return basic_string<_CharT,_Traits,_Allocator>(1, __lhs) += __rhs; } template inline basic_string<_CharT,_Traits,_Allocator> operator+(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const _CharT* __rhs) { __glibcxx_check_string(__rhs); return basic_string<_CharT,_Traits,_Allocator>(__lhs) += __rhs; } template inline basic_string<_CharT,_Traits,_Allocator> operator+(const basic_string<_CharT,_Traits,_Allocator>& __lhs, _CharT __rhs) { return basic_string<_CharT,_Traits,_Allocator>(__lhs) += __rhs; } template inline bool operator==(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator==(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { __glibcxx_check_string(__lhs); return __lhs == __rhs._M_base(); } template inline bool operator==(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const _CharT* __rhs) { __glibcxx_check_string(__rhs); return __lhs._M_base() == __rhs; } template inline bool operator!=(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator!=(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { __glibcxx_check_string(__lhs); return __lhs != __rhs._M_base(); } template inline bool operator!=(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const _CharT* __rhs) { __glibcxx_check_string(__rhs); return __lhs._M_base() != __rhs; } template inline bool operator<(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { __glibcxx_check_string(__lhs); return __lhs < __rhs._M_base(); } template inline bool operator<(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const _CharT* __rhs) { __glibcxx_check_string(__rhs); return __lhs._M_base() < __rhs; } template inline bool operator<=(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator<=(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { __glibcxx_check_string(__lhs); return __lhs <= __rhs._M_base(); } template inline bool operator<=(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const _CharT* __rhs) { __glibcxx_check_string(__rhs); return __lhs._M_base() <= __rhs; } template inline bool operator>=(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>=(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { __glibcxx_check_string(__lhs); return __lhs >= __rhs._M_base(); } template inline bool operator>=(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const _CharT* __rhs) { __glibcxx_check_string(__rhs); return __lhs._M_base() >= __rhs; } template inline bool operator>(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template inline bool operator>(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { __glibcxx_check_string(__lhs); return __lhs > __rhs._M_base(); } template inline bool operator>(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const _CharT* __rhs) { __glibcxx_check_string(__rhs); return __lhs._M_base() > __rhs; } // 21.3.7.8: template inline void swap(basic_string<_CharT,_Traits,_Allocator>& __lhs, basic_string<_CharT,_Traits,_Allocator>& __rhs) { __lhs.swap(__rhs); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const basic_string<_CharT, _Traits, _Allocator>& __str) { return __os << __str._M_base(); } template std::basic_istream<_CharT,_Traits>& operator>>(std::basic_istream<_CharT,_Traits>& __is, basic_string<_CharT,_Traits,_Allocator>& __str) { std::basic_istream<_CharT,_Traits>& __res = __is >> __str._M_base(); __str._M_invalidate_all(); return __res; } template std::basic_istream<_CharT,_Traits>& getline(std::basic_istream<_CharT,_Traits>& __is, basic_string<_CharT,_Traits,_Allocator>& __str, _CharT __delim) { std::basic_istream<_CharT,_Traits>& __res = getline(__is, __str._M_base(), __delim); __str._M_invalidate_all(); return __res; } template std::basic_istream<_CharT,_Traits>& getline(std::basic_istream<_CharT,_Traits>& __is, basic_string<_CharT,_Traits,_Allocator>& __str) { std::basic_istream<_CharT,_Traits>& __res = getline(__is, __str._M_base()); __str._M_invalidate_all(); return __res; } typedef basic_string string; #ifdef _GLIBCXX_USE_WCHAR_T typedef basic_string wstring; #endif template struct _Insert_range_from_self_is_safe< __gnu_debug::basic_string<_CharT, _Traits, _Allocator> > { enum { __value = 1 }; }; } // namespace __gnu_debug #endif PK!O 'JJ8/debug/unordered_mapnu[// Debugging unordered_map/unordered_multimap implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/unordered_map * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_UNORDERED_MAP #define _GLIBCXX_DEBUG_UNORDERED_MAP 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else # include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::unordered_map with safety/checking/debug instrumentation. template, typename _Pred = std::equal_to<_Key>, typename _Alloc = std::allocator > > class unordered_map : public __gnu_debug::_Safe_container< unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>, _Alloc, __gnu_debug::_Safe_unordered_container>, public _GLIBCXX_STD_C::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc> { typedef _GLIBCXX_STD_C::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc> _Base; typedef __gnu_debug::_Safe_container _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef typename _Base::const_local_iterator _Base_const_local_iterator; typedef typename _Base::local_iterator _Base_local_iterator; public: typedef typename _Base::size_type size_type; typedef typename _Base::hasher hasher; typedef typename _Base::key_equal key_equal; typedef typename _Base::allocator_type allocator_type; typedef typename _Base::key_type key_type; typedef typename _Base::value_type value_type; typedef __gnu_debug::_Safe_iterator< _Base_iterator, unordered_map> iterator; typedef __gnu_debug::_Safe_iterator< _Base_const_iterator, unordered_map> const_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_local_iterator, unordered_map> local_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_const_local_iterator, unordered_map> const_local_iterator; unordered_map() = default; explicit unordered_map(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__n, __hf, __eql, __a) { } template unordered_map(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __n, __hf, __eql, __a) { } unordered_map(const unordered_map&) = default; unordered_map(const _Base& __x) : _Base(__x) { } unordered_map(unordered_map&&) = default; explicit unordered_map(const allocator_type& __a) : _Base(__a) { } unordered_map(const unordered_map& __umap, const allocator_type& __a) : _Base(__umap, __a) { } unordered_map(unordered_map&& __umap, const allocator_type& __a) : _Safe(std::move(__umap._M_safe()), __a), _Base(std::move(__umap._M_base()), __a) { } unordered_map(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__l, __n, __hf, __eql, __a) { } unordered_map(size_type __n, const allocator_type& __a) : unordered_map(__n, hasher(), key_equal(), __a) { } unordered_map(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_map(__n, __hf, key_equal(), __a) { } template unordered_map(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_map(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_map(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_map(__first, __last, __n, __hf, key_equal(), __a) { } unordered_map(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_map(__l, __n, hasher(), key_equal(), __a) { } unordered_map(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_map(__l, __n, __hf, key_equal(), __a) { } ~unordered_map() = default; unordered_map& operator=(const unordered_map&) = default; unordered_map& operator=(unordered_map&&) = default; unordered_map& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } void swap(unordered_map& __x) noexcept( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() noexcept { _Base::clear(); this->_M_invalidate_all(); } iterator begin() noexcept { return iterator(_Base::begin(), this); } const_iterator begin() const noexcept { return const_iterator(_Base::begin(), this); } iterator end() noexcept { return iterator(_Base::end(), this); } const_iterator end() const noexcept { return const_iterator(_Base::end(), this); } const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } // local versions local_iterator begin(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::begin(__b), this); } local_iterator end(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::end(__b), this); } const_local_iterator begin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::begin(__b), this); } const_local_iterator end(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::end(__b), this); } const_local_iterator cbegin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cbegin(__b), this); } const_local_iterator cend(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cend(__b), this); } size_type bucket_size(size_type __b) const { __glibcxx_check_bucket_index(__b); return _Base::bucket_size(__b); } float max_load_factor() const noexcept { return _Base::max_load_factor(); } void max_load_factor(float __f) { __glibcxx_check_max_load_factor(__f); _Base::max_load_factor(__f); } template std::pair emplace(_Args&&... __args) { size_type __bucket_count = this->bucket_count(); std::pair<_Base_iterator, bool> __res = _Base::emplace(std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return std::make_pair(iterator(__res.first, this), __res.second); } template iterator emplace_hint(const_iterator __hint, _Args&&... __args) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::emplace_hint(__hint.base(), std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return iterator(__it, this); } std::pair insert(const value_type& __obj) { size_type __bucket_count = this->bucket_count(); auto __res = _Base::insert(__obj); _M_check_rehashed(__bucket_count); return { iterator(__res.first, this), __res.second }; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init std::pair insert(value_type&& __x) { size_type __bucket_count = this->bucket_count(); auto __res = _Base::insert(std::move(__x)); _M_check_rehashed(__bucket_count); return { iterator(__res.first, this), __res.second }; } template::value>::type> std::pair insert(_Pair&& __obj) { size_type __bucket_count = this->bucket_count(); std::pair<_Base_iterator, bool> __res = _Base::insert(std::forward<_Pair>(__obj)); _M_check_rehashed(__bucket_count); return std::make_pair(iterator(__res.first, this), __res.second); } iterator insert(const_iterator __hint, const value_type& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), __obj); _M_check_rehashed(__bucket_count); return iterator(__it, this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __hint, value_type&& __x) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); auto __it = _Base::insert(__hint.base(), std::move(__x)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } template::value>::type> iterator insert(const_iterator __hint, _Pair&& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), std::forward<_Pair>(__obj)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } void insert(std::initializer_list __l) { size_type __bucket_count = this->bucket_count(); _Base::insert(__l); _M_check_rehashed(__bucket_count); } template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); size_type __bucket_count = this->bucket_count(); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); _M_check_rehashed(__bucket_count); } #if __cplusplus > 201402L template pair try_emplace(const key_type& __k, _Args&&... __args) { auto __res = _Base::try_emplace(__k, std::forward<_Args>(__args)...); return { iterator(__res.first, this), __res.second }; } template pair try_emplace(key_type&& __k, _Args&&... __args) { auto __res = _Base::try_emplace(std::move(__k), std::forward<_Args>(__args)...); return { iterator(__res.first, this), __res.second }; } template iterator try_emplace(const_iterator __hint, const key_type& __k, _Args&&... __args) { __glibcxx_check_insert(__hint); return iterator(_Base::try_emplace(__hint.base(), __k, std::forward<_Args>(__args)...), this); } template iterator try_emplace(const_iterator __hint, key_type&& __k, _Args&&... __args) { __glibcxx_check_insert(__hint); return iterator(_Base::try_emplace(__hint.base(), std::move(__k), std::forward<_Args>(__args)...), this); } template pair insert_or_assign(const key_type& __k, _Obj&& __obj) { auto __res = _Base::insert_or_assign(__k, std::forward<_Obj>(__obj)); return { iterator(__res.first, this), __res.second }; } template pair insert_or_assign(key_type&& __k, _Obj&& __obj) { auto __res = _Base::insert_or_assign(std::move(__k), std::forward<_Obj>(__obj)); return { iterator(__res.first, this), __res.second }; } template iterator insert_or_assign(const_iterator __hint, const key_type& __k, _Obj&& __obj) { __glibcxx_check_insert(__hint); return iterator(_Base::insert_or_assign(__hint.base(), __k, std::forward<_Obj>(__obj)), this); } template iterator insert_or_assign(const_iterator __hint, key_type&& __k, _Obj&& __obj) { __glibcxx_check_insert(__hint); return iterator(_Base::insert_or_assign(__hint.base(), std::move(__k), std::forward<_Obj>(__obj)), this); } #endif // C++17 #if __cplusplus > 201402L using node_type = typename _Base::node_type; using insert_return_type = _Node_insert_return; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); _Base_const_iterator __victim = __position.base(); this->_M_invalidate_if( [__victim](_Base_const_iterator __it) { return __it == __victim; } ); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } insert_return_type insert(node_type&& __nh) { auto __ret = _Base::insert(std::move(__nh)); iterator __pos = iterator(__ret.position, this); return { __pos, __ret.inserted, std::move(__ret.node) }; } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 iterator find(const key_type& __key) { return iterator(_Base::find(__key), this); } const_iterator find(const key_type& __key) const { return const_iterator(_Base::find(__key), this); } std::pair equal_range(const key_type& __key) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__key); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } std::pair equal_range(const key_type& __key) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__key); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } size_type erase(const key_type& __key) { size_type __ret(0); _Base_iterator __victim(_Base::find(__key)); if (__victim != _Base::end()) { this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); size_type __bucket_count = this->bucket_count(); _Base::erase(__victim); _M_check_rehashed(__bucket_count); __ret = 1; } return __ret; } iterator erase(const_iterator __it) { __glibcxx_check_erase(__it); _Base_const_iterator __victim = __it.base(); this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); size_type __bucket_count = this->bucket_count(); _Base_iterator __next = _Base::erase(__it.base()); _M_check_rehashed(__bucket_count); return iterator(__next, this); } iterator erase(iterator __it) { return erase(const_iterator(__it)); } iterator erase(const_iterator __first, const_iterator __last) { __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __tmp = __first.base(); __tmp != __last.base(); ++__tmp) { _GLIBCXX_DEBUG_VERIFY(__tmp != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if([__tmp](_Base_const_iterator __it) { return __it == __tmp; }); this->_M_invalidate_local_if( [__tmp](_Base_const_local_iterator __it) { return __it._M_curr() == __tmp._M_cur; }); } size_type __bucket_count = this->bucket_count(); _Base_iterator __next = _Base::erase(__first.base(), __last.base()); _M_check_rehashed(__bucket_count); return iterator(__next, this); } _Base& _M_base() noexcept { return *this; } const _Base& _M_base() const noexcept { return *this; } private: void _M_check_rehashed(size_type __prev_count) { if (__prev_count != this->bucket_count()) this->_M_invalidate_locals(); } }; #if __cpp_deduction_guides >= 201606 template>, typename _Pred = equal_to<__iter_key_t<_InputIterator>>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, typename unordered_map::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Key>, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> unordered_map(initializer_list>, typename unordered_map::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_map<_Key, _Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, typename unordered_map::size_type, _Allocator) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, _Allocator) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, typename unordered_map::size_type, _Hash, _Allocator) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template> unordered_map(initializer_list>, typename unordered_map::size_type, _Allocator) -> unordered_map<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_map(initializer_list>, _Allocator) -> unordered_map<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_map(initializer_list>, typename unordered_map::size_type, _Hash, _Allocator) -> unordered_map<_Key, _Tp, _Hash, equal_to<_Key>, _Allocator>; #endif template inline void swap(unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline bool operator==(const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return __x._M_base() == __y._M_base(); } template inline bool operator!=(const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } /// Class std::unordered_multimap with safety/checking/debug instrumentation. template, typename _Pred = std::equal_to<_Key>, typename _Alloc = std::allocator > > class unordered_multimap : public __gnu_debug::_Safe_container< unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>, _Alloc, __gnu_debug::_Safe_unordered_container>, public _GLIBCXX_STD_C::unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc> { typedef _GLIBCXX_STD_C::unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc> _Base; typedef __gnu_debug::_Safe_container _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef typename _Base::const_local_iterator _Base_const_local_iterator; typedef typename _Base::local_iterator _Base_local_iterator; public: typedef typename _Base::size_type size_type; typedef typename _Base::hasher hasher; typedef typename _Base::key_equal key_equal; typedef typename _Base::allocator_type allocator_type; typedef typename _Base::key_type key_type; typedef typename _Base::value_type value_type; typedef __gnu_debug::_Safe_iterator< _Base_iterator, unordered_multimap> iterator; typedef __gnu_debug::_Safe_iterator< _Base_const_iterator, unordered_multimap> const_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_local_iterator, unordered_multimap> local_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_const_local_iterator, unordered_multimap> const_local_iterator; unordered_multimap() = default; explicit unordered_multimap(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__n, __hf, __eql, __a) { } template unordered_multimap(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __n, __hf, __eql, __a) { } unordered_multimap(const unordered_multimap&) = default; unordered_multimap(const _Base& __x) : _Base(__x) { } unordered_multimap(unordered_multimap&&) = default; explicit unordered_multimap(const allocator_type& __a) : _Base(__a) { } unordered_multimap(const unordered_multimap& __umap, const allocator_type& __a) : _Base(__umap, __a) { } unordered_multimap(unordered_multimap&& __umap, const allocator_type& __a) : _Safe(std::move(__umap._M_safe()), __a), _Base(std::move(__umap._M_base()), __a) { } unordered_multimap(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__l, __n, __hf, __eql, __a) { } unordered_multimap(size_type __n, const allocator_type& __a) : unordered_multimap(__n, hasher(), key_equal(), __a) { } unordered_multimap(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multimap(__n, __hf, key_equal(), __a) { } template unordered_multimap(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_multimap(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_multimap(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multimap(__first, __last, __n, __hf, key_equal(), __a) { } unordered_multimap(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_multimap(__l, __n, hasher(), key_equal(), __a) { } unordered_multimap(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multimap(__l, __n, __hf, key_equal(), __a) { } ~unordered_multimap() = default; unordered_multimap& operator=(const unordered_multimap&) = default; unordered_multimap& operator=(unordered_multimap&&) = default; unordered_multimap& operator=(initializer_list __l) { this->_M_base() = __l; this->_M_invalidate_all(); return *this; } void swap(unordered_multimap& __x) noexcept( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() noexcept { _Base::clear(); this->_M_invalidate_all(); } iterator begin() noexcept { return iterator(_Base::begin(), this); } const_iterator begin() const noexcept { return const_iterator(_Base::begin(), this); } iterator end() noexcept { return iterator(_Base::end(), this); } const_iterator end() const noexcept { return const_iterator(_Base::end(), this); } const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } // local versions local_iterator begin(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::begin(__b), this); } local_iterator end(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::end(__b), this); } const_local_iterator begin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::begin(__b), this); } const_local_iterator end(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::end(__b), this); } const_local_iterator cbegin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cbegin(__b), this); } const_local_iterator cend(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cend(__b), this); } size_type bucket_size(size_type __b) const { __glibcxx_check_bucket_index(__b); return _Base::bucket_size(__b); } float max_load_factor() const noexcept { return _Base::max_load_factor(); } void max_load_factor(float __f) { __glibcxx_check_max_load_factor(__f); _Base::max_load_factor(__f); } template iterator emplace(_Args&&... __args) { size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::emplace(std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return iterator(__it, this); } template iterator emplace_hint(const_iterator __hint, _Args&&... __args) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::emplace_hint(__hint.base(), std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return iterator(__it, this); } iterator insert(const value_type& __obj) { size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__obj); _M_check_rehashed(__bucket_count); return iterator(__it, this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(value_type&& __x) { size_type __bucket_count = this->bucket_count(); auto __it = _Base::insert(std::move(__x)); _M_check_rehashed(__bucket_count); return { __it, this }; } iterator insert(const_iterator __hint, const value_type& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), __obj); _M_check_rehashed(__bucket_count); return iterator(__it, this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __hint, value_type&& __x) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); auto __it = _Base::insert(__hint.base(), std::move(__x)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } template::value>::type> iterator insert(_Pair&& __obj) { size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(std::forward<_Pair>(__obj)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } template::value>::type> iterator insert(const_iterator __hint, _Pair&& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), std::forward<_Pair>(__obj)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } void insert(std::initializer_list __l) { _Base::insert(__l); } template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); size_type __bucket_count = this->bucket_count(); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); _M_check_rehashed(__bucket_count); } #if __cplusplus > 201402L using node_type = typename _Base::node_type; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); _Base_const_iterator __victim = __position.base(); this->_M_invalidate_if( [__victim](_Base_const_iterator __it) { return __it == __victim; } ); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } iterator insert(node_type&& __nh) { return iterator(_Base::insert(std::move(__nh)), this); } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 iterator find(const key_type& __key) { return iterator(_Base::find(__key), this); } const_iterator find(const key_type& __key) const { return const_iterator(_Base::find(__key), this); } std::pair equal_range(const key_type& __key) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__key); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } std::pair equal_range(const key_type& __key) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__key); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } size_type erase(const key_type& __key) { size_type __ret(0); size_type __bucket_count = this->bucket_count(); std::pair<_Base_iterator, _Base_iterator> __pair = _Base::equal_range(__key); for (_Base_iterator __victim = __pair.first; __victim != __pair.second;) { this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); _Base::erase(__victim++); ++__ret; } _M_check_rehashed(__bucket_count); return __ret; } iterator erase(const_iterator __it) { __glibcxx_check_erase(__it); _Base_const_iterator __victim = __it.base(); this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); size_type __bucket_count = this->bucket_count(); _Base_iterator __next = _Base::erase(__it.base()); _M_check_rehashed(__bucket_count); return iterator(__next, this); } iterator erase(iterator __it) { return erase(const_iterator(__it)); } iterator erase(const_iterator __first, const_iterator __last) { __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __tmp = __first.base(); __tmp != __last.base(); ++__tmp) { _GLIBCXX_DEBUG_VERIFY(__tmp != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if([__tmp](_Base_const_iterator __it) { return __it == __tmp; }); this->_M_invalidate_local_if( [__tmp](_Base_const_local_iterator __it) { return __it._M_curr() == __tmp._M_cur; }); } size_type __bucket_count = this->bucket_count(); _Base_iterator __next = _Base::erase(__first.base(), __last.base()); _M_check_rehashed(__bucket_count); return iterator(__next, this); } _Base& _M_base() noexcept { return *this; } const _Base& _M_base() const noexcept { return *this; } private: void _M_check_rehashed(size_type __prev_count) { if (__prev_count != this->bucket_count()) this->_M_invalidate_locals(); } }; #if __cpp_deduction_guides >= 201606 template>, typename _Pred = equal_to<__iter_key_t<_InputIterator>>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, unordered_multimap::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Key>, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> unordered_multimap(initializer_list>, unordered_multimap::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multimap<_Key, _Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, unordered_multimap::size_type, _Allocator) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, _Allocator) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, unordered_multimap::size_type, _Hash, _Allocator) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template> unordered_multimap(initializer_list>, unordered_multimap::size_type, _Allocator) -> unordered_multimap<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_multimap(initializer_list>, _Allocator) -> unordered_multimap<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_multimap(initializer_list>, unordered_multimap::size_type, _Hash, _Allocator) -> unordered_multimap<_Key, _Tp, _Hash, equal_to<_Key>, _Allocator>; #endif template inline void swap(unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline bool operator==(const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return __x._M_base() == __y._M_base(); } template inline bool operator!=(const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } } // namespace __debug } // namespace std #endif // C++11 #endif PK!v݋݋8/debug/unordered_setnu[// Debugging unordered_set/unordered_multiset implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/unordered_set * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_UNORDERED_SET #define _GLIBCXX_DEBUG_UNORDERED_SET 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else # include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::unordered_set with safety/checking/debug instrumentation. template, typename _Pred = std::equal_to<_Value>, typename _Alloc = std::allocator<_Value> > class unordered_set : public __gnu_debug::_Safe_container< unordered_set<_Value, _Hash, _Pred, _Alloc>, _Alloc, __gnu_debug::_Safe_unordered_container>, public _GLIBCXX_STD_C::unordered_set<_Value, _Hash, _Pred, _Alloc> { typedef _GLIBCXX_STD_C::unordered_set< _Value, _Hash, _Pred, _Alloc> _Base; typedef __gnu_debug::_Safe_container< unordered_set, _Alloc, __gnu_debug::_Safe_unordered_container> _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef typename _Base::const_local_iterator _Base_const_local_iterator; typedef typename _Base::local_iterator _Base_local_iterator; public: typedef typename _Base::size_type size_type; typedef typename _Base::hasher hasher; typedef typename _Base::key_equal key_equal; typedef typename _Base::allocator_type allocator_type; typedef typename _Base::key_type key_type; typedef typename _Base::value_type value_type; typedef __gnu_debug::_Safe_iterator< _Base_iterator, unordered_set> iterator; typedef __gnu_debug::_Safe_iterator< _Base_const_iterator, unordered_set> const_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_local_iterator, unordered_set> local_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_const_local_iterator, unordered_set> const_local_iterator; unordered_set() = default; explicit unordered_set(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__n, __hf, __eql, __a) { } template unordered_set(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __n, __hf, __eql, __a) { } unordered_set(const unordered_set&) = default; unordered_set(const _Base& __x) : _Base(__x) { } unordered_set(unordered_set&&) = default; explicit unordered_set(const allocator_type& __a) : _Base(__a) { } unordered_set(const unordered_set& __uset, const allocator_type& __a) : _Base(__uset, __a) { } unordered_set(unordered_set&& __uset, const allocator_type& __a) : _Safe(std::move(__uset._M_safe()), __a), _Base(std::move(__uset._M_base()), __a) { } unordered_set(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__l, __n, __hf, __eql, __a) { } unordered_set(size_type __n, const allocator_type& __a) : unordered_set(__n, hasher(), key_equal(), __a) { } unordered_set(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_set(__n, __hf, key_equal(), __a) { } template unordered_set(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_set(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_set(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_set(__first, __last, __n, __hf, key_equal(), __a) { } unordered_set(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_set(__l, __n, hasher(), key_equal(), __a) { } unordered_set(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_set(__l, __n, __hf, key_equal(), __a) { } ~unordered_set() = default; unordered_set& operator=(const unordered_set&) = default; unordered_set& operator=(unordered_set&&) = default; unordered_set& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } void swap(unordered_set& __x) noexcept( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() noexcept { _Base::clear(); this->_M_invalidate_all(); } iterator begin() noexcept { return iterator(_Base::begin(), this); } const_iterator begin() const noexcept { return const_iterator(_Base::begin(), this); } iterator end() noexcept { return iterator(_Base::end(), this); } const_iterator end() const noexcept { return const_iterator(_Base::end(), this); } const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } // local versions local_iterator begin(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::begin(__b), this); } local_iterator end(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::end(__b), this); } const_local_iterator begin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::begin(__b), this); } const_local_iterator end(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::end(__b), this); } const_local_iterator cbegin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cbegin(__b), this); } const_local_iterator cend(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cend(__b), this); } size_type bucket_size(size_type __b) const { __glibcxx_check_bucket_index(__b); return _Base::bucket_size(__b); } float max_load_factor() const noexcept { return _Base::max_load_factor(); } void max_load_factor(float __f) { __glibcxx_check_max_load_factor(__f); _Base::max_load_factor(__f); } template std::pair emplace(_Args&&... __args) { size_type __bucket_count = this->bucket_count(); std::pair<_Base_iterator, bool> __res = _Base::emplace(std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return std::make_pair(iterator(__res.first, this), __res.second); } template iterator emplace_hint(const_iterator __hint, _Args&&... __args) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::emplace_hint(__hint.base(), std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return iterator(__it, this); } std::pair insert(const value_type& __obj) { size_type __bucket_count = this->bucket_count(); std::pair<_Base_iterator, bool> __res = _Base::insert(__obj); _M_check_rehashed(__bucket_count); return std::make_pair(iterator(__res.first, this), __res.second); } iterator insert(const_iterator __hint, const value_type& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), __obj); _M_check_rehashed(__bucket_count); return iterator(__it, this); } std::pair insert(value_type&& __obj) { size_type __bucket_count = this->bucket_count(); std::pair<_Base_iterator, bool> __res = _Base::insert(std::move(__obj)); _M_check_rehashed(__bucket_count); return std::make_pair(iterator(__res.first, this), __res.second); } iterator insert(const_iterator __hint, value_type&& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), std::move(__obj)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } void insert(std::initializer_list __l) { size_type __bucket_count = this->bucket_count(); _Base::insert(__l); _M_check_rehashed(__bucket_count); } template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); size_type __bucket_count = this->bucket_count(); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); _M_check_rehashed(__bucket_count); } #if __cplusplus > 201402L using node_type = typename _Base::node_type; using insert_return_type = _Node_insert_return; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); _Base_const_iterator __victim = __position.base(); this->_M_invalidate_if( [__victim](_Base_const_iterator __it) { return __it == __victim; } ); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } insert_return_type insert(node_type&& __nh) { auto __ret = _Base::insert(std::move(__nh)); iterator __pos = iterator(__ret.position, this); return { __pos, __ret.inserted, std::move(__ret.node) }; } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 iterator find(const key_type& __key) { return iterator(_Base::find(__key), this); } const_iterator find(const key_type& __key) const { return const_iterator(_Base::find(__key), this); } std::pair equal_range(const key_type& __key) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__key); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } std::pair equal_range(const key_type& __key) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__key); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } size_type erase(const key_type& __key) { size_type __ret(0); _Base_iterator __victim(_Base::find(__key)); if (__victim != _Base::end()) { this->_M_invalidate_if( [__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); size_type __bucket_count = this->bucket_count(); _Base::erase(__victim); _M_check_rehashed(__bucket_count); __ret = 1; } return __ret; } iterator erase(const_iterator __it) { __glibcxx_check_erase(__it); _Base_const_iterator __victim = __it.base(); this->_M_invalidate_if( [__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); size_type __bucket_count = this->bucket_count(); _Base_iterator __next = _Base::erase(__it.base()); _M_check_rehashed(__bucket_count); return iterator(__next, this); } iterator erase(iterator __it) { return erase(const_iterator(__it)); } iterator erase(const_iterator __first, const_iterator __last) { __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __tmp = __first.base(); __tmp != __last.base(); ++__tmp) { _GLIBCXX_DEBUG_VERIFY(__tmp != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if( [__tmp](_Base_const_iterator __it) { return __it == __tmp; }); this->_M_invalidate_local_if( [__tmp](_Base_const_local_iterator __it) { return __it._M_curr() == __tmp._M_cur; }); } size_type __bucket_count = this->bucket_count(); _Base_iterator __next = _Base::erase(__first.base(), __last.base()); _M_check_rehashed(__bucket_count); return iterator(__next, this); } _Base& _M_base() noexcept { return *this; } const _Base& _M_base() const noexcept { return *this; } private: void _M_check_rehashed(size_type __prev_count) { if (__prev_count != this->bucket_count()) this->_M_invalidate_locals(); } }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Pred = equal_to::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_set(_InputIterator, _InputIterator, unordered_set::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_set::value_type, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Tp>, typename _Allocator = allocator<_Tp>, typename = _RequireAllocator<_Allocator>> unordered_set(initializer_list<_Tp>, unordered_set::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_set<_Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_set(_InputIterator, _InputIterator, unordered_set::size_type, _Allocator) -> unordered_set::value_type, hash< typename iterator_traits<_InputIterator>::value_type>, equal_to< typename iterator_traits<_InputIterator>::value_type>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_set(_InputIterator, _InputIterator, unordered_set::size_type, _Hash, _Allocator) -> unordered_set::value_type, _Hash, equal_to< typename iterator_traits<_InputIterator>::value_type>, _Allocator>; template> unordered_set(initializer_list<_Tp>, unordered_set::size_type, _Allocator) -> unordered_set<_Tp, hash<_Tp>, equal_to<_Tp>, _Allocator>; template> unordered_set(initializer_list<_Tp>, unordered_set::size_type, _Hash, _Allocator) -> unordered_set<_Tp, _Hash, equal_to<_Tp>, _Allocator>; #endif template inline void swap(unordered_set<_Value, _Hash, _Pred, _Alloc>& __x, unordered_set<_Value, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline bool operator==(const unordered_set<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_set<_Value, _Hash, _Pred, _Alloc>& __y) { return __x._M_base() == __y._M_base(); } template inline bool operator!=(const unordered_set<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_set<_Value, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } /// Class std::unordered_multiset with safety/checking/debug instrumentation. template, typename _Pred = std::equal_to<_Value>, typename _Alloc = std::allocator<_Value> > class unordered_multiset : public __gnu_debug::_Safe_container< unordered_multiset<_Value, _Hash, _Pred, _Alloc>, _Alloc, __gnu_debug::_Safe_unordered_container>, public _GLIBCXX_STD_C::unordered_multiset<_Value, _Hash, _Pred, _Alloc> { typedef _GLIBCXX_STD_C::unordered_multiset< _Value, _Hash, _Pred, _Alloc> _Base; typedef __gnu_debug::_Safe_container _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef typename _Base::const_local_iterator _Base_const_local_iterator; typedef typename _Base::local_iterator _Base_local_iterator; public: typedef typename _Base::size_type size_type; typedef typename _Base::hasher hasher; typedef typename _Base::key_equal key_equal; typedef typename _Base::allocator_type allocator_type; typedef typename _Base::key_type key_type; typedef typename _Base::value_type value_type; typedef __gnu_debug::_Safe_iterator< _Base_iterator, unordered_multiset> iterator; typedef __gnu_debug::_Safe_iterator< _Base_const_iterator, unordered_multiset> const_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_local_iterator, unordered_multiset> local_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_const_local_iterator, unordered_multiset> const_local_iterator; unordered_multiset() = default; explicit unordered_multiset(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__n, __hf, __eql, __a) { } template unordered_multiset(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __n, __hf, __eql, __a) { } unordered_multiset(const unordered_multiset&) = default; unordered_multiset(const _Base& __x) : _Base(__x) { } unordered_multiset(unordered_multiset&&) = default; explicit unordered_multiset(const allocator_type& __a) : _Base(__a) { } unordered_multiset(const unordered_multiset& __uset, const allocator_type& __a) : _Base(__uset, __a) { } unordered_multiset(unordered_multiset&& __uset, const allocator_type& __a) : _Safe(std::move(__uset._M_safe()), __a), _Base(std::move(__uset._M_base()), __a) { } unordered_multiset(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__l, __n, __hf, __eql, __a) { } unordered_multiset(size_type __n, const allocator_type& __a) : unordered_multiset(__n, hasher(), key_equal(), __a) { } unordered_multiset(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multiset(__n, __hf, key_equal(), __a) { } template unordered_multiset(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_multiset(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_multiset(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multiset(__first, __last, __n, __hf, key_equal(), __a) { } unordered_multiset(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_multiset(__l, __n, hasher(), key_equal(), __a) { } unordered_multiset(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multiset(__l, __n, __hf, key_equal(), __a) { } ~unordered_multiset() = default; unordered_multiset& operator=(const unordered_multiset&) = default; unordered_multiset& operator=(unordered_multiset&&) = default; unordered_multiset& operator=(initializer_list __l) { this->_M_base() = __l; this->_M_invalidate_all(); return *this; } void swap(unordered_multiset& __x) noexcept( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() noexcept { _Base::clear(); this->_M_invalidate_all(); } iterator begin() noexcept { return iterator(_Base::begin(), this); } const_iterator begin() const noexcept { return const_iterator(_Base::begin(), this); } iterator end() noexcept { return iterator(_Base::end(), this); } const_iterator end() const noexcept { return const_iterator(_Base::end(), this); } const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } // local versions local_iterator begin(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::begin(__b), this); } local_iterator end(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::end(__b), this); } const_local_iterator begin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::begin(__b), this); } const_local_iterator end(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::end(__b), this); } const_local_iterator cbegin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cbegin(__b), this); } const_local_iterator cend(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cend(__b), this); } size_type bucket_size(size_type __b) const { __glibcxx_check_bucket_index(__b); return _Base::bucket_size(__b); } float max_load_factor() const noexcept { return _Base::max_load_factor(); } void max_load_factor(float __f) { __glibcxx_check_max_load_factor(__f); _Base::max_load_factor(__f); } template iterator emplace(_Args&&... __args) { size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::emplace(std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return iterator(__it, this); } template iterator emplace_hint(const_iterator __hint, _Args&&... __args) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::emplace_hint(__hint.base(), std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return iterator(__it, this); } iterator insert(const value_type& __obj) { size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__obj); _M_check_rehashed(__bucket_count); return iterator(__it, this); } iterator insert(const_iterator __hint, const value_type& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), __obj); _M_check_rehashed(__bucket_count); return iterator(__it, this); } iterator insert(value_type&& __obj) { size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(std::move(__obj)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } iterator insert(const_iterator __hint, value_type&& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), std::move(__obj)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } void insert(std::initializer_list __l) { size_type __bucket_count = this->bucket_count(); _Base::insert(__l); _M_check_rehashed(__bucket_count); } template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); size_type __bucket_count = this->bucket_count(); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); _M_check_rehashed(__bucket_count); } #if __cplusplus > 201402L using node_type = typename _Base::node_type; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); _Base_const_iterator __victim = __position.base(); this->_M_invalidate_if( [__victim](_Base_const_iterator __it) { return __it == __victim; } ); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } iterator insert(node_type&& __nh) { return iterator(_Base::insert(std::move(__nh)), this); } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 iterator find(const key_type& __key) { return iterator(_Base::find(__key), this); } const_iterator find(const key_type& __key) const { return const_iterator(_Base::find(__key), this); } std::pair equal_range(const key_type& __key) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__key); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } std::pair equal_range(const key_type& __key) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__key); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } size_type erase(const key_type& __key) { size_type __ret(0); std::pair<_Base_iterator, _Base_iterator> __pair = _Base::equal_range(__key); for (_Base_iterator __victim = __pair.first; __victim != __pair.second;) { this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); _Base::erase(__victim++); ++__ret; } return __ret; } iterator erase(const_iterator __it) { __glibcxx_check_erase(__it); _Base_const_iterator __victim = __it.base(); this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); return iterator(_Base::erase(__it.base()), this); } iterator erase(iterator __it) { return erase(const_iterator(__it)); } iterator erase(const_iterator __first, const_iterator __last) { __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __tmp = __first.base(); __tmp != __last.base(); ++__tmp) { _GLIBCXX_DEBUG_VERIFY(__tmp != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if([__tmp](_Base_const_iterator __it) { return __it == __tmp; }); this->_M_invalidate_local_if( [__tmp](_Base_const_local_iterator __it) { return __it._M_curr() == __tmp._M_cur; }); } return iterator(_Base::erase(__first.base(), __last.base()), this); } _Base& _M_base() noexcept { return *this; } const _Base& _M_base() const noexcept { return *this; } private: void _M_check_rehashed(size_type __prev_count) { if (__prev_count != this->bucket_count()) this->_M_invalidate_locals(); } }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Pred = equal_to::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_multiset(_InputIterator, _InputIterator, unordered_multiset::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multiset::value_type, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Tp>, typename _Allocator = allocator<_Tp>, typename = _RequireAllocator<_Allocator>> unordered_multiset(initializer_list<_Tp>, unordered_multiset::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multiset<_Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multiset(_InputIterator, _InputIterator, unordered_multiset::size_type, _Allocator) -> unordered_multiset::value_type, hash::value_type>, equal_to::value_type>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multiset(_InputIterator, _InputIterator, unordered_multiset::size_type, _Hash, _Allocator) -> unordered_multiset::value_type, _Hash, equal_to< typename iterator_traits<_InputIterator>::value_type>, _Allocator>; template> unordered_multiset(initializer_list<_Tp>, unordered_multiset::size_type, _Allocator) -> unordered_multiset<_Tp, hash<_Tp>, equal_to<_Tp>, _Allocator>; template> unordered_multiset(initializer_list<_Tp>, unordered_multiset::size_type, _Hash, _Allocator) -> unordered_multiset<_Tp, _Hash, equal_to<_Tp>, _Allocator>; #endif template inline void swap(unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x, unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline bool operator==(const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y) { return __x._M_base() == __y._M_base(); } template inline bool operator!=(const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } } // namespace __debug } // namespace std #endif // C++11 #endif PK!˲. /** @file debug/vector * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_VECTOR #define _GLIBCXX_DEBUG_VECTOR 1 #pragma GCC system_header #include #include #include #include #include namespace __gnu_debug { /** @brief Base class for Debug Mode vector. * * Adds information about the guaranteed capacity, which is useful for * detecting code which relies on non-portable implementation details of * the libstdc++ reallocation policy. */ template class _Safe_vector { typedef typename _BaseSequence::size_type size_type; const _SafeSequence& _M_seq() const { return *static_cast(this); } protected: _Safe_vector() _GLIBCXX_NOEXCEPT : _M_guaranteed_capacity(0) { _M_update_guaranteed_capacity(); } _Safe_vector(const _Safe_vector&) _GLIBCXX_NOEXCEPT : _M_guaranteed_capacity(0) { _M_update_guaranteed_capacity(); } _Safe_vector(size_type __n) _GLIBCXX_NOEXCEPT : _M_guaranteed_capacity(__n) { } #if __cplusplus >= 201103L _Safe_vector(_Safe_vector&& __x) noexcept : _Safe_vector() { __x._M_guaranteed_capacity = 0; } _Safe_vector& operator=(const _Safe_vector&) noexcept { _M_update_guaranteed_capacity(); return *this; } _Safe_vector& operator=(_Safe_vector&& __x) noexcept { _M_update_guaranteed_capacity(); __x._M_guaranteed_capacity = 0; return *this; } #endif size_type _M_guaranteed_capacity; bool _M_requires_reallocation(size_type __elements) const _GLIBCXX_NOEXCEPT { return __elements > _M_seq().capacity(); } void _M_update_guaranteed_capacity() _GLIBCXX_NOEXCEPT { if (_M_seq().size() > _M_guaranteed_capacity) _M_guaranteed_capacity = _M_seq().size(); } }; } namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::vector with safety/checking/debug instrumentation. template > class vector : public __gnu_debug::_Safe_container< vector<_Tp, _Allocator>, _Allocator, __gnu_debug::_Safe_sequence>, public _GLIBCXX_STD_C::vector<_Tp, _Allocator>, public __gnu_debug::_Safe_vector< vector<_Tp, _Allocator>, _GLIBCXX_STD_C::vector<_Tp, _Allocator> > { typedef _GLIBCXX_STD_C::vector<_Tp, _Allocator> _Base; typedef __gnu_debug::_Safe_container< vector, _Allocator, __gnu_debug::_Safe_sequence> _Safe; typedef __gnu_debug::_Safe_vector _Safe_vector; typedef typename _Base::iterator _Base_iterator; typedef typename _Base::const_iterator _Base_const_iterator; typedef __gnu_debug::_Equal_to<_Base_const_iterator> _Equal; public: typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator< _Base_iterator, vector> iterator; typedef __gnu_debug::_Safe_iterator< _Base_const_iterator, vector> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef _Tp value_type; typedef _Allocator allocator_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // 23.2.4.1 construct/copy/destroy: #if __cplusplus < 201103L vector() _GLIBCXX_NOEXCEPT : _Base() { } #else vector() = default; #endif explicit vector(const _Allocator& __a) _GLIBCXX_NOEXCEPT : _Base(__a) { } #if __cplusplus >= 201103L explicit vector(size_type __n, const _Allocator& __a = _Allocator()) : _Base(__n, __a), _Safe_vector(__n) { } vector(size_type __n, const _Tp& __value, const _Allocator& __a = _Allocator()) : _Base(__n, __value, __a) { } #else explicit vector(size_type __n, const _Tp& __value = _Tp(), const _Allocator& __a = _Allocator()) : _Base(__n, __value, __a) { } #endif #if __cplusplus >= 201103L template> #else template #endif vector(_InputIterator __first, _InputIterator __last, const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __a) { } #if __cplusplus < 201103L vector(const vector& __x) : _Base(__x) { } ~vector() _GLIBCXX_NOEXCEPT { } #else vector(const vector&) = default; vector(vector&&) = default; vector(const vector& __x, const allocator_type& __a) : _Base(__x, __a) { } vector(vector&& __x, const allocator_type& __a) : _Safe(std::move(__x._M_safe()), __a), _Base(std::move(__x._M_base()), __a), _Safe_vector(std::move(__x)) { } vector(initializer_list __l, const allocator_type& __a = allocator_type()) : _Base(__l, __a) { } ~vector() = default; #endif /// Construction from a normal-mode vector vector(const _Base& __x) : _Base(__x) { } #if __cplusplus < 201103L vector& operator=(const vector& __x) { this->_M_safe() = __x; _M_base() = __x; this->_M_update_guaranteed_capacity(); return *this; } #else vector& operator=(const vector&) = default; vector& operator=(vector&&) = default; vector& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); return *this; } #endif #if __cplusplus >= 201103L template> #else template #endif void assign(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::assign(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::assign(__first, __last); this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); } void assign(size_type __n, const _Tp& __u) { _Base::assign(__n, __u); this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); } #if __cplusplus >= 201103L void assign(initializer_list __l) { _Base::assign(__l); this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); } #endif using _Base::get_allocator; // iterators: iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // 23.2.4.2 capacity: using _Base::size; using _Base::max_size; #if __cplusplus >= 201103L void resize(size_type __sz) { bool __realloc = this->_M_requires_reallocation(__sz); if (__sz < this->size()) this->_M_invalidate_after_nth(__sz); _Base::resize(__sz); if (__realloc) this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); } void resize(size_type __sz, const _Tp& __c) { bool __realloc = this->_M_requires_reallocation(__sz); if (__sz < this->size()) this->_M_invalidate_after_nth(__sz); _Base::resize(__sz, __c); if (__realloc) this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); } #else void resize(size_type __sz, _Tp __c = _Tp()) { bool __realloc = this->_M_requires_reallocation(__sz); if (__sz < this->size()) this->_M_invalidate_after_nth(__sz); _Base::resize(__sz, __c); if (__realloc) this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); } #endif #if __cplusplus >= 201103L void shrink_to_fit() { if (_Base::_M_shrink_to_fit()) { this->_M_guaranteed_capacity = _Base::capacity(); this->_M_invalidate_all(); } } #endif size_type capacity() const _GLIBCXX_NOEXCEPT { #ifdef _GLIBCXX_DEBUG_PEDANTIC return this->_M_guaranteed_capacity; #else return _Base::capacity(); #endif } using _Base::empty; void reserve(size_type __n) { bool __realloc = this->_M_requires_reallocation(__n); _Base::reserve(__n); if (__n > this->_M_guaranteed_capacity) this->_M_guaranteed_capacity = __n; if (__realloc) this->_M_invalidate_all(); } // element access: reference operator[](size_type __n) _GLIBCXX_NOEXCEPT { __glibcxx_check_subscript(__n); return _M_base()[__n]; } const_reference operator[](size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_check_subscript(__n); return _M_base()[__n]; } using _Base::at; reference front() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::front(); } const_reference front() const _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::front(); } reference back() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::back(); } const_reference back() const _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::back(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 464. Suggestion for new member functions in standard containers. using _Base::data; // 23.2.4.3 modifiers: void push_back(const _Tp& __x) { bool __realloc = this->_M_requires_reallocation(this->size() + 1); _Base::push_back(__x); if (__realloc) this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); } #if __cplusplus >= 201103L template typename __gnu_cxx::__enable_if::__value, void>::__type push_back(_Tp&& __x) { emplace_back(std::move(__x)); } template #if __cplusplus > 201402L reference #else void #endif emplace_back(_Args&&... __args) { bool __realloc = this->_M_requires_reallocation(this->size() + 1); _Base::emplace_back(std::forward<_Args>(__args)...); if (__realloc) this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); #if __cplusplus > 201402L return back(); #endif } #endif void pop_back() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); this->_M_invalidate_if(_Equal(--_Base::end())); _Base::pop_back(); } #if __cplusplus >= 201103L template iterator emplace(const_iterator __position, _Args&&... __args) { __glibcxx_check_insert(__position); bool __realloc = this->_M_requires_reallocation(this->size() + 1); difference_type __offset = __position.base() - _Base::begin(); _Base_iterator __res = _Base::emplace(__position.base(), std::forward<_Args>(__args)...); if (__realloc) this->_M_invalidate_all(); else this->_M_invalidate_after_nth(__offset); this->_M_update_guaranteed_capacity(); return iterator(__res, this); } #endif iterator #if __cplusplus >= 201103L insert(const_iterator __position, const _Tp& __x) #else insert(iterator __position, const _Tp& __x) #endif { __glibcxx_check_insert(__position); bool __realloc = this->_M_requires_reallocation(this->size() + 1); difference_type __offset = __position.base() - _Base::begin(); _Base_iterator __res = _Base::insert(__position.base(), __x); if (__realloc) this->_M_invalidate_all(); else this->_M_invalidate_after_nth(__offset); this->_M_update_guaranteed_capacity(); return iterator(__res, this); } #if __cplusplus >= 201103L template typename __gnu_cxx::__enable_if::__value, iterator>::__type insert(const_iterator __position, _Tp&& __x) { return emplace(__position, std::move(__x)); } iterator insert(const_iterator __position, initializer_list __l) { return this->insert(__position, __l.begin(), __l.end()); } #endif #if __cplusplus >= 201103L iterator insert(const_iterator __position, size_type __n, const _Tp& __x) { __glibcxx_check_insert(__position); bool __realloc = this->_M_requires_reallocation(this->size() + __n); difference_type __offset = __position.base() - _Base::cbegin(); _Base_iterator __res = _Base::insert(__position.base(), __n, __x); if (__realloc) this->_M_invalidate_all(); else this->_M_invalidate_after_nth(__offset); this->_M_update_guaranteed_capacity(); return iterator(__res, this); } #else void insert(iterator __position, size_type __n, const _Tp& __x) { __glibcxx_check_insert(__position); bool __realloc = this->_M_requires_reallocation(this->size() + __n); difference_type __offset = __position.base() - _Base::begin(); _Base::insert(__position.base(), __n, __x); if (__realloc) this->_M_invalidate_all(); else this->_M_invalidate_after_nth(__offset); this->_M_update_guaranteed_capacity(); } #endif #if __cplusplus >= 201103L template> iterator insert(const_iterator __position, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range(__position, __first, __last, __dist); /* Hard to guess if invalidation will occur, because __last - __first can't be calculated in all cases, so we just punt here by checking if it did occur. */ _Base_iterator __old_begin = _M_base().begin(); difference_type __offset = __position.base() - _Base::cbegin(); _Base_iterator __res; if (__dist.second >= __gnu_debug::__dp_sign) __res = _Base::insert(__position.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else __res = _Base::insert(__position.base(), __first, __last); if (_M_base().begin() != __old_begin) this->_M_invalidate_all(); else this->_M_invalidate_after_nth(__offset); this->_M_update_guaranteed_capacity(); return iterator(__res, this); } #else template void insert(iterator __position, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range(__position, __first, __last, __dist); /* Hard to guess if invalidation will occur, because __last - __first can't be calculated in all cases, so we just punt here by checking if it did occur. */ _Base_iterator __old_begin = _M_base().begin(); difference_type __offset = __position.base() - _Base::begin(); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__position.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__position.base(), __first, __last); if (_M_base().begin() != __old_begin) this->_M_invalidate_all(); else this->_M_invalidate_after_nth(__offset); this->_M_update_guaranteed_capacity(); } #endif iterator #if __cplusplus >= 201103L erase(const_iterator __position) #else erase(iterator __position) #endif { __glibcxx_check_erase(__position); difference_type __offset = __position.base() - _Base::begin(); _Base_iterator __res = _Base::erase(__position.base()); this->_M_invalidate_after_nth(__offset); return iterator(__res, this); } iterator #if __cplusplus >= 201103L erase(const_iterator __first, const_iterator __last) #else erase(iterator __first, iterator __last) #endif { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); if (__first.base() != __last.base()) { difference_type __offset = __first.base() - _Base::begin(); _Base_iterator __res = _Base::erase(__first.base(), __last.base()); this->_M_invalidate_after_nth(__offset); return iterator(__res, this); } else #if __cplusplus >= 201103L return begin() + (__first.base() - cbegin().base()); #else return __first; #endif } void swap(vector& __x) _GLIBCXX_NOEXCEPT_IF( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); std::swap(this->_M_guaranteed_capacity, __x._M_guaranteed_capacity); } void clear() _GLIBCXX_NOEXCEPT { _Base::clear(); this->_M_invalidate_all(); } _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } private: void _M_invalidate_after_nth(difference_type __n) _GLIBCXX_NOEXCEPT { typedef __gnu_debug::_After_nth_from<_Base_const_iterator> _After_nth; this->_M_invalidate_if(_After_nth(__n, _Base::begin())); } }; template inline bool operator==(const vector<_Tp, _Alloc>& __lhs, const vector<_Tp, _Alloc>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator!=(const vector<_Tp, _Alloc>& __lhs, const vector<_Tp, _Alloc>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator<(const vector<_Tp, _Alloc>& __lhs, const vector<_Tp, _Alloc>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<=(const vector<_Tp, _Alloc>& __lhs, const vector<_Tp, _Alloc>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator>=(const vector<_Tp, _Alloc>& __lhs, const vector<_Tp, _Alloc>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>(const vector<_Tp, _Alloc>& __lhs, const vector<_Tp, _Alloc>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template inline void swap(vector<_Tp, _Alloc>& __lhs, vector<_Tp, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT_IF(noexcept(__lhs.swap(__rhs))) { __lhs.swap(__rhs); } #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> vector(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> vector<_ValT, _Allocator>; #endif } // namespace __debug #if __cplusplus >= 201103L _GLIBCXX_BEGIN_NAMESPACE_VERSION // DR 1182. /// std::hash specialization for vector. template struct hash<__debug::vector> : public __hash_base> { size_t operator()(const __debug::vector& __b) const noexcept { return std::hash<_GLIBCXX_STD_C::vector>()(__b); } }; _GLIBCXX_END_NAMESPACE_VERSION #endif } // namespace std namespace __gnu_debug { template struct _Is_contiguous_sequence > : std::__true_type { }; template struct _Is_contiguous_sequence > : std::__false_type { }; } #endif PK!_"0DD8/decimal/decimalnu[// -*- C++ -*- // Copyright (C) 2009-2018 Free Software Foundation, Inc. // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file decimal/decimal * This is a Standard C++ Library header. */ // ISO/IEC TR 24733 // Written by Janis Johnson #ifndef _GLIBCXX_DECIMAL #define _GLIBCXX_DECIMAL 1 #pragma GCC system_header #include #ifndef _GLIBCXX_USE_DECIMAL_FLOAT #error This file requires compiler and library support for ISO/IEC TR 24733 \ that is currently not available. #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup decimal Decimal Floating-Point Arithmetic * @ingroup numerics * * Classes and functions for decimal floating-point arithmetic. * @{ */ /** @namespace std::decimal * @brief ISO/IEC TR 24733 Decimal floating-point arithmetic. */ namespace decimal { class decimal32; class decimal64; class decimal128; // 3.2.5 Initialization from coefficient and exponent. static decimal32 make_decimal32(long long __coeff, int __exp); static decimal32 make_decimal32(unsigned long long __coeff, int __exp); static decimal64 make_decimal64(long long __coeff, int __exp); static decimal64 make_decimal64(unsigned long long __coeff, int __exp); static decimal128 make_decimal128(long long __coeff, int __exp); static decimal128 make_decimal128(unsigned long long __coeff, int __exp); /// Non-conforming extension: Conversion to integral type. long long decimal32_to_long_long(decimal32 __d); long long decimal64_to_long_long(decimal64 __d); long long decimal128_to_long_long(decimal128 __d); long long decimal_to_long_long(decimal32 __d); long long decimal_to_long_long(decimal64 __d); long long decimal_to_long_long(decimal128 __d); // 3.2.6 Conversion to generic floating-point type. float decimal32_to_float(decimal32 __d); float decimal64_to_float(decimal64 __d); float decimal128_to_float(decimal128 __d); float decimal_to_float(decimal32 __d); float decimal_to_float(decimal64 __d); float decimal_to_float(decimal128 __d); double decimal32_to_double(decimal32 __d); double decimal64_to_double(decimal64 __d); double decimal128_to_double(decimal128 __d); double decimal_to_double(decimal32 __d); double decimal_to_double(decimal64 __d); double decimal_to_double(decimal128 __d); long double decimal32_to_long_double(decimal32 __d); long double decimal64_to_long_double(decimal64 __d); long double decimal128_to_long_double(decimal128 __d); long double decimal_to_long_double(decimal32 __d); long double decimal_to_long_double(decimal64 __d); long double decimal_to_long_double(decimal128 __d); // 3.2.7 Unary arithmetic operators. decimal32 operator+(decimal32 __rhs); decimal64 operator+(decimal64 __rhs); decimal128 operator+(decimal128 __rhs); decimal32 operator-(decimal32 __rhs); decimal64 operator-(decimal64 __rhs); decimal128 operator-(decimal128 __rhs); // 3.2.8 Binary arithmetic operators. #define _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(_Op, _T1, _T2, _T3) \ _T1 operator _Op(_T2 __lhs, _T3 __rhs); #define _DECLARE_DECIMAL_BINARY_OP_WITH_INT(_Op, _Tp) \ _Tp operator _Op(_Tp __lhs, int __rhs); \ _Tp operator _Op(_Tp __lhs, unsigned int __rhs); \ _Tp operator _Op(_Tp __lhs, long __rhs); \ _Tp operator _Op(_Tp __lhs, unsigned long __rhs); \ _Tp operator _Op(_Tp __lhs, long long __rhs); \ _Tp operator _Op(_Tp __lhs, unsigned long long __rhs); \ _Tp operator _Op(int __lhs, _Tp __rhs); \ _Tp operator _Op(unsigned int __lhs, _Tp __rhs); \ _Tp operator _Op(long __lhs, _Tp __rhs); \ _Tp operator _Op(unsigned long __lhs, _Tp __rhs); \ _Tp operator _Op(long long __lhs, _Tp __rhs); \ _Tp operator _Op(unsigned long long __lhs, _Tp __rhs); _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal32, decimal32, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_INT(+, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal64, decimal32, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal64, decimal64, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal64, decimal64, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_INT(+, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal128, decimal32, decimal128) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal128, decimal64, decimal128) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal128, decimal128, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal128, decimal128, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal128, decimal128, decimal128) _DECLARE_DECIMAL_BINARY_OP_WITH_INT(+, decimal128) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal32, decimal32, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_INT(-, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal64, decimal32, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal64, decimal64, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal64, decimal64, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_INT(-, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal128, decimal32, decimal128) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal128, decimal64, decimal128) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal128, decimal128, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal128, decimal128, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal128, decimal128, decimal128) _DECLARE_DECIMAL_BINARY_OP_WITH_INT(-, decimal128) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal32, decimal32, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_INT(*, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal64, decimal32, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal64, decimal64, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal64, decimal64, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_INT(*, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal128, decimal32, decimal128) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal128, decimal64, decimal128) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal128, decimal128, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal128, decimal128, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal128, decimal128, decimal128) _DECLARE_DECIMAL_BINARY_OP_WITH_INT(*, decimal128) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal32, decimal32, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_INT(/, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal64, decimal32, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal64, decimal64, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal64, decimal64, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_INT(/, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal128, decimal32, decimal128) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal128, decimal64, decimal128) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal128, decimal128, decimal32) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal128, decimal128, decimal64) _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal128, decimal128, decimal128) _DECLARE_DECIMAL_BINARY_OP_WITH_INT(/, decimal128) #undef _DECLARE_DECIMAL_BINARY_OP_WITH_DEC #undef _DECLARE_DECIMAL_BINARY_OP_WITH_INT // 3.2.9 Comparison operators. #define _DECLARE_DECIMAL_COMPARISON(_Op, _Tp) \ bool operator _Op(_Tp __lhs, decimal32 __rhs); \ bool operator _Op(_Tp __lhs, decimal64 __rhs); \ bool operator _Op(_Tp __lhs, decimal128 __rhs); \ bool operator _Op(_Tp __lhs, int __rhs); \ bool operator _Op(_Tp __lhs, unsigned int __rhs); \ bool operator _Op(_Tp __lhs, long __rhs); \ bool operator _Op(_Tp __lhs, unsigned long __rhs); \ bool operator _Op(_Tp __lhs, long long __rhs); \ bool operator _Op(_Tp __lhs, unsigned long long __rhs); \ bool operator _Op(int __lhs, _Tp __rhs); \ bool operator _Op(unsigned int __lhs, _Tp __rhs); \ bool operator _Op(long __lhs, _Tp __rhs); \ bool operator _Op(unsigned long __lhs, _Tp __rhs); \ bool operator _Op(long long __lhs, _Tp __rhs); \ bool operator _Op(unsigned long long __lhs, _Tp __rhs); _DECLARE_DECIMAL_COMPARISON(==, decimal32) _DECLARE_DECIMAL_COMPARISON(==, decimal64) _DECLARE_DECIMAL_COMPARISON(==, decimal128) _DECLARE_DECIMAL_COMPARISON(!=, decimal32) _DECLARE_DECIMAL_COMPARISON(!=, decimal64) _DECLARE_DECIMAL_COMPARISON(!=, decimal128) _DECLARE_DECIMAL_COMPARISON(<, decimal32) _DECLARE_DECIMAL_COMPARISON(<, decimal64) _DECLARE_DECIMAL_COMPARISON(<, decimal128) _DECLARE_DECIMAL_COMPARISON(>=, decimal32) _DECLARE_DECIMAL_COMPARISON(>=, decimal64) _DECLARE_DECIMAL_COMPARISON(>=, decimal128) _DECLARE_DECIMAL_COMPARISON(>, decimal32) _DECLARE_DECIMAL_COMPARISON(>, decimal64) _DECLARE_DECIMAL_COMPARISON(>, decimal128) _DECLARE_DECIMAL_COMPARISON(>=, decimal32) _DECLARE_DECIMAL_COMPARISON(>=, decimal64) _DECLARE_DECIMAL_COMPARISON(>=, decimal128) #undef _DECLARE_DECIMAL_COMPARISON /// 3.2.2 Class decimal32. class decimal32 { public: typedef float __decfloat32 __attribute__((mode(SD))); // 3.2.2.2 Construct/copy/destroy. decimal32() : __val(0.e-101DF) {} // 3.2.2.3 Conversion from floating-point type. explicit decimal32(decimal64 __d64); explicit decimal32(decimal128 __d128); explicit decimal32(float __r) : __val(__r) {} explicit decimal32(double __r) : __val(__r) {} explicit decimal32(long double __r) : __val(__r) {} // 3.2.2.4 Conversion from integral type. decimal32(int __z) : __val(__z) {} decimal32(unsigned int __z) : __val(__z) {} decimal32(long __z) : __val(__z) {} decimal32(unsigned long __z) : __val(__z) {} decimal32(long long __z) : __val(__z) {} decimal32(unsigned long long __z) : __val(__z) {} /// Conforming extension: Conversion from scalar decimal type. decimal32(__decfloat32 __z) : __val(__z) {} #if __cplusplus >= 201103L // 3.2.2.5 Conversion to integral type. // Note: explicit per n3407. explicit operator long long() const { return (long long)__val; } #endif // 3.2.2.6 Increment and decrement operators. decimal32& operator++() { __val += 1; return *this; } decimal32 operator++(int) { decimal32 __tmp = *this; __val += 1; return __tmp; } decimal32& operator--() { __val -= 1; return *this; } decimal32 operator--(int) { decimal32 __tmp = *this; __val -= 1; return __tmp; } // 3.2.2.7 Compound assignment. #define _DECLARE_DECIMAL32_COMPOUND_ASSIGNMENT(_Op) \ decimal32& operator _Op(decimal32 __rhs); \ decimal32& operator _Op(decimal64 __rhs); \ decimal32& operator _Op(decimal128 __rhs); \ decimal32& operator _Op(int __rhs); \ decimal32& operator _Op(unsigned int __rhs); \ decimal32& operator _Op(long __rhs); \ decimal32& operator _Op(unsigned long __rhs); \ decimal32& operator _Op(long long __rhs); \ decimal32& operator _Op(unsigned long long __rhs); _DECLARE_DECIMAL32_COMPOUND_ASSIGNMENT(+=) _DECLARE_DECIMAL32_COMPOUND_ASSIGNMENT(-=) _DECLARE_DECIMAL32_COMPOUND_ASSIGNMENT(*=) _DECLARE_DECIMAL32_COMPOUND_ASSIGNMENT(/=) #undef _DECLARE_DECIMAL32_COMPOUND_ASSIGNMENT private: __decfloat32 __val; public: __decfloat32 __getval(void) { return __val; } void __setval(__decfloat32 __x) { __val = __x; } }; /// 3.2.3 Class decimal64. class decimal64 { public: typedef float __decfloat64 __attribute__((mode(DD))); // 3.2.3.2 Construct/copy/destroy. decimal64() : __val(0.e-398dd) {} // 3.2.3.3 Conversion from floating-point type. decimal64(decimal32 d32); explicit decimal64(decimal128 d128); explicit decimal64(float __r) : __val(__r) {} explicit decimal64(double __r) : __val(__r) {} explicit decimal64(long double __r) : __val(__r) {} // 3.2.3.4 Conversion from integral type. decimal64(int __z) : __val(__z) {} decimal64(unsigned int __z) : __val(__z) {} decimal64(long __z) : __val(__z) {} decimal64(unsigned long __z) : __val(__z) {} decimal64(long long __z) : __val(__z) {} decimal64(unsigned long long __z) : __val(__z) {} /// Conforming extension: Conversion from scalar decimal type. decimal64(__decfloat64 __z) : __val(__z) {} #if __cplusplus >= 201103L // 3.2.3.5 Conversion to integral type. // Note: explicit per n3407. explicit operator long long() const { return (long long)__val; } #endif // 3.2.3.6 Increment and decrement operators. decimal64& operator++() { __val += 1; return *this; } decimal64 operator++(int) { decimal64 __tmp = *this; __val += 1; return __tmp; } decimal64& operator--() { __val -= 1; return *this; } decimal64 operator--(int) { decimal64 __tmp = *this; __val -= 1; return __tmp; } // 3.2.3.7 Compound assignment. #define _DECLARE_DECIMAL64_COMPOUND_ASSIGNMENT(_Op) \ decimal64& operator _Op(decimal32 __rhs); \ decimal64& operator _Op(decimal64 __rhs); \ decimal64& operator _Op(decimal128 __rhs); \ decimal64& operator _Op(int __rhs); \ decimal64& operator _Op(unsigned int __rhs); \ decimal64& operator _Op(long __rhs); \ decimal64& operator _Op(unsigned long __rhs); \ decimal64& operator _Op(long long __rhs); \ decimal64& operator _Op(unsigned long long __rhs); _DECLARE_DECIMAL64_COMPOUND_ASSIGNMENT(+=) _DECLARE_DECIMAL64_COMPOUND_ASSIGNMENT(-=) _DECLARE_DECIMAL64_COMPOUND_ASSIGNMENT(*=) _DECLARE_DECIMAL64_COMPOUND_ASSIGNMENT(/=) #undef _DECLARE_DECIMAL64_COMPOUND_ASSIGNMENT private: __decfloat64 __val; public: __decfloat64 __getval(void) { return __val; } void __setval(__decfloat64 __x) { __val = __x; } }; /// 3.2.4 Class decimal128. class decimal128 { public: typedef float __decfloat128 __attribute__((mode(TD))); // 3.2.4.2 Construct/copy/destroy. decimal128() : __val(0.e-6176DL) {} // 3.2.4.3 Conversion from floating-point type. decimal128(decimal32 d32); decimal128(decimal64 d64); explicit decimal128(float __r) : __val(__r) {} explicit decimal128(double __r) : __val(__r) {} explicit decimal128(long double __r) : __val(__r) {} // 3.2.4.4 Conversion from integral type. decimal128(int __z) : __val(__z) {} decimal128(unsigned int __z) : __val(__z) {} decimal128(long __z) : __val(__z) {} decimal128(unsigned long __z) : __val(__z) {} decimal128(long long __z) : __val(__z) {} decimal128(unsigned long long __z) : __val(__z) {} /// Conforming extension: Conversion from scalar decimal type. decimal128(__decfloat128 __z) : __val(__z) {} #if __cplusplus >= 201103L // 3.2.4.5 Conversion to integral type. // Note: explicit per n3407. explicit operator long long() const { return (long long)__val; } #endif // 3.2.4.6 Increment and decrement operators. decimal128& operator++() { __val += 1; return *this; } decimal128 operator++(int) { decimal128 __tmp = *this; __val += 1; return __tmp; } decimal128& operator--() { __val -= 1; return *this; } decimal128 operator--(int) { decimal128 __tmp = *this; __val -= 1; return __tmp; } // 3.2.4.7 Compound assignment. #define _DECLARE_DECIMAL128_COMPOUND_ASSIGNMENT(_Op) \ decimal128& operator _Op(decimal32 __rhs); \ decimal128& operator _Op(decimal64 __rhs); \ decimal128& operator _Op(decimal128 __rhs); \ decimal128& operator _Op(int __rhs); \ decimal128& operator _Op(unsigned int __rhs); \ decimal128& operator _Op(long __rhs); \ decimal128& operator _Op(unsigned long __rhs); \ decimal128& operator _Op(long long __rhs); \ decimal128& operator _Op(unsigned long long __rhs); _DECLARE_DECIMAL128_COMPOUND_ASSIGNMENT(+=) _DECLARE_DECIMAL128_COMPOUND_ASSIGNMENT(-=) _DECLARE_DECIMAL128_COMPOUND_ASSIGNMENT(*=) _DECLARE_DECIMAL128_COMPOUND_ASSIGNMENT(/=) #undef _DECLARE_DECIMAL128_COMPOUND_ASSIGNMENT private: __decfloat128 __val; public: __decfloat128 __getval(void) { return __val; } void __setval(__decfloat128 __x) { __val = __x; } }; #define _GLIBCXX_USE_DECIMAL_ 1 } // namespace decimal // @} group decimal _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #include #endif /* _GLIBCXX_DECIMAL */ PK!\ogBgB8/decimal/decimal.hnu[// decimal classes -*- C++ -*- // Copyright (C) 2009-2018 Free Software Foundation, Inc. // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file decimal/decimal.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{decimal} */ // ISO/IEC TR 24733 // Written by Janis Johnson #ifndef _GLIBCXX_DECIMAL_IMPL #define _GLIBCXX_DECIMAL_IMPL 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace decimal { // ISO/IEC TR 24733 3.2.[234].1 Construct/copy/destroy. inline decimal32::decimal32(decimal64 __r) : __val(__r.__getval()) {} inline decimal32::decimal32(decimal128 __r) : __val(__r.__getval()) {} inline decimal64::decimal64(decimal32 __r) : __val(__r.__getval()) {} inline decimal64::decimal64(decimal128 __r) : __val(__r.__getval()) {} inline decimal128::decimal128(decimal32 __r) : __val(__r.__getval()) {} inline decimal128::decimal128(decimal64 __r) : __val(__r.__getval()) {} // ISO/IEC TR 24733 3.2.[234].6 Compound assignment. #define _DEFINE_DECIMAL_COMPOUND_ASSIGNMENT_DEC(_Op1, _Op2, _T1, _T2) \ inline _T1& _T1::operator _Op1(_T2 __rhs) \ { \ __setval(__getval() _Op2 __rhs.__getval()); \ return *this; \ } #define _DEFINE_DECIMAL_COMPOUND_ASSIGNMENT_INT(_Op1, _Op2, _T1, _T2) \ inline _T1& _T1::operator _Op1(_T2 __rhs) \ { \ __setval(__getval() _Op2 __rhs); \ return *this; \ } #define _DEFINE_DECIMAL_COMPOUND_ASSIGNMENTS(_Op1, _Op2, _T1) \ _DEFINE_DECIMAL_COMPOUND_ASSIGNMENT_DEC(_Op1, _Op2, _T1, decimal32) \ _DEFINE_DECIMAL_COMPOUND_ASSIGNMENT_DEC(_Op1, _Op2, _T1, decimal64) \ _DEFINE_DECIMAL_COMPOUND_ASSIGNMENT_DEC(_Op1, _Op2, _T1, decimal128) \ _DEFINE_DECIMAL_COMPOUND_ASSIGNMENT_INT(_Op1, _Op2, _T1, int) \ _DEFINE_DECIMAL_COMPOUND_ASSIGNMENT_INT(_Op1, _Op2, _T1, unsigned int) \ _DEFINE_DECIMAL_COMPOUND_ASSIGNMENT_INT(_Op1, _Op2, _T1, long) \ _DEFINE_DECIMAL_COMPOUND_ASSIGNMENT_INT(_Op1, _Op2, _T1, unsigned long)\ _DEFINE_DECIMAL_COMPOUND_ASSIGNMENT_INT(_Op1, _Op2, _T1, long long) \ _DEFINE_DECIMAL_COMPOUND_ASSIGNMENT_INT(_Op1, _Op2, _T1, unsigned long long) _DEFINE_DECIMAL_COMPOUND_ASSIGNMENTS(+=, +, decimal32) _DEFINE_DECIMAL_COMPOUND_ASSIGNMENTS(-=, -, decimal32) _DEFINE_DECIMAL_COMPOUND_ASSIGNMENTS(*=, *, decimal32) _DEFINE_DECIMAL_COMPOUND_ASSIGNMENTS(/=, /, decimal32) _DEFINE_DECIMAL_COMPOUND_ASSIGNMENTS(+=, +, decimal64) _DEFINE_DECIMAL_COMPOUND_ASSIGNMENTS(-=, -, decimal64) _DEFINE_DECIMAL_COMPOUND_ASSIGNMENTS(*=, *, decimal64) _DEFINE_DECIMAL_COMPOUND_ASSIGNMENTS(/=, /, decimal64) _DEFINE_DECIMAL_COMPOUND_ASSIGNMENTS(+=, +, decimal128) _DEFINE_DECIMAL_COMPOUND_ASSIGNMENTS(-=, -, decimal128) _DEFINE_DECIMAL_COMPOUND_ASSIGNMENTS(*=, *, decimal128) _DEFINE_DECIMAL_COMPOUND_ASSIGNMENTS(/=, /, decimal128) #undef _DEFINE_DECIMAL_COMPOUND_ASSIGNMENT_DEC #undef _DEFINE_DECIMAL_COMPOUND_ASSIGNMENT_INT #undef _DEFINE_DECIMAL_COMPOUND_ASSIGNMENTS // Extension: Conversion to integral type. inline long long decimal32_to_long_long(decimal32 __d) { return (long long)__d.__getval(); } inline long long decimal64_to_long_long(decimal64 __d) { return (long long)__d.__getval(); } inline long long decimal128_to_long_long(decimal128 __d) { return (long long)__d.__getval(); } inline long long decimal_to_long_long(decimal32 __d) { return (long long)__d.__getval(); } inline long long decimal_to_long_long(decimal64 __d) { return (long long)__d.__getval(); } inline long long decimal_to_long_long(decimal128 __d) { return (long long)__d.__getval(); } // ISO/IEC TR 24733 3.2.5 Initialization from coefficient and exponent. static decimal32 make_decimal32(long long __coeff, int __exponent) { decimal32 __decexp = 1, __multiplier; if (__exponent < 0) { __multiplier = 1.E-1DF; __exponent = -__exponent; } else __multiplier = 1.E1DF; for (int __i = 0; __i < __exponent; ++__i) __decexp *= __multiplier; return __coeff * __decexp; } static decimal32 make_decimal32(unsigned long long __coeff, int __exponent) { decimal32 __decexp = 1, __multiplier; if (__exponent < 0) { __multiplier = 1.E-1DF; __exponent = -__exponent; } else __multiplier = 1.E1DF; for (int __i = 0; __i < __exponent; ++__i) __decexp *= __multiplier; return __coeff * __decexp; } static decimal64 make_decimal64(long long __coeff, int __exponent) { decimal64 __decexp = 1, __multiplier; if (__exponent < 0) { __multiplier = 1.E-1DD; __exponent = -__exponent; } else __multiplier = 1.E1DD; for (int __i = 0; __i < __exponent; ++__i) __decexp *= __multiplier; return __coeff * __decexp; } static decimal64 make_decimal64(unsigned long long __coeff, int __exponent) { decimal64 __decexp = 1, __multiplier; if (__exponent < 0) { __multiplier = 1.E-1DD; __exponent = -__exponent; } else __multiplier = 1.E1DD; for (int __i = 0; __i < __exponent; ++__i) __decexp *= __multiplier; return __coeff * __decexp; } static decimal128 make_decimal128(long long __coeff, int __exponent) { decimal128 __decexp = 1, __multiplier; if (__exponent < 0) { __multiplier = 1.E-1DL; __exponent = -__exponent; } else __multiplier = 1.E1DL; for (int __i = 0; __i < __exponent; ++__i) __decexp *= __multiplier; return __coeff * __decexp; } static decimal128 make_decimal128(unsigned long long __coeff, int __exponent) { decimal128 __decexp = 1, __multiplier; if (__exponent < 0) { __multiplier = 1.E-1DL; __exponent = -__exponent; } else __multiplier = 1.E1DL; for (int __i = 0; __i < __exponent; ++__i) __decexp *= __multiplier; return __coeff * __decexp; } // ISO/IEC TR 24733 3.2.6 Conversion to generic floating-point type. inline float decimal32_to_float(decimal32 __d) { return (float)__d.__getval(); } inline float decimal64_to_float(decimal64 __d) { return (float)__d.__getval(); } inline float decimal128_to_float(decimal128 __d) { return (float)__d.__getval(); } inline float decimal_to_float(decimal32 __d) { return (float)__d.__getval(); } inline float decimal_to_float(decimal64 __d) { return (float)__d.__getval(); } inline float decimal_to_float(decimal128 __d) { return (float)__d.__getval(); } inline double decimal32_to_double(decimal32 __d) { return (double)__d.__getval(); } inline double decimal64_to_double(decimal64 __d) { return (double)__d.__getval(); } inline double decimal128_to_double(decimal128 __d) { return (double)__d.__getval(); } inline double decimal_to_double(decimal32 __d) { return (double)__d.__getval(); } inline double decimal_to_double(decimal64 __d) { return (double)__d.__getval(); } inline double decimal_to_double(decimal128 __d) { return (double)__d.__getval(); } inline long double decimal32_to_long_double(decimal32 __d) { return (long double)__d.__getval(); } inline long double decimal64_to_long_double(decimal64 __d) { return (long double)__d.__getval(); } inline long double decimal128_to_long_double(decimal128 __d) { return (long double)__d.__getval(); } inline long double decimal_to_long_double(decimal32 __d) { return (long double)__d.__getval(); } inline long double decimal_to_long_double(decimal64 __d) { return (long double)__d.__getval(); } inline long double decimal_to_long_double(decimal128 __d) { return (long double)__d.__getval(); } // ISO/IEC TR 24733 3.2.7 Unary arithmetic operators. #define _DEFINE_DECIMAL_UNARY_OP(_Op, _Tp) \ inline _Tp operator _Op(_Tp __rhs) \ { \ _Tp __tmp; \ __tmp.__setval(_Op __rhs.__getval()); \ return __tmp; \ } _DEFINE_DECIMAL_UNARY_OP(+, decimal32) _DEFINE_DECIMAL_UNARY_OP(+, decimal64) _DEFINE_DECIMAL_UNARY_OP(+, decimal128) _DEFINE_DECIMAL_UNARY_OP(-, decimal32) _DEFINE_DECIMAL_UNARY_OP(-, decimal64) _DEFINE_DECIMAL_UNARY_OP(-, decimal128) #undef _DEFINE_DECIMAL_UNARY_OP // ISO/IEC TR 24733 3.2.8 Binary arithmetic operators. #define _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(_Op, _T1, _T2, _T3) \ inline _T1 operator _Op(_T2 __lhs, _T3 __rhs) \ { \ _T1 __retval; \ __retval.__setval(__lhs.__getval() _Op __rhs.__getval()); \ return __retval; \ } #define _DEFINE_DECIMAL_BINARY_OP_BOTH(_Op, _T1, _T2, _T3) \ inline _T1 operator _Op(_T2 __lhs, _T3 __rhs) \ { \ _T1 __retval; \ __retval.__setval(__lhs.__getval() _Op __rhs.__getval()); \ return __retval; \ } #define _DEFINE_DECIMAL_BINARY_OP_LHS(_Op, _T1, _T2) \ inline _T1 operator _Op(_T1 __lhs, _T2 __rhs) \ { \ _T1 __retval; \ __retval.__setval(__lhs.__getval() _Op __rhs); \ return __retval; \ } #define _DEFINE_DECIMAL_BINARY_OP_RHS(_Op, _T1, _T2) \ inline _T1 operator _Op(_T2 __lhs, _T1 __rhs) \ { \ _T1 __retval; \ __retval.__setval(__lhs _Op __rhs.__getval()); \ return __retval; \ } #define _DEFINE_DECIMAL_BINARY_OP_WITH_INT(_Op, _T1) \ _DEFINE_DECIMAL_BINARY_OP_LHS(_Op, _T1, int); \ _DEFINE_DECIMAL_BINARY_OP_LHS(_Op, _T1, unsigned int); \ _DEFINE_DECIMAL_BINARY_OP_LHS(_Op, _T1, long); \ _DEFINE_DECIMAL_BINARY_OP_LHS(_Op, _T1, unsigned long); \ _DEFINE_DECIMAL_BINARY_OP_LHS(_Op, _T1, long long); \ _DEFINE_DECIMAL_BINARY_OP_LHS(_Op, _T1, unsigned long long); \ _DEFINE_DECIMAL_BINARY_OP_RHS(_Op, _T1, int); \ _DEFINE_DECIMAL_BINARY_OP_RHS(_Op, _T1, unsigned int); \ _DEFINE_DECIMAL_BINARY_OP_RHS(_Op, _T1, long); \ _DEFINE_DECIMAL_BINARY_OP_RHS(_Op, _T1, unsigned long); \ _DEFINE_DECIMAL_BINARY_OP_RHS(_Op, _T1, long long); \ _DEFINE_DECIMAL_BINARY_OP_RHS(_Op, _T1, unsigned long long); \ _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal32, decimal32, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_INT(+, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal64, decimal32, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal64, decimal64, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal64, decimal64, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_INT(+, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal128, decimal32, decimal128) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal128, decimal64, decimal128) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal128, decimal128, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal128, decimal128, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal128, decimal128, decimal128) _DEFINE_DECIMAL_BINARY_OP_WITH_INT(+, decimal128) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal32, decimal32, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_INT(-, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal64, decimal32, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal64, decimal64, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal64, decimal64, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_INT(-, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal128, decimal32, decimal128) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal128, decimal64, decimal128) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal128, decimal128, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal128, decimal128, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal128, decimal128, decimal128) _DEFINE_DECIMAL_BINARY_OP_WITH_INT(-, decimal128) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal32, decimal32, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_INT(*, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal64, decimal32, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal64, decimal64, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal64, decimal64, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_INT(*, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal128, decimal32, decimal128) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal128, decimal64, decimal128) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal128, decimal128, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal128, decimal128, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal128, decimal128, decimal128) _DEFINE_DECIMAL_BINARY_OP_WITH_INT(*, decimal128) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal32, decimal32, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_INT(/, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal64, decimal32, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal64, decimal64, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal64, decimal64, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_INT(/, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal128, decimal32, decimal128) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal128, decimal64, decimal128) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal128, decimal128, decimal32) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal128, decimal128, decimal64) _DEFINE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal128, decimal128, decimal128) _DEFINE_DECIMAL_BINARY_OP_WITH_INT(/, decimal128) #undef _DEFINE_DECIMAL_BINARY_OP_WITH_DEC #undef _DEFINE_DECIMAL_BINARY_OP_BOTH #undef _DEFINE_DECIMAL_BINARY_OP_LHS #undef _DEFINE_DECIMAL_BINARY_OP_RHS #undef _DEFINE_DECIMAL_BINARY_OP_WITH_INT // ISO/IEC TR 24733 3.2.9 Comparison operators. #define _DEFINE_DECIMAL_COMPARISON_BOTH(_Op, _T1, _T2) \ inline bool operator _Op(_T1 __lhs, _T2 __rhs) \ { return __lhs.__getval() _Op __rhs.__getval(); } #define _DEFINE_DECIMAL_COMPARISON_LHS(_Op, _T1, _T2) \ inline bool operator _Op(_T1 __lhs, _T2 __rhs) \ { return __lhs.__getval() _Op __rhs; } #define _DEFINE_DECIMAL_COMPARISON_RHS(_Op, _T1, _T2) \ inline bool operator _Op(_T1 __lhs, _T2 __rhs) \ { return __lhs _Op __rhs.__getval(); } #define _DEFINE_DECIMAL_COMPARISONS(_Op, _Tp) \ _DEFINE_DECIMAL_COMPARISON_BOTH(_Op, _Tp, decimal32) \ _DEFINE_DECIMAL_COMPARISON_BOTH(_Op, _Tp, decimal64) \ _DEFINE_DECIMAL_COMPARISON_BOTH(_Op, _Tp, decimal128) \ _DEFINE_DECIMAL_COMPARISON_LHS(_Op, _Tp, int) \ _DEFINE_DECIMAL_COMPARISON_LHS(_Op, _Tp, unsigned int) \ _DEFINE_DECIMAL_COMPARISON_LHS(_Op, _Tp, long) \ _DEFINE_DECIMAL_COMPARISON_LHS(_Op, _Tp, unsigned long) \ _DEFINE_DECIMAL_COMPARISON_LHS(_Op, _Tp, long long) \ _DEFINE_DECIMAL_COMPARISON_LHS(_Op, _Tp, unsigned long long) \ _DEFINE_DECIMAL_COMPARISON_RHS(_Op, int, _Tp) \ _DEFINE_DECIMAL_COMPARISON_RHS(_Op, unsigned int, _Tp) \ _DEFINE_DECIMAL_COMPARISON_RHS(_Op, long, _Tp) \ _DEFINE_DECIMAL_COMPARISON_RHS(_Op, unsigned long, _Tp) \ _DEFINE_DECIMAL_COMPARISON_RHS(_Op, long long, _Tp) \ _DEFINE_DECIMAL_COMPARISON_RHS(_Op, unsigned long long, _Tp) _DEFINE_DECIMAL_COMPARISONS(==, decimal32) _DEFINE_DECIMAL_COMPARISONS(==, decimal64) _DEFINE_DECIMAL_COMPARISONS(==, decimal128) _DEFINE_DECIMAL_COMPARISONS(!=, decimal32) _DEFINE_DECIMAL_COMPARISONS(!=, decimal64) _DEFINE_DECIMAL_COMPARISONS(!=, decimal128) _DEFINE_DECIMAL_COMPARISONS(<, decimal32) _DEFINE_DECIMAL_COMPARISONS(<, decimal64) _DEFINE_DECIMAL_COMPARISONS(<, decimal128) _DEFINE_DECIMAL_COMPARISONS(<=, decimal32) _DEFINE_DECIMAL_COMPARISONS(<=, decimal64) _DEFINE_DECIMAL_COMPARISONS(<=, decimal128) _DEFINE_DECIMAL_COMPARISONS(>, decimal32) _DEFINE_DECIMAL_COMPARISONS(>, decimal64) _DEFINE_DECIMAL_COMPARISONS(>, decimal128) _DEFINE_DECIMAL_COMPARISONS(>=, decimal32) _DEFINE_DECIMAL_COMPARISONS(>=, decimal64) _DEFINE_DECIMAL_COMPARISONS(>=, decimal128) #undef _DEFINE_DECIMAL_COMPARISON_BOTH #undef _DEFINE_DECIMAL_COMPARISON_LHS #undef _DEFINE_DECIMAL_COMPARISON_RHS #undef _DEFINE_DECIMAL_COMPARISONS } // namespace decimal _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _GLIBCXX_DECIMAL_IMPL */ PK!!!8/experimental/bits/erase_if.hnu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/bits/erase_if.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. */ #ifndef _GLIBCXX_EXPERIMENTAL_ERASE_IF_H #define _GLIBCXX_EXPERIMENTAL_ERASE_IF_H 1 #pragma GCC system_header #if __cplusplus >= 201402L #include namespace std { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { namespace __detail { template void __erase_nodes_if(_Container& __cont, _Predicate __pred) { for (auto __iter = __cont.begin(), __last = __cont.end(); __iter != __last;) { if (__pred(*__iter)) __iter = __cont.erase(__iter); else ++__iter; } } } // namespace __detail } // inline namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_ERASE_IF_H PK!?#,*,*8/experimental/bits/fs_dir.hnu[// Filesystem directory utilities -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/bits/fs_dir.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{experimental/filesystem} */ #ifndef _GLIBCXX_EXPERIMENTAL_FS_DIR_H #define _GLIBCXX_EXPERIMENTAL_FS_DIR_H 1 #if __cplusplus < 201103L # include #else # include # include # include # include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { namespace filesystem { inline namespace v1 { /** * @ingroup filesystem-ts * @{ */ class file_status { public: // constructors explicit file_status(file_type __ft = file_type::none, perms __prms = perms::unknown) noexcept : _M_type(__ft), _M_perms(__prms) { } file_status(const file_status&) noexcept = default; file_status(file_status&&) noexcept = default; ~file_status() = default; file_status& operator=(const file_status&) noexcept = default; file_status& operator=(file_status&&) noexcept = default; // observers file_type type() const noexcept { return _M_type; } perms permissions() const noexcept { return _M_perms; } // modifiers void type(file_type __ft) noexcept { _M_type = __ft; } void permissions(perms __prms) noexcept { _M_perms = __prms; } private: file_type _M_type; perms _M_perms; }; _GLIBCXX_BEGIN_NAMESPACE_CXX11 class directory_entry { public: // constructors and destructor directory_entry() noexcept = default; directory_entry(const directory_entry&) = default; directory_entry(directory_entry&&) noexcept = default; explicit directory_entry(const filesystem::path& __p) : _M_path(__p) { } ~directory_entry() = default; // modifiers directory_entry& operator=(const directory_entry&) = default; directory_entry& operator=(directory_entry&&) noexcept = default; void assign(const filesystem::path& __p) { _M_path = __p; } void replace_filename(const filesystem::path& __p) { _M_path = _M_path.parent_path() / __p; } // observers const filesystem::path& path() const noexcept { return _M_path; } operator const filesystem::path&() const noexcept { return _M_path; } file_status status() const { return filesystem::status(_M_path); } file_status status(error_code& __ec) const noexcept { return filesystem::status(_M_path, __ec); } file_status symlink_status() const { return filesystem::symlink_status(_M_path); } file_status symlink_status(error_code& __ec) const noexcept { return filesystem::symlink_status(_M_path, __ec); } bool operator< (const directory_entry& __rhs) const noexcept { return _M_path < __rhs._M_path; } bool operator==(const directory_entry& __rhs) const noexcept { return _M_path == __rhs._M_path; } bool operator!=(const directory_entry& __rhs) const noexcept { return _M_path != __rhs._M_path; } bool operator<=(const directory_entry& __rhs) const noexcept { return _M_path <= __rhs._M_path; } bool operator> (const directory_entry& __rhs) const noexcept { return _M_path > __rhs._M_path; } bool operator>=(const directory_entry& __rhs) const noexcept { return _M_path >= __rhs._M_path; } private: filesystem::path _M_path; }; struct _Dir; class directory_iterator; class recursive_directory_iterator; struct __directory_iterator_proxy { const directory_entry& operator*() const& noexcept { return _M_entry; } directory_entry operator*() && noexcept { return std::move(_M_entry); } private: friend class directory_iterator; friend class recursive_directory_iterator; explicit __directory_iterator_proxy(const directory_entry& __e) : _M_entry(__e) { } directory_entry _M_entry; }; class directory_iterator { public: typedef directory_entry value_type; typedef ptrdiff_t difference_type; typedef const directory_entry* pointer; typedef const directory_entry& reference; typedef input_iterator_tag iterator_category; directory_iterator() = default; explicit directory_iterator(const path& __p) : directory_iterator(__p, directory_options::none, nullptr) { } directory_iterator(const path& __p, directory_options __options) : directory_iterator(__p, __options, nullptr) { } directory_iterator(const path& __p, error_code& __ec) noexcept : directory_iterator(__p, directory_options::none, __ec) { } directory_iterator(const path& __p, directory_options __options, error_code& __ec) noexcept : directory_iterator(__p, __options, &__ec) { } directory_iterator(const directory_iterator& __rhs) = default; directory_iterator(directory_iterator&& __rhs) noexcept = default; ~directory_iterator() = default; directory_iterator& operator=(const directory_iterator& __rhs) = default; directory_iterator& operator=(directory_iterator&& __rhs) noexcept = default; const directory_entry& operator*() const; const directory_entry* operator->() const { return &**this; } directory_iterator& operator++(); directory_iterator& increment(error_code& __ec) noexcept; __directory_iterator_proxy operator++(int) { __directory_iterator_proxy __pr{**this}; ++*this; return __pr; } private: directory_iterator(const path&, directory_options, error_code*); friend bool operator==(const directory_iterator& __lhs, const directory_iterator& __rhs); friend class recursive_directory_iterator; std::shared_ptr<_Dir> _M_dir; }; inline directory_iterator begin(directory_iterator __iter) noexcept { return __iter; } inline directory_iterator end(directory_iterator) noexcept { return directory_iterator(); } inline bool operator==(const directory_iterator& __lhs, const directory_iterator& __rhs) { return !__rhs._M_dir.owner_before(__lhs._M_dir) && !__lhs._M_dir.owner_before(__rhs._M_dir); } inline bool operator!=(const directory_iterator& __lhs, const directory_iterator& __rhs) { return !(__lhs == __rhs); } class recursive_directory_iterator { public: typedef directory_entry value_type; typedef ptrdiff_t difference_type; typedef const directory_entry* pointer; typedef const directory_entry& reference; typedef input_iterator_tag iterator_category; recursive_directory_iterator() = default; explicit recursive_directory_iterator(const path& __p) : recursive_directory_iterator(__p, directory_options::none, nullptr) { } recursive_directory_iterator(const path& __p, directory_options __options) : recursive_directory_iterator(__p, __options, nullptr) { } recursive_directory_iterator(const path& __p, directory_options __options, error_code& __ec) noexcept : recursive_directory_iterator(__p, __options, &__ec) { } recursive_directory_iterator(const path& __p, error_code& __ec) noexcept : recursive_directory_iterator(__p, directory_options::none, &__ec) { } recursive_directory_iterator( const recursive_directory_iterator&) = default; recursive_directory_iterator(recursive_directory_iterator&&) = default; ~recursive_directory_iterator(); // observers directory_options options() const { return _M_options; } int depth() const; bool recursion_pending() const { return _M_pending; } const directory_entry& operator*() const; const directory_entry* operator->() const { return &**this; } // modifiers recursive_directory_iterator& operator=(const recursive_directory_iterator& __rhs) noexcept; recursive_directory_iterator& operator=(recursive_directory_iterator&& __rhs) noexcept; recursive_directory_iterator& operator++(); recursive_directory_iterator& increment(error_code& __ec) noexcept; __directory_iterator_proxy operator++(int) { __directory_iterator_proxy __pr{**this}; ++*this; return __pr; } void pop(); void pop(error_code&); void disable_recursion_pending() { _M_pending = false; } private: recursive_directory_iterator(const path&, directory_options, error_code*); friend bool operator==(const recursive_directory_iterator& __lhs, const recursive_directory_iterator& __rhs); struct _Dir_stack; std::shared_ptr<_Dir_stack> _M_dirs; directory_options _M_options = {}; bool _M_pending = false; }; inline recursive_directory_iterator begin(recursive_directory_iterator __iter) noexcept { return __iter; } inline recursive_directory_iterator end(recursive_directory_iterator) noexcept { return recursive_directory_iterator(); } inline bool operator==(const recursive_directory_iterator& __lhs, const recursive_directory_iterator& __rhs) { return !__rhs._M_dirs.owner_before(__lhs._M_dirs) && !__lhs._M_dirs.owner_before(__rhs._M_dirs); } inline bool operator!=(const recursive_directory_iterator& __lhs, const recursive_directory_iterator& __rhs) { return !(__lhs == __rhs); } _GLIBCXX_END_NAMESPACE_CXX11 // @} group filesystem-ts } // namespace v1 } // namespace filesystem } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif // _GLIBCXX_EXPERIMENTAL_FS_DIR_H PK! ! !8/experimental/bits/fs_fwd.hnu[// Filesystem declarations -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/bits/fs_fwd.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{experimental/filesystem} */ #ifndef _GLIBCXX_EXPERIMENTAL_FS_FWD_H #define _GLIBCXX_EXPERIMENTAL_FS_FWD_H 1 #if __cplusplus < 201103L # include #else #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { namespace filesystem { inline namespace v1 { #if _GLIBCXX_USE_CXX11_ABI inline namespace __cxx11 __attribute__((__abi_tag__ ("cxx11"))) { } #endif /** * @defgroup filesystem-ts Filesystem TS * @ingroup experimental * * Utilities for performing operations on file systems and their components, * such as paths, regular files, and directories. * * @{ */ class file_status; _GLIBCXX_BEGIN_NAMESPACE_CXX11 class path; class filesystem_error; class directory_entry; class directory_iterator; class recursive_directory_iterator; _GLIBCXX_END_NAMESPACE_CXX11 struct space_info { uintmax_t capacity; uintmax_t free; uintmax_t available; }; enum class file_type : signed char { none = 0, not_found = -1, regular = 1, directory = 2, symlink = 3, block = 4, character = 5, fifo = 6, socket = 7, unknown = 8 }; /// Bitmask type enum class copy_options : unsigned short { none = 0, skip_existing = 1, overwrite_existing = 2, update_existing = 4, recursive = 8, copy_symlinks = 16, skip_symlinks = 32, directories_only = 64, create_symlinks = 128, create_hard_links = 256 }; constexpr copy_options operator&(copy_options __x, copy_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) & static_cast<__utype>(__y)); } constexpr copy_options operator|(copy_options __x, copy_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) | static_cast<__utype>(__y)); } constexpr copy_options operator^(copy_options __x, copy_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) ^ static_cast<__utype>(__y)); } constexpr copy_options operator~(copy_options __x) noexcept { using __utype = typename std::underlying_type::type; return static_cast(~static_cast<__utype>(__x)); } inline copy_options& operator&=(copy_options& __x, copy_options __y) noexcept { return __x = __x & __y; } inline copy_options& operator|=(copy_options& __x, copy_options __y) noexcept { return __x = __x | __y; } inline copy_options& operator^=(copy_options& __x, copy_options __y) noexcept { return __x = __x ^ __y; } /// Bitmask type enum class perms : unsigned { none = 0, owner_read = 0400, owner_write = 0200, owner_exec = 0100, owner_all = 0700, group_read = 040, group_write = 020, group_exec = 010, group_all = 070, others_read = 04, others_write = 02, others_exec = 01, others_all = 07, all = 0777, set_uid = 04000, set_gid = 02000, sticky_bit = 01000, mask = 07777, unknown = 0xFFFF, add_perms = 0x10000, remove_perms = 0x20000, symlink_nofollow = 0x40000 }; constexpr perms operator&(perms __x, perms __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) & static_cast<__utype>(__y)); } constexpr perms operator|(perms __x, perms __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) | static_cast<__utype>(__y)); } constexpr perms operator^(perms __x, perms __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) ^ static_cast<__utype>(__y)); } constexpr perms operator~(perms __x) noexcept { using __utype = typename std::underlying_type::type; return static_cast(~static_cast<__utype>(__x)); } inline perms& operator&=(perms& __x, perms __y) noexcept { return __x = __x & __y; } inline perms& operator|=(perms& __x, perms __y) noexcept { return __x = __x | __y; } inline perms& operator^=(perms& __x, perms __y) noexcept { return __x = __x ^ __y; } // Bitmask type enum class directory_options : unsigned char { none = 0, follow_directory_symlink = 1, skip_permission_denied = 2 }; constexpr directory_options operator&(directory_options __x, directory_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) & static_cast<__utype>(__y)); } constexpr directory_options operator|(directory_options __x, directory_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) | static_cast<__utype>(__y)); } constexpr directory_options operator^(directory_options __x, directory_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) ^ static_cast<__utype>(__y)); } constexpr directory_options operator~(directory_options __x) noexcept { using __utype = typename std::underlying_type::type; return static_cast(~static_cast<__utype>(__x)); } inline directory_options& operator&=(directory_options& __x, directory_options __y) noexcept { return __x = __x & __y; } inline directory_options& operator|=(directory_options& __x, directory_options __y) noexcept { return __x = __x | __y; } inline directory_options& operator^=(directory_options& __x, directory_options __y) noexcept { return __x = __x ^ __y; } using file_time_type = std::chrono::system_clock::time_point; // operational functions void copy(const path& __from, const path& __to, copy_options __options); void copy(const path& __from, const path& __to, copy_options __options, error_code&) noexcept; bool copy_file(const path& __from, const path& __to, copy_options __option); bool copy_file(const path& __from, const path& __to, copy_options __option, error_code&) noexcept; path current_path(); file_status status(const path&); file_status status(const path&, error_code&) noexcept; bool status_known(file_status) noexcept; file_status symlink_status(const path&); file_status symlink_status(const path&, error_code&) noexcept; bool is_regular_file(file_status) noexcept; bool is_symlink(file_status) noexcept; // @} group filesystem-ts } // namespace v1 } // namespace filesystem } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif // _GLIBCXX_EXPERIMENTAL_FS_FWD_H PK![y$y$8/experimental/bits/fs_ops.hnu[// Filesystem operational functions -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your __option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/bits/fs_fwd.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{experimental/filesystem} */ #ifndef _GLIBCXX_EXPERIMENTAL_FS_OPS_H #define _GLIBCXX_EXPERIMENTAL_FS_OPS_H 1 #if __cplusplus < 201103L # include #else #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { namespace filesystem { inline namespace v1 { /** * @ingroup filesystem-ts * @{ */ path absolute(const path& __p, const path& __base = current_path()); path canonical(const path& __p, const path& __base = current_path()); path canonical(const path& __p, error_code& __ec); path canonical(const path& __p, const path& __base, error_code& __ec); inline void copy(const path& __from, const path& __to) { copy(__from, __to, copy_options::none); } inline void copy(const path& __from, const path& __to, error_code& __ec) noexcept { copy(__from, __to, copy_options::none, __ec); } void copy(const path& __from, const path& __to, copy_options __options); void copy(const path& __from, const path& __to, copy_options __options, error_code& __ec) noexcept; inline bool copy_file(const path& __from, const path& __to) { return copy_file(__from, __to, copy_options::none); } inline bool copy_file(const path& __from, const path& __to, error_code& __ec) noexcept { return copy_file(__from, __to, copy_options::none, __ec); } bool copy_file(const path& __from, const path& __to, copy_options __option); bool copy_file(const path& __from, const path& __to, copy_options __option, error_code& __ec) noexcept; void copy_symlink(const path& __existing_symlink, const path& __new_symlink); void copy_symlink(const path& __existing_symlink, const path& __new_symlink, error_code& __ec) noexcept; bool create_directories(const path& __p); bool create_directories(const path& __p, error_code& __ec) noexcept; bool create_directory(const path& __p); bool create_directory(const path& __p, error_code& __ec) noexcept; bool create_directory(const path& __p, const path& attributes); bool create_directory(const path& __p, const path& attributes, error_code& __ec) noexcept; void create_directory_symlink(const path& __to, const path& __new_symlink); void create_directory_symlink(const path& __to, const path& __new_symlink, error_code& __ec) noexcept; void create_hard_link(const path& __to, const path& __new_hard_link); void create_hard_link(const path& __to, const path& __new_hard_link, error_code& __ec) noexcept; void create_symlink(const path& __to, const path& __new_symlink); void create_symlink(const path& __to, const path& __new_symlink, error_code& __ec) noexcept; path current_path(); path current_path(error_code& __ec); void current_path(const path& __p); void current_path(const path& __p, error_code& __ec) noexcept; bool equivalent(const path& __p1, const path& __p2); bool equivalent(const path& __p1, const path& __p2, error_code& __ec) noexcept; inline bool exists(file_status __s) noexcept { return status_known(__s) && __s.type() != file_type::not_found; } inline bool exists(const path& __p) { return exists(status(__p)); } inline bool exists(const path& __p, error_code& __ec) noexcept { auto __s = status(__p, __ec); if (status_known(__s)) { __ec.clear(); return __s.type() != file_type::not_found; } return false; } uintmax_t file_size(const path& __p); uintmax_t file_size(const path& __p, error_code& __ec) noexcept; uintmax_t hard_link_count(const path& __p); uintmax_t hard_link_count(const path& __p, error_code& __ec) noexcept; inline bool is_block_file(file_status __s) noexcept { return __s.type() == file_type::block; } inline bool is_block_file(const path& __p) { return is_block_file(status(__p)); } inline bool is_block_file(const path& __p, error_code& __ec) noexcept { return is_block_file(status(__p, __ec)); } inline bool is_character_file(file_status __s) noexcept { return __s.type() == file_type::character; } inline bool is_character_file(const path& __p) { return is_character_file(status(__p)); } inline bool is_character_file(const path& __p, error_code& __ec) noexcept { return is_character_file(status(__p, __ec)); } inline bool is_directory(file_status __s) noexcept { return __s.type() == file_type::directory; } inline bool is_directory(const path& __p) { return is_directory(status(__p)); } inline bool is_directory(const path& __p, error_code& __ec) noexcept { return is_directory(status(__p, __ec)); } bool is_empty(const path& __p); bool is_empty(const path& __p, error_code& __ec) noexcept; inline bool is_fifo(file_status __s) noexcept { return __s.type() == file_type::fifo; } inline bool is_fifo(const path& __p) { return is_fifo(status(__p)); } inline bool is_fifo(const path& __p, error_code& __ec) noexcept { return is_fifo(status(__p, __ec)); } inline bool is_other(file_status __s) noexcept { return exists(__s) && !is_regular_file(__s) && !is_directory(__s) && !is_symlink(__s); } inline bool is_other(const path& __p) { return is_other(status(__p)); } inline bool is_other(const path& __p, error_code& __ec) noexcept { return is_other(status(__p, __ec)); } inline bool is_regular_file(file_status __s) noexcept { return __s.type() == file_type::regular; } inline bool is_regular_file(const path& __p) { return is_regular_file(status(__p)); } inline bool is_regular_file(const path& __p, error_code& __ec) noexcept { return is_regular_file(status(__p, __ec)); } inline bool is_socket(file_status __s) noexcept { return __s.type() == file_type::socket; } inline bool is_socket(const path& __p) { return is_socket(status(__p)); } inline bool is_socket(const path& __p, error_code& __ec) noexcept { return is_socket(status(__p, __ec)); } inline bool is_symlink(file_status __s) noexcept { return __s.type() == file_type::symlink; } inline bool is_symlink(const path& __p) { return is_symlink(symlink_status(__p)); } inline bool is_symlink(const path& __p, error_code& __ec) noexcept { return is_symlink(symlink_status(__p, __ec)); } file_time_type last_write_time(const path& __p); file_time_type last_write_time(const path& __p, error_code& __ec) noexcept; void last_write_time(const path& __p, file_time_type __new_time); void last_write_time(const path& __p, file_time_type __new_time, error_code& __ec) noexcept; void permissions(const path& __p, perms __prms); void permissions(const path& __p, perms __prms, error_code& __ec) noexcept; path read_symlink(const path& __p); path read_symlink(const path& __p, error_code& __ec); bool remove(const path& __p); bool remove(const path& __p, error_code& __ec) noexcept; uintmax_t remove_all(const path& __p); uintmax_t remove_all(const path& __p, error_code& __ec) noexcept; void rename(const path& __from, const path& __to); void rename(const path& __from, const path& __to, error_code& __ec) noexcept; void resize_file(const path& __p, uintmax_t __size); void resize_file(const path& __p, uintmax_t __size, error_code& __ec) noexcept; space_info space(const path& __p); space_info space(const path& __p, error_code& __ec) noexcept; file_status status(const path& __p); file_status status(const path& __p, error_code& __ec) noexcept; inline bool status_known(file_status __s) noexcept { return __s.type() != file_type::none; } file_status symlink_status(const path& __p); file_status symlink_status(const path& __p, error_code& __ec) noexcept; path system_complete(const path& __p); path system_complete(const path& __p, error_code& __ec); path temp_directory_path(); path temp_directory_path(error_code& __ec); // @} group filesystem-ts } // namespace v1 } // namespace filesystem } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif // _GLIBCXX_EXPERIMENTAL_FS_OPS_H PK!`0${${8/experimental/bits/fs_path.hnu[// Class filesystem::path -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/bits/fs_path.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{experimental/filesystem} */ #ifndef _GLIBCXX_EXPERIMENTAL_FS_PATH_H #define _GLIBCXX_EXPERIMENTAL_FS_PATH_H 1 #if __cplusplus < 201103L # include #else #include #include #include #include #include #include #include #include #include #include #if __cplusplus == 201402L # include #endif #if defined(_WIN32) && !defined(__CYGWIN__) # define _GLIBCXX_FILESYSTEM_IS_WINDOWS 1 # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { namespace filesystem { inline namespace v1 { _GLIBCXX_BEGIN_NAMESPACE_CXX11 #if __cplusplus == 201402L using std::experimental::basic_string_view; #elif __cplusplus > 201402L using std::basic_string_view; #endif /** * @ingroup filesystem-ts * @{ */ /// A filesystem path. class path { template struct __is_encoded_char : std::false_type { }; template> using __is_path_iter_src = __and_<__is_encoded_char, std::is_base_of>; template static __is_path_iter_src<_Iter> __is_path_src(_Iter, int); template static __is_encoded_char<_CharT> __is_path_src(const basic_string<_CharT, _Traits, _Alloc>&, int); #if __cplusplus >= 201402L template static __is_encoded_char<_CharT> __is_path_src(const basic_string_view<_CharT, _Traits>&, int); #endif template static std::false_type __is_path_src(const _Unknown&, ...); template struct __constructible_from; template struct __constructible_from<_Iter, _Iter> : __is_path_iter_src<_Iter> { }; template struct __constructible_from<_Source, void> : decltype(__is_path_src(std::declval<_Source>(), 0)) { }; template::type, typename _Tp1_noptr = typename remove_pointer<_Tp1>::type> using _Path = typename std::enable_if<__and_<__not_>, __not_>, __constructible_from<_Tp1, _Tp2>>::value, path>::type; template static _Source _S_range_begin(_Source __begin) { return __begin; } struct __null_terminated { }; template static __null_terminated _S_range_end(_Source) { return {}; } template static const _CharT* _S_range_begin(const basic_string<_CharT, _Traits, _Alloc>& __str) { return __str.data(); } template static const _CharT* _S_range_end(const basic_string<_CharT, _Traits, _Alloc>& __str) { return __str.data() + __str.size(); } #if __cplusplus >= 201402L template static const _CharT* _S_range_begin(const basic_string_view<_CharT, _Traits>& __str) { return __str.data(); } template static const _CharT* _S_range_end(const basic_string_view<_CharT, _Traits>& __str) { return __str.data() + __str.size(); } #endif template())), typename _Val = typename std::iterator_traits<_Iter>::value_type> using __value_type_is_char = typename std::enable_if::value>::type; public: #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS typedef wchar_t value_type; static constexpr value_type preferred_separator = L'\\'; #else typedef char value_type; static constexpr value_type preferred_separator = '/'; #endif typedef std::basic_string string_type; // constructors and destructor path() noexcept { } path(const path& __p) = default; path(path&& __p) noexcept : _M_pathname(std::move(__p._M_pathname)), _M_type(__p._M_type) { if (_M_type == _Type::_Multi) _M_split_cmpts(); __p.clear(); } path(string_type&& __source) : _M_pathname(std::move(__source)) { _M_split_cmpts(); } template> path(_Source const& __source) : _M_pathname(_S_convert(_S_range_begin(__source), _S_range_end(__source))) { _M_split_cmpts(); } template> path(_InputIterator __first, _InputIterator __last) : _M_pathname(_S_convert(__first, __last)) { _M_split_cmpts(); } template, typename _Require2 = __value_type_is_char<_Source>> path(_Source const& __source, const locale& __loc) : _M_pathname(_S_convert_loc(_S_range_begin(__source), _S_range_end(__source), __loc)) { _M_split_cmpts(); } template, typename _Require2 = __value_type_is_char<_InputIterator>> path(_InputIterator __first, _InputIterator __last, const locale& __loc) : _M_pathname(_S_convert_loc(__first, __last, __loc)) { _M_split_cmpts(); } ~path() = default; // assignments path& operator=(const path& __p) = default; path& operator=(path&& __p) noexcept; path& operator=(string_type&& __source); path& assign(string_type&& __source); template _Path<_Source>& operator=(_Source const& __source) { return *this = path(__source); } template _Path<_Source>& assign(_Source const& __source) { return *this = path(__source); } template _Path<_InputIterator, _InputIterator>& assign(_InputIterator __first, _InputIterator __last) { return *this = path(__first, __last); } // appends path& operator/=(const path& __p) { return _M_append(__p._M_pathname); } template _Path<_Source>& operator/=(_Source const& __source) { return append(__source); } template _Path<_Source>& append(_Source const& __source) { return _M_append(_S_convert(_S_range_begin(__source), _S_range_end(__source))); } template _Path<_InputIterator, _InputIterator>& append(_InputIterator __first, _InputIterator __last) { return _M_append(_S_convert(__first, __last)); } // concatenation path& operator+=(const path& __x); path& operator+=(const string_type& __x); path& operator+=(const value_type* __x); path& operator+=(value_type __x); #if __cplusplus >= 201402L path& operator+=(basic_string_view __x); #endif template _Path<_Source>& operator+=(_Source const& __x) { return concat(__x); } template _Path<_CharT*, _CharT*>& operator+=(_CharT __x); template _Path<_Source>& concat(_Source const& __x) { return *this += _S_convert(_S_range_begin(__x), _S_range_end(__x)); } template _Path<_InputIterator, _InputIterator>& concat(_InputIterator __first, _InputIterator __last) { return *this += _S_convert(__first, __last); } // modifiers void clear() noexcept { _M_pathname.clear(); _M_split_cmpts(); } path& make_preferred(); path& remove_filename(); path& replace_filename(const path& __replacement); path& replace_extension(const path& __replacement = path()); void swap(path& __rhs) noexcept; // native format observers const string_type& native() const noexcept { return _M_pathname; } const value_type* c_str() const noexcept { return _M_pathname.c_str(); } operator string_type() const { return _M_pathname; } template, typename _Allocator = std::allocator<_CharT>> std::basic_string<_CharT, _Traits, _Allocator> string(const _Allocator& __a = _Allocator()) const; std::string string() const; #if _GLIBCXX_USE_WCHAR_T std::wstring wstring() const; #endif std::string u8string() const; std::u16string u16string() const; std::u32string u32string() const; // generic format observers template, typename _Allocator = std::allocator<_CharT>> std::basic_string<_CharT, _Traits, _Allocator> generic_string(const _Allocator& __a = _Allocator()) const; std::string generic_string() const; #if _GLIBCXX_USE_WCHAR_T std::wstring generic_wstring() const; #endif std::string generic_u8string() const; std::u16string generic_u16string() const; std::u32string generic_u32string() const; // compare int compare(const path& __p) const noexcept; int compare(const string_type& __s) const; int compare(const value_type* __s) const; #if __cplusplus >= 201402L int compare(const basic_string_view __s) const; #endif // decomposition path root_name() const; path root_directory() const; path root_path() const; path relative_path() const; path parent_path() const; path filename() const; path stem() const; path extension() const; // query bool empty() const noexcept { return _M_pathname.empty(); } bool has_root_name() const; bool has_root_directory() const; bool has_root_path() const; bool has_relative_path() const; bool has_parent_path() const; bool has_filename() const; bool has_stem() const; bool has_extension() const; bool is_absolute() const { return has_root_directory(); } bool is_relative() const { return !is_absolute(); } // iterators class iterator; typedef iterator const_iterator; iterator begin() const; iterator end() const; private: enum class _Type : unsigned char { _Multi, _Root_name, _Root_dir, _Filename }; path(string_type __str, _Type __type) : _M_pathname(__str), _M_type(__type) { __glibcxx_assert(!empty()); __glibcxx_assert(_M_type != _Type::_Multi); } enum class _Split { _Stem, _Extension }; path& _M_append(const string_type& __str) { if (!_M_pathname.empty() && !_S_is_dir_sep(_M_pathname.back()) && !__str.empty() && !_S_is_dir_sep(__str.front())) _M_pathname += preferred_separator; _M_pathname += __str; _M_split_cmpts(); return *this; } pair _M_find_extension() const; template struct _Cvt; static string_type _S_convert(value_type* __src, __null_terminated) { return string_type(__src); } static string_type _S_convert(const value_type* __src, __null_terminated) { return string_type(__src); } template static string_type _S_convert(_Iter __first, _Iter __last) { using __value_type = typename std::iterator_traits<_Iter>::value_type; return _Cvt::type>:: _S_convert(__first, __last); } template static string_type _S_convert(_InputIterator __src, __null_terminated) { using _Tp = typename std::iterator_traits<_InputIterator>::value_type; std::basic_string::type> __tmp; for (; *__src != _Tp{}; ++__src) __tmp.push_back(*__src); return _S_convert(__tmp.c_str(), __tmp.c_str() + __tmp.size()); } static string_type _S_convert_loc(const char* __first, const char* __last, const std::locale& __loc); template static string_type _S_convert_loc(_Iter __first, _Iter __last, const std::locale& __loc) { const std::string __str(__first, __last); return _S_convert_loc(__str.data(), __str.data()+__str.size(), __loc); } template static string_type _S_convert_loc(_InputIterator __src, __null_terminated, const std::locale& __loc) { std::string __tmp; while (*__src != '\0') __tmp.push_back(*__src++); return _S_convert_loc(__tmp.data(), __tmp.data()+__tmp.size(), __loc); } static bool _S_is_dir_sep(value_type __ch) { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS return __ch == L'/' || __ch == preferred_separator; #else return __ch == '/'; #endif } void _M_split_cmpts(); void _M_trim(); void _M_add_root_name(size_t __n); void _M_add_root_dir(size_t __pos); void _M_add_filename(size_t __pos, size_t __n); string_type _M_pathname; struct _Cmpt; using _List = _GLIBCXX_STD_C::vector<_Cmpt>; _List _M_cmpts; // empty unless _M_type == _Type::_Multi _Type _M_type = _Type::_Multi; }; inline void swap(path& __lhs, path& __rhs) noexcept { __lhs.swap(__rhs); } size_t hash_value(const path& __p) noexcept; /// Compare paths inline bool operator<(const path& __lhs, const path& __rhs) noexcept { return __lhs.compare(__rhs) < 0; } /// Compare paths inline bool operator<=(const path& __lhs, const path& __rhs) noexcept { return !(__rhs < __lhs); } /// Compare paths inline bool operator>(const path& __lhs, const path& __rhs) noexcept { return __rhs < __lhs; } /// Compare paths inline bool operator>=(const path& __lhs, const path& __rhs) noexcept { return !(__lhs < __rhs); } /// Compare paths inline bool operator==(const path& __lhs, const path& __rhs) noexcept { return __lhs.compare(__rhs) == 0; } /// Compare paths inline bool operator!=(const path& __lhs, const path& __rhs) noexcept { return !(__lhs == __rhs); } /// Append one path to another inline path operator/(const path& __lhs, const path& __rhs) { path __result(__lhs); __result /= __rhs; return __result; } /// Write a path to a stream template basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, const path& __p) { auto __tmp = __p.string<_CharT, _Traits>(); using __quoted_string = std::__detail::_Quoted_string; __os << __quoted_string{__tmp, '"', '\\'}; return __os; } /// Read a path from a stream template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __is, path& __p) { basic_string<_CharT, _Traits> __tmp; using __quoted_string = std::__detail::_Quoted_string; if (__is >> __quoted_string{ __tmp, '"', '\\' }) __p = std::move(__tmp); return __is; } // TODO constrain with _Path and __value_type_is_char template inline path u8path(const _Source& __source) { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS return path{ path::string_type{__source} }; #else return path{ __source }; #endif } // TODO constrain with _Path and __value_type_is_char template inline path u8path(_InputIterator __first, _InputIterator __last) { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS return path{ path::string_type{__first, __last} }; #else return path{ __first, __last }; #endif } class filesystem_error : public std::system_error { public: filesystem_error(const string& __what_arg, error_code __ec) : system_error(__ec, __what_arg) { } filesystem_error(const string& __what_arg, const path& __p1, error_code __ec) : system_error(__ec, __what_arg), _M_path1(__p1) { } filesystem_error(const string& __what_arg, const path& __p1, const path& __p2, error_code __ec) : system_error(__ec, __what_arg), _M_path1(__p1), _M_path2(__p2) { } ~filesystem_error(); const path& path1() const noexcept { return _M_path1; } const path& path2() const noexcept { return _M_path2; } const char* what() const noexcept { return _M_what.c_str(); } private: std::string _M_gen_what(); path _M_path1; path _M_path2; std::string _M_what = _M_gen_what(); }; template<> struct path::__is_encoded_char : std::true_type { using value_type = char; }; template<> struct path::__is_encoded_char : std::true_type { using value_type = wchar_t; }; template<> struct path::__is_encoded_char : std::true_type { using value_type = char16_t; }; template<> struct path::__is_encoded_char : std::true_type { using value_type = char32_t; }; template struct path::__is_encoded_char : __is_encoded_char<_Tp> { }; struct path::_Cmpt : path { _Cmpt(string_type __s, _Type __t, size_t __pos) : path(std::move(__s), __t), _M_pos(__pos) { } _Cmpt() : _M_pos(-1) { } size_t _M_pos; }; // specialize _Cvt for degenerate 'noconv' case template<> struct path::_Cvt { template static string_type _S_convert(_Iter __first, _Iter __last) { return string_type{__first, __last}; } }; template struct path::_Cvt { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS static string_type _S_wconvert(const char* __f, const char* __l, true_type) { using _Cvt = std::codecvt; const auto& __cvt = std::use_facet<_Cvt>(std::locale{}); std::wstring __wstr; if (__str_codecvt_in(__f, __l, __wstr, __cvt)) return __wstr; _GLIBCXX_THROW_OR_ABORT(filesystem_error( "Cannot convert character sequence", std::make_error_code(errc::illegal_byte_sequence))); } static string_type _S_wconvert(const _CharT* __f, const _CharT* __l, false_type) { std::codecvt_utf8<_CharT> __cvt; std::string __str; if (__str_codecvt_out(__f, __l, __str, __cvt)) { const char* __f2 = __str.data(); const char* __l2 = __f2 + __str.size(); std::codecvt_utf8 __wcvt; std::wstring __wstr; if (__str_codecvt_in(__f2, __l2, __wstr, __wcvt)) return __wstr; } _GLIBCXX_THROW_OR_ABORT(filesystem_error( "Cannot convert character sequence", std::make_error_code(errc::illegal_byte_sequence))); } static string_type _S_convert(const _CharT* __f, const _CharT* __l) { return _S_wconvert(__f, __l, is_same<_CharT, char>{}); } #else static string_type _S_convert(const _CharT* __f, const _CharT* __l) { std::codecvt_utf8<_CharT> __cvt; std::string __str; if (__str_codecvt_out(__f, __l, __str, __cvt)) return __str; _GLIBCXX_THROW_OR_ABORT(filesystem_error( "Cannot convert character sequence", std::make_error_code(errc::illegal_byte_sequence))); } #endif static string_type _S_convert(_CharT* __f, _CharT* __l) { return _S_convert(const_cast(__f), const_cast(__l)); } template static string_type _S_convert(_Iter __first, _Iter __last) { const std::basic_string<_CharT> __str(__first, __last); return _S_convert(__str.data(), __str.data() + __str.size()); } template static string_type _S_convert(__gnu_cxx::__normal_iterator<_Iter, _Cont> __first, __gnu_cxx::__normal_iterator<_Iter, _Cont> __last) { return _S_convert(__first.base(), __last.base()); } }; /// An iterator for the components of a path class path::iterator { public: using difference_type = std::ptrdiff_t; using value_type = path; using reference = const path&; using pointer = const path*; using iterator_category = std::bidirectional_iterator_tag; iterator() : _M_path(nullptr), _M_cur(), _M_at_end() { } iterator(const iterator&) = default; iterator& operator=(const iterator&) = default; reference operator*() const; pointer operator->() const { return std::__addressof(**this); } iterator& operator++(); iterator operator++(int) { auto __tmp = *this; ++*this; return __tmp; } iterator& operator--(); iterator operator--(int) { auto __tmp = *this; --*this; return __tmp; } friend bool operator==(const iterator& __lhs, const iterator& __rhs) { return __lhs._M_equals(__rhs); } friend bool operator!=(const iterator& __lhs, const iterator& __rhs) { return !__lhs._M_equals(__rhs); } private: friend class path; iterator(const path* __path, path::_List::const_iterator __iter) : _M_path(__path), _M_cur(__iter), _M_at_end() { } iterator(const path* __path, bool __at_end) : _M_path(__path), _M_cur(), _M_at_end(__at_end) { } bool _M_equals(iterator) const; const path* _M_path; path::_List::const_iterator _M_cur; bool _M_at_end; // only used when type != _Multi }; inline path& path::operator=(path&& __p) noexcept { _M_pathname = std::move(__p._M_pathname); _M_cmpts = std::move(__p._M_cmpts); _M_type = __p._M_type; __p.clear(); return *this; } inline path& path::operator=(string_type&& __source) { return *this = path(std::move(__source)); } inline path& path::assign(string_type&& __source) { return *this = path(std::move(__source)); } inline path& path::operator+=(const path& __p) { return operator+=(__p.native()); } inline path& path::operator+=(const string_type& __x) { _M_pathname += __x; _M_split_cmpts(); return *this; } inline path& path::operator+=(const value_type* __x) { _M_pathname += __x; _M_split_cmpts(); return *this; } inline path& path::operator+=(value_type __x) { _M_pathname += __x; _M_split_cmpts(); return *this; } #if __cplusplus >= 201402L inline path& path::operator+=(basic_string_view __x) { _M_pathname.append(__x.data(), __x.size()); _M_split_cmpts(); return *this; } #endif template inline path::_Path<_CharT*, _CharT*>& path::operator+=(_CharT __x) { auto* __addr = std::__addressof(__x); return concat(__addr, __addr + 1); } inline path& path::make_preferred() { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS std::replace(_M_pathname.begin(), _M_pathname.end(), L'/', preferred_separator); #endif return *this; } inline void path::swap(path& __rhs) noexcept { _M_pathname.swap(__rhs._M_pathname); _M_cmpts.swap(__rhs._M_cmpts); std::swap(_M_type, __rhs._M_type); } template inline std::basic_string<_CharT, _Traits, _Allocator> path::string(const _Allocator& __a) const { if (is_same<_CharT, value_type>::value) return { _M_pathname.begin(), _M_pathname.end(), __a }; const value_type* __first = _M_pathname.data(); const value_type* __last = __first + _M_pathname.size(); #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS using _CharAlloc = __alloc_rebind<_Allocator, char>; using _String = basic_string, _CharAlloc>; using _WString = basic_string<_CharT, _Traits, _Allocator>; // use codecvt_utf8 to convert native string to UTF-8 codecvt_utf8 __cvt; _String __u8str{_CharAlloc{__a}}; if (__str_codecvt_out(__first, __last, __u8str, __cvt)) { struct { const _String* operator()(const _String& __from, _String&, true_type) { return std::__addressof(__from); } _WString* operator()(const _String& __from, _WString& __to, false_type) { // use codecvt_utf8<_CharT> to convert UTF-8 to wide string codecvt_utf8<_CharT> __cvt; const char* __f = __from.data(); const char* __l = __f + __from.size(); if (__str_codecvt_in(__f, __l, __to, __cvt)) return std::__addressof(__to); return nullptr; } } __dispatch; _WString __wstr; if (auto* __p = __dispatch(__u8str, __wstr, is_same<_CharT, char>{})) return *__p; } #else codecvt_utf8<_CharT> __cvt; basic_string<_CharT, _Traits, _Allocator> __wstr{__a}; if (__str_codecvt_in(__first, __last, __wstr, __cvt)) return __wstr; #endif _GLIBCXX_THROW_OR_ABORT(filesystem_error( "Cannot convert character sequence", std::make_error_code(errc::illegal_byte_sequence))); } inline std::string path::string() const { return string(); } #if _GLIBCXX_USE_WCHAR_T inline std::wstring path::wstring() const { return string(); } #endif inline std::string path::u8string() const { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS std::string __str; // convert from native encoding to UTF-8 codecvt_utf8 __cvt; const value_type* __first = _M_pathname.data(); const value_type* __last = __first + _M_pathname.size(); if (__str_codecvt_out(__first, __last, __str, __cvt)) return __str; _GLIBCXX_THROW_OR_ABORT(filesystem_error( "Cannot convert character sequence", std::make_error_code(errc::illegal_byte_sequence))); #else return _M_pathname; #endif } inline std::u16string path::u16string() const { return string(); } inline std::u32string path::u32string() const { return string(); } template inline std::basic_string<_CharT, _Traits, _Allocator> path::generic_string(const _Allocator& __a) const { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS const _CharT __slash = is_same<_CharT, wchar_t>::value ? _CharT(L'/') : _CharT('/'); // Assume value is correct for the encoding. #else const _CharT __slash = _CharT('/'); #endif basic_string<_CharT, _Traits, _Allocator> __str(__a); __str.reserve(_M_pathname.size()); bool __add_slash = false; for (auto& __elem : *this) { if (__elem._M_type == _Type::_Root_dir) { __str += __slash; continue; } if (__add_slash) __str += __slash; __str += __elem.string<_CharT, _Traits, _Allocator>(__a); __add_slash = __elem._M_type == _Type::_Filename; } return __str; } inline std::string path::generic_string() const { return generic_string(); } #if _GLIBCXX_USE_WCHAR_T inline std::wstring path::generic_wstring() const { return generic_string(); } #endif inline std::string path::generic_u8string() const { return generic_string(); } inline std::u16string path::generic_u16string() const { return generic_string(); } inline std::u32string path::generic_u32string() const { return generic_string(); } inline int path::compare(const string_type& __s) const { return compare(path(__s)); } inline int path::compare(const value_type* __s) const { return compare(path(__s)); } #if __cplusplus >= 201402L inline int path::compare(basic_string_view __s) const { return compare(path(__s)); } #endif inline path path::filename() const { return empty() ? path() : *--end(); } inline path path::stem() const { auto ext = _M_find_extension(); if (ext.first && ext.second != 0) return path{ext.first->substr(0, ext.second)}; return {}; } inline path path::extension() const { auto ext = _M_find_extension(); if (ext.first && ext.second != string_type::npos) return path{ext.first->substr(ext.second)}; return {}; } inline bool path::has_stem() const { auto ext = _M_find_extension(); return ext.first && ext.second != 0; } inline bool path::has_extension() const { auto ext = _M_find_extension(); return ext.first && ext.second != string_type::npos; } inline path::iterator path::begin() const { if (_M_type == _Type::_Multi) return iterator(this, _M_cmpts.begin()); return iterator(this, false); } inline path::iterator path::end() const { if (_M_type == _Type::_Multi) return iterator(this, _M_cmpts.end()); return iterator(this, true); } inline path::iterator& path::iterator::operator++() { __glibcxx_assert(_M_path != nullptr); if (_M_path->_M_type == _Type::_Multi) { __glibcxx_assert(_M_cur != _M_path->_M_cmpts.end()); ++_M_cur; } else { __glibcxx_assert(!_M_at_end); _M_at_end = true; } return *this; } inline path::iterator& path::iterator::operator--() { __glibcxx_assert(_M_path != nullptr); if (_M_path->_M_type == _Type::_Multi) { __glibcxx_assert(_M_cur != _M_path->_M_cmpts.begin()); --_M_cur; } else { __glibcxx_assert(_M_at_end); _M_at_end = false; } return *this; } inline path::iterator::reference path::iterator::operator*() const { __glibcxx_assert(_M_path != nullptr); if (_M_path->_M_type == _Type::_Multi) { __glibcxx_assert(_M_cur != _M_path->_M_cmpts.end()); return *_M_cur; } return *_M_path; } inline bool path::iterator::_M_equals(iterator __rhs) const { if (_M_path != __rhs._M_path) return false; if (_M_path == nullptr) return true; if (_M_path->_M_type == path::_Type::_Multi) return _M_cur == __rhs._M_cur; return _M_at_end == __rhs._M_at_end; } // @} group filesystem-ts _GLIBCXX_END_NAMESPACE_CXX11 } // namespace v1 } // namespace filesystem } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif // _GLIBCXX_EXPERIMENTAL_FS_PATH_H PK!EE!8/experimental/bits/lfts_config.hnu[// Namespace declarations for Library Fundamentals TS -*- C++ -*- // Copyright (C) 2016-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/bits/lfts_config.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. */ #if __cplusplus >= 201402L #include #if _GLIBCXX_INLINE_VERSION namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace chrono { namespace experimental { inline namespace fundamentals_v1 { } inline namespace fundamentals_v2 { } } // namespace experimental } // namespace chrono namespace experimental { inline namespace fundamentals_v1 { } inline namespace fundamentals_v2 { } inline namespace literals { inline namespace string_view_literals { } } } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif #endif PK! O O 8/experimental/bits/shared_ptr.hnu[// Experimental shared_ptr with array support -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/bits/shared_ptr.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{experimental/memory} */ #ifndef _GLIBCXX_EXPERIMENTAL_SHARED_PTR_H #define _GLIBCXX_EXPERIMENTAL_SHARED_PTR_H 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { // 8.2.1 template class shared_ptr; template class weak_ptr; template class enable_shared_from_this; template constexpr bool __sp_compatible_v = std::__sp_compatible_with<_Yp*, _Tp*>::value; template constexpr bool __sp_is_constructible_v = std::__sp_is_constructible<_Tp, _Yp>::value; template class shared_ptr : public __shared_ptr<_Tp> { using _Base_type = __shared_ptr<_Tp>; public: using element_type = typename _Base_type::element_type; private: // Constraint for construction from a pointer of type _Yp*: template using _SafeConv = enable_if_t<__sp_is_constructible_v<_Tp, _Yp>>; template using _Compatible = enable_if_t<__sp_compatible_v<_Tp1, _Tp>, _Res>; template::pointer, typename _Res = void> using _UniqCompatible = enable_if_t< __sp_compatible_v<_Tp1, _Tp> && experimental::is_convertible_v<_Ptr, element_type*>, _Res>; public: // 8.2.1.1, shared_ptr constructors constexpr shared_ptr() noexcept = default; template> explicit shared_ptr(_Tp1* __p) : _Base_type(__p) { _M_enable_shared_from_this_with(__p); } template> shared_ptr(_Tp1* __p, _Deleter __d) : _Base_type(__p, __d) { _M_enable_shared_from_this_with(__p); } template> shared_ptr(_Tp1* __p, _Deleter __d, _Alloc __a) : _Base_type(__p, __d, __a) { _M_enable_shared_from_this_with(__p); } template shared_ptr(nullptr_t __p, _Deleter __d) : _Base_type(__p, __d) { } template shared_ptr(nullptr_t __p, _Deleter __d, _Alloc __a) : _Base_type(__p, __d, __a) { } template shared_ptr(const shared_ptr<_Tp1>& __r, element_type* __p) noexcept : _Base_type(__r, __p) { } shared_ptr(const shared_ptr& __r) noexcept : _Base_type(__r) { } template> shared_ptr(const shared_ptr<_Tp1>& __r) noexcept : _Base_type(__r) { } shared_ptr(shared_ptr&& __r) noexcept : _Base_type(std::move(__r)) { } template> shared_ptr(shared_ptr<_Tp1>&& __r) noexcept : _Base_type(std::move(__r)) { } template> explicit shared_ptr(const weak_ptr<_Tp1>& __r) : _Base_type(__r) { } #if _GLIBCXX_USE_DEPRECATED template> shared_ptr(std::auto_ptr<_Tp1>&& __r) : _Base_type(std::move(__r)) { _M_enable_shared_from_this_with(static_cast<_Tp1*>(this->get())); } #endif template> shared_ptr(unique_ptr<_Tp1, _Del>&& __r) : _Base_type(std::move(__r)) { // XXX assume conversion from __r.get() to this->get() to __elem_t* // is a round trip, which might not be true in all cases. using __elem_t = typename unique_ptr<_Tp1, _Del>::element_type; _M_enable_shared_from_this_with(static_cast<__elem_t*>(this->get())); } constexpr shared_ptr(nullptr_t __p) : _Base_type(__p) { } // C++14 §20.8.2.2 ~shared_ptr() = default; // C++14 §20.8.2.3 shared_ptr& operator=(const shared_ptr&) noexcept = default; template _Compatible<_Tp1, shared_ptr&> operator=(const shared_ptr<_Tp1>& __r) noexcept { _Base_type::operator=(__r); return *this; } shared_ptr& operator=(shared_ptr&& __r) noexcept { _Base_type::operator=(std::move(__r)); return *this; } template _Compatible<_Tp1, shared_ptr&> operator=(shared_ptr<_Tp1>&& __r) noexcept { _Base_type::operator=(std::move(__r)); return *this; } #if _GLIBCXX_USE_DEPRECATED template _Compatible<_Tp1, shared_ptr&> operator=(std::auto_ptr<_Tp1>&& __r) { __shared_ptr<_Tp>::operator=(std::move(__r)); return *this; } #endif template _UniqCompatible<_Tp1, _Del, shared_ptr&> operator=(unique_ptr<_Tp1, _Del>&& __r) { _Base_type::operator=(std::move(__r)); return *this; } // C++14 §20.8.2.2.4 // swap & reset // 8.2.1.2 shared_ptr observers // in __shared_ptr private: template shared_ptr(_Sp_make_shared_tag __tag, const _Alloc& __a, _Args&&... __args) : _Base_type(__tag, __a, std::forward<_Args>(__args)...) { _M_enable_shared_from_this_with(this->get()); } template friend shared_ptr<_Tp1> allocate_shared(const _Alloc& __a, _Args&&... __args); shared_ptr(const weak_ptr<_Tp>& __r, std::nothrow_t) : _Base_type(__r, std::nothrow) { } friend class weak_ptr<_Tp>; template using __esft_base_t = decltype(__expt_enable_shared_from_this_base(std::declval<_Yp*>())); // Detect an accessible and unambiguous enable_shared_from_this base. template struct __has_esft_base : false_type { }; template struct __has_esft_base<_Yp, __void_t<__esft_base_t<_Yp>>> : __bool_constant> { }; // ignore base for arrays template typename enable_if<__has_esft_base<_Yp>::value>::type _M_enable_shared_from_this_with(const _Yp* __p) noexcept { if (auto __base = __expt_enable_shared_from_this_base(__p)) { __base->_M_weak_this = shared_ptr<_Yp>(*this, const_cast<_Yp*>(__p)); } } template typename enable_if::value>::type _M_enable_shared_from_this_with(const _Yp*) noexcept { } }; // C++14 §20.8.2.2.7 //DOING template bool operator==(const shared_ptr<_Tp1>& __a, const shared_ptr<_Tp2>& __b) noexcept { return __a.get() == __b.get(); } template inline bool operator==(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { return !__a; } template inline bool operator==(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { return !__a; } template inline bool operator!=(const shared_ptr<_Tp1>& __a, const shared_ptr<_Tp2>& __b) noexcept { return __a.get() != __b.get(); } template inline bool operator!=(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { return (bool)__a; } template inline bool operator!=(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { return (bool)__a; } template inline bool operator<(const shared_ptr<_Tp1>& __a, const shared_ptr<_Tp2>& __b) noexcept { using __elem_t1 = typename shared_ptr<_Tp1>::element_type; using __elem_t2 = typename shared_ptr<_Tp2>::element_type; using _CT = common_type_t<__elem_t1*, __elem_t2*>; return std::less<_CT>()(__a.get(), __b.get()); } template inline bool operator<(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { using __elem_t = typename shared_ptr<_Tp>::element_type; return std::less<__elem_t*>()(__a.get(), nullptr); } template inline bool operator<(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { using __elem_t = typename shared_ptr<_Tp>::element_type; return std::less<__elem_t*>()(nullptr, __a.get()); } template inline bool operator<=(const shared_ptr<_Tp1>& __a, const shared_ptr<_Tp2>& __b) noexcept { return !(__b < __a); } template inline bool operator<=(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { return !(nullptr < __a); } template inline bool operator<=(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { return !(__a < nullptr); } template inline bool operator>(const shared_ptr<_Tp1>& __a, const shared_ptr<_Tp2>& __b) noexcept { return (__b < __a); } template inline bool operator>(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { using __elem_t = typename shared_ptr<_Tp>::element_type; return std::less<__elem_t*>()(nullptr, __a.get()); } template inline bool operator>(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { using __elem_t = typename shared_ptr<_Tp>::element_type; return std::less<__elem_t*>()(__a.get(), nullptr); } template inline bool operator>=(const shared_ptr<_Tp1>& __a, const shared_ptr<_Tp2>& __b) noexcept { return !(__a < __b); } template inline bool operator>=(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { return !(__a < nullptr); } template inline bool operator>=(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { return !(nullptr < __a); } // C++14 §20.8.2.2.8 template inline void swap(shared_ptr<_Tp>& __a, shared_ptr<_Tp>& __b) noexcept { __a.swap(__b); } // 8.2.1.3, shared_ptr casts template inline shared_ptr<_Tp> static_pointer_cast(const shared_ptr<_Tp1>& __r) noexcept { using __elem_t = typename shared_ptr<_Tp>::element_type; return shared_ptr<_Tp>(__r, static_cast<__elem_t*>(__r.get())); } template inline shared_ptr<_Tp> dynamic_pointer_cast(const shared_ptr<_Tp1>& __r) noexcept { using __elem_t = typename shared_ptr<_Tp>::element_type; if (_Tp* __p = dynamic_cast<__elem_t*>(__r.get())) return shared_ptr<_Tp>(__r, __p); return shared_ptr<_Tp>(); } template inline shared_ptr<_Tp> const_pointer_cast(const shared_ptr<_Tp1>& __r) noexcept { using __elem_t = typename shared_ptr<_Tp>::element_type; return shared_ptr<_Tp>(__r, const_cast<__elem_t*>(__r.get())); } template inline shared_ptr<_Tp> reinterpret_pointer_cast(const shared_ptr<_Tp1>& __r) noexcept { using __elem_t = typename shared_ptr<_Tp>::element_type; return shared_ptr<_Tp>(__r, reinterpret_cast<__elem_t*>(__r.get())); } // C++14 §20.8.2.3 template class weak_ptr : public __weak_ptr<_Tp> { template using _Compatible = enable_if_t<__sp_compatible_v<_Tp1, _Tp>, _Res>; using _Base_type = __weak_ptr<_Tp>; public: constexpr weak_ptr() noexcept = default; template> weak_ptr(const shared_ptr<_Tp1>& __r) noexcept : _Base_type(__r) { } weak_ptr(const weak_ptr&) noexcept = default; template> weak_ptr(const weak_ptr<_Tp1>& __r) noexcept : _Base_type(__r) { } weak_ptr(weak_ptr&&) noexcept = default; template> weak_ptr(weak_ptr<_Tp1>&& __r) noexcept : _Base_type(std::move(__r)) { } weak_ptr& operator=(const weak_ptr& __r) noexcept = default; template _Compatible<_Tp1, weak_ptr&> operator=(const weak_ptr<_Tp1>& __r) noexcept { this->_Base_type::operator=(__r); return *this; } template _Compatible<_Tp1, weak_ptr&> operator=(const shared_ptr<_Tp1>& __r) noexcept { this->_Base_type::operator=(__r); return *this; } weak_ptr& operator=(weak_ptr&& __r) noexcept = default; template _Compatible<_Tp1, weak_ptr&> operator=(weak_ptr<_Tp1>&& __r) noexcept { this->_Base_type::operator=(std::move(__r)); return *this; } shared_ptr<_Tp> lock() const noexcept { return shared_ptr<_Tp>(*this, std::nothrow); } friend class enable_shared_from_this<_Tp>; }; // C++14 §20.8.2.3.6 template inline void swap(weak_ptr<_Tp>& __a, weak_ptr<_Tp>& __b) noexcept { __a.swap(__b); } /// C++14 §20.8.2.2.10 template inline _Del* get_deleter(const shared_ptr<_Tp>& __p) noexcept { return std::get_deleter<_Del>(__p); } // C++14 §20.8.2.2.11 template inline std::basic_ostream<_Ch, _Tr>& operator<<(std::basic_ostream<_Ch, _Tr>& __os, const shared_ptr<_Tp>& __p) { __os << __p.get(); return __os; } // C++14 §20.8.2.4 template class owner_less; /// Partial specialization of owner_less for shared_ptr. template struct owner_less> : public _Sp_owner_less, weak_ptr<_Tp>> { }; /// Partial specialization of owner_less for weak_ptr. template struct owner_less> : public _Sp_owner_less, shared_ptr<_Tp>> { }; template<> class owner_less { template bool operator()(shared_ptr<_Tp> const& __lhs, shared_ptr<_Up> const& __rhs) const { return __lhs.owner_before(__rhs); } template bool operator()(shared_ptr<_Tp> const& __lhs, weak_ptr<_Up> const& __rhs) const { return __lhs.owner_before(__rhs); } template bool operator()(weak_ptr<_Tp> const& __lhs, shared_ptr<_Up> const& __rhs) const { return __lhs.owner_before(__rhs); } template bool operator()(weak_ptr<_Tp> const& __lhs, weak_ptr<_Up> const& __rhs) const { return __lhs.owner_before(__rhs); } typedef void is_transparent; }; // C++14 §20.8.2.6 template inline bool atomic_is_lock_free(const shared_ptr<_Tp>* __p) { return std::atomic_is_lock_free<_Tp, __default_lock_policy>(__p); } template shared_ptr<_Tp> atomic_load(const shared_ptr<_Tp>* __p) { return std::atomic_load<_Tp>(__p); } template shared_ptr<_Tp> atomic_load_explicit(const shared_ptr<_Tp>* __p, memory_order __mo) { return std::atomic_load_explicit<_Tp>(__p, __mo); } template void atomic_store(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r) { return std::atomic_store<_Tp>(__p, __r); } template shared_ptr<_Tp> atomic_store_explicit(const shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r, memory_order __mo) { return std::atomic_store_explicit<_Tp>(__p, __r, __mo); } template void atomic_exchange(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r) { return std::atomic_exchange<_Tp>(__p, __r); } template shared_ptr<_Tp> atomic_exchange_explicit(const shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r, memory_order __mo) { return std::atomic_exchange_explicit<_Tp>(__p, __r, __mo); } template bool atomic_compare_exchange_weak(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w) { return std::atomic_compare_exchange_weak<_Tp>(__p, __v, __w); } template bool atomic_compare_exchange_strong(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w) { return std::atomic_compare_exchange_strong<_Tp>(__p, __v, __w); } template bool atomic_compare_exchange_weak_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w, memory_order __success, memory_order __failure) { return std::atomic_compare_exchange_weak_explicit<_Tp>(__p, __v, __w, __success, __failure); } template bool atomic_compare_exchange_strong_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w, memory_order __success, memory_order __failure) { return std::atomic_compare_exchange_strong_explicit<_Tp>(__p, __v, __w, __success, __failure); } //enable_shared_from_this template class enable_shared_from_this { protected: constexpr enable_shared_from_this() noexcept { } enable_shared_from_this(const enable_shared_from_this&) noexcept { } enable_shared_from_this& operator=(const enable_shared_from_this&) noexcept { return *this; } ~enable_shared_from_this() { } public: shared_ptr<_Tp> shared_from_this() { return shared_ptr<_Tp>(this->_M_weak_this); } shared_ptr shared_from_this() const { return shared_ptr(this->_M_weak_this); } weak_ptr<_Tp> weak_from_this() noexcept { return _M_weak_this; } weak_ptr weak_from_this() const noexcept { return _M_weak_this; } private: template void _M_weak_assign(_Tp1* __p, const __shared_count<>& __n) const noexcept { _M_weak_this._M_assign(__p, __n); } // Found by ADL when this is an associated class. friend const enable_shared_from_this* __expt_enable_shared_from_this_base(const enable_shared_from_this* __p) { return __p; } template friend class shared_ptr; mutable weak_ptr<_Tp> _M_weak_this; }; } // namespace fundamentals_v2 } // namespace experimental /// std::hash specialization for shared_ptr. template struct hash> : public __hash_base> { size_t operator()(const experimental::shared_ptr<_Tp>& __s) const noexcept { return std::hash<_Tp*>()(__s.get()); } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // __cplusplus <= 201103L #endif // _GLIBCXX_EXPERIMENTAL_SHARED_PTR_H PK!A#8/experimental/bits/string_view.tccnu[// Components for manipulating non-owning sequences of characters -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/bits/string_view.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{experimental/string_view} */ // // N3762 basic_string_view library // #ifndef _GLIBCXX_EXPERIMENTAL_STRING_VIEW_TCC #define _GLIBCXX_EXPERIMENTAL_STRING_VIEW_TCC 1 #pragma GCC system_header #if __cplusplus >= 201402L namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v1 { template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find(const _CharT* __str, size_type __pos, size_type __n) const noexcept { __glibcxx_requires_string_len(__str, __n); if (__n == 0) return __pos <= this->_M_len ? __pos : npos; if (__n <= this->_M_len) { for (; __pos <= this->_M_len - __n; ++__pos) if (traits_type::eq(this->_M_str[__pos], __str[0]) && traits_type::compare(this->_M_str + __pos + 1, __str + 1, __n - 1) == 0) return __pos; } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find(_CharT __c, size_type __pos) const noexcept { size_type __ret = npos; if (__pos < this->_M_len) { const size_type __n = this->_M_len - __pos; const _CharT* __p = traits_type::find(this->_M_str + __pos, __n, __c); if (__p) __ret = __p - this->_M_str; } return __ret; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: rfind(const _CharT* __str, size_type __pos, size_type __n) const noexcept { __glibcxx_requires_string_len(__str, __n); if (__n <= this->_M_len) { __pos = std::min(size_type(this->_M_len - __n), __pos); do { if (traits_type::compare(this->_M_str + __pos, __str, __n) == 0) return __pos; } while (__pos-- > 0); } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: rfind(_CharT __c, size_type __pos) const noexcept { size_type __size = this->_M_len; if (__size > 0) { if (--__size > __pos) __size = __pos; for (++__size; __size-- > 0; ) if (traits_type::eq(this->_M_str[__size], __c)) return __size; } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_first_of(const _CharT* __str, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__str, __n); for (; __n && __pos < this->_M_len; ++__pos) { const _CharT* __p = traits_type::find(__str, __n, this->_M_str[__pos]); if (__p) return __pos; } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_last_of(const _CharT* __str, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__str, __n); size_type __size = this->size(); if (__size && __n) { if (--__size > __pos) __size = __pos; do { if (traits_type::find(__str, __n, this->_M_str[__size])) return __size; } while (__size-- != 0); } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_first_not_of(const _CharT* __str, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__str, __n); for (; __pos < this->_M_len; ++__pos) if (!traits_type::find(__str, __n, this->_M_str[__pos])) return __pos; return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_first_not_of(_CharT __c, size_type __pos) const noexcept { for (; __pos < this->_M_len; ++__pos) if (!traits_type::eq(this->_M_str[__pos], __c)) return __pos; return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_last_not_of(const _CharT* __str, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__str, __n); size_type __size = this->_M_len; if (__size) { if (--__size > __pos) __size = __pos; do { if (!traits_type::find(__str, __n, this->_M_str[__size])) return __size; } while (__size--); } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_last_not_of(_CharT __c, size_type __pos) const noexcept { size_type __size = this->_M_len; if (__size) { if (--__size > __pos) __size = __pos; do { if (!traits_type::eq(this->_M_str[__size], __c)) return __size; } while (__size--); } return npos; } } // namespace fundamentals_v1 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // __cplusplus <= 201103L #endif // _GLIBCXX_EXPERIMENTAL_STRING_VIEW_TCC PK!;ULL8/experimental/algorithmnu[// -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/algorithm * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_ALGORITHM #define _GLIBCXX_EXPERIMENTAL_ALGORITHM 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { template inline _ForwardIterator search(_ForwardIterator __first, _ForwardIterator __last, const _Searcher& __searcher) { return __searcher(__first, __last); } #define __cpp_lib_experimental_sample 201402 /// Take a random sample from a population. template _SampleIterator sample(_PopulationIterator __first, _PopulationIterator __last, _SampleIterator __out, _Distance __n, _UniformRandomNumberGenerator&& __g) { using __pop_cat = typename std::iterator_traits<_PopulationIterator>::iterator_category; using __samp_cat = typename std::iterator_traits<_SampleIterator>::iterator_category; static_assert( __or_, is_convertible<__samp_cat, random_access_iterator_tag>>::value, "output range must use a RandomAccessIterator when input range" " does not meet the ForwardIterator requirements"); static_assert(is_integral<_Distance>::value, "sample size must be an integer type"); typename iterator_traits<_PopulationIterator>::difference_type __d = __n; return std::__sample(__first, __last, __pop_cat{}, __out, __samp_cat{}, __d, std::forward<_UniformRandomNumberGenerator>(__g)); } template inline _SampleIterator sample(_PopulationIterator __first, _PopulationIterator __last, _SampleIterator __out, _Distance __n) { return experimental::sample(__first, __last, __out, __n, _S_randint_engine()); } template inline void shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last) { return std::shuffle(__first, __last, _S_randint_engine()); } } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_ALGORITHM PK!9>9>8/experimental/anynu[// -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/any * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_ANY #define _GLIBCXX_EXPERIMENTAL_ANY 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v1 { /** * @defgroup any Type-safe container of any type * @ingroup experimental * * A type-safe container for single values of value types, as * described in n3804 "Any Library Proposal (Revision 3)". * * @{ */ #define __cpp_lib_experimental_any 201411 /** * @brief Exception class thrown by a failed @c any_cast * @ingroup exceptions */ class bad_any_cast : public bad_cast { public: virtual const char* what() const noexcept { return "bad any_cast"; } }; [[gnu::noreturn]] inline void __throw_bad_any_cast() { #if __cpp_exceptions throw bad_any_cast{}; #else __builtin_abort(); #endif } /** * @brief A type-safe container of any type. * * An @c any object's state is either empty or it stores a contained object * of CopyConstructible type. */ class any { // Holds either pointer to a heap object or the contained object itself. union _Storage { // This constructor intentionally doesn't initialize anything. _Storage() = default; // Prevent trivial copies of this type, buffer might hold a non-POD. _Storage(const _Storage&) = delete; _Storage& operator=(const _Storage&) = delete; void* _M_ptr; aligned_storage::type _M_buffer; }; template, bool _Fits = (sizeof(_Tp) <= sizeof(_Storage)) && (alignof(_Tp) <= alignof(_Storage))> using _Internal = std::integral_constant; template struct _Manager_internal; // uses small-object optimization template struct _Manager_external; // creates contained object on the heap template using _Manager = conditional_t<_Internal<_Tp>::value, _Manager_internal<_Tp>, _Manager_external<_Tp>>; template> using _Decay = enable_if_t::value, _Decayed>; public: // construct/destruct /// Default constructor, creates an empty object. any() noexcept : _M_manager(nullptr) { } /// Copy constructor, copies the state of @p __other any(const any& __other) { if (__other.empty()) _M_manager = nullptr; else { _Arg __arg; __arg._M_any = this; __other._M_manager(_Op_clone, &__other, &__arg); } } /** * @brief Move constructor, transfer the state from @p __other * * @post @c __other.empty() (this postcondition is a GNU extension) */ any(any&& __other) noexcept { if (__other.empty()) _M_manager = nullptr; else { _Arg __arg; __arg._M_any = this; __other._M_manager(_Op_xfer, &__other, &__arg); } } /// Construct with a copy of @p __value as the contained object. template , typename _Mgr = _Manager<_Tp>, typename enable_if::value, bool>::type = true> any(_ValueType&& __value) : _M_manager(&_Mgr::_S_manage) { _Mgr::_S_create(_M_storage, std::forward<_ValueType>(__value)); static_assert(is_copy_constructible<_Tp>::value, "The contained object must be CopyConstructible"); } /// Construct with a copy of @p __value as the contained object. template , typename _Mgr = _Manager<_Tp>, typename enable_if::value, bool>::type = false> any(_ValueType&& __value) : _M_manager(&_Mgr::_S_manage) { _Mgr::_S_create(_M_storage, __value); static_assert(is_copy_constructible<_Tp>::value, "The contained object must be CopyConstructible"); } /// Destructor, calls @c clear() ~any() { clear(); } // assignments /// Copy the state of another object. any& operator=(const any& __rhs) { *this = any(__rhs); return *this; } /** * @brief Move assignment operator * * @post @c __rhs.empty() (not guaranteed for other implementations) */ any& operator=(any&& __rhs) noexcept { if (__rhs.empty()) clear(); else if (this != &__rhs) { clear(); _Arg __arg; __arg._M_any = this; __rhs._M_manager(_Op_xfer, &__rhs, &__arg); } return *this; } /// Store a copy of @p __rhs as the contained object. template enable_if_t>::value, any&> operator=(_ValueType&& __rhs) { *this = any(std::forward<_ValueType>(__rhs)); return *this; } // modifiers /// If not empty, destroy the contained object. void clear() noexcept { if (!empty()) { _M_manager(_Op_destroy, this, nullptr); _M_manager = nullptr; } } /// Exchange state with another object. void swap(any& __rhs) noexcept { if (empty() && __rhs.empty()) return; if (!empty() && !__rhs.empty()) { if (this == &__rhs) return; any __tmp; _Arg __arg; __arg._M_any = &__tmp; __rhs._M_manager(_Op_xfer, &__rhs, &__arg); __arg._M_any = &__rhs; _M_manager(_Op_xfer, this, &__arg); __arg._M_any = this; __tmp._M_manager(_Op_xfer, &__tmp, &__arg); } else { any* __empty = empty() ? this : &__rhs; any* __full = empty() ? &__rhs : this; _Arg __arg; __arg._M_any = __empty; __full->_M_manager(_Op_xfer, __full, &__arg); } } // observers /// Reports whether there is a contained object or not. bool empty() const noexcept { return _M_manager == nullptr; } #if __cpp_rtti /// The @c typeid of the contained object, or @c typeid(void) if empty. const type_info& type() const noexcept { if (empty()) return typeid(void); _Arg __arg; _M_manager(_Op_get_type_info, this, &__arg); return *__arg._M_typeinfo; } #endif template static constexpr bool __is_valid_cast() { return __or_, is_copy_constructible<_Tp>>::value; } private: enum _Op { _Op_access, _Op_get_type_info, _Op_clone, _Op_destroy, _Op_xfer }; union _Arg { void* _M_obj; const std::type_info* _M_typeinfo; any* _M_any; }; void (*_M_manager)(_Op, const any*, _Arg*); _Storage _M_storage; template friend enable_if_t::value, void*> __any_caster(const any* __any); // Manage in-place contained object. template struct _Manager_internal { static void _S_manage(_Op __which, const any* __anyp, _Arg* __arg); template static void _S_create(_Storage& __storage, _Up&& __value) { void* __addr = &__storage._M_buffer; ::new (__addr) _Tp(std::forward<_Up>(__value)); } }; // Manage external contained object. template struct _Manager_external { static void _S_manage(_Op __which, const any* __anyp, _Arg* __arg); template static void _S_create(_Storage& __storage, _Up&& __value) { __storage._M_ptr = new _Tp(std::forward<_Up>(__value)); } }; }; /// Exchange the states of two @c any objects. inline void swap(any& __x, any& __y) noexcept { __x.swap(__y); } /** * @brief Access the contained object. * * @tparam _ValueType A const-reference or CopyConstructible type. * @param __any The object to access. * @return The contained object. * @throw bad_any_cast If * __any.type() != typeid(remove_reference_t<_ValueType>) * */ template inline _ValueType any_cast(const any& __any) { static_assert(any::__is_valid_cast<_ValueType>(), "Template argument must be a reference or CopyConstructible type"); auto __p = any_cast>>(&__any); if (__p) return *__p; __throw_bad_any_cast(); } /** * @brief Access the contained object. * * @tparam _ValueType A reference or CopyConstructible type. * @param __any The object to access. * @return The contained object. * @throw bad_any_cast If * __any.type() != typeid(remove_reference_t<_ValueType>) * * * @{ */ template inline _ValueType any_cast(any& __any) { static_assert(any::__is_valid_cast<_ValueType>(), "Template argument must be a reference or CopyConstructible type"); auto __p = any_cast>(&__any); if (__p) return *__p; __throw_bad_any_cast(); } template::value || is_lvalue_reference<_ValueType>::value, bool>::type = true> inline _ValueType any_cast(any&& __any) { static_assert(any::__is_valid_cast<_ValueType>(), "Template argument must be a reference or CopyConstructible type"); auto __p = any_cast>(&__any); if (__p) return *__p; __throw_bad_any_cast(); } template::value && !is_lvalue_reference<_ValueType>::value, bool>::type = false> inline _ValueType any_cast(any&& __any) { static_assert(any::__is_valid_cast<_ValueType>(), "Template argument must be a reference or CopyConstructible type"); auto __p = any_cast>(&__any); if (__p) return std::move(*__p); __throw_bad_any_cast(); } // @} /// @cond undocumented template enable_if_t::value, void*> __any_caster(const any* __any) { // any_cast returns non-null if __any->type() == typeid(T) and // typeid(T) ignores cv-qualifiers so remove them: using _Up = remove_cv_t<_Tp>; // The contained value has a decayed type, so if decay_t is not U, // then it's not possible to have a contained value of type U. using __does_not_decay = is_same, _Up>; // Only copy constructible types can be used for contained values. using __is_copyable = is_copy_constructible<_Up>; // If the type _Tp could never be stored in an any we don't want to // instantiate _Manager<_Tp>, so use _Manager instead, which // is explicitly specialized and has a no-op _S_manage function. using _Vp = conditional_t<__and_<__does_not_decay, __is_copyable>::value, _Up, any::_Op>; // First try comparing function addresses, which works without RTTI if (__any->_M_manager == &any::_Manager<_Vp>::_S_manage #if __cpp_rtti || __any->type() == typeid(_Tp) #endif ) { any::_Arg __arg; __any->_M_manager(any::_Op_access, __any, &__arg); return __arg._M_obj; } return nullptr; } // This overload exists so that std::any_cast(a) is well-formed. template enable_if_t::value, _Tp*> __any_caster(const any*) noexcept { return nullptr; } /// @endcond /** * @brief Access the contained object. * * @tparam _ValueType The type of the contained object. * @param __any A pointer to the object to access. * @return The address of the contained object if * __any != nullptr && __any.type() == typeid(_ValueType) * , otherwise a null pointer. * * @{ */ template inline const _ValueType* any_cast(const any* __any) noexcept { if (__any) return static_cast<_ValueType*>(__any_caster<_ValueType>(__any)); return nullptr; } template inline _ValueType* any_cast(any* __any) noexcept { if (__any) return static_cast<_ValueType*>(__any_caster<_ValueType>(__any)); return nullptr; } // @} template void any::_Manager_internal<_Tp>:: _S_manage(_Op __which, const any* __any, _Arg* __arg) { // The contained object is in _M_storage._M_buffer auto __ptr = reinterpret_cast(&__any->_M_storage._M_buffer); switch (__which) { case _Op_access: __arg->_M_obj = const_cast<_Tp*>(__ptr); break; case _Op_get_type_info: #if __cpp_rtti __arg->_M_typeinfo = &typeid(_Tp); #endif break; case _Op_clone: ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp(*__ptr); __arg->_M_any->_M_manager = __any->_M_manager; break; case _Op_destroy: __ptr->~_Tp(); break; case _Op_xfer: ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp (std::move(*const_cast<_Tp*>(__ptr))); __ptr->~_Tp(); __arg->_M_any->_M_manager = __any->_M_manager; const_cast(__any)->_M_manager = nullptr; break; } } template void any::_Manager_external<_Tp>:: _S_manage(_Op __which, const any* __any, _Arg* __arg) { // The contained object is *_M_storage._M_ptr auto __ptr = static_cast(__any->_M_storage._M_ptr); switch (__which) { case _Op_access: __arg->_M_obj = const_cast<_Tp*>(__ptr); break; case _Op_get_type_info: #if __cpp_rtti __arg->_M_typeinfo = &typeid(_Tp); #endif break; case _Op_clone: __arg->_M_any->_M_storage._M_ptr = new _Tp(*__ptr); __arg->_M_any->_M_manager = __any->_M_manager; break; case _Op_destroy: delete __ptr; break; case _Op_xfer: __arg->_M_any->_M_storage._M_ptr = __any->_M_storage._M_ptr; __arg->_M_any->_M_manager = __any->_M_manager; const_cast(__any)->_M_manager = nullptr; break; } } // Dummy specialization used by __any_caster. template<> struct any::_Manager_internal { static void _S_manage(_Op, const any*, _Arg*) { } }; // @} group any } // namespace fundamentals_v1 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_ANY PK!Xe 8/experimental/arraynu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/array * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_ARRAY #define _GLIBCXX_EXPERIMENTAL_ARRAY 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { #define __cpp_lib_experimental_make_array 201505 /** * @defgroup make_array Array creation functions * @ingroup experimental * * Array creation functions as described in N4529, * Working Draft, C++ Extensions for Library Fundamentals, Version 2 * * @{ */ template struct __make_array_elem { using type = _Dest; }; template struct __make_array_elem : common_type<_Types...> { template struct __is_reference_wrapper : false_type {}; template struct __is_reference_wrapper> : true_type {}; static_assert(!__or_<__is_reference_wrapper>...>::value, "make_array must be used with an explicit target type when" "any of the arguments is a reference_wrapper"); }; template constexpr array::type, sizeof...(_Types)> make_array(_Types&&... __t) { return {{ std::forward<_Types>(__t)... }}; } template constexpr array, _Nm> __to_array(_Tp (&__a)[_Nm], index_sequence<_Idx...>) { return {{__a[_Idx]...}}; } template constexpr array, _Nm> to_array(_Tp (&__a)[_Nm]) noexcept(is_nothrow_constructible, _Tp&>::value) { return __to_array(__a, make_index_sequence<_Nm>{}); } // @} group make_array } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_ARRAY PK!88/experimental/chrononu[// Variable Templates For chrono -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/chrono * This is a TS C++ Library header. */ // // N3932 Variable Templates For Type Traits (Revision 1) // #ifndef _GLIBCXX_EXPERIMENTAL_CHRONO #define _GLIBCXX_EXPERIMENTAL_CHRONO 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace chrono { namespace experimental { inline namespace fundamentals_v1 { // See C++14 §20.12.4, customization traits template constexpr bool treat_as_floating_point_v = treat_as_floating_point<_Rep>::value; } // namespace fundamentals_v1 } // namespace experimental } // namespace chrono _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // __cplusplus <= 201103L #endif // _GLIBCXX_EXPERIMENTAL_CHRONO PK!y+8/experimental/dequenu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/deque * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_DEQUE #define _GLIBCXX_EXPERIMENTAL_DEQUE 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { template void erase_if(deque<_Tp, _Alloc>& __cont, _Predicate __pred) { __cont.erase(std::remove_if(__cont.begin(), __cont.end(), __pred), __cont.end()); } template void erase(deque<_Tp, _Alloc>& __cont, const _Up& __value) { __cont.erase(std::remove(__cont.begin(), __cont.end(), __value), __cont.end()); } namespace pmr { template using deque = std::deque<_Tp, polymorphic_allocator<_Tp>>; } // namespace pmr } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_DEQUE PK!*jZ8/experimental/filesystemnu[// -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/filesystem * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_FILESYSTEM #define _GLIBCXX_EXPERIMENTAL_FILESYSTEM 1 #pragma GCC system_header #if __cplusplus >= 201103L #include #include #include #include #define __cpp_lib_experimental_filesystem 201406 #endif // C++11 #endif // _GLIBCXX_EXPERIMENTAL_FILESYSTEM PK!5 8/experimental/forward_listnu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/forward_list * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_FORWARD_LIST #define _GLIBCXX_EXPERIMENTAL_FORWARD_LIST 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { template inline void erase_if(forward_list<_Tp, _Alloc>& __cont, _Predicate __pred) { __cont.remove_if(__pred); } template inline void erase(forward_list<_Tp, _Alloc>& __cont, const _Up& __value) { using __elem_type = typename forward_list<_Tp, _Alloc>::value_type; erase_if(__cont, [&](__elem_type& __elem) { return __elem == __value; }); } namespace pmr { template using forward_list = std::forward_list<_Tp, polymorphic_allocator<_Tp>>; } // namespace pmr } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_FORWARD_LIST PK![008/experimental/functionalnu[// -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/functional * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_FUNCTIONAL #define _GLIBCXX_EXPERIMENTAL_FUNCTIONAL 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include #include #include #include #include #ifdef _GLIBCXX_PARALLEL # include // For std::__parallel::search #endif #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v1 { // See C++14 §20.9.9, Function object binders /// Variable template for std::is_bind_expression template constexpr bool is_bind_expression_v = std::is_bind_expression<_Tp>::value; /// Variable template for std::is_placeholder template constexpr int is_placeholder_v = std::is_placeholder<_Tp>::value; #define __cpp_lib_experimental_boyer_moore_searching 201411 // Searchers template> class default_searcher { public: default_searcher(_ForwardIterator1 __pat_first, _ForwardIterator1 __pat_last, _BinaryPredicate __pred = _BinaryPredicate()) : _M_m(__pat_first, __pat_last, std::move(__pred)) { } template _ForwardIterator2 operator()(_ForwardIterator2 __first, _ForwardIterator2 __last) const { return std::search(__first, __last, std::get<0>(_M_m), std::get<1>(_M_m), std::get<2>(_M_m)); } private: std::tuple<_ForwardIterator1, _ForwardIterator1, _BinaryPredicate> _M_m; }; template struct __boyer_moore_map_base { template __boyer_moore_map_base(_RAIter __pat, size_t __patlen, _Hash&& __hf, _Pred&& __pred) : _M_bad_char{ __patlen, std::move(__hf), std::move(__pred) } { if (__patlen > 0) for (__diff_type __i = 0; __i < __patlen - 1; ++__i) _M_bad_char[__pat[__i]] = __patlen - 1 - __i; } using __diff_type = _Tp; __diff_type _M_lookup(_Key __key, __diff_type __not_found) const { auto __iter = _M_bad_char.find(__key); if (__iter == _M_bad_char.end()) return __not_found; return __iter->second; } _Pred _M_pred() const { return _M_bad_char.key_eq(); } _GLIBCXX_STD_C::unordered_map<_Key, _Tp, _Hash, _Pred> _M_bad_char; }; template struct __boyer_moore_array_base { template __boyer_moore_array_base(_RAIter __pat, size_t __patlen, _Unused&&, _Pred&& __pred) : _M_bad_char{ _GLIBCXX_STD_C::array<_Tp, _Len>{}, std::move(__pred) } { std::get<0>(_M_bad_char).fill(__patlen); if (__patlen > 0) for (__diff_type __i = 0; __i < __patlen - 1; ++__i) { auto __ch = __pat[__i]; using _UCh = std::make_unsigned_t; auto __uch = static_cast<_UCh>(__ch); std::get<0>(_M_bad_char)[__uch] = __patlen - 1 - __i; } } using __diff_type = _Tp; template __diff_type _M_lookup(_Key __key, __diff_type __not_found) const { auto __ukey = static_cast>(__key); if (__ukey >= _Len) return __not_found; return std::get<0>(_M_bad_char)[__ukey]; } const _Pred& _M_pred() const { return std::get<1>(_M_bad_char); } std::tuple<_GLIBCXX_STD_C::array<_Tp, _Len>, _Pred> _M_bad_char; }; // Use __boyer_moore_array_base when pattern consists of narrow characters // (or std::byte) and uses std::equal_to as the predicate. template::value_type, typename _Diff = typename iterator_traits<_RAIter>::difference_type> using __boyer_moore_base_t = std::conditional_t::value, __boyer_moore_array_base<_Diff, 256, _Pred>, __boyer_moore_map_base<_Val, _Diff, _Hash, _Pred>>; template::value_type>, typename _BinaryPredicate = std::equal_to<>> class boyer_moore_searcher : __boyer_moore_base_t<_RAIter, _Hash, _BinaryPredicate> { using _Base = __boyer_moore_base_t<_RAIter, _Hash, _BinaryPredicate>; using typename _Base::__diff_type; public: boyer_moore_searcher(_RAIter __pat_first, _RAIter __pat_last, _Hash __hf = _Hash(), _BinaryPredicate __pred = _BinaryPredicate()); template _RandomAccessIterator2 operator()(_RandomAccessIterator2 __first, _RandomAccessIterator2 __last) const; private: bool _M_is_prefix(_RAIter __word, __diff_type __len, __diff_type __pos) { const auto& __pred = this->_M_pred(); __diff_type __suffixlen = __len - __pos; for (__diff_type __i = 0; __i < __suffixlen; ++__i) if (!__pred(__word[__i], __word[__pos + __i])) return false; return true; } __diff_type _M_suffix_length(_RAIter __word, __diff_type __len, __diff_type __pos) { const auto& __pred = this->_M_pred(); __diff_type __i = 0; while (__pred(__word[__pos - __i], __word[__len - 1 - __i]) && __i < __pos) { ++__i; } return __i; } template __diff_type _M_bad_char_shift(_Tp __c) const { return this->_M_lookup(__c, _M_pat_end - _M_pat); } _RAIter _M_pat; _RAIter _M_pat_end; _GLIBCXX_STD_C::vector<__diff_type> _M_good_suffix; }; template::value_type>, typename _BinaryPredicate = std::equal_to<>> class boyer_moore_horspool_searcher : __boyer_moore_base_t<_RAIter, _Hash, _BinaryPredicate> { using _Base = __boyer_moore_base_t<_RAIter, _Hash, _BinaryPredicate>; using typename _Base::__diff_type; public: boyer_moore_horspool_searcher(_RAIter __pat, _RAIter __pat_end, _Hash __hf = _Hash(), _BinaryPredicate __pred = _BinaryPredicate()) : _Base(__pat, __pat_end - __pat, std::move(__hf), std::move(__pred)), _M_pat(__pat), _M_pat_end(__pat_end) { } template _RandomAccessIterator2 operator()(_RandomAccessIterator2 __first, _RandomAccessIterator2 __last) const { const auto& __pred = this->_M_pred(); auto __patlen = _M_pat_end - _M_pat; if (__patlen == 0) return __first; auto __len = __last - __first; while (__len >= __patlen) { for (auto __scan = __patlen - 1; __pred(__first[__scan], _M_pat[__scan]); --__scan) if (__scan == 0) return __first; auto __shift = _M_bad_char_shift(__first[__patlen - 1]); __len -= __shift; __first += __shift; } return __last; } private: template __diff_type _M_bad_char_shift(_Tp __c) const { return this->_M_lookup(__c, _M_pat_end - _M_pat); } _RAIter _M_pat; _RAIter _M_pat_end; }; /// Generator function for default_searcher template> inline default_searcher<_ForwardIterator, _BinaryPredicate> make_default_searcher(_ForwardIterator __pat_first, _ForwardIterator __pat_last, _BinaryPredicate __pred = _BinaryPredicate()) { return { __pat_first, __pat_last, __pred }; } /// Generator function for boyer_moore_searcher template::value_type>, typename _BinaryPredicate = equal_to<>> inline boyer_moore_searcher<_RAIter, _Hash, _BinaryPredicate> make_boyer_moore_searcher(_RAIter __pat_first, _RAIter __pat_last, _Hash __hf = _Hash(), _BinaryPredicate __pred = _BinaryPredicate()) { return { __pat_first, __pat_last, std::move(__hf), std::move(__pred) }; } /// Generator function for boyer_moore_horspool_searcher template::value_type>, typename _BinaryPredicate = equal_to<>> inline boyer_moore_horspool_searcher<_RAIter, _Hash, _BinaryPredicate> make_boyer_moore_horspool_searcher(_RAIter __pat_first, _RAIter __pat_last, _Hash __hf = _Hash(), _BinaryPredicate __pred = _BinaryPredicate()) { return { __pat_first, __pat_last, std::move(__hf), std::move(__pred) }; } template boyer_moore_searcher<_RAIter, _Hash, _BinaryPredicate>:: boyer_moore_searcher(_RAIter __pat, _RAIter __pat_end, _Hash __hf, _BinaryPredicate __pred) : _Base(__pat, __pat_end - __pat, std::move(__hf), std::move(__pred)), _M_pat(__pat), _M_pat_end(__pat_end), _M_good_suffix(__pat_end - __pat) { auto __patlen = __pat_end - __pat; if (__patlen == 0) return; __diff_type __last_prefix = __patlen - 1; for (__diff_type __p = __patlen - 1; __p >= 0; --__p) { if (_M_is_prefix(__pat, __patlen, __p + 1)) __last_prefix = __p + 1; _M_good_suffix[__p] = __last_prefix + (__patlen - 1 - __p); } for (__diff_type __p = 0; __p < __patlen - 1; ++__p) { auto __slen = _M_suffix_length(__pat, __patlen, __p); auto __pos = __patlen - 1 - __slen; if (!__pred(__pat[__p - __slen], __pat[__pos])) _M_good_suffix[__pos] = __patlen - 1 - __p + __slen; } } template template _RandomAccessIterator2 boyer_moore_searcher<_RAIter, _Hash, _BinaryPredicate>:: operator()(_RandomAccessIterator2 __first, _RandomAccessIterator2 __last) const { auto __patlen = _M_pat_end - _M_pat; if (__patlen == 0) return __first; const auto& __pred = this->_M_pred(); __diff_type __i = __patlen - 1; auto __stringlen = __last - __first; while (__i < __stringlen) { __diff_type __j = __patlen - 1; while (__j >= 0 && __pred(__first[__i], _M_pat[__j])) { --__i; --__j; } if (__j < 0) return __first + __i + 1; __i += std::max(_M_bad_char_shift(__first[__i]), _M_good_suffix[__j]); } return __last; } } // namespace fundamentals_v1 inline namespace fundamentals_v2 { #define __cpp_lib_experimental_not_fn 201406 /// [func.not_fn] Function template not_fn template inline auto not_fn(_Fn&& __fn) noexcept(std::is_nothrow_constructible, _Fn&&>::value) { return std::_Not_fn>{std::forward<_Fn>(__fn), 0}; } } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_FUNCTIONAL PK!HәӶ 8/experimental/iteratornu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/iterator * This is a TS C++ Library header. */ // // N4336 Working Draft, C++ Extensions for Library Fundamentals, Version 2 // #ifndef _GLIBCXX_EXPERIMENTAL_ITERATOR #define _GLIBCXX_EXPERIMENTAL_ITERATOR 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { #define __cpp_lib_experimental_ostream_joiner 201411 /// Output iterator that inserts a delimiter between elements. template> class ostream_joiner { public: typedef _CharT char_type; typedef _Traits traits_type; typedef basic_ostream<_CharT, _Traits> ostream_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; ostream_joiner(ostream_type& __os, const _DelimT& __delimiter) noexcept(is_nothrow_copy_constructible_v<_DelimT>) : _M_out(std::__addressof(__os)), _M_delim(__delimiter) { } ostream_joiner(ostream_type& __os, _DelimT&& __delimiter) noexcept(is_nothrow_move_constructible_v<_DelimT>) : _M_out(std::__addressof(__os)), _M_delim(std::move(__delimiter)) { } template ostream_joiner& operator=(const _Tp& __value) { if (!_M_first) *_M_out << _M_delim; _M_first = false; *_M_out << __value; return *this; } ostream_joiner& operator*() noexcept { return *this; } ostream_joiner& operator++() noexcept { return *this; } ostream_joiner& operator++(int) noexcept { return *this; } private: ostream_type* _M_out; _DelimT _M_delim; bool _M_first = true; }; /// Object generator for ostream_joiner. template inline ostream_joiner, _CharT, _Traits> make_ostream_joiner(basic_ostream<_CharT, _Traits>& __os, _DelimT&& __delimiter) { return { __os, std::forward<_DelimT>(__delimiter) }; } } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // __cplusplus <= 201103L #endif // _GLIBCXX_EXPERIMENTAL_ITERATOR PK! -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/list * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_LIST #define _GLIBCXX_EXPERIMENTAL_LIST 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { template inline void erase_if(list<_Tp, _Alloc>& __cont, _Predicate __pred) { __cont.remove_if(__pred); } template inline void erase(list<_Tp, _Alloc>& __cont, const _Up& __value) { using __elem_type = typename list<_Tp, _Alloc>::value_type; erase_if(__cont, [&](__elem_type& __elem) { return __elem == __value; }); } namespace pmr { template using list = std::list<_Tp, polymorphic_allocator<_Tp>>; } // namespace pmr } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_LIST PK!] 8/experimental/mapnu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/map * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_MAP #define _GLIBCXX_EXPERIMENTAL_MAP 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { template inline void erase_if(map<_Key, _Tp, _Compare, _Alloc>& __cont, _Predicate __pred) { __detail::__erase_nodes_if(__cont, __pred); } template inline void erase_if(multimap<_Key, _Tp, _Compare, _Alloc>& __cont, _Predicate __pred) { __detail::__erase_nodes_if(__cont, __pred); } namespace pmr { template> using map = std::map<_Key, _Tp, _Compare, polymorphic_allocator>>; template> using multimap = std::multimap<_Key, _Tp, _Compare, polymorphic_allocator>>; } // namespace pmr } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_MAP PK!hY08/experimental/memorynu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/memory * This is a TS C++ Library header. */ // // N4336 Working Draft, C++ Extensions for Library Fundamentals, Version 2 // #ifndef _GLIBCXX_EXPERIMENTAL_MEMORY #define _GLIBCXX_EXPERIMENTAL_MEMORY 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { #define __cpp_lib_experimental_observer_ptr 201411 template class observer_ptr { public: // publish our template parameter and variations thereof using element_type = _Tp; using __pointer = add_pointer_t<_Tp>; // exposition-only using __reference = add_lvalue_reference_t<_Tp>; // exposition-only // 3.2.2, observer_ptr constructors // default c’tor constexpr observer_ptr() noexcept : __t() { } // pointer-accepting c’tors constexpr observer_ptr(nullptr_t) noexcept : __t() { } constexpr explicit observer_ptr(__pointer __p) noexcept : __t(__p) { } // copying c’tors (in addition to compiler-generated copy c’tor) template ::type, __pointer >::value >::type> constexpr observer_ptr(observer_ptr<_Up> __p) noexcept : __t(__p.get()) { } // 3.2.3, observer_ptr observers constexpr __pointer get() const noexcept { return __t; } constexpr __reference operator*() const { return *get(); } constexpr __pointer operator->() const noexcept { return get(); } constexpr explicit operator bool() const noexcept { return get() != nullptr; } // 3.2.4, observer_ptr conversions constexpr explicit operator __pointer() const noexcept { return get(); } // 3.2.5, observer_ptr modifiers constexpr __pointer release() noexcept { __pointer __tmp = get(); reset(); return __tmp; } constexpr void reset(__pointer __p = nullptr) noexcept { __t = __p; } constexpr void swap(observer_ptr& __p) noexcept { std::swap(__t, __p.__t); } private: __pointer __t; }; // observer_ptr<> template void swap(observer_ptr<_Tp>& __p1, observer_ptr<_Tp>& __p2) noexcept { __p1.swap(__p2); } template observer_ptr<_Tp> make_observer(_Tp* __p) noexcept { return observer_ptr<_Tp>(__p); } template bool operator==(observer_ptr<_Tp> __p1, observer_ptr<_Up> __p2) { return __p1.get() == __p2.get(); } template bool operator!=(observer_ptr<_Tp> __p1, observer_ptr<_Up> __p2) { return !(__p1 == __p2); } template bool operator==(observer_ptr<_Tp> __p, nullptr_t) noexcept { return !__p; } template bool operator==(nullptr_t, observer_ptr<_Tp> __p) noexcept { return !__p; } template bool operator!=(observer_ptr<_Tp> __p, nullptr_t) noexcept { return bool(__p); } template bool operator!=(nullptr_t, observer_ptr<_Tp> __p) noexcept { return bool(__p); } template bool operator<(observer_ptr<_Tp> __p1, observer_ptr<_Up> __p2) { return std::less::type, typename add_pointer<_Up>::type >::type >{}(__p1.get(), __p2.get()); } template bool operator>(observer_ptr<_Tp> __p1, observer_ptr<_Up> __p2) { return __p2 < __p1; } template bool operator<=(observer_ptr<_Tp> __p1, observer_ptr<_Up> __p2) { return !(__p2 < __p1); } template bool operator>=(observer_ptr<_Tp> __p1, observer_ptr<_Up> __p2) { return !(__p1 < __p2); } } // namespace fundamentals_v2 } // namespace experimental template struct hash> { using result_type = size_t; using argument_type = experimental::observer_ptr<_Tp>; size_t operator()(const experimental::observer_ptr<_Tp>& __t) const noexcept(noexcept(hash::type> {}(__t.get()))) { return hash::type> {}(__t.get()); } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // __cplusplus <= 201103L #endif // _GLIBCXX_EXPERIMENTAL_MEMORY PK!h{r2r28/experimental/memory_resourcenu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/memory_resource * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_MEMORY_RESOURCE #define _GLIBCXX_EXPERIMENTAL_MEMORY_RESOURCE 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include #include #include namespace std { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { namespace pmr { #define __cpp_lib_experimental_memory_resources 201402L class memory_resource; template class polymorphic_allocator; template class __resource_adaptor_imp; template using resource_adaptor = __resource_adaptor_imp< typename allocator_traits<_Alloc>::template rebind_alloc>; template struct __uses_allocator_construction_helper; // Global memory resources memory_resource* new_delete_resource() noexcept; memory_resource* null_memory_resource() noexcept; // The default memory resource memory_resource* get_default_resource() noexcept; memory_resource* set_default_resource(memory_resource* __r) noexcept; // Standard memory resources // 8.5 Class memory_resource class memory_resource { protected: static constexpr size_t _S_max_align = alignof(max_align_t); public: virtual ~memory_resource() { } void* allocate(size_t __bytes, size_t __alignment = _S_max_align) { return do_allocate(__bytes, __alignment); } void deallocate(void* __p, size_t __bytes, size_t __alignment = _S_max_align) { return do_deallocate(__p, __bytes, __alignment); } bool is_equal(const memory_resource& __other) const noexcept { return do_is_equal(__other); } protected: virtual void* do_allocate(size_t __bytes, size_t __alignment) = 0; virtual void do_deallocate(void* __p, size_t __bytes, size_t __alignment) = 0; virtual bool do_is_equal(const memory_resource& __other) const noexcept = 0; }; inline bool operator==(const memory_resource& __a, const memory_resource& __b) noexcept { return &__a == &__b || __a.is_equal(__b); } inline bool operator!=(const memory_resource& __a, const memory_resource& __b) noexcept { return !(__a == __b); } // 8.6 Class template polymorphic_allocator template class polymorphic_allocator { using __uses_alloc1_ = __uses_alloc1; using __uses_alloc2_ = __uses_alloc2; template void _M_construct(__uses_alloc0, _Tp1* __p, _Args&&... __args) { ::new(__p) _Tp1(std::forward<_Args>(__args)...); } template void _M_construct(__uses_alloc1_, _Tp1* __p, _Args&&... __args) { ::new(__p) _Tp1(allocator_arg, this->resource(), std::forward<_Args>(__args)...); } template void _M_construct(__uses_alloc2_, _Tp1* __p, _Args&&... __args) { ::new(__p) _Tp1(std::forward<_Args>(__args)..., this->resource()); } public: using value_type = _Tp; polymorphic_allocator() noexcept : _M_resource(get_default_resource()) { } polymorphic_allocator(memory_resource* __r) : _M_resource(__r) { _GLIBCXX_DEBUG_ASSERT(__r); } polymorphic_allocator(const polymorphic_allocator& __other) = default; template polymorphic_allocator(const polymorphic_allocator<_Up>& __other) noexcept : _M_resource(__other.resource()) { } polymorphic_allocator& operator=(const polymorphic_allocator& __rhs) = default; _Tp* allocate(size_t __n) { return static_cast<_Tp*>(_M_resource->allocate(__n * sizeof(_Tp), alignof(_Tp))); } void deallocate(_Tp* __p, size_t __n) { _M_resource->deallocate(__p, __n * sizeof(_Tp), alignof(_Tp)); } template //used here void construct(_Tp1* __p, _Args&&... __args) { memory_resource* const __resource = this->resource(); auto __use_tag = __use_alloc<_Tp1, memory_resource*, _Args...>(__resource); _M_construct(__use_tag, __p, std::forward<_Args>(__args)...); } // Specializations for pair using piecewise construction template void construct(pair<_Tp1, _Tp2>* __p, piecewise_construct_t, tuple<_Args1...> __x, tuple<_Args2...> __y) { memory_resource* const __resource = this->resource(); auto __x_use_tag = __use_alloc<_Tp1, memory_resource*, _Args1...>(__resource); auto __y_use_tag = __use_alloc<_Tp2, memory_resource*, _Args2...>(__resource); ::new(__p) std::pair<_Tp1, _Tp2>(piecewise_construct, _M_construct_p(__x_use_tag, __x), _M_construct_p(__y_use_tag, __y)); } template void construct(pair<_Tp1,_Tp2>* __p) { this->construct(__p, piecewise_construct, tuple<>(), tuple<>()); } template void construct(pair<_Tp1,_Tp2>* __p, _Up&& __x, _Vp&& __y) { this->construct(__p, piecewise_construct, forward_as_tuple(std::forward<_Up>(__x)), forward_as_tuple(std::forward<_Vp>(__y))); } template void construct(pair<_Tp1,_Tp2>* __p, const std::pair<_Up, _Vp>& __pr) { this->construct(__p, piecewise_construct, forward_as_tuple(__pr.first), forward_as_tuple(__pr.second)); } template void construct(pair<_Tp1,_Tp2>* __p, pair<_Up, _Vp>&& __pr) { this->construct(__p, piecewise_construct, forward_as_tuple(std::forward<_Up>(__pr.first)), forward_as_tuple(std::forward<_Vp>(__pr.second))); } template void destroy(_Up* __p) { __p->~_Up(); } // Return a default-constructed allocator (no allocator propagation) polymorphic_allocator select_on_container_copy_construction() const { return polymorphic_allocator(); } memory_resource* resource() const { return _M_resource; } private: template _Tuple&& _M_construct_p(__uses_alloc0, _Tuple& __t) { return std::move(__t); } template decltype(auto) _M_construct_p(__uses_alloc1_ __ua, tuple<_Args...>& __t) { return tuple_cat(make_tuple(allocator_arg, *(__ua._M_a)), std::move(__t)); } template decltype(auto) _M_construct_p(__uses_alloc2_ __ua, tuple<_Args...>& __t) { return tuple_cat(std::move(__t), make_tuple(*(__ua._M_a))); } memory_resource* _M_resource; }; template bool operator==(const polymorphic_allocator<_Tp1>& __a, const polymorphic_allocator<_Tp2>& __b) noexcept { return *__a.resource() == *__b.resource(); } template bool operator!=(const polymorphic_allocator<_Tp1>& __a, const polymorphic_allocator<_Tp2>& __b) noexcept { return !(__a == __b); } // 8.7.1 __resource_adaptor_imp template class __resource_adaptor_imp : public memory_resource { static_assert(is_same::value_type>::value, "Allocator's value_type is char"); static_assert(is_same::pointer>::value, "Allocator's pointer type is value_type*"); static_assert(is_same::const_pointer>::value, "Allocator's const_pointer type is value_type const*"); static_assert(is_same::void_pointer>::value, "Allocator's void_pointer type is void*"); static_assert(is_same::const_void_pointer>::value, "Allocator's const_void_pointer type is void const*"); public: using allocator_type = _Alloc; __resource_adaptor_imp() = default; __resource_adaptor_imp(const __resource_adaptor_imp&) = default; __resource_adaptor_imp(__resource_adaptor_imp&&) = default; explicit __resource_adaptor_imp(const _Alloc& __a2) : _M_alloc(__a2) { } explicit __resource_adaptor_imp(_Alloc&& __a2) : _M_alloc(std::move(__a2)) { } __resource_adaptor_imp& operator=(const __resource_adaptor_imp&) = default; allocator_type get_allocator() const noexcept { return _M_alloc; } protected: virtual void* do_allocate(size_t __bytes, size_t __alignment) { using _Aligned_alloc = std::__alloc_rebind<_Alloc, char>; size_t __new_size = _S_aligned_size(__bytes, _S_supported(__alignment) ? __alignment : _S_max_align); return _Aligned_alloc(_M_alloc).allocate(__new_size); } virtual void do_deallocate(void* __p, size_t __bytes, size_t __alignment) { using _Aligned_alloc = std::__alloc_rebind<_Alloc, char>; size_t __new_size = _S_aligned_size(__bytes, _S_supported(__alignment) ? __alignment : _S_max_align); using _Ptr = typename allocator_traits<_Aligned_alloc>::pointer; _Aligned_alloc(_M_alloc).deallocate(static_cast<_Ptr>(__p), __new_size); } virtual bool do_is_equal(const memory_resource& __other) const noexcept { auto __p = dynamic_cast(&__other); return __p ? (_M_alloc == __p->_M_alloc) : false; } private: // Calculate Aligned Size // Returns a size that is larger than or equal to __size and divisible // by __alignment, where __alignment is required to be a power of 2. static size_t _S_aligned_size(size_t __size, size_t __alignment) { return ((__size - 1)|(__alignment - 1)) + 1; } // Determine whether alignment meets one of those preconditions: // 1. Equal to Zero // 2. Is power of two static bool _S_supported (size_t __x) { return ((__x != 0) && !(__x & (__x - 1))); } _Alloc _M_alloc; }; // Global memory resources inline memory_resource* new_delete_resource() noexcept { using type = resource_adaptor>; alignas(type) static unsigned char __buf[sizeof(type)]; static type* __r = new(__buf) type; return __r; } inline memory_resource* null_memory_resource() noexcept { class type final : public memory_resource { void* do_allocate(size_t, size_t) override { std::__throw_bad_alloc(); } void do_deallocate(void*, size_t, size_t) noexcept override { } bool do_is_equal(const memory_resource& __other) const noexcept override { return this == &__other; } }; alignas(type) static unsigned char __buf[sizeof(type)]; static type* __r = new(__buf) type; return __r; } // The default memory resource inline std::atomic& __get_default_resource() { using type = atomic; alignas(type) static unsigned char __buf[sizeof(type)]; static type* __r = new(__buf) type(new_delete_resource()); return *__r; } inline memory_resource* get_default_resource() noexcept { return __get_default_resource().load(); } inline memory_resource* set_default_resource(memory_resource* __r) noexcept { if (__r == nullptr) __r = new_delete_resource(); return __get_default_resource().exchange(__r); } } // namespace pmr } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_MEMORY_RESOURCE PK!(:I{ { 8/experimental/numericnu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/numeric * This is a TS C++ Library header. */ // // N4336 Working Draft, C++ Extensions for Library Fundamentals, Version 2 // #ifndef _GLIBCXX_EXPERIMENTAL_NUMERIC #define _GLIBCXX_EXPERIMENTAL_NUMERIC 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { #define __cpp_lib_experimental_gcd_lcm 201411 /// Greatest common divisor template constexpr common_type_t<_Mn, _Nn> gcd(_Mn __m, _Nn __n) noexcept { static_assert(is_integral_v<_Mn>, "std::experimental::gcd arguments must be integers"); static_assert(is_integral_v<_Nn>, "std::experimental::gcd arguments must be integers"); static_assert(_Mn(2) != _Mn(1), "std::experimental::gcd arguments must not be bool"); static_assert(_Nn(2) != _Nn(1), "std::experimental::gcd arguments must not be bool"); using _Up = make_unsigned_t>; return std::__detail::__gcd(std::__detail::__absu<_Up>(__m), std::__detail::__absu<_Up>(__n)); } /// Least common multiple template constexpr common_type_t<_Mn, _Nn> lcm(_Mn __m, _Nn __n) { static_assert(is_integral_v<_Mn>, "std::experimental::lcm arguments must be integers"); static_assert(is_integral_v<_Nn>, "std::experimental::lcm arguments must be integers"); static_assert(_Mn(2) != _Mn(1), "std::experimental::lcm arguments must not be bool"); static_assert(_Nn(2) != _Nn(1), "std::experimental::lcm arguments must not be bool"); using _Up = make_unsigned_t>; return std::__detail::__lcm(std::__detail::__absu<_Up>(__m), std::__detail::__absu<_Up>(__n)); } } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // __cplusplus <= 201103L #endif // _GLIBCXX_EXPERIMENTAL_NUMERIC PK!#6pp8/experimental/optionalnu[// -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/optional * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_OPTIONAL #define _GLIBCXX_EXPERIMENTAL_OPTIONAL 1 /** * @defgroup experimental Experimental * * Components specified by various Technical Specifications. * * As indicated by the std::experimental namespace and the header paths, * the contents of these Technical Specifications are experimental and not * part of the C++ standard. As such the interfaces and implementations may * change in the future, and there is no guarantee of compatibility * between different GCC releases for these features. */ #if __cplusplus >= 201402L #include #include #include #include #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v1 { /** * @defgroup optional Optional values * @ingroup experimental * * Class template for optional values and surrounding facilities, as * described in n3793 "A proposal to add a utility class to represent * optional objects (Revision 5)". * * @{ */ #define __cpp_lib_experimental_optional 201411 // All subsequent [X.Y.n] references are against n3793. // [X.Y.4] template class optional; // [X.Y.5] /// Tag type for in-place construction. struct in_place_t { }; /// Tag for in-place construction. constexpr in_place_t in_place { }; // [X.Y.6] /// Tag type to disengage optional objects. struct nullopt_t { // Do not user-declare default constructor at all for // optional_value = {} syntax to work. // nullopt_t() = delete; // Used for constructing nullopt. enum class _Construct { _Token }; // Must be constexpr for nullopt_t to be literal. explicit constexpr nullopt_t(_Construct) { } }; // [X.Y.6] /// Tag to disengage optional objects. constexpr nullopt_t nullopt { nullopt_t::_Construct::_Token }; // [X.Y.7] /** * @brief Exception class thrown when a disengaged optional object is * dereferenced. * @ingroup exceptions */ class bad_optional_access : public logic_error { public: bad_optional_access() : logic_error("bad optional access") { } // XXX This constructor is non-standard. Should not be inline explicit bad_optional_access(const char* __arg) : logic_error(__arg) { } virtual ~bad_optional_access() noexcept = default; }; void __throw_bad_optional_access(const char*) __attribute__((__noreturn__)); // XXX Does not belong here. inline void __throw_bad_optional_access(const char* __s) { _GLIBCXX_THROW_OR_ABORT(bad_optional_access(__s)); } #ifndef __cpp_lib_addressof_constexpr template struct _Has_addressof_mem : std::false_type { }; template struct _Has_addressof_mem<_Tp, __void_t().operator&() )> > : std::true_type { }; template struct _Has_addressof_free : std::false_type { }; template struct _Has_addressof_free<_Tp, __void_t()) )> > : std::true_type { }; /** * @brief Trait that detects the presence of an overloaded unary operator&. * * Practically speaking this detects the presence of such an operator when * called on a const-qualified lvalue (e.g. * declval().operator&()). */ template struct _Has_addressof : std::__or_<_Has_addressof_mem<_Tp>, _Has_addressof_free<_Tp>>::type { }; /** * @brief An overload that attempts to take the address of an lvalue as a * constant expression. Falls back to __addressof in the presence of an * overloaded addressof operator (unary operator&), in which case the call * will not be a constant expression. */ template constexpr enable_if_t::value, _Tp*> __constexpr_addressof(_Tp& __t) { return &__t; } /** * @brief Fallback overload that defers to __addressof. */ template inline enable_if_t<_Has_addressof<_Tp>::value, _Tp*> __constexpr_addressof(_Tp& __t) { return std::__addressof(__t); } #endif // __cpp_lib_addressof_constexpr /** * @brief Class template that holds the necessary state for @ref optional * and that has the responsibility for construction and the special members. * * Such a separate base class template is necessary in order to * conditionally enable the special members (e.g. copy/move constructors). * Note that this means that @ref _Optional_base implements the * functionality for copy and move assignment, but not for converting * assignment. * * @see optional, _Enable_special_members */ template::value> class _Optional_base { private: // Remove const to avoid prohibition of reusing object storage for // const-qualified types in [3.8/9]. This is strictly internal // and even optional itself is oblivious to it. using _Stored_type = remove_const_t<_Tp>; public: // [X.Y.4.1] Constructors. // Constructors for disengaged optionals. constexpr _Optional_base() noexcept : _M_empty{} { } constexpr _Optional_base(nullopt_t) noexcept : _Optional_base{} { } // Constructors for engaged optionals. template constexpr explicit _Optional_base(in_place_t, _Args&&... __args) : _M_payload(std::forward<_Args>(__args)...), _M_engaged(true) { } template&, _Args&&...>::value, int>...> constexpr explicit _Optional_base(in_place_t, initializer_list<_Up> __il, _Args&&... __args) : _M_payload(__il, std::forward<_Args>(__args)...), _M_engaged(true) { } // Copy and move constructors. _Optional_base(const _Optional_base& __other) { if (__other._M_engaged) this->_M_construct(__other._M_get()); } _Optional_base(_Optional_base&& __other) noexcept(is_nothrow_move_constructible<_Tp>()) { if (__other._M_engaged) this->_M_construct(std::move(__other._M_get())); } // [X.Y.4.3] (partly) Assignment. _Optional_base& operator=(const _Optional_base& __other) { if (this->_M_engaged && __other._M_engaged) this->_M_get() = __other._M_get(); else { if (__other._M_engaged) this->_M_construct(__other._M_get()); else this->_M_reset(); } return *this; } _Optional_base& operator=(_Optional_base&& __other) noexcept(__and_, is_nothrow_move_assignable<_Tp>>()) { if (this->_M_engaged && __other._M_engaged) this->_M_get() = std::move(__other._M_get()); else { if (__other._M_engaged) this->_M_construct(std::move(__other._M_get())); else this->_M_reset(); } return *this; } // [X.Y.4.2] Destructor. ~_Optional_base() { if (this->_M_engaged) this->_M_payload.~_Stored_type(); } // The following functionality is also needed by optional, hence the // protected accessibility. protected: constexpr bool _M_is_engaged() const noexcept { return this->_M_engaged; } // The _M_get operations have _M_engaged as a precondition. constexpr _Tp& _M_get() noexcept { return _M_payload; } constexpr const _Tp& _M_get() const noexcept { return _M_payload; } // The _M_construct operation has !_M_engaged as a precondition // while _M_destruct has _M_engaged as a precondition. template void _M_construct(_Args&&... __args) noexcept(is_nothrow_constructible<_Stored_type, _Args...>()) { ::new (std::__addressof(this->_M_payload)) _Stored_type(std::forward<_Args>(__args)...); this->_M_engaged = true; } void _M_destruct() { this->_M_engaged = false; this->_M_payload.~_Stored_type(); } // _M_reset is a 'safe' operation with no precondition. void _M_reset() { if (this->_M_engaged) this->_M_destruct(); } private: struct _Empty_byte { }; union { _Empty_byte _M_empty; _Stored_type _M_payload; }; bool _M_engaged = false; }; /// Partial specialization that is exactly identical to the primary template /// save for not providing a destructor, to fulfill triviality requirements. template class _Optional_base<_Tp, false> { private: using _Stored_type = remove_const_t<_Tp>; public: constexpr _Optional_base() noexcept : _M_empty{} { } constexpr _Optional_base(nullopt_t) noexcept : _Optional_base{} { } template constexpr explicit _Optional_base(in_place_t, _Args&&... __args) : _M_payload(std::forward<_Args>(__args)...), _M_engaged(true) { } template&, _Args&&...>::value, int>...> constexpr explicit _Optional_base(in_place_t, initializer_list<_Up> __il, _Args&&... __args) : _M_payload(__il, std::forward<_Args>(__args)...), _M_engaged(true) { } _Optional_base(const _Optional_base& __other) { if (__other._M_engaged) this->_M_construct(__other._M_get()); } _Optional_base(_Optional_base&& __other) noexcept(is_nothrow_move_constructible<_Tp>()) { if (__other._M_engaged) this->_M_construct(std::move(__other._M_get())); } _Optional_base& operator=(const _Optional_base& __other) { if (this->_M_engaged && __other._M_engaged) this->_M_get() = __other._M_get(); else { if (__other._M_engaged) this->_M_construct(__other._M_get()); else this->_M_reset(); } return *this; } _Optional_base& operator=(_Optional_base&& __other) noexcept(__and_, is_nothrow_move_assignable<_Tp>>()) { if (this->_M_engaged && __other._M_engaged) this->_M_get() = std::move(__other._M_get()); else { if (__other._M_engaged) this->_M_construct(std::move(__other._M_get())); else this->_M_reset(); } return *this; } // Sole difference // ~_Optional_base() noexcept = default; protected: constexpr bool _M_is_engaged() const noexcept { return this->_M_engaged; } _Tp& _M_get() noexcept { return _M_payload; } constexpr const _Tp& _M_get() const noexcept { return _M_payload; } template void _M_construct(_Args&&... __args) noexcept(is_nothrow_constructible<_Stored_type, _Args...>()) { ::new (std::__addressof(this->_M_payload)) _Stored_type(std::forward<_Args>(__args)...); this->_M_engaged = true; } void _M_destruct() { this->_M_engaged = false; this->_M_payload.~_Stored_type(); } void _M_reset() { if (this->_M_engaged) this->_M_destruct(); } private: struct _Empty_byte { }; union { _Empty_byte _M_empty; _Stored_type _M_payload; }; bool _M_engaged = false; }; template class optional; template using __converts_from_optional = __or_&>, is_constructible<_Tp, optional<_Up>&>, is_constructible<_Tp, const optional<_Up>&&>, is_constructible<_Tp, optional<_Up>&&>, is_convertible&, _Tp>, is_convertible&, _Tp>, is_convertible&&, _Tp>, is_convertible&&, _Tp>>; template using __assigns_from_optional = __or_&>, is_assignable<_Tp&, optional<_Up>&>, is_assignable<_Tp&, const optional<_Up>&&>, is_assignable<_Tp&, optional<_Up>&&>>; /** * @brief Class template for optional values. */ template class optional : private _Optional_base<_Tp>, private _Enable_copy_move< // Copy constructor. is_copy_constructible<_Tp>::value, // Copy assignment. __and_, is_copy_assignable<_Tp>>::value, // Move constructor. is_move_constructible<_Tp>::value, // Move assignment. __and_, is_move_assignable<_Tp>>::value, // Unique tag type. optional<_Tp>> { static_assert(__and_<__not_, nullopt_t>>, __not_, in_place_t>>, __not_>>(), "Invalid instantiation of optional"); private: using _Base = _Optional_base<_Tp>; public: using value_type = _Tp; // _Optional_base has the responsibility for construction. using _Base::_Base; constexpr optional() = default; // Converting constructors for engaged optionals. template , decay_t<_Up>>>, is_constructible<_Tp, _Up&&>, is_convertible<_Up&&, _Tp> >::value, bool> = true> constexpr optional(_Up&& __t) : _Base(in_place, std::forward<_Up>(__t)) { } template , decay_t<_Up>>>, is_constructible<_Tp, _Up&&>, __not_> >::value, bool> = false> explicit constexpr optional(_Up&& __t) : _Base(in_place, std::forward<_Up>(__t)) { } template >, is_constructible<_Tp, const _Up&>, is_convertible, __not_<__converts_from_optional<_Tp, _Up>> >::value, bool> = true> constexpr optional(const optional<_Up>& __t) { if (__t) emplace(*__t); } template >, is_constructible<_Tp, const _Up&>, __not_>, __not_<__converts_from_optional<_Tp, _Up>> >::value, bool> = false> explicit constexpr optional(const optional<_Up>& __t) { if (__t) emplace(*__t); } template >, is_constructible<_Tp, _Up&&>, is_convertible<_Up&&, _Tp>, __not_<__converts_from_optional<_Tp, _Up>> >::value, bool> = true> constexpr optional(optional<_Up>&& __t) { if (__t) emplace(std::move(*__t)); } template >, is_constructible<_Tp, _Up&&>, __not_>, __not_<__converts_from_optional<_Tp, _Up>> >::value, bool> = false> explicit constexpr optional(optional<_Up>&& __t) { if (__t) emplace(std::move(*__t)); } // [X.Y.4.3] (partly) Assignment. optional& operator=(nullopt_t) noexcept { this->_M_reset(); return *this; } template enable_if_t<__and_< __not_, decay_t<_Up>>>, is_constructible<_Tp, _Up>, __not_<__and_, is_same<_Tp, decay_t<_Up>>>>, is_assignable<_Tp&, _Up>>::value, optional&> operator=(_Up&& __u) { if (this->_M_is_engaged()) this->_M_get() = std::forward<_Up>(__u); else this->_M_construct(std::forward<_Up>(__u)); return *this; } template enable_if_t<__and_< __not_>, is_constructible<_Tp, const _Up&>, is_assignable<_Tp&, _Up>, __not_<__converts_from_optional<_Tp, _Up>>, __not_<__assigns_from_optional<_Tp, _Up>> >::value, optional&> operator=(const optional<_Up>& __u) { if (__u) { if (this->_M_is_engaged()) this->_M_get() = *__u; else this->_M_construct(*__u); } else { this->_M_reset(); } return *this; } template enable_if_t<__and_< __not_>, is_constructible<_Tp, _Up>, is_assignable<_Tp&, _Up>, __not_<__converts_from_optional<_Tp, _Up>>, __not_<__assigns_from_optional<_Tp, _Up>> >::value, optional&> operator=(optional<_Up>&& __u) { if (__u) { if (this->_M_is_engaged()) this->_M_get() = std::move(*__u); else this->_M_construct(std::move(*__u)); } else { this->_M_reset(); } return *this; } template enable_if_t::value> emplace(_Args&&... __args) { this->_M_reset(); this->_M_construct(std::forward<_Args>(__args)...); } template enable_if_t&, _Args&&...>::value> emplace(initializer_list<_Up> __il, _Args&&... __args) { this->_M_reset(); this->_M_construct(__il, std::forward<_Args>(__args)...); } // [X.Y.4.2] Destructor is implicit, implemented in _Optional_base. // [X.Y.4.4] Swap. void swap(optional& __other) noexcept(is_nothrow_move_constructible<_Tp>() && __is_nothrow_swappable<_Tp>::value) { using std::swap; if (this->_M_is_engaged() && __other._M_is_engaged()) swap(this->_M_get(), __other._M_get()); else if (this->_M_is_engaged()) { __other._M_construct(std::move(this->_M_get())); this->_M_destruct(); } else if (__other._M_is_engaged()) { this->_M_construct(std::move(__other._M_get())); __other._M_destruct(); } } // [X.Y.4.5] Observers. constexpr const _Tp* operator->() const { #ifndef __cpp_lib_addressof_constexpr return __constexpr_addressof(this->_M_get()); #else return std::__addressof(this->_M_get()); #endif } _Tp* operator->() { return std::__addressof(this->_M_get()); } constexpr const _Tp& operator*() const& { return this->_M_get(); } constexpr _Tp& operator*()& { return this->_M_get(); } constexpr _Tp&& operator*()&& { return std::move(this->_M_get()); } constexpr const _Tp&& operator*() const&& { return std::move(this->_M_get()); } constexpr explicit operator bool() const noexcept { return this->_M_is_engaged(); } constexpr const _Tp& value() const& { return this->_M_is_engaged() ? this->_M_get() : (__throw_bad_optional_access("Attempt to access value of a " "disengaged optional object"), this->_M_get()); } constexpr _Tp& value()& { return this->_M_is_engaged() ? this->_M_get() : (__throw_bad_optional_access("Attempt to access value of a " "disengaged optional object"), this->_M_get()); } constexpr _Tp&& value()&& { return this->_M_is_engaged() ? std::move(this->_M_get()) : (__throw_bad_optional_access("Attempt to access value of a " "disengaged optional object"), std::move(this->_M_get())); } constexpr const _Tp&& value() const&& { return this->_M_is_engaged() ? std::move(this->_M_get()) : (__throw_bad_optional_access("Attempt to access value of a " "disengaged optional object"), std::move(this->_M_get())); } template constexpr _Tp value_or(_Up&& __u) const& { static_assert(__and_, is_convertible<_Up&&, _Tp>>(), "Cannot return value"); return this->_M_is_engaged() ? this->_M_get() : static_cast<_Tp>(std::forward<_Up>(__u)); } template _Tp value_or(_Up&& __u) && { static_assert(__and_, is_convertible<_Up&&, _Tp>>(), "Cannot return value" ); return this->_M_is_engaged() ? std::move(this->_M_get()) : static_cast<_Tp>(std::forward<_Up>(__u)); } }; // [X.Y.8] Comparisons between optional values. template constexpr bool operator==(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs) { return static_cast(__lhs) == static_cast(__rhs) && (!__lhs || *__lhs == *__rhs); } template constexpr bool operator!=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs) { return !(__lhs == __rhs); } template constexpr bool operator<(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs) { return static_cast(__rhs) && (!__lhs || *__lhs < *__rhs); } template constexpr bool operator>(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs) { return __rhs < __lhs; } template constexpr bool operator<=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs) { return !(__rhs < __lhs); } template constexpr bool operator>=(const optional<_Tp>& __lhs, const optional<_Tp>& __rhs) { return !(__lhs < __rhs); } // [X.Y.9] Comparisons with nullopt. template constexpr bool operator==(const optional<_Tp>& __lhs, nullopt_t) noexcept { return !__lhs; } template constexpr bool operator==(nullopt_t, const optional<_Tp>& __rhs) noexcept { return !__rhs; } template constexpr bool operator!=(const optional<_Tp>& __lhs, nullopt_t) noexcept { return static_cast(__lhs); } template constexpr bool operator!=(nullopt_t, const optional<_Tp>& __rhs) noexcept { return static_cast(__rhs); } template constexpr bool operator<(const optional<_Tp>& /* __lhs */, nullopt_t) noexcept { return false; } template constexpr bool operator<(nullopt_t, const optional<_Tp>& __rhs) noexcept { return static_cast(__rhs); } template constexpr bool operator>(const optional<_Tp>& __lhs, nullopt_t) noexcept { return static_cast(__lhs); } template constexpr bool operator>(nullopt_t, const optional<_Tp>& /* __rhs */) noexcept { return false; } template constexpr bool operator<=(const optional<_Tp>& __lhs, nullopt_t) noexcept { return !__lhs; } template constexpr bool operator<=(nullopt_t, const optional<_Tp>& /* __rhs */) noexcept { return true; } template constexpr bool operator>=(const optional<_Tp>& /* __lhs */, nullopt_t) noexcept { return true; } template constexpr bool operator>=(nullopt_t, const optional<_Tp>& __rhs) noexcept { return !__rhs; } // [X.Y.10] Comparisons with value type. template constexpr bool operator==(const optional<_Tp>& __lhs, const _Tp& __rhs) { return __lhs && *__lhs == __rhs; } template constexpr bool operator==(const _Tp& __lhs, const optional<_Tp>& __rhs) { return __rhs && __lhs == *__rhs; } template constexpr bool operator!=(const optional<_Tp>& __lhs, _Tp const& __rhs) { return !__lhs || !(*__lhs == __rhs); } template constexpr bool operator!=(const _Tp& __lhs, const optional<_Tp>& __rhs) { return !__rhs || !(__lhs == *__rhs); } template constexpr bool operator<(const optional<_Tp>& __lhs, const _Tp& __rhs) { return !__lhs || *__lhs < __rhs; } template constexpr bool operator<(const _Tp& __lhs, const optional<_Tp>& __rhs) { return __rhs && __lhs < *__rhs; } template constexpr bool operator>(const optional<_Tp>& __lhs, const _Tp& __rhs) { return __lhs && __rhs < *__lhs; } template constexpr bool operator>(const _Tp& __lhs, const optional<_Tp>& __rhs) { return !__rhs || *__rhs < __lhs; } template constexpr bool operator<=(const optional<_Tp>& __lhs, const _Tp& __rhs) { return !__lhs || !(__rhs < *__lhs); } template constexpr bool operator<=(const _Tp& __lhs, const optional<_Tp>& __rhs) { return __rhs && !(*__rhs < __lhs); } template constexpr bool operator>=(const optional<_Tp>& __lhs, const _Tp& __rhs) { return __lhs && !(*__lhs < __rhs); } template constexpr bool operator>=(const _Tp& __lhs, const optional<_Tp>& __rhs) { return !__rhs || !(__lhs < *__rhs); } // [X.Y.11] template inline void swap(optional<_Tp>& __lhs, optional<_Tp>& __rhs) noexcept(noexcept(__lhs.swap(__rhs))) { __lhs.swap(__rhs); } template constexpr optional> make_optional(_Tp&& __t) { return optional> { std::forward<_Tp>(__t) }; } // @} group optional } // namespace fundamentals_v1 } // namespace experimental // [X.Y.12] template struct hash> { using result_type = size_t; using argument_type = experimental::optional<_Tp>; size_t operator()(const experimental::optional<_Tp>& __t) const noexcept(noexcept(hash<_Tp> {}(*__t))) { // We pick an arbitrary hash for disengaged optionals which hopefully // usual values of _Tp won't typically hash to. constexpr size_t __magic_disengaged_hash = static_cast(-3333); return __t ? hash<_Tp> {}(*__t) : __magic_disengaged_hash; } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_OPTIONAL PK!t";;8/experimental/propagate_constnu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/propagate_const * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_PROPAGATE_CONST #define _GLIBCXX_EXPERIMENTAL_PROPAGATE_CONST 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { /** * @defgroup propagate_const Const-propagating wrapper * @ingroup experimental * * A const-propagating wrapper that propagates const to pointer-like members, * as described in n4388 "A Proposal to Add a Const-Propagating Wrapper * to the Standard Library". * * @{ */ /// Const-propagating wrapper. template class propagate_const { public: typedef remove_reference_t())> element_type; private: template struct __is_propagate_const : false_type { }; template struct __is_propagate_const> : true_type { }; template friend constexpr const _Up& get_underlying(const propagate_const<_Up>& __pt) noexcept; template friend constexpr _Up& get_underlying(propagate_const<_Up>& __pt) noexcept; template static constexpr element_type* __to_raw_pointer(_Up* __u) { return __u; } template static constexpr element_type* __to_raw_pointer(_Up& __u) { return __u.get(); } template static constexpr const element_type* __to_raw_pointer(const _Up* __u) { return __u; } template static constexpr const element_type* __to_raw_pointer(const _Up& __u) { return __u.get(); } public: static_assert(__and_::type>, __not_>, __or_, is_pointer<_Tp>>>::value, "propagate_const requires a class or a pointer to an" " object type"); // [propagate_const.ctor], constructors constexpr propagate_const() = default; propagate_const(const propagate_const& __p) = delete; constexpr propagate_const(propagate_const&& __p) = default; template , is_convertible<_Up&&, _Tp>>::value, bool >::type=true> constexpr propagate_const(propagate_const<_Up>&& __pu) : _M_t(std::move(get_underlying(__pu))) {} template , __not_>>::value, bool>::type=false> constexpr explicit propagate_const(propagate_const<_Up>&& __pu) : _M_t(std::move(get_underlying(__pu))) {} template , is_convertible<_Up&&, _Tp>, __not_<__is_propagate_const< typename decay<_Up>::type>> >::value, bool>::type=true> constexpr propagate_const(_Up&& __u) : _M_t(std::forward<_Up>(__u)) {} template , __not_>, __not_<__is_propagate_const< typename decay<_Up>::type>> >::value, bool>::type=false> constexpr explicit propagate_const(_Up&& __u) : _M_t(std::forward<_Up>(__u)) {} // [propagate_const.assignment], assignment propagate_const& operator=(const propagate_const& __p) = delete; constexpr propagate_const& operator=(propagate_const&& __p) = default; template ::value>::type> constexpr propagate_const& operator=(propagate_const<_Up>&& __pu) { _M_t = std::move(get_underlying(__pu)); return *this; } template , __not_<__is_propagate_const< typename decay<_Up>::type>> >::value>::type> constexpr propagate_const& operator=(_Up&& __u) { _M_t = std::forward<_Up>(__u); return *this; } // [propagate_const.const_observers], const observers explicit constexpr operator bool() const { return bool(_M_t); } constexpr const element_type* operator->() const { return get(); } template , is_convertible<_Up, const element_type*> >::value, bool>::type = true> constexpr operator const element_type*() const { return get(); } constexpr const element_type& operator*() const { return *get(); } constexpr const element_type* get() const { return __to_raw_pointer(_M_t); } // [propagate_const.non_const_observers], non-const observers constexpr element_type* operator->() { return get(); } template , is_convertible<_Up, const element_type*> >::value, bool>::type = true> constexpr operator element_type*() { return get(); } constexpr element_type& operator*() { return *get(); } constexpr element_type* get() { return __to_raw_pointer(_M_t); } // [propagate_const.modifiers], modifiers constexpr void swap(propagate_const& __pt) noexcept(__is_nothrow_swappable<_Tp>::value) { using std::swap; swap(_M_t, get_underlying(__pt)); } private: _Tp _M_t; }; // [propagate_const.relational], relational operators template constexpr bool operator==(const propagate_const<_Tp>& __pt, nullptr_t) { return get_underlying(__pt) == nullptr; } template constexpr bool operator==(nullptr_t, const propagate_const<_Tp>& __pu) { return nullptr == get_underlying(__pu); } template constexpr bool operator!=(const propagate_const<_Tp>& __pt, nullptr_t) { return get_underlying(__pt) != nullptr; } template constexpr bool operator!=(nullptr_t, const propagate_const<_Tp>& __pu) { return nullptr != get_underlying(__pu); } template constexpr bool operator==(const propagate_const<_Tp>& __pt, const propagate_const<_Up>& __pu) { return get_underlying(__pt) == get_underlying(__pu); } template constexpr bool operator!=(const propagate_const<_Tp>& __pt, const propagate_const<_Up>& __pu) { return get_underlying(__pt) != get_underlying(__pu); } template constexpr bool operator<(const propagate_const<_Tp>& __pt, const propagate_const<_Up>& __pu) { return get_underlying(__pt) < get_underlying(__pu); } template constexpr bool operator>(const propagate_const<_Tp>& __pt, const propagate_const<_Up>& __pu) { return get_underlying(__pt) > get_underlying(__pu); } template constexpr bool operator<=(const propagate_const<_Tp>& __pt, const propagate_const<_Up>& __pu) { return get_underlying(__pt) <= get_underlying(__pu); } template constexpr bool operator>=(const propagate_const<_Tp>& __pt, const propagate_const<_Up>& __pu) { return get_underlying(__pt) >= get_underlying(__pu); } template constexpr bool operator==(const propagate_const<_Tp>& __pt, const _Up& __u) { return get_underlying(__pt) == __u; } template constexpr bool operator!=(const propagate_const<_Tp>& __pt, const _Up& __u) { return get_underlying(__pt) != __u; } template constexpr bool operator<(const propagate_const<_Tp>& __pt, const _Up& __u) { return get_underlying(__pt) < __u; } template constexpr bool operator>(const propagate_const<_Tp>& __pt, const _Up& __u) { return get_underlying(__pt) > __u; } template constexpr bool operator<=(const propagate_const<_Tp>& __pt, const _Up& __u) { return get_underlying(__pt) <= __u; } template constexpr bool operator>=(const propagate_const<_Tp>& __pt, const _Up& __u) { return get_underlying(__pt) >= __u; } template constexpr bool operator==(const _Tp& __t, const propagate_const<_Up>& __pu) { return __t == get_underlying(__pu); } template constexpr bool operator!=(const _Tp& __t, const propagate_const<_Up>& __pu) { return __t != get_underlying(__pu); } template constexpr bool operator<(const _Tp& __t, const propagate_const<_Up>& __pu) { return __t < get_underlying(__pu); } template constexpr bool operator>(const _Tp& __t, const propagate_const<_Up>& __pu) { return __t > get_underlying(__pu); } template constexpr bool operator<=(const _Tp& __t, const propagate_const<_Up>& __pu) { return __t <= get_underlying(__pu); } template constexpr bool operator>=(const _Tp& __t, const propagate_const<_Up>& __pu) { return __t >= get_underlying(__pu); } // [propagate_const.algorithms], specialized algorithms template constexpr void swap(propagate_const<_Tp>& __pt, propagate_const<_Tp>& __pt2) noexcept(__is_nothrow_swappable<_Tp>::value) { __pt.swap(__pt2); } // [propagate_const.underlying], underlying pointer access template constexpr const _Tp& get_underlying(const propagate_const<_Tp>& __pt) noexcept { return __pt._M_t; } template constexpr _Tp& get_underlying(propagate_const<_Tp>& __pt) noexcept { return __pt._M_t; } // @} group propagate_const } // namespace fundamentals_v2 } // namespace experimental // [propagate_const.hash], hash support template struct hash> { using result_type = size_t; using argument_type = experimental::propagate_const<_Tp>; size_t operator()(const experimental::propagate_const<_Tp>& __t) const noexcept(noexcept(hash<_Tp>{}(get_underlying(__t)))) { return hash<_Tp>{}(get_underlying(__t)); } }; // [propagate_const.comparison_function_objects], comparison function objects template struct equal_to> { constexpr bool operator()(const experimental::propagate_const<_Tp>& __x, const experimental::propagate_const<_Tp>& __y) const { return equal_to<_Tp>{}(get_underlying(__x), get_underlying(__y)); } typedef experimental::propagate_const<_Tp> first_argument_type; typedef experimental::propagate_const<_Tp> second_argument_type; typedef bool result_type; }; template struct not_equal_to> { constexpr bool operator()(const experimental::propagate_const<_Tp>& __x, const experimental::propagate_const<_Tp>& __y) const { return not_equal_to<_Tp>{}(get_underlying(__x), get_underlying(__y)); } typedef experimental::propagate_const<_Tp> first_argument_type; typedef experimental::propagate_const<_Tp> second_argument_type; typedef bool result_type; }; template struct less> { constexpr bool operator()(const experimental::propagate_const<_Tp>& __x, const experimental::propagate_const<_Tp>& __y) const { return less<_Tp>{}(get_underlying(__x), get_underlying(__y)); } typedef experimental::propagate_const<_Tp> first_argument_type; typedef experimental::propagate_const<_Tp> second_argument_type; typedef bool result_type; }; template struct greater> { constexpr bool operator()(const experimental::propagate_const<_Tp>& __x, const experimental::propagate_const<_Tp>& __y) const { return greater<_Tp>{}(get_underlying(__x), get_underlying(__y)); } typedef experimental::propagate_const<_Tp> first_argument_type; typedef experimental::propagate_const<_Tp> second_argument_type; typedef bool result_type; }; template struct less_equal> { constexpr bool operator()(const experimental::propagate_const<_Tp>& __x, const experimental::propagate_const<_Tp>& __y) const { return less_equal<_Tp>{}(get_underlying(__x), get_underlying(__y)); } typedef experimental::propagate_const<_Tp> first_argument_type; typedef experimental::propagate_const<_Tp> second_argument_type; typedef bool result_type; }; template struct greater_equal> { constexpr bool operator()(const experimental::propagate_const<_Tp>& __x, const experimental::propagate_const<_Tp>& __y) const { return greater_equal<_Tp>{}(get_underlying(__x), get_underlying(__y)); } typedef experimental::propagate_const<_Tp> first_argument_type; typedef experimental::propagate_const<_Tp> second_argument_type; typedef bool result_type; }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_PROPAGATE_CONST PK!{| 8/experimental/randomnu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/random * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_RANDOM #define _GLIBCXX_EXPERIMENTAL_RANDOM 1 #if __cplusplus >= 201402L #include #include namespace std { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { #define __cpp_lib_experimental_randint 201511 inline std::default_random_engine& _S_randint_engine() { static thread_local default_random_engine __eng{random_device{}()}; return __eng; } // 13.2.2.1, Function template randint template inline _IntType randint(_IntType __a, _IntType __b) { static_assert(is_integral<_IntType>::value && sizeof(_IntType) > 1, "argument must be an integer type"); using _Dist = std::uniform_int_distribution<_IntType>; // This relies on the fact our uniform_int_distribution is stateless, // otherwise we'd need a static thread_local _Dist and pass it // _Dist::param_type{__a, __b}. return _Dist(__a, __b)(_S_randint_engine()); } inline void reseed() { _S_randint_engine().seed(random_device{}()); } inline void reseed(default_random_engine::result_type __value) { _S_randint_engine().seed(__value); } } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_RANDOM PK!)}p p 8/experimental/rationu[// Variable Templates For ratio -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/ratio * This is a TS C++ Library header. */ // // N3932 Variable Templates For Type Traits (Revision 1) // #ifndef _GLIBCXX_EXPERIMENTAL_RATIO #define _GLIBCXX_EXPERIMENTAL_RATIO 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v1 { // See C++14 §20.11.5, ratio comparison template constexpr bool ratio_equal_v = ratio_equal<_R1, _R2>::value; template constexpr bool ratio_not_equal_v = ratio_not_equal<_R1, _R2>::value; template constexpr bool ratio_less_v = ratio_less<_R1, _R2>::value; template constexpr bool ratio_less_equal_v = ratio_less_equal<_R1, _R2>::value; template constexpr bool ratio_greater_v = ratio_greater<_R1, _R2>::value; template constexpr bool ratio_greater_equal_v = ratio_greater_equal<_R1, _R2>::value; } // namespace fundamentals_v1 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // __cplusplus <= 201103L #endif // _GLIBCXX_EXPERIMENTAL_RATIO PK!Cn3118/experimental/regexnu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/regex * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_REGEX #define _GLIBCXX_EXPERIMENTAL_REGEX 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { #if _GLIBCXX_USE_CXX11_ABI namespace pmr { template using match_results = std::match_results<_BidirectionalIterator, polymorphic_allocator< sub_match<_BidirectionalIterator>>>; typedef match_results cmatch; typedef match_results wcmatch; typedef match_results smatch; typedef match_results wsmatch; } // namespace pmr #endif } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_REGEX PK!h 8/experimental/setnu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/set * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_SET #define _GLIBCXX_EXPERIMENTAL_SET 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { template inline void erase_if(set<_Key, _Compare, _Alloc>& __cont, _Predicate __pred) { __detail::__erase_nodes_if(__cont, __pred); } template inline void erase_if(multiset<_Key, _Compare, _Alloc>& __cont, _Predicate __pred) { __detail::__erase_nodes_if(__cont, __pred); } namespace pmr { template> using set = std::set<_Key, _Compare, polymorphic_allocator<_Key>>; template> using multiset = std::multiset<_Key, _Compare, polymorphic_allocator<_Key>>; } // namespace pmr } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_SET PK!?% 8/experimental/source_locationnu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/source_location * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_SRCLOC #define _GLIBCXX_EXPERIMENTAL_SRCLOC 1 #if __cplusplus >= 201402L #include namespace std { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { #define __cpp_lib_experimental_source_location 201505 struct source_location { #ifndef _GLIBCXX_USE_C99_STDINT_TR1 private: using uint_least32_t = unsigned; public: #endif // 14.1.2, source_location creation static constexpr source_location current(const char* __file = __builtin_FILE(), const char* __func = __builtin_FUNCTION(), int __line = __builtin_LINE(), int __col = 0) noexcept { source_location __loc; __loc._M_file = __file; __loc._M_func = __func; __loc._M_line = __line; __loc._M_col = __col; return __loc; } constexpr source_location() noexcept : _M_file("unknown"), _M_func(_M_file), _M_line(0), _M_col(0) { } // 14.1.3, source_location field access constexpr uint_least32_t line() const noexcept { return _M_line; } constexpr uint_least32_t column() const noexcept { return _M_col; } constexpr const char* file_name() const noexcept { return _M_file; } constexpr const char* function_name() const noexcept { return _M_func; } private: const char* _M_file; const char* _M_func; uint_least32_t _M_line; uint_least32_t _M_col; }; } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_SRCLOC PK!Q)  8/experimental/stringnu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/string * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_STRING #define _GLIBCXX_EXPERIMENTAL_STRING 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { template inline void erase_if(basic_string<_CharT, _Traits, _Alloc>& __cont, _Predicate __pred) { __cont.erase(std::remove_if(__cont.begin(), __cont.end(), __pred), __cont.end()); } template inline void erase(basic_string<_CharT, _Traits, _Alloc>& __cont, const _Up& __value) { __cont.erase(std::remove(__cont.begin(), __cont.end(), __value), __cont.end()); } #if _GLIBCXX_USE_CXX11_ABI namespace pmr { // basic_string using polymorphic allocator in namespace pmr template> using basic_string = std::basic_string<_CharT, _Traits, polymorphic_allocator<_CharT>>; // basic_string typedef names using polymorphic allocator in namespace // std::experimental::pmr typedef basic_string string; typedef basic_string u16string; typedef basic_string u32string; typedef basic_string wstring; } // namespace pmr #endif } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_STRING PK!J+˯SS8/experimental/string_viewnu[// Components for manipulating non-owning sequences of characters -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/string_view * This is a TS C++ Library header. */ // // N3762 basic_string_view library // #ifndef _GLIBCXX_EXPERIMENTAL_STRING_VIEW #define _GLIBCXX_EXPERIMENTAL_STRING_VIEW 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v1 { #define __cpp_lib_experimental_string_view 201411 /** * @class basic_string_view * @brief A non-owning reference to a string. * * @ingroup strings * @ingroup sequences * @ingroup experimental * * @tparam _CharT Type of character * @tparam _Traits Traits for character type, defaults to * char_traits<_CharT>. * * A basic_string_view looks like this: * * @code * _CharT* _M_str * size_t _M_len * @endcode */ template> class basic_string_view { public: // types using traits_type = _Traits; using value_type = _CharT; using pointer = const _CharT*; using const_pointer = const _CharT*; using reference = const _CharT&; using const_reference = const _CharT&; using const_iterator = const _CharT*; using iterator = const_iterator; using const_reverse_iterator = std::reverse_iterator; using reverse_iterator = const_reverse_iterator; using size_type = size_t; using difference_type = ptrdiff_t; static constexpr size_type npos = size_type(-1); // [string.view.cons], construct/copy constexpr basic_string_view() noexcept : _M_len{0}, _M_str{nullptr} { } constexpr basic_string_view(const basic_string_view&) noexcept = default; template basic_string_view(const basic_string<_CharT, _Traits, _Allocator>& __str) noexcept : _M_len{__str.length()}, _M_str{__str.data()} { } constexpr basic_string_view(const _CharT* __str) : _M_len{__str == nullptr ? 0 : traits_type::length(__str)}, _M_str{__str} { } constexpr basic_string_view(const _CharT* __str, size_type __len) : _M_len{__len}, _M_str{__str} { } basic_string_view& operator=(const basic_string_view&) noexcept = default; // [string.view.iterators], iterators constexpr const_iterator begin() const noexcept { return this->_M_str; } constexpr const_iterator end() const noexcept { return this->_M_str + this->_M_len; } constexpr const_iterator cbegin() const noexcept { return this->_M_str; } constexpr const_iterator cend() const noexcept { return this->_M_str + this->_M_len; } const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(this->end()); } const_reverse_iterator rend() const noexcept { return const_reverse_iterator(this->begin()); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(this->end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(this->begin()); } // [string.view.capacity], capacity constexpr size_type size() const noexcept { return this->_M_len; } constexpr size_type length() const noexcept { return _M_len; } constexpr size_type max_size() const noexcept { return (npos - sizeof(size_type) - sizeof(void*)) / sizeof(value_type) / 4; } constexpr bool empty() const noexcept { return this->_M_len == 0; } // [string.view.access], element access constexpr const _CharT& operator[](size_type __pos) const { __glibcxx_assert(__pos < this->_M_len); return *(this->_M_str + __pos); } constexpr const _CharT& at(size_type __pos) const { return __pos < this->_M_len ? *(this->_M_str + __pos) : (__throw_out_of_range_fmt(__N("basic_string_view::at: __pos " "(which is %zu) >= this->size() " "(which is %zu)"), __pos, this->size()), *this->_M_str); } constexpr const _CharT& front() const { __glibcxx_assert(this->_M_len > 0); return *this->_M_str; } constexpr const _CharT& back() const { __glibcxx_assert(this->_M_len > 0); return *(this->_M_str + this->_M_len - 1); } constexpr const _CharT* data() const noexcept { return this->_M_str; } // [string.view.modifiers], modifiers: constexpr void remove_prefix(size_type __n) { __glibcxx_assert(this->_M_len >= __n); this->_M_str += __n; this->_M_len -= __n; } constexpr void remove_suffix(size_type __n) { this->_M_len -= __n; } constexpr void swap(basic_string_view& __sv) noexcept { auto __tmp = *this; *this = __sv; __sv = __tmp; } // [string.view.ops], string operations: template explicit operator basic_string<_CharT, _Traits, _Allocator>() const { return { this->_M_str, this->_M_len }; } template> basic_string<_CharT, _Traits, _Allocator> to_string(const _Allocator& __alloc = _Allocator()) const { return { this->_M_str, this->_M_len, __alloc }; } size_type copy(_CharT* __str, size_type __n, size_type __pos = 0) const { __glibcxx_requires_string_len(__str, __n); if (__pos > this->_M_len) __throw_out_of_range_fmt(__N("basic_string_view::copy: __pos " "(which is %zu) > this->size() " "(which is %zu)"), __pos, this->size()); size_type __rlen{std::min(__n, size_type{this->_M_len - __pos})}; for (auto __begin = this->_M_str + __pos, __end = __begin + __rlen; __begin != __end;) *__str++ = *__begin++; return __rlen; } // [string.view.ops], string operations: constexpr basic_string_view substr(size_type __pos = 0, size_type __n = npos) const { return __pos <= this->_M_len ? basic_string_view{this->_M_str + __pos, std::min(__n, size_type{this->_M_len - __pos})} : (__throw_out_of_range_fmt(__N("basic_string_view::substr: __pos " "(which is %zu) > this->size() " "(which is %zu)"), __pos, this->size()), basic_string_view{}); } constexpr int compare(basic_string_view __str) const noexcept { int __ret = traits_type::compare(this->_M_str, __str._M_str, std::min(this->_M_len, __str._M_len)); if (__ret == 0) __ret = _S_compare(this->_M_len, __str._M_len); return __ret; } constexpr int compare(size_type __pos1, size_type __n1, basic_string_view __str) const { return this->substr(__pos1, __n1).compare(__str); } constexpr int compare(size_type __pos1, size_type __n1, basic_string_view __str, size_type __pos2, size_type __n2) const { return this->substr(__pos1, __n1).compare(__str.substr(__pos2, __n2)); } constexpr int compare(const _CharT* __str) const noexcept { return this->compare(basic_string_view{__str}); } constexpr int compare(size_type __pos1, size_type __n1, const _CharT* __str) const { return this->substr(__pos1, __n1).compare(basic_string_view{__str}); } constexpr int compare(size_type __pos1, size_type __n1, const _CharT* __str, size_type __n2) const { return this->substr(__pos1, __n1) .compare(basic_string_view(__str, __n2)); } constexpr size_type find(basic_string_view __str, size_type __pos = 0) const noexcept { return this->find(__str._M_str, __pos, __str._M_len); } constexpr size_type find(_CharT __c, size_type __pos=0) const noexcept; constexpr size_type find(const _CharT* __str, size_type __pos, size_type __n) const noexcept; constexpr size_type find(const _CharT* __str, size_type __pos=0) const noexcept { return this->find(__str, __pos, traits_type::length(__str)); } constexpr size_type rfind(basic_string_view __str, size_type __pos = npos) const noexcept { return this->rfind(__str._M_str, __pos, __str._M_len); } constexpr size_type rfind(_CharT __c, size_type __pos = npos) const noexcept; constexpr size_type rfind(const _CharT* __str, size_type __pos, size_type __n) const noexcept; constexpr size_type rfind(const _CharT* __str, size_type __pos = npos) const noexcept { return this->rfind(__str, __pos, traits_type::length(__str)); } constexpr size_type find_first_of(basic_string_view __str, size_type __pos = 0) const noexcept { return this->find_first_of(__str._M_str, __pos, __str._M_len); } constexpr size_type find_first_of(_CharT __c, size_type __pos = 0) const noexcept { return this->find(__c, __pos); } constexpr size_type find_first_of(const _CharT* __str, size_type __pos, size_type __n) const; constexpr size_type find_first_of(const _CharT* __str, size_type __pos = 0) const noexcept { return this->find_first_of(__str, __pos, traits_type::length(__str)); } constexpr size_type find_last_of(basic_string_view __str, size_type __pos = npos) const noexcept { return this->find_last_of(__str._M_str, __pos, __str._M_len); } constexpr size_type find_last_of(_CharT __c, size_type __pos=npos) const noexcept { return this->rfind(__c, __pos); } constexpr size_type find_last_of(const _CharT* __str, size_type __pos, size_type __n) const; constexpr size_type find_last_of(const _CharT* __str, size_type __pos = npos) const noexcept { return this->find_last_of(__str, __pos, traits_type::length(__str)); } constexpr size_type find_first_not_of(basic_string_view __str, size_type __pos = 0) const noexcept { return this->find_first_not_of(__str._M_str, __pos, __str._M_len); } constexpr size_type find_first_not_of(_CharT __c, size_type __pos = 0) const noexcept; constexpr size_type find_first_not_of(const _CharT* __str, size_type __pos, size_type __n) const; constexpr size_type find_first_not_of(const _CharT* __str, size_type __pos = 0) const noexcept { return this->find_first_not_of(__str, __pos, traits_type::length(__str)); } constexpr size_type find_last_not_of(basic_string_view __str, size_type __pos = npos) const noexcept { return this->find_last_not_of(__str._M_str, __pos, __str._M_len); } constexpr size_type find_last_not_of(_CharT __c, size_type __pos = npos) const noexcept; constexpr size_type find_last_not_of(const _CharT* __str, size_type __pos, size_type __n) const; constexpr size_type find_last_not_of(const _CharT* __str, size_type __pos = npos) const noexcept { return this->find_last_not_of(__str, __pos, traits_type::length(__str)); } private: static constexpr int _S_compare(size_type __n1, size_type __n2) noexcept { return difference_type(__n1 - __n2) > std::numeric_limits::max() ? std::numeric_limits::max() : difference_type(__n1 - __n2) < std::numeric_limits::min() ? std::numeric_limits::min() : static_cast(difference_type(__n1 - __n2)); } size_t _M_len; const _CharT* _M_str; }; // [string.view.comparison], non-member basic_string_view comparison functions namespace __detail { // Identity transform to create a non-deduced context, so that only one // argument participates in template argument deduction and the other // argument gets implicitly converted to the deduced type. See n3766.html. template using __idt = common_type_t<_Tp>; } template constexpr bool operator==(basic_string_view<_CharT, _Traits> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.size() == __y.size() && __x.compare(__y) == 0; } template constexpr bool operator==(basic_string_view<_CharT, _Traits> __x, __detail::__idt> __y) noexcept { return __x.size() == __y.size() && __x.compare(__y) == 0; } template constexpr bool operator==(__detail::__idt> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.size() == __y.size() && __x.compare(__y) == 0; } template constexpr bool operator!=(basic_string_view<_CharT, _Traits> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return !(__x == __y); } template constexpr bool operator!=(basic_string_view<_CharT, _Traits> __x, __detail::__idt> __y) noexcept { return !(__x == __y); } template constexpr bool operator!=(__detail::__idt> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return !(__x == __y); } template constexpr bool operator< (basic_string_view<_CharT, _Traits> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) < 0; } template constexpr bool operator< (basic_string_view<_CharT, _Traits> __x, __detail::__idt> __y) noexcept { return __x.compare(__y) < 0; } template constexpr bool operator< (__detail::__idt> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) < 0; } template constexpr bool operator> (basic_string_view<_CharT, _Traits> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) > 0; } template constexpr bool operator> (basic_string_view<_CharT, _Traits> __x, __detail::__idt> __y) noexcept { return __x.compare(__y) > 0; } template constexpr bool operator> (__detail::__idt> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) > 0; } template constexpr bool operator<=(basic_string_view<_CharT, _Traits> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) <= 0; } template constexpr bool operator<=(basic_string_view<_CharT, _Traits> __x, __detail::__idt> __y) noexcept { return __x.compare(__y) <= 0; } template constexpr bool operator<=(__detail::__idt> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) <= 0; } template constexpr bool operator>=(basic_string_view<_CharT, _Traits> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) >= 0; } template constexpr bool operator>=(basic_string_view<_CharT, _Traits> __x, __detail::__idt> __y) noexcept { return __x.compare(__y) >= 0; } template constexpr bool operator>=(__detail::__idt> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) >= 0; } // [string.view.io], Inserters and extractors template inline basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, basic_string_view<_CharT,_Traits> __str) { return __ostream_insert(__os, __str.data(), __str.size()); } // basic_string_view typedef names using string_view = basic_string_view; #ifdef _GLIBCXX_USE_WCHAR_T using wstring_view = basic_string_view; #endif #ifdef _GLIBCXX_USE_C99_STDINT_TR1 using u16string_view = basic_string_view; using u32string_view = basic_string_view; #endif } // namespace fundamentals_v1 } // namespace experimental // [string.view.hash], hash support: template struct hash; template<> struct hash : public __hash_base { size_t operator()(const experimental::string_view& __str) const noexcept { return std::_Hash_impl::hash(__str.data(), __str.length()); } }; template<> struct __is_fast_hash> : std::false_type { }; #ifdef _GLIBCXX_USE_WCHAR_T template<> struct hash : public __hash_base { size_t operator()(const experimental::wstring_view& __s) const noexcept { return std::_Hash_impl::hash(__s.data(), __s.length() * sizeof(wchar_t)); } }; template<> struct __is_fast_hash> : std::false_type { }; #endif #ifdef _GLIBCXX_USE_C99_STDINT_TR1 template<> struct hash : public __hash_base { size_t operator()(const experimental::u16string_view& __s) const noexcept { return std::_Hash_impl::hash(__s.data(), __s.length() * sizeof(char16_t)); } }; template<> struct __is_fast_hash> : std::false_type { }; template<> struct hash : public __hash_base { size_t operator()(const experimental::u32string_view& __s) const noexcept { return std::_Hash_impl::hash(__s.data(), __s.length() * sizeof(char32_t)); } }; template<> struct __is_fast_hash> : std::false_type { }; #endif namespace experimental { // I added these EMSR. inline namespace literals { inline namespace string_view_literals { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wliteral-suffix" inline constexpr basic_string_view operator""sv(const char* __str, size_t __len) noexcept { return basic_string_view{__str, __len}; } #ifdef _GLIBCXX_USE_WCHAR_T inline constexpr basic_string_view operator""sv(const wchar_t* __str, size_t __len) noexcept { return basic_string_view{__str, __len}; } #endif #ifdef _GLIBCXX_USE_C99_STDINT_TR1 inline constexpr basic_string_view operator""sv(const char16_t* __str, size_t __len) noexcept { return basic_string_view{__str, __len}; } inline constexpr basic_string_view operator""sv(const char32_t* __str, size_t __len) noexcept { return basic_string_view{__str, __len}; } #endif #pragma GCC diagnostic pop } // namespace string_literals } // namespace literals } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #include #endif // __cplusplus <= 201103L #endif // _GLIBCXX_EXPERIMENTAL_STRING_VIEW PK!@8/experimental/system_errornu[// Variable Templates For system_error -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/system_error * This is a TS C++ Library header. */ // // N3932 Variable Templates For Type Traits (Revision 1) // #ifndef _GLIBCXX_EXPERIMENTAL_SYSTEM_ERROR #define _GLIBCXX_EXPERIMENTAL_SYSTEM_ERROR 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v1 { // See C++14 §19.5, System error support template constexpr bool is_error_code_enum_v = is_error_code_enum<_Tp>::value; template constexpr bool is_error_condition_enum_v = is_error_condition_enum<_Tp>::value; } // namespace fundamentals_v1 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // __cplusplus <= 201103L #endif // _GLIBCXX_EXPERIMENTAL_SYSTEM_ERROR PK!=ƻ 8/experimental/tuplenu[// -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/tuple * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_TUPLE #define _GLIBCXX_EXPERIMENTAL_TUPLE 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v1 { // See C++14 §20.4.2.5, tuple helper classes template constexpr size_t tuple_size_v = tuple_size<_Tp>::value; #define __cpp_lib_experimental_tuple 201402 template constexpr decltype(auto) __apply_impl(_Fn&& __f, _Tuple&& __t, std::index_sequence<_Idx...>) { return std::__invoke(std::forward<_Fn>(__f), std::get<_Idx>(std::forward<_Tuple>(__t))...); } template constexpr decltype(auto) apply(_Fn&& __f, _Tuple&& __t) { using _Indices = std::make_index_sequence>>; return experimental::__apply_impl(std::forward<_Fn>(__f), std::forward<_Tuple>(__t), _Indices{}); } } // namespace fundamentals_v1 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_TUPLE PK!**8/experimental/type_traitsnu[// Variable Templates For Type Traits -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/type_traits * This is a TS C++ Library header. */ // // N3932 Variable Templates For Type Traits (Revision 1) // #ifndef _GLIBCXX_EXPERIMENTAL_TYPE_TRAITS #define _GLIBCXX_EXPERIMENTAL_TYPE_TRAITS 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v1 { #define __cpp_lib_experimental_type_trait_variable_templates 201402 // See C++14 §20.10.4.1, primary type categories template constexpr bool is_void_v = is_void<_Tp>::value; template constexpr bool is_null_pointer_v = is_null_pointer<_Tp>::value; template constexpr bool is_integral_v = is_integral<_Tp>::value; template constexpr bool is_floating_point_v = is_floating_point<_Tp>::value; template constexpr bool is_array_v = is_array<_Tp>::value; template constexpr bool is_pointer_v = is_pointer<_Tp>::value; template constexpr bool is_lvalue_reference_v = is_lvalue_reference<_Tp>::value; template constexpr bool is_rvalue_reference_v = is_rvalue_reference<_Tp>::value; template constexpr bool is_member_object_pointer_v = is_member_object_pointer<_Tp>::value; template constexpr bool is_member_function_pointer_v = is_member_function_pointer<_Tp>::value; template constexpr bool is_enum_v = is_enum<_Tp>::value; template constexpr bool is_union_v = is_union<_Tp>::value; template constexpr bool is_class_v = is_class<_Tp>::value; template constexpr bool is_function_v = is_function<_Tp>::value; // See C++14 §20.10.4.2, composite type categories template constexpr bool is_reference_v = is_reference<_Tp>::value; template constexpr bool is_arithmetic_v = is_arithmetic<_Tp>::value; template constexpr bool is_fundamental_v = is_fundamental<_Tp>::value; template constexpr bool is_object_v = is_object<_Tp>::value; template constexpr bool is_scalar_v = is_scalar<_Tp>::value; template constexpr bool is_compound_v = is_compound<_Tp>::value; template constexpr bool is_member_pointer_v = is_member_pointer<_Tp>::value; // See C++14 §20.10.4.3, type properties template constexpr bool is_const_v = is_const<_Tp>::value; template constexpr bool is_volatile_v = is_volatile<_Tp>::value; template constexpr bool is_trivial_v = is_trivial<_Tp>::value; template constexpr bool is_trivially_copyable_v = is_trivially_copyable<_Tp>::value; template constexpr bool is_standard_layout_v = is_standard_layout<_Tp>::value; template constexpr bool is_pod_v = is_pod<_Tp>::value; template constexpr bool is_literal_type_v = is_literal_type<_Tp>::value; template constexpr bool is_empty_v = is_empty<_Tp>::value; template constexpr bool is_polymorphic_v = is_polymorphic<_Tp>::value; template constexpr bool is_abstract_v = is_abstract<_Tp>::value; template constexpr bool is_final_v = is_final<_Tp>::value; template constexpr bool is_signed_v = is_signed<_Tp>::value; template constexpr bool is_unsigned_v = is_unsigned<_Tp>::value; template constexpr bool is_constructible_v = is_constructible<_Tp, _Args...>::value; template constexpr bool is_default_constructible_v = is_default_constructible<_Tp>::value; template constexpr bool is_copy_constructible_v = is_copy_constructible<_Tp>::value; template constexpr bool is_move_constructible_v = is_move_constructible<_Tp>::value; template constexpr bool is_assignable_v = is_assignable<_Tp, _Up>::value; template constexpr bool is_copy_assignable_v = is_copy_assignable<_Tp>::value; template constexpr bool is_move_assignable_v = is_move_assignable<_Tp>::value; template constexpr bool is_destructible_v = is_destructible<_Tp>::value; template constexpr bool is_trivially_constructible_v = is_trivially_constructible<_Tp, _Args...>::value; template constexpr bool is_trivially_default_constructible_v = is_trivially_default_constructible<_Tp>::value; template constexpr bool is_trivially_copy_constructible_v = is_trivially_copy_constructible<_Tp>::value; template constexpr bool is_trivially_move_constructible_v = is_trivially_move_constructible<_Tp>::value; template constexpr bool is_trivially_assignable_v = is_trivially_assignable<_Tp, _Up>::value; template constexpr bool is_trivially_copy_assignable_v = is_trivially_copy_assignable<_Tp>::value; template constexpr bool is_trivially_move_assignable_v = is_trivially_move_assignable<_Tp>::value; template constexpr bool is_trivially_destructible_v = is_trivially_destructible<_Tp>::value; template constexpr bool is_nothrow_constructible_v = is_nothrow_constructible<_Tp, _Args...>::value; template constexpr bool is_nothrow_default_constructible_v = is_nothrow_default_constructible<_Tp>::value; template constexpr bool is_nothrow_copy_constructible_v = is_nothrow_copy_constructible<_Tp>::value; template constexpr bool is_nothrow_move_constructible_v = is_nothrow_move_constructible<_Tp>::value; template constexpr bool is_nothrow_assignable_v = is_nothrow_assignable<_Tp, _Up>::value; template constexpr bool is_nothrow_copy_assignable_v = is_nothrow_copy_assignable<_Tp>::value; template constexpr bool is_nothrow_move_assignable_v = is_nothrow_move_assignable<_Tp>::value; template constexpr bool is_nothrow_destructible_v = is_nothrow_destructible<_Tp>::value; template constexpr bool has_virtual_destructor_v = has_virtual_destructor<_Tp>::value; // See C++14 §20.10.5, type property queries template constexpr size_t alignment_of_v = alignment_of<_Tp>::value; template constexpr size_t rank_v = rank<_Tp>::value; template constexpr size_t extent_v = extent<_Tp, _Idx>::value; // See C++14 §20.10.6, type relations template constexpr bool is_same_v = is_same<_Tp, _Up>::value; template constexpr bool is_base_of_v = is_base_of<_Base, _Derived>::value; template constexpr bool is_convertible_v = is_convertible<_From, _To>::value; // 3.3.2, Other type transformations // invocation_type (still unimplemented) // raw_invocation_type (still unimplemented) // invocation_type_t (still unimplemented) // raw_invocation_type_t (still unimplemented) } // namespace fundamentals_v1 inline namespace fundamentals_v2 { #define __cpp_lib_experimental_detect 201505 // [meta.detect] template using void_t = void; struct nonesuch { nonesuch() = delete; ~nonesuch() = delete; nonesuch(nonesuch const&) = delete; void operator=(nonesuch const&) = delete; }; template class _Op, typename... _Args> using is_detected = typename std::__detector::value_t; template class _Op, typename... _Args> constexpr bool is_detected_v = is_detected<_Op, _Args...>::value; template class _Op, typename... _Args> using detected_t = typename std::__detector::type; template class _Op, typename... _Args> using detected_or = std::__detected_or<_Default, _Op, _Args...>; template class _Op, typename... _Args> using detected_or_t = typename detected_or<_Default, _Op, _Args...>::type; template class _Op, typename... _Args> using is_detected_exact = is_same<_Expected, detected_t<_Op, _Args...>>; template class _Op, typename... _Args> constexpr bool is_detected_exact_v = is_detected_exact<_Expected, _Op, _Args...>::value; template class _Op, typename... _Args> using is_detected_convertible = is_convertible, _To>; template class _Op, typename... _Args> constexpr bool is_detected_convertible_v = is_detected_convertible<_To, _Op, _Args...>::value; #define __cpp_lib_experimental_logical_traits 201511 template struct conjunction : __and_<_Bn...> { }; template struct disjunction : __or_<_Bn...> { }; template struct negation : __not_<_Pp> { }; template constexpr bool conjunction_v = conjunction<_Bn...>::value; template constexpr bool disjunction_v = disjunction<_Bn...>::value; template constexpr bool negation_v = negation<_Pp>::value; } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // __cplusplus <= 201103L #endif // _GLIBCXX_EXPERIMENTAL_TYPE_TRAITS PK!qe  8/experimental/unordered_mapnu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/unordered_map * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_UNORDERED_MAP #define _GLIBCXX_EXPERIMENTAL_UNORDERED_MAP 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { template inline void erase_if(unordered_map<_Key, _Tp, _Hash, _CPred, _Alloc>& __cont, _Predicate __pred) { __detail::__erase_nodes_if(__cont, __pred); } template inline void erase_if(unordered_multimap<_Key, _Tp, _Hash, _CPred, _Alloc>& __cont, _Predicate __pred) { __detail::__erase_nodes_if(__cont, __pred); } namespace pmr { template, typename _Pred = equal_to<_Key>> using unordered_map = std::unordered_map<_Key, _Tp, _Hash, _Pred, polymorphic_allocator>>; template, typename _Pred = equal_to<_Key>> using unordered_multimap = std::unordered_multimap<_Key, _Tp, _Hash, _Pred, polymorphic_allocator>>; } // namespace pmr } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_UNORDERED_MAP PK!2 8/experimental/unordered_setnu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/unordered_set * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_UNORDERED_SET #define _GLIBCXX_EXPERIMENTAL_UNORDERED_SET 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { template inline void erase_if(unordered_set<_Key, _Hash, _CPred, _Alloc>& __cont, _Predicate __pred) { __detail::__erase_nodes_if(__cont, __pred); } template inline void erase_if(unordered_multiset<_Key, _Hash, _CPred, _Alloc>& __cont, _Predicate __pred) { __detail::__erase_nodes_if(__cont, __pred); } namespace pmr { template, typename _Pred = equal_to<_Key>> using unordered_set = std::unordered_set<_Key, _Hash, _Pred, polymorphic_allocator<_Key>>; template, typename _Pred = equal_to<_Key>> using unordered_multiset = std::unordered_multiset<_Key, _Hash, _Pred, polymorphic_allocator<_Key>>; } // namespace pmr } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_UNORDERED_SET PK!}ԭ8/experimental/utilitynu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/utility * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_UTILITY #define _GLIBCXX_EXPERIMENTAL_UTILITY 1 #if __cplusplus >= 201402L #include #include #include namespace std { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { // 3.1.2, erased-type placeholder using erased_type = std::__erased_type; } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_UTILITY PK!˺  8/experimental/vectornu[// -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file experimental/vector * This is a TS C++ Library header. */ #ifndef _GLIBCXX_EXPERIMENTAL_VECTOR #define _GLIBCXX_EXPERIMENTAL_VECTOR 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace experimental { inline namespace fundamentals_v2 { #define __cpp_lib_experimental_erase_if 201411 template inline void erase_if(vector<_Tp, _Alloc>& __cont, _Predicate __pred) { __cont.erase(std::remove_if(__cont.begin(), __cont.end(), __pred), __cont.end()); } template inline void erase(vector<_Tp, _Alloc>& __cont, const _Up& __value) { __cont.erase(std::remove(__cont.begin(), __cont.end(), __value), __cont.end()); } namespace pmr { template using vector = std::vector<_Tp, polymorphic_allocator<_Tp>>; } // namespace pmr } // namespace fundamentals_v2 } // namespace experimental _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_EXPERIMENTAL_VECTOR PK! `@`@8/ext/typelist.hnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice and // this permission notice appear in supporting documentation. None of // the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied warranty. /** * @file ext/typelist.h * This file is a GNU extension to the Standard C++ Library. * * Contains typelist_chain definitions. * Typelists are an idea by Andrei Alexandrescu. */ #ifndef _TYPELIST_H #define _TYPELIST_H 1 #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** @namespace __gnu_cxx::typelist * @brief GNU typelist extensions for public compile-time use. */ namespace typelist { struct null_type { }; template struct node { typedef Root root; }; // Forward declarations of functors. template struct chain { typedef Hd head; typedef Typelist tail; }; // Apply all typelist types to unary functor. template void apply(Fn&, Typelist); /// Apply all typelist types to generator functor. template void apply_generator(Gn&, Typelist); // Apply all typelist types and values to generator functor. template void apply_generator(Gn&, TypelistT, TypelistV); template struct append; template struct append_typelist; template struct contains; template class Pred> struct filter; template struct at_index; template class Transform> struct transform; template struct flatten; template struct from_first; template struct create1; template struct create2; template struct create3; template struct create4; template struct create5; template struct create6; namespace detail { template struct apply_; template struct apply_ > { void operator()(Fn& f) { f.operator()(Hd()); apply_ next; next(f); } }; template struct apply_ { void operator()(Fn&) { } }; template struct apply_generator1_; template struct apply_generator1_ > { void operator()(Gn& g) { g.template operator()(); apply_generator1_ next; next(g); } }; template struct apply_generator1_ { void operator()(Gn&) { } }; template struct apply_generator2_; template struct apply_generator2_, chain > { void operator()(Gn& g) { g.template operator()(); apply_generator2_ next; next(g); } }; template struct apply_generator2_ { void operator()(Gn&) { } }; template struct append_; template struct append_, Typelist_Chain> { private: typedef append_ append_type; public: typedef chain type; }; template struct append_ { typedef Typelist_Chain type; }; template struct append_ { typedef Typelist_Chain type; }; template<> struct append_ { typedef null_type type; }; template struct append_typelist_; template struct append_typelist_ > { typedef chain type; }; template struct append_typelist_ > { private: typedef typename append_typelist_::type rest_type; public: typedef typename append >::type::root type; }; template struct contains_; template struct contains_ { enum { value = false }; }; template struct contains_, T> { enum { value = contains_::value }; }; template struct contains_, T> { enum { value = true }; }; template class Pred> struct chain_filter_; template class Pred> struct chain_filter_ { typedef null_type type; }; template class Pred> struct chain_filter_, Pred> { private: enum { include_hd = Pred::value }; typedef typename chain_filter_::type rest_type; typedef chain chain_type; public: typedef typename __conditional_type::__type type; }; template struct chain_at_index_; template struct chain_at_index_, 0> { typedef Hd type; }; template struct chain_at_index_, i> { typedef typename chain_at_index_::type type; }; template class Transform> struct chain_transform_; template class Transform> struct chain_transform_ { typedef null_type type; }; template class Transform> struct chain_transform_, Transform> { private: typedef typename chain_transform_::type rest_type; typedef typename Transform::type transform_type; public: typedef chain type; }; template struct chain_flatten_; template struct chain_flatten_ > { typedef typename Hd_Tl::root type; }; template struct chain_flatten_ > { private: typedef typename chain_flatten_::type rest_type; typedef append > append_type; public: typedef typename append_type::type::root type; }; } // namespace detail #define _GLIBCXX_TYPELIST_CHAIN1(X0) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN2(X0, X1) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN3(X0, X1, X2) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN4(X0, X1, X2, X3) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN5(X0, X1, X2, X3, X4) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN6(X0, X1, X2, X3, X4, X5) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN7(X0, X1, X2, X3, X4, X5, X6) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN8(X0, X1, X2, X3, X4, X5, X6, X7) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN9(X0, X1, X2, X3, X4, X5, X6, X7, X8) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN10(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN11(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN12(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN13(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN14(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN15(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN16(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14, X15) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN17(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14, X15, X16) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN18(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14, X15, X16, X17) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN19(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14, X15, X16, X17, X18) __gnu_cxx::typelist::chain #define _GLIBCXX_TYPELIST_CHAIN20(X0, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14, X15, X16, X17, X18, X19) __gnu_cxx::typelist::chain template void apply(Fn& fn, Typelist) { detail::apply_ a; a(fn); } template void apply_generator(Fn& fn, Typelist) { detail::apply_generator1_ a; a(fn); } template void apply_generator(Fn& fn, TypelistT, TypelistV) { typedef typename TypelistT::root rootT; typedef typename TypelistV::root rootV; detail::apply_generator2_ a; a(fn); } template struct append { private: typedef typename Typelist0::root root0_type; typedef typename Typelist1::root root1_type; typedef detail::append_ append_type; public: typedef node type; }; template struct append_typelist { private: typedef typename Typelist_Typelist::root root_type; typedef detail::append_typelist_ append_type; public: typedef node type; }; template struct contains { private: typedef typename Typelist::root root_type; public: enum { value = detail::contains_::value }; }; template class Pred> struct filter { private: typedef typename Typelist::root root_type; typedef detail::chain_filter_ filter_type; public: typedef node type; }; template struct at_index { private: typedef typename Typelist::root root_type; typedef detail::chain_at_index_ index_type; public: typedef typename index_type::type type; }; template class Transform> struct transform { private: typedef typename Typelist::root root_type; typedef detail::chain_transform_ transform_type; public: typedef node type; }; template struct flatten { private: typedef typename Typelist_Typelist::root root_type; typedef typename detail::chain_flatten_::type flatten_type; public: typedef node type; }; template struct from_first { private: typedef typename at_index::type first_type; public: typedef node > type; }; template struct create1 { typedef node<_GLIBCXX_TYPELIST_CHAIN1(T1)> type; }; template struct create2 { typedef node<_GLIBCXX_TYPELIST_CHAIN2(T1,T2)> type; }; template struct create3 { typedef node<_GLIBCXX_TYPELIST_CHAIN3(T1,T2,T3)> type; }; template struct create4 { typedef node<_GLIBCXX_TYPELIST_CHAIN4(T1,T2,T3,T4)> type; }; template struct create5 { typedef node<_GLIBCXX_TYPELIST_CHAIN5(T1,T2,T3,T4,T5)> type; }; template struct create6 { typedef node<_GLIBCXX_TYPELIST_CHAIN6(T1,T2,T3,T4,T5,T6)> type; }; } // namespace typelist _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!P>\>\8/ext/vstring.tccnu[// Versatile string -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/vstring.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ext/vstring.h} */ #ifndef _VSTRING_TCC #define _VSTRING_TCC 1 #pragma GCC system_header #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template class _Base> const typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>::npos; template class _Base> void __versa_string<_CharT, _Traits, _Alloc, _Base>:: resize(size_type __n, _CharT __c) { const size_type __size = this->size(); if (__size < __n) this->append(__n - __size, __c); else if (__n < __size) this->_M_erase(__n, __size - __n); } template class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base>& __versa_string<_CharT, _Traits, _Alloc, _Base>:: _M_append(const _CharT* __s, size_type __n) { const size_type __len = __n + this->size(); if (__len <= this->capacity() && !this->_M_is_shared()) { if (__n) this->_S_copy(this->_M_data() + this->size(), __s, __n); } else this->_M_mutate(this->size(), size_type(0), __s, __n); this->_M_set_length(__len); return *this; } template class _Base> template __versa_string<_CharT, _Traits, _Alloc, _Base>& __versa_string<_CharT, _Traits, _Alloc, _Base>:: _M_replace_dispatch(const_iterator __i1, const_iterator __i2, _InputIterator __k1, _InputIterator __k2, std::__false_type) { const __versa_string __s(__k1, __k2); const size_type __n1 = __i2 - __i1; return _M_replace(__i1 - _M_ibegin(), __n1, __s._M_data(), __s.size()); } template class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base>& __versa_string<_CharT, _Traits, _Alloc, _Base>:: _M_replace_aux(size_type __pos1, size_type __n1, size_type __n2, _CharT __c) { _M_check_length(__n1, __n2, "__versa_string::_M_replace_aux"); const size_type __old_size = this->size(); const size_type __new_size = __old_size + __n2 - __n1; if (__new_size <= this->capacity() && !this->_M_is_shared()) { _CharT* __p = this->_M_data() + __pos1; const size_type __how_much = __old_size - __pos1 - __n1; if (__how_much && __n1 != __n2) this->_S_move(__p + __n2, __p + __n1, __how_much); } else this->_M_mutate(__pos1, __n1, 0, __n2); if (__n2) this->_S_assign(this->_M_data() + __pos1, __n2, __c); this->_M_set_length(__new_size); return *this; } template class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base>& __versa_string<_CharT, _Traits, _Alloc, _Base>:: _M_replace(size_type __pos, size_type __len1, const _CharT* __s, const size_type __len2) { _M_check_length(__len1, __len2, "__versa_string::_M_replace"); const size_type __old_size = this->size(); const size_type __new_size = __old_size + __len2 - __len1; if (__new_size <= this->capacity() && !this->_M_is_shared()) { _CharT* __p = this->_M_data() + __pos; const size_type __how_much = __old_size - __pos - __len1; if (_M_disjunct(__s)) { if (__how_much && __len1 != __len2) this->_S_move(__p + __len2, __p + __len1, __how_much); if (__len2) this->_S_copy(__p, __s, __len2); } else { // Work in-place. if (__len2 && __len2 <= __len1) this->_S_move(__p, __s, __len2); if (__how_much && __len1 != __len2) this->_S_move(__p + __len2, __p + __len1, __how_much); if (__len2 > __len1) { if (__s + __len2 <= __p + __len1) this->_S_move(__p, __s, __len2); else if (__s >= __p + __len1) this->_S_copy(__p, __s + __len2 - __len1, __len2); else { const size_type __nleft = (__p + __len1) - __s; this->_S_move(__p, __s, __nleft); this->_S_copy(__p + __nleft, __p + __len2, __len2 - __nleft); } } } } else this->_M_mutate(__pos, __len1, __s, __len2); this->_M_set_length(__new_size); return *this; } template class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base> operator+(const __versa_string<_CharT, _Traits, _Alloc, _Base>& __lhs, const __versa_string<_CharT, _Traits, _Alloc, _Base>& __rhs) { __versa_string<_CharT, _Traits, _Alloc, _Base> __str; __str.reserve(__lhs.size() + __rhs.size()); __str.append(__lhs); __str.append(__rhs); return __str; } template class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base> operator+(const _CharT* __lhs, const __versa_string<_CharT, _Traits, _Alloc, _Base>& __rhs) { __glibcxx_requires_string(__lhs); typedef __versa_string<_CharT, _Traits, _Alloc, _Base> __string_type; typedef typename __string_type::size_type __size_type; const __size_type __len = _Traits::length(__lhs); __string_type __str; __str.reserve(__len + __rhs.size()); __str.append(__lhs, __len); __str.append(__rhs); return __str; } template class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base> operator+(_CharT __lhs, const __versa_string<_CharT, _Traits, _Alloc, _Base>& __rhs) { __versa_string<_CharT, _Traits, _Alloc, _Base> __str; __str.reserve(__rhs.size() + 1); __str.push_back(__lhs); __str.append(__rhs); return __str; } template class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base> operator+(const __versa_string<_CharT, _Traits, _Alloc, _Base>& __lhs, const _CharT* __rhs) { __glibcxx_requires_string(__rhs); typedef __versa_string<_CharT, _Traits, _Alloc, _Base> __string_type; typedef typename __string_type::size_type __size_type; const __size_type __len = _Traits::length(__rhs); __string_type __str; __str.reserve(__lhs.size() + __len); __str.append(__lhs); __str.append(__rhs, __len); return __str; } template class _Base> __versa_string<_CharT, _Traits, _Alloc, _Base> operator+(const __versa_string<_CharT, _Traits, _Alloc, _Base>& __lhs, _CharT __rhs) { __versa_string<_CharT, _Traits, _Alloc, _Base> __str; __str.reserve(__lhs.size() + 1); __str.append(__lhs); __str.push_back(__rhs); return __str; } template class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: copy(_CharT* __s, size_type __n, size_type __pos) const { _M_check(__pos, "__versa_string::copy"); __n = _M_limit(__pos, __n); __glibcxx_requires_string_len(__s, __n); if (__n) this->_S_copy(__s, this->_M_data() + __pos, __n); // 21.3.5.7 par 3: do not append null. (good.) return __n; } template class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__s, __n); const size_type __size = this->size(); const _CharT* __data = this->_M_data(); if (__n == 0) return __pos <= __size ? __pos : npos; if (__n <= __size) { for (; __pos <= __size - __n; ++__pos) if (traits_type::eq(__data[__pos], __s[0]) && traits_type::compare(__data + __pos + 1, __s + 1, __n - 1) == 0) return __pos; } return npos; } template class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { size_type __ret = npos; const size_type __size = this->size(); if (__pos < __size) { const _CharT* __data = this->_M_data(); const size_type __n = __size - __pos; const _CharT* __p = traits_type::find(__data + __pos, __n, __c); if (__p) __ret = __p - __data; } return __ret; } template class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: rfind(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__s, __n); const size_type __size = this->size(); if (__n <= __size) { __pos = std::min(size_type(__size - __n), __pos); const _CharT* __data = this->_M_data(); do { if (traits_type::compare(__data + __pos, __s, __n) == 0) return __pos; } while (__pos-- > 0); } return npos; } template class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: rfind(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { size_type __size = this->size(); if (__size) { if (--__size > __pos) __size = __pos; for (++__size; __size-- > 0; ) if (traits_type::eq(this->_M_data()[__size], __c)) return __size; } return npos; } template class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find_first_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__s, __n); for (; __n && __pos < this->size(); ++__pos) { const _CharT* __p = traits_type::find(__s, __n, this->_M_data()[__pos]); if (__p) return __pos; } return npos; } template class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find_last_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__s, __n); size_type __size = this->size(); if (__size && __n) { if (--__size > __pos) __size = __pos; do { if (traits_type::find(__s, __n, this->_M_data()[__size])) return __size; } while (__size-- != 0); } return npos; } template class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__s, __n); for (; __pos < this->size(); ++__pos) if (!traits_type::find(__s, __n, this->_M_data()[__pos])) return __pos; return npos; } template class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find_first_not_of(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { for (; __pos < this->size(); ++__pos) if (!traits_type::eq(this->_M_data()[__pos], __c)) return __pos; return npos; } template class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find_last_not_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_requires_string_len(__s, __n); size_type __size = this->size(); if (__size) { if (--__size > __pos) __size = __pos; do { if (!traits_type::find(__s, __n, this->_M_data()[__size])) return __size; } while (__size--); } return npos; } template class _Base> typename __versa_string<_CharT, _Traits, _Alloc, _Base>::size_type __versa_string<_CharT, _Traits, _Alloc, _Base>:: find_last_not_of(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { size_type __size = this->size(); if (__size) { if (--__size > __pos) __size = __pos; do { if (!traits_type::eq(this->_M_data()[__size], __c)) return __size; } while (__size--); } return npos; } template class _Base> int __versa_string<_CharT, _Traits, _Alloc, _Base>:: compare(size_type __pos, size_type __n, const __versa_string& __str) const { _M_check(__pos, "__versa_string::compare"); __n = _M_limit(__pos, __n); const size_type __osize = __str.size(); const size_type __len = std::min(__n, __osize); int __r = traits_type::compare(this->_M_data() + __pos, __str.data(), __len); if (!__r) __r = this->_S_compare(__n, __osize); return __r; } template class _Base> int __versa_string<_CharT, _Traits, _Alloc, _Base>:: compare(size_type __pos1, size_type __n1, const __versa_string& __str, size_type __pos2, size_type __n2) const { _M_check(__pos1, "__versa_string::compare"); __str._M_check(__pos2, "__versa_string::compare"); __n1 = _M_limit(__pos1, __n1); __n2 = __str._M_limit(__pos2, __n2); const size_type __len = std::min(__n1, __n2); int __r = traits_type::compare(this->_M_data() + __pos1, __str.data() + __pos2, __len); if (!__r) __r = this->_S_compare(__n1, __n2); return __r; } template class _Base> int __versa_string<_CharT, _Traits, _Alloc, _Base>:: compare(const _CharT* __s) const { __glibcxx_requires_string(__s); const size_type __size = this->size(); const size_type __osize = traits_type::length(__s); const size_type __len = std::min(__size, __osize); int __r = traits_type::compare(this->_M_data(), __s, __len); if (!__r) __r = this->_S_compare(__size, __osize); return __r; } template class _Base> int __versa_string <_CharT, _Traits, _Alloc, _Base>:: compare(size_type __pos, size_type __n1, const _CharT* __s) const { __glibcxx_requires_string(__s); _M_check(__pos, "__versa_string::compare"); __n1 = _M_limit(__pos, __n1); const size_type __osize = traits_type::length(__s); const size_type __len = std::min(__n1, __osize); int __r = traits_type::compare(this->_M_data() + __pos, __s, __len); if (!__r) __r = this->_S_compare(__n1, __osize); return __r; } template class _Base> int __versa_string <_CharT, _Traits, _Alloc, _Base>:: compare(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2) const { __glibcxx_requires_string_len(__s, __n2); _M_check(__pos, "__versa_string::compare"); __n1 = _M_limit(__pos, __n1); const size_type __len = std::min(__n1, __n2); int __r = traits_type::compare(this->_M_data() + __pos, __s, __len); if (!__r) __r = this->_S_compare(__n1, __n2); return __r; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template class _Base> basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __in, __gnu_cxx::__versa_string<_CharT, _Traits, _Alloc, _Base>& __str) { typedef basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; typedef __gnu_cxx::__versa_string<_CharT, _Traits, _Alloc, _Base> __string_type; typedef typename __istream_type::int_type __int_type; typedef typename __string_type::size_type __size_type; typedef ctype<_CharT> __ctype_type; typedef typename __ctype_type::ctype_base __ctype_base; __size_type __extracted = 0; typename __ios_base::iostate __err = __ios_base::goodbit; typename __istream_type::sentry __cerb(__in, false); if (__cerb) { __try { // Avoid reallocation for common case. __str.erase(); _CharT __buf[128]; __size_type __len = 0; const streamsize __w = __in.width(); const __size_type __n = __w > 0 ? static_cast<__size_type>(__w) : __str.max_size(); const __ctype_type& __ct = use_facet<__ctype_type>(__in.getloc()); const __int_type __eof = _Traits::eof(); __int_type __c = __in.rdbuf()->sgetc(); while (__extracted < __n && !_Traits::eq_int_type(__c, __eof) && !__ct.is(__ctype_base::space, _Traits::to_char_type(__c))) { if (__len == sizeof(__buf) / sizeof(_CharT)) { __str.append(__buf, sizeof(__buf) / sizeof(_CharT)); __len = 0; } __buf[__len++] = _Traits::to_char_type(__c); ++__extracted; __c = __in.rdbuf()->snextc(); } __str.append(__buf, __len); if (_Traits::eq_int_type(__c, __eof)) __err |= __ios_base::eofbit; __in.width(0); } __catch(__cxxabiv1::__forced_unwind&) { __in._M_setstate(__ios_base::badbit); __throw_exception_again; } __catch(...) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 91. Description of operator>> and getline() for string<> // might cause endless loop __in._M_setstate(__ios_base::badbit); } } // 211. operator>>(istream&, string&) doesn't set failbit if (!__extracted) __err |= __ios_base::failbit; if (__err) __in.setstate(__err); return __in; } template class _Base> basic_istream<_CharT, _Traits>& getline(basic_istream<_CharT, _Traits>& __in, __gnu_cxx::__versa_string<_CharT, _Traits, _Alloc, _Base>& __str, _CharT __delim) { typedef basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; typedef __gnu_cxx::__versa_string<_CharT, _Traits, _Alloc, _Base> __string_type; typedef typename __istream_type::int_type __int_type; typedef typename __string_type::size_type __size_type; __size_type __extracted = 0; const __size_type __n = __str.max_size(); typename __ios_base::iostate __err = __ios_base::goodbit; typename __istream_type::sentry __cerb(__in, true); if (__cerb) { __try { // Avoid reallocation for common case. __str.erase(); _CharT __buf[128]; __size_type __len = 0; const __int_type __idelim = _Traits::to_int_type(__delim); const __int_type __eof = _Traits::eof(); __int_type __c = __in.rdbuf()->sgetc(); while (__extracted < __n && !_Traits::eq_int_type(__c, __eof) && !_Traits::eq_int_type(__c, __idelim)) { if (__len == sizeof(__buf) / sizeof(_CharT)) { __str.append(__buf, sizeof(__buf) / sizeof(_CharT)); __len = 0; } __buf[__len++] = _Traits::to_char_type(__c); ++__extracted; __c = __in.rdbuf()->snextc(); } __str.append(__buf, __len); if (_Traits::eq_int_type(__c, __eof)) __err |= __ios_base::eofbit; else if (_Traits::eq_int_type(__c, __idelim)) { ++__extracted; __in.rdbuf()->sbumpc(); } else __err |= __ios_base::failbit; } __catch(__cxxabiv1::__forced_unwind&) { __in._M_setstate(__ios_base::badbit); __throw_exception_again; } __catch(...) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 91. Description of operator>> and getline() for string<> // might cause endless loop __in._M_setstate(__ios_base::badbit); } } if (!__extracted) __err |= __ios_base::failbit; if (__err) __in.setstate(__err); return __in; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _VSTRING_TCC PK!8/ext/vstring_util.hnu[// Versatile string utility -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/vstring_util.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ext/vstring.h} */ #ifndef _VSTRING_UTIL_H #define _VSTRING_UTIL_H 1 #pragma GCC system_header #include #include #include // For less #include #include #include #include #include #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template struct __vstring_utility { typedef typename _Alloc::template rebind<_CharT>::other _CharT_alloc_type; typedef _Traits traits_type; typedef typename _Traits::char_type value_type; typedef typename _CharT_alloc_type::size_type size_type; typedef typename _CharT_alloc_type::difference_type difference_type; typedef typename _CharT_alloc_type::pointer pointer; typedef typename _CharT_alloc_type::const_pointer const_pointer; // For __sso_string. typedef __gnu_cxx:: __normal_iterator > __sso_iterator; typedef __gnu_cxx:: __normal_iterator > __const_sso_iterator; // For __rc_string. typedef __gnu_cxx:: __normal_iterator > __rc_iterator; typedef __gnu_cxx:: __normal_iterator > __const_rc_iterator; // NB: When the allocator is empty, deriving from it saves space // (http://www.cantrip.org/emptyopt.html). template struct _Alloc_hider : public _Alloc1 { _Alloc_hider(_CharT* __ptr) : _Alloc1(), _M_p(__ptr) { } _Alloc_hider(const _Alloc1& __a, _CharT* __ptr) : _Alloc1(__a), _M_p(__ptr) { } _CharT* _M_p; // The actual data. }; // When __n = 1 way faster than the general multichar // traits_type::copy/move/assign. static void _S_copy(_CharT* __d, const _CharT* __s, size_type __n) { if (__n == 1) traits_type::assign(*__d, *__s); else traits_type::copy(__d, __s, __n); } static void _S_move(_CharT* __d, const _CharT* __s, size_type __n) { if (__n == 1) traits_type::assign(*__d, *__s); else traits_type::move(__d, __s, __n); } static void _S_assign(_CharT* __d, size_type __n, _CharT __c) { if (__n == 1) traits_type::assign(*__d, __c); else traits_type::assign(__d, __n, __c); } // _S_copy_chars is a separate template to permit specialization // to optimize for the common case of pointers as iterators. template static void _S_copy_chars(_CharT* __p, _Iterator __k1, _Iterator __k2) { for (; __k1 != __k2; ++__k1, ++__p) traits_type::assign(*__p, *__k1); // These types are off. } static void _S_copy_chars(_CharT* __p, __sso_iterator __k1, __sso_iterator __k2) { _S_copy_chars(__p, __k1.base(), __k2.base()); } static void _S_copy_chars(_CharT* __p, __const_sso_iterator __k1, __const_sso_iterator __k2) { _S_copy_chars(__p, __k1.base(), __k2.base()); } static void _S_copy_chars(_CharT* __p, __rc_iterator __k1, __rc_iterator __k2) { _S_copy_chars(__p, __k1.base(), __k2.base()); } static void _S_copy_chars(_CharT* __p, __const_rc_iterator __k1, __const_rc_iterator __k2) { _S_copy_chars(__p, __k1.base(), __k2.base()); } static void _S_copy_chars(_CharT* __p, _CharT* __k1, _CharT* __k2) { _S_copy(__p, __k1, __k2 - __k1); } static void _S_copy_chars(_CharT* __p, const _CharT* __k1, const _CharT* __k2) { _S_copy(__p, __k1, __k2 - __k1); } static int _S_compare(size_type __n1, size_type __n2) { const difference_type __d = difference_type(__n1 - __n2); if (__d > __numeric_traits_integer::__max) return __numeric_traits_integer::__max; else if (__d < __numeric_traits_integer::__min) return __numeric_traits_integer::__min; else return int(__d); } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _VSTRING_UTIL_H */ PK!E0088/ext/pb_ds/detail/bin_search_tree_/bin_search_tree_.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/bin_search_tree_.hpp * Contains an implementation class for binary search tree. */ #include #include #include #include #include #include #include #ifdef _GLIBCXX_DEBUG #include #endif #include #include #include namespace __gnu_pbds { namespace detail { #ifdef PB_DS_DATA_TRUE_INDICATOR #define PB_DS_BIN_TREE_NAME bin_search_tree_map #endif #ifdef PB_DS_DATA_FALSE_INDICATOR #define PB_DS_BIN_TREE_NAME bin_search_tree_set #endif #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ PB_DS_BIN_TREE_NAME #define PB_DS_BIN_TREE_TRAITS_BASE \ types_traits #ifdef _GLIBCXX_DEBUG #define PB_DS_DEBUG_MAP_BASE_C_DEC \ debug_map_base, \ typename _Alloc::template rebind::other::const_reference> #endif #ifdef PB_DS_TREE_TRACE #define PB_DS_TREE_TRACE_BASE_C_DEC \ tree_trace_base #endif /* * @brief Binary search tree (BST). * * This implementation uses an idea from the SGI STL (using a @a * header node which is needed for efficient iteration). */ template class PB_DS_BIN_TREE_NAME : #ifdef _GLIBCXX_DEBUG public PB_DS_DEBUG_MAP_BASE_C_DEC, #endif #ifdef PB_DS_TREE_TRACE public PB_DS_TREE_TRACE_BASE_C_DEC, #endif public Cmp_Fn, public PB_DS_BIN_TREE_TRAITS_BASE, public Node_And_It_Traits::node_update { typedef Node_And_It_Traits traits_type; protected: typedef PB_DS_BIN_TREE_TRAITS_BASE traits_base; typedef typename _Alloc::template rebind::other node_allocator; typedef typename node_allocator::value_type node; typedef typename node_allocator::pointer node_pointer; typedef typename traits_type::null_node_update_pointer null_node_update_pointer; private: typedef cond_dealtor cond_dealtor_t; #ifdef _GLIBCXX_DEBUG typedef PB_DS_DEBUG_MAP_BASE_C_DEC debug_base; #endif public: typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef typename traits_base::key_type key_type; typedef typename traits_base::key_pointer key_pointer; typedef typename traits_base::key_const_pointer key_const_pointer; typedef typename traits_base::key_reference key_reference; typedef typename traits_base::key_const_reference key_const_reference; #ifdef PB_DS_DATA_TRUE_INDICATOR typedef typename traits_base::mapped_type mapped_type; typedef typename traits_base::mapped_pointer mapped_pointer; typedef typename traits_base::mapped_const_pointer mapped_const_pointer; typedef typename traits_base::mapped_reference mapped_reference; typedef typename traits_base::mapped_const_reference mapped_const_reference; #endif typedef typename traits_base::value_type value_type; typedef typename traits_base::pointer pointer; typedef typename traits_base::const_pointer const_pointer; typedef typename traits_base::reference reference; typedef typename traits_base::const_reference const_reference; typedef typename traits_type::point_const_iterator point_const_iterator; typedef point_const_iterator const_iterator; typedef typename traits_type::point_iterator point_iterator; typedef point_iterator iterator; typedef typename traits_type::const_reverse_iterator const_reverse_iterator; typedef typename traits_type::reverse_iterator reverse_iterator; typedef typename traits_type::node_const_iterator node_const_iterator; typedef typename traits_type::node_iterator node_iterator; typedef typename traits_type::node_update node_update; typedef Cmp_Fn cmp_fn; typedef _Alloc allocator_type; PB_DS_BIN_TREE_NAME(); PB_DS_BIN_TREE_NAME(const Cmp_Fn&); PB_DS_BIN_TREE_NAME(const Cmp_Fn&, const node_update&); PB_DS_BIN_TREE_NAME(const PB_DS_CLASS_C_DEC&); void swap(PB_DS_CLASS_C_DEC&); ~PB_DS_BIN_TREE_NAME(); inline bool empty() const; inline size_type size() const; inline size_type max_size() const; Cmp_Fn& get_cmp_fn(); const Cmp_Fn& get_cmp_fn() const; inline point_iterator lower_bound(key_const_reference); inline point_const_iterator lower_bound(key_const_reference) const; inline point_iterator upper_bound(key_const_reference); inline point_const_iterator upper_bound(key_const_reference) const; inline point_iterator find(key_const_reference); inline point_const_iterator find(key_const_reference) const; inline iterator begin(); inline const_iterator begin() const; inline iterator end(); inline const_iterator end() const; inline reverse_iterator rbegin(); inline const_reverse_iterator rbegin() const; inline reverse_iterator rend(); inline const_reverse_iterator rend() const; /// Returns a const node_iterator corresponding to the node at the /// root of the tree. inline node_const_iterator node_begin() const; /// Returns a node_iterator corresponding to the node at the /// root of the tree. inline node_iterator node_begin(); /// Returns a const node_iterator corresponding to a node just /// after a leaf of the tree. inline node_const_iterator node_end() const; /// Returns a node_iterator corresponding to a node just /// after a leaf of the tree. inline node_iterator node_end(); void clear(); protected: void value_swap(PB_DS_CLASS_C_DEC&); void initialize_min_max(); inline iterator insert_imp_empty(const_reference); inline iterator insert_leaf_new(const_reference, node_pointer, bool); inline node_pointer get_new_node_for_leaf_insert(const_reference, false_type); inline node_pointer get_new_node_for_leaf_insert(const_reference, true_type); inline void actual_erase_node(node_pointer); inline std::pair erase(node_pointer); inline void update_min_max_for_erased_node(node_pointer); static void clear_imp(node_pointer); inline std::pair insert_leaf(const_reference); inline void rotate_left(node_pointer); inline void rotate_right(node_pointer); inline void rotate_parent(node_pointer); inline void apply_update(node_pointer, null_node_update_pointer); template inline void apply_update(node_pointer, Node_Update_*); inline void update_to_top(node_pointer, null_node_update_pointer); template inline void update_to_top(node_pointer, Node_Update_*); bool join_prep(PB_DS_CLASS_C_DEC&); void join_finish(PB_DS_CLASS_C_DEC&); bool split_prep(key_const_reference, PB_DS_CLASS_C_DEC&); void split_finish(PB_DS_CLASS_C_DEC&); size_type recursive_count(node_pointer) const; #ifdef _GLIBCXX_DEBUG void assert_valid(const char*, int) const; void structure_only_assert_valid(const char*, int) const; void assert_node_consistent(const node_pointer, const char*, int) const; #endif private: #ifdef _GLIBCXX_DEBUG void assert_iterators(const char*, int) const; void assert_consistent_with_debug_base(const char*, int) const; void assert_node_consistent_with_left(const node_pointer, const char*, int) const; void assert_node_consistent_with_right(const node_pointer, const char*, int) const; void assert_consistent_with_debug_base(const node_pointer, const char*, int) const; void assert_min(const char*, int) const; void assert_min_imp(const node_pointer, const char*, int) const; void assert_max(const char*, int) const; void assert_max_imp(const node_pointer, const char*, int) const; void assert_size(const char*, int) const; typedef std::pair node_consistent_t; node_consistent_t assert_node_consistent_(const node_pointer, const char*, int) const; #endif void initialize(); node_pointer recursive_copy_node(const node_pointer); protected: node_pointer m_p_head; size_type m_size; static node_allocator s_node_allocator; }; #define PB_DS_STRUCT_ONLY_ASSERT_VALID(X) \ _GLIBCXX_DEBUG_ONLY(X.structure_only_assert_valid(__FILE__, __LINE__);) #define PB_DS_ASSERT_NODE_CONSISTENT(_Node) \ _GLIBCXX_DEBUG_ONLY(assert_node_consistent(_Node, __FILE__, __LINE__);) #include #include #include #include #include #include #include #include #include #include #undef PB_DS_ASSERT_NODE_CONSISTENT #undef PB_DS_STRUCT_ONLY_ASSERT_VALID #undef PB_DS_CLASS_C_DEC #undef PB_DS_CLASS_T_DEC #undef PB_DS_BIN_TREE_NAME #undef PB_DS_BIN_TREE_TRAITS_BASE #undef PB_DS_DEBUG_MAP_BASE_C_DEC #ifdef PB_DS_TREE_TRACE #undef PB_DS_TREE_TRACE_BASE_C_DEC #endif } // namespace detail } // namespace __gnu_pbds PK!Z"G8/ext/pb_ds/detail/bin_search_tree_/constructors_destructor_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/constructors_destructor_fn_imps.hpp * Contains an implementation class for bin_search_tree_. */ PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_allocator PB_DS_CLASS_C_DEC::s_node_allocator; PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_BIN_TREE_NAME() : m_p_head(s_node_allocator.allocate(1)), m_size(0) { initialize(); PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_BIN_TREE_NAME(const Cmp_Fn& r_cmp_fn) : Cmp_Fn(r_cmp_fn), m_p_head(s_node_allocator.allocate(1)), m_size(0) { initialize(); PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_BIN_TREE_NAME(const Cmp_Fn& r_cmp_fn, const node_update& r_node_update) : Cmp_Fn(r_cmp_fn), node_update(r_node_update), m_p_head(s_node_allocator.allocate(1)), m_size(0) { initialize(); PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_BIN_TREE_NAME(const PB_DS_CLASS_C_DEC& other) : #ifdef _GLIBCXX_DEBUG debug_base(other), #endif #ifdef PB_DS_TREE_TRACE PB_DS_TREE_TRACE_BASE_C_DEC(other), #endif Cmp_Fn(other), node_update(other), m_p_head(s_node_allocator.allocate(1)), m_size(0) { initialize(); m_size = other.m_size; PB_DS_STRUCT_ONLY_ASSERT_VALID(other) __try { m_p_head->m_p_parent = recursive_copy_node(other.m_p_head->m_p_parent); if (m_p_head->m_p_parent != 0) m_p_head->m_p_parent->m_p_parent = m_p_head; m_size = other.m_size; initialize_min_max(); } __catch(...) { _GLIBCXX_DEBUG_ONLY(debug_base::clear();) s_node_allocator.deallocate(m_p_head, 1); __throw_exception_again; } PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) PB_DS_STRUCT_ONLY_ASSERT_VALID(other) value_swap(other); std::swap((Cmp_Fn& )(*this), (Cmp_Fn& )other); PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) PB_DS_STRUCT_ONLY_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: value_swap(PB_DS_CLASS_C_DEC& other) { _GLIBCXX_DEBUG_ONLY(debug_base::swap(other);) std::swap(m_p_head, other.m_p_head); std::swap(m_size, other.m_size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~PB_DS_BIN_TREE_NAME() { clear(); s_node_allocator.deallocate(m_p_head, 1); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: initialize() { m_p_head->m_p_parent = 0; m_p_head->m_p_left = m_p_head; m_p_head->m_p_right = m_p_head; m_size = 0; } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: recursive_copy_node(const node_pointer p_nd) { if (p_nd == 0) return (0); node_pointer p_ret = s_node_allocator.allocate(1); __try { new (p_ret) node(*p_nd); } __catch(...) { s_node_allocator.deallocate(p_ret, 1); __throw_exception_again; } p_ret->m_p_left = p_ret->m_p_right = 0; __try { p_ret->m_p_left = recursive_copy_node(p_nd->m_p_left); p_ret->m_p_right = recursive_copy_node(p_nd->m_p_right); } __catch(...) { clear_imp(p_ret); __throw_exception_again; } if (p_ret->m_p_left != 0) p_ret->m_p_left->m_p_parent = p_ret; if (p_ret->m_p_right != 0) p_ret->m_p_right->m_p_parent = p_ret; PB_DS_ASSERT_NODE_CONSISTENT(p_ret) return p_ret; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: initialize_min_max() { if (m_p_head->m_p_parent == 0) { m_p_head->m_p_left = m_p_head->m_p_right = m_p_head; return; } { node_pointer p_min = m_p_head->m_p_parent; while (p_min->m_p_left != 0) p_min = p_min->m_p_left; m_p_head->m_p_left = p_min; } { node_pointer p_max = m_p_head->m_p_parent; while (p_max->m_p_right != 0) p_max = p_max->m_p_right; m_p_head->m_p_right = p_max; } } PK!58/ext/pb_ds/detail/bin_search_tree_/debug_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/debug_fn_imps.hpp * Contains an implementation class for bin_search_tree_. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { structure_only_assert_valid(__file, __line); assert_consistent_with_debug_base(__file, __line); assert_size(__file, __line); assert_iterators(__file, __line); if (m_p_head->m_p_parent == 0) { PB_DS_DEBUG_VERIFY(m_size == 0); } else { PB_DS_DEBUG_VERIFY(m_size > 0); } } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: structure_only_assert_valid(const char* __file, int __line) const { PB_DS_DEBUG_VERIFY(m_p_head != 0); if (m_p_head->m_p_parent == 0) { PB_DS_DEBUG_VERIFY(m_p_head->m_p_left == m_p_head); PB_DS_DEBUG_VERIFY(m_p_head->m_p_right == m_p_head); } else { PB_DS_DEBUG_VERIFY(m_p_head->m_p_parent->m_p_parent == m_p_head); PB_DS_DEBUG_VERIFY(m_p_head->m_p_left != m_p_head); PB_DS_DEBUG_VERIFY(m_p_head->m_p_right != m_p_head); } if (m_p_head->m_p_parent != 0) assert_node_consistent(m_p_head->m_p_parent, __file, __line); assert_min(__file, __line); assert_max(__file, __line); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_node_consistent(const node_pointer p_nd, const char* __file, int __line) const { assert_node_consistent_(p_nd, __file, __line); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_consistent_t PB_DS_CLASS_C_DEC:: assert_node_consistent_(const node_pointer p_nd, const char* __file, int __line) const { if (p_nd == 0) return (std::make_pair((const_pointer)0,(const_pointer)0)); assert_node_consistent_with_left(p_nd, __file, __line); assert_node_consistent_with_right(p_nd, __file, __line); const std::pair l_range = assert_node_consistent_(p_nd->m_p_left, __file, __line); if (l_range.second != 0) PB_DS_DEBUG_VERIFY(Cmp_Fn::operator()(PB_DS_V2F(*l_range.second), PB_DS_V2F(p_nd->m_value))); const std::pair r_range = assert_node_consistent_(p_nd->m_p_right, __file, __line); if (r_range.first != 0) PB_DS_DEBUG_VERIFY(Cmp_Fn::operator()(PB_DS_V2F(p_nd->m_value), PB_DS_V2F(*r_range.first))); return std::make_pair((l_range.first != 0) ? l_range.first : &p_nd->m_value, (r_range.second != 0)? r_range.second : &p_nd->m_value); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_node_consistent_with_left(const node_pointer p_nd, const char* __file, int __line) const { if (p_nd->m_p_left == 0) return; PB_DS_DEBUG_VERIFY(p_nd->m_p_left->m_p_parent == p_nd); PB_DS_DEBUG_VERIFY(!Cmp_Fn::operator()(PB_DS_V2F(p_nd->m_value), PB_DS_V2F(p_nd->m_p_left->m_value))); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_node_consistent_with_right(const node_pointer p_nd, const char* __file, int __line) const { if (p_nd->m_p_right == 0) return; PB_DS_DEBUG_VERIFY(p_nd->m_p_right->m_p_parent == p_nd); PB_DS_DEBUG_VERIFY(!Cmp_Fn::operator()(PB_DS_V2F(p_nd->m_p_right->m_value), PB_DS_V2F(p_nd->m_value))); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_min(const char* __file, int __line) const { assert_min_imp(m_p_head->m_p_parent, __file, __line); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_min_imp(const node_pointer p_nd, const char* __file, int __line) const { if (p_nd == 0) { PB_DS_DEBUG_VERIFY(m_p_head->m_p_left == m_p_head); return; } if (p_nd->m_p_left == 0) { PB_DS_DEBUG_VERIFY(p_nd == m_p_head->m_p_left); return; } assert_min_imp(p_nd->m_p_left, __file, __line); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_max(const char* __file, int __line) const { assert_max_imp(m_p_head->m_p_parent, __file, __line); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_max_imp(const node_pointer p_nd, const char* __file, int __line) const { if (p_nd == 0) { PB_DS_DEBUG_VERIFY(m_p_head->m_p_right == m_p_head); return; } if (p_nd->m_p_right == 0) { PB_DS_DEBUG_VERIFY(p_nd == m_p_head->m_p_right); return; } assert_max_imp(p_nd->m_p_right, __file, __line); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_iterators(const char* __file, int __line) const { size_type iterated_num = 0; const_iterator prev_it = end(); for (const_iterator it = begin(); it != end(); ++it) { ++iterated_num; PB_DS_DEBUG_VERIFY(lower_bound(PB_DS_V2F(*it)).m_p_nd == it.m_p_nd); const_iterator upper_bound_it = upper_bound(PB_DS_V2F(*it)); --upper_bound_it; PB_DS_DEBUG_VERIFY(upper_bound_it.m_p_nd == it.m_p_nd); if (prev_it != end()) PB_DS_DEBUG_VERIFY(Cmp_Fn::operator()(PB_DS_V2F(*prev_it), PB_DS_V2F(*it))); prev_it = it; } PB_DS_DEBUG_VERIFY(iterated_num == m_size); size_type reverse_iterated_num = 0; const_reverse_iterator reverse_prev_it = rend(); for (const_reverse_iterator reverse_it = rbegin(); reverse_it != rend(); ++reverse_it) { ++reverse_iterated_num; PB_DS_DEBUG_VERIFY(lower_bound( PB_DS_V2F(*reverse_it)).m_p_nd == reverse_it.m_p_nd); const_iterator upper_bound_it = upper_bound(PB_DS_V2F(*reverse_it)); --upper_bound_it; PB_DS_DEBUG_VERIFY(upper_bound_it.m_p_nd == reverse_it.m_p_nd); if (reverse_prev_it != rend()) PB_DS_DEBUG_VERIFY(!Cmp_Fn::operator()(PB_DS_V2F(*reverse_prev_it), PB_DS_V2F(*reverse_it))); reverse_prev_it = reverse_it; } PB_DS_DEBUG_VERIFY(reverse_iterated_num == m_size); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_consistent_with_debug_base(const char* __file, int __line) const { debug_base::check_size(m_size, __file, __line); assert_consistent_with_debug_base(m_p_head->m_p_parent, __file, __line); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_consistent_with_debug_base(const node_pointer p_nd, const char* __file, int __line) const { if (p_nd == 0) return; debug_base::check_key_exists(PB_DS_V2F(p_nd->m_value), __file, __line); assert_consistent_with_debug_base(p_nd->m_p_left, __file, __line); assert_consistent_with_debug_base(p_nd->m_p_right, __file, __line); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_size(const char* __file, int __line) const { PB_DS_DEBUG_VERIFY(recursive_count(m_p_head->m_p_parent) == m_size); } #endif PK!g g 58/ext/pb_ds/detail/bin_search_tree_/erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/erase_fn_imps.hpp * Contains an implementation class for bin_search_tree_. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: actual_erase_node(node_pointer p_z) { _GLIBCXX_DEBUG_ASSERT(m_size > 0); --m_size; _GLIBCXX_DEBUG_ONLY(debug_base::erase_existing(PB_DS_V2F(p_z->m_value));) p_z->~node(); s_node_allocator.deallocate(p_z, 1); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: update_min_max_for_erased_node(node_pointer p_z) { if (m_size == 1) { m_p_head->m_p_left = m_p_head->m_p_right = m_p_head; return; } if (m_p_head->m_p_left == p_z) { iterator it(p_z); ++it; m_p_head->m_p_left = it.m_p_nd; } else if (m_p_head->m_p_right == p_z) { iterator it(p_z); --it; m_p_head->m_p_right = it.m_p_nd; } } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear() { PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) clear_imp(m_p_head->m_p_parent); m_size = 0; initialize(); _GLIBCXX_DEBUG_ONLY(debug_base::clear();) PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear_imp(node_pointer p_nd) { if (p_nd == 0) return; clear_imp(p_nd->m_p_left); clear_imp(p_nd->m_p_right); p_nd->~node(); s_node_allocator.deallocate(p_nd, 1); } PK!0VGG48/ext/pb_ds/detail/bin_search_tree_/find_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/find_fn_imps.hpp * Contains an implementation class for bin_search_tree_. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_const_iterator PB_DS_CLASS_C_DEC:: lower_bound(key_const_reference r_key) const { node_pointer p_pot = m_p_head; node_pointer p_nd = m_p_head->m_p_parent; while (p_nd != 0) if (Cmp_Fn::operator()(PB_DS_V2F(p_nd->m_value), r_key)) p_nd = p_nd->m_p_right; else { p_pot = p_nd; p_nd = p_nd->m_p_left; } return iterator(p_pot); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: lower_bound(key_const_reference r_key) { node_pointer p_pot = m_p_head; node_pointer p_nd = m_p_head->m_p_parent; while (p_nd != 0) if (Cmp_Fn::operator()(PB_DS_V2F(p_nd->m_value), r_key)) p_nd = p_nd->m_p_right; else { p_pot = p_nd; p_nd = p_nd->m_p_left; } return iterator(p_pot); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_const_iterator PB_DS_CLASS_C_DEC:: upper_bound(key_const_reference r_key) const { node_pointer p_pot = m_p_head; node_pointer p_nd = m_p_head->m_p_parent; while (p_nd != 0) if (Cmp_Fn::operator()(r_key, PB_DS_V2F(p_nd->m_value))) { p_pot = p_nd; p_nd = p_nd->m_p_left; } else p_nd = p_nd->m_p_right; return const_iterator(p_pot); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: upper_bound(key_const_reference r_key) { node_pointer p_pot = m_p_head; node_pointer p_nd = m_p_head->m_p_parent; while (p_nd != 0) if (Cmp_Fn::operator()(r_key, PB_DS_V2F(p_nd->m_value))) { p_pot = p_nd; p_nd = p_nd->m_p_left; } else p_nd = p_nd->m_p_right; return point_iterator(p_pot); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: find(key_const_reference r_key) { PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) node_pointer p_pot = m_p_head; node_pointer p_nd = m_p_head->m_p_parent; while (p_nd != 0) if (!Cmp_Fn::operator()(PB_DS_V2F(p_nd->m_value), r_key)) { p_pot = p_nd; p_nd = p_nd->m_p_left; } else p_nd = p_nd->m_p_right; node_pointer ret = p_pot; if (p_pot != m_p_head) { const bool __cmp = Cmp_Fn::operator()(r_key, PB_DS_V2F(p_pot->m_value)); if (__cmp) ret = m_p_head; } return point_iterator(ret); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_const_iterator PB_DS_CLASS_C_DEC:: find(key_const_reference r_key) const { PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) node_pointer p_pot = m_p_head; node_pointer p_nd = m_p_head->m_p_parent; while (p_nd != 0) if (!Cmp_Fn::operator()(PB_DS_V2F(p_nd->m_value), r_key)) { p_pot = p_nd; p_nd = p_nd->m_p_left; } else p_nd = p_nd->m_p_right; node_pointer ret = p_pot; if (p_pot != m_p_head) { const bool __cmp = Cmp_Fn::operator()(r_key, PB_DS_V2F(p_pot->m_value)); if (__cmp) ret = m_p_head; } return point_const_iterator(ret); } PK!Y  48/ext/pb_ds/detail/bin_search_tree_/info_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/info_fn_imps.hpp * Contains an implementation class for bin_search_tree_. */ PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: empty() const { return (m_size == 0); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: size() const { return (m_size); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: max_size() const { return (s_node_allocator.max_size()); } PK!Vii68/ext/pb_ds/detail/bin_search_tree_/insert_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/insert_fn_imps.hpp * Contains an implementation class for bin_search_tree_. */ PB_DS_CLASS_T_DEC inline std::pair PB_DS_CLASS_C_DEC:: insert_leaf(const_reference r_value) { PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) if (m_size == 0) return std::make_pair(insert_imp_empty(r_value), true); node_pointer p_nd = m_p_head->m_p_parent; node_pointer p_pot = m_p_head; while (p_nd != 0) if (!Cmp_Fn::operator()(PB_DS_V2F(p_nd->m_value), PB_DS_V2F(r_value))) { p_pot = p_nd; p_nd = p_nd->m_p_left; } else p_nd = p_nd->m_p_right; if (p_pot == m_p_head) return std::make_pair(insert_leaf_new(r_value, m_p_head->m_p_right, false), true); if (!Cmp_Fn::operator()(PB_DS_V2F(r_value), PB_DS_V2F(p_pot->m_value))) { PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) PB_DS_CHECK_KEY_EXISTS(PB_DS_V2F(r_value)) return std::make_pair(p_pot, false); } PB_DS_CHECK_KEY_DOES_NOT_EXIST(PB_DS_V2F(r_value)) p_nd = p_pot->m_p_left; if (p_nd == 0) return std::make_pair(insert_leaf_new(r_value, p_pot, true), true); while (p_nd->m_p_right != 0) p_nd = p_nd->m_p_right; return std::make_pair(insert_leaf_new(r_value, p_nd, false), true); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: insert_leaf_new(const_reference r_value, node_pointer p_nd, bool left_nd) { node_pointer p_new_nd = get_new_node_for_leaf_insert(r_value, traits_base::m_no_throw_copies_indicator); if (left_nd) { _GLIBCXX_DEBUG_ASSERT(p_nd->m_p_left == 0); _GLIBCXX_DEBUG_ASSERT(Cmp_Fn::operator()(PB_DS_V2F(r_value), PB_DS_V2F(p_nd->m_value))); p_nd->m_p_left = p_new_nd; if (m_p_head->m_p_left == p_nd) m_p_head->m_p_left = p_new_nd; } else { _GLIBCXX_DEBUG_ASSERT(p_nd->m_p_right == 0); _GLIBCXX_DEBUG_ASSERT(Cmp_Fn::operator()(PB_DS_V2F(p_nd->m_value), PB_DS_V2F(r_value))); p_nd->m_p_right = p_new_nd; if (m_p_head->m_p_right == p_nd) m_p_head->m_p_right = p_new_nd; } p_new_nd->m_p_parent = p_nd; p_new_nd->m_p_left = p_new_nd->m_p_right = 0; PB_DS_ASSERT_NODE_CONSISTENT(p_nd) update_to_top(p_new_nd, (node_update* )this); _GLIBCXX_DEBUG_ONLY(debug_base::insert_new(PB_DS_V2F(r_value));) return iterator(p_new_nd); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: insert_imp_empty(const_reference r_value) { node_pointer p_new_node = get_new_node_for_leaf_insert(r_value, traits_base::m_no_throw_copies_indicator); m_p_head->m_p_left = m_p_head->m_p_right = m_p_head->m_p_parent = p_new_node; p_new_node->m_p_parent = m_p_head; p_new_node->m_p_left = p_new_node->m_p_right = 0; _GLIBCXX_DEBUG_ONLY(debug_base::insert_new(PB_DS_V2F(r_value));) update_to_top(m_p_head->m_p_parent, (node_update*)this); return iterator(p_new_node); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: get_new_node_for_leaf_insert(const_reference r_val, false_type) { node_pointer p_new_nd = s_node_allocator.allocate(1); cond_dealtor_t cond(p_new_nd); new (const_cast(static_cast(&p_new_nd->m_value))) typename node::value_type(r_val); cond.set_no_action(); p_new_nd->m_p_left = p_new_nd->m_p_right = 0; ++m_size; return p_new_nd; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: get_new_node_for_leaf_insert(const_reference r_val, true_type) { node_pointer p_new_nd = s_node_allocator.allocate(1); new (const_cast(static_cast(&p_new_nd->m_value))) typename node::value_type(r_val); p_new_nd->m_p_left = p_new_nd->m_p_right = 0; ++m_size; return p_new_nd; } PK!B 98/ext/pb_ds/detail/bin_search_tree_/iterators_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/iterators_fn_imps.hpp * Contains an implementation class for bin_search_tree_. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: begin() { return (iterator(m_p_head->m_p_left)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: begin() const { return (const_iterator(m_p_head->m_p_left)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: end() { return (iterator(m_p_head)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: end() const { return (const_iterator(m_p_head)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_reverse_iterator PB_DS_CLASS_C_DEC:: rbegin() const { return (const_reverse_iterator(m_p_head->m_p_right)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::reverse_iterator PB_DS_CLASS_C_DEC:: rbegin() { return (reverse_iterator(m_p_head->m_p_right)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::reverse_iterator PB_DS_CLASS_C_DEC:: rend() { return (reverse_iterator(m_p_head)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_reverse_iterator PB_DS_CLASS_C_DEC:: rend() const { return (const_reverse_iterator(m_p_head)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_const_iterator PB_DS_CLASS_C_DEC:: node_begin() const { return (node_const_iterator(m_p_head->m_p_parent)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_iterator PB_DS_CLASS_C_DEC:: node_begin() { return (node_iterator(m_p_head->m_p_parent)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_const_iterator PB_DS_CLASS_C_DEC:: node_end() const { return (node_const_iterator(0)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_iterator PB_DS_CLASS_C_DEC:: node_end() { return (node_iterator(0)); } PK!Mj$mm68/ext/pb_ds/detail/bin_search_tree_/node_iterators.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/node_iterators.hpp * Contains an implementation class for bin_search_tree_. */ #ifndef PB_DS_BIN_SEARCH_TREE_NODE_ITERATORS_HPP #define PB_DS_BIN_SEARCH_TREE_NODE_ITERATORS_HPP #include namespace __gnu_pbds { namespace detail { #define PB_DS_TREE_CONST_NODE_ITERATOR_CLASS_C_DEC \ bin_search_tree_const_node_it_ /// Const node iterator. template class bin_search_tree_const_node_it_ { private: typedef typename _Alloc::template rebind< Node>::other::pointer node_pointer; public: /// Category. typedef trivial_iterator_tag iterator_category; /// Difference type. typedef trivial_iterator_difference_type difference_type; /// Iterator's value type. typedef Const_Iterator value_type; /// Iterator's reference type. typedef Const_Iterator reference; /// Iterator's __const reference type. typedef Const_Iterator const_reference; /// Metadata type. typedef typename Node::metadata_type metadata_type; /// Const metadata reference type. typedef typename _Alloc::template rebind::other::const_reference metadata_const_reference; bin_search_tree_const_node_it_(const node_pointer p_nd = 0) : m_p_nd(const_cast(p_nd)) { } /// Access. const_reference operator*() const { return Const_Iterator(m_p_nd); } /// Metadata access. metadata_const_reference get_metadata() const { return m_p_nd->get_metadata(); } /// Returns the __const node iterator associated with the left node. PB_DS_TREE_CONST_NODE_ITERATOR_CLASS_C_DEC get_l_child() const { return PB_DS_TREE_CONST_NODE_ITERATOR_CLASS_C_DEC(m_p_nd->m_p_left); } /// Returns the __const node iterator associated with the right node. PB_DS_TREE_CONST_NODE_ITERATOR_CLASS_C_DEC get_r_child() const { return PB_DS_TREE_CONST_NODE_ITERATOR_CLASS_C_DEC(m_p_nd->m_p_right); } /// Compares to a different iterator object. bool operator==(const PB_DS_TREE_CONST_NODE_ITERATOR_CLASS_C_DEC& other) const { return m_p_nd == other.m_p_nd; } /// Compares (negatively) to a different iterator object. bool operator!=(const PB_DS_TREE_CONST_NODE_ITERATOR_CLASS_C_DEC& other) const { return m_p_nd != other.m_p_nd; } node_pointer m_p_nd; }; #define PB_DS_TREE_NODE_ITERATOR_CLASS_C_DEC \ bin_search_tree_node_it_ /// Node iterator. template class bin_search_tree_node_it_ : public PB_DS_TREE_CONST_NODE_ITERATOR_CLASS_C_DEC { private: typedef typename _Alloc::template rebind< Node>::other::pointer node_pointer; public: /// Iterator's value type. typedef Iterator value_type; /// Iterator's reference type. typedef Iterator reference; /// Iterator's __const reference type. typedef Iterator const_reference; inline bin_search_tree_node_it_(const node_pointer p_nd = 0) : PB_DS_TREE_CONST_NODE_ITERATOR_CLASS_C_DEC(const_cast(p_nd)) { } /// Access. Iterator operator*() const { return Iterator(PB_DS_TREE_CONST_NODE_ITERATOR_CLASS_C_DEC::m_p_nd); } /// Returns the node iterator associated with the left node. PB_DS_TREE_NODE_ITERATOR_CLASS_C_DEC get_l_child() const { return PB_DS_TREE_NODE_ITERATOR_CLASS_C_DEC( PB_DS_TREE_CONST_NODE_ITERATOR_CLASS_C_DEC::m_p_nd->m_p_left); } /// Returns the node iterator associated with the right node. PB_DS_TREE_NODE_ITERATOR_CLASS_C_DEC get_r_child() const { return PB_DS_TREE_NODE_ITERATOR_CLASS_C_DEC( PB_DS_TREE_CONST_NODE_ITERATOR_CLASS_C_DEC::m_p_nd->m_p_right); } }; #undef PB_DS_TREE_CONST_NODE_ITERATOR_CLASS_C_DEC #undef PB_DS_TREE_NODE_ITERATOR_CLASS_C_DEC } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_BIN_SEARCH_TREE_NODE_ITERATORS_HPP PK!*`##78/ext/pb_ds/detail/bin_search_tree_/point_iterators.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/point_iterators.hpp * Contains an implementation class for bin_search_tree_. */ #ifndef PB_DS_BIN_SEARCH_TREE_FIND_ITERATORS_HPP #define PB_DS_BIN_SEARCH_TREE_FIND_ITERATORS_HPP #include #include namespace __gnu_pbds { namespace detail { #define PB_DS_TREE_CONST_IT_C_DEC \ bin_search_tree_const_it_< \ Node_Pointer, \ Value_Type, \ Pointer, \ Const_Pointer, \ Reference, \ Const_Reference, \ Is_Forward_Iterator, \ _Alloc> #define PB_DS_TREE_CONST_ODIR_IT_C_DEC \ bin_search_tree_const_it_< \ Node_Pointer, \ Value_Type, \ Pointer, \ Const_Pointer, \ Reference, \ Const_Reference, \ !Is_Forward_Iterator, \ _Alloc> #define PB_DS_TREE_IT_C_DEC \ bin_search_tree_it_< \ Node_Pointer, \ Value_Type, \ Pointer, \ Const_Pointer, \ Reference, \ Const_Reference, \ Is_Forward_Iterator, \ _Alloc> #define PB_DS_TREE_ODIR_IT_C_DEC \ bin_search_tree_it_< \ Node_Pointer, \ Value_Type, \ Pointer, \ Const_Pointer, \ Reference, \ Const_Reference, \ !Is_Forward_Iterator, \ _Alloc> /// Const iterator. template class bin_search_tree_const_it_ { public: typedef std::bidirectional_iterator_tag iterator_category; typedef typename _Alloc::difference_type difference_type; typedef Value_Type value_type; typedef Pointer pointer; typedef Const_Pointer const_pointer; typedef Reference reference; typedef Const_Reference const_reference; inline bin_search_tree_const_it_(const Node_Pointer p_nd = 0) : m_p_nd(const_cast(p_nd)) { } inline bin_search_tree_const_it_(const PB_DS_TREE_CONST_ODIR_IT_C_DEC& other) : m_p_nd(other.m_p_nd) { } inline PB_DS_TREE_CONST_IT_C_DEC& operator=(const PB_DS_TREE_CONST_IT_C_DEC& other) { m_p_nd = other.m_p_nd; return *this; } inline PB_DS_TREE_CONST_IT_C_DEC& operator=(const PB_DS_TREE_CONST_ODIR_IT_C_DEC& other) { m_p_nd = other.m_p_nd; return *this; } inline const_pointer operator->() const { _GLIBCXX_DEBUG_ASSERT(m_p_nd != 0); return &m_p_nd->m_value; } inline const_reference operator*() const { _GLIBCXX_DEBUG_ASSERT(m_p_nd != 0); return m_p_nd->m_value; } inline bool operator==(const PB_DS_TREE_CONST_IT_C_DEC & other) const { return m_p_nd == other.m_p_nd; } inline bool operator==(const PB_DS_TREE_CONST_ODIR_IT_C_DEC & other) const { return m_p_nd == other.m_p_nd; } inline bool operator!=(const PB_DS_TREE_CONST_IT_C_DEC& other) const { return m_p_nd != other.m_p_nd; } inline bool operator!=(const PB_DS_TREE_CONST_ODIR_IT_C_DEC& other) const { return m_p_nd != other.m_p_nd; } inline PB_DS_TREE_CONST_IT_C_DEC& operator++() { _GLIBCXX_DEBUG_ASSERT(m_p_nd != 0); inc(integral_constant()); return *this; } inline PB_DS_TREE_CONST_IT_C_DEC operator++(int) { PB_DS_TREE_CONST_IT_C_DEC ret_it(m_p_nd); operator++(); return ret_it; } inline PB_DS_TREE_CONST_IT_C_DEC& operator--() { dec(integral_constant()); return *this; } inline PB_DS_TREE_CONST_IT_C_DEC operator--(int) { PB_DS_TREE_CONST_IT_C_DEC ret_it(m_p_nd); operator--(); return ret_it; } protected: inline void inc(false_type) { dec(true_type()); } void inc(true_type) { if (m_p_nd->special()&& m_p_nd->m_p_parent->m_p_parent == m_p_nd) { m_p_nd = m_p_nd->m_p_left; return; } if (m_p_nd->m_p_right != 0) { m_p_nd = m_p_nd->m_p_right; while (m_p_nd->m_p_left != 0) m_p_nd = m_p_nd->m_p_left; return; } Node_Pointer p_y = m_p_nd->m_p_parent; while (m_p_nd == p_y->m_p_right) { m_p_nd = p_y; p_y = p_y->m_p_parent; } if (m_p_nd->m_p_right != p_y) m_p_nd = p_y; } inline void dec(false_type) { inc(true_type()); } void dec(true_type) { if (m_p_nd->special() && m_p_nd->m_p_parent->m_p_parent == m_p_nd) { m_p_nd = m_p_nd->m_p_right; return; } if (m_p_nd->m_p_left != 0) { Node_Pointer p_y = m_p_nd->m_p_left; while (p_y->m_p_right != 0) p_y = p_y->m_p_right; m_p_nd = p_y; return; } Node_Pointer p_y = m_p_nd->m_p_parent; while (m_p_nd == p_y->m_p_left) { m_p_nd = p_y; p_y = p_y->m_p_parent; } if (m_p_nd->m_p_left != p_y) m_p_nd = p_y; } public: Node_Pointer m_p_nd; }; /// Iterator. template class bin_search_tree_it_ : public PB_DS_TREE_CONST_IT_C_DEC { public: inline bin_search_tree_it_(const Node_Pointer p_nd = 0) : PB_DS_TREE_CONST_IT_C_DEC((Node_Pointer)p_nd) { } inline bin_search_tree_it_(const PB_DS_TREE_ODIR_IT_C_DEC& other) : PB_DS_TREE_CONST_IT_C_DEC(other.m_p_nd) { } inline PB_DS_TREE_IT_C_DEC& operator=(const PB_DS_TREE_IT_C_DEC& other) { base_it_type::m_p_nd = other.m_p_nd; return *this; } inline PB_DS_TREE_IT_C_DEC& operator=(const PB_DS_TREE_ODIR_IT_C_DEC& other) { base_it_type::m_p_nd = other.m_p_nd; return *this; } inline typename PB_DS_TREE_CONST_IT_C_DEC::pointer operator->() const { _GLIBCXX_DEBUG_ASSERT(base_it_type::m_p_nd != 0); return &base_it_type::m_p_nd->m_value; } inline typename PB_DS_TREE_CONST_IT_C_DEC::reference operator*() const { _GLIBCXX_DEBUG_ASSERT(base_it_type::m_p_nd != 0); return base_it_type::m_p_nd->m_value; } inline PB_DS_TREE_IT_C_DEC& operator++() { PB_DS_TREE_CONST_IT_C_DEC:: operator++(); return *this; } inline PB_DS_TREE_IT_C_DEC operator++(int) { PB_DS_TREE_IT_C_DEC ret_it(base_it_type::m_p_nd); operator++(); return ret_it; } inline PB_DS_TREE_IT_C_DEC& operator--() { PB_DS_TREE_CONST_IT_C_DEC:: operator--(); return *this; } inline PB_DS_TREE_IT_C_DEC operator--(int) { PB_DS_TREE_IT_C_DEC ret_it(base_it_type::m_p_nd); operator--(); return ret_it; } protected: typedef PB_DS_TREE_CONST_IT_C_DEC base_it_type; }; #undef PB_DS_TREE_CONST_IT_C_DEC #undef PB_DS_TREE_CONST_ODIR_IT_C_DEC #undef PB_DS_TREE_IT_C_DEC #undef PB_DS_TREE_ODIR_IT_C_DEC } // namespace detail } // namespace __gnu_pbds #endif PK!ҿqq=8/ext/pb_ds/detail/bin_search_tree_/policy_access_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/policy_access_fn_imps.hpp * Contains an implementation class for bin_search_tree_. */ PB_DS_CLASS_T_DEC Cmp_Fn& PB_DS_CLASS_C_DEC:: get_cmp_fn() { return (*this); } PB_DS_CLASS_T_DEC const Cmp_Fn& PB_DS_CLASS_C_DEC:: get_cmp_fn() const { return (*this); } PK!C] ] 78/ext/pb_ds/detail/bin_search_tree_/r_erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/r_erase_fn_imps.hpp * Contains an implementation class for bin_search_tree_. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: actual_erase_node(node_pointer p_z) { _GLIBCXX_DEBUG_ASSERT(m_size > 0); --m_size; _GLIBCXX_DEBUG_ONLY(erase_existing(PB_DS_V2F(p_z->m_value));) p_z->~node(); s_node_allocator.deallocate(p_z, 1); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: update_min_max_for_erased_node(node_pointer p_z) { if (m_size == 1) { m_p_head->m_p_left = m_p_head->m_p_right = m_p_head; return; } if (m_p_head->m_p_left == p_z) { iterator it(p_z); ++it; m_p_head->m_p_left = it.m_p_nd; } else if (m_p_head->m_p_right == p_z) { iterator it(p_z); --it; m_p_head->m_p_right = it.m_p_nd; } } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear() { PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) clear_imp(m_p_head->m_p_parent); m_size = 0; initialize(); _GLIBCXX_DEBUG_ONLY(debug_base::clear();) PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear_imp(node_pointer p_nd) { if (p_nd == 0) return; clear_imp(p_nd->m_p_left); clear_imp(p_nd->m_p_right); p_nd->~Node(); s_node_allocator.deallocate(p_nd, 1); } PK!N^^68/ext/pb_ds/detail/bin_search_tree_/rotate_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/rotate_fn_imps.hpp * Contains imps for rotating nodes. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: rotate_left(node_pointer p_x) { node_pointer p_y = p_x->m_p_right; p_x->m_p_right = p_y->m_p_left; if (p_y->m_p_left != 0) p_y->m_p_left->m_p_parent = p_x; p_y->m_p_parent = p_x->m_p_parent; if (p_x == m_p_head->m_p_parent) m_p_head->m_p_parent = p_y; else if (p_x == p_x->m_p_parent->m_p_left) p_x->m_p_parent->m_p_left = p_y; else p_x->m_p_parent->m_p_right = p_y; p_y->m_p_left = p_x; p_x->m_p_parent = p_y; PB_DS_ASSERT_NODE_CONSISTENT(p_x) PB_DS_ASSERT_NODE_CONSISTENT(p_y) apply_update(p_x, (node_update* )this); apply_update(p_x->m_p_parent, (node_update* )this); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: rotate_right(node_pointer p_x) { node_pointer p_y = p_x->m_p_left; p_x->m_p_left = p_y->m_p_right; if (p_y->m_p_right != 0) p_y->m_p_right->m_p_parent = p_x; p_y->m_p_parent = p_x->m_p_parent; if (p_x == m_p_head->m_p_parent) m_p_head->m_p_parent = p_y; else if (p_x == p_x->m_p_parent->m_p_right) p_x->m_p_parent->m_p_right = p_y; else p_x->m_p_parent->m_p_left = p_y; p_y->m_p_right = p_x; p_x->m_p_parent = p_y; PB_DS_ASSERT_NODE_CONSISTENT(p_x) PB_DS_ASSERT_NODE_CONSISTENT(p_y) apply_update(p_x, (node_update* )this); apply_update(p_x->m_p_parent, (node_update* )this); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: rotate_parent(node_pointer p_nd) { node_pointer p_parent = p_nd->m_p_parent; if (p_nd == p_parent->m_p_left) rotate_right(p_parent); else rotate_left(p_parent); _GLIBCXX_DEBUG_ASSERT(p_parent->m_p_parent = p_nd); _GLIBCXX_DEBUG_ASSERT(p_nd->m_p_left == p_parent || p_nd->m_p_right == p_parent); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: apply_update(node_pointer /*p_nd*/, null_node_update_pointer /*p_update*/) { } PB_DS_CLASS_T_DEC template inline void PB_DS_CLASS_C_DEC:: apply_update(node_pointer p_nd, Node_Update_* /*p_update*/) { node_update::operator()(node_iterator(p_nd), node_const_iterator(static_cast(0))); } PB_DS_CLASS_T_DEC template inline void PB_DS_CLASS_C_DEC:: update_to_top(node_pointer p_nd, Node_Update_* p_update) { while (p_nd != m_p_head) { apply_update(p_nd, p_update); p_nd = p_nd->m_p_parent; } } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: update_to_top(node_pointer /*p_nd*/, null_node_update_pointer /*p_update*/) { } PK!/:8/ext/pb_ds/detail/bin_search_tree_/split_join_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/split_join_fn_imps.hpp * Contains an implementation class for bin_search_tree_. */ PB_DS_CLASS_T_DEC bool PB_DS_CLASS_C_DEC:: join_prep(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) if (other.m_size == 0) return false; if (m_size == 0) { value_swap(other); return false; } const bool greater = Cmp_Fn::operator()(PB_DS_V2F(m_p_head->m_p_right->m_value), PB_DS_V2F(other.m_p_head->m_p_left->m_value)); const bool lesser = Cmp_Fn::operator()(PB_DS_V2F(other.m_p_head->m_p_right->m_value), PB_DS_V2F(m_p_head->m_p_left->m_value)); if (!greater && !lesser) __throw_join_error(); if (lesser) value_swap(other); m_size += other.m_size; _GLIBCXX_DEBUG_ONLY(debug_base::join(other);) return true; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: join_finish(PB_DS_CLASS_C_DEC& other) { initialize_min_max(); other.initialize(); } PB_DS_CLASS_T_DEC bool PB_DS_CLASS_C_DEC:: split_prep(key_const_reference r_key, PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) other.clear(); if (m_size == 0) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return false; } if (Cmp_Fn::operator()(r_key, PB_DS_V2F(m_p_head->m_p_left->m_value))) { value_swap(other); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return false; } if (!Cmp_Fn::operator()(r_key, PB_DS_V2F(m_p_head->m_p_right->m_value))) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return false; } if (m_size == 1) { value_swap(other); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return false; } _GLIBCXX_DEBUG_ONLY(debug_base::split(r_key,(Cmp_Fn& )(*this), other);) return true; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: split_finish(PB_DS_CLASS_C_DEC& other) { other.initialize_min_max(); other.m_size = std::distance(other.begin(), other.end()); m_size -= other.m_size; initialize_min_max(); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: recursive_count(node_pointer p) const { if (p == 0) return 0; return 1 + recursive_count(p->m_p_left) + recursive_count(p->m_p_right); } PK!i.8/ext/pb_ds/detail/bin_search_tree_/traits.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file bin_search_tree_/traits.hpp * Contains an implementation for bin_search_tree_. */ #ifndef PB_DS_BIN_SEARCH_TREE_NODE_AND_IT_TRAITS_HPP #define PB_DS_BIN_SEARCH_TREE_NODE_AND_IT_TRAITS_HPP #include #include namespace __gnu_pbds { namespace detail { /// Binary search tree traits, primary template /// @ingroup traits template class Node_Update, class Node, typename _Alloc> struct bin_search_tree_traits { private: typedef types_traits type_traits; public: typedef Node node; typedef bin_search_tree_const_it_< typename _Alloc::template rebind< node>::other::pointer, typename type_traits::value_type, typename type_traits::pointer, typename type_traits::const_pointer, typename type_traits::reference, typename type_traits::const_reference, true, _Alloc> point_const_iterator; typedef bin_search_tree_it_< typename _Alloc::template rebind< node>::other::pointer, typename type_traits::value_type, typename type_traits::pointer, typename type_traits::const_pointer, typename type_traits::reference, typename type_traits::const_reference, true, _Alloc> point_iterator; typedef bin_search_tree_const_it_< typename _Alloc::template rebind< node>::other::pointer, typename type_traits::value_type, typename type_traits::pointer, typename type_traits::const_pointer, typename type_traits::reference, typename type_traits::const_reference, false, _Alloc> const_reverse_iterator; typedef bin_search_tree_it_< typename _Alloc::template rebind< node>::other::pointer, typename type_traits::value_type, typename type_traits::pointer, typename type_traits::const_pointer, typename type_traits::reference, typename type_traits::const_reference, false, _Alloc> reverse_iterator; /// This is an iterator to an iterator: it iterates over nodes, /// and de-referencing it returns one of the tree's iterators. typedef bin_search_tree_const_node_it_< Node, point_const_iterator, point_iterator, _Alloc> node_const_iterator; typedef bin_search_tree_node_it_< Node, point_const_iterator, point_iterator, _Alloc> node_iterator; typedef Node_Update< node_const_iterator, node_iterator, Cmp_Fn, _Alloc> node_update; typedef __gnu_pbds::null_node_update< node_const_iterator, node_iterator, Cmp_Fn, _Alloc>* null_node_update_pointer; }; /// Specialization. /// @ingroup traits template class Node_Update, class Node, typename _Alloc> struct bin_search_tree_traits { private: typedef types_traits type_traits; public: typedef Node node; typedef bin_search_tree_const_it_< typename _Alloc::template rebind< node>::other::pointer, typename type_traits::value_type, typename type_traits::pointer, typename type_traits::const_pointer, typename type_traits::reference, typename type_traits::const_reference, true, _Alloc> point_const_iterator; typedef point_const_iterator point_iterator; typedef bin_search_tree_const_it_< typename _Alloc::template rebind< node>::other::pointer, typename type_traits::value_type, typename type_traits::pointer, typename type_traits::const_pointer, typename type_traits::reference, typename type_traits::const_reference, false, _Alloc> const_reverse_iterator; typedef const_reverse_iterator reverse_iterator; /// This is an iterator to an iterator: it iterates over nodes, /// and de-referencing it returns one of the tree's iterators. typedef bin_search_tree_const_node_it_< Node, point_const_iterator, point_iterator, _Alloc> node_const_iterator; typedef node_const_iterator node_iterator; typedef Node_Update node_update; typedef __gnu_pbds::null_node_update< node_const_iterator, node_iterator, Cmp_Fn, _Alloc>* null_node_update_pointer; }; } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_BIN_SEARCH_TREE_NODE_AND_IT_TRAITS_HPP PK!/2#2#08/ext/pb_ds/detail/binary_heap_/binary_heap_.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/binary_heap_.hpp * Contains an implementation class for a binary heap. */ #ifndef PB_DS_BINARY_HEAP_HPP #define PB_DS_BINARY_HEAP_HPP #include #include #include #include #include #include #include #include #include #include #ifdef PB_DS_BINARY_HEAP_TRACE_ #include #endif #include #include namespace __gnu_pbds { namespace detail { #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ binary_heap #define PB_DS_ENTRY_CMP_DEC \ entry_cmp::value>::type #define PB_DS_RESIZE_POLICY_DEC \ __gnu_pbds::detail::resize_policy /** * Binary heaps composed of resize and compare policies. * * @ingroup heap-detail * * Based on CLRS. */ template class binary_heap : public PB_DS_ENTRY_CMP_DEC, public PB_DS_RESIZE_POLICY_DEC { public: typedef Value_Type value_type; typedef Cmp_Fn cmp_fn; typedef _Alloc allocator_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef typename PB_DS_ENTRY_CMP_DEC entry_cmp; typedef PB_DS_RESIZE_POLICY_DEC resize_policy; typedef cond_dealtor cond_dealtor_t; private: enum { simple_value = is_simple::value }; typedef integral_constant no_throw_copies_t; typedef typename _Alloc::template rebind __rebind_v; typedef typename __rebind_v::other value_allocator; public: typedef typename value_allocator::pointer pointer; typedef typename value_allocator::const_pointer const_pointer; typedef typename value_allocator::reference reference; typedef typename value_allocator::const_reference const_reference; typedef typename __conditional_type::__type entry; typedef typename _Alloc::template rebind::other entry_allocator; typedef typename entry_allocator::pointer entry_pointer; typedef binary_heap_point_const_iterator_ point_const_iterator; typedef point_const_iterator point_iterator; typedef binary_heap_const_iterator_ const_iterator; typedef const_iterator iterator; binary_heap(); binary_heap(const cmp_fn&); binary_heap(const binary_heap&); void swap(binary_heap&); ~binary_heap(); inline bool empty() const; inline size_type size() const; inline size_type max_size() const; Cmp_Fn& get_cmp_fn(); const Cmp_Fn& get_cmp_fn() const; inline point_iterator push(const_reference); void modify(point_iterator, const_reference); inline const_reference top() const; inline void pop(); inline void erase(point_iterator); template size_type erase_if(Pred); inline void erase_at(entry_pointer, size_type, false_type); inline void erase_at(entry_pointer, size_type, true_type); inline iterator begin(); inline const_iterator begin() const; inline iterator end(); inline const_iterator end() const; void clear(); template void split(Pred, binary_heap&); void join(binary_heap&); #ifdef PB_DS_BINARY_HEAP_TRACE_ void trace() const; #endif protected: template void copy_from_range(It, It); private: void value_swap(binary_heap&); inline void insert_value(const_reference, false_type); inline void insert_value(value_type, true_type); inline void resize_for_insert_if_needed(); inline void swap_value_imp(entry_pointer, value_type, true_type); inline void swap_value_imp(entry_pointer, const_reference, false_type); void fix(entry_pointer); inline const_reference top_imp(true_type) const; inline const_reference top_imp(false_type) const; inline static size_type left_child(size_type); inline static size_type right_child(size_type); inline static size_type parent(size_type); inline void resize_for_erase_if_needed(); template size_type partition(Pred); void make_heap() { const entry_cmp& m_cmp = static_cast(*this); entry_pointer end = m_a_entries + m_size; std::make_heap(m_a_entries, end, m_cmp); } void push_heap() { const entry_cmp& m_cmp = static_cast(*this); entry_pointer end = m_a_entries + m_size; std::push_heap(m_a_entries, end, m_cmp); } void pop_heap() { const entry_cmp& m_cmp = static_cast(*this); entry_pointer end = m_a_entries + m_size; std::pop_heap(m_a_entries, end, m_cmp); } #ifdef _GLIBCXX_DEBUG void assert_valid(const char*, int) const; #endif #ifdef PB_DS_BINARY_HEAP_TRACE_ void trace_entry(const entry&, false_type) const; void trace_entry(const entry&, true_type) const; #endif static entry_allocator s_entry_allocator; static value_allocator s_value_allocator; static no_throw_copies_t s_no_throw_copies_ind; size_type m_size; size_type m_actual_size; entry_pointer m_a_entries; }; #define PB_DS_ASSERT_VALID(X) \ _GLIBCXX_DEBUG_ONLY(X.assert_valid(__FILE__, __LINE__);) #define PB_DS_DEBUG_VERIFY(_Cond) \ _GLIBCXX_DEBUG_VERIFY_AT(_Cond, \ _M_message(#_Cond" assertion from %1;:%2;") \ ._M_string(__FILE__)._M_integer(__LINE__) \ ,__file,__line) #include #include #include #include #include #include #include #include #include #include #undef PB_DS_CLASS_C_DEC #undef PB_DS_CLASS_T_DEC #undef PB_DS_ENTRY_CMP_DEC #undef PB_DS_RESIZE_POLICY_DEC } // namespace detail } // namespace __gnu_pbds #endif PK!2fY28/ext/pb_ds/detail/binary_heap_/const_iterator.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/const_iterator.hpp * Contains an iterator class returned by the table's const find and insert * methods. */ #ifndef PB_DS_BINARY_HEAP_CONST_ITERATOR_HPP #define PB_DS_BINARY_HEAP_CONST_ITERATOR_HPP #include #include namespace __gnu_pbds { namespace detail { #define PB_DS_BIN_HEAP_CIT_BASE \ binary_heap_point_const_iterator_ /// Const point-type iterator. template class binary_heap_const_iterator_ : public PB_DS_BIN_HEAP_CIT_BASE { private: typedef PB_DS_BIN_HEAP_CIT_BASE base_type; typedef typename base_type::entry_pointer entry_pointer; public: /// Category. typedef std::forward_iterator_tag iterator_category; /// Difference type. typedef typename _Alloc::difference_type difference_type; /// Iterator's value type. typedef typename base_type::value_type value_type; /// Iterator's pointer type. typedef typename base_type::pointer pointer; /// Iterator's const pointer type. typedef typename base_type::const_pointer const_pointer; /// Iterator's reference type. typedef typename base_type::reference reference; /// Iterator's const reference type. typedef typename base_type::const_reference const_reference; inline binary_heap_const_iterator_(entry_pointer p_e) : base_type(p_e) { } /// Default constructor. inline binary_heap_const_iterator_() { } /// Copy constructor. inline binary_heap_const_iterator_(const binary_heap_const_iterator_& other) : base_type(other) { } /// Compares content to a different iterator object. inline bool operator==(const binary_heap_const_iterator_& other) const { return base_type::m_p_e == other.m_p_e; } /// Compares content (negatively) to a different iterator object. inline bool operator!=(const binary_heap_const_iterator_& other) const { return base_type::m_p_e != other.m_p_e; } inline binary_heap_const_iterator_& operator++() { _GLIBCXX_DEBUG_ASSERT(base_type::m_p_e != 0); inc(); return *this; } inline binary_heap_const_iterator_ operator++(int) { binary_heap_const_iterator_ ret_it(base_type::m_p_e); operator++(); return ret_it; } private: void inc() { ++base_type::m_p_e; } }; #undef PB_DS_BIN_HEAP_CIT_BASE } // namespace detail } // namespace __gnu_pbds #endif PK!GH]]C8/ext/pb_ds/detail/binary_heap_/constructors_destructor_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/constructors_destructor_fn_imps.hpp * Contains an implementation class for binary_heap_. */ PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::entry_allocator PB_DS_CLASS_C_DEC::s_entry_allocator; PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::value_allocator PB_DS_CLASS_C_DEC::s_value_allocator; PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::no_throw_copies_t PB_DS_CLASS_C_DEC::s_no_throw_copies_ind; PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: copy_from_range(It first_it, It last_it) { while (first_it != last_it) { insert_value(*first_it, s_no_throw_copies_ind); ++first_it; } make_heap(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: binary_heap() : m_size(0), m_actual_size(resize_policy::min_size), m_a_entries(s_entry_allocator.allocate(m_actual_size)) { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: binary_heap(const Cmp_Fn& r_cmp_fn) : entry_cmp(r_cmp_fn), m_size(0), m_actual_size(resize_policy::min_size), m_a_entries(s_entry_allocator.allocate(m_actual_size)) { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: binary_heap(const PB_DS_CLASS_C_DEC& other) : entry_cmp(other), resize_policy(other), m_size(0), m_actual_size(other.m_actual_size), m_a_entries(s_entry_allocator.allocate(m_actual_size)) { PB_DS_ASSERT_VALID(other) _GLIBCXX_DEBUG_ASSERT(m_a_entries != other.m_a_entries); __try { copy_from_range(other.begin(), other.end()); } __catch(...) { for (size_type i = 0; i < m_size; ++i) erase_at(m_a_entries, i, s_no_throw_copies_ind); s_entry_allocator.deallocate(m_a_entries, m_actual_size); __throw_exception_again; } PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) _GLIBCXX_DEBUG_ASSERT(m_a_entries != other.m_a_entries); value_swap(other); std::swap((entry_cmp&)(*this), (entry_cmp&)other); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: value_swap(PB_DS_CLASS_C_DEC& other) { std::swap(m_a_entries, other.m_a_entries); std::swap(m_size, other.m_size); std::swap(m_actual_size, other.m_actual_size); static_cast(this)->swap(other); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~binary_heap() { for (size_type i = 0; i < m_size; ++i) erase_at(m_a_entries, i, s_no_throw_copies_ind); s_entry_allocator.deallocate(m_a_entries, m_actual_size); } PK!H'B 18/ext/pb_ds/detail/binary_heap_/debug_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/debug_fn_imps.hpp * Contains an implementation class for a binary_heap. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { #ifdef PB_DS_REGRESSION s_entry_allocator.check_allocated(m_a_entries, m_actual_size); #endif resize_policy::assert_valid(__file, __line); PB_DS_DEBUG_VERIFY(m_size <= m_actual_size); for (size_type i = 0; i < m_size; ++i) { #ifdef PB_DS_REGRESSION s_value_allocator.check_allocated(m_a_entries[i], 1); #endif if (left_child(i) < m_size) PB_DS_DEBUG_VERIFY(!entry_cmp::operator()(m_a_entries[i], m_a_entries[left_child(i)])); PB_DS_DEBUG_VERIFY(parent(left_child(i)) == i); if (right_child(i) < m_size) PB_DS_DEBUG_VERIFY(!entry_cmp::operator()(m_a_entries[i], m_a_entries[right_child(i)])); PB_DS_DEBUG_VERIFY(parent(right_child(i)) == i); } } #endif PK!O  -8/ext/pb_ds/detail/binary_heap_/entry_cmp.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/entry_cmp.hpp * Contains an implementation class for a binary_heap. */ #ifndef PB_DS_BINARY_HEAP_ENTRY_CMP_HPP #define PB_DS_BINARY_HEAP_ENTRY_CMP_HPP namespace __gnu_pbds { namespace detail { /// Entry compare, primary template. template struct entry_cmp; /// Specialization, true. template struct entry_cmp<_VTp, Cmp_Fn, _Alloc, true> { /// Compare. typedef Cmp_Fn type; }; /// Specialization, false. template struct entry_cmp<_VTp, Cmp_Fn, _Alloc, false> { private: typedef typename _Alloc::template rebind<_VTp> __rebind_v; public: typedef typename __rebind_v::other::const_pointer entry; /// Compare plus entry. struct type : public Cmp_Fn { type() { } type(const Cmp_Fn& other) : Cmp_Fn(other) { } bool operator()(entry lhs, entry rhs) const { return Cmp_Fn::operator()(*lhs, *rhs); } }; }; } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_BINARY_HEAP_ENTRY_CMP_HPP PK!uL .8/ext/pb_ds/detail/binary_heap_/entry_pred.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/entry_pred.hpp * Contains an implementation class for a binary_heap. */ #ifndef PB_DS_BINARY_HEAP_ENTRY_PRED_HPP #define PB_DS_BINARY_HEAP_ENTRY_PRED_HPP namespace __gnu_pbds { namespace detail { /// Entry predicate primary class template. template struct entry_pred; /// Specialization, true. template struct entry_pred<_VTp, Pred, _Alloc, true> { typedef Pred type; }; /// Specialization, false. template struct entry_pred<_VTp, Pred, _Alloc, false> { private: typedef typename _Alloc::template rebind<_VTp> __rebind_v; public: typedef typename __rebind_v::other::const_pointer entry; struct type : public Pred { inline type() { } inline type(const Pred& other) : Pred(other) { } inline bool operator()(entry p_v) const { return Pred::operator()(*p_v); } }; }; } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_BINARY_HEAP_ENTRY_PRED_HPP PK!@Ҁ18/ext/pb_ds/detail/binary_heap_/erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/erase_fn_imps.hpp * Contains an implementation class for a binary_heap. */ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear() { for (size_type i = 0; i < m_size; ++i) erase_at(m_a_entries, i, s_no_throw_copies_ind); __try { const size_type new_size = resize_policy::get_new_size_for_arbitrary(0); entry_pointer new_entries = s_entry_allocator.allocate(new_size); resize_policy::notify_arbitrary(new_size); s_entry_allocator.deallocate(m_a_entries, m_actual_size); m_actual_size = new_size; m_a_entries = new_entries; } __catch(...) { } m_size = 0; PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: erase_at(entry_pointer a_entries, size_type i, false_type) { a_entries[i]->~value_type(); s_value_allocator.deallocate(a_entries[i], 1); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: erase_at(entry_pointer, size_type, true_type) { } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: pop() { PB_DS_ASSERT_VALID((*this)) _GLIBCXX_DEBUG_ASSERT(!empty()); pop_heap(); erase_at(m_a_entries, m_size - 1, s_no_throw_copies_ind); resize_for_erase_if_needed(); _GLIBCXX_DEBUG_ASSERT(m_size > 0); --m_size; PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC template typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: erase_if(Pred pred) { PB_DS_ASSERT_VALID((*this)) typedef typename entry_pred::type pred_t; const size_type left = partition(pred_t(pred)); _GLIBCXX_DEBUG_ASSERT(m_size >= left); const size_type ersd = m_size - left; for (size_type i = left; i < m_size; ++i) erase_at(m_a_entries, i, s_no_throw_copies_ind); __try { const size_type new_size = resize_policy::get_new_size_for_arbitrary(left); entry_pointer new_entries = s_entry_allocator.allocate(new_size); std::copy(m_a_entries, m_a_entries + left, new_entries); s_entry_allocator.deallocate(m_a_entries, m_actual_size); m_actual_size = new_size; resize_policy::notify_arbitrary(m_actual_size); } __catch(...) { }; m_size = left; make_heap(); PB_DS_ASSERT_VALID((*this)) return ersd; } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: erase(point_iterator it) { PB_DS_ASSERT_VALID((*this)) _GLIBCXX_DEBUG_ASSERT(!empty()); const size_type fix_pos = it.m_p_e - m_a_entries; std::swap(*it.m_p_e, m_a_entries[m_size - 1]); erase_at(m_a_entries, m_size - 1, s_no_throw_copies_ind); resize_for_erase_if_needed(); _GLIBCXX_DEBUG_ASSERT(m_size > 0); --m_size; _GLIBCXX_DEBUG_ASSERT(fix_pos <= m_size); if (fix_pos != m_size) fix(m_a_entries + fix_pos); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: resize_for_erase_if_needed() { if (!resize_policy::resize_needed_for_shrink(m_size)) return; __try { const size_type new_size = resize_policy::get_new_size_for_shrink(); entry_pointer new_entries = s_entry_allocator.allocate(new_size); resize_policy::notify_shrink_resize(); _GLIBCXX_DEBUG_ASSERT(m_size > 0); std::copy(m_a_entries, m_a_entries + m_size - 1, new_entries); s_entry_allocator.deallocate(m_a_entries, m_actual_size); m_actual_size = new_size; m_a_entries = new_entries; } __catch(...) { } } PB_DS_CLASS_T_DEC template typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: partition(Pred pred) { size_type left = 0; size_type right = m_size - 1; while (right + 1 != left) { _GLIBCXX_DEBUG_ASSERT(left <= m_size); if (!pred(m_a_entries[left])) ++left; else if (pred(m_a_entries[right])) --right; else { _GLIBCXX_DEBUG_ASSERT(left < right); std::swap(m_a_entries[left], m_a_entries[right]); ++left; --right; } } return left; } PK!ιy% % 08/ext/pb_ds/detail/binary_heap_/find_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/find_fn_imps.hpp * Contains an implementation class for a binary_heap. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_reference PB_DS_CLASS_C_DEC:: top() const { PB_DS_ASSERT_VALID((*this)) _GLIBCXX_DEBUG_ASSERT(!empty()); return top_imp(s_no_throw_copies_ind); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_reference PB_DS_CLASS_C_DEC:: top_imp(true_type) const { return *m_a_entries; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_reference PB_DS_CLASS_C_DEC:: top_imp(false_type) const { return **m_a_entries; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: left_child(size_type i) { return i * 2 + 1; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: right_child(size_type i) { return i * 2 + 2; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: parent(size_type i) { return (i - 1) / 2; } PK!?~08/ext/pb_ds/detail/binary_heap_/info_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/info_fn_imps.hpp * Contains an implementation class for a binary_heap. */ PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: empty() const { return m_size == 0; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: size() const { return m_size; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: max_size() const { return s_entry_allocator.max_size(); } PK!H`rr28/ext/pb_ds/detail/binary_heap_/insert_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/insert_fn_imps.hpp * Contains an implementation class for a binary_heap. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: push(const_reference r_val) { PB_DS_ASSERT_VALID((*this)) insert_value(r_val, s_no_throw_copies_ind); push_heap(); PB_DS_ASSERT_VALID((*this)) return point_iterator(m_a_entries); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: insert_value(value_type val, true_type) { resize_for_insert_if_needed(); m_a_entries[m_size++] = val; } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: insert_value(const_reference r_val, false_type) { resize_for_insert_if_needed(); pointer p_new = s_value_allocator.allocate(1); cond_dealtor_t cond(p_new); new (p_new) value_type(r_val); cond.set_no_action(); m_a_entries[m_size++] = p_new; } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: resize_for_insert_if_needed() { if (!resize_policy::resize_needed_for_grow(m_size)) { _GLIBCXX_DEBUG_ASSERT(m_size < m_actual_size); return; } const size_type new_size = resize_policy::get_new_size_for_grow(); entry_pointer new_entries = s_entry_allocator.allocate(new_size); resize_policy::notify_grow_resize(); std::copy(m_a_entries, m_a_entries + m_size, new_entries); s_entry_allocator.deallocate(m_a_entries, m_actual_size); m_actual_size = new_size; m_a_entries = new_entries; make_heap(); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: modify(point_iterator it, const_reference r_new_val) { PB_DS_ASSERT_VALID((*this)) swap_value_imp(it.m_p_e, r_new_val, s_no_throw_copies_ind); fix(it.m_p_e); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: fix(entry_pointer p_e) { size_type i = p_e - m_a_entries; if (i > 0 && entry_cmp::operator()(m_a_entries[parent(i)], m_a_entries[i])) { size_type parent_i = parent(i); while (i > 0 && entry_cmp::operator()(m_a_entries[parent_i], m_a_entries[i])) { std::swap(m_a_entries[i], m_a_entries[parent_i]); i = parent_i; parent_i = parent(i); } PB_DS_ASSERT_VALID((*this)) return; } while (i < m_size) { const size_type lchild_i = left_child(i); const size_type rchild_i = right_child(i); _GLIBCXX_DEBUG_ASSERT(rchild_i > lchild_i); const bool smaller_than_lchild = lchild_i < m_size && entry_cmp::operator()(m_a_entries[i], m_a_entries[lchild_i]); const bool smaller_than_rchild = rchild_i < m_size && entry_cmp::operator()(m_a_entries[i], m_a_entries[rchild_i]); const bool swap_with_rchild = smaller_than_rchild && (!smaller_than_lchild || entry_cmp::operator()(m_a_entries[lchild_i], m_a_entries[rchild_i])); const bool swap_with_lchild = !swap_with_rchild && smaller_than_lchild; if (swap_with_lchild) { std::swap(m_a_entries[i], m_a_entries[lchild_i]); i = lchild_i; } else if (swap_with_rchild) { std::swap(m_a_entries[i], m_a_entries[rchild_i]); i = rchild_i; } else i = m_size; } } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: swap_value_imp(entry_pointer p_e, value_type new_val, true_type) { *p_e = new_val; } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: swap_value_imp(entry_pointer p_e, const_reference r_new_val, false_type) { value_type tmp(r_new_val); (*p_e)->swap(tmp); } PK!.58/ext/pb_ds/detail/binary_heap_/iterators_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/iterators_fn_imps.hpp * Contains an implementation class for a binary_heap. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: begin() { return iterator(m_a_entries); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: begin() const { return const_iterator(m_a_entries); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: end() { return iterator(m_a_entries + m_size); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: end() const { return const_iterator(m_a_entries + m_size); } PK! IPl__88/ext/pb_ds/detail/binary_heap_/point_const_iterator.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/point_const_iterator.hpp * Contains an iterator class returned by the table's const find and insert * methods. */ #ifndef PB_DS_BINARY_HEAP_CONST_FIND_ITERATOR_HPP #define PB_DS_BINARY_HEAP_CONST_FIND_ITERATOR_HPP #include #include namespace __gnu_pbds { namespace detail { /// Const point-type iterator. template class binary_heap_point_const_iterator_ { protected: typedef typename _Alloc::template rebind::other::pointer entry_pointer; public: /// Category. typedef trivial_iterator_tag iterator_category; /// Difference type. typedef trivial_iterator_difference_type difference_type; /// Iterator's value type. typedef Value_Type value_type; /// Iterator's pointer type. typedef typename _Alloc::template rebind::other::pointer pointer; /// Iterator's const pointer type. typedef typename _Alloc::template rebind::other::const_pointer const_pointer; /// Iterator's reference type. typedef typename _Alloc::template rebind::other::reference reference; /// Iterator's const reference type. typedef typename _Alloc::template rebind::other::const_reference const_reference; inline binary_heap_point_const_iterator_(entry_pointer p_e) : m_p_e(p_e) { } /// Default constructor. inline binary_heap_point_const_iterator_() : m_p_e(0) { } /// Copy constructor. inline binary_heap_point_const_iterator_(const binary_heap_point_const_iterator_& other) : m_p_e(other.m_p_e) { } /// Access. inline const_pointer operator->() const { _GLIBCXX_DEBUG_ASSERT(m_p_e != 0); return to_ptr(integral_constant()); } /// Access. inline const_reference operator*() const { _GLIBCXX_DEBUG_ASSERT(m_p_e != 0); return *to_ptr(integral_constant()); } /// Compares content to a different iterator object. inline bool operator==(const binary_heap_point_const_iterator_& other) const { return m_p_e == other.m_p_e; } /// Compares content (negatively) to a different iterator object. inline bool operator!=(const binary_heap_point_const_iterator_& other) const { return m_p_e != other.m_p_e; } private: inline const_pointer to_ptr(true_type) const { return m_p_e; } inline const_pointer to_ptr(false_type) const { return *m_p_e; } public: entry_pointer m_p_e; }; } // namespace detail } // namespace __gnu_pbds #endif PK! uM_nn98/ext/pb_ds/detail/binary_heap_/policy_access_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/policy_access_fn_imps.hpp * Contains an implementation class for a binary_heap. */ PB_DS_CLASS_T_DEC Cmp_Fn& PB_DS_CLASS_C_DEC:: get_cmp_fn() { return (*this); } PB_DS_CLASS_T_DEC const Cmp_Fn& PB_DS_CLASS_C_DEC:: get_cmp_fn() const { return (*this); } PK!18/ext/pb_ds/detail/binary_heap_/resize_policy.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/resize_policy.hpp * Contains an implementation class for a binary_heap. */ #ifndef PB_DS_BINARY_HEAP_RESIZE_POLICY_HPP #define PB_DS_BINARY_HEAP_RESIZE_POLICY_HPP #include namespace __gnu_pbds { namespace detail { /// Resize policy for binary heap. template class resize_policy { private: enum { ratio = 8, factor = 2 }; /// Next shrink size. _Tp m_shrink_size; /// Next grow size. _Tp m_grow_size; public: typedef _Tp size_type; static const _Tp min_size = 16; resize_policy() : m_shrink_size(0), m_grow_size(min_size) { PB_DS_ASSERT_VALID((*this)) } resize_policy(const resize_policy& other) : m_shrink_size(other.m_shrink_size), m_grow_size(other.m_grow_size) { PB_DS_ASSERT_VALID((*this)) } inline void swap(resize_policy<_Tp>&); inline bool resize_needed_for_grow(size_type) const; inline bool resize_needed_for_shrink(size_type) const; inline bool grow_needed(size_type) const; inline bool shrink_needed(size_type) const; inline size_type get_new_size_for_grow() const; inline size_type get_new_size_for_shrink() const; inline size_type get_new_size_for_arbitrary(size_type) const; inline void notify_grow_resize(); inline void notify_shrink_resize(); void notify_arbitrary(size_type); #ifdef _GLIBCXX_DEBUG void assert_valid(const char*, int) const; #endif #ifdef PB_DS_BINARY_HEAP_TRACE_ void trace() const; #endif }; template const _Tp resize_policy<_Tp>::min_size; template inline void resize_policy<_Tp>:: swap(resize_policy<_Tp>& other) { std::swap(m_shrink_size, other.m_shrink_size); std::swap(m_grow_size, other.m_grow_size); } template inline bool resize_policy<_Tp>:: resize_needed_for_grow(size_type size) const { _GLIBCXX_DEBUG_ASSERT(size <= m_grow_size); return size == m_grow_size; } template inline bool resize_policy<_Tp>:: resize_needed_for_shrink(size_type size) const { _GLIBCXX_DEBUG_ASSERT(size <= m_grow_size); return size == m_shrink_size; } template inline typename resize_policy<_Tp>::size_type resize_policy<_Tp>:: get_new_size_for_grow() const { return m_grow_size * factor; } template inline typename resize_policy<_Tp>::size_type resize_policy<_Tp>:: get_new_size_for_shrink() const { const size_type half_size = m_grow_size / factor; return std::max(min_size, half_size); } template inline typename resize_policy<_Tp>::size_type resize_policy<_Tp>:: get_new_size_for_arbitrary(size_type size) const { size_type ret = min_size; while (ret < size) ret *= factor; return ret; } template inline void resize_policy<_Tp>:: notify_grow_resize() { PB_DS_ASSERT_VALID((*this)) _GLIBCXX_DEBUG_ASSERT(m_grow_size >= min_size); m_grow_size *= factor; m_shrink_size = m_grow_size / ratio; PB_DS_ASSERT_VALID((*this)) } template inline void resize_policy<_Tp>:: notify_shrink_resize() { PB_DS_ASSERT_VALID((*this)) m_shrink_size /= factor; if (m_shrink_size == 1) m_shrink_size = 0; m_grow_size = std::max(m_grow_size / factor, min_size); PB_DS_ASSERT_VALID((*this)) } template inline void resize_policy<_Tp>:: notify_arbitrary(size_type actual_size) { m_grow_size = actual_size; m_shrink_size = m_grow_size / ratio; PB_DS_ASSERT_VALID((*this)) } #ifdef _GLIBCXX_DEBUG template void resize_policy<_Tp>:: assert_valid(const char* __file, int __line) const { PB_DS_DEBUG_VERIFY(m_shrink_size == 0 || m_shrink_size * ratio == m_grow_size); PB_DS_DEBUG_VERIFY(m_grow_size >= min_size); } #endif #ifdef PB_DS_BINARY_HEAP_TRACE_ template void resize_policy<_Tp>:: trace() const { std::cerr << "shrink = " << m_shrink_size << " grow = " << m_grow_size << std::endl; } #endif } // namespace detail } // namespace __gnu_pbds #endif PK!!';;68/ext/pb_ds/detail/binary_heap_/split_join_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/split_join_fn_imps.hpp * Contains an implementation class for a binary_heap. */ PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: split(Pred pred, PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) typedef typename entry_pred::type pred_t; const size_type left = partition(pred_t(pred)); _GLIBCXX_DEBUG_ASSERT(m_size >= left); const size_type ersd = m_size - left; _GLIBCXX_DEBUG_ASSERT(m_size >= ersd); const size_type new_size = resize_policy::get_new_size_for_arbitrary(left); const size_type other_actual_size = other.get_new_size_for_arbitrary(ersd); entry_pointer a_entries = 0; entry_pointer a_other_entries = 0; __try { a_entries = s_entry_allocator.allocate(new_size); a_other_entries = s_entry_allocator.allocate(other_actual_size); } __catch(...) { if (a_entries != 0) s_entry_allocator.deallocate(a_entries, new_size); if (a_other_entries != 0) s_entry_allocator.deallocate(a_other_entries, other_actual_size); __throw_exception_again; }; for (size_type i = 0; i < other.m_size; ++i) erase_at(other.m_a_entries, i, s_no_throw_copies_ind); _GLIBCXX_DEBUG_ASSERT(new_size >= left); std::copy(m_a_entries, m_a_entries + left, a_entries); std::copy(m_a_entries + left, m_a_entries + m_size, a_other_entries); s_entry_allocator.deallocate(m_a_entries, m_actual_size); s_entry_allocator.deallocate(other.m_a_entries, other.m_actual_size); m_actual_size = new_size; other.m_actual_size = other_actual_size; m_size = left; other.m_size = ersd; m_a_entries = a_entries; other.m_a_entries = a_other_entries; make_heap(); other.make_heap(); resize_policy::notify_arbitrary(m_actual_size); other.notify_arbitrary(other.m_actual_size); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: join(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) const size_type len = m_size + other.m_size; const size_type new_size = resize_policy::get_new_size_for_arbitrary(len); entry_pointer a_entries = 0; entry_pointer a_other_entries = 0; __try { a_entries = s_entry_allocator.allocate(new_size); a_other_entries = s_entry_allocator.allocate(resize_policy::min_size); } __catch(...) { if (a_entries != 0) s_entry_allocator.deallocate(a_entries, new_size); if (a_other_entries != 0) s_entry_allocator.deallocate(a_other_entries, resize_policy::min_size); __throw_exception_again; } std::copy(m_a_entries, m_a_entries + m_size, a_entries); std::copy(other.m_a_entries, other.m_a_entries + other.m_size, a_entries + m_size); s_entry_allocator.deallocate(m_a_entries, m_actual_size); m_a_entries = a_entries; m_size = len; m_actual_size = new_size; resize_policy::notify_arbitrary(new_size); make_heap(); s_entry_allocator.deallocate(other.m_a_entries, other.m_actual_size); other.m_a_entries = a_other_entries; other.m_size = 0; other.m_actual_size = resize_policy::min_size; other.notify_arbitrary(resize_policy::min_size); other.make_heap(); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PK!_v 18/ext/pb_ds/detail/binary_heap_/trace_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binary_heap_/trace_fn_imps.hpp * Contains an implementation class for a binary_heap. */ #ifdef PB_DS_BINARY_HEAP_TRACE_ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace() const { std::cerr << this << std::endl; std::cerr << m_a_entries << std::endl; for (size_type i = 0; i < m_size; ++i) trace_entry(m_a_entries[i], s_no_throw_copies_ind); std::cerr << std::endl; std::cerr << "size = " << m_size << " " << "actual_size = " << m_actual_size << std::endl; resize_policy::trace(); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace_entry(const entry& r_e, false_type) const { std::cout << r_e << " " <<* r_e << std::endl; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace_entry(const entry& r_e, true_type) const { std::cout << r_e << std::endl; } #endif // #ifdef PB_DS_BINARY_HEAP_TRACE_ PK!RR48/ext/pb_ds/detail/binomial_heap_/binomial_heap_.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binomial_heap_.hpp * Contains an implementation class for a binomial heap. */ /* * Binomial heap. * Vuillemin J is the mastah. * Modified from CLRS. */ #include #include #include #include namespace __gnu_pbds { namespace detail { #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ binomial_heap /** * Binomial heap. * * @ingroup heap-detail */ template class binomial_heap : public binomial_heap_base { private: typedef binomial_heap_base base_type; typedef typename base_type::node_pointer node_pointer; typedef typename base_type::node_const_pointer node_const_pointer; public: typedef Value_Type value_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef typename base_type::pointer pointer; typedef typename base_type::const_pointer const_pointer; typedef typename base_type::reference reference; typedef typename base_type::const_reference const_reference; typedef typename base_type::point_const_iterator point_const_iterator; typedef typename base_type::point_iterator point_iterator; typedef typename base_type::const_iterator const_iterator; typedef typename base_type::iterator iterator; typedef typename base_type::cmp_fn cmp_fn; typedef typename base_type::allocator_type allocator_type; binomial_heap(); binomial_heap(const Cmp_Fn&); binomial_heap(const binomial_heap&); ~binomial_heap(); protected: #ifdef _GLIBCXX_DEBUG void assert_valid(const char*, int) const; #endif }; #include #include #undef PB_DS_CLASS_C_DEC #undef PB_DS_CLASS_T_DEC } // namespace detail } // namespace __gnu_pbds PK!tggE8/ext/pb_ds/detail/binomial_heap_/constructors_destructor_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file detail/binomial_heap_/constructors_destructor_fn_imps.hpp * Contains an implementation for binomial_heap_. */ PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: binomial_heap() { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: binomial_heap(const Cmp_Fn& r_cmp_fn) : base_type(r_cmp_fn) { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: binomial_heap(const PB_DS_CLASS_C_DEC& other) : base_type(other) { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~binomial_heap() { } PK!_Eii38/ext/pb_ds/detail/binomial_heap_/debug_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file detail/binomial_heap_/debug_fn_imps.hpp * Contains an implementation for binomial_heap_. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { base_type::assert_valid(true, __file, __line); } #endif PK!px::>8/ext/pb_ds/detail/binomial_heap_base_/binomial_heap_base_.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binomial_heap_base_/binomial_heap_base_.hpp * Contains an implementation class for a base of binomial heaps. */ #ifndef PB_DS_BINOMIAL_HEAP_BASE_HPP #define PB_DS_BINOMIAL_HEAP_BASE_HPP /* * Binomial heap base. * Vuillemin J is the mastah. * Modified from CLRS. */ #include #include #include #include namespace __gnu_pbds { namespace detail { #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ binomial_heap_base #ifdef _GLIBCXX_DEBUG #define PB_DS_B_HEAP_BASE \ left_child_next_sibling_heap #else #define PB_DS_B_HEAP_BASE \ left_child_next_sibling_heap #endif /// Base class for binomial heap. template class binomial_heap_base : public PB_DS_B_HEAP_BASE { private: typedef typename _Alloc::template rebind::other __rebind_v; typedef PB_DS_B_HEAP_BASE base_type; protected: typedef typename base_type::node node; typedef typename base_type::node_pointer node_pointer; typedef typename base_type::node_const_pointer node_const_pointer; public: typedef Value_Type value_type; typedef Cmp_Fn cmp_fn; typedef _Alloc allocator_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef typename __rebind_v::pointer pointer; typedef typename __rebind_v::const_pointer const_pointer; typedef typename __rebind_v::reference reference; typedef typename __rebind_v::const_reference const_reference; typedef typename base_type::point_const_iterator point_const_iterator; typedef typename base_type::point_iterator point_iterator; typedef typename base_type::const_iterator const_iterator; typedef typename base_type::iterator iterator; public: inline point_iterator push(const_reference); void modify(point_iterator, const_reference); inline const_reference top() const; void pop(); void erase(point_iterator); inline void clear(); template size_type erase_if(Pred); template void split(Pred, PB_DS_CLASS_C_DEC&); void join(PB_DS_CLASS_C_DEC&); protected: binomial_heap_base(); binomial_heap_base(const Cmp_Fn&); binomial_heap_base(const PB_DS_CLASS_C_DEC&); void swap(PB_DS_CLASS_C_DEC&); ~binomial_heap_base(); template void copy_from_range(It, It); inline void find_max(); #ifdef _GLIBCXX_DEBUG void assert_valid(bool, const char*, int) const; void assert_max(const char*, int) const; #endif private: inline node_pointer fix(node_pointer) const; inline void insert_node(node_pointer); inline void remove_parentless_node(node_pointer); inline node_pointer join(node_pointer, node_pointer) const; #ifdef _GLIBCXX_DEBUG void assert_node_consistent(node_const_pointer, bool, bool, const char*, int) const; #endif protected: node_pointer m_p_max; }; #define PB_DS_ASSERT_VALID_COND(X, _StrictlyBinomial) \ _GLIBCXX_DEBUG_ONLY(X.assert_valid(_StrictlyBinomial,__FILE__, __LINE__);) #define PB_DS_ASSERT_BASE_NODE_CONSISTENT(_Node, _Bool) \ _GLIBCXX_DEBUG_ONLY(base_type::assert_node_consistent(_Node, _Bool, \ __FILE__, __LINE__);) #include #include #include #include #include #include #undef PB_DS_ASSERT_BASE_NODE_CONSISTENT #undef PB_DS_ASSERT_VALID_COND #undef PB_DS_CLASS_C_DEC #undef PB_DS_CLASS_T_DEC #undef PB_DS_B_HEAP_BASE } // namespace detail } // namespace __gnu_pbds #endif PK!ܮY J8/ext/pb_ds/detail/binomial_heap_base_/constructors_destructor_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binomial_heap_base_/constructors_destructor_fn_imps.hpp * Contains an implementation class for a base of binomial heaps. */ PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: copy_from_range(It first_it, It last_it) { while (first_it != last_it) push(*(first_it++)); PB_DS_ASSERT_VALID_COND((*this),false) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: binomial_heap_base() : m_p_max(0) { PB_DS_ASSERT_VALID_COND((*this),false) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: binomial_heap_base(const Cmp_Fn& r_cmp_fn) : base_type(r_cmp_fn), m_p_max(0) { PB_DS_ASSERT_VALID_COND((*this),false) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: binomial_heap_base(const PB_DS_CLASS_C_DEC& other) : base_type(other), m_p_max(0) { PB_DS_ASSERT_VALID_COND((*this),false) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID_COND((*this),false) base_type::swap(other); std::swap(m_p_max, other.m_p_max); PB_DS_ASSERT_VALID_COND((*this),false) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~binomial_heap_base() { } PK!I 88/ext/pb_ds/detail/binomial_heap_base_/debug_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binomial_heap_base_/debug_fn_imps.hpp * Contains an implementation class for a base of binomial heaps. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(bool strictly_binomial, const char* __file, int __line) const { base_type::assert_valid(__file, __line); assert_node_consistent(base_type::m_p_root, strictly_binomial, true, __file, __line); assert_max(__file, __line); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_max(const char* __file, int __line) const { if (m_p_max == 0) return; PB_DS_DEBUG_VERIFY(base_type::parent(m_p_max) == 0); for (const_iterator it = base_type::begin(); it != base_type::end(); ++it) PB_DS_DEBUG_VERIFY(!Cmp_Fn::operator()(m_p_max->m_value, it.m_p_nd->m_value)); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_node_consistent(node_const_pointer p_nd, bool strictly_binomial, bool increasing, const char* __file, int __line) const { PB_DS_DEBUG_VERIFY(increasing || strictly_binomial); base_type::assert_node_consistent(p_nd, false, __file, __line); if (p_nd == 0) return; PB_DS_DEBUG_VERIFY(p_nd->m_metadata == base_type::degree(p_nd)); PB_DS_DEBUG_VERIFY(base_type::size_under_node(p_nd) == static_cast(1 << p_nd->m_metadata)); assert_node_consistent(p_nd->m_p_next_sibling, strictly_binomial, increasing, __file, __line); assert_node_consistent(p_nd->m_p_l_child, true, false, __file, __line); if (p_nd->m_p_next_sibling != 0) { if (increasing) { if (strictly_binomial) PB_DS_DEBUG_VERIFY(p_nd->m_metadata < p_nd->m_p_next_sibling->m_metadata); else PB_DS_DEBUG_VERIFY(p_nd->m_metadata <= p_nd->m_p_next_sibling->m_metadata); } else PB_DS_DEBUG_VERIFY(p_nd->m_metadata > p_nd->m_p_next_sibling->m_metadata); } } #endif PK!Dd88/ext/pb_ds/detail/binomial_heap_base_/erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binomial_heap_base_/erase_fn_imps.hpp * Contains an implementation class for a base of binomial heaps. */ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: pop() { PB_DS_ASSERT_VALID_COND((*this),true) _GLIBCXX_DEBUG_ASSERT(!base_type::empty()); if (m_p_max == 0) find_max(); _GLIBCXX_DEBUG_ASSERT(m_p_max != 0); node_pointer p_nd = m_p_max; remove_parentless_node(m_p_max); base_type::actual_erase_node(p_nd); m_p_max = 0; PB_DS_ASSERT_VALID_COND((*this),true) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: remove_parentless_node(node_pointer p_nd) { _GLIBCXX_DEBUG_ASSERT(p_nd != 0); _GLIBCXX_DEBUG_ASSERT(base_type::parent(p_nd) == 0); node_pointer p_cur_root = p_nd == base_type::m_p_root? p_nd->m_p_next_sibling : base_type::m_p_root; if (p_cur_root != 0) p_cur_root->m_p_prev_or_parent = 0; if (p_nd->m_p_prev_or_parent != 0) p_nd->m_p_prev_or_parent->m_p_next_sibling = p_nd->m_p_next_sibling; if (p_nd->m_p_next_sibling != 0) p_nd->m_p_next_sibling->m_p_prev_or_parent = p_nd->m_p_prev_or_parent; node_pointer p_child = p_nd->m_p_l_child; if (p_child != 0) { p_child->m_p_prev_or_parent = 0; while (p_child->m_p_next_sibling != 0) p_child = p_child->m_p_next_sibling; } m_p_max = 0; base_type::m_p_root = join(p_cur_root, p_child); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: clear() { base_type::clear(); m_p_max = 0; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: erase(point_iterator it) { PB_DS_ASSERT_VALID_COND((*this),true) _GLIBCXX_DEBUG_ASSERT(!base_type::empty()); base_type::bubble_to_top(it.m_p_nd); remove_parentless_node(it.m_p_nd); base_type::actual_erase_node(it.m_p_nd); m_p_max = 0; PB_DS_ASSERT_VALID_COND((*this),true) } PB_DS_CLASS_T_DEC template typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: erase_if(Pred pred) { PB_DS_ASSERT_VALID_COND((*this),true) if (base_type::empty()) { PB_DS_ASSERT_VALID_COND((*this),true) return 0; } base_type::to_linked_list(); node_pointer p_out = base_type::prune(pred); size_type ersd = 0; while (p_out != 0) { ++ersd; node_pointer p_next = p_out->m_p_next_sibling; base_type::actual_erase_node(p_out); p_out = p_next; } node_pointer p_cur = base_type::m_p_root; base_type::m_p_root = 0; while (p_cur != 0) { node_pointer p_next = p_cur->m_p_next_sibling; p_cur->m_p_l_child = p_cur->m_p_prev_or_parent = 0; p_cur->m_metadata = 0; p_cur->m_p_next_sibling = base_type::m_p_root; if (base_type::m_p_root != 0) base_type::m_p_root->m_p_prev_or_parent = p_cur; base_type::m_p_root = p_cur; base_type::m_p_root = fix(base_type::m_p_root); p_cur = p_next; } m_p_max = 0; PB_DS_ASSERT_VALID_COND((*this),true) return ersd; } PK!; m-) ) 78/ext/pb_ds/detail/binomial_heap_base_/find_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binomial_heap_base_/find_fn_imps.hpp * Contains an implementation class for a base of binomial heaps. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_reference PB_DS_CLASS_C_DEC:: top() const { PB_DS_ASSERT_VALID_COND((*this),false) _GLIBCXX_DEBUG_ASSERT(!base_type::empty()); if (m_p_max == 0) const_cast(this)->find_max(); _GLIBCXX_DEBUG_ASSERT(m_p_max != 0); return m_p_max->m_value; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: find_max() { node_pointer p_cur = base_type::m_p_root; m_p_max = p_cur; while (p_cur != 0) { if (Cmp_Fn::operator()(m_p_max->m_value, p_cur->m_value)) m_p_max = p_cur; p_cur = p_cur->m_p_next_sibling; } } PK!Ca98/ext/pb_ds/detail/binomial_heap_base_/insert_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binomial_heap_base_/insert_fn_imps.hpp * Contains an implementation class for a base of binomial heaps. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: push(const_reference r_val) { PB_DS_ASSERT_VALID_COND((*this),true) node_pointer p_nd = base_type::get_new_node_for_insert(r_val); insert_node(p_nd); m_p_max = 0; PB_DS_ASSERT_VALID_COND((*this),true) return point_iterator(p_nd); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: insert_node(node_pointer p_nd) { if (base_type::m_p_root == 0) { p_nd->m_p_next_sibling = 0; p_nd->m_p_prev_or_parent = 0; p_nd->m_p_l_child = 0; p_nd->m_metadata = 0; base_type::m_p_root = p_nd; return; } if (base_type::m_p_root->m_metadata > 0) { p_nd->m_p_prev_or_parent = p_nd->m_p_l_child = 0; p_nd->m_p_next_sibling = base_type::m_p_root; base_type::m_p_root->m_p_prev_or_parent = p_nd; base_type::m_p_root = p_nd; p_nd->m_metadata = 0; return; } if (Cmp_Fn::operator()(base_type::m_p_root->m_value, p_nd->m_value)) { p_nd->m_p_next_sibling = base_type::m_p_root->m_p_next_sibling; p_nd->m_p_prev_or_parent = 0; p_nd->m_metadata = 1; p_nd->m_p_l_child = base_type::m_p_root; base_type::m_p_root->m_p_prev_or_parent = p_nd; base_type::m_p_root->m_p_next_sibling = 0; base_type::m_p_root = p_nd; } else { p_nd->m_p_next_sibling = 0; p_nd->m_p_l_child = 0; p_nd->m_p_prev_or_parent = base_type::m_p_root; p_nd->m_metadata = 0; _GLIBCXX_DEBUG_ASSERT(base_type::m_p_root->m_p_l_child == 0); base_type::m_p_root->m_p_l_child = p_nd; base_type::m_p_root->m_metadata = 1; } base_type::m_p_root = fix(base_type::m_p_root); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: fix(node_pointer p_nd) const { while (p_nd->m_p_next_sibling != 0 && p_nd->m_metadata == p_nd->m_p_next_sibling->m_metadata) { node_pointer p_next = p_nd->m_p_next_sibling; if (Cmp_Fn::operator()(p_nd->m_value, p_next->m_value)) { p_next->m_p_prev_or_parent = p_nd->m_p_prev_or_parent; if (p_nd->m_p_prev_or_parent != 0) p_nd->m_p_prev_or_parent->m_p_next_sibling = p_next; base_type::make_child_of(p_nd, p_next); ++p_next->m_metadata; p_nd = p_next; } else { p_nd->m_p_next_sibling = p_next->m_p_next_sibling; if (p_nd->m_p_next_sibling != 0) p_next->m_p_next_sibling = 0; base_type::make_child_of(p_next, p_nd); ++p_nd->m_metadata; } } if (p_nd->m_p_next_sibling != 0) p_nd->m_p_next_sibling->m_p_prev_or_parent = p_nd; return p_nd; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: modify(point_iterator it, const_reference r_new_val) { PB_DS_ASSERT_VALID_COND((*this),true) node_pointer p_nd = it.m_p_nd; _GLIBCXX_DEBUG_ASSERT(p_nd != 0); PB_DS_ASSERT_BASE_NODE_CONSISTENT(p_nd, false) const bool bubble_up = Cmp_Fn::operator()(p_nd->m_value, r_new_val); p_nd->m_value = r_new_val; if (bubble_up) { node_pointer p_parent = base_type::parent(p_nd); while (p_parent != 0 && Cmp_Fn::operator()(p_parent->m_value, p_nd->m_value)) { base_type::swap_with_parent(p_nd, p_parent); p_parent = base_type::parent(p_nd); } if (p_nd->m_p_prev_or_parent == 0) base_type::m_p_root = p_nd; m_p_max = 0; PB_DS_ASSERT_VALID_COND((*this),true) return; } base_type::bubble_to_top(p_nd); remove_parentless_node(p_nd); insert_node(p_nd); m_p_max = 0; PB_DS_ASSERT_VALID_COND((*this),true) } PK!V =8/ext/pb_ds/detail/binomial_heap_base_/split_join_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binomial_heap_base_/split_join_fn_imps.hpp * Contains an implementation class for a base of binomial heaps. */ PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: split(Pred pred, PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID_COND((*this),true) PB_DS_ASSERT_VALID_COND(other,true) other.clear(); if (base_type::empty()) { PB_DS_ASSERT_VALID_COND((*this),true) PB_DS_ASSERT_VALID_COND(other,true) return; } base_type::to_linked_list(); node_pointer p_out = base_type::prune(pred); while (p_out != 0) { _GLIBCXX_DEBUG_ASSERT(base_type::m_size > 0); --base_type::m_size; ++other.m_size; node_pointer p_next = p_out->m_p_next_sibling; p_out->m_p_l_child = p_out->m_p_prev_or_parent = 0; p_out->m_metadata = 0; p_out->m_p_next_sibling = other.m_p_root; if (other.m_p_root != 0) other.m_p_root->m_p_prev_or_parent = p_out; other.m_p_root = p_out; other.m_p_root = other.fix(other.m_p_root); p_out = p_next; } PB_DS_ASSERT_VALID_COND(other,true) node_pointer p_cur = base_type::m_p_root; base_type::m_p_root = 0; while (p_cur != 0) { node_pointer p_next = p_cur->m_p_next_sibling; p_cur->m_p_l_child = p_cur->m_p_prev_or_parent = 0; p_cur->m_metadata = 0; p_cur->m_p_next_sibling = base_type::m_p_root; if (base_type::m_p_root != 0) base_type::m_p_root->m_p_prev_or_parent = p_cur; base_type::m_p_root = p_cur; base_type::m_p_root = fix(base_type::m_p_root); p_cur = p_next; } m_p_max = 0; PB_DS_ASSERT_VALID_COND((*this),true) PB_DS_ASSERT_VALID_COND(other,true) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: join(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID_COND((*this),true) PB_DS_ASSERT_VALID_COND(other,true) node_pointer p_other = other.m_p_root; if (p_other != 0) do { node_pointer p_next = p_other->m_p_next_sibling; std::swap(p_other->m_p_next_sibling, p_other->m_p_prev_or_parent); p_other = p_next; } while (p_other != 0); base_type::m_p_root = join(base_type::m_p_root, other.m_p_root); base_type::m_size += other.m_size; m_p_max = 0; other.m_p_root = 0; other.m_size = 0; other.m_p_max = 0; PB_DS_ASSERT_VALID_COND((*this),true) PB_DS_ASSERT_VALID_COND(other,true) } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: join(node_pointer p_lhs, node_pointer p_rhs) const { node_pointer p_ret = 0; node_pointer p_cur = 0; while (p_lhs != 0 || p_rhs != 0) { if (p_rhs == 0) { if (p_cur == 0) p_ret = p_cur = p_lhs; else { p_cur->m_p_next_sibling = p_lhs; p_lhs->m_p_prev_or_parent = p_cur; } p_cur = p_lhs = 0; } else if (p_lhs == 0 || p_rhs->m_metadata < p_lhs->m_metadata) { if (p_cur == 0) { p_ret = p_cur = p_rhs; p_rhs = p_rhs->m_p_prev_or_parent; } else { p_cur->m_p_next_sibling = p_rhs; p_rhs = p_rhs->m_p_prev_or_parent; p_cur->m_p_next_sibling->m_p_prev_or_parent = p_cur; p_cur = p_cur->m_p_next_sibling; } } else if (p_lhs->m_metadata < p_rhs->m_metadata) { if (p_cur == 0) p_ret = p_cur = p_lhs; else { p_cur->m_p_next_sibling = p_lhs; p_lhs->m_p_prev_or_parent = p_cur; p_cur = p_cur->m_p_next_sibling; } p_lhs = p_cur->m_p_next_sibling; } else { node_pointer p_next_rhs = p_rhs->m_p_prev_or_parent; p_rhs->m_p_next_sibling = p_lhs; p_lhs = fix(p_rhs); p_rhs = p_next_rhs; } } if (p_cur != 0) p_cur->m_p_next_sibling = 0; if (p_ret != 0) p_ret->m_p_prev_or_parent = 0; return p_ret; } PK!28/ext/pb_ds/detail/branch_policy/branch_policy.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file branch_policy/branch_policy.hpp * Contains a base class for branch policies. */ #ifndef PB_DS_BRANCH_POLICY_BASE_HPP #define PB_DS_BRANCH_POLICY_BASE_HPP #include namespace __gnu_pbds { namespace detail { /// Primary template, base class for branch structure policies. template struct branch_policy { protected: typedef typename Node_Itr::value_type it_type; typedef typename std::iterator_traits::value_type value_type; typedef typename value_type::first_type key_type; typedef typename remove_const::type rcvalue_type; typedef typename remove_const::type rckey_type; typedef typename _Alloc::template rebind::other rebind_v; typedef typename _Alloc::template rebind::other rebind_k; typedef typename rebind_v::reference reference; typedef typename rebind_v::const_reference const_reference; typedef typename rebind_v::const_pointer const_pointer; typedef typename rebind_k::const_reference key_const_reference; static inline key_const_reference extract_key(const_reference r_val) { return r_val.first; } virtual it_type end() = 0; it_type end_iterator() const { return const_cast(this)->end(); } virtual ~branch_policy() { } }; /// Specialization for const iterators. template struct branch_policy { protected: typedef typename Node_CItr::value_type it_type; typedef typename std::iterator_traits::value_type value_type; typedef typename remove_const::type rcvalue_type; typedef typename _Alloc::template rebind::other rebind_v; typedef typename rebind_v::reference reference; typedef typename rebind_v::const_reference const_reference; typedef typename rebind_v::const_pointer const_pointer; typedef value_type key_type; typedef typename rebind_v::const_reference key_const_reference; static inline key_const_reference extract_key(const_reference r_val) { return r_val; } virtual it_type end() const = 0; it_type end_iterator() const { return end(); } virtual ~branch_policy() { } }; } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_BRANCH_POLICY_BASE_HPP PK!) K K 78/ext/pb_ds/detail/branch_policy/null_node_metadata.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file branch_policy/null_node_metadata.hpp * Contains an implementation class for tree-like classes. */ #ifndef PB_DS_0_NODE_METADATA_HPP #define PB_DS_0_NODE_METADATA_HPP #include namespace __gnu_pbds { namespace detail { /// Constant node iterator. template struct dumnode_const_iterator { private: typedef types_traits __traits_type; typedef typename __traits_type::pointer const_iterator; public: typedef const_iterator value_type; typedef const_iterator const_reference; typedef const_reference reference; }; } // namespace detail } // namespace __gnu_pbds #endif PK!Ho +8/ext/pb_ds/detail/branch_policy/traits.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file branch_policy/traits.hpp * Contains an implementation class for tree-like classes. */ #ifndef PB_DS_NODE_AND_IT_TRAITS_HPP #define PB_DS_NODE_AND_IT_TRAITS_HPP #include #include #include #include #define PB_DS_DEBUG_VERIFY(_Cond) \ _GLIBCXX_DEBUG_VERIFY_AT(_Cond, \ _M_message(#_Cond" assertion from %1;:%2;") \ ._M_string(__FILE__)._M_integer(__LINE__) \ ,__file,__line) namespace __gnu_pbds { namespace detail { /// Tree traits class, primary template. template class Node_Update, typename Tag, typename _Alloc> struct tree_traits; /// Trie traits class, primary template. template class Node_Update, typename Tag, typename _Alloc> struct trie_traits; } // namespace detail } // namespace __gnu_pbds #include #include #include #include #undef PB_DS_DEBUG_VERIFY #endif // #ifndef PB_DS_NODE_AND_IT_TRAITS_HPP PK!MM48/ext/pb_ds/detail/cc_hash_table_map_/cc_ht_map_.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/cc_ht_map_.hpp * Contains an implementation class for cc_ht_map_. */ #include #include #include #include #include #include #include #include #ifdef _GLIBCXX_DEBUG #include #endif #ifdef PB_DS_HT_MAP_TRACE_ #include #endif #include namespace __gnu_pbds { namespace detail { #ifdef PB_DS_DATA_TRUE_INDICATOR #define PB_DS_CC_HASH_NAME cc_ht_map #endif #ifdef PB_DS_DATA_FALSE_INDICATOR #define PB_DS_CC_HASH_NAME cc_ht_set #endif #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ PB_DS_CC_HASH_NAME #define PB_DS_HASH_EQ_FN_C_DEC \ hash_eq_fn #define PB_DS_RANGED_HASH_FN_C_DEC \ ranged_hash_fn #define PB_DS_CC_HASH_TRAITS_BASE \ types_traits #ifdef _GLIBCXX_DEBUG #define PB_DS_DEBUG_MAP_BASE_C_DEC \ debug_map_base::other::const_reference> #endif /** * A collision-chaining hash-based container. * * * @ingroup hash-detail * * @tparam Key Key type. * * @tparam Mapped Map type. * * @tparam Hash_Fn Hashing functor. * Default is __gnu_cxx::hash. * * @tparam Eq_Fn Equal functor. * Default std::equal_to * * @tparam _Alloc Allocator type. * * @tparam Store_Hash If key type stores extra metadata. * Defaults to false. * * @tparam Comb_Hash_Fn Combining hash functor. * If Hash_Fn is not null_type, then this * is the ranged-hash functor; otherwise, * this is the range-hashing functor. * XXX(See Design::Hash-Based Containers::Hash Policies.) * Default direct_mask_range_hashing. * * @tparam Resize_Policy Resizes hash. * Defaults to hash_standard_resize_policy, * using hash_exponential_size_policy and * hash_load_check_resize_trigger. * * * Bases are: detail::hash_eq_fn, Resize_Policy, detail::ranged_hash_fn, * detail::types_traits. (Optional: detail::debug_map_base.) */ template class PB_DS_CC_HASH_NAME: #ifdef _GLIBCXX_DEBUG protected PB_DS_DEBUG_MAP_BASE_C_DEC, #endif public PB_DS_HASH_EQ_FN_C_DEC, public Resize_Policy, public PB_DS_RANGED_HASH_FN_C_DEC, public PB_DS_CC_HASH_TRAITS_BASE { private: typedef PB_DS_CC_HASH_TRAITS_BASE traits_base; typedef typename traits_base::comp_hash comp_hash; typedef typename traits_base::value_type value_type_; typedef typename traits_base::pointer pointer_; typedef typename traits_base::const_pointer const_pointer_; typedef typename traits_base::reference reference_; typedef typename traits_base::const_reference const_reference_; struct entry : public traits_base::stored_data_type { typename _Alloc::template rebind::other::pointer m_p_next; }; typedef cond_dealtor cond_dealtor_t; typedef typename _Alloc::template rebind::other entry_allocator; typedef typename entry_allocator::pointer entry_pointer; typedef typename entry_allocator::const_pointer const_entry_pointer; typedef typename entry_allocator::reference entry_reference; typedef typename entry_allocator::const_reference const_entry_reference; typedef typename _Alloc::template rebind::other entry_pointer_allocator; typedef typename entry_pointer_allocator::pointer entry_pointer_array; typedef PB_DS_RANGED_HASH_FN_C_DEC ranged_hash_fn_base; typedef PB_DS_HASH_EQ_FN_C_DEC hash_eq_fn_base; typedef Resize_Policy resize_base; #ifdef _GLIBCXX_DEBUG typedef PB_DS_DEBUG_MAP_BASE_C_DEC debug_base; #endif #define PB_DS_GEN_POS std::pair #include #include #include #include #undef PB_DS_GEN_POS public: typedef _Alloc allocator_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef Hash_Fn hash_fn; typedef Eq_Fn eq_fn; typedef Comb_Hash_Fn comb_hash_fn; typedef Resize_Policy resize_policy; /// Value stores hash, true or false. enum { store_hash = Store_Hash }; typedef typename traits_base::key_type key_type; typedef typename traits_base::key_pointer key_pointer; typedef typename traits_base::key_const_pointer key_const_pointer; typedef typename traits_base::key_reference key_reference; typedef typename traits_base::key_const_reference key_const_reference; typedef typename traits_base::mapped_type mapped_type; typedef typename traits_base::mapped_pointer mapped_pointer; typedef typename traits_base::mapped_const_pointer mapped_const_pointer; typedef typename traits_base::mapped_reference mapped_reference; typedef typename traits_base::mapped_const_reference mapped_const_reference; typedef typename traits_base::value_type value_type; typedef typename traits_base::pointer pointer; typedef typename traits_base::const_pointer const_pointer; typedef typename traits_base::reference reference; typedef typename traits_base::const_reference const_reference; #ifdef PB_DS_DATA_TRUE_INDICATOR typedef point_iterator_ point_iterator; #endif #ifdef PB_DS_DATA_FALSE_INDICATOR typedef point_const_iterator_ point_iterator; #endif typedef point_const_iterator_ point_const_iterator; #ifdef PB_DS_DATA_TRUE_INDICATOR typedef iterator_ iterator; #endif #ifdef PB_DS_DATA_FALSE_INDICATOR typedef const_iterator_ iterator; #endif typedef const_iterator_ const_iterator; PB_DS_CC_HASH_NAME(); PB_DS_CC_HASH_NAME(const Hash_Fn&); PB_DS_CC_HASH_NAME(const Hash_Fn&, const Eq_Fn&); PB_DS_CC_HASH_NAME(const Hash_Fn&, const Eq_Fn&, const Comb_Hash_Fn&); PB_DS_CC_HASH_NAME(const Hash_Fn&, const Eq_Fn&, const Comb_Hash_Fn&, const Resize_Policy&); PB_DS_CC_HASH_NAME(const PB_DS_CLASS_C_DEC&); virtual ~PB_DS_CC_HASH_NAME(); void swap(PB_DS_CLASS_C_DEC&); template void copy_from_range(It, It); void initialize(); inline size_type size() const; inline size_type max_size() const; /// True if size() == 0. inline bool empty() const; /// Return current hash_fn. Hash_Fn& get_hash_fn(); /// Return current const hash_fn. const Hash_Fn& get_hash_fn() const; /// Return current eq_fn. Eq_Fn& get_eq_fn(); /// Return current const eq_fn. const Eq_Fn& get_eq_fn() const; /// Return current comb_hash_fn. Comb_Hash_Fn& get_comb_hash_fn(); /// Return current const comb_hash_fn. const Comb_Hash_Fn& get_comb_hash_fn() const; /// Return current resize_policy. Resize_Policy& get_resize_policy(); /// Return current const resize_policy. const Resize_Policy& get_resize_policy() const; inline std::pair insert(const_reference r_val) { return insert_imp(r_val, traits_base::m_store_extra_indicator); } inline mapped_reference operator[](key_const_reference r_key) { #ifdef PB_DS_DATA_TRUE_INDICATOR return (subscript_imp(r_key, traits_base::m_store_extra_indicator)); #else insert(r_key); return traits_base::s_null_type; #endif } inline point_iterator find(key_const_reference); inline point_const_iterator find(key_const_reference) const; inline point_iterator find_end(); inline point_const_iterator find_end() const; inline bool erase(key_const_reference); template inline size_type erase_if(Pred); void clear(); inline iterator begin(); inline const_iterator begin() const; inline iterator end(); inline const_iterator end() const; #ifdef _GLIBCXX_DEBUG void assert_valid(const char*, int) const; #endif #ifdef PB_DS_HT_MAP_TRACE_ void trace() const; #endif private: void deallocate_all(); inline bool do_resize_if_needed(); inline void do_resize_if_needed_no_throw(); void resize_imp(size_type); void do_resize(size_type); void resize_imp_no_exceptions(size_type, entry_pointer_array, size_type); inline entry_pointer resize_imp_no_exceptions_reassign_pointer(entry_pointer, entry_pointer_array, false_type); inline entry_pointer resize_imp_no_exceptions_reassign_pointer(entry_pointer, entry_pointer_array, true_type); void deallocate_links_in_list(entry_pointer); inline entry_pointer get_entry(const_reference, false_type); inline entry_pointer get_entry(const_reference, true_type); inline void rels_entry(entry_pointer); #ifdef PB_DS_DATA_TRUE_INDICATOR inline mapped_reference subscript_imp(key_const_reference r_key, false_type) { _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) const size_type pos = ranged_hash_fn_base::operator()(r_key); entry_pointer p_e = m_entries[pos]; resize_base::notify_insert_search_start(); while (p_e != 0 && !hash_eq_fn_base::operator()(p_e->m_value.first, r_key)) { resize_base::notify_insert_search_collision(); p_e = p_e->m_p_next; } resize_base::notify_insert_search_end(); if (p_e != 0) { PB_DS_CHECK_KEY_EXISTS(r_key) return (p_e->m_value.second); } PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return insert_new_imp(value_type(r_key, mapped_type()), pos)->second; } inline mapped_reference subscript_imp(key_const_reference r_key, true_type) { _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) comp_hash pos_hash_pair = ranged_hash_fn_base::operator()(r_key); entry_pointer p_e = m_entries[pos_hash_pair.first]; resize_base::notify_insert_search_start(); while (p_e != 0 && !hash_eq_fn_base::operator()(p_e->m_value.first, p_e->m_hash, r_key, pos_hash_pair.second)) { resize_base::notify_insert_search_collision(); p_e = p_e->m_p_next; } resize_base::notify_insert_search_end(); if (p_e != 0) { PB_DS_CHECK_KEY_EXISTS(r_key) return p_e->m_value.second; } PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return insert_new_imp(value_type(r_key, mapped_type()), pos_hash_pair)->second; } #endif inline std::pair insert_imp(const_reference, false_type); inline std::pair insert_imp(const_reference, true_type); inline pointer insert_new_imp(const_reference r_val, size_type pos) { if (do_resize_if_needed()) pos = ranged_hash_fn_base::operator()(PB_DS_V2F(r_val)); // Following lines might throw an exception. entry_pointer p_e = get_entry(r_val, traits_base::m_no_throw_copies_indicator); // At this point no exceptions can be thrown. p_e->m_p_next = m_entries[pos]; m_entries[pos] = p_e; resize_base::notify_inserted(++m_num_used_e); _GLIBCXX_DEBUG_ONLY(debug_base::insert_new(PB_DS_V2F(r_val));) _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) return &p_e->m_value; } inline pointer insert_new_imp(const_reference r_val, comp_hash& r_pos_hash_pair) { // Following lines might throw an exception. if (do_resize_if_needed()) r_pos_hash_pair = ranged_hash_fn_base::operator()(PB_DS_V2F(r_val)); entry_pointer p_e = get_entry(r_val, traits_base::m_no_throw_copies_indicator); // At this point no exceptions can be thrown. p_e->m_hash = r_pos_hash_pair.second; p_e->m_p_next = m_entries[r_pos_hash_pair.first]; m_entries[r_pos_hash_pair.first] = p_e; resize_base::notify_inserted(++m_num_used_e); _GLIBCXX_DEBUG_ONLY(debug_base::insert_new(PB_DS_V2F(r_val));) _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) return &p_e->m_value; } inline pointer find_key_pointer(key_const_reference r_key, false_type) { entry_pointer p_e = m_entries[ranged_hash_fn_base::operator()(r_key)]; resize_base::notify_find_search_start(); while (p_e != 0 && !hash_eq_fn_base::operator()(PB_DS_V2F(p_e->m_value), r_key)) { resize_base::notify_find_search_collision(); p_e = p_e->m_p_next; } resize_base::notify_find_search_end(); #ifdef _GLIBCXX_DEBUG if (p_e == 0) PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) else PB_DS_CHECK_KEY_EXISTS(r_key) #endif return &p_e->m_value; } inline pointer find_key_pointer(key_const_reference r_key, true_type) { comp_hash pos_hash_pair = ranged_hash_fn_base::operator()(r_key); entry_pointer p_e = m_entries[pos_hash_pair.first]; resize_base::notify_find_search_start(); while (p_e != 0 && !hash_eq_fn_base::operator()(PB_DS_V2F(p_e->m_value), p_e->m_hash, r_key, pos_hash_pair.second)) { resize_base::notify_find_search_collision(); p_e = p_e->m_p_next; } resize_base::notify_find_search_end(); #ifdef _GLIBCXX_DEBUG if (p_e == 0) PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) else PB_DS_CHECK_KEY_EXISTS(r_key) #endif return &p_e->m_value; } inline bool erase_in_pos_imp(key_const_reference, size_type); inline bool erase_in_pos_imp(key_const_reference, const comp_hash&); inline void erase_entry_pointer(entry_pointer&); #ifdef PB_DS_DATA_TRUE_INDICATOR void inc_it_state(pointer& r_p_value, std::pair& r_pos) const { inc_it_state((mapped_const_pointer& )r_p_value, r_pos); } #endif void inc_it_state(const_pointer& r_p_value, std::pair& r_pos) const { _GLIBCXX_DEBUG_ASSERT(r_p_value != 0); r_pos.first = r_pos.first->m_p_next; if (r_pos.first != 0) { r_p_value = &r_pos.first->m_value; return; } for (++r_pos.second; r_pos.second < m_num_e; ++r_pos.second) if (m_entries[r_pos.second] != 0) { r_pos.first = m_entries[r_pos.second]; r_p_value = &r_pos.first->m_value; return; } r_p_value = 0; } void get_start_it_state(pointer& r_p_value, std::pair& r_pos) const { for (r_pos.second = 0; r_pos.second < m_num_e; ++r_pos.second) if (m_entries[r_pos.second] != 0) { r_pos.first = m_entries[r_pos.second]; r_p_value = &r_pos.first->m_value; return; } r_p_value = 0; } #ifdef _GLIBCXX_DEBUG void assert_entry_pointer_array_valid(const entry_pointer_array, const char*, int) const; void assert_entry_pointer_valid(const entry_pointer, true_type, const char*, int) const; void assert_entry_pointer_valid(const entry_pointer, false_type, const char*, int) const; #endif #ifdef PB_DS_HT_MAP_TRACE_ void trace_list(const_entry_pointer) const; #endif private: #ifdef PB_DS_DATA_TRUE_INDICATOR friend class iterator_; #endif friend class const_iterator_; static entry_allocator s_entry_allocator; static entry_pointer_allocator s_entry_pointer_allocator; static iterator s_end_it; static const_iterator s_const_end_it; static point_iterator s_find_end_it; static point_const_iterator s_const_find_end_it; size_type m_num_e; size_type m_num_used_e; entry_pointer_array m_entries; enum { store_hash_ok = !Store_Hash || !is_same::value }; PB_DS_STATIC_ASSERT(sth, store_hash_ok); }; #include #include #include #include #include #include #include #include #include #include #include #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #undef PB_DS_HASH_EQ_FN_C_DEC #undef PB_DS_RANGED_HASH_FN_C_DEC #undef PB_DS_CC_HASH_TRAITS_BASE #undef PB_DS_DEBUG_MAP_BASE_C_DEC #undef PB_DS_CC_HASH_NAME } // namespace detail } // namespace __gnu_pbds PK! 58/ext/pb_ds/detail/cc_hash_table_map_/cmp_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/cmp_fn_imps.hpp * Contains implementations of cc_ht_map_'s entire container comparison related * functions. */ PB_DS_CLASS_T_DEC template bool PB_DS_CLASS_C_DEC:: operator==(const Other_HT_Map_Type& other) const { return cmp_with_other(other); } PB_DS_CLASS_T_DEC template bool PB_DS_CLASS_C_DEC:: cmp_with_other(const Other_Map_Type& other) const { if (size() != other.size()) return false; for (typename Other_Map_Type::const_iterator it = other.begin(); it != other.end(); ++it) { key_const_reference r_key = key_const_reference(PB_DS_V2F(*it)); mapped_const_pointer p_mapped_value = const_cast(*this). find_key_pointer(r_key, traits_base::m_store_extra_indicator); if (p_mapped_value == 0) return false; #ifdef PB_DS_DATA_TRUE_INDICATOR if (p_mapped_value->second != it->second) return false; #endif } return true; } PB_DS_CLASS_T_DEC template bool PB_DS_CLASS_C_DEC:: operator!=(const Other_HT_Map_Type& other) const { return !operator==(other); } PK!A: : E8/ext/pb_ds/detail/cc_hash_table_map_/cond_key_dtor_entry_dealtor.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/cond_key_dtor_entry_dealtor.hpp * Contains a conditional key destructor, used for exception handling. */ namespace __gnu_pbds { namespace detail { /// Conditional dey destructor, cc_hash. template class cond_dealtor { public: typedef typename HT_Map::entry entry; typedef typename HT_Map::entry_allocator entry_allocator; typedef typename HT_Map::key_type key_type; cond_dealtor(entry_allocator* p_a, entry* p_e) : m_p_a(p_a), m_p_e(p_e), m_key_destruct(false), m_no_action_destructor(false) { } inline ~cond_dealtor(); void set_key_destruct() { m_key_destruct = true; } void set_no_action_destructor() { m_no_action_destructor = true; } protected: entry_allocator* const m_p_a; entry* const m_p_e; bool m_key_destruct; bool m_no_action_destructor; }; template inline cond_dealtor:: ~cond_dealtor() { if (m_no_action_destructor) return; if (m_key_destruct) m_p_e->m_value.first.~key_type(); m_p_a->deallocate(m_p_e, 1); } } // namespace detail } // namespace __gnu_pbds PK!vƟH8/ext/pb_ds/detail/cc_hash_table_map_/constructor_destructor_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/constructor_destructor_fn_imps.hpp * Contains implementations of cc_ht_map_'s constructors, destructor, * and related functions. */ PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::entry_allocator PB_DS_CLASS_C_DEC::s_entry_allocator; PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::entry_pointer_allocator PB_DS_CLASS_C_DEC::s_entry_pointer_allocator; PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: copy_from_range(It first_it, It last_it) { while (first_it != last_it) insert(*(first_it++)); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_CC_HASH_NAME() : ranged_hash_fn_base(resize_base::get_nearest_larger_size(1)), m_num_e(resize_base::get_nearest_larger_size(1)), m_num_used_e(0), m_entries(s_entry_pointer_allocator.allocate(m_num_e)) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_CC_HASH_NAME(const Hash_Fn& r_hash_fn) : ranged_hash_fn_base(resize_base::get_nearest_larger_size(1), r_hash_fn), m_num_e(resize_base::get_nearest_larger_size(1)), m_num_used_e(0), m_entries(s_entry_pointer_allocator.allocate(m_num_e)) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_CC_HASH_NAME(const Hash_Fn& r_hash_fn, const Eq_Fn& r_eq_fn) : PB_DS_HASH_EQ_FN_C_DEC(r_eq_fn), ranged_hash_fn_base(resize_base::get_nearest_larger_size(1), r_hash_fn), m_num_e(resize_base::get_nearest_larger_size(1)), m_num_used_e(0), m_entries(s_entry_pointer_allocator.allocate(m_num_e)) { std::fill(m_entries, m_entries + m_num_e, (entry_pointer)0); Resize_Policy::notify_cleared(); ranged_hash_fn_base::notify_resized(m_num_e); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_CC_HASH_NAME(const Hash_Fn& r_hash_fn, const Eq_Fn& r_eq_fn, const Comb_Hash_Fn& r_comb_hash_fn) : PB_DS_HASH_EQ_FN_C_DEC(r_eq_fn), ranged_hash_fn_base(resize_base::get_nearest_larger_size(1), r_hash_fn, r_comb_hash_fn), m_num_e(resize_base::get_nearest_larger_size(1)), m_num_used_e(0), m_entries(s_entry_pointer_allocator.allocate(m_num_e)) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_CC_HASH_NAME(const Hash_Fn& r_hash_fn, const Eq_Fn& r_eq_fn, const Comb_Hash_Fn& r_comb_hash_fn, const Resize_Policy& r_resize_policy) : PB_DS_HASH_EQ_FN_C_DEC(r_eq_fn), Resize_Policy(r_resize_policy), ranged_hash_fn_base(resize_base::get_nearest_larger_size(1), r_hash_fn, r_comb_hash_fn), m_num_e(resize_base::get_nearest_larger_size(1)), m_num_used_e(0), m_entries(s_entry_pointer_allocator.allocate(m_num_e)) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_CC_HASH_NAME(const PB_DS_CLASS_C_DEC& other) : PB_DS_HASH_EQ_FN_C_DEC(other), resize_base(other), ranged_hash_fn_base(other), m_num_e(resize_base::get_nearest_larger_size(1)), m_num_used_e(0), m_entries(s_entry_pointer_allocator.allocate(m_num_e)) { initialize(); PB_DS_ASSERT_VALID((*this)) __try { copy_from_range(other.begin(), other.end()); } __catch(...) { deallocate_all(); __throw_exception_again; } PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~PB_DS_CC_HASH_NAME() { deallocate_all(); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) std::swap(m_entries, other.m_entries); std::swap(m_num_e, other.m_num_e); std::swap(m_num_used_e, other.m_num_used_e); ranged_hash_fn_base::swap(other); hash_eq_fn_base::swap(other); resize_base::swap(other); _GLIBCXX_DEBUG_ONLY(debug_base::swap(other)); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: deallocate_all() { clear(); s_entry_pointer_allocator.deallocate(m_entries, m_num_e); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: initialize() { std::fill(m_entries, m_entries + m_num_e, entry_pointer(0)); Resize_Policy::notify_resized(m_num_e); Resize_Policy::notify_cleared(); ranged_hash_fn_base::notify_resized(m_num_e); } PK!& EV8/ext/pb_ds/detail/cc_hash_table_map_/constructor_destructor_no_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/constructor_destructor_no_store_hash_fn_imps.hpp * Contains implementations of cc_ht_map_'s constructors, destructor, * and related functions. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: constructor_insert_new_imp(mapped_const_reference r_val, size_type pos, false_type) { // Following lines might throw an exception. entry_pointer p = get_entry(r_val, traits_base::s_no_throw_copies_indicator); // At this point no exceptions can be thrown. p->m_p_next = m_entries[pos]; m_entries[pos] = p; _GLIBCXX_DEBUG_ONLY(debug_base::insert_new(r_key);) } PK!>  S8/ext/pb_ds/detail/cc_hash_table_map_/constructor_destructor_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/constructor_destructor_store_hash_fn_imps.hpp * Contains implementations of cc_ht_map_'s constructors, destructor, * and related functions. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: constructor_insert_new_imp(const_reference r_val, size_type pos, true_type) { // Following lines might throw an exception. entry_pointer p = get_entry(r_val, traits_base::s_no_throw_copies_indicator); // At this point no exceptions can be thrown. p->m_p_next = m_entries[pos]; p->m_hash = ranged_hash_fn_base::operator()((key_const_reference)(PB_DS_V2F(p->m_value))).second; m_entries[pos] = p; _GLIBCXX_DEBUG_ONLY(debug_base::insert_new(r_key);) } PK! l 78/ext/pb_ds/detail/cc_hash_table_map_/debug_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/debug_fn_imps.hpp * Contains implementations of cc_ht_map_'s debug-mode functions. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { debug_base::check_size(m_num_used_e, __file, __line); assert_entry_pointer_array_valid(m_entries, __file, __line); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_entry_pointer_array_valid(const entry_pointer_array a_p_entries, const char* __file, int __line) const { size_type iterated_num_used_e = 0; for (size_type pos = 0; pos < m_num_e; ++pos) { entry_pointer p_e = a_p_entries[pos]; while (p_e != 0) { ++iterated_num_used_e; assert_entry_pointer_valid(p_e, traits_base::m_store_extra_indicator, __file, __line); p_e = p_e->m_p_next; } } PB_DS_DEBUG_VERIFY(iterated_num_used_e == m_num_used_e); } #include #include #endif PK!E8/ext/pb_ds/detail/cc_hash_table_map_/debug_no_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/debug_no_store_hash_fn_imps.hpp * Contains implementations of cc_ht_map_'s debug-mode functions. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_entry_pointer_valid(const entry_pointer p, false_type, const char* __file, int __line) const { debug_base::check_key_exists(PB_DS_V2F(p->m_value), __file, __line); } #endif PK!^YddB8/ext/pb_ds/detail/cc_hash_table_map_/debug_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/debug_store_hash_fn_imps.hpp * Contains implementations of cc_ht_map_'s debug-mode functions. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_entry_pointer_valid(const entry_pointer p_e, true_type, const char* __file, int __line) const { debug_base::check_key_exists(PB_DS_V2F(p_e->m_value), __file, __line); comp_hash pos_hash_pair = ranged_hash_fn_base::operator()(PB_DS_V2F(p_e->m_value)); PB_DS_DEBUG_VERIFY(p_e->m_hash == pos_hash_pair.second); } #endif PK!W, <8/ext/pb_ds/detail/cc_hash_table_map_/entry_list_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/entry_list_fn_imps.hpp * Contains implementations of cc_ht_map_'s entry-list related functions. */ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: deallocate_links_in_list(entry_pointer p_e) { while (p_e != 0) { entry_pointer p_dealloc_e = p_e; p_e = p_e->m_p_next; s_entry_allocator.deallocate(p_dealloc_e, 1); } } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::entry_pointer PB_DS_CLASS_C_DEC:: get_entry(const_reference r_val, true_type) { // Following line might throw an exception. entry_pointer p_e = s_entry_allocator.allocate(1); // Following lines* cannot* throw an exception. new (&p_e->m_value) value_type(r_val); return p_e; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::entry_pointer PB_DS_CLASS_C_DEC:: get_entry(const_reference r_val, false_type) { // Following line might throw an exception. entry_pointer p_e = s_entry_allocator.allocate(1); cond_dealtor_t cond(p_e); // Following lines might throw an exception. new (&p_e->m_value) value_type(r_val); cond.set_no_action(); return p_e; } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: rels_entry(entry_pointer p_e) { // The following lines cannot throw exceptions (unless if key-data dtors do). p_e->m_value.~value_type(); s_entry_allocator.deallocate(p_e, 1); } PK!? 78/ext/pb_ds/detail/cc_hash_table_map_/erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/erase_fn_imps.hpp * Contains implementations of cc_ht_map_'s erase related functions. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: erase_entry_pointer(entry_pointer& r_p_e) { _GLIBCXX_DEBUG_ONLY(debug_base::erase_existing(PB_DS_V2F(r_p_e->m_value))); entry_pointer p_e = r_p_e; r_p_e = r_p_e->m_p_next; rels_entry(p_e); _GLIBCXX_DEBUG_ASSERT(m_num_used_e > 0); resize_base::notify_erased(--m_num_used_e); } PB_DS_CLASS_T_DEC template inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: erase_if(Pred pred) { size_type num_ersd = 0; for (size_type pos = 0; pos < m_num_e; ++pos) { while (m_entries[pos] != 0 && pred(m_entries[pos]->m_value)) { ++num_ersd; entry_pointer p_next_e = m_entries[pos]->m_p_next; erase_entry_pointer(m_entries[pos]); m_entries[pos] = p_next_e; } entry_pointer p_e = m_entries[pos]; while (p_e != 0 && p_e->m_p_next != 0) { if (pred(p_e->m_p_next->m_value)) { ++num_ersd; erase_entry_pointer(p_e->m_p_next); } else p_e = p_e->m_p_next; } } do_resize_if_needed_no_throw(); return num_ersd; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear() { for (size_type pos = 0; pos < m_num_e; ++pos) while (m_entries[pos] != 0) erase_entry_pointer(m_entries[pos]); do_resize_if_needed_no_throw(); resize_base::notify_cleared(); } #include #include PK! E8/ext/pb_ds/detail/cc_hash_table_map_/erase_no_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/erase_no_store_hash_fn_imps.hpp * Contains implementations of cc_ht_map_'s erase related functions, * when the hash value is not stored. */ PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: erase(key_const_reference r_key) { PB_DS_ASSERT_VALID((*this)) return erase_in_pos_imp(r_key, ranged_hash_fn_base::operator()(r_key)); } PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: erase_in_pos_imp(key_const_reference r_key, size_type pos) { PB_DS_ASSERT_VALID((*this)) entry_pointer p_e = m_entries[pos]; resize_base::notify_erase_search_start(); if (p_e == 0) { resize_base::notify_erase_search_end(); PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) PB_DS_ASSERT_VALID((*this)) return false; } if (hash_eq_fn_base::operator()(PB_DS_V2F(p_e->m_value), r_key)) { resize_base::notify_erase_search_end(); PB_DS_CHECK_KEY_EXISTS(r_key) erase_entry_pointer(m_entries[pos]); do_resize_if_needed_no_throw(); PB_DS_ASSERT_VALID((*this)) return true; } while (true) { entry_pointer p_next_e = p_e->m_p_next; if (p_next_e == 0) { resize_base::notify_erase_search_end(); PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) PB_DS_ASSERT_VALID((*this)) return false; } if (hash_eq_fn_base::operator()(PB_DS_V2F(p_next_e->m_value), r_key)) { resize_base::notify_erase_search_end(); PB_DS_CHECK_KEY_EXISTS(r_key) erase_entry_pointer(p_e->m_p_next); do_resize_if_needed_no_throw(); PB_DS_ASSERT_VALID((*this)) return true; } resize_base::notify_erase_search_collision(); p_e = p_next_e; } } PK!Զ) B8/ext/pb_ds/detail/cc_hash_table_map_/erase_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/erase_store_hash_fn_imps.hpp * Contains implementations of cc_ht_map_'s erase related functions, * when the hash value is stored. */ PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: erase_in_pos_imp(key_const_reference r_key, const comp_hash& r_pos_hash_pair) { PB_DS_ASSERT_VALID((*this)) entry_pointer p_e = m_entries[r_pos_hash_pair.first]; resize_base::notify_erase_search_start(); if (p_e == 0) { resize_base::notify_erase_search_end(); PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) PB_DS_ASSERT_VALID((*this)) return false; } if (hash_eq_fn_base::operator()(PB_DS_V2F(p_e->m_value), p_e->m_hash, r_key, r_pos_hash_pair.second)) { resize_base::notify_erase_search_end(); PB_DS_CHECK_KEY_EXISTS(r_key) erase_entry_pointer(m_entries[r_pos_hash_pair.first]); do_resize_if_needed_no_throw(); PB_DS_ASSERT_VALID((*this)) return true; } while (true) { entry_pointer p_next_e = p_e->m_p_next; if (p_next_e == 0) { resize_base::notify_erase_search_end(); PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) PB_DS_ASSERT_VALID((*this)) return false; } if (hash_eq_fn_base::operator()(PB_DS_V2F(p_next_e->m_value), p_next_e->m_hash, r_key, r_pos_hash_pair.second)) { resize_base::notify_erase_search_end(); PB_DS_CHECK_KEY_EXISTS(r_key) erase_entry_pointer(p_e->m_p_next); do_resize_if_needed_no_throw(); PB_DS_ASSERT_VALID((*this)) return true; } resize_base::notify_erase_search_collision(); p_e = p_next_e; } } PK!Cs 68/ext/pb_ds/detail/cc_hash_table_map_/find_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/find_fn_imps.hpp * Contains implementations of cc_ht_map_'s find related functions. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: find(key_const_reference r_key) { PB_DS_ASSERT_VALID((*this)) return find_key_pointer(r_key, traits_base::m_store_extra_indicator); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_const_iterator PB_DS_CLASS_C_DEC:: find(key_const_reference r_key) const { PB_DS_ASSERT_VALID((*this)) return const_cast(*this).find_key_pointer(r_key, traits_base::m_store_extra_indicator); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: find_end() { return 0; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_const_iterator PB_DS_CLASS_C_DEC:: find_end() const { return 0; } PK!vA8/ext/pb_ds/detail/cc_hash_table_map_/find_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/find_store_hash_fn_imps.hpp * Contains implementations of cc_ht_map_'s find related functions, * when the hash value is stored. */ PK!m' ' 68/ext/pb_ds/detail/cc_hash_table_map_/info_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/info_fn_imps.hpp * Contains implementations of cc_ht_map_'s entire container info related * functions. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: size() const { return m_num_used_e; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: max_size() const { return m_entry_allocator.max_size(); } PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: empty() const { return (size() == 0); } PB_DS_CLASS_T_DEC template bool PB_DS_CLASS_C_DEC:: operator==(const Other_HT_Map_Type& other) const { return cmp_with_other(other); } PB_DS_CLASS_T_DEC template bool PB_DS_CLASS_C_DEC:: cmp_with_other(const Other_Map_Type& other) const { if (size() != other.size()) return false; for (typename Other_Map_Type::const_iterator it = other.begin(); it != other.end(); ++it) { key_const_reference r_key =(key_const_reference)PB_DS_V2F(*it); mapped_const_pointer p_mapped_value = const_cast(*this). find_key_pointer(r_key, traits_base::m_store_extra_indicator); if (p_mapped_value == 0) return false; #ifdef PB_DS_DATA_TRUE_INDICATOR if (p_mapped_value->second != it->second) return false; #endif } return true; } PB_DS_CLASS_T_DEC template bool PB_DS_CLASS_C_DEC:: operator!=(const Other_HT_Map_Type& other) const { return !operator==(other); } PK!뾏hh88/ext/pb_ds/detail/cc_hash_table_map_/insert_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/insert_fn_imps.hpp * Contains implementations of cc_ht_map_'s insert related functions. */ #include #include PK! 9: : F8/ext/pb_ds/detail/cc_hash_table_map_/insert_no_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/insert_no_store_hash_fn_imps.hpp * Contains implementations of cc_ht_map_'s insert related functions, * when the hash value is not stored. */ PB_DS_CLASS_T_DEC inline std::pair PB_DS_CLASS_C_DEC:: insert_imp(const_reference r_val, false_type) { PB_DS_ASSERT_VALID((*this)) key_const_reference r_key = PB_DS_V2F(r_val); const size_type pos = ranged_hash_fn_base::operator()(r_key); entry_pointer p_e = m_entries[pos]; resize_base::notify_insert_search_start(); while (p_e != 0 && !hash_eq_fn_base::operator()(PB_DS_V2F(p_e->m_value), r_key)) { resize_base::notify_insert_search_collision(); p_e = p_e->m_p_next; } resize_base::notify_insert_search_end(); if (p_e != 0) { PB_DS_CHECK_KEY_EXISTS(r_key) return std::make_pair(&p_e->m_value, false); } PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return std::make_pair(insert_new_imp(r_val, pos), true); } PK!/r r C8/ext/pb_ds/detail/cc_hash_table_map_/insert_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/insert_store_hash_fn_imps.hpp * Contains implementations of cc_ht_map_'s insert related functions, * when the hash value is stored. */ PB_DS_CLASS_T_DEC inline std::pair PB_DS_CLASS_C_DEC:: insert_imp(const_reference r_val, true_type) { PB_DS_ASSERT_VALID((*this)) key_const_reference key = PB_DS_V2F(r_val); comp_hash pos_hash_pair = ranged_hash_fn_base::operator()(key); entry_pointer p_e = m_entries[pos_hash_pair.first]; resize_base::notify_insert_search_start(); while (p_e != 0 && !hash_eq_fn_base::operator()(PB_DS_V2F(p_e->m_value), p_e->m_hash, key, pos_hash_pair.second)) { resize_base::notify_insert_search_collision(); p_e = p_e->m_p_next; } resize_base::notify_insert_search_end(); if (p_e != 0) { PB_DS_CHECK_KEY_EXISTS(key) return std::make_pair(&p_e->m_value, false); } PB_DS_CHECK_KEY_DOES_NOT_EXIST(key) return std::make_pair(insert_new_imp(r_val, pos_hash_pair), true); } PK!׳h h ;8/ext/pb_ds/detail/cc_hash_table_map_/iterators_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/iterators_fn_imps.hpp * Contains implementations of cc_ht_map_'s iterators related functions, e.g., * begin(). */ PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC::s_end_it; PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC::s_const_end_it; PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: begin() { pointer p_value; std::pair pos; get_start_it_state(p_value, pos); return iterator(p_value, pos, this); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: end() { return s_end_it; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: begin() const { pointer p_value; std::pair pos; get_start_it_state(p_value, pos); return const_iterator(p_value, pos, this); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: end() const { return s_const_end_it; } PK!1 ?8/ext/pb_ds/detail/cc_hash_table_map_/policy_access_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/policy_access_fn_imps.hpp * Contains implementations of cc_ht_map_'s policy access * functions. */ PB_DS_CLASS_T_DEC Hash_Fn& PB_DS_CLASS_C_DEC:: get_hash_fn() { return *this; } PB_DS_CLASS_T_DEC const Hash_Fn& PB_DS_CLASS_C_DEC:: get_hash_fn() const { return *this; } PB_DS_CLASS_T_DEC Eq_Fn& PB_DS_CLASS_C_DEC:: get_eq_fn() { return *this; } PB_DS_CLASS_T_DEC const Eq_Fn& PB_DS_CLASS_C_DEC:: get_eq_fn() const { return *this; } PB_DS_CLASS_T_DEC Comb_Hash_Fn& PB_DS_CLASS_C_DEC:: get_comb_hash_fn() { return *this; } PB_DS_CLASS_T_DEC const Comb_Hash_Fn& PB_DS_CLASS_C_DEC:: get_comb_hash_fn() const { return *this; } PB_DS_CLASS_T_DEC Resize_Policy& PB_DS_CLASS_C_DEC:: get_resize_policy() { return *this; } PB_DS_CLASS_T_DEC const Resize_Policy& PB_DS_CLASS_C_DEC:: get_resize_policy() const { return *this; } PK!v88/ext/pb_ds/detail/cc_hash_table_map_/resize_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/resize_fn_imps.hpp * Contains implementations of cc_ht_map_'s resize related functions. */ PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: do_resize_if_needed() { if (!resize_base::is_resize_needed()) return false; resize_imp(resize_base::get_new_size(m_num_e, m_num_used_e)); return true; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: do_resize(size_type len) { resize_imp(resize_base::get_nearest_larger_size(len)); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: do_resize_if_needed_no_throw() { if (!resize_base::is_resize_needed()) return; __try { resize_imp(resize_base::get_new_size(m_num_e, m_num_used_e)); } __catch(...) { } PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: resize_imp(size_type new_size) { PB_DS_ASSERT_VALID((*this)) if (new_size == m_num_e) return; const size_type old_size = m_num_e; entry_pointer_array a_p_entries_resized; // Following line might throw an exception. ranged_hash_fn_base::notify_resized(new_size); __try { // Following line might throw an exception. a_p_entries_resized = s_entry_pointer_allocator.allocate(new_size); m_num_e = new_size; } __catch(...) { ranged_hash_fn_base::notify_resized(old_size); __throw_exception_again; } // At this point no exceptions can be thrown. resize_imp_no_exceptions(new_size, a_p_entries_resized, old_size); Resize_Policy::notify_resized(new_size); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: resize_imp_no_exceptions(size_type new_size, entry_pointer_array a_p_entries_resized, size_type old_size) { std::fill(a_p_entries_resized, a_p_entries_resized + m_num_e, entry_pointer(0)); for (size_type pos = 0; pos < old_size; ++pos) { entry_pointer p_e = m_entries[pos]; while (p_e != 0) p_e = resize_imp_no_exceptions_reassign_pointer(p_e, a_p_entries_resized, traits_base::m_store_extra_indicator); } m_num_e = new_size; _GLIBCXX_DEBUG_ONLY(assert_entry_pointer_array_valid(a_p_entries_resized, __FILE__, __LINE__);) s_entry_pointer_allocator.deallocate(m_entries, old_size); m_entries = a_p_entries_resized; PB_DS_ASSERT_VALID((*this)) } #include #include PK!4F8/ext/pb_ds/detail/cc_hash_table_map_/resize_no_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/resize_no_store_hash_fn_imps.hpp * Contains implementations of cc_ht_map_'s resize related functions, when the * hash value is not stored. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::entry_pointer PB_DS_CLASS_C_DEC:: resize_imp_no_exceptions_reassign_pointer(entry_pointer p_e, entry_pointer_array a_p_entries_resized, false_type) { const size_type hash_pos = ranged_hash_fn_base::operator()(PB_DS_V2F(p_e->m_value)); entry_pointer const p_next_e = p_e->m_p_next; p_e->m_p_next = a_p_entries_resized[hash_pos]; a_p_entries_resized[hash_pos] = p_e; return p_next_e; } PK!C.C8/ext/pb_ds/detail/cc_hash_table_map_/resize_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/resize_store_hash_fn_imps.hpp * Contains implementations of cc_ht_map_'s resize related functions, when the * hash value is stored. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::entry_pointer PB_DS_CLASS_C_DEC:: resize_imp_no_exceptions_reassign_pointer(entry_pointer p_e, entry_pointer_array a_p_entries_resized, true_type) { const comp_hash pos_hash_pair = ranged_hash_fn_base::operator()(PB_DS_V2F(p_e->m_value), p_e->m_hash); entry_pointer const p_next_e = p_e->m_p_next; p_e->m_p_next = a_p_entries_resized[pos_hash_pair.first]; a_p_entries_resized[pos_hash_pair.first] = p_e; return p_next_e; } PK!ִ ==68/ext/pb_ds/detail/cc_hash_table_map_/size_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/size_fn_imps.hpp * Contains implementations of cc_ht_map_'s entire container size related * functions. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: size() const { return m_num_used_e; } PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: empty() const { return (size() == 0); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: max_size() const { return s_entry_allocator.max_size(); } PK!E}; ; 78/ext/pb_ds/detail/cc_hash_table_map_/trace_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_table_map_/trace_fn_imps.hpp * Contains implementations of cc_ht_map_'s trace-mode functions. */ #ifdef PB_DS_HT_MAP_TRACE_ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace() const { std::cerr << static_cast(m_num_e) << " " << static_cast(m_num_used_e) << std::endl; for (size_type i = 0; i < m_num_e; ++i) { std::cerr << static_cast(i) << " "; trace_list(m_entries[i]); std::cerr << std::endl; } } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace_list(const_entry_pointer p_l) const { size_type iterated_num_used_e = 0; while (p_l != 0) { std::cerr << PB_DS_V2F(p_l->m_value) << " "; p_l = p_l->m_p_next; } } #endif PK!Ld  '8/ext/pb_ds/detail/eq_fn/eq_by_less.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file eq_by_less.hpp * Contains an equivalence function. */ #ifndef PB_DS_EQ_BY_LESS_HPP #define PB_DS_EQ_BY_LESS_HPP #include #include #include #include #include namespace __gnu_pbds { namespace detail { /// Equivalence function. template struct eq_by_less : private Cmp_Fn { bool operator()(const Key& r_lhs, const Key& r_rhs) const { const bool l = Cmp_Fn::operator()(r_lhs, r_rhs); const bool g = Cmp_Fn::operator()(r_rhs, r_lhs); return !(l || g); } }; } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_EQ_BY_LESS_HPP PK!d9'8/ext/pb_ds/detail/eq_fn/hash_eq_fn.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file hash_eq_fn.hpp * Contains 2 eqivalence functions, one employing a hash value, * and one ignoring it. */ #ifndef PB_DS_HASH_EQ_FN_HPP #define PB_DS_HASH_EQ_FN_HPP #include #include namespace __gnu_pbds { namespace detail { /// Primary template. template struct hash_eq_fn; /// Specialization 1 - The client requests that hash values not be stored. template struct hash_eq_fn : public Eq_Fn { typedef Eq_Fn eq_fn_base; typedef typename _Alloc::template rebind::other key_allocator; typedef typename key_allocator::const_reference key_const_reference; hash_eq_fn() { } hash_eq_fn(const Eq_Fn& r_eq_fn) : Eq_Fn(r_eq_fn) { } bool operator()(key_const_reference r_lhs_key, key_const_reference r_rhs_key) const { return eq_fn_base::operator()(r_lhs_key, r_rhs_key); } void swap(const hash_eq_fn& other) { std::swap((Eq_Fn&)(*this), (Eq_Fn&)other); } }; /// Specialization 2 - The client requests that hash values be stored. template struct hash_eq_fn : public Eq_Fn { typedef typename _Alloc::size_type size_type; typedef Eq_Fn eq_fn_base; typedef typename _Alloc::template rebind::other key_allocator; typedef typename key_allocator::const_reference key_const_reference; hash_eq_fn() { } hash_eq_fn(const Eq_Fn& r_eq_fn) : Eq_Fn(r_eq_fn) { } bool operator()(key_const_reference r_lhs_key, size_type lhs_hash, key_const_reference r_rhs_key, size_type rhs_hash) const { _GLIBCXX_DEBUG_ASSERT(!eq_fn_base::operator()(r_lhs_key, r_rhs_key) || lhs_hash == rhs_hash); return (lhs_hash == rhs_hash && eq_fn_base::operator()(r_lhs_key, r_rhs_key)); } void swap(const hash_eq_fn& other) { std::swap((Eq_Fn&)(*this), (Eq_Fn&)(other)); } }; } // namespace detail } // namespace __gnu_pbds #endif PK!57H8/ext/pb_ds/detail/gp_hash_table_map_/constructor_destructor_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/constructor_destructor_fn_imps.hpp * Contains implementations of gp_ht_map_'s constructors, destructor, * and related functions. */ PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::entry_allocator PB_DS_CLASS_C_DEC::s_entry_allocator; PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: copy_from_range(It first_it, It last_it) { while (first_it != last_it) insert(*(first_it++)); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_GP_HASH_NAME() : ranged_probe_fn_base(resize_base::get_nearest_larger_size(1)), m_num_e(resize_base::get_nearest_larger_size(1)), m_num_used_e(0), m_entries(s_entry_allocator.allocate(m_num_e)) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_GP_HASH_NAME(const Hash_Fn& r_hash_fn) : ranged_probe_fn_base(resize_base::get_nearest_larger_size(1), r_hash_fn), m_num_e(resize_base::get_nearest_larger_size(1)), m_num_used_e(0), m_entries(s_entry_allocator.allocate(m_num_e)) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_GP_HASH_NAME(const Hash_Fn& r_hash_fn, const Eq_Fn& r_eq_fn) : hash_eq_fn_base(r_eq_fn), ranged_probe_fn_base(resize_base::get_nearest_larger_size(1), r_hash_fn), m_num_e(resize_base::get_nearest_larger_size(1)), m_num_used_e(0), m_entries(s_entry_allocator.allocate(m_num_e)) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_GP_HASH_NAME(const Hash_Fn& r_hash_fn, const Eq_Fn& r_eq_fn, const Comb_Probe_Fn& r_comb_hash_fn) : hash_eq_fn_base(r_eq_fn), ranged_probe_fn_base(resize_base::get_nearest_larger_size(1), r_hash_fn, r_comb_hash_fn), m_num_e(resize_base::get_nearest_larger_size(1)), m_num_used_e(0), m_entries(s_entry_allocator.allocate(m_num_e)) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_GP_HASH_NAME(const Hash_Fn& r_hash_fn, const Eq_Fn& r_eq_fn, const Comb_Probe_Fn& comb_hash_fn, const Probe_Fn& prober) : hash_eq_fn_base(r_eq_fn), ranged_probe_fn_base(resize_base::get_nearest_larger_size(1), r_hash_fn, comb_hash_fn, prober), m_num_e(resize_base::get_nearest_larger_size(1)), m_num_used_e(0), m_entries(s_entry_allocator.allocate(m_num_e)) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_GP_HASH_NAME(const Hash_Fn& r_hash_fn, const Eq_Fn& r_eq_fn, const Comb_Probe_Fn& comb_hash_fn, const Probe_Fn& prober, const Resize_Policy& r_resize_policy) : hash_eq_fn_base(r_eq_fn), resize_base(r_resize_policy), ranged_probe_fn_base(resize_base::get_nearest_larger_size(1), r_hash_fn, comb_hash_fn, prober), m_num_e(resize_base::get_nearest_larger_size(1)), m_num_used_e(0), m_entries(s_entry_allocator.allocate(m_num_e)) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_GP_HASH_NAME(const PB_DS_CLASS_C_DEC& other) : #ifdef _GLIBCXX_DEBUG debug_base(other), #endif hash_eq_fn_base(other), resize_base(other), ranged_probe_fn_base(other), m_num_e(other.m_num_e), m_num_used_e(other.m_num_used_e), m_entries(s_entry_allocator.allocate(m_num_e)) { for (size_type i = 0; i < m_num_e; ++i) m_entries[i].m_stat = (entry_status)empty_entry_status; __try { for (size_type i = 0; i < m_num_e; ++i) { m_entries[i].m_stat = other.m_entries[i].m_stat; if (m_entries[i].m_stat == valid_entry_status) new (m_entries + i) entry(other.m_entries[i]); } } __catch(...) { deallocate_all(); __throw_exception_again; } PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~PB_DS_GP_HASH_NAME() { deallocate_all(); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) std::swap(m_num_e, other.m_num_e); std::swap(m_num_used_e, other.m_num_used_e); std::swap(m_entries, other.m_entries); ranged_probe_fn_base::swap(other); hash_eq_fn_base::swap(other); resize_base::swap(other); _GLIBCXX_DEBUG_ONLY(debug_base::swap(other)); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: deallocate_all() { clear(); erase_all_valid_entries(m_entries, m_num_e); s_entry_allocator.deallocate(m_entries, m_num_e); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: erase_all_valid_entries(entry_array a_entries_resized, size_type len) { for (size_type pos = 0; pos < len; ++pos) { entry_pointer p_e = &a_entries_resized[pos]; if (p_e->m_stat == valid_entry_status) p_e->m_value.~value_type(); } } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: initialize() { Resize_Policy::notify_resized(m_num_e); Resize_Policy::notify_cleared(); ranged_probe_fn_base::notify_resized(m_num_e); for (size_type i = 0; i < m_num_e; ++i) m_entries[i].m_stat = empty_entry_status; } PK!CV8/ext/pb_ds/detail/gp_hash_table_map_/constructor_destructor_no_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/constructor_destructor_no_store_hash_fn_imps.hpp * Contains implementations of gp_ht_map_'s constructors, destructor, * and related functions. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: constructor_insert_new_imp(mapped_const_reference r_val, size_type pos, false_type) { _GLIBCXX_DEBUG_ASSERT(m_entries[pos].m_stat != valid_entry_status)k; entry* const p_e = m_entries + pos; new (&p_e->m_value) mapped_value_type(r_val); p_e->m_stat = valid_entry_status; _GLIBCXX_DEBUG_ONLY(debug_base::insert_new(p_e->m_value.first);) } PK!!S8/ext/pb_ds/detail/gp_hash_table_map_/constructor_destructor_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/constructor_destructor_store_hash_fn_imps.hpp * Contains implementations of gp_ht_map_'s constructors, destructor, * and related functions. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: constructor_insert_new_imp(mapped_const_reference r_val, size_type pos, true_type) { _GLIBCXX_DEBUG_ASSERT(m_entries[pos].m_stat != valid_entry_status); entry* const p_e = m_entries + pos; new (&p_e->m_value) mapped_value_type(r_val); p_e->m_hash = ranged_probe_fn_base::operator()(PB_DS_V2F(r_val)).second; p_e->m_stat = valid_entry_status; _GLIBCXX_DEBUG_ONLY(debug_base::insert_new(p_e->m_value.first);) } PK!P߂~~78/ext/pb_ds/detail/gp_hash_table_map_/debug_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/debug_fn_imps.hpp * Contains implementations of gp_ht_map_'s debug-mode functions. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { debug_base::check_size(m_num_used_e, __file, __line); assert_entry_array_valid(m_entries, traits_base::m_store_extra_indicator, __file, __line); } #include #include #endif PK!m E8/ext/pb_ds/detail/gp_hash_table_map_/debug_no_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/debug_no_store_hash_fn_imps.hpp * Contains implementations of gp_ht_map_'s debug-mode functions. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_entry_array_valid(const entry_array a_entries, false_type, const char* __file, int __line) const { size_type iterated_num_used_e = 0; for (size_type pos = 0; pos < m_num_e; ++pos) { const_entry_pointer p_e = &a_entries[pos]; switch(p_e->m_stat) { case empty_entry_status: case erased_entry_status: break; case valid_entry_status: { key_const_reference r_key = PB_DS_V2F(p_e->m_value); debug_base::check_key_exists(r_key, __file, __line); ++iterated_num_used_e; break; } default: PB_DS_DEBUG_VERIFY(0); }; } PB_DS_DEBUG_VERIFY(iterated_num_used_e == m_num_used_e); } #endif PK!ޝU U B8/ext/pb_ds/detail/gp_hash_table_map_/debug_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/debug_store_hash_fn_imps.hpp * Contains implementations of gp_ht_map_'s debug-mode functions. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_entry_array_valid(const entry_array a_entries, true_type, const char* __file, int __line) const { size_type iterated_num_used_e = 0; for (size_type pos = 0; pos < m_num_e; ++pos) { const_entry_pointer p_e =& a_entries[pos]; switch(p_e->m_stat) { case empty_entry_status: case erased_entry_status: break; case valid_entry_status: { key_const_reference r_key = PB_DS_V2F(p_e->m_value); debug_base::check_key_exists(r_key, __file, __line); const comp_hash pos_hash_pair = ranged_probe_fn_base::operator()(r_key); PB_DS_DEBUG_VERIFY(p_e->m_hash == pos_hash_pair.second); ++iterated_num_used_e; break; } default: PB_DS_DEBUG_VERIFY(0); }; } PB_DS_DEBUG_VERIFY(iterated_num_used_e == m_num_used_e); } #endif PK![ 78/ext/pb_ds/detail/gp_hash_table_map_/erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/erase_fn_imps.hpp * Contains implementations of gp_ht_map_'s erase related functions. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: erase_entry(entry_pointer p_e) { _GLIBCXX_DEBUG_ASSERT(p_e->m_stat = valid_entry_status); _GLIBCXX_DEBUG_ONLY(debug_base::erase_existing(PB_DS_V2F(p_e->m_value));) p_e->m_value.~value_type(); p_e->m_stat = erased_entry_status; _GLIBCXX_DEBUG_ASSERT(m_num_used_e > 0); resize_base::notify_erased(--m_num_used_e); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear() { for (size_type pos = 0; pos < m_num_e; ++pos) { entry_pointer p_e = &m_entries[pos]; if (p_e->m_stat == valid_entry_status) erase_entry(p_e); } do_resize_if_needed_no_throw(); resize_base::notify_cleared(); } PB_DS_CLASS_T_DEC template inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: erase_if(Pred pred) { PB_DS_ASSERT_VALID((*this)) size_type num_ersd = 0; for (size_type pos = 0; pos < m_num_e; ++pos) { entry_pointer p_e = &m_entries[pos]; if (p_e->m_stat == valid_entry_status) if (pred(p_e->m_value)) { ++num_ersd; erase_entry(p_e); } } do_resize_if_needed_no_throw(); PB_DS_ASSERT_VALID((*this)) return num_ersd; } PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: erase(key_const_reference r_key) { return erase_imp(r_key, traits_base::m_store_extra_indicator); } #include #include PK!E E E8/ext/pb_ds/detail/gp_hash_table_map_/erase_no_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/erase_no_store_hash_fn_imps.hpp * Contains implementations of gp_ht_map_'s erase related functions, * when the hash value is not stored. */ PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: erase_imp(key_const_reference r_key, false_type) { PB_DS_ASSERT_VALID((*this)) size_type hash = ranged_probe_fn_base::operator()(r_key); size_type i; resize_base::notify_erase_search_start(); for (i = 0; i < m_num_e; ++i) { const size_type pos = ranged_probe_fn_base::operator()(r_key, hash, i); entry* const p_e = m_entries + pos; switch(p_e->m_stat) { case empty_entry_status: { resize_base::notify_erase_search_end(); PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return false; } break; case valid_entry_status: if (hash_eq_fn_base::operator()(PB_DS_V2F(p_e->m_value), r_key)) { resize_base::notify_erase_search_end(); erase_entry(p_e); do_resize_if_needed_no_throw(); return true; } break; case erased_entry_status: break; default: _GLIBCXX_DEBUG_ASSERT(0); }; resize_base::notify_erase_search_collision(); } resize_base::notify_erase_search_end(); return false; } PK!;|g g B8/ext/pb_ds/detail/gp_hash_table_map_/erase_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/erase_store_hash_fn_imps.hpp * Contains implementations of gp_ht_map_'s erase related functions, * when the hash value is stored. */ PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: erase_imp(key_const_reference r_key, true_type) { const comp_hash pos_hash_pair = ranged_probe_fn_base::operator()(r_key); size_type i; resize_base::notify_erase_search_start(); for (i = 0; i < m_num_e; ++i) { const size_type pos = ranged_probe_fn_base::operator()(r_key, pos_hash_pair.second, i); entry* const p_e = m_entries + pos; switch(p_e->m_stat) { case empty_entry_status: { resize_base::notify_erase_search_end(); PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return false; } break; case valid_entry_status: if (hash_eq_fn_base::operator()(PB_DS_V2F(p_e->m_value), p_e->m_hash, r_key, pos_hash_pair.second)) { resize_base::notify_erase_search_end(); erase_entry(p_e); do_resize_if_needed_no_throw(); return true; } break; case erased_entry_status: break; default: _GLIBCXX_DEBUG_ASSERT(0); }; resize_base::notify_erase_search_collision(); } resize_base::notify_erase_search_end(); return false; } PK!H09 68/ext/pb_ds/detail/gp_hash_table_map_/find_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/find_fn_imps.hpp * Contains implementations of gp_ht_map_'s find related functions. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: find(key_const_reference r_key) { PB_DS_ASSERT_VALID((*this)) return find_key_pointer(r_key, traits_base::m_store_extra_indicator); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_const_iterator PB_DS_CLASS_C_DEC:: find(key_const_reference r_key) const { PB_DS_ASSERT_VALID((*this)) return const_cast(*this).find_key_pointer(r_key, traits_base::m_store_extra_indicator); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: find_end() { return 0; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_const_iterator PB_DS_CLASS_C_DEC:: find_end() const { return 0; } PK! ńD8/ext/pb_ds/detail/gp_hash_table_map_/find_no_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/find_no_store_hash_fn_imps.hpp * Contains implementations of gp_ht_map_'s find related functions, * when the hash value is not stored. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::pointer PB_DS_CLASS_C_DEC:: find_key_pointer(key_const_reference r_key, false_type) PK!$A8/ext/pb_ds/detail/gp_hash_table_map_/find_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/find_store_hash_fn_imps.hpp * Contains implementations of gp_ht_map_'s insert related functions, * when the hash value is stored. */ PK!vjEOO48/ext/pb_ds/detail/gp_hash_table_map_/gp_ht_map_.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/gp_ht_map_.hpp * Contains an implementation class for general probing hash. */ #include #include #include #include #include #include #ifdef PB_DS_HT_MAP_TRACE_ #include #endif #ifdef _GLIBCXX_DEBUG #include #endif #include namespace __gnu_pbds { namespace detail { #ifdef PB_DS_DATA_TRUE_INDICATOR #define PB_DS_GP_HASH_NAME gp_ht_map #endif #ifdef PB_DS_DATA_FALSE_INDICATOR #define PB_DS_GP_HASH_NAME gp_ht_set #endif #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ PB_DS_GP_HASH_NAME #define PB_DS_HASH_EQ_FN_C_DEC \ hash_eq_fn #define PB_DS_RANGED_PROBE_FN_C_DEC \ ranged_probe_fn #define PB_DS_GP_HASH_TRAITS_BASE \ types_traits #ifdef _GLIBCXX_DEBUG #define PB_DS_DEBUG_MAP_BASE_C_DEC \ debug_map_base::other::const_reference> #endif /** * A general-probing hash-based container. * * * @ingroup hash-detail * * @tparam Key Key type. * * @tparam Mapped Map type. * * @tparam Hash_Fn Hashing functor. * Default is __gnu_cxx::hash. * * @tparam Eq_Fn Equal functor. * Default std::equal_to * * @tparam _Alloc Allocator type. * * @tparam Store_Hash If key type stores extra metadata. * Defaults to false. * * @tparam Comb_Probe_Fn Combining probe functor. * If Hash_Fn is not null_type, then this * is the ranged-probe functor; otherwise, * this is the range-hashing functor. * XXX See Design::Hash-Based Containers::Hash Policies. * Default direct_mask_range_hashing. * * @tparam Probe_Fn Probe functor. * Defaults to linear_probe_fn, * also quadratic_probe_fn. * * @tparam Resize_Policy Resizes hash. * Defaults to hash_standard_resize_policy, * using hash_exponential_size_policy and * hash_load_check_resize_trigger. * * * Bases are: detail::hash_eq_fn, Resize_Policy, detail::ranged_probe_fn, * detail::types_traits. (Optional: detail::debug_map_base.) */ template class PB_DS_GP_HASH_NAME : #ifdef _GLIBCXX_DEBUG protected PB_DS_DEBUG_MAP_BASE_C_DEC, #endif public PB_DS_HASH_EQ_FN_C_DEC, public Resize_Policy, public PB_DS_RANGED_PROBE_FN_C_DEC, public PB_DS_GP_HASH_TRAITS_BASE { private: typedef PB_DS_GP_HASH_TRAITS_BASE traits_base; typedef typename traits_base::value_type value_type_; typedef typename traits_base::pointer pointer_; typedef typename traits_base::const_pointer const_pointer_; typedef typename traits_base::reference reference_; typedef typename traits_base::const_reference const_reference_; typedef typename traits_base::comp_hash comp_hash; enum entry_status { empty_entry_status, valid_entry_status, erased_entry_status } __attribute__ ((__packed__)); struct entry : public traits_base::stored_data_type { entry_status m_stat; }; typedef typename _Alloc::template rebind::other entry_allocator; typedef typename entry_allocator::pointer entry_pointer; typedef typename entry_allocator::const_pointer const_entry_pointer; typedef typename entry_allocator::reference entry_reference; typedef typename entry_allocator::const_reference const_entry_reference; typedef typename entry_allocator::pointer entry_array; typedef PB_DS_RANGED_PROBE_FN_C_DEC ranged_probe_fn_base; #ifdef _GLIBCXX_DEBUG typedef PB_DS_DEBUG_MAP_BASE_C_DEC debug_base; #endif typedef PB_DS_HASH_EQ_FN_C_DEC hash_eq_fn_base; typedef Resize_Policy resize_base; #define PB_DS_GEN_POS typename _Alloc::size_type #include #include #include #include #undef PB_DS_GEN_POS public: typedef _Alloc allocator_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef Hash_Fn hash_fn; typedef Eq_Fn eq_fn; typedef Probe_Fn probe_fn; typedef Comb_Probe_Fn comb_probe_fn; typedef Resize_Policy resize_policy; /// Value stores hash, true or false. enum { store_hash = Store_Hash }; typedef typename traits_base::key_type key_type; typedef typename traits_base::key_pointer key_pointer; typedef typename traits_base::key_const_pointer key_const_pointer; typedef typename traits_base::key_reference key_reference; typedef typename traits_base::key_const_reference key_const_reference; typedef typename traits_base::mapped_type mapped_type; typedef typename traits_base::mapped_pointer mapped_pointer; typedef typename traits_base::mapped_const_pointer mapped_const_pointer; typedef typename traits_base::mapped_reference mapped_reference; typedef typename traits_base::mapped_const_reference mapped_const_reference; typedef typename traits_base::value_type value_type; typedef typename traits_base::pointer pointer; typedef typename traits_base::const_pointer const_pointer; typedef typename traits_base::reference reference; typedef typename traits_base::const_reference const_reference; #ifdef PB_DS_DATA_TRUE_INDICATOR typedef point_iterator_ point_iterator; #endif #ifdef PB_DS_DATA_FALSE_INDICATOR typedef point_const_iterator_ point_iterator; #endif typedef point_const_iterator_ point_const_iterator; #ifdef PB_DS_DATA_TRUE_INDICATOR typedef iterator_ iterator; #endif #ifdef PB_DS_DATA_FALSE_INDICATOR typedef const_iterator_ iterator; #endif typedef const_iterator_ const_iterator; PB_DS_GP_HASH_NAME(); PB_DS_GP_HASH_NAME(const PB_DS_CLASS_C_DEC&); PB_DS_GP_HASH_NAME(const Hash_Fn&); PB_DS_GP_HASH_NAME(const Hash_Fn&, const Eq_Fn&); PB_DS_GP_HASH_NAME(const Hash_Fn&, const Eq_Fn&, const Comb_Probe_Fn&); PB_DS_GP_HASH_NAME(const Hash_Fn&, const Eq_Fn&, const Comb_Probe_Fn&, const Probe_Fn&); PB_DS_GP_HASH_NAME(const Hash_Fn&, const Eq_Fn&, const Comb_Probe_Fn&, const Probe_Fn&, const Resize_Policy&); template void copy_from_range(It, It); virtual ~PB_DS_GP_HASH_NAME(); void swap(PB_DS_CLASS_C_DEC&); inline size_type size() const; inline size_type max_size() const; /// True if size() == 0. inline bool empty() const; /// Return current hash_fn. Hash_Fn& get_hash_fn(); /// Return current const hash_fn. const Hash_Fn& get_hash_fn() const; /// Return current eq_fn. Eq_Fn& get_eq_fn(); /// Return current const eq_fn. const Eq_Fn& get_eq_fn() const; /// Return current probe_fn. Probe_Fn& get_probe_fn(); /// Return current const probe_fn. const Probe_Fn& get_probe_fn() const; /// Return current comb_probe_fn. Comb_Probe_Fn& get_comb_probe_fn(); /// Return current const comb_probe_fn. const Comb_Probe_Fn& get_comb_probe_fn() const; /// Return current resize_policy. Resize_Policy& get_resize_policy(); /// Return current const resize_policy. const Resize_Policy& get_resize_policy() const; inline std::pair insert(const_reference r_val) { _GLIBCXX_DEBUG_ONLY(PB_DS_CLASS_C_DEC::assert_valid(__FILE__, __LINE__);) return insert_imp(r_val, traits_base::m_store_extra_indicator); } inline mapped_reference operator[](key_const_reference r_key) { #ifdef PB_DS_DATA_TRUE_INDICATOR return subscript_imp(r_key, traits_base::m_store_extra_indicator); #else insert(r_key); return traits_base::s_null_type; #endif } inline point_iterator find(key_const_reference); inline point_const_iterator find(key_const_reference) const; inline point_iterator find_end(); inline point_const_iterator find_end() const; inline bool erase(key_const_reference); template inline size_type erase_if(Pred); void clear(); inline iterator begin(); inline const_iterator begin() const; inline iterator end(); inline const_iterator end() const; #ifdef _GLIBCXX_DEBUG void assert_valid(const char*, int) const; #endif #ifdef PB_DS_HT_MAP_TRACE_ void trace() const; #endif private: #ifdef PB_DS_DATA_TRUE_INDICATOR friend class iterator_; #endif friend class const_iterator_; void deallocate_all(); void initialize(); void erase_all_valid_entries(entry_array, size_type); inline bool do_resize_if_needed(); inline void do_resize_if_needed_no_throw(); void resize_imp(size_type); virtual void do_resize(size_type); void resize_imp(entry_array, size_type); inline void resize_imp_reassign(entry_pointer, entry_array, false_type); inline void resize_imp_reassign(entry_pointer, entry_array, true_type); inline size_type find_ins_pos(key_const_reference, false_type); inline comp_hash find_ins_pos(key_const_reference, true_type); inline std::pair insert_imp(const_reference, false_type); inline std::pair insert_imp(const_reference, true_type); inline pointer insert_new_imp(const_reference r_val, size_type pos) { _GLIBCXX_DEBUG_ASSERT(m_entries[pos].m_stat != valid_entry_status); if (do_resize_if_needed()) pos = find_ins_pos(PB_DS_V2F(r_val), traits_base::m_store_extra_indicator); _GLIBCXX_DEBUG_ASSERT(m_entries[pos].m_stat != valid_entry_status); entry* const p_e = m_entries + pos; new (&p_e->m_value) value_type(r_val); p_e->m_stat = valid_entry_status; resize_base::notify_inserted(++m_num_used_e); _GLIBCXX_DEBUG_ONLY(debug_base::insert_new(PB_DS_V2F(p_e->m_value));) _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) return &p_e->m_value; } inline pointer insert_new_imp(const_reference r_val, comp_hash& r_pos_hash_pair) { _GLIBCXX_DEBUG_ASSERT(m_entries[r_pos_hash_pair.first].m_stat != valid_entry_status); if (do_resize_if_needed()) r_pos_hash_pair = find_ins_pos(PB_DS_V2F(r_val), traits_base::m_store_extra_indicator); _GLIBCXX_DEBUG_ASSERT(m_entries[r_pos_hash_pair.first].m_stat != valid_entry_status); entry* const p_e = m_entries + r_pos_hash_pair.first; new (&p_e->m_value) value_type(r_val); p_e->m_hash = r_pos_hash_pair.second; p_e->m_stat = valid_entry_status; resize_base::notify_inserted(++m_num_used_e); _GLIBCXX_DEBUG_ONLY(debug_base::insert_new(PB_DS_V2F(p_e->m_value));) _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) return &p_e->m_value; } #ifdef PB_DS_DATA_TRUE_INDICATOR inline mapped_reference subscript_imp(key_const_reference key, false_type) { _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) const size_type pos = find_ins_pos(key, traits_base::m_store_extra_indicator); entry_pointer p_e = &m_entries[pos]; if (p_e->m_stat != valid_entry_status) return insert_new_imp(value_type(key, mapped_type()), pos)->second; PB_DS_CHECK_KEY_EXISTS(key) return p_e->m_value.second; } inline mapped_reference subscript_imp(key_const_reference key, true_type) { _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) comp_hash pos_hash_pair = find_ins_pos(key, traits_base::m_store_extra_indicator); if (m_entries[pos_hash_pair.first].m_stat != valid_entry_status) return insert_new_imp(value_type(key, mapped_type()), pos_hash_pair)->second; PB_DS_CHECK_KEY_EXISTS(key) return (m_entries + pos_hash_pair.first)->m_value.second; } #endif inline pointer find_key_pointer(key_const_reference key, false_type) { const size_type hash = ranged_probe_fn_base::operator()(key); resize_base::notify_find_search_start(); // Loop until entry is found or until all possible entries accessed. for (size_type i = 0; i < m_num_e; ++i) { const size_type pos = ranged_probe_fn_base::operator()(key, hash, i); entry* const p_e = m_entries + pos; switch (p_e->m_stat) { case empty_entry_status: { resize_base::notify_find_search_end(); PB_DS_CHECK_KEY_DOES_NOT_EXIST(key) return 0; } break; case valid_entry_status: if (hash_eq_fn_base::operator()(PB_DS_V2F(p_e->m_value), key)) { resize_base::notify_find_search_end(); PB_DS_CHECK_KEY_EXISTS(key) return pointer(&p_e->m_value); } break; case erased_entry_status: break; default: _GLIBCXX_DEBUG_ASSERT(0); }; resize_base::notify_find_search_collision(); } PB_DS_CHECK_KEY_DOES_NOT_EXIST(key) resize_base::notify_find_search_end(); return 0; } inline pointer find_key_pointer(key_const_reference key, true_type) { comp_hash pos_hash_pair = ranged_probe_fn_base::operator()(key); resize_base::notify_find_search_start(); // Loop until entry is found or until all possible entries accessed. for (size_type i = 0; i < m_num_e; ++i) { const size_type pos = ranged_probe_fn_base::operator()(key, pos_hash_pair.second, i); entry* const p_e = m_entries + pos; switch(p_e->m_stat) { case empty_entry_status: { resize_base::notify_find_search_end(); PB_DS_CHECK_KEY_DOES_NOT_EXIST(key) return 0; } break; case valid_entry_status: if (hash_eq_fn_base::operator()(PB_DS_V2F(p_e->m_value), p_e->m_hash, key, pos_hash_pair.second)) { resize_base::notify_find_search_end(); PB_DS_CHECK_KEY_EXISTS(key) return pointer(&p_e->m_value); } break; case erased_entry_status: break; default: _GLIBCXX_DEBUG_ASSERT(0); }; resize_base::notify_find_search_collision(); } PB_DS_CHECK_KEY_DOES_NOT_EXIST(key) resize_base::notify_find_search_end(); return 0; } inline bool erase_imp(key_const_reference, true_type); inline bool erase_imp(key_const_reference, false_type); inline void erase_entry(entry_pointer); #ifdef PB_DS_DATA_TRUE_INDICATOR void inc_it_state(pointer& r_p_value, size_type& r_pos) const { inc_it_state((mapped_const_pointer& )r_p_value, r_pos); } #endif void inc_it_state(const_pointer& r_p_value, size_type& r_pos) const { _GLIBCXX_DEBUG_ASSERT(r_p_value != 0); for (++r_pos; r_pos < m_num_e; ++r_pos) { const_entry_pointer p_e =& m_entries[r_pos]; if (p_e->m_stat == valid_entry_status) { r_p_value =& p_e->m_value; return; } } r_p_value = 0; } void get_start_it_state(const_pointer& r_p_value, size_type& r_pos) const { for (r_pos = 0; r_pos < m_num_e; ++r_pos) { const_entry_pointer p_e = &m_entries[r_pos]; if (p_e->m_stat == valid_entry_status) { r_p_value = &p_e->m_value; return; } } r_p_value = 0; } void get_start_it_state(pointer& r_p_value, size_type& r_pos) { for (r_pos = 0; r_pos < m_num_e; ++r_pos) { entry_pointer p_e = &m_entries[r_pos]; if (p_e->m_stat == valid_entry_status) { r_p_value = &p_e->m_value; return; } } r_p_value = 0; } #ifdef _GLIBCXX_DEBUG void assert_entry_array_valid(const entry_array, false_type, const char*, int) const; void assert_entry_array_valid(const entry_array, true_type, const char*, int) const; #endif static entry_allocator s_entry_allocator; static iterator s_end_it; static const_iterator s_const_end_it; size_type m_num_e; size_type m_num_used_e; entry_pointer m_entries; enum { store_hash_ok = !Store_Hash || !is_same::value }; PB_DS_STATIC_ASSERT(sth, store_hash_ok); }; #include #include #include #include #include #include #include #include #include #include #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #undef PB_DS_HASH_EQ_FN_C_DEC #undef PB_DS_RANGED_PROBE_FN_C_DEC #undef PB_DS_GP_HASH_TRAITS_BASE #undef PB_DS_DEBUG_MAP_BASE_C_DEC #undef PB_DS_GP_HASH_NAME } // namespace detail } // namespace __gnu_pbds PK!:<<68/ext/pb_ds/detail/gp_hash_table_map_/info_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/info_fn_imps.hpp * Contains implementations of gp_ht_map_'s entire container info related * functions. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: size() const { return m_num_used_e; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: max_size() const { return s_entry_allocator.max_size(); } PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: empty() const { return (size() == 0); } PK!Fhh88/ext/pb_ds/detail/gp_hash_table_map_/insert_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/insert_fn_imps.hpp * Contains implementations of gp_ht_map_'s insert related functions. */ #include #include PK!!F8/ext/pb_ds/detail/gp_hash_table_map_/insert_no_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/insert_no_store_hash_fn_imps.hpp * Contains implementations of gp_ht_map_'s insert related functions, * when the hash value is not stored. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: find_ins_pos(key_const_reference r_key, false_type) { size_type hash = ranged_probe_fn_base::operator()(r_key); size_type i; /* The insertion position is initted to a non-legal value to indicate * that it has not been initted yet. */ size_type ins_pos = m_num_e; resize_base::notify_insert_search_start(); for (i = 0; i < m_num_e; ++i) { const size_type pos = ranged_probe_fn_base::operator()(r_key, hash, i); _GLIBCXX_DEBUG_ASSERT(pos < m_num_e); entry* const p_e = m_entries + pos; switch(p_e->m_stat) { case empty_entry_status: { resize_base::notify_insert_search_end(); PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return (ins_pos == m_num_e) ? pos : ins_pos; } break; case erased_entry_status: if (ins_pos == m_num_e) ins_pos = pos; break; case valid_entry_status: if (hash_eq_fn_base::operator()(PB_DS_V2F(p_e->m_value), r_key)) { resize_base::notify_insert_search_end(); PB_DS_CHECK_KEY_EXISTS(r_key) return pos; } break; default: _GLIBCXX_DEBUG_ASSERT(0); }; resize_base::notify_insert_search_collision(); } resize_base::notify_insert_search_end(); if (ins_pos == m_num_e) __throw_insert_error(); return ins_pos; } PB_DS_CLASS_T_DEC inline std::pair PB_DS_CLASS_C_DEC:: insert_imp(const_reference r_val, false_type) { key_const_reference r_key = PB_DS_V2F(r_val); const size_type pos = find_ins_pos(r_key, traits_base::m_store_extra_indicator); if (m_entries[pos].m_stat == valid_entry_status) { PB_DS_CHECK_KEY_EXISTS(r_key) return std::make_pair(&(m_entries + pos)->m_value, false); } PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return std::make_pair(insert_new_imp(r_val, pos), true); } PK!pC8/ext/pb_ds/detail/gp_hash_table_map_/insert_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/insert_store_hash_fn_imps.hpp * Contains implementations of gp_ht_map_'s find related functions, * when the hash value is stored. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::comp_hash PB_DS_CLASS_C_DEC:: find_ins_pos(key_const_reference r_key, true_type) { PB_DS_ASSERT_VALID((*this)) comp_hash pos_hash_pair = ranged_probe_fn_base::operator()(r_key); size_type i; /* The insertion position is initted to a non-legal value to indicate * that it has not been initted yet. */ size_type ins_pos = m_num_e; resize_base::notify_insert_search_start(); for (i = 0; i < m_num_e; ++i) { const size_type pos = ranged_probe_fn_base::operator()(r_key, pos_hash_pair.second, i); entry* const p_e = m_entries + pos; switch(p_e->m_stat) { case empty_entry_status: { resize_base::notify_insert_search_end(); PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return ((ins_pos == m_num_e) ? std::make_pair(pos, pos_hash_pair.second) : std::make_pair(ins_pos, pos_hash_pair.second)); } break; case erased_entry_status: if (ins_pos == m_num_e) ins_pos = pos; break; case valid_entry_status: if (hash_eq_fn_base::operator()(PB_DS_V2F(p_e->m_value), p_e->m_hash, r_key, pos_hash_pair.second)) { resize_base::notify_insert_search_end(); PB_DS_CHECK_KEY_EXISTS(r_key) return std::make_pair(pos, pos_hash_pair.second); } break; default: _GLIBCXX_DEBUG_ASSERT(0); }; resize_base::notify_insert_search_collision(); } resize_base::notify_insert_search_end(); if (ins_pos == m_num_e) __throw_insert_error(); return std::make_pair(ins_pos, pos_hash_pair.second); } PB_DS_CLASS_T_DEC inline std::pair PB_DS_CLASS_C_DEC:: insert_imp(const_reference r_val, true_type) { key_const_reference r_key = PB_DS_V2F(r_val); comp_hash pos_hash_pair = find_ins_pos(r_key, traits_base::m_store_extra_indicator); _GLIBCXX_DEBUG_ASSERT(pos_hash_pair.first < m_num_e); entry_pointer p_e =& m_entries[pos_hash_pair.first]; if (p_e->m_stat == valid_entry_status) { PB_DS_CHECK_KEY_EXISTS(r_key) return std::make_pair(&p_e->m_value, false); } PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return std::make_pair(insert_new_imp(r_val, pos_hash_pair), true); } PK!ä; ; :8/ext/pb_ds/detail/gp_hash_table_map_/iterator_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/iterator_fn_imps.hpp * Contains implementations of gp_ht_map_'s iterators related functions, e.g., * begin(). */ PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC::s_end_it; PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC::s_const_end_it; PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: begin() { pointer_ p_value; size_type pos; get_start_it_state(p_value, pos); return iterator(p_value, pos, this); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: end() { return s_end_it; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: begin() const { const_pointer_ p_value; size_type pos; get_start_it_state(p_value, pos); return const_iterator(p_value, pos, this); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: end() const { return s_const_end_it; } PK!Od d ?8/ext/pb_ds/detail/gp_hash_table_map_/policy_access_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/policy_access_fn_imps.hpp * Contains implementations of gp_ht_map_'s policy agpess * functions. */ PB_DS_CLASS_T_DEC Hash_Fn& PB_DS_CLASS_C_DEC:: get_hash_fn() { return *this; } PB_DS_CLASS_T_DEC const Hash_Fn& PB_DS_CLASS_C_DEC:: get_hash_fn() const { return *this; } PB_DS_CLASS_T_DEC Eq_Fn& PB_DS_CLASS_C_DEC:: get_eq_fn() { return *this; } PB_DS_CLASS_T_DEC const Eq_Fn& PB_DS_CLASS_C_DEC:: get_eq_fn() const { return *this; } PB_DS_CLASS_T_DEC Probe_Fn& PB_DS_CLASS_C_DEC:: get_probe_fn() { return *this; } PB_DS_CLASS_T_DEC const Probe_Fn& PB_DS_CLASS_C_DEC:: get_probe_fn() const { return *this; } PB_DS_CLASS_T_DEC Comb_Probe_Fn& PB_DS_CLASS_C_DEC:: get_comb_probe_fn() { return *this; } PB_DS_CLASS_T_DEC const Comb_Probe_Fn& PB_DS_CLASS_C_DEC:: get_comb_probe_fn() const { return *this; } PB_DS_CLASS_T_DEC Resize_Policy& PB_DS_CLASS_C_DEC:: get_resize_policy() { return *this; } PB_DS_CLASS_T_DEC const Resize_Policy& PB_DS_CLASS_C_DEC:: get_resize_policy() const { return *this; } PK!C~==88/ext/pb_ds/detail/gp_hash_table_map_/resize_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/resize_fn_imps.hpp * Contains implementations of gp_ht_map_'s resize related functions. */ PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: do_resize_if_needed() { if (!resize_base::is_resize_needed()) return false; resize_imp(resize_base::get_new_size(m_num_e, m_num_used_e)); return true; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: do_resize(size_type n) { resize_imp(resize_base::get_nearest_larger_size(n)); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: do_resize_if_needed_no_throw() { if (!resize_base::is_resize_needed()) return; __try { resize_imp(resize_base::get_new_size(m_num_e, m_num_used_e)); } __catch(...) { } PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: resize_imp(size_type new_size) { #ifdef PB_DS_REGRESSION typename _Alloc::group_adjustor adjust(m_num_e); #endif if (new_size == m_num_e) return; PB_DS_ASSERT_VALID((*this)) const size_type old_size = m_num_e; entry_array a_entries_resized = 0; // Following line might throw an exception. a_entries_resized = s_entry_allocator.allocate(new_size); ranged_probe_fn_base::notify_resized(new_size); m_num_e = new_size; for (size_type i = 0; i < m_num_e; ++i) a_entries_resized[i].m_stat = empty_entry_status; __try { resize_imp(a_entries_resized, old_size); } __catch(...) { erase_all_valid_entries(a_entries_resized, new_size); m_num_e = old_size; s_entry_allocator.deallocate(a_entries_resized, new_size); ranged_probe_fn_base::notify_resized(old_size); __throw_exception_again; } // At this point no exceptions can be thrown. _GLIBCXX_DEBUG_ONLY(assert_entry_array_valid(a_entries_resized, traits_base::m_store_extra_indicator, __FILE__, __LINE__);) Resize_Policy::notify_resized(new_size); erase_all_valid_entries(m_entries, old_size); s_entry_allocator.deallocate(m_entries, old_size); m_entries = a_entries_resized; PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: resize_imp(entry_array a_entries_resized, size_type old_size) { for (size_type pos = 0; pos < old_size; ++pos) if (m_entries[pos].m_stat == valid_entry_status) resize_imp_reassign(m_entries + pos, a_entries_resized, traits_base::m_store_extra_indicator); } #include #include PK!A^: : F8/ext/pb_ds/detail/gp_hash_table_map_/resize_no_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/resize_no_store_hash_fn_imps.hpp * Contains implementations of gp_ht_map_'s resize related functions, when the * hash value is not stored. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: resize_imp_reassign(entry_pointer p_e, entry_array a_entries_resized, false_type) { key_const_reference r_key = PB_DS_V2F(p_e->m_value); size_type hash = ranged_probe_fn_base::operator()(r_key); size_type i; for (i = 0; i < m_num_e; ++i) { const size_type pos = ranged_probe_fn_base::operator()(r_key, hash, i); entry_pointer p_new_e = a_entries_resized + pos; switch(p_new_e->m_stat) { case empty_entry_status: new (&p_new_e->m_value) value_type(p_e->m_value); p_new_e->m_stat = valid_entry_status; return; case erased_entry_status: _GLIBCXX_DEBUG_ASSERT(0); break; case valid_entry_status: break; default: _GLIBCXX_DEBUG_ASSERT(0); }; } __throw_insert_error(); } PK!6'[ [ C8/ext/pb_ds/detail/gp_hash_table_map_/resize_store_hash_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/resize_store_hash_fn_imps.hpp * Contains implementations of gp_ht_map_'s resize related functions, when the * hash value is stored. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: resize_imp_reassign(entry_pointer p_e, entry_array a_entries_resized, true_type) { key_const_reference r_key = PB_DS_V2F(p_e->m_value); size_type hash = ranged_probe_fn_base::operator()(r_key, p_e->m_hash); size_type i; for (i = 0; i < m_num_e; ++i) { const size_type pos = ranged_probe_fn_base::operator()(r_key, hash, i); entry_pointer p_new_e = a_entries_resized + pos; switch(p_new_e->m_stat) { case empty_entry_status: new (&p_new_e->m_value) value_type(p_e->m_value); p_new_e->m_hash = hash; p_new_e->m_stat = valid_entry_status; return; case erased_entry_status: _GLIBCXX_DEBUG_ASSERT(0); break; case valid_entry_status: break; default: _GLIBCXX_DEBUG_ASSERT(0); }; } __throw_insert_error(); } PK!(x x 78/ext/pb_ds/detail/gp_hash_table_map_/trace_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file gp_hash_table_map_/trace_fn_imps.hpp * Contains implementations of gp_ht_map_'s trace-mode functions. */ #ifdef PB_DS_HT_MAP_TRACE_ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace() const { std::cerr << static_cast(m_num_e) << " " << static_cast(m_num_used_e) << std::endl; for (size_type i = 0; i < m_num_e; ++i) { std::cerr << static_cast(i) << " "; switch(m_entries[i].m_stat) { case empty_entry_status: std::cerr << ""; break; case erased_entry_status: std::cerr << ""; break; case valid_entry_status: std::cerr << PB_DS_V2F(m_entries[i].m_value); break; default: _GLIBCXX_DEBUG_ASSERT(0); }; std::cerr << std::endl; } } #endif // #ifdef PB_DS_HT_MAP_TRACE_ PK!xx88<8/ext/pb_ds/detail/hash_fn/direct_mask_range_hashing_imp.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file direct_mask_range_hashing_imp.hpp * Contains a range-hashing policy implementation */ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { mask_based_base::swap(other); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_resized(size_type size) { mask_based_base::notify_resized(size); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: operator()(size_type hash) const { return mask_based_base::range_hash(hash); } PK!VF ..;8/ext/pb_ds/detail/hash_fn/direct_mod_range_hashing_imp.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file direct_mod_range_hashing_imp.hpp * Contains a range-hashing policy implementation */ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { mod_based_base::swap(other); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_resized(size_type n) { mod_based_base::notify_resized(n); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: operator()(size_type hash) const { return mod_based_base::range_hash(hash); } PK!lyy28/ext/pb_ds/detail/hash_fn/linear_probe_fn_imp.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file linear_probe_fn_imp.hpp * Contains a probe policy implementation */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: operator()(size_type i) const { return (i); } PK! 78/ext/pb_ds/detail/hash_fn/mask_based_range_hashing.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file mask_based_range_hashing.hpp * Contains a range hashing policy base. */ #ifndef PB_DS_MASK_BASED_RANGE_HASHING_HPP #define PB_DS_MASK_BASED_RANGE_HASHING_HPP namespace __gnu_pbds { namespace detail { /// Range hashing policy. template class mask_based_range_hashing { protected: typedef Size_Type size_type; void swap(mask_based_range_hashing& other) { std::swap(m_mask, other.m_mask); } void notify_resized(size_type size); inline size_type range_hash(size_type hash) const { return size_type(hash & m_mask); } private: size_type m_mask; const static size_type s_num_bits_in_size_type; const static size_type s_highest_bit_1; }; template const typename mask_based_range_hashing::size_type mask_based_range_hashing::s_num_bits_in_size_type = sizeof(typename mask_based_range_hashing::size_type) << 3; template const typename mask_based_range_hashing::size_type mask_based_range_hashing::s_highest_bit_1 = static_cast::size_type>(1) << (s_num_bits_in_size_type - 1); template void mask_based_range_hashing:: notify_resized(size_type size) { size_type i = 0; while (size ^ s_highest_bit_1) { size <<= 1; ++i; } m_mask = 1; i += 2; while (i++ < s_num_bits_in_size_type) m_mask = (m_mask << 1) ^ 1; } } // namespace detail } // namespace __gnu_pbds #endif PK!xW~W W 68/ext/pb_ds/detail/hash_fn/mod_based_range_hashing.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file mod_based_range_hashing.hpp * Contains a range hashing policy base. */ #ifndef PB_DS_MOD_BASED_RANGE_HASHING_HPP #define PB_DS_MOD_BASED_RANGE_HASHING_HPP namespace __gnu_pbds { namespace detail { /// Mod based range hashing. template class mod_based_range_hashing { protected: typedef Size_Type size_type; void swap(mod_based_range_hashing& other) { std::swap(m_size, other.m_size); } void notify_resized(size_type s) { m_size = s; } inline size_type range_hash(size_type s) const { return s % m_size; } private: size_type m_size; }; } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_MOD_BASED_RANGE_HASHING_HPP PK!fч,8/ext/pb_ds/detail/hash_fn/probe_fn_base.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file probe_fn_base.hpp * Contains a probe policy base. */ #ifndef PB_DS_PROBE_FN_BASE_HPP #define PB_DS_PROBE_FN_BASE_HPP #include namespace __gnu_pbds { namespace detail { /// Probe functor base. template class probe_fn_base { protected: ~probe_fn_base() { } }; } // namespace detail } // namespace __gnu_pbds #endif PK!O58/ext/pb_ds/detail/hash_fn/quadratic_probe_fn_imp.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file quadratic_probe_fn_imp.hpp * Contains a probe policy implementation */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: operator()(size_type i) const { return (i* i); } PK!m~{){)-8/ext/pb_ds/detail/hash_fn/ranged_hash_fn.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file ranged_hash_fn.hpp * Contains a unified ranged hash functor, allowing the hash tables * to deal with a single class for ranged hashing. */ #ifndef PB_DS_RANGED_HASH_FN_HPP #define PB_DS_RANGED_HASH_FN_HPP #include #include namespace __gnu_pbds { namespace detail { /// Primary template. template class ranged_hash_fn; #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ ranged_hash_fn /** * Specialization 1 * The client supplies a hash function and a ranged hash function, * and requests that hash values not be stored. **/ template class ranged_hash_fn< Key, Hash_Fn, _Alloc, Comb_Hash_Fn, false> : public Hash_Fn, public Comb_Hash_Fn { protected: typedef typename _Alloc::size_type size_type; typedef Hash_Fn hash_fn_base; typedef Comb_Hash_Fn comb_hash_fn_base; typedef typename _Alloc::template rebind< Key>::other key_allocator; typedef typename key_allocator::const_reference key_const_reference; ranged_hash_fn(size_type); ranged_hash_fn(size_type, const Hash_Fn&); ranged_hash_fn(size_type, const Hash_Fn&, const Comb_Hash_Fn&); void swap(PB_DS_CLASS_C_DEC&); void notify_resized(size_type); inline size_type operator()(key_const_reference) const; }; PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_hash_fn(size_type size) { Comb_Hash_Fn::notify_resized(size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_hash_fn(size_type size, const Hash_Fn& r_hash_fn) : Hash_Fn(r_hash_fn) { Comb_Hash_Fn::notify_resized(size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_hash_fn(size_type size, const Hash_Fn& r_hash_fn, const Comb_Hash_Fn& r_comb_hash_fn) : Hash_Fn(r_hash_fn), Comb_Hash_Fn(r_comb_hash_fn) { comb_hash_fn_base::notify_resized(size); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { comb_hash_fn_base::swap(other); std::swap((Hash_Fn& )(*this), (Hash_Fn& )other); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_resized(size_type size) { comb_hash_fn_base::notify_resized(size); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: operator()(key_const_reference r_key) const { return (comb_hash_fn_base::operator()(hash_fn_base::operator()(r_key)));} #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ ranged_hash_fn /** * Specialization 2 * The client supplies a hash function and a ranged hash function, * and requests that hash values be stored. **/ template class ranged_hash_fn : public Hash_Fn, public Comb_Hash_Fn { protected: typedef typename _Alloc::size_type size_type; typedef std::pair comp_hash; typedef Hash_Fn hash_fn_base; typedef Comb_Hash_Fn comb_hash_fn_base; typedef typename _Alloc::template rebind::other key_allocator; typedef typename key_allocator::const_reference key_const_reference; ranged_hash_fn(size_type); ranged_hash_fn(size_type, const Hash_Fn&); ranged_hash_fn(size_type, const Hash_Fn&, const Comb_Hash_Fn&); void swap(PB_DS_CLASS_C_DEC&); void notify_resized(size_type); inline comp_hash operator()(key_const_reference) const; inline comp_hash operator()(key_const_reference, size_type) const; }; PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_hash_fn(size_type size) { Comb_Hash_Fn::notify_resized(size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_hash_fn(size_type size, const Hash_Fn& r_hash_fn) : Hash_Fn(r_hash_fn) { Comb_Hash_Fn::notify_resized(size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_hash_fn(size_type size, const Hash_Fn& r_hash_fn, const Comb_Hash_Fn& r_comb_hash_fn) : Hash_Fn(r_hash_fn), Comb_Hash_Fn(r_comb_hash_fn) { comb_hash_fn_base::notify_resized(size); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { comb_hash_fn_base::swap(other); std::swap((Hash_Fn& )(*this), (Hash_Fn& )other); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_resized(size_type size) { comb_hash_fn_base::notify_resized(size); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::comp_hash PB_DS_CLASS_C_DEC:: operator()(key_const_reference r_key) const { const size_type hash = hash_fn_base::operator()(r_key); return std::make_pair(comb_hash_fn_base::operator()(hash), hash); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::comp_hash PB_DS_CLASS_C_DEC:: operator() #ifdef _GLIBCXX_DEBUG (key_const_reference r_key, size_type hash) const #else (key_const_reference /*r_key*/, size_type hash) const #endif { _GLIBCXX_DEBUG_ASSERT(hash == hash_fn_base::operator()(r_key)); return std::make_pair(comb_hash_fn_base::operator()(hash), hash); } #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ ranged_hash_fn /** * Specialization 3 * The client does not supply a hash function (by specifying * null_type as the Hash_Fn parameter), and requests that hash * values not be stored. **/ template class ranged_hash_fn : public Comb_Hash_Fn { protected: typedef typename _Alloc::size_type size_type; typedef Comb_Hash_Fn comb_hash_fn_base; ranged_hash_fn(size_type); ranged_hash_fn(size_type, const Comb_Hash_Fn&); ranged_hash_fn(size_type, const null_type&, const Comb_Hash_Fn&); void swap(PB_DS_CLASS_C_DEC&); }; PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_hash_fn(size_type size) { Comb_Hash_Fn::notify_resized(size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_hash_fn(size_type size, const Comb_Hash_Fn& r_comb_hash_fn) : Comb_Hash_Fn(r_comb_hash_fn) { } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_hash_fn(size_type size, const null_type& r_null_type, const Comb_Hash_Fn& r_comb_hash_fn) : Comb_Hash_Fn(r_comb_hash_fn) { } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { comb_hash_fn_base::swap(other); } #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ ranged_hash_fn /** * Specialization 4 * The client does not supply a hash function (by specifying * null_type as the Hash_Fn parameter), and requests that hash * values be stored. **/ template class ranged_hash_fn : public Comb_Hash_Fn { protected: typedef typename _Alloc::size_type size_type; typedef Comb_Hash_Fn comb_hash_fn_base; ranged_hash_fn(size_type); ranged_hash_fn(size_type, const Comb_Hash_Fn&); ranged_hash_fn(size_type, const null_type&, const Comb_Hash_Fn&); void swap(PB_DS_CLASS_C_DEC&); }; PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_hash_fn(size_type size) { Comb_Hash_Fn::notify_resized(size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_hash_fn(size_type size, const Comb_Hash_Fn& r_comb_hash_fn) : Comb_Hash_Fn(r_comb_hash_fn) { } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_hash_fn(size_type size, const null_type& r_null_type, const Comb_Hash_Fn& r_comb_hash_fn) : Comb_Hash_Fn(r_comb_hash_fn) { } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { comb_hash_fn_base::swap(other); } #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC } // namespace detail } // namespace __gnu_pbds #endif PK!45((.8/ext/pb_ds/detail/hash_fn/ranged_probe_fn.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file ranged_probe_fn.hpp * Contains a unified ranged probe functor, allowing the probe tables to deal with * a single class for ranged probeing. */ #ifndef PB_DS_RANGED_PROBE_FN_HPP #define PB_DS_RANGED_PROBE_FN_HPP #include #include namespace __gnu_pbds { namespace detail { /// Primary template. template class ranged_probe_fn; #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ ranged_probe_fn /** * Specialization 1 * The client supplies a probe function and a ranged probe * function, and requests that hash values not be stored. **/ template class ranged_probe_fn : public Hash_Fn, public Comb_Probe_Fn, public Probe_Fn { protected: typedef typename _Alloc::size_type size_type; typedef Comb_Probe_Fn comb_probe_fn_base; typedef Hash_Fn hash_fn_base; typedef Probe_Fn probe_fn_base; typedef typename _Alloc::template rebind::other key_allocator; typedef typename key_allocator::const_reference key_const_reference; ranged_probe_fn(size_type); ranged_probe_fn(size_type, const Hash_Fn&); ranged_probe_fn(size_type, const Hash_Fn&, const Comb_Probe_Fn&); ranged_probe_fn(size_type, const Hash_Fn&, const Comb_Probe_Fn&, const Probe_Fn&); void swap(PB_DS_CLASS_C_DEC&); void notify_resized(size_type); inline size_type operator()(key_const_reference) const; inline size_type operator()(key_const_reference, size_type, size_type) const; }; PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_probe_fn(size_type size) { Comb_Probe_Fn::notify_resized(size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_probe_fn(size_type size, const Hash_Fn& r_hash_fn) : Hash_Fn(r_hash_fn) { Comb_Probe_Fn::notify_resized(size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_probe_fn(size_type size, const Hash_Fn& r_hash_fn, const Comb_Probe_Fn& r_comb_probe_fn) : Hash_Fn(r_hash_fn), Comb_Probe_Fn(r_comb_probe_fn) { comb_probe_fn_base::notify_resized(size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_probe_fn(size_type size, const Hash_Fn& r_hash_fn, const Comb_Probe_Fn& r_comb_probe_fn, const Probe_Fn& r_probe_fn) : Hash_Fn(r_hash_fn), Comb_Probe_Fn(r_comb_probe_fn), Probe_Fn(r_probe_fn) { comb_probe_fn_base::notify_resized(size); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { comb_probe_fn_base::swap(other); std::swap((Hash_Fn& )(*this), (Hash_Fn&)other); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_resized(size_type size) { comb_probe_fn_base::notify_resized(size); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: operator()(key_const_reference r_key) const { return comb_probe_fn_base::operator()(hash_fn_base::operator()(r_key)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: operator()(key_const_reference, size_type hash, size_type i) const { return comb_probe_fn_base::operator()(hash + probe_fn_base::operator()(i)); } #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ ranged_probe_fn /** * Specialization 2- The client supplies a probe function and a ranged * probe function, and requests that hash values not be stored. **/ template class ranged_probe_fn : public Hash_Fn, public Comb_Probe_Fn, public Probe_Fn { protected: typedef typename _Alloc::size_type size_type; typedef std::pair comp_hash; typedef Comb_Probe_Fn comb_probe_fn_base; typedef Hash_Fn hash_fn_base; typedef Probe_Fn probe_fn_base; typedef typename _Alloc::template rebind::other key_allocator; typedef typename key_allocator::const_reference key_const_reference; ranged_probe_fn(size_type); ranged_probe_fn(size_type, const Hash_Fn&); ranged_probe_fn(size_type, const Hash_Fn&, const Comb_Probe_Fn&); ranged_probe_fn(size_type, const Hash_Fn&, const Comb_Probe_Fn&, const Probe_Fn&); void swap(PB_DS_CLASS_C_DEC&); void notify_resized(size_type); inline comp_hash operator()(key_const_reference) const; inline size_type operator()(key_const_reference, size_type, size_type) const; inline size_type operator()(key_const_reference, size_type) const; }; PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_probe_fn(size_type size) { Comb_Probe_Fn::notify_resized(size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_probe_fn(size_type size, const Hash_Fn& r_hash_fn) : Hash_Fn(r_hash_fn) { Comb_Probe_Fn::notify_resized(size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_probe_fn(size_type size, const Hash_Fn& r_hash_fn, const Comb_Probe_Fn& r_comb_probe_fn) : Hash_Fn(r_hash_fn), Comb_Probe_Fn(r_comb_probe_fn) { comb_probe_fn_base::notify_resized(size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ranged_probe_fn(size_type size, const Hash_Fn& r_hash_fn, const Comb_Probe_Fn& r_comb_probe_fn, const Probe_Fn& r_probe_fn) : Hash_Fn(r_hash_fn), Comb_Probe_Fn(r_comb_probe_fn), Probe_Fn(r_probe_fn) { comb_probe_fn_base::notify_resized(size); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { comb_probe_fn_base::swap(other); std::swap((Hash_Fn& )(*this), (Hash_Fn& )other); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_resized(size_type size) { comb_probe_fn_base::notify_resized(size); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::comp_hash PB_DS_CLASS_C_DEC:: operator()(key_const_reference r_key) const { const size_type hash = hash_fn_base::operator()(r_key); return std::make_pair(comb_probe_fn_base::operator()(hash), hash); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: operator()(key_const_reference, size_type hash, size_type i) const { return comb_probe_fn_base::operator()(hash + probe_fn_base::operator()(i)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: operator() #ifdef _GLIBCXX_DEBUG (key_const_reference r_key, size_type hash) const #else (key_const_reference /*r_key*/, size_type hash) const #endif { _GLIBCXX_DEBUG_ASSERT(hash == hash_fn_base::operator()(r_key)); return hash; } #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC /** * Specialization 3 and 4 * The client does not supply a hash function or probe function, * and requests that hash values not be stored. **/ template class ranged_probe_fn : public Comb_Probe_Fn { protected: typedef typename _Alloc::size_type size_type; typedef Comb_Probe_Fn comb_probe_fn_base; typedef typename _Alloc::template rebind::other key_allocator; typedef typename key_allocator::const_reference key_const_reference; ranged_probe_fn(size_type size) { Comb_Probe_Fn::notify_resized(size); } ranged_probe_fn(size_type, const Comb_Probe_Fn& r_comb_probe_fn) : Comb_Probe_Fn(r_comb_probe_fn) { } ranged_probe_fn(size_type, const null_type&, const Comb_Probe_Fn& r_comb_probe_fn, const null_type&) : Comb_Probe_Fn(r_comb_probe_fn) { } void swap(ranged_probe_fn& other) { comb_probe_fn_base::swap(other); } }; } // namespace detail } // namespace __gnu_pbds #endif PK!-.8/ext/pb_ds/detail/hash_fn/sample_probe_fn.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file sample_probe_fn.hpp * Contains a sample probe policy. */ #ifndef PB_DS_SAMPLE_PROBE_FN_HPP #define PB_DS_SAMPLE_PROBE_FN_HPP namespace __gnu_pbds { /// A sample probe policy. class sample_probe_fn { public: typedef std::size_t size_type; /// Default constructor. sample_probe_fn(); /// Copy constructor. sample_probe_fn(const sample_probe_fn&); /// Swaps content. inline void swap(sample_probe_fn&); protected: /// Returns the i-th offset from the hash value of some key r_key. inline size_type operator()(key_const_reference r_key, size_type i) const; }; } #endif // #ifndef PB_DS_SAMPLE_PROBE_FN_HPP PK!vįO 38/ext/pb_ds/detail/hash_fn/sample_range_hashing.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file sample_range_hashing.hpp * Contains a range hashing policy. */ #ifndef PB_DS_SAMPLE_RANGE_HASHING_HPP #define PB_DS_SAMPLE_RANGE_HASHING_HPP namespace __gnu_pbds { /// A sample range-hashing functor. class sample_range_hashing { public: /// Size type. typedef std::size_t size_type; /// Default constructor. sample_range_hashing(); /// Copy constructor. sample_range_hashing(const sample_range_hashing& other); /// Swaps content. inline void swap(sample_range_hashing& other); protected: /// Notifies the policy object that the container's size has /// changed to argument's size. void notify_resized(size_type); /// Transforms the __hash value hash into a ranged-hash value. inline size_type operator()(size_type ) const; }; } #endif // #ifndef PB_DS_SAMPLE_RANGE_HASHING_HPP PK!JX̥ 48/ext/pb_ds/detail/hash_fn/sample_ranged_hash_fn.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file sample_ranged_hash_fn.hpp * Contains a ranged hash policy. */ #ifndef PB_DS_SAMPLE_RANGED_HASH_FN_HPP #define PB_DS_SAMPLE_RANGED_HASH_FN_HPP namespace __gnu_pbds { /// A sample ranged-hash functor. class sample_ranged_hash_fn { public: typedef std::size_t size_type; /// Default constructor. sample_ranged_hash_fn(); /// Copy constructor. sample_ranged_hash_fn(const sample_ranged_hash_fn&); /// Swaps content. inline void swap(sample_ranged_hash_fn&); protected: /// Notifies the policy object that the container's __size has /// changed to size. void notify_resized(size_type); /// Transforms key_const_reference into a position within the table. inline size_type operator()(key_const_reference) const; }; } #endif // #ifndef PB_DS_SAMPLE_RANGED_HASH_FN_HPP PK!k6& & 58/ext/pb_ds/detail/hash_fn/sample_ranged_probe_fn.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file sample_ranged_probe_fn.hpp * Contains a ranged probe policy. */ #ifndef PB_DS_SAMPLE_RANGED_PROBE_FN_HPP #define PB_DS_SAMPLE_RANGED_PROBE_FN_HPP namespace __gnu_pbds { /// A sample ranged-probe functor. class sample_ranged_probe_fn { public: typedef std::size_t size_type; // Default constructor. sample_ranged_probe_fn(); // Copy constructor. sample_ranged_probe_fn(const sample_ranged_probe_fn&); // Swaps content. inline void swap(sample_ranged_probe_fn&); protected: // Notifies the policy object that the container's __size has // changed to size. void notify_resized(size_type); // Transforms the const key reference r_key into the i-th position // within the table. This method is called for each collision within // the probe sequence. inline size_type operator()(key_const_reference, std::size_t, size_type) const; }; } #endif // #ifndef PB_DS_SAMPLE_RANGED_PROBE_FN_HPP PK!ko<<C8/ext/pb_ds/detail/left_child_next_sibling_heap_/const_iterator.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file left_child_next_sibling_heap_/const_iterator.hpp * Contains an iterator class returned by the table's const find and insert * methods. */ #ifndef PB_DS_LEFT_CHILD_NEXT_SIBLING_HEAP_CONST_ITERATOR_HPP #define PB_DS_LEFT_CHILD_NEXT_SIBLING_HEAP_CONST_ITERATOR_HPP #include #include namespace __gnu_pbds { namespace detail { #define PB_DS_CLASS_C_DEC \ left_child_next_sibling_heap_const_iterator_ #define PB_DS_BASIC_HEAP_CIT_BASE \ left_child_next_sibling_heap_node_point_const_iterator_ /// Const point-type iterator. template class left_child_next_sibling_heap_const_iterator_ : public PB_DS_BASIC_HEAP_CIT_BASE { private: typedef PB_DS_BASIC_HEAP_CIT_BASE base_type; typedef typename base_type::node_pointer node_pointer; public: /// Category. typedef std::forward_iterator_tag iterator_category; /// Difference type. typedef typename _Alloc::difference_type difference_type; /// Iterator's value type. typedef typename base_type::value_type value_type; /// Iterator's pointer type. typedef typename base_type::pointer pointer; /// Iterator's const pointer type. typedef typename base_type::const_pointer const_pointer; /// Iterator's reference type. typedef typename base_type::reference reference; /// Iterator's const reference type. typedef typename base_type::const_reference const_reference; inline left_child_next_sibling_heap_const_iterator_(node_pointer p_nd) : base_type(p_nd) { } /// Default constructor. inline left_child_next_sibling_heap_const_iterator_() { } /// Copy constructor. inline left_child_next_sibling_heap_const_iterator_(const PB_DS_CLASS_C_DEC& other) : base_type(other) { } /// Compares content to a different iterator object. bool operator==(const PB_DS_CLASS_C_DEC& other) const { return (base_type::m_p_nd == other.m_p_nd); } /// Compares content (negatively) to a different iterator object. bool operator!=(const PB_DS_CLASS_C_DEC& other) const { return (base_type::m_p_nd != other.m_p_nd); } PB_DS_CLASS_C_DEC& operator++() { _GLIBCXX_DEBUG_ASSERT(base_type::m_p_nd != 0); inc(); return (*this); } PB_DS_CLASS_C_DEC operator++(int) { PB_DS_CLASS_C_DEC ret_it(base_type::m_p_nd); operator++(); return (ret_it); } private: void inc() { if (base_type::m_p_nd->m_p_next_sibling != 0) { base_type::m_p_nd = base_type::m_p_nd->m_p_next_sibling; while (base_type::m_p_nd->m_p_l_child != 0) base_type::m_p_nd = base_type::m_p_nd->m_p_l_child; return; } while (true) { node_pointer p_next = base_type::m_p_nd; base_type::m_p_nd = base_type::m_p_nd->m_p_prev_or_parent; if (base_type::m_p_nd == 0 || base_type::m_p_nd->m_p_l_child == p_next) return; } } }; #undef PB_DS_CLASS_C_DEC #undef PB_DS_BASIC_HEAP_CIT_BASE } // namespace detail } // namespace __gnu_pbds #endif PK! T8/ext/pb_ds/detail/left_child_next_sibling_heap_/constructors_destructor_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file left_child_next_sibling_heap_/constructors_destructor_fn_imps.hpp * Contains an implementation class for left_child_next_sibling_heap_. */ PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_allocator PB_DS_CLASS_C_DEC::s_node_allocator; PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::no_throw_copies_t PB_DS_CLASS_C_DEC::s_no_throw_copies_ind; PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: left_child_next_sibling_heap() : m_p_root(0), m_size(0) { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: left_child_next_sibling_heap(const Cmp_Fn& r_cmp_fn) : Cmp_Fn(r_cmp_fn), m_p_root(0), m_size(0) { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: left_child_next_sibling_heap(const PB_DS_CLASS_C_DEC& other) : Cmp_Fn(other), m_p_root(0), m_size(0) { m_size = other.m_size; PB_DS_ASSERT_VALID(other) m_p_root = recursive_copy_node(other.m_p_root); m_size = other.m_size; PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) value_swap(other); std::swap((Cmp_Fn& )(*this), (Cmp_Fn& )other); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: value_swap(PB_DS_CLASS_C_DEC& other) { std::swap(m_p_root, other.m_p_root); std::swap(m_size, other.m_size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~left_child_next_sibling_heap() { clear(); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: recursive_copy_node(node_const_pointer p_nd) { if (p_nd == 0) return (0); node_pointer p_ret = s_node_allocator.allocate(1); __try { new (p_ret) node(*p_nd); } __catch(...) { s_node_allocator.deallocate(p_ret, 1); __throw_exception_again; } p_ret->m_p_l_child = p_ret->m_p_next_sibling = p_ret->m_p_prev_or_parent = 0; __try { p_ret->m_p_l_child = recursive_copy_node(p_nd->m_p_l_child); p_ret->m_p_next_sibling = recursive_copy_node(p_nd->m_p_next_sibling); } __catch(...) { clear_imp(p_ret); __throw_exception_again; } if (p_ret->m_p_l_child != 0) p_ret->m_p_l_child->m_p_prev_or_parent = p_ret; if (p_ret->m_p_next_sibling != 0) p_ret->m_p_next_sibling->m_p_prev_or_parent = p_nd->m_p_next_sibling->m_p_prev_or_parent == p_nd ? p_ret : 0; return p_ret; } PK!XjB8/ext/pb_ds/detail/left_child_next_sibling_heap_/debug_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file left_child_next_sibling_heap_/debug_fn_imps.hpp * Contains an implementation class for left_child_next_sibling_heap_. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { PB_DS_DEBUG_VERIFY(m_p_root == 0 || m_p_root->m_p_prev_or_parent == 0); if (m_p_root != 0) assert_node_consistent(m_p_root, Single_Link_Roots, __file, __line); assert_size(__file, __line); assert_iterators(__file, __line); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_node_consistent(node_const_pointer p_nd, bool single_link, const char* __file, int __line) const { if (p_nd == 0) return; assert_node_consistent(p_nd->m_p_l_child, false, __file, __line); assert_node_consistent(p_nd->m_p_next_sibling, single_link, __file, __line); if (single_link) PB_DS_DEBUG_VERIFY(p_nd->m_p_prev_or_parent == 0); else if (p_nd->m_p_next_sibling != 0) PB_DS_DEBUG_VERIFY(p_nd->m_p_next_sibling->m_p_prev_or_parent == p_nd); if (p_nd->m_p_l_child == 0) return; node_const_pointer p_child = p_nd->m_p_l_child; while (p_child != 0) { node_const_pointer p_next_child = p_child->m_p_next_sibling; PB_DS_DEBUG_VERIFY(!Cmp_Fn::operator()(p_nd->m_value, p_child->m_value)); p_child = p_next_child; } PB_DS_DEBUG_VERIFY(p_nd->m_p_l_child->m_p_prev_or_parent == p_nd); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_iterators(const char* __file, int __line) const { PB_DS_DEBUG_VERIFY(std::distance(begin(), end()) == size()); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_size(const char* __file, int __line) const { PB_DS_DEBUG_VERIFY(size_from_node(m_p_root) == m_size); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: size_under_node(node_const_pointer p_nd) { return 1 + size_from_node(p_nd->m_p_l_child); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: size_from_node(node_const_pointer p_nd) { size_type ret = 0; while (p_nd != 0) { ret += 1 + size_from_node(p_nd->m_p_l_child); p_nd = p_nd->m_p_next_sibling; } return ret; } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: degree(node_const_pointer p_nd) { size_type ret = 0; node_const_pointer p_child = p_nd->m_p_l_child; while (p_child != 0) { ++ret; p_child = p_child->m_p_next_sibling; } return ret; } #endif PK!wwB8/ext/pb_ds/detail/left_child_next_sibling_heap_/erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file left_child_next_sibling_heap_/erase_fn_imps.hpp * Contains an implementation class for left_child_next_sibling_heap_. */ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear() { clear_imp(m_p_root); _GLIBCXX_DEBUG_ASSERT(m_size == 0); m_p_root = 0; } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: actual_erase_node(node_pointer p_nd) { _GLIBCXX_DEBUG_ASSERT(m_size > 0); --m_size; p_nd->~node(); s_node_allocator.deallocate(p_nd, 1); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear_imp(node_pointer p_nd) { while (p_nd != 0) { clear_imp(p_nd->m_p_l_child); node_pointer p_next = p_nd->m_p_next_sibling; actual_erase_node(p_nd); p_nd = p_next; } } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: to_linked_list() { PB_DS_ASSERT_VALID((*this)) node_pointer p_cur = m_p_root; while (p_cur != 0) if (p_cur->m_p_l_child != 0) { node_pointer p_child_next = p_cur->m_p_l_child->m_p_next_sibling; p_cur->m_p_l_child->m_p_next_sibling = p_cur->m_p_next_sibling; p_cur->m_p_next_sibling = p_cur->m_p_l_child; p_cur->m_p_l_child = p_child_next; } else p_cur = p_cur->m_p_next_sibling; #ifdef _GLIBCXX_DEBUG node_const_pointer p_counter = m_p_root; size_type count = 0; while (p_counter != 0) { ++count; _GLIBCXX_DEBUG_ASSERT(p_counter->m_p_l_child == 0); p_counter = p_counter->m_p_next_sibling; } _GLIBCXX_DEBUG_ASSERT(count == m_size); #endif } PB_DS_CLASS_T_DEC template typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: prune(Pred pred) { node_pointer p_cur = m_p_root; m_p_root = 0; node_pointer p_out = 0; while (p_cur != 0) { node_pointer p_next = p_cur->m_p_next_sibling; if (pred(p_cur->m_value)) { p_cur->m_p_next_sibling = p_out; if (p_out != 0) p_out->m_p_prev_or_parent = p_cur; p_out = p_cur; } else { p_cur->m_p_next_sibling = m_p_root; if (m_p_root != 0) m_p_root->m_p_prev_or_parent = p_cur; m_p_root = p_cur; } p_cur = p_next; } return p_out; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: bubble_to_top(node_pointer p_nd) { node_pointer p_parent = parent(p_nd); while (p_parent != 0) { swap_with_parent(p_nd, p_parent); p_parent = parent(p_nd); } } PK!H:::A8/ext/pb_ds/detail/left_child_next_sibling_heap_/info_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file left_child_next_sibling_heap_/info_fn_imps.hpp * Contains an implementation class for left_child_next_sibling_heap_. */ PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: empty() const { return (m_size == 0); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: size() const { return (m_size); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: max_size() const { return (s_node_allocator.max_size()); } PK!jQQC8/ext/pb_ds/detail/left_child_next_sibling_heap_/insert_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file left_child_next_sibling_heap_/insert_fn_imps.hpp * Contains an implementation class for left_child_next_sibling_heap_. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: get_new_node_for_insert(const_reference r_val) { return get_new_node_for_insert(r_val, s_no_throw_copies_ind); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: get_new_node_for_insert(const_reference r_val, false_type) { node_pointer p_new_nd = s_node_allocator.allocate(1); cond_dealtor_t cond(p_new_nd); new (const_cast( static_cast(&p_new_nd->m_value))) typename node::value_type(r_val); cond.set_no_action(); ++m_size; return (p_new_nd); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: get_new_node_for_insert(const_reference r_val, true_type) { node_pointer p_new_nd = s_node_allocator.allocate(1); new (const_cast( static_cast(&p_new_nd->m_value))) typename node::value_type(r_val); ++m_size; return (p_new_nd); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: make_child_of(node_pointer p_nd, node_pointer p_new_parent) { _GLIBCXX_DEBUG_ASSERT(p_nd != 0); _GLIBCXX_DEBUG_ASSERT(p_new_parent != 0); p_nd->m_p_next_sibling = p_new_parent->m_p_l_child; if (p_new_parent->m_p_l_child != 0) p_new_parent->m_p_l_child->m_p_prev_or_parent = p_nd; p_nd->m_p_prev_or_parent = p_new_parent; p_new_parent->m_p_l_child = p_nd; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: parent(node_pointer p_nd) { while (true) { node_pointer p_pot = p_nd->m_p_prev_or_parent; if (p_pot == 0 || p_pot->m_p_l_child == p_nd) return p_pot; p_nd = p_pot; } } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: swap_with_parent(node_pointer p_nd, node_pointer p_parent) { if (p_parent == m_p_root) m_p_root = p_nd; _GLIBCXX_DEBUG_ASSERT(p_nd != 0); _GLIBCXX_DEBUG_ASSERT(p_parent != 0); _GLIBCXX_DEBUG_ASSERT(parent(p_nd) == p_parent); const bool nd_direct_child = p_parent->m_p_l_child == p_nd; const bool parent_root = p_parent->m_p_prev_or_parent == 0; const bool parent_direct_child = !parent_root&& p_parent->m_p_prev_or_parent->m_p_l_child == p_parent; std::swap(p_parent->m_p_prev_or_parent, p_nd->m_p_prev_or_parent); std::swap(p_parent->m_p_next_sibling, p_nd->m_p_next_sibling); std::swap(p_parent->m_p_l_child, p_nd->m_p_l_child); std::swap(p_parent->m_metadata, p_nd->m_metadata); _GLIBCXX_DEBUG_ASSERT(p_nd->m_p_l_child != 0); _GLIBCXX_DEBUG_ASSERT(p_parent->m_p_prev_or_parent != 0); if (p_nd->m_p_next_sibling != 0) p_nd->m_p_next_sibling->m_p_prev_or_parent = p_nd; if (p_parent->m_p_next_sibling != 0) p_parent->m_p_next_sibling->m_p_prev_or_parent = p_parent; if (p_parent->m_p_l_child != 0) p_parent->m_p_l_child->m_p_prev_or_parent = p_parent; if (parent_direct_child) p_nd->m_p_prev_or_parent->m_p_l_child = p_nd; else if (!parent_root) p_nd->m_p_prev_or_parent->m_p_next_sibling = p_nd; if (!nd_direct_child) { p_nd->m_p_l_child->m_p_prev_or_parent = p_nd; p_parent->m_p_prev_or_parent->m_p_next_sibling = p_parent; } else { _GLIBCXX_DEBUG_ASSERT(p_nd->m_p_l_child == p_nd); _GLIBCXX_DEBUG_ASSERT(p_parent->m_p_prev_or_parent == p_parent); p_nd->m_p_l_child = p_parent; p_parent->m_p_prev_or_parent = p_nd; } _GLIBCXX_DEBUG_ASSERT(parent(p_parent) == p_nd); } PK!^y8 F8/ext/pb_ds/detail/left_child_next_sibling_heap_/iterators_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file left_child_next_sibling_heap_/iterators_fn_imps.hpp * Contains an implementation class for left_child_next_sibling_heap_. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: begin() { node_pointer p_nd = m_p_root; if (p_nd == 0) return (iterator(0)); while (p_nd->m_p_l_child != 0) p_nd = p_nd->m_p_l_child; return (iterator(p_nd)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: begin() const { node_pointer p_nd = m_p_root; if (p_nd == 0) return (const_iterator(0)); while (p_nd->m_p_l_child != 0) p_nd = p_nd->m_p_l_child; return (const_iterator(p_nd)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: end() { return (iterator(0)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: end() const { return (const_iterator(0)); } PK!XˆR8/ext/pb_ds/detail/left_child_next_sibling_heap_/left_child_next_sibling_heap_.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file left_child_next_sibling_heap_/left_child_next_sibling_heap_.hpp * Contains an implementation class for a basic heap. */ #ifndef PB_DS_LEFT_CHILD_NEXT_SIBLING_HEAP_HPP #define PB_DS_LEFT_CHILD_NEXT_SIBLING_HEAP_HPP /* * Based on CLRS. */ #include #include #include #include #include #include #ifdef PB_DS_LC_NS_HEAP_TRACE_ #include #endif #include namespace __gnu_pbds { namespace detail { #ifdef _GLIBCXX_DEBUG #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ left_child_next_sibling_heap #else #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ left_child_next_sibling_heap #endif /// Base class for a basic heap. template #else > #endif class left_child_next_sibling_heap : public Cmp_Fn { protected: typedef typename _Alloc::template rebind< left_child_next_sibling_heap_node_ >::other node_allocator; typedef typename node_allocator::value_type node; typedef typename node_allocator::pointer node_pointer; typedef typename node_allocator::const_pointer node_const_pointer; typedef Node_Metadata node_metadata; typedef std::pair< node_pointer, node_pointer> node_pointer_pair; private: typedef cond_dealtor< node, _Alloc> cond_dealtor_t; enum { simple_value = is_simple::value }; typedef integral_constant no_throw_copies_t; typedef typename _Alloc::template rebind __rebind_v; public: typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef Value_Type value_type; typedef typename __rebind_v::other::pointer pointer; typedef typename __rebind_v::other::const_pointer const_pointer; typedef typename __rebind_v::other::reference reference; typedef typename __rebind_v::other::const_reference const_reference; typedef left_child_next_sibling_heap_node_point_const_iterator_ point_const_iterator; typedef point_const_iterator point_iterator; typedef left_child_next_sibling_heap_const_iterator_ const_iterator; typedef const_iterator iterator; typedef Cmp_Fn cmp_fn; typedef _Alloc allocator_type; left_child_next_sibling_heap(); left_child_next_sibling_heap(const Cmp_Fn&); left_child_next_sibling_heap(const left_child_next_sibling_heap&); void swap(PB_DS_CLASS_C_DEC&); ~left_child_next_sibling_heap(); inline bool empty() const; inline size_type size() const; inline size_type max_size() const; Cmp_Fn& get_cmp_fn(); const Cmp_Fn& get_cmp_fn() const; inline iterator begin(); inline const_iterator begin() const; inline iterator end(); inline const_iterator end() const; void clear(); #ifdef PB_DS_LC_NS_HEAP_TRACE_ void trace() const; #endif protected: inline node_pointer get_new_node_for_insert(const_reference); inline static void make_child_of(node_pointer, node_pointer); void value_swap(left_child_next_sibling_heap&); inline static node_pointer parent(node_pointer); inline void swap_with_parent(node_pointer, node_pointer); void bubble_to_top(node_pointer); inline void actual_erase_node(node_pointer); void clear_imp(node_pointer); void to_linked_list(); template node_pointer prune(Pred); #ifdef _GLIBCXX_DEBUG void assert_valid(const char*, int) const; void assert_node_consistent(node_const_pointer, bool, const char*, int) const; static size_type size_under_node(node_const_pointer); static size_type degree(node_const_pointer); #endif #ifdef PB_DS_LC_NS_HEAP_TRACE_ static void trace_node(node_const_pointer, size_type); #endif private: #ifdef _GLIBCXX_DEBUG void assert_iterators(const char*, int) const; void assert_size(const char*, int) const; static size_type size_from_node(node_const_pointer); #endif node_pointer recursive_copy_node(node_const_pointer); inline node_pointer get_new_node_for_insert(const_reference, false_type); inline node_pointer get_new_node_for_insert(const_reference, true_type); #ifdef PB_DS_LC_NS_HEAP_TRACE_ template static void trace_node_metadata(node_const_pointer, type_to_type); static void trace_node_metadata(node_const_pointer, type_to_type); #endif static node_allocator s_node_allocator; static no_throw_copies_t s_no_throw_copies_ind; protected: node_pointer m_p_root; size_type m_size; }; #include #include #include #include #include #include #include #include #undef PB_DS_CLASS_C_DEC #undef PB_DS_CLASS_T_DEC } // namespace detail } // namespace __gnu_pbds #endif PK![ht 98/ext/pb_ds/detail/left_child_next_sibling_heap_/node.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file left_child_next_sibling_heap_/node.hpp * Contains an implementation struct for this type of heap's node. */ #ifndef PB_DS_LEFT_CHILD_NEXT_SIBLING_HEAP_NODE_HPP #define PB_DS_LEFT_CHILD_NEXT_SIBLING_HEAP_NODE_HPP namespace __gnu_pbds { namespace detail { /// Node. template struct left_child_next_sibling_heap_node_ { private: typedef left_child_next_sibling_heap_node_<_Value, _Metadata, _Alloc> this_type; public: typedef _Value value_type; typedef typename _Alloc::size_type size_type; typedef _Metadata metadata_type; typedef typename _Alloc::template rebind::other::pointer node_pointer; value_type m_value; metadata_type m_metadata; node_pointer m_p_l_child; node_pointer m_p_next_sibling; node_pointer m_p_prev_or_parent; }; template struct left_child_next_sibling_heap_node_<_Value, null_type, _Alloc> { private: typedef left_child_next_sibling_heap_node_<_Value, null_type, _Alloc> this_type; public: typedef _Value value_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::template rebind::other::pointer node_pointer; value_type m_value; node_pointer m_p_l_child; node_pointer m_p_next_sibling; node_pointer m_p_prev_or_parent; }; } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_LEFT_CHILD_NEXT_SIBLING_HEAP_NODE_HPP PK!k͐I8/ext/pb_ds/detail/left_child_next_sibling_heap_/point_const_iterator.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file left_child_next_sibling_heap_/point_const_iterator.hpp * Contains an iterator class returned by the table's const find and insert * methods. */ #ifndef PB_DS_LEFT_CHILD_NEXT_SIBLING_HEAP_CONST_FIND_ITERATOR_HPP #define PB_DS_LEFT_CHILD_NEXT_SIBLING_HEAP_CONST_FIND_ITERATOR_HPP #include #include namespace __gnu_pbds { namespace detail { #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ left_child_next_sibling_heap_node_point_const_iterator_ /// Const point-type iterator. template class left_child_next_sibling_heap_node_point_const_iterator_ { protected: typedef typename _Alloc::template rebind::other::pointer node_pointer; public: /// Category. typedef trivial_iterator_tag iterator_category; /// Difference type. typedef trivial_iterator_difference_type difference_type; /// Iterator's value type. typedef typename Node::value_type value_type; /// Iterator's pointer type. typedef typename _Alloc::template rebind< value_type>::other::pointer pointer; /// Iterator's const pointer type. typedef typename _Alloc::template rebind< value_type>::other::const_pointer const_pointer; /// Iterator's reference type. typedef typename _Alloc::template rebind< value_type>::other::reference reference; /// Iterator's const reference type. typedef typename _Alloc::template rebind< value_type>::other::const_reference const_reference; inline left_child_next_sibling_heap_node_point_const_iterator_(node_pointer p_nd) : m_p_nd(p_nd) { } /// Default constructor. inline left_child_next_sibling_heap_node_point_const_iterator_() : m_p_nd(0) { } /// Copy constructor. inline left_child_next_sibling_heap_node_point_const_iterator_(const PB_DS_CLASS_C_DEC& other) : m_p_nd(other.m_p_nd) { } /// Access. const_pointer operator->() const { _GLIBCXX_DEBUG_ASSERT(m_p_nd != 0); return &m_p_nd->m_value; } /// Access. const_reference operator*() const { _GLIBCXX_DEBUG_ASSERT(m_p_nd != 0); return m_p_nd->m_value; } /// Compares content to a different iterator object. bool operator==(const PB_DS_CLASS_C_DEC& other) const { return m_p_nd == other.m_p_nd; } /// Compares content (negatively) to a different iterator object. bool operator!=(const PB_DS_CLASS_C_DEC& other) const { return m_p_nd != other.m_p_nd; } node_pointer m_p_nd; }; #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC } // namespace detail } // namespace __gnu_pbds #endif PK!ՇJ8/ext/pb_ds/detail/left_child_next_sibling_heap_/policy_access_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file left_child_next_sibling_heap_/policy_access_fn_imps.hpp * Contains an implementation class for left_child_next_sibling_heap_. */ PB_DS_CLASS_T_DEC Cmp_Fn& PB_DS_CLASS_C_DEC:: get_cmp_fn() { return *this; } PB_DS_CLASS_T_DEC const Cmp_Fn& PB_DS_CLASS_C_DEC:: get_cmp_fn() const { return *this; } PK!sR B8/ext/pb_ds/detail/left_child_next_sibling_heap_/trace_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file left_child_next_sibling_heap_/trace_fn_imps.hpp * Contains an implementation class for left_child_next_sibling_heap_. */ #ifdef PB_DS_LC_NS_HEAP_TRACE_ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace() const { std::cerr << std::endl; trace_node(m_p_root, 0); std::cerr << std::endl; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace_node(node_const_pointer p_nd, size_type level) { while (p_nd != 0) { for (size_type i = 0; i < level; ++i) std::cerr << ' '; std::cerr << p_nd << " prev = " << p_nd->m_p_prev_or_parent << " next " << p_nd->m_p_next_sibling << " left = " << p_nd->m_p_l_child << " "; trace_node_metadata(p_nd, type_to_type()); std::cerr << p_nd->m_value << std::endl; trace_node(p_nd->m_p_l_child, level + 1); p_nd = p_nd->m_p_next_sibling; } } PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: trace_node_metadata(node_const_pointer p_nd, type_to_type) { std::cerr << "(" << p_nd->m_metadata << ") "; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace_node_metadata(node_const_pointer, type_to_type) { } #endif // #ifdef PB_DS_LC_NS_HEAP_TRACE_ PK!^ F8/ext/pb_ds/detail/list_update_map_/constructor_destructor_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file list_update_map_/constructor_destructor_fn_imps.hpp */ PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::entry_allocator PB_DS_CLASS_C_DEC::s_entry_allocator; PB_DS_CLASS_T_DEC Eq_Fn PB_DS_CLASS_C_DEC::s_eq_fn; PB_DS_CLASS_T_DEC null_type PB_DS_CLASS_C_DEC::s_null_type; PB_DS_CLASS_T_DEC Update_Policy PB_DS_CLASS_C_DEC::s_update_policy; PB_DS_CLASS_T_DEC type_to_type< typename PB_DS_CLASS_C_DEC::update_metadata> PB_DS_CLASS_C_DEC::s_metadata_type_indicator; PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: copy_from_range(It first_it, It last_it) { while (first_it != last_it) insert(*(first_it++)); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_LU_NAME() : m_p_l(0) { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC template PB_DS_CLASS_C_DEC:: PB_DS_LU_NAME(It first_it, It last_it) : m_p_l(0) { copy_from_range(first_it, last_it); PB_DS_ASSERT_VALID((*this)); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_LU_NAME(const PB_DS_CLASS_C_DEC& other) : m_p_l(0) { __try { for (const_iterator it = other.begin(); it != other.end(); ++it) { entry_pointer p_l = allocate_new_entry(*it, traits_base::m_no_throw_copies_indicator); p_l->m_p_next = m_p_l; m_p_l = p_l; } } __catch(...) { deallocate_all(); __throw_exception_again; } PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) _GLIBCXX_DEBUG_ONLY(debug_base::swap(other);) std::swap(m_p_l, other.m_p_l); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: deallocate_all() { entry_pointer p_l = m_p_l; while (p_l != 0) { entry_pointer p_next_l = p_l->m_p_next; actual_erase_entry(p_l); p_l = p_next_l; } m_p_l = 0; } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~PB_DS_LU_NAME() { deallocate_all(); } PK!K//58/ext/pb_ds/detail/list_update_map_/debug_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file list_update_map_/debug_fn_imps.hpp * Contains implementations of cc_ht_map_'s debug-mode functions. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { size_type calc_size = 0; for (const_iterator it = begin(); it != end(); ++it) { debug_base::check_key_exists(PB_DS_V2F(*it), __file, __line); ++calc_size; } debug_base::check_size(calc_size, __file, __line); } #endif PK!O{EE;8/ext/pb_ds/detail/list_update_map_/entry_metadata_base.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file list_update_map_/entry_metadata_base.hpp * Contains an implementation for a list update map. */ #ifndef PB_DS_LU_MAP_ENTRY_METADATA_BASE_HPP #define PB_DS_LU_MAP_ENTRY_METADATA_BASE_HPP namespace __gnu_pbds { namespace detail { template struct lu_map_entry_metadata_base { Metadata m_update_metadata; }; template<> struct lu_map_entry_metadata_base { }; } // namespace detail } // namespace __gnu_pbds #endif PK! 58/ext/pb_ds/detail/list_update_map_/erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file list_update_map_/erase_fn_imps.hpp * Contains implementations of lu_map_. */ PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: erase(key_const_reference r_key) { PB_DS_ASSERT_VALID((*this)) if (m_p_l == 0) return false; if (s_eq_fn(r_key, PB_DS_V2F(m_p_l->m_value))) { entry_pointer p_next = m_p_l->m_p_next; actual_erase_entry(m_p_l); m_p_l = p_next; return true; } entry_pointer p_l = m_p_l; while (p_l->m_p_next != 0) if (s_eq_fn(r_key, PB_DS_V2F(p_l->m_p_next->m_value))) { erase_next(p_l); return true; } else p_l = p_l->m_p_next; return false; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear() { deallocate_all(); } PB_DS_CLASS_T_DEC template inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: erase_if(Pred pred) { PB_DS_ASSERT_VALID((*this)) size_type num_ersd = 0; while (m_p_l != 0 && pred(m_p_l->m_value)) { entry_pointer p_next = m_p_l->m_p_next; ++num_ersd; actual_erase_entry(m_p_l); m_p_l = p_next; } if (m_p_l == 0) return num_ersd; entry_pointer p_l = m_p_l; while (p_l->m_p_next != 0) { if (pred(p_l->m_p_next->m_value)) { ++num_ersd; erase_next(p_l); } else p_l = p_l->m_p_next; } PB_DS_ASSERT_VALID((*this)) return num_ersd; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: erase_next(entry_pointer p_l) { _GLIBCXX_DEBUG_ASSERT(p_l != 0); _GLIBCXX_DEBUG_ASSERT(p_l->m_p_next != 0); entry_pointer p_next_l = p_l->m_p_next->m_p_next; actual_erase_entry(p_l->m_p_next); p_l->m_p_next = p_next_l; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: actual_erase_entry(entry_pointer p_l) { _GLIBCXX_DEBUG_ONLY(debug_base::erase_existing(PB_DS_V2F(p_l->m_value));) p_l->~entry(); s_entry_allocator.deallocate(p_l, 1); } PK! C- - 48/ext/pb_ds/detail/list_update_map_/find_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file list_update_map_/find_fn_imps.hpp * Contains implementations of lu_map_. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::entry_pointer PB_DS_CLASS_C_DEC:: find_imp(key_const_reference r_key) const { if (m_p_l == 0) return 0; if (s_eq_fn(r_key, PB_DS_V2F(m_p_l->m_value))) { apply_update(m_p_l, s_metadata_type_indicator); PB_DS_CHECK_KEY_EXISTS(r_key) return m_p_l; } entry_pointer p_l = m_p_l; while (p_l->m_p_next != 0) { entry_pointer p_next = p_l->m_p_next; if (s_eq_fn(r_key, PB_DS_V2F(p_next->m_value))) { if (apply_update(p_next, s_metadata_type_indicator)) { p_l->m_p_next = p_next->m_p_next; p_next->m_p_next = m_p_l; m_p_l = p_next; return m_p_l; } return p_next; } else p_l = p_next; } PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return 0; } PB_DS_CLASS_T_DEC template inline bool PB_DS_CLASS_C_DEC:: apply_update(entry_pointer p_l, type_to_type) { return s_update_policy(p_l->m_update_metadata); } PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: apply_update(entry_pointer, type_to_type) { return s_update_policy(s_null_type); } PK! 48/ext/pb_ds/detail/list_update_map_/info_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file list_update_map_/info_fn_imps.hpp * Contains implementations of lu_map_. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: size() const { return std::distance(begin(), end()); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: max_size() const { return s_entry_allocator.max_size(); } PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: empty() const { return (m_p_l == 0); } PK!56 68/ext/pb_ds/detail/list_update_map_/insert_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file list_update_map_/insert_fn_imps.hpp * Contains implementations of lu_map_. */ PB_DS_CLASS_T_DEC inline std::pair< typename PB_DS_CLASS_C_DEC::point_iterator, bool> PB_DS_CLASS_C_DEC:: insert(const_reference r_val) { PB_DS_ASSERT_VALID((*this)) entry_pointer p_l = find_imp(PB_DS_V2F(r_val)); if (p_l != 0) { PB_DS_CHECK_KEY_EXISTS(PB_DS_V2F(r_val)) return std::make_pair(point_iterator(&p_l->m_value), false); } PB_DS_CHECK_KEY_DOES_NOT_EXIST(PB_DS_V2F(r_val)) p_l = allocate_new_entry(r_val, traits_base::m_no_throw_copies_indicator); p_l->m_p_next = m_p_l; m_p_l = p_l; PB_DS_ASSERT_VALID((*this)) return std::make_pair(point_iterator(&p_l->m_value), true); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::entry_pointer PB_DS_CLASS_C_DEC:: allocate_new_entry(const_reference r_val, false_type) { entry_pointer p_l = s_entry_allocator.allocate(1); cond_dealtor_t cond(p_l); new (const_cast(static_cast(&p_l->m_value))) value_type(r_val); cond.set_no_action(); _GLIBCXX_DEBUG_ONLY(debug_base::insert_new(PB_DS_V2F(r_val));) init_entry_metadata(p_l, s_metadata_type_indicator); return p_l; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::entry_pointer PB_DS_CLASS_C_DEC:: allocate_new_entry(const_reference r_val, true_type) { entry_pointer p_l = s_entry_allocator.allocate(1); new (&p_l->m_value) value_type(r_val); _GLIBCXX_DEBUG_ONLY(debug_base::insert_new(PB_DS_V2F(r_val));) init_entry_metadata(p_l, s_metadata_type_indicator); return p_l; } PB_DS_CLASS_T_DEC template inline void PB_DS_CLASS_C_DEC:: init_entry_metadata(entry_pointer p_l, type_to_type) { new (&p_l->m_update_metadata) Metadata(s_update_policy()); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: init_entry_metadata(entry_pointer, type_to_type) { } PK!Ԯ_ 98/ext/pb_ds/detail/list_update_map_/iterators_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file list_update_map_/iterators_fn_imps.hpp * Contains implementations of lu_map_. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: begin() { if (m_p_l == 0) { _GLIBCXX_DEBUG_ASSERT(empty()); return end(); } return iterator(&m_p_l->m_value, m_p_l, this); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: begin() const { if (m_p_l == 0) { _GLIBCXX_DEBUG_ASSERT(empty()); return end(); } return iterator(&m_p_l->m_value, m_p_l, const_cast(this)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: end() { return iterator(0, 0, this); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: end() const { return const_iterator(0, 0, const_cast(this)); } PK!dX((/8/ext/pb_ds/detail/list_update_map_/lu_map_.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file list_update_map_/lu_map_.hpp * Contains a list update map. */ #include #include #include #include #include #include #include #ifdef _GLIBCXX_DEBUG #include #endif #ifdef PB_DS_LU_MAP_TRACE_ #include #endif #include namespace __gnu_pbds { namespace detail { #ifdef PB_DS_DATA_TRUE_INDICATOR #define PB_DS_LU_NAME lu_map #endif #ifdef PB_DS_DATA_FALSE_INDICATOR #define PB_DS_LU_NAME lu_set #endif #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ PB_DS_LU_NAME #define PB_DS_LU_TRAITS_BASE \ types_traits #ifdef _GLIBCXX_DEBUG #define PB_DS_DEBUG_MAP_BASE_C_DEC \ debug_map_base::other::const_reference> #endif /// list-based (with updates) associative container. /// Skip to the lu, my darling. template class PB_DS_LU_NAME : #ifdef _GLIBCXX_DEBUG protected PB_DS_DEBUG_MAP_BASE_C_DEC, #endif public PB_DS_LU_TRAITS_BASE { private: typedef PB_DS_LU_TRAITS_BASE traits_base; struct entry : public lu_map_entry_metadata_base { typename traits_base::value_type m_value; typename _Alloc::template rebind::other::pointer m_p_next; }; typedef typename _Alloc::template rebind::other entry_allocator; typedef typename entry_allocator::pointer entry_pointer; typedef typename entry_allocator::const_pointer const_entry_pointer; typedef typename entry_allocator::reference entry_reference; typedef typename entry_allocator::const_reference const_entry_reference; typedef typename _Alloc::template rebind::other entry_pointer_allocator; typedef typename entry_pointer_allocator::pointer entry_pointer_array; typedef typename traits_base::value_type value_type_; typedef typename traits_base::pointer pointer_; typedef typename traits_base::const_pointer const_pointer_; typedef typename traits_base::reference reference_; typedef typename traits_base::const_reference const_reference_; #define PB_DS_GEN_POS entry_pointer #include #include #include #include #undef PB_DS_GEN_POS #ifdef _GLIBCXX_DEBUG typedef PB_DS_DEBUG_MAP_BASE_C_DEC debug_base; #endif typedef cond_dealtor cond_dealtor_t; public: typedef _Alloc allocator_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef Eq_Fn eq_fn; typedef Update_Policy update_policy; typedef typename Update_Policy::metadata_type update_metadata; typedef typename traits_base::key_type key_type; typedef typename traits_base::key_pointer key_pointer; typedef typename traits_base::key_const_pointer key_const_pointer; typedef typename traits_base::key_reference key_reference; typedef typename traits_base::key_const_reference key_const_reference; typedef typename traits_base::mapped_type mapped_type; typedef typename traits_base::mapped_pointer mapped_pointer; typedef typename traits_base::mapped_const_pointer mapped_const_pointer; typedef typename traits_base::mapped_reference mapped_reference; typedef typename traits_base::mapped_const_reference mapped_const_reference; typedef typename traits_base::value_type value_type; typedef typename traits_base::pointer pointer; typedef typename traits_base::const_pointer const_pointer; typedef typename traits_base::reference reference; typedef typename traits_base::const_reference const_reference; #ifdef PB_DS_DATA_TRUE_INDICATOR typedef point_iterator_ point_iterator; #endif #ifdef PB_DS_DATA_FALSE_INDICATOR typedef point_const_iterator_ point_iterator; #endif typedef point_const_iterator_ point_const_iterator; #ifdef PB_DS_DATA_TRUE_INDICATOR typedef iterator_ iterator; #endif #ifdef PB_DS_DATA_FALSE_INDICATOR typedef const_iterator_ iterator; #endif typedef const_iterator_ const_iterator; public: PB_DS_LU_NAME(); PB_DS_LU_NAME(const PB_DS_CLASS_C_DEC&); virtual ~PB_DS_LU_NAME(); template PB_DS_LU_NAME(It, It); void swap(PB_DS_CLASS_C_DEC&); inline size_type size() const; inline size_type max_size() const; inline bool empty() const; inline mapped_reference operator[](key_const_reference r_key) { #ifdef PB_DS_DATA_TRUE_INDICATOR _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) return insert(std::make_pair(r_key, mapped_type())).first->second; #else insert(r_key); return traits_base::s_null_type; #endif } inline std::pair insert(const_reference); inline point_iterator find(key_const_reference r_key) { _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) entry_pointer p_e = find_imp(r_key); return point_iterator(p_e == 0 ? 0: &p_e->m_value); } inline point_const_iterator find(key_const_reference r_key) const { _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) entry_pointer p_e = find_imp(r_key); return point_const_iterator(p_e == 0 ? 0: &p_e->m_value); } inline bool erase(key_const_reference); template inline size_type erase_if(Pred); void clear(); inline iterator begin(); inline const_iterator begin() const; inline iterator end(); inline const_iterator end() const; #ifdef _GLIBCXX_DEBUG void assert_valid(const char* file, int line) const; #endif #ifdef PB_DS_LU_MAP_TRACE_ void trace() const; #endif protected: template void copy_from_range(It, It); private: #ifdef PB_DS_DATA_TRUE_INDICATOR friend class iterator_; #endif friend class const_iterator_; inline entry_pointer allocate_new_entry(const_reference, false_type); inline entry_pointer allocate_new_entry(const_reference, true_type); template inline static void init_entry_metadata(entry_pointer, type_to_type); inline static void init_entry_metadata(entry_pointer, type_to_type); void deallocate_all(); void erase_next(entry_pointer); void actual_erase_entry(entry_pointer); void inc_it_state(const_pointer& r_p_value, entry_pointer& r_pos) const { r_pos = r_pos->m_p_next; r_p_value = (r_pos == 0) ? 0 : &r_pos->m_value; } template inline static bool apply_update(entry_pointer, type_to_type); inline static bool apply_update(entry_pointer, type_to_type); inline entry_pointer find_imp(key_const_reference) const; static entry_allocator s_entry_allocator; static Eq_Fn s_eq_fn; static Update_Policy s_update_policy; static type_to_type s_metadata_type_indicator; static null_type s_null_type; mutable entry_pointer m_p_l; }; #include #include #include #include #include #include #include #include #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #undef PB_DS_LU_TRAITS_BASE #undef PB_DS_DEBUG_MAP_BASE_C_DEC #undef PB_DS_LU_NAME } // namespace detail } // namespace __gnu_pbds PK!U|58/ext/pb_ds/detail/list_update_map_/trace_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file list_update_map_/trace_fn_imps.hpp * Contains implementations of lu_map_. */ #ifdef PB_DS_LU_MAP_TRACE_ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace() const { std::cerr << m_p_l << std::endl << std::endl; const_entry_pointer p_l = m_p_l; while (p_l != 0) { std::cerr << PB_DS_V2F(p_l->m_value) << std::endl; p_l = p_l->m_p_next; } std::cerr << std::endl; } #endif PK!]B" " =8/ext/pb_ds/detail/list_update_policy/lu_counter_metadata.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file lu_counter_metadata.hpp * Contains implementation of a lu counter policy's metadata. */ namespace __gnu_pbds { namespace detail { template class lu_counter_policy_base; /// A list-update metadata type that moves elements to the front of /// the list based on the counter algorithm. template class lu_counter_metadata { public: typedef Size_Type size_type; private: lu_counter_metadata(size_type init_count) : m_count(init_count) { } friend class lu_counter_policy_base; mutable size_type m_count; }; /// Base class for list-update counter policy. template class lu_counter_policy_base { protected: typedef Size_Type size_type; lu_counter_metadata operator()(size_type max_size) const { return lu_counter_metadata(std::rand() % max_size); } template bool operator()(Metadata_Reference r_data, size_type m_max_count) const { if (++r_data.m_count != m_max_count) return false; r_data.m_count = 0; return true; } }; } // namespace detail } // namespace __gnu_pbds PK!#Bp p >8/ext/pb_ds/detail/list_update_policy/sample_update_policy.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file sample_update_policy.hpp * Contains a sample policy for list update containers. */ #ifndef PB_DS_SAMPLE_UPDATE_POLICY_HPP #define PB_DS_SAMPLE_UPDATE_POLICY_HPP namespace __gnu_pbds { /// A sample list-update policy. struct sample_update_policy { /// Default constructor. sample_update_policy(); /// Copy constructor. sample_update_policy(const sample_update_policy&); /// Swaps content. inline void swap(sample_update_policy& other); protected: /// Metadata on which this functor operates. typedef some_metadata_type metadata_type; /// Creates a metadata object. metadata_type operator()() const; /// Decides whether a metadata object should be moved to the front /// of the list. A list-update based containers object will call /// this method to decide whether to move a node to the front of /// the list. The method shoule return true if the node should be /// moved to the front of the list. bool operator()(metadata_reference) const; }; } #endif PK!7/C8/ext/pb_ds/detail/ov_tree_map_/constructors_destructor_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file ov_tree_map_/constructors_destructor_fn_imps.hpp * Contains an implementation class for ov_tree_. */ PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::value_allocator PB_DS_CLASS_C_DEC::s_value_alloc; PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::metadata_allocator PB_DS_CLASS_C_DEC::s_metadata_alloc; PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_OV_TREE_NAME() : m_a_values(0), m_a_metadata(0), m_end_it(0), m_size(0) { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_OV_TREE_NAME(const Cmp_Fn& r_cmp_fn) : cmp_fn(r_cmp_fn), m_a_values(0), m_a_metadata(0), m_end_it(0), m_size(0) { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_OV_TREE_NAME(const Cmp_Fn& r_cmp_fn, const node_update& r_nodeu) : cmp_fn(r_cmp_fn), node_update(r_nodeu), m_a_values(0), m_a_metadata(0), m_end_it(0), m_size(0) { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_OV_TREE_NAME(const PB_DS_CLASS_C_DEC& other) : #ifdef PB_DS_TREE_TRACE trace_base(other), #endif cmp_fn(other), node_update(other), m_a_values(0), m_a_metadata(0), m_end_it(0), m_size(0) { copy_from_ordered_range(other.begin(), other.end()); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC template inline void PB_DS_CLASS_C_DEC:: copy_from_range(It first_it, It last_it) { #ifdef PB_DS_DATA_TRUE_INDICATOR typedef std::map::other> map_type; #else typedef std::set::other> map_type; #endif map_type m(first_it, last_it); copy_from_ordered_range(m.begin(), m.end()); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: copy_from_ordered_range(It first_it, It last_it) { const size_type len = std::distance(first_it, last_it); if (len == 0) return; value_vector a_values = s_value_alloc.allocate(len); iterator target_it = a_values; It source_it = first_it; It source_end_it = last_it; cond_dtor cd(a_values, target_it, len); while (source_it != source_end_it) { void* __v = const_cast(static_cast(target_it)); new (__v) value_type(*source_it++); ++target_it; } reallocate_metadata((node_update*)this, len); cd.set_no_action(); m_a_values = a_values; m_size = len; m_end_it = m_a_values + m_size; update(PB_DS_node_begin_imp(), (node_update*)this); #ifdef _GLIBCXX_DEBUG for (const_iterator dbg_it = m_a_values; dbg_it != m_end_it; ++dbg_it) debug_base::insert_new(PB_DS_V2F(*dbg_it)); #endif } PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: copy_from_ordered_range(It first_it, It last_it, It other_first_it, It other_last_it) { clear(); const size_type len = std::distance(first_it, last_it) + std::distance(other_first_it, other_last_it); value_vector a_values = s_value_alloc.allocate(len); iterator target_it = a_values; It source_it = first_it; It source_end_it = last_it; cond_dtor cd(a_values, target_it, len); while (source_it != source_end_it) { new (const_cast(static_cast(target_it))) value_type(*source_it++); ++target_it; } source_it = other_first_it; source_end_it = other_last_it; while (source_it != source_end_it) { new (const_cast(static_cast(target_it))) value_type(*source_it++); ++target_it; } reallocate_metadata((node_update* )this, len); cd.set_no_action(); m_a_values = a_values; m_size = len; m_end_it = m_a_values + m_size; update(PB_DS_node_begin_imp(), (node_update* )this); #ifdef _GLIBCXX_DEBUG for (const_iterator dbg_it = m_a_values; dbg_it != m_end_it; ++dbg_it) debug_base::insert_new(PB_DS_V2F(*dbg_it)); #endif } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) value_swap(other); std::swap(static_cast(*this), static_cast(other)); std::swap(static_cast(*this), static_cast(other)); PB_DS_ASSERT_VALID(other) PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: value_swap(PB_DS_CLASS_C_DEC& other) { _GLIBCXX_DEBUG_ONLY(debug_base::swap(other);) std::swap(m_a_values, other.m_a_values); std::swap(m_a_metadata, other.m_a_metadata); std::swap(m_size, other.m_size); std::swap(m_end_it, other.m_end_it); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~PB_DS_OV_TREE_NAME() { PB_DS_ASSERT_VALID((*this)) cond_dtor cd(m_a_values, m_end_it, m_size); reallocate_metadata((node_update*)this, 0); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: update(node_iterator, null_node_update_pointer) { } PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: update(node_iterator nd_it, Node_Update* p_update) { node_const_iterator end_it = PB_DS_node_end_imp(); if (nd_it != end_it) { update(nd_it.get_l_child(), p_update); update(nd_it.get_r_child(), p_update); node_update::operator()(nd_it, end_it); } } PK!&;  18/ext/pb_ds/detail/ov_tree_map_/debug_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file ov_tree_map_/debug_fn_imps.hpp * Contains an implementation class for ov_tree_. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { if (m_a_values == 0 || m_end_it == 0 || m_size == 0) PB_DS_DEBUG_VERIFY(m_a_values == 0 && m_end_it == 0 && m_size == 0); assert_iterators(__file, __line); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_iterators(const char* __file, int __line) const { debug_base::check_size(m_size, __file, __line); size_type iterated_num = 0; const_iterator prev_it = end(); PB_DS_DEBUG_VERIFY(m_end_it == m_a_values + m_size); for (const_iterator it = begin(); it != end(); ++it) { ++iterated_num; debug_base::check_key_exists(PB_DS_V2F(*it), __file, __line); PB_DS_DEBUG_VERIFY(lower_bound(PB_DS_V2F(*it)) == it); const_iterator upper_bound_it = upper_bound(PB_DS_V2F(*it)); --upper_bound_it; PB_DS_DEBUG_VERIFY(upper_bound_it == it); if (prev_it != end()) PB_DS_DEBUG_VERIFY(Cmp_Fn::operator()(PB_DS_V2F(*prev_it), PB_DS_V2F(*it))); prev_it = it; } PB_DS_DEBUG_VERIFY(iterated_num == m_size); } #endif PK!k1_tuu18/ext/pb_ds/detail/ov_tree_map_/erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file ov_tree_map_/erase_fn_imps.hpp * Contains an implementation class for ov_tree_. */ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear() { PB_DS_ASSERT_VALID((*this)) if (m_size == 0) { return; } else { reallocate_metadata((node_update* )this, 0); cond_dtor cd(m_a_values, m_end_it, m_size); } _GLIBCXX_DEBUG_ONLY(debug_base::clear();) m_a_values = 0; m_size = 0; m_end_it = m_a_values; PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC template inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: erase_if(Pred pred) { PB_DS_ASSERT_VALID((*this)) #ifdef PB_DS_REGRESSION typename _Alloc::group_adjustor adjust(m_size); #endif size_type new_size = 0; size_type num_val_ersd = 0; for (iterator source_it = begin(); source_it != m_end_it; ++source_it) if (!pred(*source_it)) ++new_size; else ++num_val_ersd; if (new_size == 0) { clear(); return num_val_ersd; } value_vector a_new_values = s_value_alloc.allocate(new_size); iterator target_it = a_new_values; cond_dtor cd(a_new_values, target_it, new_size); _GLIBCXX_DEBUG_ONLY(debug_base::clear()); for (iterator source_it = begin(); source_it != m_end_it; ++source_it) { if (!pred(*source_it)) { new (const_cast(static_cast(target_it))) value_type(*source_it); _GLIBCXX_DEBUG_ONLY(debug_base::insert_new(PB_DS_V2F(*source_it))); ++target_it; } } reallocate_metadata((node_update*)this, new_size); cd.set_no_action(); { cond_dtor cd1(m_a_values, m_end_it, m_size); } m_a_values = a_new_values; m_size = new_size; m_end_it = target_it; update(node_begin(), (node_update*)this); PB_DS_ASSERT_VALID((*this)) return num_val_ersd; } PB_DS_CLASS_T_DEC template It PB_DS_CLASS_C_DEC:: erase_imp(It it) { PB_DS_ASSERT_VALID((*this)) if (it == end()) return end(); PB_DS_CHECK_KEY_EXISTS(PB_DS_V2F(*it)) #ifdef PB_DS_REGRESSION typename _Alloc::group_adjustor adjust(m_size); #endif _GLIBCXX_DEBUG_ASSERT(m_size > 0); value_vector a_values = s_value_alloc.allocate(m_size - 1); iterator source_it = begin(); iterator source_end_it = end(); iterator target_it = a_values; iterator ret_it = end(); cond_dtor cd(a_values, target_it, m_size - 1); _GLIBCXX_DEBUG_ONLY(size_type cnt = 0;) while (source_it != source_end_it) { if (source_it != it) { _GLIBCXX_DEBUG_ONLY(++cnt;) _GLIBCXX_DEBUG_ASSERT(cnt != m_size); new (const_cast(static_cast(target_it))) value_type(*source_it); ++target_it; } else ret_it = target_it; ++source_it; } _GLIBCXX_DEBUG_ASSERT(m_size > 0); reallocate_metadata((node_update*)this, m_size - 1); cd.set_no_action(); _GLIBCXX_DEBUG_ONLY(debug_base::erase_existing(PB_DS_V2F(*it));) { cond_dtor cd1(m_a_values, m_end_it, m_size); } m_a_values = a_values; --m_size; m_end_it = m_a_values + m_size; update(node_begin(), (node_update*)this); PB_DS_ASSERT_VALID((*this)) return It(ret_it); } PB_DS_CLASS_T_DEC bool PB_DS_CLASS_C_DEC:: erase(key_const_reference r_key) { point_iterator it = find(r_key); if (it == end()) return false; erase(it); return true; } PK!cC$$08/ext/pb_ds/detail/ov_tree_map_/info_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file ov_tree_map_/info_fn_imps.hpp * Contains an implementation class for ov_tree_. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: size() const { PB_DS_ASSERT_VALID((*this)) return m_size; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: max_size() const { return s_value_alloc.max_size(); } PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: empty() const { return size() == 0; } PK![>m 28/ext/pb_ds/detail/ov_tree_map_/insert_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file ov_tree_map_/insert_fn_imps.hpp * Contains an implementation class for ov_tree_. */ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: reallocate_metadata(null_node_update_pointer, size_type) { } PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: reallocate_metadata(Node_Update_* , size_type new_size) { metadata_pointer a_new_metadata_vec =(new_size == 0) ? 0 : s_metadata_alloc.allocate(new_size); if (m_a_metadata != 0) { for (size_type i = 0; i < m_size; ++i) m_a_metadata[i].~metadata_type(); s_metadata_alloc.deallocate(m_a_metadata, m_size); } std::swap(m_a_metadata, a_new_metadata_vec); } PK!m?! ! 58/ext/pb_ds/detail/ov_tree_map_/iterators_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file ov_tree_map_/iterators_fn_imps.hpp * Contains an implementation class for ov_tree_. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_const_iterator PB_DS_CLASS_C_DEC:: node_begin() const { return PB_DS_node_begin_imp(); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_const_iterator PB_DS_CLASS_C_DEC:: node_end() const { return PB_DS_node_end_imp(); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_iterator PB_DS_CLASS_C_DEC:: node_begin() { return PB_DS_node_begin_imp(); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_iterator PB_DS_CLASS_C_DEC:: node_end() { return PB_DS_node_end_imp(); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_const_iterator PB_DS_CLASS_C_DEC:: PB_DS_node_begin_imp() const { return node_const_iterator(const_cast(mid_pointer(begin(), end())), const_cast(begin()), const_cast(end()),(m_a_metadata == 0)? 0 : mid_pointer(m_a_metadata, m_a_metadata + m_size)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_const_iterator PB_DS_CLASS_C_DEC:: PB_DS_node_end_imp() const { return node_const_iterator(end(), end(), end(), (m_a_metadata == 0) ? 0 : m_a_metadata + m_size); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_iterator PB_DS_CLASS_C_DEC:: PB_DS_node_begin_imp() { return node_iterator(mid_pointer(begin(), end()), begin(), end(), (m_a_metadata == 0) ? 0 : mid_pointer(m_a_metadata, m_a_metadata + m_size)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_iterator PB_DS_CLASS_C_DEC:: PB_DS_node_end_imp() { return node_iterator(end(), end(), end(),(m_a_metadata == 0) ? 0 : m_a_metadata + m_size); } PK! k"k"28/ext/pb_ds/detail/ov_tree_map_/node_iterators.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file ov_tree_map_/node_iterators.hpp * Contains an implementation class for ov_tree_. */ #ifndef PB_DS_OV_TREE_NODE_ITERATORS_HPP #define PB_DS_OV_TREE_NODE_ITERATORS_HPP #include #include #include namespace __gnu_pbds { namespace detail { #define PB_DS_OV_TREE_CONST_NODE_ITERATOR_C_DEC \ ov_tree_node_const_it_ /// Const node reference. template class ov_tree_node_const_it_ { protected: typedef typename _Alloc::template rebind< Value_Type>::other::pointer pointer; typedef typename _Alloc::template rebind< Value_Type>::other::const_pointer const_pointer; typedef typename _Alloc::template rebind< Metadata_Type>::other::const_pointer const_metadata_pointer; typedef PB_DS_OV_TREE_CONST_NODE_ITERATOR_C_DEC this_type; protected: template inline static Ptr mid_pointer(Ptr p_begin, Ptr p_end) { _GLIBCXX_DEBUG_ASSERT(p_end >= p_begin); return (p_begin + (p_end - p_begin) / 2); } public: typedef trivial_iterator_tag iterator_category; typedef trivial_iterator_difference_type difference_type; typedef typename _Alloc::template rebind< Value_Type>::other::const_pointer value_type; typedef typename _Alloc::template rebind< typename remove_const< Value_Type>::type>::other::const_pointer reference; typedef typename _Alloc::template rebind< typename remove_const< Value_Type>::type>::other::const_pointer const_reference; typedef Metadata_Type metadata_type; typedef typename _Alloc::template rebind< metadata_type>::other::const_reference metadata_const_reference; public: inline ov_tree_node_const_it_(const_pointer p_nd = 0, const_pointer p_begin_nd = 0, const_pointer p_end_nd = 0, const_metadata_pointer p_metadata = 0) : m_p_value(const_cast(p_nd)), m_p_begin_value(const_cast(p_begin_nd)), m_p_end_value(const_cast(p_end_nd)), m_p_metadata(p_metadata) { } inline const_reference operator*() const { return m_p_value; } inline metadata_const_reference get_metadata() const { enum { has_metadata = !is_same::value }; PB_DS_STATIC_ASSERT(should_have_metadata, has_metadata); _GLIBCXX_DEBUG_ASSERT(m_p_metadata != 0); return *m_p_metadata; } /// Returns the node iterator associated with the left node. inline this_type get_l_child() const { if (m_p_begin_value == m_p_value) return (this_type(m_p_begin_value, m_p_begin_value, m_p_begin_value)); const_metadata_pointer p_begin_metadata = m_p_metadata - (m_p_value - m_p_begin_value); return (this_type(mid_pointer(m_p_begin_value, m_p_value), m_p_begin_value, m_p_value, mid_pointer(p_begin_metadata, m_p_metadata))); } /// Returns the node iterator associated with the right node. inline this_type get_r_child() const { if (m_p_value == m_p_end_value) return (this_type(m_p_end_value, m_p_end_value, m_p_end_value)); const_metadata_pointer p_end_metadata = m_p_metadata + (m_p_end_value - m_p_value); return (this_type(mid_pointer(m_p_value + 1, m_p_end_value), m_p_value + 1, m_p_end_value,(m_p_metadata == 0) ? 0 : mid_pointer(m_p_metadata + 1, p_end_metadata))); } inline bool operator==(const this_type& other) const { const bool is_end = m_p_begin_value == m_p_end_value; const bool is_other_end = other.m_p_begin_value == other.m_p_end_value; if (is_end) return (is_other_end); if (is_other_end) return (is_end); return m_p_value == other.m_p_value; } inline bool operator!=(const this_type& other) const { return !operator==(other); } public: pointer m_p_value; pointer m_p_begin_value; pointer m_p_end_value; const_metadata_pointer m_p_metadata; }; #define PB_DS_OV_TREE_NODE_ITERATOR_C_DEC \ ov_tree_node_it_ /// Node reference. template class ov_tree_node_it_ : public PB_DS_OV_TREE_CONST_NODE_ITERATOR_C_DEC { private: typedef PB_DS_OV_TREE_NODE_ITERATOR_C_DEC this_type; typedef PB_DS_OV_TREE_CONST_NODE_ITERATOR_C_DEC base_type; typedef typename base_type::pointer pointer; typedef typename base_type::const_pointer const_pointer; typedef typename base_type::const_metadata_pointer const_metadata_pointer; public: typedef trivial_iterator_tag iterator_category; typedef trivial_iterator_difference_type difference_type; typedef typename _Alloc::template rebind< Value_Type>::other::pointer value_type; typedef typename _Alloc::template rebind< typename remove_const< Value_Type>::type>::other::pointer reference; typedef typename _Alloc::template rebind< typename remove_const< Value_Type>::type>::other::pointer const_reference; inline ov_tree_node_it_(const_pointer p_nd = 0, const_pointer p_begin_nd = 0, const_pointer p_end_nd = 0, const_metadata_pointer p_metadata = 0) : base_type(p_nd, p_begin_nd, p_end_nd, p_metadata) { } /// Access. inline reference operator*() const { return reference(base_type::m_p_value); } /// Returns the node reference associated with the left node. inline ov_tree_node_it_ get_l_child() const { if (base_type::m_p_begin_value == base_type::m_p_value) return (this_type(base_type::m_p_begin_value, base_type::m_p_begin_value, base_type::m_p_begin_value)); const_metadata_pointer p_begin_metadata = base_type::m_p_metadata - (base_type::m_p_value - base_type::m_p_begin_value); return (this_type(base_type::mid_pointer(base_type::m_p_begin_value, base_type::m_p_value), base_type::m_p_begin_value, base_type::m_p_value, base_type::mid_pointer(p_begin_metadata, base_type::m_p_metadata))); } /// Returns the node reference associated with the right node. inline ov_tree_node_it_ get_r_child() const { if (base_type::m_p_value == base_type::m_p_end_value) return this_type(base_type::m_p_end_value, base_type::m_p_end_value, base_type::m_p_end_value); const_metadata_pointer p_end_metadata = base_type::m_p_metadata + (base_type::m_p_end_value - base_type::m_p_value); return (this_type(base_type::mid_pointer(base_type::m_p_value + 1, base_type::m_p_end_value), base_type::m_p_value + 1, base_type::m_p_end_value,(base_type::m_p_metadata == 0)? 0 : base_type::mid_pointer(base_type::m_p_metadata + 1, p_end_metadata))); } }; #undef PB_DS_OV_TREE_NODE_ITERATOR_C_DEC #undef PB_DS_OV_TREE_CONST_NODE_ITERATOR_C_DEC } // namespace detail } // namespace __gnu_pbds #endif PK!}$<<08/ext/pb_ds/detail/ov_tree_map_/ov_tree_map_.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file ov_tree_map_/ov_tree_map_.hpp * Contains an implementation class for ov_tree. */ #include #include #include #include #include #include #include #include #ifdef _GLIBCXX_DEBUG #include #endif #include #include #include #include #include #include namespace __gnu_pbds { namespace detail { #ifdef PB_DS_DATA_TRUE_INDICATOR #define PB_DS_OV_TREE_NAME ov_tree_map #define PB_DS_CONST_NODE_ITERATOR_NAME ov_tree_node_const_iterator_map #endif #ifdef PB_DS_DATA_FALSE_INDICATOR #define PB_DS_OV_TREE_NAME ov_tree_set #define PB_DS_CONST_NODE_ITERATOR_NAME ov_tree_node_const_iterator_set #endif #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ PB_DS_OV_TREE_NAME #define PB_DS_OV_TREE_TRAITS_BASE \ types_traits #ifdef _GLIBCXX_DEBUG #define PB_DS_DEBUG_MAP_BASE_C_DEC \ debug_map_base, \ typename _Alloc::template rebind::other::const_reference> #endif #ifdef PB_DS_TREE_TRACE #define PB_DS_TREE_TRACE_BASE_C_DEC \ tree_trace_base #endif #ifndef PB_DS_CHECK_KEY_EXISTS # error Missing definition #endif /** * @brief Ordered-vector tree associative-container. * @ingroup branch-detail */ template class PB_DS_OV_TREE_NAME : #ifdef _GLIBCXX_DEBUG protected PB_DS_DEBUG_MAP_BASE_C_DEC, #endif #ifdef PB_DS_TREE_TRACE public PB_DS_TREE_TRACE_BASE_C_DEC, #endif public Cmp_Fn, public Node_And_It_Traits::node_update, public PB_DS_OV_TREE_TRAITS_BASE { private: typedef PB_DS_OV_TREE_TRAITS_BASE traits_base; typedef Node_And_It_Traits traits_type; typedef typename remove_const::type non_const_value_type; typedef typename _Alloc::template rebind::other value_allocator; typedef typename value_allocator::pointer value_vector; #ifdef _GLIBCXX_DEBUG typedef PB_DS_DEBUG_MAP_BASE_C_DEC debug_base; #endif #ifdef PB_DS_TREE_TRACE typedef PB_DS_TREE_TRACE_BASE_C_DEC trace_base; #endif typedef typename traits_base::pointer mapped_pointer_; typedef typename traits_base::const_pointer mapped_const_pointer_; typedef typename traits_type::metadata_type metadata_type; typedef typename _Alloc::template rebind::other metadata_allocator; typedef typename metadata_allocator::pointer metadata_pointer; typedef typename metadata_allocator::const_reference metadata_const_reference; typedef typename metadata_allocator::reference metadata_reference; typedef typename traits_type::null_node_update_pointer null_node_update_pointer; public: typedef ov_tree_tag container_category; typedef _Alloc allocator_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef Cmp_Fn cmp_fn; typedef typename traits_base::key_type key_type; typedef typename traits_base::key_pointer key_pointer; typedef typename traits_base::key_const_pointer key_const_pointer; typedef typename traits_base::key_reference key_reference; typedef typename traits_base::key_const_reference key_const_reference; typedef typename traits_base::mapped_type mapped_type; typedef typename traits_base::mapped_pointer mapped_pointer; typedef typename traits_base::mapped_const_pointer mapped_const_pointer; typedef typename traits_base::mapped_reference mapped_reference; typedef typename traits_base::mapped_const_reference mapped_const_reference; typedef typename traits_base::value_type value_type; typedef typename traits_base::pointer pointer; typedef typename traits_base::const_pointer const_pointer; typedef typename traits_base::reference reference; typedef typename traits_base::const_reference const_reference; typedef const_pointer point_const_iterator; #ifdef PB_DS_DATA_TRUE_INDICATOR typedef pointer point_iterator; #else typedef point_const_iterator point_iterator; #endif typedef point_iterator iterator; typedef point_const_iterator const_iterator; /// Conditional destructor. template class cond_dtor { public: cond_dtor(value_vector a_vec, iterator& r_last_it, Size_Type total_size) : m_a_vec(a_vec), m_r_last_it(r_last_it), m_max_size(total_size), m_no_action(false) { } ~cond_dtor() { if (m_no_action) return; iterator it = m_a_vec; while (it != m_r_last_it) { it->~value_type(); ++it; } if (m_max_size > 0) value_allocator().deallocate(m_a_vec, m_max_size); } inline void set_no_action() { m_no_action = true; } protected: value_vector m_a_vec; iterator& m_r_last_it; const Size_Type m_max_size; bool m_no_action; }; typedef typename traits_type::node_update node_update; typedef typename traits_type::node_iterator node_iterator; typedef typename traits_type::node_const_iterator node_const_iterator; PB_DS_OV_TREE_NAME(); PB_DS_OV_TREE_NAME(const Cmp_Fn&); PB_DS_OV_TREE_NAME(const Cmp_Fn&, const node_update&); PB_DS_OV_TREE_NAME(const PB_DS_CLASS_C_DEC&); ~PB_DS_OV_TREE_NAME(); void swap(PB_DS_CLASS_C_DEC&); template void copy_from_range(It, It); inline size_type max_size() const; inline bool empty() const; inline size_type size() const; Cmp_Fn& get_cmp_fn(); const Cmp_Fn& get_cmp_fn() const; inline mapped_reference operator[](key_const_reference r_key) { #ifdef PB_DS_DATA_TRUE_INDICATOR PB_DS_ASSERT_VALID((*this)) point_iterator it = lower_bound(r_key); if (it != end() && !Cmp_Fn::operator()(r_key, PB_DS_V2F(*it))) { PB_DS_CHECK_KEY_EXISTS(r_key) PB_DS_ASSERT_VALID((*this)) return it->second; } return insert_new_val(it, std::make_pair(r_key, mapped_type()))->second; #else insert(r_key); return traits_base::s_null_type; #endif } inline std::pair insert(const_reference r_value) { PB_DS_ASSERT_VALID((*this)) key_const_reference r_key = PB_DS_V2F(r_value); point_iterator it = lower_bound(r_key); if (it != end()&& !Cmp_Fn::operator()(r_key, PB_DS_V2F(*it))) { PB_DS_ASSERT_VALID((*this)) PB_DS_CHECK_KEY_EXISTS(r_key) return std::make_pair(it, false); } return std::make_pair(insert_new_val(it, r_value), true); } inline point_iterator lower_bound(key_const_reference r_key) { pointer it = m_a_values; pointer e_it = m_a_values + m_size; while (it != e_it) { pointer mid_it = it + ((e_it - it) >> 1); if (cmp_fn::operator()(PB_DS_V2F(*mid_it), r_key)) it = ++mid_it; else e_it = mid_it; } return it; } inline point_const_iterator lower_bound(key_const_reference r_key) const { return const_cast(*this).lower_bound(r_key); } inline point_iterator upper_bound(key_const_reference r_key) { iterator pot_it = lower_bound(r_key); if (pot_it != end() && !Cmp_Fn::operator()(r_key, PB_DS_V2F(*pot_it))) { PB_DS_CHECK_KEY_EXISTS(r_key) return ++pot_it; } PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return pot_it; } inline point_const_iterator upper_bound(key_const_reference r_key) const { return const_cast(*this).upper_bound(r_key); } inline point_iterator find(key_const_reference r_key) { PB_DS_ASSERT_VALID((*this)) iterator pot_it = lower_bound(r_key); if (pot_it != end() && !Cmp_Fn::operator()(r_key, PB_DS_V2F(*pot_it))) { PB_DS_CHECK_KEY_EXISTS(r_key) return pot_it; } PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return end(); } inline point_const_iterator find(key_const_reference r_key) const { return (const_cast(*this).find(r_key)); } bool erase(key_const_reference); template inline size_type erase_if(Pred); inline iterator erase(iterator it) { return erase_imp(it); } void clear(); void join(PB_DS_CLASS_C_DEC&); void split(key_const_reference, PB_DS_CLASS_C_DEC&); inline iterator begin() { return m_a_values; } inline const_iterator begin() const { return m_a_values; } inline iterator end() { return m_end_it; } inline const_iterator end() const { return m_end_it; } /// Returns a const node_iterator corresponding to the node at the /// root of the tree. inline node_const_iterator node_begin() const; /// Returns a node_iterator corresponding to the node at the /// root of the tree. inline node_iterator node_begin(); /// Returns a const node_iterator corresponding to a node just /// after a leaf of the tree. inline node_const_iterator node_end() const; /// Returns a node_iterator corresponding to a node just /// after a leaf of the tree. inline node_iterator node_end(); private: inline void update(node_iterator, null_node_update_pointer); template void update(node_iterator, Node_Update*); void reallocate_metadata(null_node_update_pointer, size_type); template void reallocate_metadata(Node_Update_*, size_type); template void copy_from_ordered_range(It, It); void value_swap(PB_DS_CLASS_C_DEC&); template void copy_from_ordered_range(It, It, It, It); template inline static Ptr mid_pointer(Ptr p_begin, Ptr p_end) { _GLIBCXX_DEBUG_ASSERT(p_end >= p_begin); return (p_begin + (p_end - p_begin) / 2); } inline iterator insert_new_val(iterator it, const_reference r_value) { #ifdef PB_DS_REGRESSION typename _Alloc::group_adjustor adjust(m_size); #endif PB_DS_CHECK_KEY_DOES_NOT_EXIST(PB_DS_V2F(r_value)) value_vector a_values = s_value_alloc.allocate(m_size + 1); iterator source_it = begin(); iterator source_end_it = end(); iterator target_it = a_values; iterator ret_it; cond_dtor cd(a_values, target_it, m_size + 1); while (source_it != it) { new (const_cast(static_cast(target_it))) value_type(*source_it++); ++target_it; } new (const_cast(static_cast(ret_it = target_it))) value_type(r_value); ++target_it; while (source_it != source_end_it) { new (const_cast(static_cast(target_it))) value_type(*source_it++); ++target_it; } reallocate_metadata((node_update*)this, m_size + 1); cd.set_no_action(); if (m_size != 0) { cond_dtor cd1(m_a_values, m_end_it, m_size); } ++m_size; m_a_values = a_values; m_end_it = m_a_values + m_size; _GLIBCXX_DEBUG_ONLY(debug_base::insert_new(PB_DS_V2F(r_value))); update(node_begin(), (node_update* )this); PB_DS_ASSERT_VALID((*this)) return ret_it; } #ifdef _GLIBCXX_DEBUG void assert_valid(const char*, int) const; void assert_iterators(const char*, int) const; #endif template It erase_imp(It); inline node_const_iterator PB_DS_node_begin_imp() const; inline node_const_iterator PB_DS_node_end_imp() const; inline node_iterator PB_DS_node_begin_imp(); inline node_iterator PB_DS_node_end_imp(); private: static value_allocator s_value_alloc; static metadata_allocator s_metadata_alloc; value_vector m_a_values; metadata_pointer m_a_metadata; iterator m_end_it; size_type m_size; }; #include #include #include #include #include #include #include #include #undef PB_DS_CLASS_C_DEC #undef PB_DS_CLASS_T_DEC #undef PB_DS_OV_TREE_NAME #undef PB_DS_OV_TREE_TRAITS_BASE #undef PB_DS_DEBUG_MAP_BASE_C_DEC #ifdef PB_DS_TREE_TRACE #undef PB_DS_TREE_TRACE_BASE_C_DEC #endif #undef PB_DS_CONST_NODE_ITERATOR_NAME } // namespace detail } // namespace __gnu_pbds PK!1p__98/ext/pb_ds/detail/ov_tree_map_/policy_access_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file ov_tree_map_/policy_access_fn_imps.hpp * Contains an implementation class for ov_tree. */ PB_DS_CLASS_T_DEC Cmp_Fn& PB_DS_CLASS_C_DEC:: get_cmp_fn() { return *this; } PB_DS_CLASS_T_DEC const Cmp_Fn& PB_DS_CLASS_C_DEC:: get_cmp_fn() const { return *this; } PK!L68/ext/pb_ds/detail/ov_tree_map_/split_join_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file ov_tree_map_/split_join_fn_imps.hpp * Contains an implementation class for ov_tree_. */ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: split(key_const_reference r_key, PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) if (m_size == 0) { other.clear(); return; } if (Cmp_Fn::operator()(r_key, PB_DS_V2F(*begin()))) { value_swap(other); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return; } if (!Cmp_Fn::operator()(r_key, PB_DS_V2F(*(end() - 1)))) { return; } if (m_size == 1) { value_swap(other); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return; } iterator it = upper_bound(r_key); PB_DS_CLASS_C_DEC new_other(other, other); new_other.copy_from_ordered_range(it, end()); PB_DS_CLASS_C_DEC new_this(*this, *this); new_this.copy_from_ordered_range(begin(), it); // No exceptions from this point. other.update(other.node_begin(), (node_update*)(&other)); update(node_begin(), (node_update*)this); other.value_swap(new_other); value_swap(new_this); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: join(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) if (other.m_size == 0) return; if (m_size == 0) { value_swap(other); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return; } const bool greater = Cmp_Fn::operator()(PB_DS_V2F(*(end() - 1)), PB_DS_V2F(*other.begin())); const bool lesser = Cmp_Fn::operator()(PB_DS_V2F(*(other.end() - 1)), PB_DS_V2F(*begin())); if (!greater && !lesser) __throw_join_error(); PB_DS_CLASS_C_DEC new_this(*this, *this); if (greater) new_this.copy_from_ordered_range(begin(), end(), other.begin(), other.end()); else new_this.copy_from_ordered_range(other.begin(), other.end(), begin(), end()); // No exceptions from this point. value_swap(new_this); other.clear(); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PK!4Y*8/ext/pb_ds/detail/ov_tree_map_/traits.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file ov_tree_map_/traits.hpp * Contains an implementation class for ov_tree_. */ #ifndef PB_DS_OV_TREE_NODE_AND_IT_TRAITS_HPP #define PB_DS_OV_TREE_NODE_AND_IT_TRAITS_HPP #include namespace __gnu_pbds { namespace detail { /// Tree traits. /// @ingroup traits template class Node_Update, typename _Alloc> struct tree_traits< Key, Mapped, Cmp_Fn, Node_Update, ov_tree_tag, _Alloc> { private: typedef typename types_traits< Key, Mapped, _Alloc, false>::value_type value_type; public: typedef typename tree_node_metadata_dispatch< Key, Mapped, Cmp_Fn, Node_Update, _Alloc>::type metadata_type; /// This is an iterator to an iterator: it iterates over nodes, /// and de-referencing it returns one of the tree's iterators. typedef ov_tree_node_const_it_< value_type, metadata_type, _Alloc> node_const_iterator; typedef ov_tree_node_it_< value_type, metadata_type, _Alloc> node_iterator; typedef Node_Update< node_const_iterator, node_iterator, Cmp_Fn, _Alloc> node_update; typedef __gnu_pbds::null_node_update< node_const_iterator, node_iterator, Cmp_Fn, _Alloc>* null_node_update_pointer; }; /// Specialization. /// @ingroup traits template class Node_Update, typename _Alloc> struct tree_traits< Key, null_type, Cmp_Fn, Node_Update, ov_tree_tag, _Alloc> { private: typedef typename types_traits< Key, null_type, _Alloc, false>::value_type value_type; public: typedef typename tree_node_metadata_dispatch< Key, null_type, Cmp_Fn, Node_Update, _Alloc>::type metadata_type; /// This is an iterator to an iterator: it iterates over nodes, /// and de-referencing it returns one of the tree's iterators. typedef ov_tree_node_const_it_< value_type, metadata_type, _Alloc> node_const_iterator; typedef node_const_iterator node_iterator; typedef Node_Update< node_const_iterator, node_const_iterator, Cmp_Fn, _Alloc> node_update; typedef __gnu_pbds::null_node_update< node_const_iterator, node_iterator, Cmp_Fn, _Alloc>* null_node_update_pointer; }; } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_OV_TREE_NODE_AND_IT_TRAITS_HPP PK! D8/ext/pb_ds/detail/pairing_heap_/constructors_destructor_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pairing_heap_/constructors_destructor_fn_imps.hpp * Contains an implementation class for a pairing heap. */ PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: copy_from_range(It first_it, It last_it) { while (first_it != last_it) push(*(first_it++)); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: pairing_heap() { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: pairing_heap(const Cmp_Fn& r_cmp_fn) : base_type(r_cmp_fn) { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: pairing_heap(const PB_DS_CLASS_C_DEC& other) : base_type(other) { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) base_type::swap(other); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~pairing_heap() { } PK!1o28/ext/pb_ds/detail/pairing_heap_/debug_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pairing_heap_/debug_fn_imps.hpp * Contains an implementation class for a pairing heap. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { PB_DS_DEBUG_VERIFY(base_type::m_p_root == 0 || base_type::m_p_root->m_p_next_sibling == 0); base_type::assert_valid(__file, __line); } #endif PK!6228/ext/pb_ds/detail/pairing_heap_/erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pairing_heap_/erase_fn_imps.hpp * Contains an implementation class for a pairing heap. */ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: pop() { PB_DS_ASSERT_VALID((*this)) _GLIBCXX_DEBUG_ASSERT(!base_type::empty()); node_pointer p_new_root = join_node_children(base_type::m_p_root); PB_DS_ASSERT_NODE_CONSISTENT(p_new_root, false) if (p_new_root != 0) p_new_root->m_p_prev_or_parent = 0; base_type::actual_erase_node(base_type::m_p_root); base_type::m_p_root = p_new_root; PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: erase(point_iterator it) { PB_DS_ASSERT_VALID((*this)) _GLIBCXX_DEBUG_ASSERT(!base_type::empty()); remove_node(it.m_p_nd); base_type::actual_erase_node(it.m_p_nd); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: remove_node(node_pointer p_nd) { PB_DS_ASSERT_VALID((*this)) _GLIBCXX_DEBUG_ASSERT(!base_type::empty()); node_pointer p_new_child = join_node_children(p_nd); PB_DS_ASSERT_NODE_CONSISTENT(p_new_child, false) if (p_nd == base_type::m_p_root) { if (p_new_child != 0) p_new_child->m_p_prev_or_parent = 0; base_type::m_p_root = p_new_child; PB_DS_ASSERT_NODE_CONSISTENT(base_type::m_p_root, false) return; } _GLIBCXX_DEBUG_ASSERT(p_nd->m_p_prev_or_parent != 0); if (p_nd->m_p_prev_or_parent->m_p_l_child == p_nd) { if (p_new_child != 0) { p_new_child->m_p_prev_or_parent = p_nd->m_p_prev_or_parent; p_new_child->m_p_next_sibling = p_nd->m_p_next_sibling; if (p_new_child->m_p_next_sibling != 0) p_new_child->m_p_next_sibling->m_p_prev_or_parent = p_new_child; p_nd->m_p_prev_or_parent->m_p_l_child = p_new_child; PB_DS_ASSERT_NODE_CONSISTENT(p_nd->m_p_prev_or_parent, false) return; } p_nd->m_p_prev_or_parent->m_p_l_child = p_nd->m_p_next_sibling; if (p_nd->m_p_next_sibling != 0) p_nd->m_p_next_sibling->m_p_prev_or_parent = p_nd->m_p_prev_or_parent; PB_DS_ASSERT_NODE_CONSISTENT(p_nd->m_p_prev_or_parent, false) return; } if (p_new_child != 0) { p_new_child->m_p_prev_or_parent = p_nd->m_p_prev_or_parent; p_new_child->m_p_next_sibling = p_nd->m_p_next_sibling; if (p_new_child->m_p_next_sibling != 0) p_new_child->m_p_next_sibling->m_p_prev_or_parent = p_new_child; p_new_child->m_p_prev_or_parent->m_p_next_sibling = p_new_child; PB_DS_ASSERT_NODE_CONSISTENT(p_nd->m_p_prev_or_parent, false) return; } p_nd->m_p_prev_or_parent->m_p_next_sibling = p_nd->m_p_next_sibling; if (p_nd->m_p_next_sibling != 0) p_nd->m_p_next_sibling->m_p_prev_or_parent = p_nd->m_p_prev_or_parent; PB_DS_ASSERT_NODE_CONSISTENT(p_nd->m_p_prev_or_parent, false) } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: join_node_children(node_pointer p_nd) { _GLIBCXX_DEBUG_ASSERT(p_nd != 0); node_pointer p_ret = p_nd->m_p_l_child; if (p_ret == 0) return 0; while (p_ret->m_p_next_sibling != 0) p_ret = forward_join(p_ret, p_ret->m_p_next_sibling); while (p_ret->m_p_prev_or_parent != p_nd) p_ret = back_join(p_ret->m_p_prev_or_parent, p_ret); PB_DS_ASSERT_NODE_CONSISTENT(p_ret, false) return p_ret; } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: forward_join(node_pointer p_nd, node_pointer p_next) { _GLIBCXX_DEBUG_ASSERT(p_nd != 0); _GLIBCXX_DEBUG_ASSERT(p_nd->m_p_next_sibling == p_next); if (Cmp_Fn::operator()(p_nd->m_value, p_next->m_value)) { p_next->m_p_prev_or_parent = p_nd->m_p_prev_or_parent; base_type::make_child_of(p_nd, p_next); return p_next->m_p_next_sibling == 0 ? p_next : p_next->m_p_next_sibling; } if (p_next->m_p_next_sibling != 0) { p_next->m_p_next_sibling->m_p_prev_or_parent = p_nd; p_nd->m_p_next_sibling = p_next->m_p_next_sibling; base_type::make_child_of(p_next, p_nd); return p_nd->m_p_next_sibling; } p_nd->m_p_next_sibling = 0; base_type::make_child_of(p_next, p_nd); PB_DS_ASSERT_NODE_CONSISTENT(p_nd, false) return p_nd; } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: back_join(node_pointer p_nd, node_pointer p_next) { _GLIBCXX_DEBUG_ASSERT(p_nd != 0); _GLIBCXX_DEBUG_ASSERT(p_next->m_p_next_sibling == 0); if (Cmp_Fn::operator()(p_nd->m_value, p_next->m_value)) { p_next->m_p_prev_or_parent = p_nd->m_p_prev_or_parent; base_type::make_child_of(p_nd, p_next); PB_DS_ASSERT_NODE_CONSISTENT(p_next, false) return p_next; } p_nd->m_p_next_sibling = 0; base_type::make_child_of(p_next, p_nd); PB_DS_ASSERT_NODE_CONSISTENT(p_nd, false) return p_nd; } PB_DS_CLASS_T_DEC template typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: erase_if(Pred pred) { PB_DS_ASSERT_VALID((*this)) if (base_type::empty()) { PB_DS_ASSERT_VALID((*this)) return 0; } base_type::to_linked_list(); node_pointer p_out = base_type::prune(pred); size_type ersd = 0; while (p_out != 0) { ++ersd; node_pointer p_next = p_out->m_p_next_sibling; base_type::actual_erase_node(p_out); p_out = p_next; } node_pointer p_cur = base_type::m_p_root; base_type::m_p_root = 0; while (p_cur != 0) { node_pointer p_next = p_cur->m_p_next_sibling; p_cur->m_p_l_child = p_cur->m_p_next_sibling = p_cur->m_p_prev_or_parent = 0; push_imp(p_cur); p_cur = p_next; } PB_DS_ASSERT_VALID((*this)) return ersd; } PK!6;18/ext/pb_ds/detail/pairing_heap_/find_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pairing_heap_/find_fn_imps.hpp * Contains an implementation class for a pairing heap. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_reference PB_DS_CLASS_C_DEC:: top() const { PB_DS_ASSERT_VALID((*this)) _GLIBCXX_DEBUG_ASSERT(!base_type::empty()); return base_type::m_p_root->m_value; } PK!i_ W 38/ext/pb_ds/detail/pairing_heap_/insert_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pairing_heap_/insert_fn_imps.hpp * Contains an implementation class for a pairing heap. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: push(const_reference r_val) { PB_DS_ASSERT_VALID((*this)) node_pointer p_new_nd = base_type::get_new_node_for_insert(r_val); push_imp(p_new_nd); PB_DS_ASSERT_VALID((*this)) return point_iterator(p_new_nd); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: push_imp(node_pointer p_nd) { p_nd->m_p_l_child = 0; if (base_type::m_p_root == 0) { p_nd->m_p_next_sibling = p_nd->m_p_prev_or_parent = 0; base_type::m_p_root = p_nd; } else if (Cmp_Fn::operator()(base_type::m_p_root->m_value, p_nd->m_value)) { p_nd->m_p_next_sibling = p_nd->m_p_prev_or_parent = 0; base_type::make_child_of(base_type::m_p_root, p_nd); PB_DS_ASSERT_NODE_CONSISTENT(p_nd, false) base_type::m_p_root = p_nd; } else { base_type::make_child_of(p_nd, base_type::m_p_root); PB_DS_ASSERT_NODE_CONSISTENT(base_type::m_p_root, false) } } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: modify(point_iterator it, const_reference r_new_val) { PB_DS_ASSERT_VALID((*this)) remove_node(it.m_p_nd); it.m_p_nd->m_value = r_new_val; push_imp(it.m_p_nd); PB_DS_ASSERT_VALID((*this)) } PK!)28/ext/pb_ds/detail/pairing_heap_/pairing_heap_.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pairing_heap_/pairing_heap_.hpp * Contains an implementation class for a pairing heap. */ /* * Pairing heap: * Michael L. Fredman, Robert Sedgewick, Daniel Dominic Sleator, * and Robert Endre Tarjan, The Pairing Heap: * A New Form of Self-Adjusting Heap, Algorithmica, 1(1):111-129, 1986. */ #include #include #include #include namespace __gnu_pbds { namespace detail { #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ pairing_heap #ifdef _GLIBCXX_DEBUG #define PB_DS_P_HEAP_BASE \ left_child_next_sibling_heap #else #define PB_DS_P_HEAP_BASE \ left_child_next_sibling_heap #endif /** * Pairing heap. * * @ingroup heap-detail */ template class pairing_heap : public PB_DS_P_HEAP_BASE { private: typedef PB_DS_P_HEAP_BASE base_type; typedef typename base_type::node_pointer node_pointer; typedef typename _Alloc::template rebind::other __rebind_a; public: typedef Value_Type value_type; typedef Cmp_Fn cmp_fn; typedef _Alloc allocator_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef typename __rebind_a::pointer pointer; typedef typename __rebind_a::const_pointer const_pointer; typedef typename __rebind_a::reference reference; typedef typename __rebind_a::const_reference const_reference; typedef typename base_type::point_const_iterator point_const_iterator; typedef typename base_type::point_iterator point_iterator; typedef typename base_type::const_iterator const_iterator; typedef typename base_type::iterator iterator; pairing_heap(); pairing_heap(const Cmp_Fn&); pairing_heap(const pairing_heap&); void swap(pairing_heap&); ~pairing_heap(); inline point_iterator push(const_reference); void modify(point_iterator, const_reference); inline const_reference top() const; void pop(); void erase(point_iterator); template size_type erase_if(Pred); template void split(Pred, pairing_heap&); void join(pairing_heap&); protected: template void copy_from_range(It, It); #ifdef _GLIBCXX_DEBUG void assert_valid(const char*, int) const; #endif private: inline void push_imp(node_pointer); node_pointer join_node_children(node_pointer); node_pointer forward_join(node_pointer, node_pointer); node_pointer back_join(node_pointer, node_pointer); void remove_node(node_pointer); }; #define PB_DS_ASSERT_NODE_CONSISTENT(_Node, _Bool) \ _GLIBCXX_DEBUG_ONLY(base_type::assert_node_consistent(_Node, _Bool, \ __FILE__, __LINE__);) #include #include #include #include #include #include #undef PB_DS_ASSERT_NODE_CONSISTENT #undef PB_DS_CLASS_C_DEC #undef PB_DS_CLASS_T_DEC #undef PB_DS_P_HEAP_BASE } // namespace detail } // namespace __gnu_pbds PK!`zz78/ext/pb_ds/detail/pairing_heap_/split_join_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pairing_heap_/split_join_fn_imps.hpp * Contains an implementation class for a pairing heap. */ PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: split(Pred pred, PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) other.clear(); if (base_type::empty()) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return; } base_type::to_linked_list(); node_pointer p_out = base_type::prune(pred); while (p_out != 0) { _GLIBCXX_DEBUG_ASSERT(base_type::m_size > 0); --base_type::m_size; ++other.m_size; node_pointer p_next = p_out->m_p_next_sibling; p_out->m_p_l_child = p_out->m_p_next_sibling = p_out->m_p_prev_or_parent = 0; other.push_imp(p_out); p_out = p_next; } PB_DS_ASSERT_VALID(other) node_pointer p_cur = base_type::m_p_root; base_type::m_p_root = 0; while (p_cur != 0) { node_pointer p_next = p_cur->m_p_next_sibling; p_cur->m_p_l_child = p_cur->m_p_next_sibling = p_cur->m_p_prev_or_parent = 0; push_imp(p_cur); p_cur = p_next; } PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: join(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) if (other.m_p_root == 0) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return; } if (base_type::m_p_root == 0) base_type::m_p_root = other.m_p_root; else if (Cmp_Fn::operator()(base_type::m_p_root->m_value, other.m_p_root->m_value)) { base_type::make_child_of(base_type::m_p_root, other.m_p_root); PB_DS_ASSERT_NODE_CONSISTENT(other.m_p_root, false) base_type::m_p_root = other.m_p_root; } else { base_type::make_child_of(other.m_p_root, base_type::m_p_root); PB_DS_ASSERT_NODE_CONSISTENT(base_type::m_p_root, false) } base_type::m_size += other.m_size; other.m_p_root = 0; other.m_size = 0; PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PK!]hPP@8/ext/pb_ds/detail/pat_trie_/constructors_destructor_fn_imps.hppnu[ // -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/constructors_destructor_fn_imps.hpp * Contains an implementation class for pat_trie. */ PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::head_allocator PB_DS_CLASS_C_DEC::s_head_allocator; PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::inode_allocator PB_DS_CLASS_C_DEC::s_inode_allocator; PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::leaf_allocator PB_DS_CLASS_C_DEC::s_leaf_allocator; PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_PAT_TRIE_NAME() : m_p_head(s_head_allocator.allocate(1)), m_size(0) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_PAT_TRIE_NAME(const access_traits& r_access_traits) : synth_access_traits(r_access_traits), m_p_head(s_head_allocator.allocate(1)), m_size(0) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_PAT_TRIE_NAME(const PB_DS_CLASS_C_DEC& other) : #ifdef _GLIBCXX_DEBUG debug_base(other), #endif synth_access_traits(other), node_update(other), m_p_head(s_head_allocator.allocate(1)), m_size(0) { initialize(); m_size = other.m_size; PB_DS_ASSERT_VALID(other) if (other.m_p_head->m_p_parent == 0) { PB_DS_ASSERT_VALID((*this)) return; } __try { m_p_head->m_p_parent = recursive_copy_node(other.m_p_head->m_p_parent); } __catch(...) { s_head_allocator.deallocate(m_p_head, 1); __throw_exception_again; } m_p_head->m_p_min = leftmost_descendant(m_p_head->m_p_parent); m_p_head->m_p_max = rightmost_descendant(m_p_head->m_p_parent); m_p_head->m_p_parent->m_p_parent = m_p_head; PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) value_swap(other); std::swap((access_traits& )(*this), (access_traits& )other); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: value_swap(PB_DS_CLASS_C_DEC& other) { _GLIBCXX_DEBUG_ONLY(debug_base::swap(other);) std::swap(m_p_head, other.m_p_head); std::swap(m_size, other.m_size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~PB_DS_PAT_TRIE_NAME() { clear(); s_head_allocator.deallocate(m_p_head, 1); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: initialize() { new (m_p_head) head(); m_p_head->m_p_parent = 0; m_p_head->m_p_min = m_p_head; m_p_head->m_p_max = m_p_head; m_size = 0; } PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: copy_from_range(It first_it, It last_it) { while (first_it != last_it) insert(*(first_it++)); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: recursive_copy_node(node_const_pointer p_ncp) { _GLIBCXX_DEBUG_ASSERT(p_ncp != 0); if (p_ncp->m_type == leaf_node) { leaf_const_pointer p_other_lf = static_cast(p_ncp); leaf_pointer p_new_lf = s_leaf_allocator.allocate(1); cond_dealtor cond(p_new_lf); new (p_new_lf) leaf(p_other_lf->value()); apply_update(p_new_lf, (node_update*)this); cond.set_no_action_dtor(); return (p_new_lf); } _GLIBCXX_DEBUG_ASSERT(p_ncp->m_type == i_node); node_pointer a_p_children[inode::arr_size]; size_type child_i = 0; inode_const_pointer p_icp = static_cast(p_ncp); typename inode::const_iterator child_it = p_icp->begin(); inode_pointer p_ret; __try { while (child_it != p_icp->end()) { a_p_children[child_i] = recursive_copy_node(*(child_it)); child_i++; child_it++; } p_ret = s_inode_allocator.allocate(1); } __catch(...) { while (child_i-- > 0) clear_imp(a_p_children[child_i]); __throw_exception_again; } new (p_ret) inode(p_icp->get_e_ind(), pref_begin(a_p_children[0])); --child_i; _GLIBCXX_DEBUG_ASSERT(child_i >= 1); do p_ret->add_child(a_p_children[child_i], pref_begin(a_p_children[child_i]), pref_end(a_p_children[child_i]), this); while (child_i-- > 0); apply_update(p_ret, (node_update*)this); return p_ret; } PK!ļ.8/ext/pb_ds/detail/pat_trie_/debug_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/debug_fn_imps.hpp * Contains an implementation class for pat_trie_. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { if (m_p_head->m_p_parent != 0) m_p_head->m_p_parent->assert_valid(this, __file, __line); assert_iterators(__file, __line); assert_reverse_iterators(__file, __line); if (m_p_head->m_p_parent == 0) { PB_DS_DEBUG_VERIFY(m_p_head->m_p_min == m_p_head); PB_DS_DEBUG_VERIFY(m_p_head->m_p_max == m_p_head); PB_DS_DEBUG_VERIFY(empty()); return; } PB_DS_DEBUG_VERIFY(m_p_head->m_p_min->m_type == leaf_node); PB_DS_DEBUG_VERIFY(m_p_head->m_p_max->m_type == leaf_node); PB_DS_DEBUG_VERIFY(!empty()); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_iterators(const char* __file, int __line) const { size_type calc_size = 0; for (const_iterator it = begin(); it != end(); ++it) { ++calc_size; debug_base::check_key_exists(PB_DS_V2F(*it), __file, __line); PB_DS_DEBUG_VERIFY(lower_bound(PB_DS_V2F(*it)) == it); PB_DS_DEBUG_VERIFY(--upper_bound(PB_DS_V2F(*it)) == it); } PB_DS_DEBUG_VERIFY(calc_size == m_size); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_reverse_iterators(const char* __file, int __line) const { size_type calc_size = 0; for (const_reverse_iterator it = rbegin(); it != rend(); ++it) { ++calc_size; node_const_pointer p_nd = const_cast(this)->find_imp(PB_DS_V2F(*it)); PB_DS_DEBUG_VERIFY(p_nd == it.m_p_nd); } PB_DS_DEBUG_VERIFY(calc_size == m_size); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: recursive_count_leafs(node_const_pointer p_nd, const char* __file, int __line) { if (p_nd == 0) return (0); if (p_nd->m_type == leaf_node) return (1); PB_DS_DEBUG_VERIFY(p_nd->m_type == i_node); size_type ret = 0; for (typename inode::const_iterator it = static_cast(p_nd)->begin(); it != static_cast(p_nd)->end(); ++it) ret += recursive_count_leafs(*it, __file, __line); return ret; } #endif PK!lZz  .8/ext/pb_ds/detail/pat_trie_/erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/erase_fn_imps.hpp * Contains an implementation class for pat_trie. */ PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: erase(key_const_reference r_key) { node_pointer p_nd = find_imp(r_key); if (p_nd == 0 || p_nd->m_type == i_node) { PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return false; } _GLIBCXX_DEBUG_ASSERT(p_nd->m_type == leaf_node); if (!synth_access_traits::equal_keys(PB_DS_V2F(reinterpret_cast(p_nd)->value()), r_key)) { PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return false; } PB_DS_CHECK_KEY_EXISTS(r_key) erase_leaf(static_cast(p_nd)); PB_DS_ASSERT_VALID((*this)) return true; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: erase_fixup(inode_pointer p_nd) { _GLIBCXX_DEBUG_ASSERT(std::distance(p_nd->begin(), p_nd->end()) >= 1); if (std::distance(p_nd->begin(), p_nd->end()) == 1) { node_pointer p_parent = p_nd->m_p_parent; if (p_parent == m_p_head) m_p_head->m_p_parent = *p_nd->begin(); else { _GLIBCXX_DEBUG_ASSERT(p_parent->m_type == i_node); node_pointer p_new_child = *p_nd->begin(); typedef inode_pointer inode_ptr; inode_ptr p_internal = static_cast(p_parent); p_internal->replace_child(p_new_child, pref_begin(p_new_child), pref_end(p_new_child), this); } (*p_nd->begin())->m_p_parent = p_nd->m_p_parent; p_nd->~inode(); s_inode_allocator.deallocate(p_nd, 1); if (p_parent == m_p_head) return; _GLIBCXX_DEBUG_ASSERT(p_parent->m_type == i_node); p_nd = static_cast(p_parent); } while (true) { _GLIBCXX_DEBUG_ASSERT(std::distance(p_nd->begin(), p_nd->end()) > 1); p_nd->update_prefixes(this); apply_update(p_nd, (node_update*)this); PB_DS_ASSERT_NODE_VALID(p_nd) if (p_nd->m_p_parent->m_type == head_node) return; _GLIBCXX_DEBUG_ASSERT(p_nd->m_p_parent->m_type == i_node); p_nd = static_cast(p_nd->m_p_parent); } } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: actual_erase_leaf(leaf_pointer p_l) { _GLIBCXX_DEBUG_ASSERT(m_size > 0); --m_size; _GLIBCXX_DEBUG_ONLY(debug_base::erase_existing(PB_DS_V2F(p_l->value()))); p_l->~leaf(); s_leaf_allocator.deallocate(p_l, 1); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear() { if (!empty()) { clear_imp(m_p_head->m_p_parent); m_size = 0; initialize(); _GLIBCXX_DEBUG_ONLY(debug_base::clear();) PB_DS_ASSERT_VALID((*this)) } } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear_imp(node_pointer p_nd) { if (p_nd->m_type == i_node) { _GLIBCXX_DEBUG_ASSERT(p_nd->m_type == i_node); for (typename inode::iterator it = static_cast(p_nd)->begin(); it != static_cast(p_nd)->end(); ++it) { node_pointer p_child =* it; clear_imp(p_child); } s_inode_allocator.deallocate(static_cast(p_nd), 1); return; } _GLIBCXX_DEBUG_ASSERT(p_nd->m_type == leaf_node); static_cast(p_nd)->~leaf(); s_leaf_allocator.deallocate(static_cast(p_nd), 1); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: erase(const_iterator it) { PB_DS_ASSERT_VALID((*this)) if (it == end()) return it; const_iterator ret_it = it; ++ret_it; _GLIBCXX_DEBUG_ASSERT(it.m_p_nd->m_type == leaf_node); erase_leaf(static_cast(it.m_p_nd)); PB_DS_ASSERT_VALID((*this)) return ret_it; } #ifdef PB_DS_DATA_TRUE_INDICATOR PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: erase(iterator it) { PB_DS_ASSERT_VALID((*this)) if (it == end()) return it; iterator ret_it = it; ++ret_it; _GLIBCXX_DEBUG_ASSERT(it.m_p_nd->m_type == leaf_node); erase_leaf(static_cast(it.m_p_nd)); PB_DS_ASSERT_VALID((*this)) return ret_it; } #endif // #ifdef PB_DS_DATA_TRUE_INDICATOR PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_reverse_iterator PB_DS_CLASS_C_DEC:: erase(const_reverse_iterator it) { PB_DS_ASSERT_VALID((*this)) if (it.m_p_nd == m_p_head) return it; const_reverse_iterator ret_it = it; ++ret_it; _GLIBCXX_DEBUG_ASSERT(it.m_p_nd->m_type == leaf_node); erase_leaf(static_cast(it.m_p_nd)); PB_DS_ASSERT_VALID((*this)) return ret_it; } #ifdef PB_DS_DATA_TRUE_INDICATOR PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::reverse_iterator PB_DS_CLASS_C_DEC:: erase(reverse_iterator it) { PB_DS_ASSERT_VALID((*this)) if (it.m_p_nd == m_p_head) return it; reverse_iterator ret_it = it; ++ret_it; _GLIBCXX_DEBUG_ASSERT(it.m_p_nd->m_type == leaf_node); erase_leaf(static_cast(it.m_p_nd)); PB_DS_ASSERT_VALID((*this)) return ret_it; } #endif // #ifdef PB_DS_DATA_TRUE_INDICATOR PB_DS_CLASS_T_DEC template inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: erase_if(Pred pred) { size_type num_ersd = 0; PB_DS_ASSERT_VALID((*this)) iterator it = begin(); while (it != end()) { PB_DS_ASSERT_VALID((*this)) if (pred(*it)) { ++num_ersd; it = erase(it); } else ++it; } PB_DS_ASSERT_VALID((*this)) return num_ersd; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: erase_leaf(leaf_pointer p_l) { update_min_max_for_erased_leaf(p_l); if (p_l->m_p_parent->m_type == head_node) { _GLIBCXX_DEBUG_ASSERT(size() == 1); clear(); return; } _GLIBCXX_DEBUG_ASSERT(size() > 1); _GLIBCXX_DEBUG_ASSERT(p_l->m_p_parent->m_type == i_node); inode_pointer p_parent = static_cast(p_l->m_p_parent); p_parent->remove_child(p_l); erase_fixup(p_parent); actual_erase_leaf(p_l); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: update_min_max_for_erased_leaf(leaf_pointer p_l) { if (m_size == 1) { m_p_head->m_p_min = m_p_head; m_p_head->m_p_max = m_p_head; return; } if (p_l == static_cast(m_p_head->m_p_min)) { iterator it(p_l); ++it; m_p_head->m_p_min = it.m_p_nd; return; } if (p_l == static_cast(m_p_head->m_p_max)) { iterator it(p_l); --it; m_p_head->m_p_max = it.m_p_nd; } } PK!<-8/ext/pb_ds/detail/pat_trie_/find_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/find_fn_imps.hpp * Contains an implementation class for pat_trie. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: find(key_const_reference r_key) { PB_DS_ASSERT_VALID((*this)) node_pointer p_nd = find_imp(r_key); if (p_nd == 0 || p_nd->m_type != leaf_node) { PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return end(); } if (synth_access_traits::equal_keys(PB_DS_V2F(static_cast(p_nd)->value()), r_key)) { PB_DS_CHECK_KEY_EXISTS(r_key) return iterator(p_nd); } PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return end(); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_const_iterator PB_DS_CLASS_C_DEC:: find(key_const_reference r_key) const { PB_DS_ASSERT_VALID((*this)) node_const_pointer p_nd = const_cast(this)->find_imp(r_key); if (p_nd == 0 || p_nd->m_type != leaf_node) { PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return end(); } if (synth_access_traits::equal_keys(PB_DS_V2F(static_cast(p_nd)->value()), r_key)) { PB_DS_CHECK_KEY_EXISTS(r_key) return const_iterator(const_cast(p_nd)); } PB_DS_CHECK_KEY_DOES_NOT_EXIST(r_key) return end(); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: find_imp(key_const_reference r_key) { if (empty()) return 0; typename synth_access_traits::const_iterator b_it = synth_access_traits::begin(r_key); typename synth_access_traits::const_iterator e_it = synth_access_traits::end(r_key); node_pointer p_nd = m_p_head->m_p_parent; _GLIBCXX_DEBUG_ASSERT(p_nd != 0); while (p_nd->m_type != leaf_node) { _GLIBCXX_DEBUG_ASSERT(p_nd->m_type == i_node); node_pointer p_next_nd = static_cast(p_nd)->get_child_node(b_it, e_it, this); if (p_next_nd == 0) return p_nd; p_nd = p_next_nd; } return p_nd; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: lower_bound_imp(key_const_reference r_key) { if (empty()) return (m_p_head); node_pointer p_nd = m_p_head->m_p_parent; _GLIBCXX_DEBUG_ASSERT(p_nd != 0); typename PB_DS_CLASS_C_DEC::a_const_iterator b_it = synth_access_traits::begin(r_key); typename PB_DS_CLASS_C_DEC::a_const_iterator e_it = synth_access_traits::end(r_key); size_type checked_ind = 0; while (true) { if (p_nd->m_type == leaf_node) { if (!synth_access_traits::cmp_keys(PB_DS_V2F(static_cast(p_nd)->value()), r_key)) return p_nd; iterator it(p_nd); ++it; return it.m_p_nd; } _GLIBCXX_DEBUG_ASSERT(p_nd->m_type == i_node); const size_type new_checked_ind = static_cast(p_nd)->get_e_ind(); p_nd = static_cast(p_nd)->get_lower_bound_child_node( b_it, e_it, checked_ind, this); checked_ind = new_checked_ind; } } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: lower_bound(key_const_reference r_key) { return point_iterator(lower_bound_imp(r_key)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_const_iterator PB_DS_CLASS_C_DEC:: lower_bound(key_const_reference r_key) const { return point_const_iterator(const_cast(this)->lower_bound_imp(r_key)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: upper_bound(key_const_reference r_key) { point_iterator l_bound_it = lower_bound(r_key); _GLIBCXX_DEBUG_ASSERT(l_bound_it == end() || !synth_access_traits::cmp_keys(PB_DS_V2F(*l_bound_it), r_key)); if (l_bound_it == end() || synth_access_traits::cmp_keys(r_key, PB_DS_V2F(*l_bound_it))) return l_bound_it; return ++l_bound_it; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_const_iterator PB_DS_CLASS_C_DEC:: upper_bound(key_const_reference r_key) const { point_const_iterator l_bound_it = lower_bound(r_key); _GLIBCXX_DEBUG_ASSERT(l_bound_it == end() || !synth_access_traits::cmp_keys(PB_DS_V2F(*l_bound_it), r_key)); if (l_bound_it == end() || synth_access_traits::cmp_keys(r_key, PB_DS_V2F(*l_bound_it))) return l_bound_it; return ++l_bound_it; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::a_const_iterator PB_DS_CLASS_C_DEC:: pref_begin(node_const_pointer p_nd) { if (p_nd->m_type == leaf_node) return (synth_access_traits::begin(PB_DS_V2F(static_cast(p_nd)->value()))); _GLIBCXX_DEBUG_ASSERT(p_nd->m_type == i_node); return static_cast(p_nd)->pref_b_it(); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::a_const_iterator PB_DS_CLASS_C_DEC:: pref_end(node_const_pointer p_nd) { if (p_nd->m_type == leaf_node) return (synth_access_traits::end(PB_DS_V2F(static_cast(p_nd)->value()))); _GLIBCXX_DEBUG_ASSERT(p_nd->m_type == i_node); return static_cast(p_nd)->pref_e_it(); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::leaf_const_pointer PB_DS_CLASS_C_DEC:: leftmost_descendant(node_const_pointer p_nd) { if (p_nd->m_type == leaf_node) return static_cast(p_nd); return static_cast(p_nd)->leftmost_descendant(); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::leaf_pointer PB_DS_CLASS_C_DEC:: leftmost_descendant(node_pointer p_nd) { if (p_nd->m_type == leaf_node) return static_cast(p_nd); return static_cast(p_nd)->leftmost_descendant(); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::leaf_const_pointer PB_DS_CLASS_C_DEC:: rightmost_descendant(node_const_pointer p_nd) { if (p_nd->m_type == leaf_node) return static_cast(p_nd); return static_cast(p_nd)->rightmost_descendant(); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::leaf_pointer PB_DS_CLASS_C_DEC:: rightmost_descendant(node_pointer p_nd) { if (p_nd->m_type == leaf_node) return static_cast(p_nd); return static_cast(p_nd)->rightmost_descendant(); } PK!`-8/ext/pb_ds/detail/pat_trie_/info_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/info_fn_imps.hpp * Contains an implementation class for pat_trie. */ PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: empty() const { return (m_size == 0); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: size() const { return m_size; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: max_size() const { return s_inode_allocator.max_size(); } PK!:8848/ext/pb_ds/detail/pat_trie_/insert_join_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/insert_join_fn_imps.hpp * Contains an implementation class for pat_trie. */ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: join(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) branch_bag bag; if (!join_prep(other, bag)) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return; } m_p_head->m_p_parent = rec_join(m_p_head->m_p_parent, other.m_p_head->m_p_parent, 0, bag); m_p_head->m_p_parent->m_p_parent = m_p_head; m_size += other.m_size; other.initialize(); PB_DS_ASSERT_VALID(other) m_p_head->m_p_min = leftmost_descendant(m_p_head->m_p_parent); m_p_head->m_p_max = rightmost_descendant(m_p_head->m_p_parent); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC bool PB_DS_CLASS_C_DEC:: join_prep(PB_DS_CLASS_C_DEC& other, branch_bag& r_bag) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) if (other.m_size == 0) return false; if (m_size == 0) { value_swap(other); return false; } const bool greater = synth_access_traits::cmp_keys(PB_DS_V2F(static_cast(m_p_head->m_p_max)->value()), PB_DS_V2F(static_cast(other.m_p_head->m_p_min)->value())); const bool lesser = synth_access_traits::cmp_keys(PB_DS_V2F(static_cast(other.m_p_head->m_p_max)->value()), PB_DS_V2F(static_cast(m_p_head->m_p_min)->value())); if (!greater && !lesser) __throw_join_error(); rec_join_prep(m_p_head->m_p_parent, other.m_p_head->m_p_parent, r_bag); _GLIBCXX_DEBUG_ONLY(debug_base::join(other, false);) return true; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: rec_join_prep(node_const_pointer p_l, node_const_pointer p_r, branch_bag& r_bag) { if (p_l->m_type == leaf_node) { if (p_r->m_type == leaf_node) { rec_join_prep(static_cast(p_l), static_cast(p_r), r_bag); return; } _GLIBCXX_DEBUG_ASSERT(p_r->m_type == i_node); rec_join_prep(static_cast(p_l), static_cast(p_r), r_bag); return; } _GLIBCXX_DEBUG_ASSERT(p_l->m_type == i_node); if (p_r->m_type == leaf_node) { rec_join_prep(static_cast(p_l), static_cast(p_r), r_bag); return; } _GLIBCXX_DEBUG_ASSERT(p_r->m_type == i_node); rec_join_prep(static_cast(p_l), static_cast(p_r), r_bag); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: rec_join_prep(leaf_const_pointer /*p_l*/, leaf_const_pointer /*p_r*/, branch_bag& r_bag) { r_bag.add_branch(); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: rec_join_prep(leaf_const_pointer /*p_l*/, inode_const_pointer /*p_r*/, branch_bag& r_bag) { r_bag.add_branch(); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: rec_join_prep(inode_const_pointer /*p_l*/, leaf_const_pointer /*p_r*/, branch_bag& r_bag) { r_bag.add_branch(); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: rec_join_prep(inode_const_pointer p_l, inode_const_pointer p_r, branch_bag& r_bag) { if (p_l->get_e_ind() == p_r->get_e_ind() && synth_access_traits::equal_prefixes(p_l->pref_b_it(), p_l->pref_e_it(), p_r->pref_b_it(), p_r->pref_e_it())) { for (typename inode::const_iterator it = p_r->begin(); it != p_r->end(); ++ it) { node_const_pointer p_l_join_child = p_l->get_join_child(*it, this); if (p_l_join_child != 0) rec_join_prep(p_l_join_child, * it, r_bag); } return; } if (p_r->get_e_ind() < p_l->get_e_ind() && p_r->should_be_mine(p_l->pref_b_it(), p_l->pref_e_it(), 0, this)) { node_const_pointer p_r_join_child = p_r->get_join_child(p_l, this); if (p_r_join_child != 0) rec_join_prep(p_r_join_child, p_l, r_bag); return; } if (p_r->get_e_ind() < p_l->get_e_ind() && p_r->should_be_mine(p_l->pref_b_it(), p_l->pref_e_it(), 0, this)) { node_const_pointer p_r_join_child = p_r->get_join_child(p_l, this); if (p_r_join_child != 0) rec_join_prep(p_r_join_child, p_l, r_bag); return; } r_bag.add_branch(); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: rec_join(node_pointer p_l, node_pointer p_r, size_type checked_ind, branch_bag& r_bag) { _GLIBCXX_DEBUG_ASSERT(p_r != 0); if (p_l == 0) { apply_update(p_r, (node_update*)this); return (p_r); } if (p_l->m_type == leaf_node) { if (p_r->m_type == leaf_node) { node_pointer p_ret = rec_join(static_cast(p_l), static_cast(p_r), r_bag); apply_update(p_ret, (node_update*)this); return p_ret; } _GLIBCXX_DEBUG_ASSERT(p_r->m_type == i_node); node_pointer p_ret = rec_join(static_cast(p_l), static_cast(p_r), checked_ind, r_bag); apply_update(p_ret, (node_update*)this); return p_ret; } _GLIBCXX_DEBUG_ASSERT(p_l->m_type == i_node); if (p_r->m_type == leaf_node) { node_pointer p_ret = rec_join(static_cast(p_l), static_cast(p_r), checked_ind, r_bag); apply_update(p_ret, (node_update*)this); return p_ret; } _GLIBCXX_DEBUG_ASSERT(p_r->m_type == i_node); node_pointer p_ret = rec_join(static_cast(p_l), static_cast(p_r), r_bag); apply_update(p_ret, (node_update*)this); return p_ret; } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: rec_join(leaf_pointer p_l, leaf_pointer p_r, branch_bag& r_bag) { _GLIBCXX_DEBUG_ASSERT(p_r != 0); if (p_l == 0) return (p_r); node_pointer p_ret = insert_branch(p_l, p_r, r_bag); _GLIBCXX_DEBUG_ASSERT(PB_DS_RECURSIVE_COUNT_LEAFS(p_ret) == 2); return p_ret; } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: rec_join(leaf_pointer p_l, inode_pointer p_r, size_type checked_ind, branch_bag& r_bag) { #ifdef _GLIBCXX_DEBUG const size_type lhs_leafs = PB_DS_RECURSIVE_COUNT_LEAFS(p_l); const size_type rhs_leafs = PB_DS_RECURSIVE_COUNT_LEAFS(p_r); #endif _GLIBCXX_DEBUG_ASSERT(p_r != 0); node_pointer p_ret = rec_join(p_r, p_l, checked_ind, r_bag); _GLIBCXX_DEBUG_ASSERT(PB_DS_RECURSIVE_COUNT_LEAFS(p_ret) == lhs_leafs + rhs_leafs); return p_ret; } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: rec_join(inode_pointer p_l, leaf_pointer p_r, size_type checked_ind, branch_bag& r_bag) { _GLIBCXX_DEBUG_ASSERT(p_l != 0); _GLIBCXX_DEBUG_ASSERT(p_r != 0); #ifdef _GLIBCXX_DEBUG const size_type lhs_leafs = PB_DS_RECURSIVE_COUNT_LEAFS(p_l); const size_type rhs_leafs = PB_DS_RECURSIVE_COUNT_LEAFS(p_r); #endif if (!p_l->should_be_mine(pref_begin(p_r), pref_end(p_r), checked_ind, this)) { node_pointer p_ret = insert_branch(p_l, p_r, r_bag); PB_DS_ASSERT_NODE_VALID(p_ret) _GLIBCXX_DEBUG_ASSERT(PB_DS_RECURSIVE_COUNT_LEAFS(p_ret) == lhs_leafs + rhs_leafs); return p_ret; } node_pointer p_pot_child = p_l->add_child(p_r, pref_begin(p_r), pref_end(p_r), this); if (p_pot_child != p_r) { node_pointer p_new_child = rec_join(p_pot_child, p_r, p_l->get_e_ind(), r_bag); p_l->replace_child(p_new_child, pref_begin(p_new_child), pref_end(p_new_child), this); } PB_DS_ASSERT_NODE_VALID(p_l) _GLIBCXX_DEBUG_ASSERT(PB_DS_RECURSIVE_COUNT_LEAFS(p_l) == lhs_leafs + rhs_leafs); return p_l; } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: rec_join(inode_pointer p_l, inode_pointer p_r, branch_bag& r_bag) { _GLIBCXX_DEBUG_ASSERT(p_l != 0); _GLIBCXX_DEBUG_ASSERT(p_r != 0); #ifdef _GLIBCXX_DEBUG const size_type lhs_leafs = PB_DS_RECURSIVE_COUNT_LEAFS(p_l); const size_type rhs_leafs = PB_DS_RECURSIVE_COUNT_LEAFS(p_r); #endif if (p_l->get_e_ind() == p_r->get_e_ind() && synth_access_traits::equal_prefixes(p_l->pref_b_it(), p_l->pref_e_it(), p_r->pref_b_it(), p_r->pref_e_it())) { for (typename inode::iterator it = p_r->begin(); it != p_r->end(); ++ it) { node_pointer p_new_child = rec_join(p_l->get_join_child(*it, this), * it, 0, r_bag); p_l->replace_child(p_new_child, pref_begin(p_new_child), pref_end(p_new_child), this); } p_r->~inode(); s_inode_allocator.deallocate(p_r, 1); PB_DS_ASSERT_NODE_VALID(p_l) _GLIBCXX_DEBUG_ASSERT(PB_DS_RECURSIVE_COUNT_LEAFS(p_l) == lhs_leafs + rhs_leafs); return p_l; } if (p_l->get_e_ind() < p_r->get_e_ind() && p_l->should_be_mine(p_r->pref_b_it(), p_r->pref_e_it(), 0, this)) { node_pointer p_new_child = rec_join(p_l->get_join_child(p_r, this), p_r, 0, r_bag); p_l->replace_child(p_new_child, pref_begin(p_new_child), pref_end(p_new_child), this); PB_DS_ASSERT_NODE_VALID(p_l) return p_l; } if (p_r->get_e_ind() < p_l->get_e_ind() && p_r->should_be_mine(p_l->pref_b_it(), p_l->pref_e_it(), 0, this)) { node_pointer p_new_child = rec_join(p_r->get_join_child(p_l, this), p_l, 0, r_bag); p_r->replace_child(p_new_child, pref_begin(p_new_child), pref_end(p_new_child), this); PB_DS_ASSERT_NODE_VALID(p_r) _GLIBCXX_DEBUG_ASSERT(PB_DS_RECURSIVE_COUNT_LEAFS(p_r) == lhs_leafs + rhs_leafs); return p_r; } node_pointer p_ret = insert_branch(p_l, p_r, r_bag); PB_DS_ASSERT_NODE_VALID(p_ret) _GLIBCXX_DEBUG_ASSERT(PB_DS_RECURSIVE_COUNT_LEAFS(p_ret) == lhs_leafs + rhs_leafs); return p_ret; } PB_DS_CLASS_T_DEC inline std::pair PB_DS_CLASS_C_DEC:: insert(const_reference r_val) { node_pointer p_lf = find_imp(PB_DS_V2F(r_val)); if (p_lf != 0 && p_lf->m_type == leaf_node && synth_access_traits::equal_keys(PB_DS_V2F(static_cast(p_lf)->value()), PB_DS_V2F(r_val))) { PB_DS_CHECK_KEY_EXISTS(PB_DS_V2F(r_val)) PB_DS_ASSERT_VALID((*this)) return std::make_pair(iterator(p_lf), false); } PB_DS_CHECK_KEY_DOES_NOT_EXIST(PB_DS_V2F(r_val)) leaf_pointer p_new_lf = s_leaf_allocator.allocate(1); cond_dealtor cond(p_new_lf); new (p_new_lf) leaf(r_val); apply_update(p_new_lf, (node_update*)this); cond.set_call_destructor(); branch_bag bag; bag.add_branch(); m_p_head->m_p_parent = rec_join(m_p_head->m_p_parent, p_new_lf, 0, bag); m_p_head->m_p_parent->m_p_parent = m_p_head; cond.set_no_action_dtor(); ++m_size; update_min_max_for_inserted_leaf(p_new_lf); _GLIBCXX_DEBUG_ONLY(debug_base::insert_new(PB_DS_V2F(r_val));) PB_DS_ASSERT_VALID((*this)) return std::make_pair(point_iterator(p_new_lf), true); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: keys_diff_ind(typename access_traits::const_iterator b_l, typename access_traits::const_iterator e_l, typename access_traits::const_iterator b_r, typename access_traits::const_iterator e_r) { size_type diff_pos = 0; while (b_l != e_l) { if (b_r == e_r) return (diff_pos); if (access_traits::e_pos(*b_l) != access_traits::e_pos(*b_r)) return (diff_pos); ++b_l; ++b_r; ++diff_pos; } _GLIBCXX_DEBUG_ASSERT(b_r != e_r); return diff_pos; } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::inode_pointer PB_DS_CLASS_C_DEC:: insert_branch(node_pointer p_l, node_pointer p_r, branch_bag& r_bag) { typename synth_access_traits::const_iterator left_b_it = pref_begin(p_l); typename synth_access_traits::const_iterator left_e_it = pref_end(p_l); typename synth_access_traits::const_iterator right_b_it = pref_begin(p_r); typename synth_access_traits::const_iterator right_e_it = pref_end(p_r); const size_type diff_ind = keys_diff_ind(left_b_it, left_e_it, right_b_it, right_e_it); inode_pointer p_new_nd = r_bag.get_branch(); new (p_new_nd) inode(diff_ind, left_b_it); p_new_nd->add_child(p_l, left_b_it, left_e_it, this); p_new_nd->add_child(p_r, right_b_it, right_e_it, this); p_l->m_p_parent = p_new_nd; p_r->m_p_parent = p_new_nd; PB_DS_ASSERT_NODE_VALID(p_new_nd) return (p_new_nd); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: update_min_max_for_inserted_leaf(leaf_pointer p_new_lf) { if (m_p_head->m_p_min == m_p_head || synth_access_traits::cmp_keys(PB_DS_V2F(p_new_lf->value()), PB_DS_V2F(static_cast(m_p_head->m_p_min)->value()))) m_p_head->m_p_min = p_new_lf; if (m_p_head->m_p_max == m_p_head || synth_access_traits::cmp_keys(PB_DS_V2F(static_cast(m_p_head->m_p_max)->value()), PB_DS_V2F(p_new_lf->value()))) m_p_head->m_p_max = p_new_lf; } PK!0? 28/ext/pb_ds/detail/pat_trie_/iterators_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/iterators_fn_imps.hpp * Contains an implementation class for pat_trie. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: begin() { return iterator(m_p_head->m_p_min); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: begin() const { return const_iterator(m_p_head->m_p_min); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: end() { return iterator(m_p_head); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: end() const { return const_iterator(m_p_head); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_reverse_iterator PB_DS_CLASS_C_DEC:: rbegin() const { if (empty()) return rend(); return --end(); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::reverse_iterator PB_DS_CLASS_C_DEC:: rbegin() { if (empty()) return rend(); return --end(); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::reverse_iterator PB_DS_CLASS_C_DEC:: rend() { return reverse_iterator(m_p_head); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_reverse_iterator PB_DS_CLASS_C_DEC:: rend() const { return const_reverse_iterator(m_p_head); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_const_iterator PB_DS_CLASS_C_DEC:: node_begin() const { return node_const_iterator(m_p_head->m_p_parent, this); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_iterator PB_DS_CLASS_C_DEC:: node_begin() { return node_iterator(m_p_head->m_p_parent, this); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_const_iterator PB_DS_CLASS_C_DEC:: node_end() const { return node_const_iterator(0, this); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_iterator PB_DS_CLASS_C_DEC:: node_end() { return node_iterator(0, this); } PK!#ӌAA*8/ext/pb_ds/detail/pat_trie_/pat_trie_.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/pat_trie_.hpp * Contains an implementation class for a patricia tree. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef _GLIBCXX_DEBUG #include #endif #include namespace __gnu_pbds { namespace detail { #ifdef PB_DS_DATA_TRUE_INDICATOR #define PB_DS_PAT_TRIE_NAME pat_trie_map #endif #ifdef PB_DS_DATA_FALSE_INDICATOR #define PB_DS_PAT_TRIE_NAME pat_trie_set #endif #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ PB_DS_PAT_TRIE_NAME #define PB_DS_PAT_TRIE_TRAITS_BASE \ types_traits #ifdef _GLIBCXX_DEBUG #define PB_DS_DEBUG_MAP_BASE_C_DEC \ debug_map_base >, \ typename _Alloc::template rebind::other::const_reference> #endif /** * @brief PATRICIA trie. * @ingroup branch-detail * * This implementation loosely borrows ideas from: * 1) Fast Mergeable Integer Maps, Okasaki, Gill 1998 * 2) Ptset: Sets of integers implemented as Patricia trees, * Jean-Christophe Filliatr, 2000 */ template class PB_DS_PAT_TRIE_NAME : #ifdef _GLIBCXX_DEBUG public PB_DS_DEBUG_MAP_BASE_C_DEC, #endif public Node_And_It_Traits::synth_access_traits, public Node_And_It_Traits::node_update, public PB_DS_PAT_TRIE_TRAITS_BASE, public pat_trie_base { private: typedef pat_trie_base base_type; typedef PB_DS_PAT_TRIE_TRAITS_BASE traits_base; typedef Node_And_It_Traits traits_type; typedef typename traits_type::synth_access_traits synth_access_traits; typedef typename synth_access_traits::const_iterator a_const_iterator; typedef typename traits_type::node node; typedef typename _Alloc::template rebind __rebind_n; typedef typename __rebind_n::other::const_pointer node_const_pointer; typedef typename __rebind_n::other::pointer node_pointer; typedef typename traits_type::head head; typedef typename _Alloc::template rebind __rebind_h; typedef typename __rebind_h::other head_allocator; typedef typename head_allocator::pointer head_pointer; typedef typename traits_type::leaf leaf; typedef typename _Alloc::template rebind __rebind_l; typedef typename __rebind_l::other leaf_allocator; typedef typename leaf_allocator::pointer leaf_pointer; typedef typename leaf_allocator::const_pointer leaf_const_pointer; typedef typename traits_type::inode inode; typedef typename inode::iterator inode_iterator; typedef typename _Alloc::template rebind __rebind_in; typedef typename __rebind_in::other __rebind_ina; typedef typename __rebind_in::other inode_allocator; typedef typename __rebind_ina::pointer inode_pointer; typedef typename __rebind_ina::const_pointer inode_const_pointer; /// Conditional deallocator. class cond_dealtor { protected: leaf_pointer m_p_nd; bool m_no_action_dtor; bool m_call_destructor; public: cond_dealtor(leaf_pointer p_nd) : m_p_nd(p_nd), m_no_action_dtor(false), m_call_destructor(false) { } void set_no_action_dtor() { m_no_action_dtor = true; } void set_call_destructor() { m_call_destructor = true; } ~cond_dealtor() { if (m_no_action_dtor) return; if (m_call_destructor) m_p_nd->~leaf(); s_leaf_allocator.deallocate(m_p_nd, 1); } }; /// Branch bag, for split-join. class branch_bag { private: typedef inode_pointer __inp; typedef typename _Alloc::template rebind<__inp>::other __rebind_inp; #ifdef _GLIBCXX_DEBUG typedef std::_GLIBCXX_STD_C::list<__inp, __rebind_inp> bag_type; #else typedef std::list<__inp, __rebind_inp> bag_type; #endif bag_type m_bag; public: void add_branch() { inode_pointer p_nd = s_inode_allocator.allocate(1); __try { m_bag.push_back(p_nd); } __catch(...) { s_inode_allocator.deallocate(p_nd, 1); __throw_exception_again; } } inode_pointer get_branch() { _GLIBCXX_DEBUG_ASSERT(!m_bag.empty()); inode_pointer p_nd = *m_bag.begin(); m_bag.pop_front(); return p_nd; } ~branch_bag() { while (!m_bag.empty()) { inode_pointer p_nd = *m_bag.begin(); s_inode_allocator.deallocate(p_nd, 1); m_bag.pop_front(); } } inline bool empty() const { return m_bag.empty(); } }; #ifdef _GLIBCXX_DEBUG typedef PB_DS_DEBUG_MAP_BASE_C_DEC debug_base; #endif typedef typename traits_type::null_node_update_pointer null_node_update_pointer; public: typedef pat_trie_tag container_category; typedef _Alloc allocator_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef typename traits_base::key_type key_type; typedef typename traits_base::key_pointer key_pointer; typedef typename traits_base::key_const_pointer key_const_pointer; typedef typename traits_base::key_reference key_reference; typedef typename traits_base::key_const_reference key_const_reference; typedef typename traits_base::mapped_type mapped_type; typedef typename traits_base::mapped_pointer mapped_pointer; typedef typename traits_base::mapped_const_pointer mapped_const_pointer; typedef typename traits_base::mapped_reference mapped_reference; typedef typename traits_base::mapped_const_reference mapped_const_reference; typedef typename traits_base::value_type value_type; typedef typename traits_base::pointer pointer; typedef typename traits_base::const_pointer const_pointer; typedef typename traits_base::reference reference; typedef typename traits_base::const_reference const_reference; typedef typename traits_type::access_traits access_traits; typedef typename traits_type::const_iterator point_const_iterator; typedef typename traits_type::iterator point_iterator; typedef point_const_iterator const_iterator; typedef point_iterator iterator; typedef typename traits_type::reverse_iterator reverse_iterator; typedef typename traits_type::const_reverse_iterator const_reverse_iterator; typedef typename traits_type::node_const_iterator node_const_iterator; typedef typename traits_type::node_iterator node_iterator; typedef typename traits_type::node_update node_update; PB_DS_PAT_TRIE_NAME(); PB_DS_PAT_TRIE_NAME(const access_traits&); PB_DS_PAT_TRIE_NAME(const PB_DS_CLASS_C_DEC&); void swap(PB_DS_CLASS_C_DEC&); ~PB_DS_PAT_TRIE_NAME(); inline bool empty() const; inline size_type size() const; inline size_type max_size() const; access_traits& get_access_traits(); const access_traits& get_access_traits() const; node_update& get_node_update(); const node_update& get_node_update() const; inline std::pair insert(const_reference); inline mapped_reference operator[](key_const_reference r_key) { #ifdef PB_DS_DATA_TRUE_INDICATOR return insert(std::make_pair(r_key, mapped_type())).first->second; #else insert(r_key); return traits_base::s_null_type; #endif } inline point_iterator find(key_const_reference); inline point_const_iterator find(key_const_reference) const; inline point_iterator lower_bound(key_const_reference); inline point_const_iterator lower_bound(key_const_reference) const; inline point_iterator upper_bound(key_const_reference); inline point_const_iterator upper_bound(key_const_reference) const; void clear(); inline bool erase(key_const_reference); inline const_iterator erase(const_iterator); #ifdef PB_DS_DATA_TRUE_INDICATOR inline iterator erase(iterator); #endif inline const_reverse_iterator erase(const_reverse_iterator); #ifdef PB_DS_DATA_TRUE_INDICATOR inline reverse_iterator erase(reverse_iterator); #endif template inline size_type erase_if(Pred); void join(PB_DS_CLASS_C_DEC&); void split(key_const_reference, PB_DS_CLASS_C_DEC&); inline iterator begin(); inline const_iterator begin() const; inline iterator end(); inline const_iterator end() const; inline reverse_iterator rbegin(); inline const_reverse_iterator rbegin() const; inline reverse_iterator rend(); inline const_reverse_iterator rend() const; /// Returns a const node_iterator corresponding to the node at the /// root of the tree. inline node_const_iterator node_begin() const; /// Returns a node_iterator corresponding to the node at the /// root of the tree. inline node_iterator node_begin(); /// Returns a const node_iterator corresponding to a node just /// after a leaf of the tree. inline node_const_iterator node_end() const; /// Returns a node_iterator corresponding to a node just /// after a leaf of the tree. inline node_iterator node_end(); #ifdef PB_DS_PAT_TRIE_TRACE_ void trace() const; #endif protected: template void copy_from_range(It, It); void value_swap(PB_DS_CLASS_C_DEC&); node_pointer recursive_copy_node(node_const_pointer); private: void initialize(); inline void apply_update(node_pointer, null_node_update_pointer); template inline void apply_update(node_pointer, Node_Update_*); bool join_prep(PB_DS_CLASS_C_DEC&, branch_bag&); void rec_join_prep(node_const_pointer, node_const_pointer, branch_bag&); void rec_join_prep(leaf_const_pointer, leaf_const_pointer, branch_bag&); void rec_join_prep(leaf_const_pointer, inode_const_pointer, branch_bag&); void rec_join_prep(inode_const_pointer, leaf_const_pointer, branch_bag&); void rec_join_prep(inode_const_pointer, inode_const_pointer, branch_bag&); node_pointer rec_join(node_pointer, node_pointer, size_type, branch_bag&); node_pointer rec_join(leaf_pointer, leaf_pointer, branch_bag&); node_pointer rec_join(leaf_pointer, inode_pointer, size_type, branch_bag&); node_pointer rec_join(inode_pointer, leaf_pointer, size_type, branch_bag&); node_pointer rec_join(inode_pointer, inode_pointer, branch_bag&); size_type keys_diff_ind(typename access_traits::const_iterator, typename access_traits::const_iterator, typename access_traits::const_iterator, typename access_traits::const_iterator); inode_pointer insert_branch(node_pointer, node_pointer, branch_bag&); void update_min_max_for_inserted_leaf(leaf_pointer); void erase_leaf(leaf_pointer); inline void actual_erase_leaf(leaf_pointer); void clear_imp(node_pointer); void erase_fixup(inode_pointer); void update_min_max_for_erased_leaf(leaf_pointer); static inline a_const_iterator pref_begin(node_const_pointer); static inline a_const_iterator pref_end(node_const_pointer); inline node_pointer find_imp(key_const_reference); inline node_pointer lower_bound_imp(key_const_reference); inline node_pointer upper_bound_imp(key_const_reference); inline static leaf_const_pointer leftmost_descendant(node_const_pointer); inline static leaf_pointer leftmost_descendant(node_pointer); inline static leaf_const_pointer rightmost_descendant(node_const_pointer); inline static leaf_pointer rightmost_descendant(node_pointer); #ifdef _GLIBCXX_DEBUG void assert_valid(const char*, int) const; void assert_iterators(const char*, int) const; void assert_reverse_iterators(const char*, int) const; static size_type recursive_count_leafs(node_const_pointer, const char*, int); #endif #ifdef PB_DS_PAT_TRIE_TRACE_ static void trace_node(node_const_pointer, size_type); template static void trace_node_metadata(node_const_pointer, type_to_type); static void trace_node_metadata(node_const_pointer, type_to_type); #endif leaf_pointer split_prep(key_const_reference, PB_DS_CLASS_C_DEC&, branch_bag&); node_pointer rec_split(node_pointer, a_const_iterator, a_const_iterator, PB_DS_CLASS_C_DEC&, branch_bag&); void split_insert_branch(size_type, a_const_iterator, inode_iterator, size_type, branch_bag&); static head_allocator s_head_allocator; static inode_allocator s_inode_allocator; static leaf_allocator s_leaf_allocator; head_pointer m_p_head; size_type m_size; }; #define PB_DS_ASSERT_NODE_VALID(X) \ _GLIBCXX_DEBUG_ONLY(X->assert_valid(this, __FILE__, __LINE__);) #define PB_DS_RECURSIVE_COUNT_LEAFS(X) \ recursive_count_leafs(X, __FILE__, __LINE__) #include #include #include #include #include #include #include #include #include #include #include #undef PB_DS_RECURSIVE_COUNT_LEAFS #undef PB_DS_ASSERT_NODE_VALID #undef PB_DS_CLASS_C_DEC #undef PB_DS_CLASS_T_DEC #undef PB_DS_PAT_TRIE_NAME #undef PB_DS_PAT_TRIE_TRAITS_BASE #undef PB_DS_DEBUG_MAP_BASE_C_DEC } // namespace detail } // namespace __gnu_pbds PK!ڂj.8/ext/pb_ds/detail/pat_trie_/pat_trie_base.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/pat_trie_base.hpp * Contains the base class for a patricia tree. */ #ifndef PB_DS_PAT_TRIE_BASE #define PB_DS_PAT_TRIE_BASE #include namespace __gnu_pbds { namespace detail { /// Base type for PATRICIA trees. struct pat_trie_base { /** * @brief Three types of nodes. * * i_node is used by _Inode, leaf_node by _Leaf, and head_node by _Head. */ enum node_type { i_node, leaf_node, head_node }; /// Metadata base primary template. template struct _Metadata { typedef Metadata metadata_type; typedef _Alloc allocator_type; typedef typename _Alloc::template rebind __rebind_m; typedef typename __rebind_m::other::const_reference const_reference; const_reference get_metadata() const { return m_metadata; } metadata_type m_metadata; }; /// Specialization for null metadata. template struct _Metadata { typedef null_type metadata_type; typedef _Alloc allocator_type; }; /// Node base. template struct _Node_base : public Metadata { private: typedef typename Metadata::allocator_type _Alloc; public: typedef _Alloc allocator_type; typedef _ATraits access_traits; typedef typename _ATraits::type_traits type_traits; typedef typename _Alloc::template rebind<_Node_base> __rebind_n; typedef typename __rebind_n::other::pointer node_pointer; node_pointer m_p_parent; const node_type m_type; _Node_base(node_type type) : m_type(type) { } typedef typename _Alloc::template rebind<_ATraits> __rebind_at; typedef typename __rebind_at::other::const_pointer a_const_pointer; typedef typename _ATraits::const_iterator a_const_iterator; #ifdef _GLIBCXX_DEBUG typedef std::pair node_debug_info; void assert_valid(a_const_pointer p_traits, const char* __file, int __line) const { assert_valid_imp(p_traits, __file, __line); } virtual node_debug_info assert_valid_imp(a_const_pointer, const char*, int) const = 0; #endif }; /// Head node for PATRICIA tree. template struct _Head : public _Node_base<_ATraits, Metadata> { typedef _Node_base<_ATraits, Metadata> base_type; typedef typename base_type::type_traits type_traits; typedef typename base_type::node_pointer node_pointer; node_pointer m_p_min; node_pointer m_p_max; _Head() : base_type(head_node) { } #ifdef _GLIBCXX_DEBUG typedef typename base_type::node_debug_info node_debug_info; typedef typename base_type::a_const_pointer a_const_pointer; virtual node_debug_info assert_valid_imp(a_const_pointer, const char* __file, int __line) const { _GLIBCXX_DEBUG_VERIFY_AT(false, _M_message("Assertion from %1;:%2;") ._M_string(__FILE__)._M_integer(__LINE__), __file, __line); return node_debug_info(); } #endif }; /// Leaf node for PATRICIA tree. template struct _Leaf : public _Node_base<_ATraits, Metadata> { typedef _Node_base<_ATraits, Metadata> base_type; typedef typename base_type::type_traits type_traits; typedef typename type_traits::value_type value_type; typedef typename type_traits::reference reference; typedef typename type_traits::const_reference const_reference; private: value_type m_value; _Leaf(const _Leaf&); public: _Leaf(const_reference other) : base_type(leaf_node), m_value(other) { } reference value() { return m_value; } const_reference value() const { return m_value; } #ifdef _GLIBCXX_DEBUG typedef typename base_type::node_debug_info node_debug_info; typedef typename base_type::a_const_pointer a_const_pointer; virtual node_debug_info assert_valid_imp(a_const_pointer p_traits, const char* __file, int __line) const { PB_DS_DEBUG_VERIFY(base_type::m_type == leaf_node); node_debug_info ret; const_reference r_val = value(); return std::make_pair(p_traits->begin(p_traits->extract_key(r_val)), p_traits->end(p_traits->extract_key(r_val))); } virtual ~_Leaf() { } #endif }; /// Internal node type, PATRICIA tree. template struct _Inode : public _Node_base<_ATraits, Metadata> { typedef _Node_base<_ATraits, Metadata> base_type; typedef typename base_type::type_traits type_traits; typedef typename base_type::access_traits access_traits; typedef typename type_traits::value_type value_type; typedef typename base_type::allocator_type _Alloc; typedef _Alloc allocator_type; typedef typename _Alloc::size_type size_type; private: typedef typename base_type::a_const_pointer a_const_pointer; typedef typename base_type::a_const_iterator a_const_iterator; typedef typename base_type::node_pointer node_pointer; typedef typename _Alloc::template rebind __rebind_n; typedef typename __rebind_n::other::const_pointer node_const_pointer; typedef _Leaf<_ATraits, Metadata> leaf; typedef typename _Alloc::template rebind::other __rebind_l; typedef typename __rebind_l::pointer leaf_pointer; typedef typename __rebind_l::const_pointer leaf_const_pointer; typedef typename _Alloc::template rebind<_Inode>::other __rebind_in; typedef typename __rebind_in::pointer inode_pointer; typedef typename __rebind_in::const_pointer inode_const_pointer; inline size_type get_pref_pos(a_const_iterator, a_const_iterator, a_const_pointer) const; public: typedef typename _Alloc::template rebind::other __rebind_np; typedef typename __rebind_np::pointer node_pointer_pointer; typedef typename __rebind_np::reference node_pointer_reference; enum { arr_size = _ATraits::max_size + 1 }; PB_DS_STATIC_ASSERT(min_arr_size, arr_size >= 2); /// Constant child iterator. struct const_iterator { node_pointer_pointer m_p_p_cur; node_pointer_pointer m_p_p_end; typedef std::forward_iterator_tag iterator_category; typedef typename _Alloc::difference_type difference_type; typedef node_pointer value_type; typedef node_pointer_pointer pointer; typedef node_pointer_reference reference; const_iterator(node_pointer_pointer p_p_cur = 0, node_pointer_pointer p_p_end = 0) : m_p_p_cur(p_p_cur), m_p_p_end(p_p_end) { } bool operator==(const const_iterator& other) const { return m_p_p_cur == other.m_p_p_cur; } bool operator!=(const const_iterator& other) const { return m_p_p_cur != other.m_p_p_cur; } const_iterator& operator++() { do ++m_p_p_cur; while (m_p_p_cur != m_p_p_end && *m_p_p_cur == 0); return *this; } const_iterator operator++(int) { const_iterator ret_it(*this); operator++(); return ret_it; } const node_pointer_pointer operator->() const { _GLIBCXX_DEBUG_ONLY(assert_referencible();) return m_p_p_cur; } node_const_pointer operator*() const { _GLIBCXX_DEBUG_ONLY(assert_referencible();) return *m_p_p_cur; } protected: #ifdef _GLIBCXX_DEBUG void assert_referencible() const { _GLIBCXX_DEBUG_ASSERT(m_p_p_cur != m_p_p_end && *m_p_p_cur != 0); } #endif }; /// Child iterator. struct iterator : public const_iterator { public: typedef std::forward_iterator_tag iterator_category; typedef typename _Alloc::difference_type difference_type; typedef node_pointer value_type; typedef node_pointer_pointer pointer; typedef node_pointer_reference reference; inline iterator(node_pointer_pointer p_p_cur = 0, node_pointer_pointer p_p_end = 0) : const_iterator(p_p_cur, p_p_end) { } bool operator==(const iterator& other) const { return const_iterator::m_p_p_cur == other.m_p_p_cur; } bool operator!=(const iterator& other) const { return const_iterator::m_p_p_cur != other.m_p_p_cur; } iterator& operator++() { const_iterator::operator++(); return *this; } iterator operator++(int) { iterator ret_it(*this); operator++(); return ret_it; } node_pointer_pointer operator->() { _GLIBCXX_DEBUG_ONLY(const_iterator::assert_referencible();) return const_iterator::m_p_p_cur; } node_pointer operator*() { _GLIBCXX_DEBUG_ONLY(const_iterator::assert_referencible();) return *const_iterator::m_p_p_cur; } }; _Inode(size_type, const a_const_iterator); void update_prefixes(a_const_pointer); const_iterator begin() const; iterator begin(); const_iterator end() const; iterator end(); inline node_pointer get_child_node(a_const_iterator, a_const_iterator, a_const_pointer); inline node_const_pointer get_child_node(a_const_iterator, a_const_iterator, a_const_pointer) const; inline iterator get_child_it(a_const_iterator, a_const_iterator, a_const_pointer); inline node_pointer get_lower_bound_child_node(a_const_iterator, a_const_iterator, size_type, a_const_pointer); inline node_pointer add_child(node_pointer, a_const_iterator, a_const_iterator, a_const_pointer); inline node_const_pointer get_join_child(node_const_pointer, a_const_pointer) const; inline node_pointer get_join_child(node_pointer, a_const_pointer); void remove_child(node_pointer); void remove_child(iterator); void replace_child(node_pointer, a_const_iterator, a_const_iterator, a_const_pointer); inline a_const_iterator pref_b_it() const; inline a_const_iterator pref_e_it() const; bool should_be_mine(a_const_iterator, a_const_iterator, size_type, a_const_pointer) const; leaf_pointer leftmost_descendant(); leaf_const_pointer leftmost_descendant() const; leaf_pointer rightmost_descendant(); leaf_const_pointer rightmost_descendant() const; #ifdef _GLIBCXX_DEBUG typedef typename base_type::node_debug_info node_debug_info; virtual node_debug_info assert_valid_imp(a_const_pointer, const char*, int) const; #endif size_type get_e_ind() const { return m_e_ind; } private: _Inode(const _Inode&); size_type get_begin_pos() const; static __rebind_l s_leaf_alloc; static __rebind_in s_inode_alloc; const size_type m_e_ind; a_const_iterator m_pref_b_it; a_const_iterator m_pref_e_it; node_pointer m_a_p_children[arr_size]; }; #define PB_DS_CONST_IT_C_DEC \ _CIter #define PB_DS_CONST_ODIR_IT_C_DEC \ _CIter #define PB_DS_IT_C_DEC \ _Iter #define PB_DS_ODIR_IT_C_DEC \ _Iter /// Const iterator. template class _CIter { public: // These types are all the same for the first four template arguments. typedef typename Node::allocator_type allocator_type; typedef typename Node::type_traits type_traits; typedef std::bidirectional_iterator_tag iterator_category; typedef typename allocator_type::difference_type difference_type; typedef typename type_traits::value_type value_type; typedef typename type_traits::pointer pointer; typedef typename type_traits::reference reference; typedef typename type_traits::const_pointer const_pointer; typedef typename type_traits::const_reference const_reference; typedef allocator_type _Alloc; typedef typename _Alloc::template rebind __rebind_n; typedef typename __rebind_n::other::pointer node_pointer; typedef typename _Alloc::template rebind __rebind_l; typedef typename __rebind_l::other::pointer leaf_pointer; typedef typename __rebind_l::other::const_pointer leaf_const_pointer; typedef typename _Alloc::template rebind __rebind_h; typedef typename __rebind_h::other::pointer head_pointer; typedef typename _Alloc::template rebind __rebind_in; typedef typename __rebind_in::other::pointer inode_pointer; typedef typename Inode::iterator inode_iterator; node_pointer m_p_nd; _CIter(node_pointer p_nd = 0) : m_p_nd(p_nd) { } _CIter(const PB_DS_CONST_ODIR_IT_C_DEC& other) : m_p_nd(other.m_p_nd) { } _CIter& operator=(const _CIter& other) { m_p_nd = other.m_p_nd; return *this; } _CIter& operator=(const PB_DS_CONST_ODIR_IT_C_DEC& other) { m_p_nd = other.m_p_nd; return *this; } const_pointer operator->() const { _GLIBCXX_DEBUG_ASSERT(m_p_nd->m_type == leaf_node); return &static_cast(m_p_nd)->value(); } const_reference operator*() const { _GLIBCXX_DEBUG_ASSERT(m_p_nd->m_type == leaf_node); return static_cast(m_p_nd)->value(); } bool operator==(const _CIter& other) const { return m_p_nd == other.m_p_nd; } bool operator==(const PB_DS_CONST_ODIR_IT_C_DEC& other) const { return m_p_nd == other.m_p_nd; } bool operator!=(const _CIter& other) const { return m_p_nd != other.m_p_nd; } bool operator!=(const PB_DS_CONST_ODIR_IT_C_DEC& other) const { return m_p_nd != other.m_p_nd; } _CIter& operator++() { inc(integral_constant()); return *this; } _CIter operator++(int) { _CIter ret_it(m_p_nd); operator++(); return ret_it; } _CIter& operator--() { dec(integral_constant()); return *this; } _CIter operator--(int) { _CIter ret_it(m_p_nd); operator--(); return ret_it; } protected: void inc(false_type) { dec(true_type()); } void inc(true_type) { if (m_p_nd->m_type == head_node) { m_p_nd = static_cast(m_p_nd)->m_p_min; return; } node_pointer p_y = m_p_nd->m_p_parent; while (p_y->m_type != head_node && get_larger_sibling(m_p_nd) == 0) { m_p_nd = p_y; p_y = p_y->m_p_parent; } if (p_y->m_type == head_node) { m_p_nd = p_y; return; } m_p_nd = leftmost_descendant(get_larger_sibling(m_p_nd)); } void dec(false_type) { inc(true_type()); } void dec(true_type) { if (m_p_nd->m_type == head_node) { m_p_nd = static_cast(m_p_nd)->m_p_max; return; } node_pointer p_y = m_p_nd->m_p_parent; while (p_y->m_type != head_node && get_smaller_sibling(m_p_nd) == 0) { m_p_nd = p_y; p_y = p_y->m_p_parent; } if (p_y->m_type == head_node) { m_p_nd = p_y; return; } m_p_nd = rightmost_descendant(get_smaller_sibling(m_p_nd)); } static node_pointer get_larger_sibling(node_pointer p_nd) { inode_pointer p_parent = static_cast(p_nd->m_p_parent); inode_iterator it = p_parent->begin(); while (*it != p_nd) ++it; inode_iterator next_it = it; ++next_it; return (next_it == p_parent->end())? 0 : *next_it; } static node_pointer get_smaller_sibling(node_pointer p_nd) { inode_pointer p_parent = static_cast(p_nd->m_p_parent); inode_iterator it = p_parent->begin(); if (*it == p_nd) return 0; inode_iterator prev_it; do { prev_it = it; ++it; if (*it == p_nd) return *prev_it; } while (true); _GLIBCXX_DEBUG_ASSERT(false); return 0; } static leaf_pointer leftmost_descendant(node_pointer p_nd) { if (p_nd->m_type == leaf_node) return static_cast(p_nd); return static_cast(p_nd)->leftmost_descendant(); } static leaf_pointer rightmost_descendant(node_pointer p_nd) { if (p_nd->m_type == leaf_node) return static_cast(p_nd); return static_cast(p_nd)->rightmost_descendant(); } }; /// Iterator. template class _Iter : public _CIter { public: typedef _CIter base_type; typedef typename base_type::allocator_type allocator_type; typedef typename base_type::type_traits type_traits; typedef typename type_traits::value_type value_type; typedef typename type_traits::pointer pointer; typedef typename type_traits::reference reference; typedef typename base_type::node_pointer node_pointer; typedef typename base_type::leaf_pointer leaf_pointer; typedef typename base_type::leaf_const_pointer leaf_const_pointer; typedef typename base_type::head_pointer head_pointer; typedef typename base_type::inode_pointer inode_pointer; _Iter(node_pointer p_nd = 0) : base_type(p_nd) { } _Iter(const PB_DS_ODIR_IT_C_DEC& other) : base_type(other.m_p_nd) { } _Iter& operator=(const _Iter& other) { base_type::m_p_nd = other.m_p_nd; return *this; } _Iter& operator=(const PB_DS_ODIR_IT_C_DEC& other) { base_type::m_p_nd = other.m_p_nd; return *this; } pointer operator->() const { _GLIBCXX_DEBUG_ASSERT(base_type::m_p_nd->m_type == leaf_node); return &static_cast(base_type::m_p_nd)->value(); } reference operator*() const { _GLIBCXX_DEBUG_ASSERT(base_type::m_p_nd->m_type == leaf_node); return static_cast(base_type::m_p_nd)->value(); } _Iter& operator++() { base_type::operator++(); return *this; } _Iter operator++(int) { _Iter ret(base_type::m_p_nd); operator++(); return ret; } _Iter& operator--() { base_type::operator--(); return *this; } _Iter operator--(int) { _Iter ret(base_type::m_p_nd); operator--(); return ret; } }; #undef PB_DS_CONST_ODIR_IT_C_DEC #undef PB_DS_ODIR_IT_C_DEC #define PB_DS_PAT_TRIE_NODE_CONST_ITERATOR_C_DEC \ _Node_citer #define PB_DS_PAT_TRIE_NODE_ITERATOR_C_DEC \ _Node_iter /// Node const iterator. template class _Node_citer { protected: typedef typename _Alloc::template rebind __rebind_n; typedef typename __rebind_n::other::pointer node_pointer; typedef typename _Alloc::template rebind __rebind_l; typedef typename __rebind_l::other::pointer leaf_pointer; typedef typename __rebind_l::other::const_pointer leaf_const_pointer; typedef typename _Alloc::template rebind __rebind_in; typedef typename __rebind_in::other::pointer inode_pointer; typedef typename __rebind_in::other::const_pointer inode_const_pointer; typedef typename Node::a_const_pointer a_const_pointer; typedef typename Node::a_const_iterator a_const_iterator; private: a_const_iterator pref_begin() const { if (m_p_nd->m_type == leaf_node) { leaf_const_pointer lcp = static_cast(m_p_nd); return m_p_traits->begin(m_p_traits->extract_key(lcp->value())); } _GLIBCXX_DEBUG_ASSERT(m_p_nd->m_type == i_node); return static_cast(m_p_nd)->pref_b_it(); } a_const_iterator pref_end() const { if (m_p_nd->m_type == leaf_node) { leaf_const_pointer lcp = static_cast(m_p_nd); return m_p_traits->end(m_p_traits->extract_key(lcp->value())); } _GLIBCXX_DEBUG_ASSERT(m_p_nd->m_type == i_node); return static_cast(m_p_nd)->pref_e_it(); } public: typedef trivial_iterator_tag iterator_category; typedef trivial_iterator_difference_type difference_type; typedef typename _Alloc::size_type size_type; typedef _CIterator value_type; typedef value_type reference; typedef value_type const_reference; /// Metadata type. typedef typename Node::metadata_type metadata_type; /// Const metadata reference type. typedef typename _Alloc::template rebind __rebind_m; typedef typename __rebind_m::other __rebind_ma; typedef typename __rebind_ma::const_reference metadata_const_reference; inline _Node_citer(node_pointer p_nd = 0, a_const_pointer p_traits = 0) : m_p_nd(const_cast(p_nd)), m_p_traits(p_traits) { } /// Subtree valid prefix. std::pair valid_prefix() const { return std::make_pair(pref_begin(), pref_end()); } /// Const access; returns the __const iterator* associated with /// the current leaf. const_reference operator*() const { _GLIBCXX_DEBUG_ASSERT(num_children() == 0); return _CIterator(m_p_nd); } /// Metadata access. metadata_const_reference get_metadata() const { return m_p_nd->get_metadata(); } /// Returns the number of children in the corresponding node. size_type num_children() const { if (m_p_nd->m_type == leaf_node) return 0; _GLIBCXX_DEBUG_ASSERT(m_p_nd->m_type == i_node); inode_pointer inp = static_cast(m_p_nd); return std::distance(inp->begin(), inp->end()); } /// Returns a __const node __iterator to the corresponding node's /// i-th child. _Node_citer get_child(size_type i) const { _GLIBCXX_DEBUG_ASSERT(m_p_nd->m_type == i_node); inode_pointer inp = static_cast(m_p_nd); typename Inode::iterator it = inp->begin(); std::advance(it, i); return _Node_citer(*it, m_p_traits); } /// Compares content to a different iterator object. bool operator==(const _Node_citer& other) const { return m_p_nd == other.m_p_nd; } /// Compares content (negatively) to a different iterator object. bool operator!=(const _Node_citer& other) const { return m_p_nd != other.m_p_nd; } node_pointer m_p_nd; a_const_pointer m_p_traits; }; /// Node iterator. template class _Node_iter : public _Node_citer { private: typedef _Node_citer base_type; typedef typename _Alloc::template rebind __rebind_n; typedef typename __rebind_n::other::pointer node_pointer; typedef typename base_type::inode_pointer inode_pointer; typedef typename base_type::a_const_pointer a_const_pointer; typedef Iterator iterator; public: typedef typename base_type::size_type size_type; typedef Iterator value_type; typedef value_type reference; typedef value_type const_reference; _Node_iter(node_pointer p_nd = 0, a_const_pointer p_traits = 0) : base_type(p_nd, p_traits) { } /// Access; returns the iterator* associated with the current leaf. reference operator*() const { _GLIBCXX_DEBUG_ASSERT(base_type::num_children() == 0); return iterator(base_type::m_p_nd); } /// Returns a node __iterator to the corresponding node's i-th child. _Node_iter get_child(size_type i) const { _GLIBCXX_DEBUG_ASSERT(base_type::m_p_nd->m_type == i_node); typename Inode::iterator it = static_cast(base_type::m_p_nd)->begin(); std::advance(it, i); return _Node_iter(*it, base_type::m_p_traits); } }; }; #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ pat_trie_base::_Inode<_ATraits, Metadata> PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::__rebind_l PB_DS_CLASS_C_DEC::s_leaf_alloc; PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::__rebind_in PB_DS_CLASS_C_DEC::s_inode_alloc; PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: get_pref_pos(a_const_iterator b_it, a_const_iterator e_it, a_const_pointer p_traits) const { if (static_cast(std::distance(b_it, e_it)) <= m_e_ind) return 0; std::advance(b_it, m_e_ind); return 1 + p_traits->e_pos(*b_it); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: _Inode(size_type len, const a_const_iterator it) : base_type(i_node), m_e_ind(len), m_pref_b_it(it), m_pref_e_it(it) { std::advance(m_pref_e_it, m_e_ind); std::fill(m_a_p_children, m_a_p_children + arr_size, static_cast(0)); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: update_prefixes(a_const_pointer p_traits) { node_pointer p_first = *begin(); if (p_first->m_type == leaf_node) { leaf_const_pointer p = static_cast(p_first); m_pref_b_it = p_traits->begin(access_traits::extract_key(p->value())); } else { inode_pointer p = static_cast(p_first); _GLIBCXX_DEBUG_ASSERT(p_first->m_type == i_node); m_pref_b_it = p->pref_b_it(); } m_pref_e_it = m_pref_b_it; std::advance(m_pref_e_it, m_e_ind); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: begin() const { typedef node_pointer_pointer pointer_type; pointer_type p = const_cast(m_a_p_children); return const_iterator(p + get_begin_pos(), p + arr_size); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: begin() { return iterator(m_a_p_children + get_begin_pos(), m_a_p_children + arr_size); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: end() const { typedef node_pointer_pointer pointer_type; pointer_type p = const_cast(m_a_p_children) + arr_size; return const_iterator(p, p); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: end() { return iterator(m_a_p_children + arr_size, m_a_p_children + arr_size); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: get_child_node(a_const_iterator b_it, a_const_iterator e_it, a_const_pointer p_traits) { const size_type i = get_pref_pos(b_it, e_it, p_traits); _GLIBCXX_DEBUG_ASSERT(i < arr_size); return m_a_p_children[i]; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: get_child_it(a_const_iterator b_it, a_const_iterator e_it, a_const_pointer p_traits) { const size_type i = get_pref_pos(b_it, e_it, p_traits); _GLIBCXX_DEBUG_ASSERT(i < arr_size); _GLIBCXX_DEBUG_ASSERT(m_a_p_children[i] != 0); return iterator(m_a_p_children + i, m_a_p_children + i); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_const_pointer PB_DS_CLASS_C_DEC:: get_child_node(a_const_iterator b_it, a_const_iterator e_it, a_const_pointer p_traits) const { return const_cast(get_child_node(b_it, e_it, p_traits)); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: get_lower_bound_child_node(a_const_iterator b_it, a_const_iterator e_it, size_type checked_ind, a_const_pointer p_traits) { if (!should_be_mine(b_it, e_it, checked_ind, p_traits)) { if (p_traits->cmp_prefixes(b_it, e_it, m_pref_b_it, m_pref_e_it, true)) return leftmost_descendant(); return rightmost_descendant(); } size_type i = get_pref_pos(b_it, e_it, p_traits); _GLIBCXX_DEBUG_ASSERT(i < arr_size); if (m_a_p_children[i] != 0) return m_a_p_children[i]; while (++i < arr_size) if (m_a_p_children[i] != 0) { const node_type& __nt = m_a_p_children[i]->m_type; node_pointer ret = m_a_p_children[i]; if (__nt == leaf_node) return ret; _GLIBCXX_DEBUG_ASSERT(__nt == i_node); inode_pointer inp = static_cast(ret); return inp->leftmost_descendant(); } return rightmost_descendant(); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: add_child(node_pointer p_nd, a_const_iterator b_it, a_const_iterator e_it, a_const_pointer p_traits) { const size_type i = get_pref_pos(b_it, e_it, p_traits); _GLIBCXX_DEBUG_ASSERT(i < arr_size); if (m_a_p_children[i] == 0) { m_a_p_children[i] = p_nd; p_nd->m_p_parent = this; return p_nd; } return m_a_p_children[i]; } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_const_pointer PB_DS_CLASS_C_DEC:: get_join_child(node_const_pointer p_nd, a_const_pointer p_tr) const { node_pointer p = const_cast(p_nd); return const_cast(this)->get_join_child(p, p_tr); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: get_join_child(node_pointer p_nd, a_const_pointer p_traits) { size_type i; a_const_iterator b_it; a_const_iterator e_it; if (p_nd->m_type == leaf_node) { leaf_const_pointer p = static_cast(p_nd); typedef typename type_traits::key_const_reference kcr; kcr r_key = access_traits::extract_key(p->value()); b_it = p_traits->begin(r_key); e_it = p_traits->end(r_key); } else { b_it = static_cast(p_nd)->pref_b_it(); e_it = static_cast(p_nd)->pref_e_it(); } i = get_pref_pos(b_it, e_it, p_traits); _GLIBCXX_DEBUG_ASSERT(i < arr_size); return m_a_p_children[i]; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: remove_child(node_pointer p_nd) { size_type i = 0; for (; i < arr_size; ++i) if (m_a_p_children[i] == p_nd) { m_a_p_children[i] = 0; return; } _GLIBCXX_DEBUG_ASSERT(i != arr_size); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: remove_child(iterator it) { *it.m_p_p_cur = 0; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: replace_child(node_pointer p_nd, a_const_iterator b_it, a_const_iterator e_it, a_const_pointer p_traits) { const size_type i = get_pref_pos(b_it, e_it, p_traits); _GLIBCXX_DEBUG_ASSERT(i < arr_size); m_a_p_children[i] = p_nd; p_nd->m_p_parent = this; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::a_const_iterator PB_DS_CLASS_C_DEC:: pref_b_it() const { return m_pref_b_it; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::a_const_iterator PB_DS_CLASS_C_DEC:: pref_e_it() const { return m_pref_e_it; } PB_DS_CLASS_T_DEC bool PB_DS_CLASS_C_DEC:: should_be_mine(a_const_iterator b_it, a_const_iterator e_it, size_type checked_ind, a_const_pointer p_traits) const { if (m_e_ind == 0) return true; const size_type num_es = std::distance(b_it, e_it); if (num_es < m_e_ind) return false; a_const_iterator key_b_it = b_it; std::advance(key_b_it, checked_ind); a_const_iterator key_e_it = b_it; std::advance(key_e_it, m_e_ind); a_const_iterator value_b_it = m_pref_b_it; std::advance(value_b_it, checked_ind); a_const_iterator value_e_it = m_pref_b_it; std::advance(value_e_it, m_e_ind); return p_traits->equal_prefixes(key_b_it, key_e_it, value_b_it, value_e_it); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::leaf_pointer PB_DS_CLASS_C_DEC:: leftmost_descendant() { node_pointer p_pot = *begin(); if (p_pot->m_type == leaf_node) return (static_cast(p_pot)); _GLIBCXX_DEBUG_ASSERT(p_pot->m_type == i_node); return static_cast(p_pot)->leftmost_descendant(); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::leaf_const_pointer PB_DS_CLASS_C_DEC:: leftmost_descendant() const { return const_cast(this)->leftmost_descendant(); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::leaf_pointer PB_DS_CLASS_C_DEC:: rightmost_descendant() { const size_type num_children = std::distance(begin(), end()); _GLIBCXX_DEBUG_ASSERT(num_children >= 2); iterator it = begin(); std::advance(it, num_children - 1); node_pointer p_pot =* it; if (p_pot->m_type == leaf_node) return static_cast(p_pot); _GLIBCXX_DEBUG_ASSERT(p_pot->m_type == i_node); return static_cast(p_pot)->rightmost_descendant(); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::leaf_const_pointer PB_DS_CLASS_C_DEC:: rightmost_descendant() const { return const_cast(this)->rightmost_descendant(); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: get_begin_pos() const { size_type i = 0; for (; i < arr_size && m_a_p_children[i] == 0; ++i) ; return i; } #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_debug_info PB_DS_CLASS_C_DEC:: assert_valid_imp(a_const_pointer p_traits, const char* __file, int __line) const { PB_DS_DEBUG_VERIFY(base_type::m_type == i_node); PB_DS_DEBUG_VERIFY(static_cast(std::distance(pref_b_it(), pref_e_it())) == m_e_ind); PB_DS_DEBUG_VERIFY(std::distance(begin(), end()) >= 2); for (typename _Inode::const_iterator it = begin(); it != end(); ++it) { node_const_pointer p_nd = *it; PB_DS_DEBUG_VERIFY(p_nd->m_p_parent == this); node_debug_info child_ret = p_nd->assert_valid_imp(p_traits, __file, __line); PB_DS_DEBUG_VERIFY(static_cast(std::distance(child_ret.first, child_ret.second)) >= m_e_ind); PB_DS_DEBUG_VERIFY(should_be_mine(child_ret.first, child_ret.second, 0, p_traits)); PB_DS_DEBUG_VERIFY(get_pref_pos(child_ret.first, child_ret.second, p_traits) == static_cast(it.m_p_p_cur - m_a_p_children)); } return std::make_pair(pref_b_it(), pref_e_it()); } #endif #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC } // namespace detail } // namespace __gnu_pbds #endif PK!9ݧ68/ext/pb_ds/detail/pat_trie_/policy_access_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/policy_access_fn_imps.hpp * Contains an implementation class for pat_trie. */ PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::access_traits& PB_DS_CLASS_C_DEC:: get_access_traits() { return *this; } PB_DS_CLASS_T_DEC const typename PB_DS_CLASS_C_DEC::access_traits& PB_DS_CLASS_C_DEC:: get_access_traits() const { return *this; } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_update& PB_DS_CLASS_C_DEC:: get_node_update() { return *this; } PB_DS_CLASS_T_DEC const typename PB_DS_CLASS_C_DEC::node_update& PB_DS_CLASS_C_DEC:: get_node_update() const { return *this; } PK!I% h h 08/ext/pb_ds/detail/pat_trie_/r_erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/r_erase_fn_imps.hpp * Contains an implementation class for pat_trie. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: actual_erase_node(node_pointer p_z) { _GLIBCXX_DEBUG_ASSERT(m_size > 0); --m_size; _GLIBCXX_DEBUG_ONLY(debug_base::erase_existing(PB_DS_V2F(p_z->m_value))); p_z->~node(); s_node_allocator.deallocate(p_z, 1); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: update_min_max_for_erased_node(node_pointer p_z) { if (m_size == 1) { m_p_head->m_p_left = m_p_head->m_p_right = m_p_head; return; } if (m_p_head->m_p_left == p_z) { iterator it(p_z); ++it; m_p_head->m_p_left = it.m_p_nd; } else if (m_p_head->m_p_right == p_z) { iterator it(p_z); --it; m_p_head->m_p_right = it.m_p_nd; } } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear() { _GLIBCXX_DEBUG_ONLY(assert_valid(true, true);) clear_imp(m_p_head->m_p_parent); m_size = 0; initialize(); _GLIBCXX_DEBUG_ONLY(debug_base::clear();) _GLIBCXX_DEBUG_ONLY(assert_valid(true, true);) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear_imp(node_pointer p_nd) { if (p_nd == 0) return; clear_imp(p_nd->m_p_left); clear_imp(p_nd->m_p_right); p_nd->~Node(); s_node_allocator.deallocate(p_nd, 1); } PK!ա/8/ext/pb_ds/detail/pat_trie_/rotate_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/rotate_fn_imps.hpp * Contains imps for rotating nodes. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: rotate_left(node_pointer p_x) { node_pointer p_y = p_x->m_p_right; p_x->m_p_right = p_y->m_p_left; if (p_y->m_p_left != 0) p_y->m_p_left->m_p_parent = p_x; p_y->m_p_parent = p_x->m_p_parent; if (p_x == m_p_head->m_p_parent) m_p_head->m_p_parent = p_y; else if (p_x == p_x->m_p_parent->m_p_left) p_x->m_p_parent->m_p_left = p_y; else p_x->m_p_parent->m_p_right = p_y; p_y->m_p_left = p_x; p_x->m_p_parent = p_y; _GLIBCXX_DEBUG_ONLY(assert_node_consistent(p_x);) _GLIBCXX_DEBUG_ONLY(assert_node_consistent(p_y);) apply_update(p_x, (Node_Update*)this); apply_update(p_x->m_p_parent, (Node_Update*)this); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: rotate_right(node_pointer p_x) { node_pointer p_y = p_x->m_p_left; p_x->m_p_left = p_y->m_p_right; if (p_y->m_p_right != 0) p_y->m_p_right->m_p_parent = p_x; p_y->m_p_parent = p_x->m_p_parent; if (p_x == m_p_head->m_p_parent) m_p_head->m_p_parent = p_y; else if (p_x == p_x->m_p_parent->m_p_right) p_x->m_p_parent->m_p_right = p_y; else p_x->m_p_parent->m_p_left = p_y; p_y->m_p_right = p_x; p_x->m_p_parent = p_y; _GLIBCXX_DEBUG_ONLY(assert_node_consistent(p_x);) _GLIBCXX_DEBUG_ONLY(assert_node_consistent(p_y);) apply_update(p_x, (Node_Update*)this); apply_update(p_x->m_p_parent, (Node_Update*)this); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: rotate_parent(node_pointer p_nd) { node_pointer p_parent = p_nd->m_p_parent; if (p_nd == p_parent->m_p_left) rotate_right(p_parent); else rotate_left(p_parent); _GLIBCXX_DEBUG_ASSERT(p_parent->m_p_parent = p_nd); _GLIBCXX_DEBUG_ASSERT(p_nd->m_p_left == p_parent || p_nd->m_p_right == p_parent); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: apply_update(node_pointer /*p_nd*/, __gnu_pbds::null_node_update* /*p_update*/) { } PB_DS_CLASS_T_DEC template inline void PB_DS_CLASS_C_DEC:: apply_update(node_pointer p_nd, Node_Update_* p_update) { p_update->operator()(& PB_DS_V2F(p_nd->m_value),(p_nd->m_p_left == 0) ? 0 : & PB_DS_V2F(p_nd->m_p_left->m_value),(p_nd->m_p_right == 0) ? 0 : & PB_DS_V2F(p_nd->m_p_right->m_value)); } PB_DS_CLASS_T_DEC template inline void PB_DS_CLASS_C_DEC:: update_to_top(node_pointer p_nd, Node_Update_* p_update) { while (p_nd != m_p_head) { apply_update(p_nd, p_update); p_nd = p_nd->m_p_parent; } } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: update_to_top(node_pointer /*p_nd*/, __gnu_pbds::null_node_update* /*p_update*/) { } PK!'--.8/ext/pb_ds/detail/pat_trie_/split_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/split_fn_imps.hpp * Contains an implementation class for pat_trie. */ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: split(key_const_reference r_key, PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) branch_bag bag; leaf_pointer p_split_lf = split_prep(r_key, other, bag); if (p_split_lf == 0) { _GLIBCXX_DEBUG_ASSERT(bag.empty()); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return; } _GLIBCXX_DEBUG_ASSERT(!bag.empty()); other.clear(); m_p_head->m_p_parent = rec_split(m_p_head->m_p_parent, pref_begin(p_split_lf), pref_end(p_split_lf), other, bag); m_p_head->m_p_parent->m_p_parent = m_p_head; head_pointer __ohead = other.m_p_head; __ohead->m_p_max = m_p_head->m_p_max; m_p_head->m_p_max = rightmost_descendant(m_p_head->m_p_parent); __ohead->m_p_min = other.leftmost_descendant(__ohead->m_p_parent); other.m_size = std::distance(other.PB_DS_CLASS_C_DEC::begin(), other.PB_DS_CLASS_C_DEC::end()); m_size -= other.m_size; PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::leaf_pointer PB_DS_CLASS_C_DEC:: split_prep(key_const_reference r_key, PB_DS_CLASS_C_DEC& other, branch_bag& r_bag) { _GLIBCXX_DEBUG_ASSERT(r_bag.empty()); if (m_size == 0) { other.clear(); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return 0; } if (synth_access_traits::cmp_keys(r_key, PB_DS_V2F(static_cast(m_p_head->m_p_min)->value()))) { other.clear(); value_swap(other); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return 0; } if (!synth_access_traits::cmp_keys(r_key, PB_DS_V2F(static_cast(m_p_head->m_p_max)->value()))) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return 0; } iterator it = lower_bound(r_key); if (!synth_access_traits::equal_keys(PB_DS_V2F(*it), r_key)) --it; node_pointer p_nd = it.m_p_nd; _GLIBCXX_DEBUG_ASSERT(p_nd->m_type == leaf_node); leaf_pointer p_ret_l = static_cast(p_nd); while (p_nd->m_type != head_node) { r_bag.add_branch(); p_nd = p_nd->m_p_parent; } _GLIBCXX_DEBUG_ONLY(debug_base::split(r_key,(synth_access_traits&)(*this), other);) return p_ret_l; } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: rec_split(node_pointer p_nd, a_const_iterator b_it, a_const_iterator e_it, PB_DS_CLASS_C_DEC& other, branch_bag& r_bag) { if (p_nd->m_type == leaf_node) { _GLIBCXX_DEBUG_ASSERT(other.m_p_head->m_p_parent == 0); return p_nd; } _GLIBCXX_DEBUG_ASSERT(p_nd->m_type == i_node); inode_pointer p_ind = static_cast(p_nd); node_pointer pfirst = p_ind->get_child_node(b_it, e_it, this); node_pointer p_child_ret = rec_split(pfirst, b_it, e_it, other, r_bag); PB_DS_ASSERT_NODE_VALID(p_child_ret) p_ind->replace_child(p_child_ret, b_it, e_it, this); apply_update(p_ind, (node_update*)this); inode_iterator child_it = p_ind->get_child_it(b_it, e_it, this); const size_type lhs_dist = std::distance(p_ind->begin(), child_it); const size_type lhs_num_children = lhs_dist + 1; _GLIBCXX_DEBUG_ASSERT(lhs_num_children > 0); const size_type rhs_dist = std::distance(p_ind->begin(), p_ind->end()); size_type rhs_num_children = rhs_dist - lhs_num_children; if (rhs_num_children == 0) { apply_update(p_ind, (node_update*)this); return p_ind; } other.split_insert_branch(p_ind->get_e_ind(), b_it, child_it, rhs_num_children, r_bag); child_it = p_ind->get_child_it(b_it, e_it, this); while (rhs_num_children != 0) { ++child_it; p_ind->remove_child(child_it); --rhs_num_children; } apply_update(p_ind, (node_update*)this); const size_type int_dist = std::distance(p_ind->begin(), p_ind->end()); _GLIBCXX_DEBUG_ASSERT(int_dist >= 1); if (int_dist > 1) { p_ind->update_prefixes(this); PB_DS_ASSERT_NODE_VALID(p_ind) apply_update(p_ind, (node_update*)this); return p_ind; } node_pointer p_ret = *p_ind->begin(); p_ind->~inode(); s_inode_allocator.deallocate(p_ind, 1); apply_update(p_ret, (node_update*)this); return p_ret; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: split_insert_branch(size_type e_ind, a_const_iterator b_it, inode_iterator child_b_it, size_type num_children, branch_bag& r_bag) { #ifdef _GLIBCXX_DEBUG if (m_p_head->m_p_parent != 0) PB_DS_ASSERT_NODE_VALID(m_p_head->m_p_parent) #endif const size_type start = m_p_head->m_p_parent == 0 ? 0 : 1; const size_type total_num_children = start + num_children; if (total_num_children == 0) { _GLIBCXX_DEBUG_ASSERT(m_p_head->m_p_parent == 0); return; } if (total_num_children == 1) { if (m_p_head->m_p_parent != 0) { PB_DS_ASSERT_NODE_VALID(m_p_head->m_p_parent) return; } _GLIBCXX_DEBUG_ASSERT(m_p_head->m_p_parent == 0); ++child_b_it; m_p_head->m_p_parent = *child_b_it; m_p_head->m_p_parent->m_p_parent = m_p_head; apply_update(m_p_head->m_p_parent, (node_update*)this); PB_DS_ASSERT_NODE_VALID(m_p_head->m_p_parent) return; } _GLIBCXX_DEBUG_ASSERT(total_num_children > 1); inode_pointer p_new_root = r_bag.get_branch(); new (p_new_root) inode(e_ind, b_it); size_type num_inserted = 0; while (num_inserted++ < num_children) { ++child_b_it; PB_DS_ASSERT_NODE_VALID((*child_b_it)) p_new_root->add_child(*child_b_it, pref_begin(*child_b_it), pref_end(*child_b_it), this); } if (m_p_head->m_p_parent != 0) p_new_root->add_child(m_p_head->m_p_parent, pref_begin(m_p_head->m_p_parent), pref_end(m_p_head->m_p_parent), this); m_p_head->m_p_parent = p_new_root; p_new_root->m_p_parent = m_p_head; apply_update(m_p_head->m_p_parent, (node_update*)this); PB_DS_ASSERT_NODE_VALID(m_p_head->m_p_parent) } PK!'j>>48/ext/pb_ds/detail/pat_trie_/synth_access_traits.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/synth_access_traits.hpp * Contains an implementation class for a patricia tree. */ #ifndef PB_DS_SYNTH_E_ACCESS_TRAITS_HPP #define PB_DS_SYNTH_E_ACCESS_TRAITS_HPP #include namespace __gnu_pbds { namespace detail { #define PB_DS_SYNTH_E_ACCESS_TRAITS_T_DEC \ template #define PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC \ synth_access_traits /// Synthetic element access traits. template struct synth_access_traits : public _ATraits { typedef _ATraits base_type; typedef typename base_type::const_iterator const_iterator; typedef Type_Traits type_traits; typedef typename type_traits::const_reference const_reference; typedef typename type_traits::key_const_reference key_const_reference; synth_access_traits(); synth_access_traits(const base_type&); inline bool equal_prefixes(const_iterator, const_iterator, const_iterator, const_iterator, bool compare_after = true) const; bool equal_keys(key_const_reference, key_const_reference) const; bool cmp_prefixes(const_iterator, const_iterator, const_iterator, const_iterator, bool compare_after = false) const; bool cmp_keys(key_const_reference, key_const_reference) const; inline static key_const_reference extract_key(const_reference); #ifdef _GLIBCXX_DEBUG bool operator()(key_const_reference, key_const_reference); #endif private: inline static key_const_reference extract_key(const_reference, true_type); inline static key_const_reference extract_key(const_reference, false_type); static integral_constant s_set_ind; }; PB_DS_SYNTH_E_ACCESS_TRAITS_T_DEC integral_constant PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC::s_set_ind; PB_DS_SYNTH_E_ACCESS_TRAITS_T_DEC PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC:: synth_access_traits() { } PB_DS_SYNTH_E_ACCESS_TRAITS_T_DEC PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC:: synth_access_traits(const _ATraits& r_traits) : _ATraits(r_traits) { } PB_DS_SYNTH_E_ACCESS_TRAITS_T_DEC inline bool PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC:: equal_prefixes(const_iterator b_l, const_iterator e_l, const_iterator b_r, const_iterator e_r, bool compare_after /*= false */) const { while (b_l != e_l) { if (b_r == e_r) return false; if (base_type::e_pos(*b_l) != base_type::e_pos(*b_r)) return false; ++b_l; ++b_r; } return (!compare_after || b_r == e_r); } PB_DS_SYNTH_E_ACCESS_TRAITS_T_DEC bool PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC:: equal_keys(key_const_reference r_lhs_key, key_const_reference r_rhs_key) const { return equal_prefixes(base_type::begin(r_lhs_key), base_type::end(r_lhs_key), base_type::begin(r_rhs_key), base_type::end(r_rhs_key), true); } PB_DS_SYNTH_E_ACCESS_TRAITS_T_DEC bool PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC:: cmp_prefixes(const_iterator b_l, const_iterator e_l, const_iterator b_r, const_iterator e_r, bool compare_after /* = false*/) const { while (b_l != e_l) { if (b_r == e_r) return false; const typename base_type::size_type l_pos = base_type::e_pos(*b_l); const typename base_type::size_type r_pos = base_type::e_pos(*b_r); if (l_pos != r_pos) return l_pos < r_pos; ++b_l; ++b_r; } if (!compare_after) return false; return b_r != e_r; } PB_DS_SYNTH_E_ACCESS_TRAITS_T_DEC bool PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC:: cmp_keys(key_const_reference r_lhs_key, key_const_reference r_rhs_key) const { return cmp_prefixes(base_type::begin(r_lhs_key), base_type::end(r_lhs_key), base_type::begin(r_rhs_key), base_type::end(r_rhs_key), true); } PB_DS_SYNTH_E_ACCESS_TRAITS_T_DEC inline typename PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC::key_const_reference PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC:: extract_key(const_reference r_val) { return extract_key(r_val, s_set_ind); } PB_DS_SYNTH_E_ACCESS_TRAITS_T_DEC inline typename PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC::key_const_reference PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC:: extract_key(const_reference r_val, true_type) { return r_val; } PB_DS_SYNTH_E_ACCESS_TRAITS_T_DEC inline typename PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC::key_const_reference PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC:: extract_key(const_reference r_val, false_type) { return r_val.first; } #ifdef _GLIBCXX_DEBUG PB_DS_SYNTH_E_ACCESS_TRAITS_T_DEC bool PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC:: operator()(key_const_reference r_lhs, key_const_reference r_rhs) { return cmp_keys(r_lhs, r_rhs); } #endif #undef PB_DS_SYNTH_E_ACCESS_TRAITS_T_DEC #undef PB_DS_SYNTH_E_ACCESS_TRAITS_C_DEC } // namespace detail } // namespace __gnu_pbds #endif PK!11I I .8/ext/pb_ds/detail/pat_trie_/trace_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/trace_fn_imps.hpp * Contains an implementation class for pat_trie_. */ #ifdef PB_DS_PAT_TRIE_TRACE_ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace() const { std::cerr << std::endl; if (m_p_head->m_p_parent == 0) return; trace_node(m_p_head->m_p_parent, 0); std::cerr << std::endl; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace_node(node_const_pointer p_nd, size_type level) { for (size_type i = 0; i < level; ++i) std::cerr << ' '; std::cerr << p_nd << " "; std::cerr << ((p_nd->m_type == pat_trie_leaf_node_type) ? "l " : "i "); trace_node_metadata(p_nd, type_to_type()); typename access_traits::const_iterator el_it = pref_begin(p_nd); while (el_it != pref_end(p_nd)) { std::cerr <<* el_it; ++el_it; } if (p_nd->m_type == pat_trie_leaf_node_type) { std::cerr << std::endl; return; } inode_const_pointer p_internal = static_cast(p_nd); std::cerr << " " << static_cast(p_internal->get_e_ind()) << std::endl; const size_type num_children = std::distance(p_internal->begin(), p_internal->end()); for (size_type child_i = 0; child_i < num_children; ++child_i) { typename inode::const_iterator child_it = p_internal->begin(); std::advance(child_it, num_children - child_i - 1); trace_node(*child_it, level + 1); } } PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: trace_node_metadata(node_const_pointer p_nd, type_to_type) { std::cerr << "(" << static_cast(p_nd->get_metadata()) << ") "; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace_node_metadata(node_const_pointer, type_to_type) { } #endif PK!,'+'8/ext/pb_ds/detail/pat_trie_/traits.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/traits.hpp * Contains an implementation class for pat_trie_. */ #ifndef PB_DS_PAT_TRIE_NODE_AND_IT_TRAITS_HPP #define PB_DS_PAT_TRIE_NODE_AND_IT_TRAITS_HPP #include #include namespace __gnu_pbds { namespace detail { /// Specialization. /// @ingroup traits template class Node_Update, typename _Alloc> struct trie_traits { private: typedef pat_trie_base base_type; typedef types_traits type_traits; public: typedef typename trie_node_metadata_dispatch::type metadata_type; typedef base_type::_Metadata metadata; typedef _ATraits access_traits; /// Type for synthesized traits. typedef __gnu_pbds::detail::synth_access_traits synth_access_traits; typedef base_type::_Node_base node; typedef base_type::_Head head; typedef base_type::_Leaf leaf; typedef base_type::_Inode inode; typedef base_type::_Iter iterator; typedef base_type::_CIter const_iterator; typedef base_type::_Iter reverse_iterator; typedef base_type::_CIter const_reverse_iterator; /// This is an iterator to an iterator: it iterates over nodes, /// and de-referencing it returns one of the tree's iterators. typedef base_type::_Node_citer node_const_iterator; typedef base_type::_Node_iter node_iterator; /// Type for node update. typedef Node_Update node_update; typedef null_node_update* null_node_update_pointer; }; /// Specialization. /// @ingroup traits template class Node_Update, typename _Alloc> struct trie_traits { private: typedef pat_trie_base base_type; typedef types_traits type_traits; public: typedef typename trie_node_metadata_dispatch::type metadata_type; typedef base_type::_Metadata metadata; typedef _ATraits access_traits; /// Type for synthesized traits. typedef __gnu_pbds::detail::synth_access_traits synth_access_traits; typedef base_type::_Node_base node; typedef base_type::_Head head; typedef base_type::_Leaf leaf; typedef base_type::_Inode inode; typedef base_type::_CIter const_iterator; typedef const_iterator iterator; typedef base_type::_CIter const_reverse_iterator; typedef const_reverse_iterator reverse_iterator; /// This is an iterator to an iterator: it iterates over nodes, /// and de-referencing it returns one of the tree's iterators. typedef base_type::_Node_citer node_const_iterator; typedef node_const_iterator node_iterator; /// Type for node update. typedef Node_Update node_update; typedef null_node_update* null_node_update_pointer; }; } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_PAT_TRIE_NODE_AND_IT_TRAITS_HPP PK!(lq/8/ext/pb_ds/detail/pat_trie_/update_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file pat_trie_/update_fn_imps.hpp * Contains an implementation class for pat_trie_. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: apply_update(node_pointer, null_node_update_pointer) { } PB_DS_CLASS_T_DEC template inline void PB_DS_CLASS_C_DEC:: apply_update(node_pointer p_nd, Node_Update_*) { Node_Update_::operator()(node_iterator(p_nd, this), node_const_iterator(0, this)); } PK! C8/ext/pb_ds/detail/rb_tree_map_/constructors_destructor_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rb_tree_map_/constructors_destructor_fn_imps.hpp * Contains an implementation for rb_tree_. */ PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: copy_from_range(It first_it, It last_it) { while (first_it != last_it) insert(*(first_it++)); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_RB_TREE_NAME() { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_RB_TREE_NAME(const Cmp_Fn& r_cmp_fn) : base_type(r_cmp_fn) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_RB_TREE_NAME(const Cmp_Fn& r_cmp_fn, const node_update& r_node_update) : base_type(r_cmp_fn, r_node_update) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_RB_TREE_NAME(const PB_DS_CLASS_C_DEC& other) : base_type(other) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) base_type::swap(other); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: initialize() { base_type::m_p_head->m_red = true; } PK!A 18/ext/pb_ds/detail/rb_tree_map_/debug_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rb_tree_map_/debug_fn_imps.hpp * Contains an implementation for rb_tree_. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: assert_node_consistent(const node_pointer p_nd, const char* __file, int __line) const { if (p_nd == 0) return 1; const size_type l_height = assert_node_consistent(p_nd->m_p_left, __file, __line); const size_type r_height = assert_node_consistent(p_nd->m_p_right, __file, __line); if (p_nd->m_red) { PB_DS_DEBUG_VERIFY(is_effectively_black(p_nd->m_p_left)); PB_DS_DEBUG_VERIFY(is_effectively_black(p_nd->m_p_right)); } PB_DS_DEBUG_VERIFY(l_height == r_height); return (p_nd->m_red ? 0 : 1) + l_height; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { base_type::assert_valid(__file, __line); const node_pointer p_head = base_type::m_p_head; PB_DS_DEBUG_VERIFY(p_head->m_red); if (p_head->m_p_parent != 0) { PB_DS_DEBUG_VERIFY(!p_head->m_p_parent->m_red); assert_node_consistent(p_head->m_p_parent, __file, __line); } } #endif PK!M18/ext/pb_ds/detail/rb_tree_map_/erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rb_tree_map_/erase_fn_imps.hpp * Contains an implementation for rb_tree_. */ PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: erase(key_const_reference r_key) { point_iterator it = this->find(r_key); if (it == base_type::end()) return false; erase(it); return true; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: erase(iterator it) { PB_DS_ASSERT_VALID((*this)) if (it == base_type::end()) return it; iterator ret_it = it; ++ret_it; erase_node(it.m_p_nd); PB_DS_ASSERT_VALID((*this)) return ret_it; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::reverse_iterator PB_DS_CLASS_C_DEC:: erase(reverse_iterator it) { PB_DS_ASSERT_VALID((*this)) if (it.m_p_nd == base_type::m_p_head) return it; reverse_iterator ret_it = it; ++ret_it; erase_node(it.m_p_nd); PB_DS_ASSERT_VALID((*this)) return ret_it; } PB_DS_CLASS_T_DEC template inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: erase_if(Pred pred) { PB_DS_ASSERT_VALID((*this)) size_type num_ersd = 0; iterator it = base_type::begin(); while (it != base_type::end()) { if (pred(*it)) { ++num_ersd; it = erase(it); } else ++it; } PB_DS_ASSERT_VALID((*this)) return num_ersd; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: erase_node(node_pointer p_nd) { remove_node(p_nd); base_type::actual_erase_node(p_nd); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: remove_node(node_pointer p_z) { this->update_min_max_for_erased_node(p_z); node_pointer p_y = p_z; node_pointer p_x = 0; node_pointer p_new_x_parent = 0; if (p_y->m_p_left == 0) p_x = p_y->m_p_right; else if (p_y->m_p_right == 0) p_x = p_y->m_p_left; else { p_y = p_y->m_p_right; while (p_y->m_p_left != 0) p_y = p_y->m_p_left; p_x = p_y->m_p_right; } if (p_y == p_z) { p_new_x_parent = p_y->m_p_parent; if (p_x != 0) p_x->m_p_parent = p_y->m_p_parent; if (base_type::m_p_head->m_p_parent == p_z) base_type::m_p_head->m_p_parent = p_x; else if (p_z->m_p_parent->m_p_left == p_z) { p_y->m_p_left = p_z->m_p_parent; p_z->m_p_parent->m_p_left = p_x; } else { p_y->m_p_left = 0; p_z->m_p_parent->m_p_right = p_x; } } else { p_z->m_p_left->m_p_parent = p_y; p_y->m_p_left = p_z->m_p_left; if (p_y != p_z->m_p_right) { p_new_x_parent = p_y->m_p_parent; if (p_x != 0) p_x->m_p_parent = p_y->m_p_parent; p_y->m_p_parent->m_p_left = p_x; p_y->m_p_right = p_z->m_p_right; p_z->m_p_right->m_p_parent = p_y; } else p_new_x_parent = p_y; if (base_type::m_p_head->m_p_parent == p_z) base_type::m_p_head->m_p_parent = p_y; else if (p_z->m_p_parent->m_p_left == p_z) p_z->m_p_parent->m_p_left = p_y; else p_z->m_p_parent->m_p_right = p_y; p_y->m_p_parent = p_z->m_p_parent; std::swap(p_y->m_red, p_z->m_red); p_y = p_z; } this->update_to_top(p_new_x_parent, (node_update* )this); if (p_y->m_red) return; remove_fixup(p_x, p_new_x_parent); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: remove_fixup(node_pointer p_x, node_pointer p_new_x_parent) { _GLIBCXX_DEBUG_ASSERT(p_x == 0 || p_x->m_p_parent == p_new_x_parent); while (p_x != base_type::m_p_head->m_p_parent && is_effectively_black(p_x)) if (p_x == p_new_x_parent->m_p_left) { node_pointer p_w = p_new_x_parent->m_p_right; if (p_w->m_red) { p_w->m_red = false; p_new_x_parent->m_red = true; base_type::rotate_left(p_new_x_parent); p_w = p_new_x_parent->m_p_right; } if (is_effectively_black(p_w->m_p_left) && is_effectively_black(p_w->m_p_right)) { p_w->m_red = true; p_x = p_new_x_parent; p_new_x_parent = p_new_x_parent->m_p_parent; } else { if (is_effectively_black(p_w->m_p_right)) { if (p_w->m_p_left != 0) p_w->m_p_left->m_red = false; p_w->m_red = true; base_type::rotate_right(p_w); p_w = p_new_x_parent->m_p_right; } p_w->m_red = p_new_x_parent->m_red; p_new_x_parent->m_red = false; if (p_w->m_p_right != 0) p_w->m_p_right->m_red = false; base_type::rotate_left(p_new_x_parent); this->update_to_top(p_new_x_parent, (node_update* )this); break; } } else { node_pointer p_w = p_new_x_parent->m_p_left; if (p_w->m_red == true) { p_w->m_red = false; p_new_x_parent->m_red = true; base_type::rotate_right(p_new_x_parent); p_w = p_new_x_parent->m_p_left; } if (is_effectively_black(p_w->m_p_right) && is_effectively_black(p_w->m_p_left)) { p_w->m_red = true; p_x = p_new_x_parent; p_new_x_parent = p_new_x_parent->m_p_parent; } else { if (is_effectively_black(p_w->m_p_left)) { if (p_w->m_p_right != 0) p_w->m_p_right->m_red = false; p_w->m_red = true; base_type::rotate_left(p_w); p_w = p_new_x_parent->m_p_left; } p_w->m_red = p_new_x_parent->m_red; p_new_x_parent->m_red = false; if (p_w->m_p_left != 0) p_w->m_p_left->m_red = false; base_type::rotate_right(p_new_x_parent); this->update_to_top(p_new_x_parent, (node_update* )this); break; } } if (p_x != 0) p_x->m_red = false; } PK!ק08/ext/pb_ds/detail/rb_tree_map_/find_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rb_tree_map_/find_fn_imps.hpp * Contains an implementation for rb_tree_. */ PK!d1108/ext/pb_ds/detail/rb_tree_map_/info_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rb_tree_map_/info_fn_imps.hpp * Contains an implementation for rb_tree_. */ PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: is_effectively_black(const node_pointer p_nd) { return (p_nd == 0 || !p_nd->m_red); } PK!Y28/ext/pb_ds/detail/rb_tree_map_/insert_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rb_tree_map_/insert_fn_imps.hpp * Contains an implementation for rb_tree_. */ PB_DS_CLASS_T_DEC inline std::pair PB_DS_CLASS_C_DEC:: insert(const_reference r_value) { PB_DS_ASSERT_VALID((*this)) std::pair ins_pair = base_type::insert_leaf(r_value); if (ins_pair.second == true) { ins_pair.first.m_p_nd->m_red = true; PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) insert_fixup(ins_pair.first.m_p_nd); } PB_DS_ASSERT_VALID((*this)) return ins_pair; } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: insert_fixup(node_pointer p_nd) { _GLIBCXX_DEBUG_ASSERT(p_nd->m_red == true); while (p_nd != base_type::m_p_head->m_p_parent && p_nd->m_p_parent->m_red) { if (p_nd->m_p_parent == p_nd->m_p_parent->m_p_parent->m_p_left) { node_pointer p_y = p_nd->m_p_parent->m_p_parent->m_p_right; if (p_y != 0 && p_y->m_red) { p_nd->m_p_parent->m_red = false; p_y->m_red = false; p_nd->m_p_parent->m_p_parent->m_red = true; p_nd = p_nd->m_p_parent->m_p_parent; } else { if (p_nd == p_nd->m_p_parent->m_p_right) { p_nd = p_nd->m_p_parent; base_type::rotate_left(p_nd); } p_nd->m_p_parent->m_red = false; p_nd->m_p_parent->m_p_parent->m_red = true; base_type::rotate_right(p_nd->m_p_parent->m_p_parent); } } else { node_pointer p_y = p_nd->m_p_parent->m_p_parent->m_p_left; if (p_y != 0 && p_y->m_red) { p_nd->m_p_parent->m_red = false; p_y->m_red = false; p_nd->m_p_parent->m_p_parent->m_red = true; p_nd = p_nd->m_p_parent->m_p_parent; } else { if (p_nd == p_nd->m_p_parent->m_p_left) { p_nd = p_nd->m_p_parent; base_type::rotate_right(p_nd); } p_nd->m_p_parent->m_red = false; p_nd->m_p_parent->m_p_parent->m_red = true; base_type::rotate_left(p_nd->m_p_parent->m_p_parent); } } } base_type::update_to_top(p_nd, (node_update* )this); base_type::m_p_head->m_p_parent->m_red = false; } PK!h(8/ext/pb_ds/detail/rb_tree_map_/node.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rb_tree_map_/node.hpp * Contains an implementation for rb_tree_. */ #ifndef PB_DS_RB_TREE_NODE_HPP #define PB_DS_RB_TREE_NODE_HPP #include namespace __gnu_pbds { namespace detail { /// Node for Red-Black trees. template struct rb_tree_node_ { public: typedef Value_Type value_type; typedef Metadata metadata_type; typedef typename _Alloc::template rebind< rb_tree_node_< Value_Type, Metadata, _Alloc> >::other::pointer node_pointer; typedef typename _Alloc::template rebind< metadata_type>::other::reference metadata_reference; typedef typename _Alloc::template rebind< metadata_type>::other::const_reference metadata_const_reference; bool special() const { return m_red; } metadata_const_reference get_metadata() const { return m_metadata; } metadata_reference get_metadata() { return m_metadata; } #ifdef PB_DS_BIN_SEARCH_TREE_TRACE_ void trace() const { std::cout << PB_DS_V2F(m_value) <<(m_red? " " : " ") << "(" << m_metadata << ")"; } #endif node_pointer m_p_left; node_pointer m_p_right; node_pointer m_p_parent; value_type m_value; bool m_red; metadata_type m_metadata; }; template struct rb_tree_node_ { public: typedef Value_Type value_type; typedef null_type metadata_type; typedef typename _Alloc::template rebind< rb_tree_node_< Value_Type, null_type, _Alloc> >::other::pointer node_pointer; bool special() const { return m_red; } #ifdef PB_DS_BIN_SEARCH_TREE_TRACE_ void trace() const { std::cout << PB_DS_V2F(m_value) <<(m_red? " " : " "); } #endif node_pointer m_p_left; node_pointer m_p_right; node_pointer m_p_parent; value_type m_value; bool m_red; }; } // namespace detail } // namespace __gnu_pbds #endif PK!b,8/ext/pb_ds/detail/rb_tree_map_/rb_tree_.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rb_tree_map_/rb_tree_.hpp * Contains an implementation for Red Black trees. */ #include #include #include #include #include namespace __gnu_pbds { namespace detail { #define PB_DS_CLASS_T_DEC \ template #ifdef PB_DS_DATA_TRUE_INDICATOR # define PB_DS_RB_TREE_NAME rb_tree_map # define PB_DS_RB_TREE_BASE_NAME bin_search_tree_map #endif #ifdef PB_DS_DATA_FALSE_INDICATOR # define PB_DS_RB_TREE_NAME rb_tree_set # define PB_DS_RB_TREE_BASE_NAME bin_search_tree_set #endif #define PB_DS_CLASS_C_DEC \ PB_DS_RB_TREE_NAME #define PB_DS_RB_TREE_BASE \ PB_DS_RB_TREE_BASE_NAME /** * @brief Red-Black tree. * @ingroup branch-detail * * This implementation uses an idea from the SGI STL (using a * @a header node which is needed for efficient iteration). */ template class PB_DS_RB_TREE_NAME : public PB_DS_RB_TREE_BASE { private: typedef PB_DS_RB_TREE_BASE base_type; typedef typename base_type::node_pointer node_pointer; public: typedef rb_tree_tag container_category; typedef Cmp_Fn cmp_fn; typedef _Alloc allocator_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef typename base_type::key_type key_type; typedef typename base_type::key_pointer key_pointer; typedef typename base_type::key_const_pointer key_const_pointer; typedef typename base_type::key_reference key_reference; typedef typename base_type::key_const_reference key_const_reference; typedef typename base_type::mapped_type mapped_type; typedef typename base_type::mapped_pointer mapped_pointer; typedef typename base_type::mapped_const_pointer mapped_const_pointer; typedef typename base_type::mapped_reference mapped_reference; typedef typename base_type::mapped_const_reference mapped_const_reference; typedef typename base_type::value_type value_type; typedef typename base_type::pointer pointer; typedef typename base_type::const_pointer const_pointer; typedef typename base_type::reference reference; typedef typename base_type::const_reference const_reference; typedef typename base_type::point_iterator point_iterator; typedef typename base_type::const_iterator point_const_iterator; typedef typename base_type::iterator iterator; typedef typename base_type::const_iterator const_iterator; typedef typename base_type::reverse_iterator reverse_iterator; typedef typename base_type::const_reverse_iterator const_reverse_iterator; typedef typename base_type::node_update node_update; PB_DS_RB_TREE_NAME(); PB_DS_RB_TREE_NAME(const Cmp_Fn&); PB_DS_RB_TREE_NAME(const Cmp_Fn&, const node_update&); PB_DS_RB_TREE_NAME(const PB_DS_CLASS_C_DEC&); void swap(PB_DS_CLASS_C_DEC&); template void copy_from_range(It, It); inline std::pair insert(const_reference); inline mapped_reference operator[](key_const_reference r_key) { #ifdef PB_DS_DATA_TRUE_INDICATOR _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) std::pair ins_pair = base_type::insert_leaf(value_type(r_key, mapped_type())); if (ins_pair.second == true) { ins_pair.first.m_p_nd->m_red = true; _GLIBCXX_DEBUG_ONLY(this->structure_only_assert_valid(__FILE__, __LINE__);) insert_fixup(ins_pair.first.m_p_nd); } _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) return ins_pair.first.m_p_nd->m_value.second; #else insert(r_key); return base_type::s_null_type; #endif } inline bool erase(key_const_reference); inline iterator erase(iterator); inline reverse_iterator erase(reverse_iterator); template inline size_type erase_if(Pred); void join(PB_DS_CLASS_C_DEC&); void split(key_const_reference, PB_DS_CLASS_C_DEC&); private: #ifdef _GLIBCXX_DEBUG void assert_valid(const char*, int) const; size_type assert_node_consistent(const node_pointer, const char*, int) const; #endif inline static bool is_effectively_black(const node_pointer); void initialize(); void insert_fixup(node_pointer); void erase_node(node_pointer); void remove_node(node_pointer); void remove_fixup(node_pointer, node_pointer); void split_imp(node_pointer, PB_DS_CLASS_C_DEC&); inline node_pointer split_min(); std::pair split_min_imp(); void join_imp(node_pointer, node_pointer); std::pair find_join_pos_right(node_pointer, size_type, size_type); std::pair find_join_pos_left(node_pointer, size_type, size_type); inline size_type black_height(node_pointer); void split_at_node(node_pointer, PB_DS_CLASS_C_DEC&); }; #define PB_DS_STRUCT_ONLY_ASSERT_VALID(X) \ _GLIBCXX_DEBUG_ONLY(X.structure_only_assert_valid(__FILE__, __LINE__);) #include #include #include #include #include #include #undef PB_DS_STRUCT_ONLY_ASSERT_VALID #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #undef PB_DS_RB_TREE_NAME #undef PB_DS_RB_TREE_BASE_NAME #undef PB_DS_RB_TREE_BASE } // namespace detail } // namespace __gnu_pbds PK!Põ68/ext/pb_ds/detail/rb_tree_map_/split_join_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rb_tree_map_/split_join_fn_imps.hpp * Contains an implementation for rb_tree_. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: join(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) if (base_type::join_prep(other) == false) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return; } const node_pointer p_x = other.split_min(); join_imp(p_x, other.m_p_head->m_p_parent); base_type::join_finish(other); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: join_imp(node_pointer p_x, node_pointer p_r) { _GLIBCXX_DEBUG_ASSERT(p_x != 0); if (p_r != 0) p_r->m_red = false; const size_type h = black_height(base_type::m_p_head->m_p_parent); const size_type other_h = black_height(p_r); node_pointer p_x_l; node_pointer p_x_r; std::pair join_pos; const bool right_join = h >= other_h; if (right_join) { join_pos = find_join_pos_right(base_type::m_p_head->m_p_parent, h, other_h); p_x_l = join_pos.first; p_x_r = p_r; } else { p_x_l = base_type::m_p_head->m_p_parent; base_type::m_p_head->m_p_parent = p_r; if (p_r != 0) p_r->m_p_parent = base_type::m_p_head; join_pos = find_join_pos_left(base_type::m_p_head->m_p_parent, h, other_h); p_x_r = join_pos.first; } node_pointer p_parent = join_pos.second; if (p_parent == base_type::m_p_head) { base_type::m_p_head->m_p_parent = p_x; p_x->m_p_parent = base_type::m_p_head; } else { p_x->m_p_parent = p_parent; if (right_join) p_x->m_p_parent->m_p_right = p_x; else p_x->m_p_parent->m_p_left = p_x; } p_x->m_p_left = p_x_l; if (p_x_l != 0) p_x_l->m_p_parent = p_x; p_x->m_p_right = p_x_r; if (p_x_r != 0) p_x_r->m_p_parent = p_x; p_x->m_red = true; base_type::initialize_min_max(); PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) base_type::update_to_top(p_x, (node_update* )this); insert_fixup(p_x); PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: split_min() { node_pointer p_min = base_type::m_p_head->m_p_left; #ifdef _GLIBCXX_DEBUG const node_pointer p_head = base_type::m_p_head; _GLIBCXX_DEBUG_ASSERT(p_min != p_head); #endif remove_node(p_min); return p_min; } PB_DS_CLASS_T_DEC std::pair< typename PB_DS_CLASS_C_DEC::node_pointer, typename PB_DS_CLASS_C_DEC::node_pointer> PB_DS_CLASS_C_DEC:: find_join_pos_right(node_pointer p_l, size_type h_l, size_type h_r) { _GLIBCXX_DEBUG_ASSERT(h_l >= h_r); if (base_type::m_p_head->m_p_parent == 0) return (std::make_pair((node_pointer)0, base_type::m_p_head)); node_pointer p_l_parent = base_type::m_p_head; while (h_l > h_r) { if (p_l->m_red == false) { _GLIBCXX_DEBUG_ASSERT(h_l > 0); --h_l; } p_l_parent = p_l; p_l = p_l->m_p_right; } if (!is_effectively_black(p_l)) { p_l_parent = p_l; p_l = p_l->m_p_right; } _GLIBCXX_DEBUG_ASSERT(is_effectively_black(p_l)); _GLIBCXX_DEBUG_ASSERT(black_height(p_l) == h_r); _GLIBCXX_DEBUG_ASSERT(p_l == 0 || p_l->m_p_parent == p_l_parent); return std::make_pair(p_l, p_l_parent); } PB_DS_CLASS_T_DEC std::pair< typename PB_DS_CLASS_C_DEC::node_pointer, typename PB_DS_CLASS_C_DEC::node_pointer> PB_DS_CLASS_C_DEC:: find_join_pos_left(node_pointer p_r, size_type h_l, size_type h_r) { _GLIBCXX_DEBUG_ASSERT(h_r > h_l); if (base_type::m_p_head->m_p_parent == 0) return (std::make_pair((node_pointer)0, base_type::m_p_head)); node_pointer p_r_parent = base_type::m_p_head; while (h_r > h_l) { if (p_r->m_red == false) { _GLIBCXX_DEBUG_ASSERT(h_r > 0); --h_r; } p_r_parent = p_r; p_r = p_r->m_p_left; } if (!is_effectively_black(p_r)) { p_r_parent = p_r; p_r = p_r->m_p_left; } _GLIBCXX_DEBUG_ASSERT(is_effectively_black(p_r)); _GLIBCXX_DEBUG_ASSERT(black_height(p_r) == h_l); _GLIBCXX_DEBUG_ASSERT(p_r == 0 || p_r->m_p_parent == p_r_parent); return std::make_pair(p_r, p_r_parent); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: black_height(node_pointer p_nd) { size_type h = 1; while (p_nd != 0) { if (p_nd->m_red == false) ++h; p_nd = p_nd->m_p_left; } return h; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: split(key_const_reference r_key, PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) if (base_type::split_prep(r_key, other) == false) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return; } PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) PB_DS_STRUCT_ONLY_ASSERT_VALID(other) node_pointer p_nd = this->upper_bound(r_key).m_p_nd; do { node_pointer p_next_nd = p_nd->m_p_parent; if (Cmp_Fn::operator()(r_key, PB_DS_V2F(p_nd->m_value))) split_at_node(p_nd, other); PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) PB_DS_STRUCT_ONLY_ASSERT_VALID(other) p_nd = p_next_nd; } while (p_nd != base_type::m_p_head); base_type::split_finish(other); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: split_at_node(node_pointer p_nd, PB_DS_CLASS_C_DEC& other) { _GLIBCXX_DEBUG_ASSERT(p_nd != 0); node_pointer p_l = p_nd->m_p_left; node_pointer p_r = p_nd->m_p_right; node_pointer p_parent = p_nd->m_p_parent; if (p_parent == base_type::m_p_head) { base_type::m_p_head->m_p_parent = p_l; if (p_l != 0) { p_l->m_p_parent = base_type::m_p_head; p_l->m_red = false; } } else { if (p_parent->m_p_left == p_nd) p_parent->m_p_left = p_l; else p_parent->m_p_right = p_l; if (p_l != 0) p_l->m_p_parent = p_parent; this->update_to_top(p_parent, (node_update* )this); if (!p_nd->m_red) remove_fixup(p_l, p_parent); } base_type::initialize_min_max(); other.join_imp(p_nd, p_r); PB_DS_STRUCT_ONLY_ASSERT_VALID((*this)) PB_DS_STRUCT_ONLY_ASSERT_VALID(other) } PK!;# *8/ext/pb_ds/detail/rb_tree_map_/traits.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rb_tree_map_/traits.hpp * Contains an implementation for rb_tree_. */ #ifndef PB_DS_RB_TREE_NODE_AND_IT_TRAITS_HPP #define PB_DS_RB_TREE_NODE_AND_IT_TRAITS_HPP #include namespace __gnu_pbds { namespace detail { /// Specialization. /// @ingroup traits template class Node_Update, typename _Alloc> struct tree_traits : public bin_search_tree_traits< Key, Mapped, Cmp_Fn, Node_Update, rb_tree_node_< typename types_traits::value_type, typename tree_node_metadata_dispatch::type, _Alloc>, _Alloc> { }; /// Specialization. /// @ingroup traits template class Node_Update, typename _Alloc> struct tree_traits : public bin_search_tree_traits< Key, null_type, Cmp_Fn, Node_Update, rb_tree_node_< typename types_traits::value_type, typename tree_node_metadata_dispatch::type, _Alloc>, _Alloc> { }; } // namespace detail } // namespace __gnu_pbds #endif PK!e H8/ext/pb_ds/detail/rc_binomial_heap_/constructors_destructor_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rc_binomial_heap_/constructors_destructor_fn_imps.hpp * Contains an implementation for rc_binomial_heap_. */ PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: rc_binomial_heap() { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: rc_binomial_heap(const Cmp_Fn& r_cmp_fn) : base_type(r_cmp_fn) { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: rc_binomial_heap(const PB_DS_CLASS_C_DEC& other) : base_type(other) { make_binomial_heap(); base_type::find_max(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~rc_binomial_heap() { } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) base_type::swap(other); m_rc.swap(other.m_rc); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PK! 68/ext/pb_ds/detail/rc_binomial_heap_/debug_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rc_binomial_heap_/debug_fn_imps.hpp * Contains an implementation for rc_binomial_heap_. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { base_type::assert_valid(false, __file, __line); if (!base_type::empty()) { PB_DS_DEBUG_VERIFY(base_type::m_p_max != 0); base_type::assert_max(__file, __line); } m_rc.assert_valid(__file, __line); if (m_rc.empty()) { base_type::assert_valid(true, __file, __line); PB_DS_DEBUG_VERIFY(next_2_pointer(base_type::m_p_root) == 0); return; } node_const_pointer p_nd = next_2_pointer(base_type::m_p_root); typename rc_t::const_iterator it = m_rc.end(); --it; while (p_nd != 0) { PB_DS_DEBUG_VERIFY(*it == p_nd); node_const_pointer p_next = p_nd->m_p_next_sibling; PB_DS_DEBUG_VERIFY(p_next != 0); PB_DS_DEBUG_VERIFY(p_nd->m_metadata == p_next->m_metadata); PB_DS_DEBUG_VERIFY(p_next->m_p_next_sibling == 0 || p_next->m_metadata < p_next->m_p_next_sibling->m_metadata); --it; p_nd = next_2_pointer(next_after_0_pointer(p_nd)); } PB_DS_DEBUG_VERIFY(it + 1 == m_rc.begin()); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_const_pointer PB_DS_CLASS_C_DEC:: next_2_pointer(node_const_pointer p_nd) { if (p_nd == 0) return 0; node_pointer p_next = p_nd->m_p_next_sibling; if (p_next == 0) return 0; if (p_nd->m_metadata == p_next->m_metadata) return p_nd; return next_2_pointer(p_next); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_const_pointer PB_DS_CLASS_C_DEC:: next_after_0_pointer(node_const_pointer p_nd) { if (p_nd == 0) return 0; node_pointer p_next = p_nd->m_p_next_sibling; if (p_next == 0) return 0; if (p_nd->m_metadata < p_next->m_metadata) return p_next; return next_after_0_pointer(p_next); } #endif PK!OqI I 68/ext/pb_ds/detail/rc_binomial_heap_/erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rc_binomial_heap_/erase_fn_imps.hpp * Contains an implementation for rc_binomial_heap_. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: pop() { make_binomial_heap(); _GLIBCXX_DEBUG_ASSERT(!base_type::empty()); base_type::pop(); base_type::find_max(); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear() { base_type::clear(); m_rc.clear(); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: make_binomial_heap() { node_pointer p_nd = base_type::m_p_root; while (p_nd != 0) { node_pointer p_next = p_nd->m_p_next_sibling; if (p_next == 0) p_nd = p_next; else if (p_nd->m_metadata == p_next->m_metadata) p_nd = link_with_next_sibling(p_nd); else if (p_nd->m_metadata < p_next->m_metadata) p_nd = p_next; #ifdef _GLIBCXX_DEBUG else _GLIBCXX_DEBUG_ASSERT(0); #endif } m_rc.clear(); } PB_DS_CLASS_T_DEC template typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: erase_if(Pred pred) { make_binomial_heap(); const size_type ersd = base_type::erase_if(pred); base_type::find_max(); PB_DS_ASSERT_VALID((*this)) return ersd; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: erase(point_iterator it) { make_binomial_heap(); base_type::erase(it); base_type::find_max(); } PK!Ep78/ext/pb_ds/detail/rc_binomial_heap_/insert_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rc_binomial_heap_/insert_fn_imps.hpp * Contains an implementation for rc_binomial_heap_. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: push(const_reference r_val) { PB_DS_ASSERT_VALID((*this)) make_0_exposed(); PB_DS_ASSERT_VALID((*this)) node_pointer p_nd = base_type::get_new_node_for_insert(r_val); p_nd->m_p_l_child = p_nd->m_p_prev_or_parent = 0; p_nd->m_metadata = 0; if (base_type::m_p_max == 0 || Cmp_Fn::operator()(base_type::m_p_max->m_value, r_val)) base_type::m_p_max = p_nd; p_nd->m_p_next_sibling = base_type::m_p_root; if (base_type::m_p_root != 0) base_type::m_p_root->m_p_prev_or_parent = p_nd; base_type::m_p_root = p_nd; if (p_nd->m_p_next_sibling != 0&& p_nd->m_p_next_sibling->m_metadata == 0) m_rc.push(p_nd); PB_DS_ASSERT_VALID((*this)) return point_iterator(p_nd); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: modify(point_iterator it, const_reference r_new_val) { PB_DS_ASSERT_VALID((*this)) make_binomial_heap(); base_type::modify(it, r_new_val); base_type::find_max(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: link_with_next_sibling(node_pointer p_nd) { node_pointer p_next = p_nd->m_p_next_sibling; _GLIBCXX_DEBUG_ASSERT(p_next != 0); _GLIBCXX_DEBUG_ASSERT(p_next->m_p_prev_or_parent == p_nd); if (Cmp_Fn::operator()(p_nd->m_value, p_next->m_value)) { p_next->m_p_prev_or_parent = p_nd->m_p_prev_or_parent; if (p_next->m_p_prev_or_parent == 0) base_type::m_p_root = p_next; else p_next->m_p_prev_or_parent->m_p_next_sibling = p_next; if (base_type::m_p_max == p_nd) base_type::m_p_max = p_next; base_type::make_child_of(p_nd, p_next); ++p_next->m_metadata; return p_next; } p_nd->m_p_next_sibling = p_next->m_p_next_sibling; if (p_nd->m_p_next_sibling != 0) p_nd->m_p_next_sibling->m_p_prev_or_parent = p_nd; if (base_type::m_p_max == p_next) base_type::m_p_max = p_nd; base_type::make_child_of(p_next, p_nd); ++p_nd->m_metadata; return p_nd; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: make_0_exposed() { if (m_rc.empty()) return; node_pointer p_nd = m_rc.top(); m_rc.pop(); _GLIBCXX_DEBUG_ASSERT(p_nd->m_p_next_sibling != 0); _GLIBCXX_DEBUG_ASSERT(p_nd->m_metadata == p_nd->m_p_next_sibling->m_metadata); node_pointer p_res = link_with_next_sibling(p_nd); if (p_res->m_p_next_sibling != 0&& p_res->m_metadata == p_res->m_p_next_sibling->m_metadata) m_rc.push(p_res); } PK!갓yy+8/ext/pb_ds/detail/rc_binomial_heap_/rc.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rc_binomial_heap_/rc.hpp * Contains a redundant (binary counter). */ #ifndef PB_DS_RC_HPP #define PB_DS_RC_HPP namespace __gnu_pbds { namespace detail { /// Redundant binary counter. template class rc { private: typedef _Alloc allocator_type; typedef typename allocator_type::size_type size_type; typedef _Node node; typedef typename _Alloc::template rebind __rebind_n; typedef typename __rebind_n::other::pointer node_pointer; typedef typename _Alloc::template rebind __rebind_np; typedef typename __rebind_np::other::pointer entry_pointer; typedef typename __rebind_np::other::const_pointer entry_const_pointer; enum { max_entries = sizeof(size_type) << 3 }; public: typedef node_pointer entry; typedef entry_const_pointer const_iterator; rc(); rc(const rc&); inline void swap(rc&); inline void push(entry); inline node_pointer top() const; inline void pop(); inline bool empty() const; inline size_type size() const; void clear(); const const_iterator begin() const; const const_iterator end() const; #ifdef _GLIBCXX_DEBUG void assert_valid(const char*, int) const; #endif #ifdef PB_DS_RC_BINOMIAL_HEAP_TRACE_ void trace() const; #endif private: node_pointer m_a_entries[max_entries]; size_type m_over_top; }; template rc<_Node, _Alloc>:: rc() : m_over_top(0) { PB_DS_ASSERT_VALID((*this)) } template rc<_Node, _Alloc>:: rc(const rc<_Node, _Alloc>& other) : m_over_top(0) { PB_DS_ASSERT_VALID((*this)) } template inline void rc<_Node, _Alloc>:: swap(rc<_Node, _Alloc>& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) const size_type over_top = std::max(m_over_top, other.m_over_top); for (size_type i = 0; i < over_top; ++i) std::swap(m_a_entries[i], other.m_a_entries[i]); std::swap(m_over_top, other.m_over_top); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } template inline void rc<_Node, _Alloc>:: push(entry p_nd) { PB_DS_ASSERT_VALID((*this)) _GLIBCXX_DEBUG_ASSERT(m_over_top < max_entries); m_a_entries[m_over_top++] = p_nd; PB_DS_ASSERT_VALID((*this)) } template inline void rc<_Node, _Alloc>:: pop() { PB_DS_ASSERT_VALID((*this)) _GLIBCXX_DEBUG_ASSERT(!empty()); --m_over_top; PB_DS_ASSERT_VALID((*this)) } template inline typename rc<_Node, _Alloc>::node_pointer rc<_Node, _Alloc>:: top() const { PB_DS_ASSERT_VALID((*this)) _GLIBCXX_DEBUG_ASSERT(!empty()); return *(m_a_entries + m_over_top - 1); } template inline bool rc<_Node, _Alloc>:: empty() const { PB_DS_ASSERT_VALID((*this)) return m_over_top == 0; } template inline typename rc<_Node, _Alloc>::size_type rc<_Node, _Alloc>:: size() const { return m_over_top; } template void rc<_Node, _Alloc>:: clear() { PB_DS_ASSERT_VALID((*this)) m_over_top = 0; PB_DS_ASSERT_VALID((*this)) } template const typename rc<_Node, _Alloc>::const_iterator rc<_Node, _Alloc>:: begin() const { return& m_a_entries[0]; } template const typename rc<_Node, _Alloc>::const_iterator rc<_Node, _Alloc>:: end() const { return& m_a_entries[m_over_top]; } #ifdef _GLIBCXX_DEBUG template void rc<_Node, _Alloc>:: assert_valid(const char* __file, int __line) const { PB_DS_DEBUG_VERIFY(m_over_top < max_entries); } #endif #ifdef PB_DS_RC_BINOMIAL_HEAP_TRACE_ template void rc<_Node, _Alloc>:: trace() const { std::cout << "rc" << std::endl; for (size_type i = 0; i < m_over_top; ++i) std::cerr << m_a_entries[i] << std::endl; std::cout << std::endl; } #endif } // namespace detail } // namespace __gnu_pbds #endif PK!eO~:8/ext/pb_ds/detail/rc_binomial_heap_/rc_binomial_heap_.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rc_binomial_heap_/rc_binomial_heap_.hpp * Contains an implementation for redundant-counter binomial heap. */ #include #include #include #include #include namespace __gnu_pbds { namespace detail { #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ rc_binomial_heap #define PB_DS_RC_C_DEC \ rc::node, _Alloc> /** * Redundant-counter binomial heap. * * @ingroup heap-detail */ template class rc_binomial_heap : public binomial_heap_base { private: typedef binomial_heap_base base_type; typedef typename base_type::node_pointer node_pointer; typedef typename base_type::node_const_pointer node_const_pointer; typedef PB_DS_RC_C_DEC rc_t; public: typedef Value_Type value_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef typename base_type::pointer pointer; typedef typename base_type::const_pointer const_pointer; typedef typename base_type::reference reference; typedef typename base_type::const_reference const_reference; typedef typename base_type::point_const_iterator point_const_iterator; typedef typename base_type::point_iterator point_iterator; typedef typename base_type::const_iterator const_iterator; typedef typename base_type::iterator iterator; typedef typename base_type::cmp_fn cmp_fn; typedef typename base_type::allocator_type allocator_type; rc_binomial_heap(); rc_binomial_heap(const Cmp_Fn&); rc_binomial_heap(const PB_DS_CLASS_C_DEC&); ~rc_binomial_heap(); void swap(PB_DS_CLASS_C_DEC&); inline point_iterator push(const_reference); void modify(point_iterator, const_reference); inline void pop(); void erase(point_iterator); inline void clear(); template size_type erase_if(Pred); template void split(Pred, PB_DS_CLASS_C_DEC&); void join(PB_DS_CLASS_C_DEC&); #ifdef _GLIBCXX_DEBUG void assert_valid(const char*, int) const; #endif #ifdef PB_DS_RC_BINOMIAL_HEAP_TRACE_ void trace() const; #endif private: inline node_pointer link_with_next_sibling(node_pointer); void make_0_exposed(); void make_binomial_heap(); #ifdef _GLIBCXX_DEBUG static node_const_pointer next_2_pointer(node_const_pointer); static node_const_pointer next_after_0_pointer(node_const_pointer); #endif rc_t m_rc; }; #include #include #include #include #include #include #undef PB_DS_CLASS_C_DEC #undef PB_DS_CLASS_T_DEC #undef PB_DS_RC_C_DEC } // namespace detail } // namespace __gnu_pbds PK!>r r ;8/ext/pb_ds/detail/rc_binomial_heap_/split_join_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rc_binomial_heap_/split_join_fn_imps.hpp * Contains an implementation for rc_binomial_heap_. */ PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: split(Pred pred, PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) make_binomial_heap(); other.make_binomial_heap(); base_type::split(pred, other); base_type::find_max(); other.find_max(); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: join(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) make_binomial_heap(); other.make_binomial_heap(); base_type::join(other); base_type::find_max(); other.find_max(); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PK!eTpp68/ext/pb_ds/detail/rc_binomial_heap_/trace_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rc_binomial_heap_/trace_fn_imps.hpp * Contains an implementation for rc_binomial_heap_. */ #ifdef PB_DS_RC_BINOMIAL_HEAP_TRACE_ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace() const { base_type::trace(); m_rc.trace(); } #endif // #ifdef PB_DS_RC_BINOMIAL_HEAP_TRACE_ PK!g3##S8/ext/pb_ds/detail/resize_policy/cc_hash_max_collision_check_resize_trigger_imp.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file cc_hash_max_collision_check_resize_trigger_imp.hpp * Contains a resize trigger implementation. */ PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: cc_hash_max_collision_check_resize_trigger(float load) : m_load(load), m_size(0), m_num_col(0), m_max_col(0), m_resize_needed(false) { } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_find_search_start() { } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_find_search_collision() { } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_find_search_end() { } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_insert_search_start() { m_num_col = 0; } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_insert_search_collision() { ++m_num_col; } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_insert_search_end() { calc_resize_needed(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erase_search_start() { } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erase_search_collision() { } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erase_search_end() { } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_inserted(size_type) { } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erased(size_type) { m_resize_needed = true; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_cleared() { m_resize_needed = false; } PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: is_resize_needed() const { return m_resize_needed; } PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: is_grow_needed(size_type /*size*/, size_type /*num_used_e*/) const { return m_num_col >= m_max_col; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_resized(size_type new_size) { m_size = new_size; #ifdef PB_DS_HT_MAP_RESIZE_TRACE_ std::cerr << "chmccrt::notify_resized " << static_cast(new_size) << std::endl; #endif calc_max_num_coll(); calc_resize_needed(); m_num_col = 0; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: calc_max_num_coll() { // max_col <-- \sqrt{2 load \ln( 2 m \ln( m ) ) } const double ln_arg = 2 * m_size * std::log(double(m_size)); m_max_col = size_type(std::ceil(std::sqrt(2 * m_load * std::log(ln_arg)))); #ifdef PB_DS_HT_MAP_RESIZE_TRACE_ std::cerr << "chmccrt::calc_max_num_coll " << static_cast(m_size) << " " << static_cast(m_max_col) << std::endl; #endif } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_externally_resized(size_type new_size) { notify_resized(new_size); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { std::swap(m_load, other.m_load); std::swap(m_size, other.m_size); std::swap(m_num_col, other.m_num_col); std::swap(m_max_col, other.m_max_col); std::swap(m_resize_needed, other.m_resize_needed); } PB_DS_CLASS_T_DEC inline float PB_DS_CLASS_C_DEC:: get_load() const { PB_DS_STATIC_ASSERT(access, external_load_access); return m_load; } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: calc_resize_needed() { m_resize_needed = m_resize_needed || m_num_col >= m_max_col; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: set_load(float load) { PB_DS_STATIC_ASSERT(access, external_load_access); m_load = load; calc_max_num_coll(); calc_resize_needed(); } PK!у E8/ext/pb_ds/detail/resize_policy/hash_exponential_size_policy_imp.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file hash_exponential_size_policy_imp.hpp * Contains a resize size policy implementation. */ PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: hash_exponential_size_policy(size_type start_size, size_type grow_factor) : m_start_size(start_size), m_grow_factor(grow_factor) { } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { std::swap(m_start_size, other.m_start_size); std::swap(m_grow_factor, other.m_grow_factor); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: get_nearest_larger_size(size_type size) const { size_type ret = m_start_size; while (ret <= size) { const size_type next_ret = ret* m_grow_factor; if (next_ret < ret) __throw_insert_error(); ret = next_ret; } return ret; } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: get_nearest_smaller_size(size_type size) const { size_type ret = m_start_size; while (true) { const size_type next_ret = ret* m_grow_factor; if (next_ret < ret) __throw_resize_error(); if (next_ret >= size) return (ret); ret = next_ret; } return ret; } PK!4 HHG8/ext/pb_ds/detail/resize_policy/hash_load_check_resize_trigger_imp.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file hash_load_check_resize_trigger_imp.hpp * Contains a resize trigger implementation. */ #define PB_DS_ASSERT_VALID(X) \ _GLIBCXX_DEBUG_ONLY(X.assert_valid(__FILE__, __LINE__);) PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: hash_load_check_resize_trigger(float load_min, float load_max) : m_load_min(load_min), m_load_max(load_max), m_next_shrink_size(0), m_next_grow_size(0), m_resize_needed(false) { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_find_search_start() { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_find_search_collision() { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_find_search_end() { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_insert_search_start() { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_insert_search_collision() { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_insert_search_end() { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erase_search_start() { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erase_search_collision() { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erase_search_end() { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_inserted(size_type num_entries) { m_resize_needed = (num_entries >= m_next_grow_size); size_base::set_size(num_entries); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erased(size_type num_entries) { size_base::set_size(num_entries); m_resize_needed = num_entries <= m_next_shrink_size; PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: is_resize_needed() const { PB_DS_ASSERT_VALID((*this)) return m_resize_needed; } PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: is_grow_needed(size_type /*size*/, size_type num_entries) const { _GLIBCXX_DEBUG_ASSERT(m_resize_needed); return num_entries >= m_next_grow_size; } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~hash_load_check_resize_trigger() { } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_resized(size_type new_size) { m_resize_needed = false; m_next_grow_size = size_type(m_load_max * new_size - 1); m_next_shrink_size = size_type(m_load_min * new_size); #ifdef PB_DS_HT_MAP_RESIZE_TRACE_ std::cerr << "hlcrt::notify_resized " << std::endl << "1 " << new_size << std::endl << "2 " << m_load_min << std::endl << "3 " << m_load_max << std::endl << "4 " << m_next_shrink_size << std::endl << "5 " << m_next_grow_size << std::endl; #endif PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_externally_resized(size_type new_size) { m_resize_needed = false; size_type new_grow_size = size_type(m_load_max * new_size - 1); size_type new_shrink_size = size_type(m_load_min * new_size); #ifdef PB_DS_HT_MAP_RESIZE_TRACE_ std::cerr << "hlcrt::notify_externally_resized " << std::endl << "1 " << new_size << std::endl << "2 " << m_load_min << std::endl << "3 " << m_load_max << std::endl << "4 " << m_next_shrink_size << std::endl << "5 " << m_next_grow_size << std::endl << "6 " << new_shrink_size << std::endl << "7 " << new_grow_size << std::endl; #endif if (new_grow_size >= m_next_grow_size) { _GLIBCXX_DEBUG_ASSERT(new_shrink_size >= m_next_shrink_size); m_next_grow_size = new_grow_size; } else { _GLIBCXX_DEBUG_ASSERT(new_shrink_size <= m_next_shrink_size); m_next_shrink_size = new_shrink_size; } PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_cleared() { PB_DS_ASSERT_VALID((*this)) size_base::set_size(0); m_resize_needed = (0 < m_next_shrink_size); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) size_base::swap(other); std::swap(m_load_min, other.m_load_min); std::swap(m_load_max, other.m_load_max); std::swap(m_resize_needed, other.m_resize_needed); std::swap(m_next_grow_size, other.m_next_grow_size); std::swap(m_next_shrink_size, other.m_next_shrink_size); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC inline std::pair PB_DS_CLASS_C_DEC:: get_loads() const { PB_DS_STATIC_ASSERT(access, external_load_access); return std::make_pair(m_load_min, m_load_max); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: set_loads(std::pair load_pair) { PB_DS_STATIC_ASSERT(access, external_load_access); const float old_load_min = m_load_min; const float old_load_max = m_load_max; const size_type old_next_shrink_size = m_next_shrink_size; const size_type old_next_grow_size = m_next_grow_size; const bool old_resize_needed = m_resize_needed; __try { m_load_min = load_pair.first; m_load_max = load_pair.second; do_resize(static_cast(size_base::get_size() / ((m_load_min + m_load_max) / 2))); } __catch(...) { m_load_min = old_load_min; m_load_max = old_load_max; m_next_shrink_size = old_next_shrink_size; m_next_grow_size = old_next_grow_size; m_resize_needed = old_resize_needed; __throw_exception_again; } } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: do_resize(size_type) { std::abort(); } #ifdef _GLIBCXX_DEBUG # define PB_DS_DEBUG_VERIFY(_Cond) \ _GLIBCXX_DEBUG_VERIFY_AT(_Cond, \ _M_message(#_Cond" assertion from %1;:%2;") \ ._M_string(__FILE__)._M_integer(__LINE__) \ ,__file,__line) PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { PB_DS_DEBUG_VERIFY(m_load_max > m_load_min); PB_DS_DEBUG_VERIFY(m_next_grow_size >= m_next_shrink_size); } # undef PB_DS_DEBUG_VERIFY #endif #undef PB_DS_ASSERT_VALID PK!)O M8/ext/pb_ds/detail/resize_policy/hash_load_check_resize_trigger_size_base.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file hash_load_check_resize_trigger_size_base.hpp * Contains an base holding size for some resize policies. */ #ifndef PB_DS_HASH_LOAD_CHECK_RESIZE_TRIGGER_SIZE_BASE_HPP #define PB_DS_HASH_LOAD_CHECK_RESIZE_TRIGGER_SIZE_BASE_HPP namespace __gnu_pbds { namespace detail { /// Primary template. template class hash_load_check_resize_trigger_size_base; /// Specializations. template class hash_load_check_resize_trigger_size_base { protected: typedef Size_Type size_type; hash_load_check_resize_trigger_size_base(): m_size(0) { } inline void swap(hash_load_check_resize_trigger_size_base& other) { std::swap(m_size, other.m_size); } inline void set_size(size_type size) { m_size = size; } inline size_type get_size() const { return m_size; } private: size_type m_size; }; template class hash_load_check_resize_trigger_size_base { protected: typedef Size_Type size_type; protected: inline void swap(hash_load_check_resize_trigger_size_base& other) { } inline void set_size(size_type size) { } }; } // namespace detail } // namespace __gnu_pbds #endif PK!cy?8/ext/pb_ds/detail/resize_policy/hash_prime_size_policy_imp.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file hash_prime_size_policy_imp.hpp * Contains a resize size policy implementation. */ #pragma GCC system_header namespace detail { enum { num_distinct_sizes_32_bit = 30, num_distinct_sizes_64_bit = 62, num_distinct_sizes = sizeof(std::size_t) != 8 ? num_distinct_sizes_32_bit : num_distinct_sizes_64_bit, }; // Originally taken from the SGI implementation; acknowledged in the docs. // Further modified (for 64 bits) from tr1's hashtable. static const std::size_t g_a_sizes[num_distinct_sizes_64_bit] = { /* 0 */ 5ul, /* 1 */ 11ul, /* 2 */ 23ul, /* 3 */ 47ul, /* 4 */ 97ul, /* 5 */ 199ul, /* 6 */ 409ul, /* 7 */ 823ul, /* 8 */ 1741ul, /* 9 */ 3469ul, /* 10 */ 6949ul, /* 11 */ 14033ul, /* 12 */ 28411ul, /* 13 */ 57557ul, /* 14 */ 116731ul, /* 15 */ 236897ul, /* 16 */ 480881ul, /* 17 */ 976369ul, /* 18 */ 1982627ul, /* 19 */ 4026031ul, /* 20 */ 8175383ul, /* 21 */ 16601593ul, /* 22 */ 33712729ul, /* 23 */ 68460391ul, /* 24 */ 139022417ul, /* 25 */ 282312799ul, /* 26 */ 573292817ul, /* 27 */ 1164186217ul, /* 28 */ 2364114217ul, /* 29 */ 4294967291ul, /* 30 */ (std::size_t)8589934583ull, /* 31 */ (std::size_t)17179869143ull, /* 32 */ (std::size_t)34359738337ull, /* 33 */ (std::size_t)68719476731ull, /* 34 */ (std::size_t)137438953447ull, /* 35 */ (std::size_t)274877906899ull, /* 36 */ (std::size_t)549755813881ull, /* 37 */ (std::size_t)1099511627689ull, /* 38 */ (std::size_t)2199023255531ull, /* 39 */ (std::size_t)4398046511093ull, /* 40 */ (std::size_t)8796093022151ull, /* 41 */ (std::size_t)17592186044399ull, /* 42 */ (std::size_t)35184372088777ull, /* 43 */ (std::size_t)70368744177643ull, /* 44 */ (std::size_t)140737488355213ull, /* 45 */ (std::size_t)281474976710597ull, /* 46 */ (std::size_t)562949953421231ull, /* 47 */ (std::size_t)1125899906842597ull, /* 48 */ (std::size_t)2251799813685119ull, /* 49 */ (std::size_t)4503599627370449ull, /* 50 */ (std::size_t)9007199254740881ull, /* 51 */ (std::size_t)18014398509481951ull, /* 52 */ (std::size_t)36028797018963913ull, /* 53 */ (std::size_t)72057594037927931ull, /* 54 */ (std::size_t)144115188075855859ull, /* 55 */ (std::size_t)288230376151711717ull, /* 56 */ (std::size_t)576460752303423433ull, /* 57 */ (std::size_t)1152921504606846883ull, /* 58 */ (std::size_t)2305843009213693951ull, /* 59 */ (std::size_t)4611686018427387847ull, /* 60 */ (std::size_t)9223372036854775783ull, /* 61 */ (std::size_t)18446744073709551557ull, }; } // namespace detail PB_DS_CLASS_T_DEC inline PB_DS_CLASS_C_DEC:: hash_prime_size_policy(size_type n) : m_start_size(n) { m_start_size = get_nearest_larger_size(n); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { std::swap(m_start_size, other.m_start_size); } PB_DS_CLASS_T_DEC inline PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: get_nearest_larger_size(size_type n) const { const std::size_t* const p_upper = std::upper_bound(detail::g_a_sizes, detail::g_a_sizes + detail::num_distinct_sizes, n); if (p_upper == detail::g_a_sizes + detail::num_distinct_sizes) __throw_resize_error(); return *p_upper; } PB_DS_CLASS_T_DEC inline PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: get_nearest_smaller_size(size_type n) const { const std::size_t* p_lower = std::lower_bound(detail::g_a_sizes, detail::g_a_sizes + detail::num_distinct_sizes, n); if (*p_lower >= n && p_lower != detail::g_a_sizes) --p_lower; if (*p_lower < m_start_size) return m_start_size; return *p_lower; } PK!18D8/ext/pb_ds/detail/resize_policy/hash_standard_resize_policy_imp.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file hash_standard_resize_policy_imp.hpp * Contains a resize policy implementation. */ PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: hash_standard_resize_policy() : m_size(Size_Policy::get_nearest_larger_size(1)) { trigger_policy_base::notify_externally_resized(m_size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: hash_standard_resize_policy(const Size_Policy& r_size_policy) : Size_Policy(r_size_policy), m_size(Size_Policy::get_nearest_larger_size(1)) { trigger_policy_base::notify_externally_resized(m_size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: hash_standard_resize_policy(const Size_Policy& r_size_policy, const Trigger_Policy& r_trigger_policy) : Size_Policy(r_size_policy), Trigger_Policy(r_trigger_policy), m_size(Size_Policy::get_nearest_larger_size(1)) { trigger_policy_base::notify_externally_resized(m_size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~hash_standard_resize_policy() { } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { trigger_policy_base::swap(other); size_policy_base::swap(other); std::swap(m_size, other.m_size); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_find_search_start() { trigger_policy_base::notify_find_search_start(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_find_search_collision() { trigger_policy_base::notify_find_search_collision(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_find_search_end() { trigger_policy_base::notify_find_search_end(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_insert_search_start() { trigger_policy_base::notify_insert_search_start(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_insert_search_collision() { trigger_policy_base::notify_insert_search_collision(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_insert_search_end() { trigger_policy_base::notify_insert_search_end(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erase_search_start() { trigger_policy_base::notify_erase_search_start(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erase_search_collision() { trigger_policy_base::notify_erase_search_collision(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erase_search_end() { trigger_policy_base::notify_erase_search_end(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_inserted(size_type num_e) { trigger_policy_base::notify_inserted(num_e); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erased(size_type num_e) { trigger_policy_base::notify_erased(num_e); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_cleared() { trigger_policy_base::notify_cleared(); } PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: is_resize_needed() const { return trigger_policy_base::is_resize_needed(); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: get_new_size(size_type size, size_type num_used_e) const { if (trigger_policy_base::is_grow_needed(size, num_used_e)) return size_policy_base::get_nearest_larger_size(size); return size_policy_base::get_nearest_smaller_size(size); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_resized(size_type new_size) { trigger_policy_base::notify_resized(new_size); m_size = new_size; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: get_actual_size() const { PB_DS_STATIC_ASSERT(access, external_size_access); return m_size; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: resize(size_type new_size) { PB_DS_STATIC_ASSERT(access, external_size_access); size_type actual_size = size_policy_base::get_nearest_larger_size(1); while (actual_size < new_size) { const size_type pot = size_policy_base::get_nearest_larger_size(actual_size); if (pot == actual_size && pot < new_size) __throw_resize_error(); actual_size = pot; } if (actual_size > 0) --actual_size; const size_type old_size = m_size; __try { do_resize(actual_size - 1); } __catch(insert_error& ) { m_size = old_size; __throw_resize_error(); } __catch(...) { m_size = old_size; __throw_exception_again; } } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: do_resize(size_type) { // Do nothing } PB_DS_CLASS_T_DEC Trigger_Policy& PB_DS_CLASS_C_DEC:: get_trigger_policy() { return *this; } PB_DS_CLASS_T_DEC const Trigger_Policy& PB_DS_CLASS_C_DEC:: get_trigger_policy() const { return *this; } PB_DS_CLASS_T_DEC Size_Policy& PB_DS_CLASS_C_DEC:: get_size_policy() { return *this; } PB_DS_CLASS_T_DEC const Size_Policy& PB_DS_CLASS_C_DEC:: get_size_policy() const { return *this; } PK!#f 98/ext/pb_ds/detail/resize_policy/sample_resize_policy.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file sample_resize_policy.hpp * Contains a sample resize policy for hash tables. */ #ifndef PB_DS_SAMPLE_RESIZE_POLICY_HPP #define PB_DS_SAMPLE_RESIZE_POLICY_HPP namespace __gnu_pbds { /// A sample resize policy. class sample_resize_policy { public: /// Size type. typedef std::size_t size_type; /// Default constructor. sample_resize_policy(); /// Copy constructor. sample_range_hashing(const sample_resize_policy& other); /// Swaps content. inline void swap(sample_resize_policy& other); protected: /// Notifies a search started. inline void notify_insert_search_start(); /// Notifies a search encountered a collision. inline void notify_insert_search_collision(); /// Notifies a search ended. inline void notify_insert_search_end(); /// Notifies a search started. inline void notify_find_search_start(); /// Notifies a search encountered a collision. inline void notify_find_search_collision(); /// Notifies a search ended. inline void notify_find_search_end(); /// Notifies a search started. inline void notify_erase_search_start(); /// Notifies a search encountered a collision. inline void notify_erase_search_collision(); /// Notifies a search ended. inline void notify_erase_search_end(); /// Notifies an element was inserted. inline void notify_inserted(size_type num_e); /// Notifies an element was erased. inline void notify_erased(size_type num_e); /// Notifies the table was cleared. void notify_cleared(); /// Notifies the table was resized to new_size. void notify_resized(size_type new_size); /// Queries whether a resize is needed. inline bool is_resize_needed() const; /// Queries what the new size should be. size_type get_new_size(size_type size, size_type num_used_e) const; }; } #endif PK!GQ=JJ:8/ext/pb_ds/detail/resize_policy/sample_resize_trigger.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file sample_resize_trigger.hpp * Contains a sample resize trigger policy class. */ #ifndef PB_DS_SAMPLE_RESIZE_TRIGGER_HPP #define PB_DS_SAMPLE_RESIZE_TRIGGER_HPP namespace __gnu_pbds { /// A sample resize trigger policy. class sample_resize_trigger { public: /// Size type. typedef std::size_t size_type; /// Default constructor. sample_resize_trigger(); /// Copy constructor. sample_range_hashing(const sample_resize_trigger&); /// Swaps content. inline void swap(sample_resize_trigger&); protected: /// Notifies a search started. inline void notify_insert_search_start(); /// Notifies a search encountered a collision. inline void notify_insert_search_collision(); /// Notifies a search ended. inline void notify_insert_search_end(); /// Notifies a search started. inline void notify_find_search_start(); /// Notifies a search encountered a collision. inline void notify_find_search_collision(); /// Notifies a search ended. inline void notify_find_search_end(); /// Notifies a search started. inline void notify_erase_search_start(); /// Notifies a search encountered a collision. inline void notify_erase_search_collision(); /// Notifies a search ended. inline void notify_erase_search_end(); /// Notifies an element was inserted. the total number of entries in /// the table is num_entries. inline void notify_inserted(size_type num_entries); /// Notifies an element was erased. inline void notify_erased(size_type num_entries); /// Notifies the table was cleared. void notify_cleared(); /// Notifies the table was resized as a result of this object's /// signifying that a resize is needed. void notify_resized(size_type new_size); /// Notifies the table was resized externally. void notify_externally_resized(size_type new_size); /// Queries whether a resize is needed. inline bool is_resize_needed() const; /// Queries whether a grow is needed. inline bool is_grow_needed(size_type size, size_type num_entries) const; private: /// Resizes to new_size. virtual void do_resize(size_type); }; } #endif PK!8{ { 78/ext/pb_ds/detail/resize_policy/sample_size_policy.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file sample_size_policy.hpp * Contains a sample size resize-policy. */ #ifndef PB_DS_SAMPLE_SIZE_POLICY_HPP #define PB_DS_SAMPLE_SIZE_POLICY_HPP namespace __gnu_pbds { /// A sample size policy. class sample_size_policy { public: /// Size type. typedef std::size_t size_type; /// Default constructor. sample_size_policy(); /// Copy constructor. sample_range_hashing(const sample_size_policy&); /// Swaps content. inline void swap(sample_size_policy& other); protected: /// Given a __size size, returns a __size that is larger. inline size_type get_nearest_larger_size(size_type size) const; /// Given a __size size, returns a __size that is smaller. inline size_type get_nearest_smaller_size(size_type size) const; }; } #endif PK!ܨ  B8/ext/pb_ds/detail/splay_tree_/constructors_destructor_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file splay_tree_/constructors_destructor_fn_imps.hpp * Contains an implementation class for splay_tree_. */ PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: copy_from_range(It first_it, It last_it) { while (first_it != last_it) insert(*(first_it++)); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_S_TREE_NAME() { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_S_TREE_NAME(const Cmp_Fn& r_cmp_fn) : base_type(r_cmp_fn) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_S_TREE_NAME(const Cmp_Fn& r_cmp_fn, const node_update& r_node_update) : base_type(r_cmp_fn, r_node_update) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: PB_DS_S_TREE_NAME(const PB_DS_CLASS_C_DEC& other) : base_type(other) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) base_type::swap(other); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: initialize() { base_type::m_p_head->m_special = true; } PK! 仧 08/ext/pb_ds/detail/splay_tree_/debug_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file splay_tree_/debug_fn_imps.hpp * Contains an implementation class for splay_tree_. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { base_type::assert_valid(__file, __line); const node_pointer p_head = base_type::m_p_head; assert_special_imp(p_head, __file, __line); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_special_imp(const node_pointer p_nd, const char* __file, int __line) const { if (p_nd == 0) return; if (p_nd == base_type::m_p_head) { PB_DS_DEBUG_VERIFY(p_nd->m_special); assert_special_imp(p_nd->m_p_parent, __file, __line); return; } PB_DS_DEBUG_VERIFY(!p_nd->m_special); assert_special_imp(p_nd->m_p_left, __file, __line); assert_special_imp(p_nd->m_p_right, __file, __line); } #endif PK!es08/ext/pb_ds/detail/splay_tree_/erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file splay_tree_/erase_fn_imps.hpp * Contains an implementation class for splay_tree_. */ PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: erase(key_const_reference r_key) { point_iterator it = find(r_key); if (it == base_type::end()) return false; erase(it); return true; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: erase(iterator it) { PB_DS_ASSERT_VALID((*this)) if (it == base_type::end()) return it; iterator ret_it = it; ++ret_it; erase_node(it.m_p_nd); PB_DS_ASSERT_VALID((*this)) return ret_it; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::reverse_iterator PB_DS_CLASS_C_DEC:: erase(reverse_iterator it) { PB_DS_ASSERT_VALID((*this)) if (it.m_p_nd == base_type::m_p_head) return (it); reverse_iterator ret_it = it; ++ret_it; erase_node(it.m_p_nd); PB_DS_ASSERT_VALID((*this)) return ret_it; } PB_DS_CLASS_T_DEC template inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: erase_if(Pred pred) { PB_DS_ASSERT_VALID((*this)) size_type num_ersd = 0; iterator it = base_type::begin(); while (it != base_type::end()) { if (pred(*it)) { ++num_ersd; it = erase(it); } else ++it; } PB_DS_ASSERT_VALID((*this)) return num_ersd; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: erase_node(node_pointer p_nd) { _GLIBCXX_DEBUG_ASSERT(p_nd != 0); splay(p_nd); PB_DS_ASSERT_VALID((*this)) _GLIBCXX_DEBUG_ASSERT(p_nd == this->m_p_head->m_p_parent); node_pointer p_l = p_nd->m_p_left; node_pointer p_r = p_nd->m_p_right; base_type::update_min_max_for_erased_node(p_nd); base_type::actual_erase_node(p_nd); if (p_r == 0) { base_type::m_p_head->m_p_parent = p_l; if (p_l != 0) p_l->m_p_parent = base_type::m_p_head; PB_DS_ASSERT_VALID((*this)) return; } node_pointer p_target_r = leftmost(p_r); _GLIBCXX_DEBUG_ASSERT(p_target_r != 0); p_r->m_p_parent = base_type::m_p_head; base_type::m_p_head->m_p_parent = p_r; splay(p_target_r); _GLIBCXX_DEBUG_ONLY(p_target_r->m_p_left = 0); _GLIBCXX_DEBUG_ASSERT(p_target_r->m_p_parent == this->m_p_head); _GLIBCXX_DEBUG_ASSERT(this->m_p_head->m_p_parent == p_target_r); p_target_r->m_p_left = p_l; if (p_l != 0) p_l->m_p_parent = p_target_r; PB_DS_ASSERT_VALID((*this)) this->apply_update(p_target_r, (node_update*)this); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: leftmost(node_pointer p_nd) { _GLIBCXX_DEBUG_ASSERT(p_nd != 0); while (p_nd->m_p_left != 0) p_nd = p_nd->m_p_left; return p_nd; } PK!94 /8/ext/pb_ds/detail/splay_tree_/find_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file splay_tree_/find_fn_imps.hpp * Contains an implementation class for splay_tree_. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: find(key_const_reference r_key) { node_pointer p_found = find_imp(r_key); if (p_found != base_type::m_p_head) splay(p_found); return point_iterator(p_found); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_const_iterator PB_DS_CLASS_C_DEC:: find(key_const_reference r_key) const { const node_pointer p_found = find_imp(r_key); if (p_found != base_type::m_p_head) const_cast(this)->splay(p_found); return point_iterator(p_found); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: find_imp(key_const_reference r_key) { _GLIBCXX_DEBUG_ONLY(base_type::structure_only_assert_valid(__FILE__, __LINE__);) node_pointer p_nd = base_type::m_p_head->m_p_parent; while (p_nd != 0) if (!Cmp_Fn::operator()(PB_DS_V2F(p_nd->m_value), r_key)) { if (!Cmp_Fn::operator()(r_key, PB_DS_V2F(p_nd->m_value))) return p_nd; p_nd = p_nd->m_p_left; } else p_nd = p_nd->m_p_right; return base_type::m_p_head; } PB_DS_CLASS_T_DEC inline const typename PB_DS_CLASS_C_DEC::node_pointer PB_DS_CLASS_C_DEC:: find_imp(key_const_reference r_key) const { PB_DS_ASSERT_VALID((*this)) node_pointer p_nd = base_type::m_p_head->m_p_parent; while (p_nd != 0) if (!Cmp_Fn::operator()(PB_DS_V2F(p_nd->m_value), r_key)) { if (!Cmp_Fn::operator()(r_key, PB_DS_V2F(p_nd->m_value))) return p_nd; p_nd = p_nd->m_p_left; } else p_nd = p_nd->m_p_right; return base_type::m_p_head; } PK!IC"/8/ext/pb_ds/detail/splay_tree_/info_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file splay_tree_/info_fn_imps.hpp * Contains an implementation. */ PK!  18/ext/pb_ds/detail/splay_tree_/insert_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file splay_tree_/insert_fn_imps.hpp * Contains an implementation class for splay_tree_. */ PB_DS_CLASS_T_DEC inline std::pair PB_DS_CLASS_C_DEC:: insert(const_reference r_value) { PB_DS_ASSERT_VALID((*this)) std::pair ins_pair = insert_leaf_imp(r_value); ins_pair.first.m_p_nd->m_special = false; PB_DS_ASSERT_VALID((*this)) splay(ins_pair.first.m_p_nd); PB_DS_ASSERT_VALID((*this)) return ins_pair; } PB_DS_CLASS_T_DEC inline std::pair PB_DS_CLASS_C_DEC:: insert_leaf_imp(const_reference r_value) { _GLIBCXX_DEBUG_ONLY(base_type::structure_only_assert_valid(__FILE__, __LINE__);) if (base_type::m_size == 0) return std::make_pair(base_type::insert_imp_empty(r_value), true); node_pointer p_nd = base_type::m_p_head->m_p_parent; node_pointer p_pot = base_type::m_p_head; while (p_nd != 0) if (!Cmp_Fn::operator()(PB_DS_V2F(p_nd->m_value), PB_DS_V2F(r_value))) { if (!Cmp_Fn::operator()(PB_DS_V2F(r_value), PB_DS_V2F(p_nd->m_value))) { return std::make_pair(point_iterator(p_nd), false); } p_pot = p_nd; p_nd = p_nd->m_p_left; } else p_nd = p_nd->m_p_right; if (p_pot == base_type::m_p_head) return std::make_pair(base_type::insert_leaf_new(r_value, base_type::m_p_head->m_p_right, false), true); PB_DS_CHECK_KEY_DOES_NOT_EXIST(PB_DS_V2F(r_value)) p_nd = p_pot->m_p_left; if (p_nd == 0) return (std::make_pair(base_type::insert_leaf_new(r_value, p_pot, true), true)); while (p_nd->m_p_right != 0) p_nd = p_nd->m_p_right; return std::make_pair(this->insert_leaf_new(r_value, p_nd, false), true); } PK!wӠ'8/ext/pb_ds/detail/splay_tree_/node.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file splay_tree_/node.hpp * Contains an implementation struct for splay_tree_'s node. */ #ifndef PB_DS_SPLAY_TREE_NODE_HPP #define PB_DS_SPLAY_TREE_NODE_HPP namespace __gnu_pbds { namespace detail { /// Node for splay tree. template struct splay_tree_node_ { public: typedef Value_Type value_type; typedef Metadata metadata_type; typedef typename _Alloc::template rebind< splay_tree_node_ >::other::pointer node_pointer; typedef typename _Alloc::template rebind::other::reference metadata_reference; typedef typename _Alloc::template rebind::other::const_reference metadata_const_reference; #ifdef PB_DS_BIN_SEARCH_TREE_TRACE_ void trace() const { std::cout << PB_DS_V2F(m_value) << "(" << m_metadata << ")"; } #endif inline bool special() const { return m_special; } inline metadata_const_reference get_metadata() const { return m_metadata; } inline metadata_reference get_metadata() { return m_metadata; } value_type m_value; bool m_special; node_pointer m_p_left; node_pointer m_p_right; node_pointer m_p_parent; metadata_type m_metadata; }; template struct splay_tree_node_ { public: typedef Value_Type value_type; typedef null_type metadata_type; typedef typename _Alloc::template rebind< splay_tree_node_ >::other::pointer node_pointer; inline bool special() const { return m_special; } #ifdef PB_DS_BIN_SEARCH_TREE_TRACE_ void trace() const { std::cout << PB_DS_V2F(m_value); } #endif node_pointer m_p_left; node_pointer m_p_right; node_pointer m_p_parent; value_type m_value; bool m_special; }; } // namespace detail } // namespace __gnu_pbds #endif PK!לqq08/ext/pb_ds/detail/splay_tree_/splay_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file splay_tree_/splay_fn_imps.hpp * Contains an implementation class for splay_tree_. */ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: splay(node_pointer p_nd) { while (p_nd->m_p_parent != base_type::m_p_head) { #ifdef _GLIBCXX_DEBUG { node_pointer p_head = base_type::m_p_head; assert_special_imp(p_head, __FILE__, __LINE__); } #endif PB_DS_ASSERT_BASE_NODE_CONSISTENT(p_nd) if (p_nd->m_p_parent->m_p_parent == base_type::m_p_head) { base_type::rotate_parent(p_nd); _GLIBCXX_DEBUG_ASSERT(p_nd == this->m_p_head->m_p_parent); } else { const node_pointer p_parent = p_nd->m_p_parent; const node_pointer p_grandparent = p_parent->m_p_parent; #ifdef _GLIBCXX_DEBUG const size_type total = base_type::recursive_count(p_grandparent); _GLIBCXX_DEBUG_ASSERT(total >= 3); #endif if (p_parent->m_p_left == p_nd && p_grandparent->m_p_right == p_parent) splay_zig_zag_left(p_nd, p_parent, p_grandparent); else if (p_parent->m_p_right == p_nd && p_grandparent->m_p_left == p_parent) splay_zig_zag_right(p_nd, p_parent, p_grandparent); else if (p_parent->m_p_left == p_nd && p_grandparent->m_p_left == p_parent) splay_zig_zig_left(p_nd, p_parent, p_grandparent); else splay_zig_zig_right(p_nd, p_parent, p_grandparent); _GLIBCXX_DEBUG_ASSERT(total ==this->recursive_count(p_nd)); } PB_DS_ASSERT_BASE_NODE_CONSISTENT(p_nd) } } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: splay_zig_zag_left(node_pointer p_nd, node_pointer p_parent, node_pointer p_grandparent) { _GLIBCXX_DEBUG_ASSERT(p_parent == p_nd->m_p_parent); _GLIBCXX_DEBUG_ASSERT(p_grandparent == p_parent->m_p_parent); PB_DS_ASSERT_BASE_NODE_CONSISTENT(p_grandparent) _GLIBCXX_DEBUG_ASSERT(p_parent->m_p_left == p_nd && p_grandparent->m_p_right == p_parent); splay_zz_start(p_nd, p_parent, p_grandparent); node_pointer p_b = p_nd->m_p_right; node_pointer p_c = p_nd->m_p_left; p_nd->m_p_right = p_parent; p_parent->m_p_parent = p_nd; p_nd->m_p_left = p_grandparent; p_grandparent->m_p_parent = p_nd; p_parent->m_p_left = p_b; if (p_b != 0) p_b->m_p_parent = p_parent; p_grandparent->m_p_right = p_c; if (p_c != 0) p_c->m_p_parent = p_grandparent; splay_zz_end(p_nd, p_parent, p_grandparent); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: splay_zig_zag_right(node_pointer p_nd, node_pointer p_parent, node_pointer p_grandparent) { _GLIBCXX_DEBUG_ASSERT(p_parent == p_nd->m_p_parent); _GLIBCXX_DEBUG_ASSERT(p_grandparent == p_parent->m_p_parent); PB_DS_ASSERT_BASE_NODE_CONSISTENT(p_grandparent) _GLIBCXX_DEBUG_ASSERT(p_parent->m_p_right == p_nd && p_grandparent->m_p_left == p_parent); splay_zz_start(p_nd, p_parent, p_grandparent); node_pointer p_b = p_nd->m_p_left; node_pointer p_c = p_nd->m_p_right; p_nd->m_p_left = p_parent; p_parent->m_p_parent = p_nd; p_nd->m_p_right = p_grandparent; p_grandparent->m_p_parent = p_nd; p_parent->m_p_right = p_b; if (p_b != 0) p_b->m_p_parent = p_parent; p_grandparent->m_p_left = p_c; if (p_c != 0) p_c->m_p_parent = p_grandparent; splay_zz_end(p_nd, p_parent, p_grandparent); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: splay_zig_zig_left(node_pointer p_nd, node_pointer p_parent, node_pointer p_grandparent) { _GLIBCXX_DEBUG_ASSERT(p_parent == p_nd->m_p_parent); _GLIBCXX_DEBUG_ASSERT(p_grandparent == p_parent->m_p_parent); PB_DS_ASSERT_BASE_NODE_CONSISTENT(p_grandparent) _GLIBCXX_DEBUG_ASSERT(p_parent->m_p_left == p_nd && p_nd->m_p_parent->m_p_parent->m_p_left == p_nd->m_p_parent); splay_zz_start(p_nd, p_parent, p_grandparent); node_pointer p_b = p_nd->m_p_right; node_pointer p_c = p_parent->m_p_right; p_nd->m_p_right = p_parent; p_parent->m_p_parent = p_nd; p_parent->m_p_right = p_grandparent; p_grandparent->m_p_parent = p_parent; p_parent->m_p_left = p_b; if (p_b != 0) p_b->m_p_parent = p_parent; p_grandparent->m_p_left = p_c; if (p_c != 0) p_c->m_p_parent = p_grandparent; splay_zz_end(p_nd, p_parent, p_grandparent); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: splay_zig_zig_right(node_pointer p_nd, node_pointer p_parent, node_pointer p_grandparent) { _GLIBCXX_DEBUG_ASSERT(p_parent == p_nd->m_p_parent); _GLIBCXX_DEBUG_ASSERT(p_grandparent == p_parent->m_p_parent); PB_DS_ASSERT_BASE_NODE_CONSISTENT(p_grandparent) _GLIBCXX_DEBUG_ASSERT(p_parent->m_p_right == p_nd && p_nd->m_p_parent->m_p_parent->m_p_right == p_nd->m_p_parent); splay_zz_start(p_nd, p_parent, p_grandparent); node_pointer p_b = p_nd->m_p_left; node_pointer p_c = p_parent->m_p_left; p_nd->m_p_left = p_parent; p_parent->m_p_parent = p_nd; p_parent->m_p_left = p_grandparent; p_grandparent->m_p_parent = p_parent; p_parent->m_p_right = p_b; if (p_b != 0) p_b->m_p_parent = p_parent; p_grandparent->m_p_right = p_c; if (p_c != 0) p_c->m_p_parent = p_grandparent; base_type::update_to_top(p_grandparent, (node_update*)this); splay_zz_end(p_nd, p_parent, p_grandparent); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: splay_zz_start(node_pointer p_nd, #ifdef _GLIBCXX_DEBUG node_pointer p_parent, #else node_pointer /*p_parent*/, #endif node_pointer p_grandparent) { _GLIBCXX_DEBUG_ASSERT(p_nd != 0); _GLIBCXX_DEBUG_ASSERT(p_parent != 0); _GLIBCXX_DEBUG_ASSERT(p_grandparent != 0); const bool grandparent_head = p_grandparent->m_p_parent == base_type::m_p_head; if (grandparent_head) { base_type::m_p_head->m_p_parent = base_type::m_p_head->m_p_parent; p_nd->m_p_parent = base_type::m_p_head; return; } node_pointer p_greatgrandparent = p_grandparent->m_p_parent; p_nd->m_p_parent = p_greatgrandparent; if (p_grandparent == p_greatgrandparent->m_p_left) p_greatgrandparent->m_p_left = p_nd; else p_greatgrandparent->m_p_right = p_nd; } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: splay_zz_end(node_pointer p_nd, node_pointer p_parent, node_pointer p_grandparent) { if (p_nd->m_p_parent == base_type::m_p_head) base_type::m_p_head->m_p_parent = p_nd; this->apply_update(p_grandparent, (node_update*)this); this->apply_update(p_parent, (node_update*)this); this->apply_update(p_nd, (node_update*)this); PB_DS_ASSERT_BASE_NODE_CONSISTENT(p_nd) } PK!轉[$[$.8/ext/pb_ds/detail/splay_tree_/splay_tree_.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file splay_tree_/splay_tree_.hpp * Contains an implementation class for splay trees. */ /* * This implementation uses an idea from the SGI STL (using a @a header node * which is needed for efficient iteration). Following is the SGI STL * copyright. * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * */ #include #include #include #include namespace __gnu_pbds { namespace detail { #ifdef PB_DS_DATA_TRUE_INDICATOR # define PB_DS_S_TREE_NAME splay_tree_map # define PB_DS_S_TREE_BASE_NAME bin_search_tree_map #endif #ifdef PB_DS_DATA_FALSE_INDICATOR # define PB_DS_S_TREE_NAME splay_tree_set # define PB_DS_S_TREE_BASE_NAME bin_search_tree_set #endif #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ PB_DS_S_TREE_NAME #define PB_DS_S_TREE_BASE \ PB_DS_S_TREE_BASE_NAME /** * @brief Splay tree. * @ingroup branch-detail */ template class PB_DS_S_TREE_NAME : public PB_DS_S_TREE_BASE { private: typedef PB_DS_S_TREE_BASE base_type; #ifdef _GLIBCXX_DEBUG typedef base_type debug_base; #endif typedef typename base_type::node_pointer node_pointer; public: typedef splay_tree_tag container_category; typedef _Alloc allocator_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef Cmp_Fn cmp_fn; typedef typename base_type::key_type key_type; typedef typename base_type::key_pointer key_pointer; typedef typename base_type::key_const_pointer key_const_pointer; typedef typename base_type::key_reference key_reference; typedef typename base_type::key_const_reference key_const_reference; typedef typename base_type::mapped_type mapped_type; typedef typename base_type::mapped_pointer mapped_pointer; typedef typename base_type::mapped_const_pointer mapped_const_pointer; typedef typename base_type::mapped_reference mapped_reference; typedef typename base_type::mapped_const_reference mapped_const_reference; typedef typename base_type::value_type value_type; typedef typename base_type::pointer pointer; typedef typename base_type::const_pointer const_pointer; typedef typename base_type::reference reference; typedef typename base_type::const_reference const_reference; typedef typename base_type::point_iterator point_iterator; typedef typename base_type::const_iterator point_const_iterator; typedef typename base_type::iterator iterator; typedef typename base_type::const_iterator const_iterator; typedef typename base_type::reverse_iterator reverse_iterator; typedef typename base_type::const_reverse_iterator const_reverse_iterator; typedef typename base_type::node_update node_update; PB_DS_S_TREE_NAME(); PB_DS_S_TREE_NAME(const Cmp_Fn&); PB_DS_S_TREE_NAME(const Cmp_Fn&, const node_update&); PB_DS_S_TREE_NAME(const PB_DS_CLASS_C_DEC&); void swap(PB_DS_CLASS_C_DEC&); template void copy_from_range(It, It); void initialize(); inline std::pair insert(const_reference r_value); inline mapped_reference operator[](key_const_reference r_key) { #ifdef PB_DS_DATA_TRUE_INDICATOR _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) std::pair ins_pair = insert_leaf_imp(value_type(r_key, mapped_type())); ins_pair.first.m_p_nd->m_special = false; _GLIBCXX_DEBUG_ONLY(base_type::assert_valid(__FILE__, __LINE__)); splay(ins_pair.first.m_p_nd); _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) return ins_pair.first.m_p_nd->m_value.second; #else insert(r_key); return base_type::s_null_type; #endif } inline point_iterator find(key_const_reference); inline point_const_iterator find(key_const_reference) const; inline bool erase(key_const_reference); inline iterator erase(iterator it); inline reverse_iterator erase(reverse_iterator); template inline size_type erase_if(Pred); void join(PB_DS_CLASS_C_DEC&); void split(key_const_reference, PB_DS_CLASS_C_DEC&); private: inline std::pair insert_leaf_imp(const_reference); inline node_pointer find_imp(key_const_reference); inline const node_pointer find_imp(key_const_reference) const; #ifdef _GLIBCXX_DEBUG void assert_valid(const char* file, int line) const; void assert_special_imp(const node_pointer, const char* file, int line) const; #endif void splay(node_pointer); inline void splay_zig_zag_left(node_pointer, node_pointer, node_pointer); inline void splay_zig_zag_right(node_pointer, node_pointer, node_pointer); inline void splay_zig_zig_left(node_pointer, node_pointer, node_pointer); inline void splay_zig_zig_right(node_pointer, node_pointer, node_pointer); inline void splay_zz_start(node_pointer, node_pointer, node_pointer); inline void splay_zz_end(node_pointer, node_pointer, node_pointer); inline node_pointer leftmost(node_pointer); void erase_node(node_pointer); }; #define PB_DS_ASSERT_BASE_NODE_CONSISTENT(_Node) \ _GLIBCXX_DEBUG_ONLY(base_type::assert_node_consistent(_Node, \ __FILE__, __LINE__);) #include #include #include #include #include #include #include #undef PB_DS_ASSERT_BASE_NODE_CONSISTENT #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #undef PB_DS_S_TREE_NAME #undef PB_DS_S_TREE_BASE_NAME #undef PB_DS_S_TREE_BASE } // namespace detail } // namespace __gnu_pbds PK!e532258/ext/pb_ds/detail/splay_tree_/split_join_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file splay_tree_/split_join_fn_imps.hpp * Contains an implementation class for splay_tree_. */ PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: join(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) if (base_type::join_prep(other) == false) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return; } node_pointer p_target_r = other.leftmost(other.m_p_head); _GLIBCXX_DEBUG_ASSERT(p_target_r != 0); other.splay(p_target_r); _GLIBCXX_DEBUG_ASSERT(p_target_r == other.m_p_head->m_p_parent); _GLIBCXX_DEBUG_ASSERT(p_target_r->m_p_left == 0); p_target_r->m_p_left = base_type::m_p_head->m_p_parent; _GLIBCXX_DEBUG_ASSERT(p_target_r->m_p_left != 0); p_target_r->m_p_left->m_p_parent = p_target_r; base_type::m_p_head->m_p_parent = p_target_r; p_target_r->m_p_parent = base_type::m_p_head; this->apply_update(p_target_r, (node_update*)this); base_type::join_finish(other); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: split(key_const_reference r_key, PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) if (base_type::split_prep(r_key, other) == false) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return; } node_pointer p_upper_bound = this->upper_bound(r_key).m_p_nd; _GLIBCXX_DEBUG_ASSERT(p_upper_bound != 0); splay(p_upper_bound); _GLIBCXX_DEBUG_ASSERT(p_upper_bound->m_p_parent == this->m_p_head); node_pointer p_new_root = p_upper_bound->m_p_left; _GLIBCXX_DEBUG_ASSERT(p_new_root != 0); base_type::m_p_head->m_p_parent = p_new_root; p_new_root->m_p_parent = base_type::m_p_head; other.m_p_head->m_p_parent = p_upper_bound; p_upper_bound->m_p_parent = other.m_p_head; p_upper_bound->m_p_left = 0; this->apply_update(p_upper_bound, (node_update*)this); base_type::split_finish(other); PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PK!P   )8/ext/pb_ds/detail/splay_tree_/traits.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file splay_tree_/traits.hpp * Contains an implementation for splay_tree_. */ #ifndef PB_DS_SPLAY_TREE_NODE_AND_IT_TRAITS_HPP #define PB_DS_SPLAY_TREE_NODE_AND_IT_TRAITS_HPP #include namespace __gnu_pbds { namespace detail { /// Specialization. /// @ingroup traits template class Node_Update, typename _Alloc> struct tree_traits : public bin_search_tree_traits::value_type, typename tree_node_metadata_dispatch::type, _Alloc>, _Alloc> { }; /// Specialization. /// @ingroup traits template class Node_Update, typename _Alloc> struct tree_traits : public bin_search_tree_traits::value_type, typename tree_node_metadata_dispatch::type, _Alloc>, _Alloc> { }; } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_SPLAY_TREE_NODE_AND_IT_TRAITS_HPP PK!3^ A8/ext/pb_ds/detail/thin_heap_/constructors_destructor_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file thin_heap_/constructors_destructor_fn_imps.hpp * Contains an implementation for thin_heap_. */ PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: copy_from_range(It first_it, It last_it) { while (first_it != last_it) push(*(first_it++)); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: thin_heap() : m_p_max(0) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: thin_heap(const Cmp_Fn& r_cmp_fn) : base_type(r_cmp_fn), m_p_max(0) { initialize(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: thin_heap(const PB_DS_CLASS_C_DEC& other) : base_type(other) { initialize(); m_p_max = base_type::m_p_root; for (node_pointer p_nd = base_type::m_p_root; p_nd != 0; p_nd = p_nd->m_p_next_sibling) if (Cmp_Fn::operator()(m_p_max->m_value, p_nd->m_value)) m_p_max = p_nd; PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) base_type::swap(other); std::swap(m_p_max, other.m_p_max); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~thin_heap() { } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: initialize() { std::fill(m_a_aux, m_a_aux + max_rank, static_cast(0)); } PK! /8/ext/pb_ds/detail/thin_heap_/debug_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file thin_heap_/debug_fn_imps.hpp * Contains an implementation for thin_heap_. */ #ifdef _GLIBCXX_DEBUG PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { base_type::assert_valid(__file, __line); assert_node_consistent(base_type::m_p_root, true, __file, __line); assert_max(__file, __line); assert_aux_null(__file, __line); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_aux_null(const char* __file, int __line) const { for (size_type i = 0; i < max_rank; ++i) PB_DS_DEBUG_VERIFY(m_a_aux[i] == 0); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_max(const char* __file, int __line) const { if (m_p_max == 0) { PB_DS_DEBUG_VERIFY(base_type::empty()); return; } PB_DS_DEBUG_VERIFY(!base_type::empty()); PB_DS_DEBUG_VERIFY(base_type::parent(m_p_max) == 0); PB_DS_DEBUG_VERIFY(m_p_max->m_p_prev_or_parent == 0); for (const_iterator it = base_type::begin(); it != base_type::end(); ++it) PB_DS_DEBUG_VERIFY(!Cmp_Fn::operator()(m_p_max->m_value, it.m_p_nd->m_value)); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_node_consistent(node_const_pointer p_nd, bool root, const char* __file, int __line) const { base_type::assert_node_consistent(p_nd, root, __file, __line); if (p_nd == 0) return; assert_node_consistent(p_nd->m_p_next_sibling, root, __file, __line); assert_node_consistent(p_nd->m_p_l_child, false, __file, __line); if (!root) { if (p_nd->m_metadata == 0) PB_DS_DEBUG_VERIFY(p_nd->m_p_next_sibling == 0); else PB_DS_DEBUG_VERIFY(p_nd->m_metadata == p_nd->m_p_next_sibling->m_metadata + 1); } if (p_nd->m_p_l_child != 0) PB_DS_DEBUG_VERIFY(p_nd->m_p_l_child->m_metadata + 1 == base_type::degree(p_nd)); const bool unmarked_valid = (p_nd->m_p_l_child == 0 && p_nd->m_metadata == 0) || (p_nd->m_p_l_child != 0 && p_nd->m_metadata == p_nd->m_p_l_child->m_metadata + 1); const bool marked_valid = (p_nd->m_p_l_child == 0 && p_nd->m_metadata == 1) || (p_nd->m_p_l_child != 0 && p_nd->m_metadata == p_nd->m_p_l_child->m_metadata + 2); PB_DS_DEBUG_VERIFY(unmarked_valid || marked_valid); if (root) PB_DS_DEBUG_VERIFY(unmarked_valid); } #endif PK!@d /8/ext/pb_ds/detail/thin_heap_/erase_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file thin_heap_/erase_fn_imps.hpp * Contains an implementation for thin_heap_. */ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: pop() { PB_DS_ASSERT_VALID((*this)) _GLIBCXX_DEBUG_ASSERT(!base_type::empty()); _GLIBCXX_DEBUG_ASSERT(m_p_max != 0); node_pointer p_nd = m_p_max; remove_max_node(); base_type::actual_erase_node(p_nd); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: remove_max_node() { to_aux_except_max(); make_from_aux(); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: to_aux_except_max() { node_pointer p_add = base_type::m_p_root; while (p_add != m_p_max) { node_pointer p_next_add = p_add->m_p_next_sibling; add_to_aux(p_add); p_add = p_next_add; } p_add = m_p_max->m_p_l_child; while (p_add != 0) { node_pointer p_next_add = p_add->m_p_next_sibling; p_add->m_metadata = p_add->m_p_l_child == 0 ? 0 : p_add->m_p_l_child->m_metadata + 1; add_to_aux(p_add); p_add = p_next_add; } p_add = m_p_max->m_p_next_sibling; while (p_add != 0) { node_pointer p_next_add = p_add->m_p_next_sibling; add_to_aux(p_add); p_add = p_next_add; } } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: add_to_aux(node_pointer p_nd) { size_type r = p_nd->m_metadata; while (m_a_aux[r] != 0) { _GLIBCXX_DEBUG_ASSERT(p_nd->m_metadata < rank_bound()); if (Cmp_Fn::operator()(m_a_aux[r]->m_value, p_nd->m_value)) make_child_of(m_a_aux[r], p_nd); else { make_child_of(p_nd, m_a_aux[r]); p_nd = m_a_aux[r]; } m_a_aux[r] = 0; ++r; } _GLIBCXX_DEBUG_ASSERT(p_nd->m_metadata < rank_bound()); m_a_aux[r] = p_nd; } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: make_child_of(node_pointer p_nd, node_pointer p_new_parent) { _GLIBCXX_DEBUG_ASSERT(p_nd->m_metadata == p_new_parent->m_metadata); _GLIBCXX_DEBUG_ASSERT(m_a_aux[p_nd->m_metadata] == p_nd || m_a_aux[p_nd->m_metadata] == p_new_parent); ++p_new_parent->m_metadata; base_type::make_child_of(p_nd, p_new_parent); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: make_from_aux() { base_type::m_p_root = m_p_max = 0; const size_type rnk_bnd = rank_bound(); size_type i = 0; while (i < rnk_bnd) { if (m_a_aux[i] != 0) { make_root_and_link(m_a_aux[i]); m_a_aux[i] = 0; } ++i; } PB_DS_ASSERT_AUX_NULL((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: remove_node(node_pointer p_nd) { node_pointer p_parent = p_nd; while (base_type::parent(p_parent) != 0) p_parent = base_type::parent(p_parent); base_type::bubble_to_top(p_nd); m_p_max = p_nd; node_pointer p_fix = base_type::m_p_root; while (p_fix != 0&& p_fix->m_p_next_sibling != p_parent) p_fix = p_fix->m_p_next_sibling; if (p_fix != 0) p_fix->m_p_next_sibling = p_nd; remove_max_node(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: clear() { base_type::clear(); m_p_max = 0; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: erase(point_iterator it) { PB_DS_ASSERT_VALID((*this)) _GLIBCXX_DEBUG_ASSERT(!base_type::empty()); node_pointer p_nd = it.m_p_nd; remove_node(p_nd); base_type::actual_erase_node(p_nd); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC template typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: erase_if(Pred pred) { PB_DS_ASSERT_VALID((*this)) if (base_type::empty()) { PB_DS_ASSERT_VALID((*this)) return 0; } base_type::to_linked_list(); node_pointer p_out = base_type::prune(pred); size_type ersd = 0; while (p_out != 0) { ++ersd; node_pointer p_next = p_out->m_p_next_sibling; base_type::actual_erase_node(p_out); p_out = p_next; } node_pointer p_cur = base_type::m_p_root; m_p_max = base_type::m_p_root = 0; while (p_cur != 0) { node_pointer p_next = p_cur->m_p_next_sibling; make_root_and_link(p_cur); p_cur = p_next; } PB_DS_ASSERT_VALID((*this)) return ersd; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: rank_bound() { using namespace std; const size_t* const p_upper = std::upper_bound(g_a_rank_bounds, g_a_rank_bounds + num_distinct_rank_bounds, base_type::m_size); if (p_upper == g_a_rank_bounds + num_distinct_rank_bounds) return max_rank; return (p_upper - g_a_rank_bounds); } PK!3.8/ext/pb_ds/detail/thin_heap_/find_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file thin_heap_/find_fn_imps.hpp * Contains an implementation for thin_heap_. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_reference PB_DS_CLASS_C_DEC:: top() const { PB_DS_ASSERT_VALID((*this)) _GLIBCXX_DEBUG_ASSERT(!base_type::empty()); _GLIBCXX_DEBUG_ASSERT(m_p_max != 0); return m_p_max->m_value; } PK!6;;08/ext/pb_ds/detail/thin_heap_/insert_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file thin_heap_/insert_fn_imps.hpp * Contains an implementation for thin_heap_. */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::point_iterator PB_DS_CLASS_C_DEC:: push(const_reference r_val) { PB_DS_ASSERT_VALID((*this)) node_pointer p_nd = base_type::get_new_node_for_insert(r_val); p_nd->m_metadata = 0; p_nd->m_p_prev_or_parent = p_nd->m_p_l_child = 0; if (base_type::m_p_root == 0) { p_nd->m_p_next_sibling = 0; m_p_max = base_type::m_p_root = p_nd; PB_DS_ASSERT_VALID((*this)) return point_iterator(p_nd); } p_nd->m_p_next_sibling = base_type::m_p_root; base_type::m_p_root->m_p_prev_or_parent = 0; base_type::m_p_root = p_nd; update_max(p_nd); PB_DS_ASSERT_VALID((*this)) return point_iterator(p_nd); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: make_root(node_pointer p_nd) { p_nd->m_metadata = p_nd->m_p_l_child == 0 ? 0 : 1 + p_nd->m_p_l_child->m_metadata; } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: make_root_and_link(node_pointer p_nd) { make_root(p_nd); p_nd->m_p_prev_or_parent = 0; p_nd->m_p_next_sibling = base_type::m_p_root; if (base_type::m_p_root != 0) base_type::m_p_root->m_p_prev_or_parent = 0; base_type::m_p_root = p_nd; update_max(p_nd); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: fix(node_pointer p_y) { while (true) { if (p_y->m_p_prev_or_parent == 0) { fix_root(p_y); return; } else if (p_y->m_metadata == 1&& p_y->m_p_next_sibling == 0) { if (p_y->m_p_l_child != 0) { fix_sibling_rank_1_unmarked(p_y); return; } fix_sibling_rank_1_marked(p_y); p_y = p_y->m_p_prev_or_parent; } else if (p_y->m_metadata > p_y->m_p_next_sibling->m_metadata + 1) { _GLIBCXX_DEBUG_ASSERT(p_y->m_p_l_child != 0); if (p_y->m_metadata != p_y->m_p_l_child->m_metadata + 2) { fix_sibling_general_unmarked(p_y); return; } fix_sibling_general_marked(p_y); p_y = p_y->m_p_prev_or_parent; } else if ((p_y->m_p_l_child == 0&& p_y->m_metadata == 2) ||(p_y->m_p_l_child != 0&& p_y->m_metadata == p_y->m_p_l_child->m_metadata + 3)) { node_pointer p_z = p_y->m_p_prev_or_parent; fix_child(p_y); p_y = p_z; } else return; } } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: fix_root(node_pointer p_y) { _GLIBCXX_DEBUG_ASSERT(p_y->m_p_prev_or_parent == 0); make_root(p_y); PB_DS_ASSERT_NODE_CONSISTENT(p_y, true) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: fix_sibling_rank_1_unmarked(node_pointer p_y) { _GLIBCXX_DEBUG_ASSERT(p_y->m_p_prev_or_parent != 0); _GLIBCXX_DEBUG_ONLY(node_pointer p_w = p_y->m_p_l_child;) _GLIBCXX_DEBUG_ASSERT(p_w != 0); _GLIBCXX_DEBUG_ASSERT(p_w->m_p_next_sibling == 0); _GLIBCXX_DEBUG_ASSERT(p_y->m_p_next_sibling == 0); p_y->m_p_next_sibling = p_y->m_p_l_child; p_y->m_p_next_sibling->m_p_prev_or_parent = p_y; p_y->m_p_l_child = 0; PB_DS_ASSERT_NODE_CONSISTENT(p_y, false) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: fix_sibling_rank_1_marked(node_pointer p_y) { _GLIBCXX_DEBUG_ASSERT(p_y->m_p_prev_or_parent != 0); _GLIBCXX_DEBUG_ASSERT(p_y->m_p_l_child == 0); p_y->m_metadata = 0; PB_DS_ASSERT_NODE_CONSISTENT(p_y, false) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: fix_sibling_general_unmarked(node_pointer p_y) { _GLIBCXX_DEBUG_ASSERT(p_y->m_p_prev_or_parent != 0); node_pointer p_w = p_y->m_p_l_child; _GLIBCXX_DEBUG_ASSERT(p_w != 0); _GLIBCXX_DEBUG_ASSERT(p_w->m_p_next_sibling != 0); p_y->m_p_l_child = p_w->m_p_next_sibling; p_w->m_p_next_sibling->m_p_prev_or_parent = p_y; p_w->m_p_next_sibling = p_y->m_p_next_sibling; _GLIBCXX_DEBUG_ASSERT(p_w->m_p_next_sibling != 0); p_w->m_p_next_sibling->m_p_prev_or_parent = p_w; p_y->m_p_next_sibling = p_w; p_w->m_p_prev_or_parent = p_y; PB_DS_ASSERT_NODE_CONSISTENT(p_y, false) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: fix_sibling_general_marked(node_pointer p_y) { _GLIBCXX_DEBUG_ASSERT(p_y->m_p_prev_or_parent != 0); --p_y->m_metadata; PB_DS_ASSERT_NODE_CONSISTENT(p_y, false) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: fix_child(node_pointer p_y) { _GLIBCXX_DEBUG_ASSERT(p_y->m_p_prev_or_parent != 0); if (p_y->m_p_next_sibling != 0) p_y->m_p_next_sibling->m_p_prev_or_parent = p_y->m_p_prev_or_parent; if (p_y->m_p_prev_or_parent->m_p_l_child == p_y) p_y->m_p_prev_or_parent->m_p_l_child = p_y->m_p_next_sibling; else p_y->m_p_prev_or_parent->m_p_next_sibling = p_y->m_p_next_sibling; make_root_and_link(p_y); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: modify(point_iterator it, const_reference r_new_val) { PB_DS_ASSERT_VALID((*this)) node_pointer p_nd = it.m_p_nd; _GLIBCXX_DEBUG_ASSERT(p_nd != 0); const bool smaller = Cmp_Fn::operator()(r_new_val, p_nd->m_value); p_nd->m_value = r_new_val; if (smaller) { remove_node(p_nd); p_nd->m_p_l_child = 0; make_root_and_link(p_nd); PB_DS_ASSERT_VALID((*this)) return; } if (p_nd->m_p_prev_or_parent == 0) { update_max(p_nd); PB_DS_ASSERT_VALID((*this)) return; } node_pointer p_y = p_nd->m_p_prev_or_parent; _GLIBCXX_DEBUG_ASSERT(p_y != 0); if (p_nd->m_p_next_sibling != 0) p_nd->m_p_next_sibling->m_p_prev_or_parent = p_y; if (p_y->m_p_l_child == p_nd) p_y->m_p_l_child = p_nd->m_p_next_sibling; else p_y->m_p_next_sibling = p_nd->m_p_next_sibling; fix(p_y); make_root_and_link(p_nd); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: update_max(node_pointer p_nd) { if (m_p_max == 0 || Cmp_Fn::operator()(m_p_max->m_value, p_nd->m_value)) m_p_max = p_nd; } PK!tS S 48/ext/pb_ds/detail/thin_heap_/split_join_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file thin_heap_/split_join_fn_imps.hpp * Contains an implementation for thin_heap_. */ PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: split(Pred pred, PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) other.clear(); if (base_type::empty()) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) return; } base_type::to_linked_list(); node_pointer p_out = base_type::prune(pred); while (p_out != 0) { _GLIBCXX_DEBUG_ASSERT(base_type::m_size > 0); --base_type::m_size; ++other.m_size; node_pointer p_next = p_out->m_p_next_sibling; other.make_root_and_link(p_out); p_out = p_next; } PB_DS_ASSERT_VALID(other) node_pointer p_cur = base_type::m_p_root; m_p_max = 0; base_type::m_p_root = 0; while (p_cur != 0) { node_pointer p_next = p_cur->m_p_next_sibling; make_root_and_link(p_cur); p_cur = p_next; } PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: join(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) node_pointer p_other = other.m_p_root; while (p_other != 0) { node_pointer p_next = p_other->m_p_next_sibling; make_root_and_link(p_other); p_other = p_next; } base_type::m_size += other.m_size; other.m_p_root = 0; other.m_size = 0; other.m_p_max = 0; PB_DS_ASSERT_VALID((*this)) PB_DS_ASSERT_VALID(other) } PK!. ,8/ext/pb_ds/detail/thin_heap_/thin_heap_.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file thin_heap_/thin_heap_.hpp * Contains an implementation class for a thin heap. */ #ifndef PB_DS_THIN_HEAP_HPP #define PB_DS_THIN_HEAP_HPP #include #include #include #include #include namespace __gnu_pbds { namespace detail { #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ thin_heap #ifdef _GLIBCXX_DEBUG #define PB_DS_BASE_T_P \ #else #define PB_DS_BASE_T_P \ #endif /** * Thin heap. * * @ingroup heap-detail * * See Tarjan and Kaplan. */ template class thin_heap : public left_child_next_sibling_heap PB_DS_BASE_T_P { private: typedef typename _Alloc::template rebind::other __rebind_a; typedef left_child_next_sibling_heap PB_DS_BASE_T_P base_type; protected: typedef typename base_type::node node; typedef typename base_type::node_pointer node_pointer; typedef typename base_type::node_const_pointer node_const_pointer; public: typedef Value_Type value_type; typedef Cmp_Fn cmp_fn; typedef _Alloc allocator_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef typename __rebind_a::pointer pointer; typedef typename __rebind_a::const_pointer const_pointer; typedef typename __rebind_a::reference reference; typedef typename __rebind_a::const_reference const_reference; typedef typename base_type::point_iterator point_iterator; typedef typename base_type::point_const_iterator point_const_iterator; typedef typename base_type::iterator iterator; typedef typename base_type::const_iterator const_iterator; inline point_iterator push(const_reference); void modify(point_iterator, const_reference); inline const_reference top() const; void pop(); void erase(point_iterator); inline void clear(); template size_type erase_if(Pred); template void split(Pred, PB_DS_CLASS_C_DEC&); void join(PB_DS_CLASS_C_DEC&); protected: thin_heap(); thin_heap(const Cmp_Fn&); thin_heap(const PB_DS_CLASS_C_DEC&); void swap(PB_DS_CLASS_C_DEC&); ~thin_heap(); template void copy_from_range(It, It); #ifdef _GLIBCXX_DEBUG void assert_valid(const char*, int) const; void assert_max(const char*, int) const; #endif #ifdef PB_DS_THIN_HEAP_TRACE_ void trace() const; #endif private: enum { max_rank = (sizeof(size_type) << 4) + 2 }; void initialize(); inline void update_max(node_pointer); inline void fix(node_pointer); inline void fix_root(node_pointer); inline void fix_sibling_rank_1_unmarked(node_pointer); inline void fix_sibling_rank_1_marked(node_pointer); inline void fix_sibling_general_unmarked(node_pointer); inline void fix_sibling_general_marked(node_pointer); inline void fix_child(node_pointer); inline static void make_root(node_pointer); inline void make_root_and_link(node_pointer); inline void remove_max_node(); void to_aux_except_max(); inline void add_to_aux(node_pointer); inline void make_from_aux(); inline size_type rank_bound(); inline void make_child_of(node_pointer, node_pointer); inline void remove_node(node_pointer); inline node_pointer join(node_pointer, node_pointer) const; #ifdef _GLIBCXX_DEBUG void assert_node_consistent(node_const_pointer, bool, const char*, int) const; void assert_aux_null(const char*, int) const; #endif node_pointer m_p_max; node_pointer m_a_aux[max_rank]; }; enum { num_distinct_rank_bounds = 48 }; // Taken from the SGI implementation; acknowledged in the docs. static const std::size_t g_a_rank_bounds[num_distinct_rank_bounds] = { /* Dealing cards... */ /* 0 */ 0ul, /* 1 */ 1ul, /* 2 */ 1ul, /* 3 */ 2ul, /* 4 */ 4ul, /* 5 */ 6ul, /* 6 */ 11ul, /* 7 */ 17ul, /* 8 */ 29ul, /* 9 */ 46ul, /* 10 */ 76ul, /* 11 */ 122ul, /* 12 */ 199ul, /* 13 */ 321ul, /* 14 */ 521ul, /* 15 */ 842ul, /* 16 */ 1364ul, /* 17 */ 2206ul, /* 18 */ 3571ul, /* 19 */ 5777ul, /* 20 */ 9349ul, /* 21 */ 15126ul, /* 22 */ 24476ul, /* 23 */ 39602ul, /* 24 */ 64079ul #if __SIZE_MAX__ > 0xfffful , /* 25 */ 103681ul, /* 26 */ 167761ul, /* 27 */ 271442ul, /* 28 */ 439204ul, /* 29 */ 710646ul #if __SIZE_MAX__ > 0xffffful , /* 30 */ 1149851ul, /* 31 */ 1860497ul, /* 32 */ 3010349ul, /* 33 */ 4870846ul, /* 34 */ 7881196ul, /* 35 */ 12752042ul #if __SIZE_MAX__ > 0xfffffful , /* 36 */ 20633239ul, /* 37 */ 33385282ul, /* 38 */ 54018521ul, /* 39 */ 87403803ul, /* 40 */ 141422324ul, /* 41 */ 228826127ul, /* 42 */ 370248451ul, /* 43 */ 599074578ul, /* 44 */ 969323029ul, /* 45 */ 1568397607ul, /* 46 */ 2537720636ul, /* 47 */ 4106118243ul #endif #endif #endif /* Pot's good, let's play */ }; #define PB_DS_ASSERT_NODE_CONSISTENT(_Node, _Bool) \ _GLIBCXX_DEBUG_ONLY(assert_node_consistent(_Node, _Bool, \ __FILE__, __LINE__);) #define PB_DS_ASSERT_AUX_NULL(X) \ _GLIBCXX_DEBUG_ONLY(X.assert_aux_null(__FILE__, __LINE__);) #include #include #include #include #include #include #include #undef PB_DS_ASSERT_AUX_NULL #undef PB_DS_ASSERT_NODE_CONSISTENT #undef PB_DS_CLASS_C_DEC #undef PB_DS_CLASS_T_DEC #undef PB_DS_BASE_T_P } // namespace detail } // namespace __gnu_pbds #endif PK!%yB/8/ext/pb_ds/detail/thin_heap_/trace_fn_imps.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file thin_heap_/trace_fn_imps.hpp * Contains an implementation class for left_child_next_sibling_heap_. */ #ifdef PB_DS_THIN_HEAP_TRACE_ PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace() const { std::cerr << std::endl; std::cerr << "m_p_max " << m_p_max << std::endl; base_type::trace(); } #endif // #ifdef PB_DS_THIN_HEAP_TRACE_ PK!a( 98/ext/pb_ds/detail/tree_policy/node_metadata_selector.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file tree_policy/node_metadata_selector.hpp * Contains an implementation class for trees. */ #ifndef PB_DS_TREE_NODE_METADATA_DISPATCH_HPP #define PB_DS_TREE_NODE_METADATA_DISPATCH_HPP #include #include namespace __gnu_pbds { namespace detail { /** * @addtogroup traits Traits * @{ */ /// Tree metadata helper. template struct tree_metadata_helper; /// Specialization, false. template struct tree_metadata_helper { typedef typename Node_Update::metadata_type type; }; /// Specialization, true. template struct tree_metadata_helper { typedef null_type type; }; /// Tree node metadata dispatch. template class Node_Update, typename _Alloc> struct tree_node_metadata_dispatch { private: typedef dumnode_const_iterator __it_type; typedef Node_Update<__it_type, __it_type, Cmp_Fn, _Alloc> __node_u; typedef null_node_update<__it_type, __it_type, Cmp_Fn, _Alloc> __nnode_u; enum { null_update = is_same<__node_u, __nnode_u>::value }; public: typedef typename tree_metadata_helper<__node_u, null_update>::type type; }; //@} } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_TREE_NODE_METADATA_DISPATCH_HPP PK!278/ext/pb_ds/detail/tree_policy/order_statistics_imp.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file tree_policy/order_statistics_imp.hpp * Contains forward declarations for order_statistics_key */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: find_by_order(size_type order) { node_iterator it = node_begin(); node_iterator end_it = node_end(); while (it != end_it) { node_iterator l_it = it.get_l_child(); const size_type o = (l_it == end_it)? 0 : l_it.get_metadata(); if (order == o) return *it; else if (order < o) it = l_it; else { order -= o + 1; it = it.get_r_child(); } } return base_type::end_iterator(); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: find_by_order(size_type order) const { return const_cast(this)->find_by_order(order); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: order_of_key(key_const_reference r_key) const { node_const_iterator it = node_begin(); node_const_iterator end_it = node_end(); const cmp_fn& r_cmp_fn = const_cast(this)->get_cmp_fn(); size_type ord = 0; while (it != end_it) { node_const_iterator l_it = it.get_l_child(); if (r_cmp_fn(r_key, this->extract_key(*(*it)))) it = l_it; else if (r_cmp_fn(this->extract_key(*(*it)), r_key)) { ord += (l_it == end_it)? 1 : 1 + l_it.get_metadata(); it = it.get_r_child(); } else { ord += (l_it == end_it)? 0 : l_it.get_metadata(); it = end_it; } } return ord; } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: operator()(node_iterator node_it, node_const_iterator end_nd_it) const { node_iterator l_it = node_it.get_l_child(); const size_type l_rank = (l_it == end_nd_it) ? 0 : l_it.get_metadata(); node_iterator r_it = node_it.get_r_child(); const size_type r_rank = (r_it == end_nd_it) ? 0 : r_it.get_metadata(); const_cast(node_it.get_metadata())= 1 + l_rank + r_rank; } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~tree_order_statistics_node_update() { } PK!5'* * :8/ext/pb_ds/detail/tree_policy/sample_tree_node_update.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file tree_policy/sample_tree_node_update.hpp * Contains a samle node update functor. */ #ifndef PB_DS_SAMPLE_TREE_NODE_UPDATOR_HPP #define PB_DS_SAMPLE_TREE_NODE_UPDATOR_HPP namespace __gnu_pbds { /// A sample node updator. template class sample_tree_node_update { typedef std::size_t metadata_type; /// Default constructor. sample_tree_node_update(); /// Updates the rank of a node through a node_iterator node_it; /// end_nd_it is the end node iterator. inline void operator()(node_iterator node_it, node_const_iterator end_nd_it) const; }; } #endif // #ifndef PB_DS_SAMPLE_TREE_NODE_UPDATOR_HPP PK!&vC 98/ext/pb_ds/detail/trie_policy/node_metadata_selector.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file trie_policy/node_metadata_selector.hpp * Contains an implementation class for tries. */ #ifndef PB_DS_TRIE_NODE_METADATA_DISPATCH_HPP #define PB_DS_TRIE_NODE_METADATA_DISPATCH_HPP #include #include namespace __gnu_pbds { namespace detail { /** * @addtogroup traits Traits * @{ */ /// Trie metadata helper. template struct trie_metadata_helper; /// Specialization, false. template struct trie_metadata_helper { typedef typename Node_Update::metadata_type type; }; /// Specialization, true. template struct trie_metadata_helper { typedef null_type type; }; /// Trie node metadata dispatch. template class Node_Update, typename _Alloc> struct trie_node_metadata_dispatch { private: typedef dumnode_const_iterator __it_type; typedef Node_Update<__it_type, __it_type, Cmp_Fn, _Alloc> __node_u; typedef null_node_update<__it_type, __it_type, Cmp_Fn, _Alloc> __nnode_u; enum { null_update = is_same<__node_u, __nnode_u>::value }; public: typedef typename trie_metadata_helper<__node_u, null_update>::type type; }; //@} } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_TRIE_NODE_METADATA_DISPATCH_HPP PK!T+f]]78/ext/pb_ds/detail/trie_policy/order_statistics_imp.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file trie_policy/order_statistics_imp.hpp * Contains forward declarations for order_statistics_key */ PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: find_by_order(size_type order) { if (empty()) return end(); ++order; node_iterator nd_it = node_begin(); while (true) { if (order > nd_it.get_metadata()) return ++base_type::rightmost_it(nd_it); const size_type num_children = nd_it.num_children(); if (num_children == 0) return *nd_it; for (size_type i = 0; i < num_children; ++i) { node_iterator child_nd_it = nd_it.get_child(i); if (order <= child_nd_it.get_metadata()) { i = num_children; nd_it = child_nd_it; } else order -= child_nd_it.get_metadata(); } } } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: find_by_order(size_type order) const { return const_cast(this)->find_by_order(order); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: order_of_key(key_const_reference r_key) const { const _ATraits& r_traits = const_cast(this)->get_access_traits(); return order_of_prefix(r_traits.begin(r_key), r_traits.end(r_key)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: order_of_prefix(typename access_traits::const_iterator b, typename access_traits::const_iterator e) const { if (empty()) return 0; const _ATraits& r_traits = const_cast(this)->get_access_traits(); node_const_iterator nd_it = node_begin(); node_const_iterator end_nd_it = node_end(); size_type ord = 0; while (true) { const size_type num_children = nd_it.num_children(); if (num_children == 0) { key_const_reference r_key = base_type::extract_key(*(*nd_it)); typename access_traits::const_iterator key_b = r_traits.begin(r_key); typename access_traits::const_iterator key_e = r_traits.end(r_key); return (base_type::less(key_b, key_e, b, e, r_traits)) ? ord + 1 : ord; } node_const_iterator next_nd_it = end_nd_it; size_type i = num_children - 1; do { node_const_iterator child_nd_it = nd_it.get_child(i); if (next_nd_it != end_nd_it) ord += child_nd_it.get_metadata(); else if (!base_type::less(b, e, child_nd_it.valid_prefix().first, child_nd_it.valid_prefix().second, r_traits)) next_nd_it = child_nd_it; } while (i-- > 0); if (next_nd_it == end_nd_it) return ord; nd_it = next_nd_it; } } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: operator()(node_iterator nd_it, node_const_iterator /*end_nd_it*/) const { const size_type num_children = nd_it.num_children(); size_type children_rank = 0; for (size_type i = 0; i < num_children; ++i) children_rank += nd_it.get_child(i).get_metadata(); const size_type res = (num_children == 0) ? 1 : children_rank; const_cast(nd_it.get_metadata()) = res; } PK! {ɟ@8/ext/pb_ds/detail/trie_policy/prefix_search_node_update_imp.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file trie_policy/prefix_search_node_update_imp.hpp * Contains an implementation of prefix_search_node_update. */ PB_DS_CLASS_T_DEC std::pair< typename PB_DS_CLASS_C_DEC::const_iterator, typename PB_DS_CLASS_C_DEC::const_iterator> PB_DS_CLASS_C_DEC:: prefix_range(key_const_reference r_key) const { const access_traits& r_traits = get_access_traits(); return (prefix_range(r_traits.begin(r_key), r_traits.end(r_key))); } PB_DS_CLASS_T_DEC std::pair< typename PB_DS_CLASS_C_DEC::iterator, typename PB_DS_CLASS_C_DEC::iterator> PB_DS_CLASS_C_DEC:: prefix_range(key_const_reference r_key) { return (prefix_range(get_access_traits().begin(r_key), get_access_traits().end(r_key))); } PB_DS_CLASS_T_DEC std::pair< typename PB_DS_CLASS_C_DEC::const_iterator, typename PB_DS_CLASS_C_DEC::const_iterator> PB_DS_CLASS_C_DEC:: prefix_range(typename access_traits::const_iterator b, typename access_traits::const_iterator e) const { const std::pair non_const_ret = const_cast(this)->prefix_range(b, e); return (std::make_pair(const_iterator(non_const_ret.first), const_iterator(non_const_ret.second))); } PB_DS_CLASS_T_DEC std::pair< typename PB_DS_CLASS_C_DEC::iterator, typename PB_DS_CLASS_C_DEC::iterator> PB_DS_CLASS_C_DEC:: prefix_range(typename access_traits::const_iterator b, typename access_traits::const_iterator e) { Node_Itr nd_it = node_begin(); Node_Itr end_nd_it = node_end(); const access_traits& r_traits = get_access_traits(); const size_type given_range_length = std::distance(b, e); while (true) { if (nd_it == end_nd_it) return (std::make_pair(end(), end())); const size_type common_range_length = base_type::common_prefix_len(nd_it, b, e, r_traits); if (common_range_length >= given_range_length) { iterator ret_b = this->leftmost_it(nd_it); iterator ret_e = this->rightmost_it(nd_it); return (std::make_pair(ret_b, ++ret_e)); } nd_it = next_child(nd_it, b, e, end_nd_it, r_traits); } } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::node_iterator PB_DS_CLASS_C_DEC:: next_child(node_iterator nd_it, typename access_traits::const_iterator b, typename access_traits::const_iterator e, node_iterator end_nd_it, const access_traits& r_traits) { const size_type num_children = nd_it.num_children(); node_iterator ret = end_nd_it; size_type max_length = 0; for (size_type i = 0; i < num_children; ++i) { node_iterator pot = nd_it.get_child(i); const size_type common_range_length = base_type::common_prefix_len(pot, b, e, r_traits); if (common_range_length > max_length) { ret = pot; max_length = common_range_length; } } return (ret); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: operator()(node_iterator /*nd_it*/, node_const_iterator /*end_nd_it*/) const { } PK!Ja <8/ext/pb_ds/detail/trie_policy/sample_trie_access_traits.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file trie_policy/sample_trie_access_traits.hpp * Contains a sample probe policy. */ #ifndef PB_DS_SAMPLE_TRIE_E_ACCESS_TRAITS_HPP #define PB_DS_SAMPLE_TRIE_E_ACCESS_TRAITS_HPP namespace __gnu_pbds { /// A sample trie element access traits. struct sample_trie_access_traits { typedef std::size_t size_type; typedef std::string key_type; typedef typename _Alloc::template rebind __rebind_k; typedef typename __rebind_k::other::const_reference key_const_reference; typedef std::string::const_iterator const_iterator; /// Element type. typedef char e_type; enum { max_size = 4 }; /// Returns a const_iterator to the first element of r_key. inline static const_iterator begin(key_const_reference); /// Returns a const_iterator to the after-last element of r_key. inline static const_iterator end(key_const_reference); /// Maps an element to a position. inline static size_type e_pos(e_type); }; } #endif // #ifndef PB_DS_SAMPLE_TRIE_E_ACCESS_TRAITS_HPP PK!, , :8/ext/pb_ds/detail/trie_policy/sample_trie_node_update.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file trie_policy/sample_trie_node_update.hpp * Contains a samle node update functor. */ #ifndef PB_DS_SAMPLE_TRIE_NODE_UPDATOR_HPP #define PB_DS_SAMPLE_TRIE_NODE_UPDATOR_HPP namespace __gnu_pbds { /// A sample node updator. template class sample_trie_node_update { public: typedef std::size_t metadata_type; protected: /// Default constructor. sample_trie_node_update(); /// Updates the rank of a node through a node_iterator node_it; /// end_nd_it is the end node iterator. inline void operator()(node_iterator, node_const_iterator) const; }; } #endif // #ifndef PB_DS_SAMPLE_TRIE_NODE_UPDATOR_HPP PK!538/ext/pb_ds/detail/trie_policy/trie_policy_base.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file trie_policy/trie_policy_base.hpp * Contains an implementation of trie_policy_base. */ #ifndef PB_DS_TRIE_POLICY_BASE_HPP #define PB_DS_TRIE_POLICY_BASE_HPP #include namespace __gnu_pbds { namespace detail { /// Base class for trie policies. template class trie_policy_base : public branch_policy { typedef branch_policy base_type; public: typedef _ATraits access_traits; typedef _Alloc allocator_type; typedef typename allocator_type::size_type size_type; typedef null_type metadata_type; typedef Node_CItr node_const_iterator; typedef Node_Itr node_iterator; typedef typename node_const_iterator::value_type const_iterator; typedef typename node_iterator::value_type iterator; typedef typename base_type::key_type key_type; typedef typename base_type::key_const_reference key_const_reference; protected: virtual const_iterator end() const = 0; virtual iterator end() = 0; virtual node_const_iterator node_begin() const = 0; virtual node_iterator node_begin() = 0; virtual node_const_iterator node_end() const = 0; virtual node_iterator node_end() = 0; virtual const access_traits& get_access_traits() const = 0; private: typedef typename access_traits::const_iterator e_const_iterator; typedef std::pair prefix_range_t; protected: static size_type common_prefix_len(node_iterator, e_const_iterator, e_const_iterator, const access_traits&); static iterator leftmost_it(node_iterator); static iterator rightmost_it(node_iterator); static bool less(e_const_iterator, e_const_iterator, e_const_iterator, e_const_iterator, const access_traits&); }; #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ trie_policy_base PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: common_prefix_len(node_iterator nd_it, e_const_iterator b_r, e_const_iterator e_r, const access_traits& r_traits) { prefix_range_t pref_range = nd_it.valid_prefix(); e_const_iterator b_l = pref_range.first; e_const_iterator e_l = pref_range.second; const size_type range_length_l = std::distance(b_l, e_l); const size_type range_length_r = std::distance(b_r, e_r); if (range_length_r < range_length_l) { std::swap(b_l, b_r); std::swap(e_l, e_r); } size_type ret = 0; while (b_l != e_l) { if (r_traits.e_pos(*b_l) != r_traits.e_pos(*b_r)) return ret; ++ret; ++b_l; ++b_r; } return ret; } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: leftmost_it(node_iterator nd_it) { if (nd_it.num_children() == 0) return *nd_it; return leftmost_it(nd_it.get_child(0)); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: rightmost_it(node_iterator nd_it) { const size_type num_children = nd_it.num_children(); if (num_children == 0) return *nd_it; return rightmost_it(nd_it.get_child(num_children - 1)); } PB_DS_CLASS_T_DEC bool PB_DS_CLASS_C_DEC:: less(e_const_iterator b_l, e_const_iterator e_l, e_const_iterator b_r, e_const_iterator e_r, const access_traits& r_traits) { while (b_l != e_l) { if (b_r == e_r) return false; size_type l_pos = r_traits.e_pos(*b_l); size_type r_pos = r_traits.e_pos(*b_r); if (l_pos != r_pos) return (l_pos < r_pos); ++b_l; ++b_r; } return b_r != e_r; } #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_TRIE_POLICY_BASE_HPP PK!96 @8/ext/pb_ds/detail/trie_policy/trie_string_access_traits_imp.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file trie_policy/trie_string_access_traits_imp.hpp * Contains a policy for extracting character positions from * a string for a vector-based PATRICIA tree */ PB_DS_CLASS_T_DEC detail::integral_constant PB_DS_CLASS_C_DEC::s_rev_ind; PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: e_pos(e_type e) { return (static_cast(e - min_e_val)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: begin(key_const_reference r_key) { return (begin_imp(r_key, s_rev_ind)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: end(key_const_reference r_key) { return (end_imp(r_key, s_rev_ind)); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: begin_imp(key_const_reference r_key, detail::false_type) { return (r_key.begin()); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: begin_imp(key_const_reference r_key, detail::true_type) { return (r_key.rbegin()); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: end_imp(key_const_reference r_key, detail::false_type) { return (r_key.end()); } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: end_imp(key_const_reference r_key, detail::true_type) { return (r_key.rend()); } PK!R  88/ext/pb_ds/detail/unordered_iterator/const_iterator.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file unordered_iterator/const_iterator.hpp * Contains an iterator class used for const ranging over the elements of the * table. */ /// Const range-type iterator. class const_iterator_ : public point_const_iterator_ { public: /// Category. typedef std::forward_iterator_tag iterator_category; /// Difference type. typedef typename _Alloc::difference_type difference_type; /// Iterator's value type. typedef value_type_ value_type; /// Iterator's pointer type. typedef pointer_ pointer; /// Iterator's const pointer type. typedef const_pointer_ const_pointer; /// Iterator's reference type. typedef reference_ reference; /// Iterator's const reference type. typedef const_reference_ const_reference; /// Default constructor. const_iterator_() : m_p_tbl(0) { } /// Increments. const_iterator_& operator++() { m_p_tbl->inc_it_state(base_type::m_p_value, m_pos); return *this; } /// Increments. const_iterator_ operator++(int) { const_iterator_ ret =* this; m_p_tbl->inc_it_state(base_type::m_p_value, m_pos); return ret; } protected: typedef point_const_iterator_ base_type; /** * Constructor used by the table to initiate the generalized * pointer and position (e.g., this is called from within a find() * of a table. * */ const_iterator_(const_pointer_ p_value, PB_DS_GEN_POS pos, const PB_DS_CLASS_C_DEC* p_tbl) : point_const_iterator_(p_value), m_p_tbl(p_tbl), m_pos(pos) { } /** * Pointer to the table object which created the iterator (used for * incrementing its position. * */ const PB_DS_CLASS_C_DEC* m_p_tbl; PB_DS_GEN_POS m_pos; friend class PB_DS_CLASS_C_DEC; }; PK!|28/ext/pb_ds/detail/unordered_iterator/iterator.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file iterator.hpp * Contains an iterator_ class used for ranging over the elements of the * table. */ /// Range-type iterator. class iterator_ : public const_iterator_ { public: /// Category. typedef std::forward_iterator_tag iterator_category; /// Difference type. typedef typename _Alloc::difference_type difference_type; /// Iterator's value type. typedef value_type_ value_type; /// Iterator's pointer type. typedef pointer_ pointer; /// Iterator's const pointer type. typedef const_pointer_ const_pointer; /// Iterator's reference type. typedef reference_ reference; /// Iterator's const reference type. typedef const_reference_ const_reference; /// Default constructor. inline iterator_() : const_iterator_(0, PB_DS_GEN_POS(), 0) { } /// Conversion to a point-type iterator. inline operator point_iterator_() { return point_iterator_(const_cast(const_iterator_::m_p_value)); } /// Conversion to a point-type iterator. inline operator const point_iterator_() const { return point_iterator_(const_cast(const_iterator_::m_p_value)); } /// Access. pointer operator->() const { _GLIBCXX_DEBUG_ASSERT(base_type::m_p_value != 0); return (const_cast(base_type::m_p_value)); } /// Access. reference operator*() const { _GLIBCXX_DEBUG_ASSERT(base_type::m_p_value != 0); return (const_cast(*base_type::m_p_value)); } /// Increments. iterator_& operator++() { base_type::m_p_tbl->inc_it_state(base_type::m_p_value, base_type::m_pos); return *this; } /// Increments. iterator_ operator++(int) { iterator_ ret =* this; base_type::m_p_tbl->inc_it_state(base_type::m_p_value, base_type::m_pos); return ret; } protected: typedef const_iterator_ base_type; /** * Constructor used by the table to initiate the generalized * pointer and position (e.g., this is called from within a find() * of a table. * */ inline iterator_(pointer p_value, PB_DS_GEN_POS pos, PB_DS_CLASS_C_DEC* p_tbl) : const_iterator_(p_value, pos, p_tbl) { } friend class PB_DS_CLASS_C_DEC; }; PK!#a>8/ext/pb_ds/detail/unordered_iterator/point_const_iterator.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file unordered_iterator/point_const_iterator.hpp * Contains an iterator class returned by the tables' const find and insert * methods. */ class point_iterator_; /// Const point-type iterator. class point_const_iterator_ { public: /// Category. typedef trivial_iterator_tag iterator_category; /// Difference type. typedef trivial_iterator_difference_type difference_type; /// Iterator's value type. typedef value_type_ value_type; /// Iterator's pointer type. typedef pointer_ pointer; /// Iterator's const pointer type. typedef const_pointer_ const_pointer; /// Iterator's reference type. typedef reference_ reference; /// Iterator's const reference type. typedef const_reference_ const_reference; inline point_const_iterator_(const_pointer p_value) : m_p_value(p_value) { } /// Default constructor. inline point_const_iterator_() : m_p_value(0) { } /// Copy constructor. inline point_const_iterator_(const point_const_iterator_& other) : m_p_value(other.m_p_value) { } /// Copy constructor. inline point_const_iterator_(const point_iterator_& other) : m_p_value(other.m_p_value) { } /// Access. const_pointer operator->() const { _GLIBCXX_DEBUG_ASSERT(m_p_value != 0); return m_p_value; } /// Access. const_reference operator*() const { _GLIBCXX_DEBUG_ASSERT(m_p_value != 0); return *m_p_value; } /// Compares content to a different iterator object. bool operator==(const point_iterator_& other) const { return m_p_value == other.m_p_value; } /// Compares content to a different iterator object. bool operator==(const point_const_iterator_& other) const { return m_p_value == other.m_p_value; } /// Compares content (negatively) to a different iterator object. bool operator!=(const point_iterator_& other) const { return m_p_value != other.m_p_value; } /// Compares content (negatively) to a different iterator object. bool operator!=(const point_const_iterator_& other) const { return m_p_value != other.m_p_value; } protected: const_pointer m_p_value; friend class point_iterator_; friend class PB_DS_CLASS_C_DEC; }; PK!0z 88/ext/pb_ds/detail/unordered_iterator/point_iterator.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file point_iterator.hpp * Contains an iterator class returned by the tables' find and insert * methods. */ /// Find type iterator. class point_iterator_ { public: /// Category. typedef trivial_iterator_tag iterator_category; /// Difference type. typedef trivial_iterator_difference_type difference_type; /// Iterator's value type. typedef value_type_ value_type; /// Iterator's pointer type. typedef pointer_ pointer; /// Iterator's const pointer type. typedef const_pointer_ const_pointer; /// Iterator's reference type. typedef reference_ reference; /// Iterator's const reference type. typedef const_reference_ const_reference; /// Default constructor. inline point_iterator_() : m_p_value(0) { } /// Copy constructor. inline point_iterator_(const point_iterator_& other) : m_p_value(other.m_p_value) { } /// Access. pointer operator->() const { _GLIBCXX_DEBUG_ASSERT(m_p_value != 0); return (m_p_value); } /// Access. reference operator*() const { _GLIBCXX_DEBUG_ASSERT(m_p_value != 0); return (*m_p_value); } /// Compares content to a different iterator object. bool operator==(const point_iterator_& other) const { return m_p_value == other.m_p_value; } /// Compares content to a different iterator object. bool operator==(const point_const_iterator_& other) const { return m_p_value == other.m_p_value; } /// Compares content to a different iterator object. bool operator!=(const point_iterator_& other) const { return m_p_value != other.m_p_value; } /// Compares content (negatively) to a different iterator object. bool operator!=(const point_const_iterator_& other) const { return m_p_value != other.m_p_value; } inline point_iterator_(pointer p_value) : m_p_value(p_value) { } protected: friend class point_const_iterator_; friend class PB_DS_CLASS_C_DEC; protected: pointer m_p_value; }; PK!; #8/ext/pb_ds/detail/cond_dealtor.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file detail/cond_dealtor.hpp * Contains a conditional deallocator. */ #ifndef PB_DS_COND_DEALTOR_HPP #define PB_DS_COND_DEALTOR_HPP namespace __gnu_pbds { namespace detail { /// Conditional deallocate constructor argument. template class cond_dealtor { typedef typename _Alloc::template rebind __rebind_e; public: typedef typename __rebind_e::other entry_allocator; typedef typename entry_allocator::pointer entry_pointer; cond_dealtor(entry_pointer p_e) : m_p_e(p_e), m_no_action_destructor(false) { } ~cond_dealtor() { if (m_no_action_destructor) return; s_alloc.deallocate(m_p_e, 1); } void set_no_action() { m_no_action_destructor = true; } private: entry_pointer m_p_e; bool m_no_action_destructor; static entry_allocator s_alloc; }; template typename cond_dealtor::entry_allocator cond_dealtor::s_alloc; } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_COND_DEALTOR_HPP PK!~@3@3.8/ext/pb_ds/detail/container_base_dispatch.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file container_base_dispatch.hpp * Contains associative container dispatching. */ #ifndef PB_DS_ASSOC_CNTNR_BASE_DS_DISPATCHER_HPP #define PB_DS_ASSOC_CNTNR_BASE_DS_DISPATCHER_HPP #include #define PB_DS_ASSERT_VALID(X) \ _GLIBCXX_DEBUG_ONLY(X.assert_valid(__FILE__, __LINE__);) #define PB_DS_DEBUG_VERIFY(_Cond) \ _GLIBCXX_DEBUG_VERIFY_AT(_Cond, \ _M_message(#_Cond" assertion from %1;:%2;") \ ._M_string(__FILE__)._M_integer(__LINE__) \ ,__file,__line) #define PB_DS_CHECK_KEY_EXISTS(_Key) \ _GLIBCXX_DEBUG_ONLY(debug_base::check_key_exists(_Key, __FILE__, __LINE__);) #define PB_DS_CHECK_KEY_DOES_NOT_EXIST(_Key) \ _GLIBCXX_DEBUG_ONLY(debug_base::check_key_does_not_exist(_Key, \ __FILE__, __LINE__);) #define PB_DS_DATA_TRUE_INDICATOR #define PB_DS_V2F(X) (X).first #define PB_DS_V2S(X) (X).second #define PB_DS_EP2VP(X)& ((X)->m_value) #include #include #include #include #include #include #include #include #undef PB_DS_DATA_TRUE_INDICATOR #undef PB_DS_V2F #undef PB_DS_V2S #undef PB_DS_EP2VP #define PB_DS_DATA_FALSE_INDICATOR #define PB_DS_V2F(X) (X) #define PB_DS_V2S(X) Mapped_Data() #define PB_DS_EP2VP(X)& ((X)->m_value.first) #include #include #include #include #include #include #include #include #undef PB_DS_DATA_FALSE_INDICATOR #undef PB_DS_V2F #undef PB_DS_V2S #undef PB_DS_EP2VP #undef PB_DS_CHECK_KEY_DOES_NOT_EXIST #undef PB_DS_CHECK_KEY_EXISTS #undef PB_DS_DEBUG_VERIFY #undef PB_DS_ASSERT_VALID namespace __gnu_pbds { namespace detail { /// Specialization for list-update map. template struct container_base_dispatch { private: typedef __gnu_cxx::typelist::at_index at0; typedef typename at0::type at0t; typedef __gnu_cxx::typelist::at_index at1; typedef typename at1::type at1t; public: /// Dispatched type. typedef lu_map type; }; /// Specialization for list-update set. template struct container_base_dispatch { private: typedef __gnu_cxx::typelist::at_index at0; typedef typename at0::type at0t; typedef __gnu_cxx::typelist::at_index at1; typedef typename at1::type at1t; public: /// Dispatched type. typedef lu_set type; }; /// Specialization for PATRICIA trie map. template struct container_base_dispatch { private: typedef __gnu_cxx::typelist::at_index at1; typedef typename at1::type at1t; public: typedef pat_trie_map type; }; /// Specialization for PATRICIA trie set. template struct container_base_dispatch { private: typedef __gnu_cxx::typelist::at_index at1; typedef typename at1::type at1t; public: /// Dispatched type. typedef pat_trie_set type; }; /// Specialization for R-B tree map. template struct container_base_dispatch { private: typedef __gnu_cxx::typelist::at_index at0; typedef typename at0::type at0t; typedef __gnu_cxx::typelist::at_index at1; typedef typename at1::type at1t; public: /// Dispatched type. typedef rb_tree_map type; }; /// Specialization for R-B tree set. template struct container_base_dispatch { private: typedef __gnu_cxx::typelist::at_index at0; typedef typename at0::type at0t; typedef __gnu_cxx::typelist::at_index at1; typedef typename at1::type at1t; public: typedef rb_tree_set type; }; /// Specialization splay tree map. template struct container_base_dispatch { private: typedef __gnu_cxx::typelist::at_index at0; typedef typename at0::type at0t; typedef __gnu_cxx::typelist::at_index at1; typedef typename at1::type at1t; public: /// Dispatched type. typedef splay_tree_map type; }; /// Specialization splay tree set. template struct container_base_dispatch { private: typedef __gnu_cxx::typelist::at_index at0; typedef typename at0::type at0t; typedef __gnu_cxx::typelist::at_index at1; typedef typename at1::type at1t; public: /// Dispatched type. typedef splay_tree_set type; }; /// Specialization ordered-vector tree map. template struct container_base_dispatch { private: typedef __gnu_cxx::typelist::at_index at0; typedef typename at0::type at0t; typedef __gnu_cxx::typelist::at_index at1; typedef typename at1::type at1t; public: /// Dispatched type. typedef ov_tree_map type; }; /// Specialization ordered-vector tree set. template struct container_base_dispatch { private: typedef __gnu_cxx::typelist::at_index at0; typedef typename at0::type at0t; typedef __gnu_cxx::typelist::at_index at1; typedef typename at1::type at1t; public: /// Dispatched type. typedef ov_tree_set type; }; /// Specialization colision-chaining hash map. template struct container_base_dispatch { private: typedef __gnu_cxx::typelist::at_index at0; typedef typename at0::type at0t; typedef __gnu_cxx::typelist::at_index at1; typedef typename at1::type at1t; typedef __gnu_cxx::typelist::at_index at2; typedef typename at2::type at2t; typedef __gnu_cxx::typelist::at_index at3; typedef typename at3::type at3t; typedef __gnu_cxx::typelist::at_index at4; typedef typename at4::type at4t; public: /// Dispatched type. typedef cc_ht_map type; }; /// Specialization colision-chaining hash set. template struct container_base_dispatch { private: typedef __gnu_cxx::typelist::at_index at0; typedef typename at0::type at0t; typedef __gnu_cxx::typelist::at_index at1; typedef typename at1::type at1t; typedef __gnu_cxx::typelist::at_index at2; typedef typename at2::type at2t; typedef __gnu_cxx::typelist::at_index at3; typedef typename at3::type at3t; typedef __gnu_cxx::typelist::at_index at4; typedef typename at4::type at4t; public: /// Dispatched type. typedef cc_ht_set type; }; /// Specialization general-probe hash map. template struct container_base_dispatch { private: typedef __gnu_cxx::typelist::at_index at0; typedef typename at0::type at0t; typedef __gnu_cxx::typelist::at_index at1; typedef typename at1::type at1t; typedef __gnu_cxx::typelist::at_index at2; typedef typename at2::type at2t; typedef __gnu_cxx::typelist::at_index at3; typedef typename at3::type at3t; typedef __gnu_cxx::typelist::at_index at4; typedef typename at4::type at4t; typedef __gnu_cxx::typelist::at_index at5; typedef typename at5::type at5t; public: /// Dispatched type. typedef gp_ht_map type; }; /// Specialization general-probe hash set. template struct container_base_dispatch { private: typedef __gnu_cxx::typelist::at_index at0; typedef typename at0::type at0t; typedef __gnu_cxx::typelist::at_index at1; typedef typename at1::type at1t; typedef __gnu_cxx::typelist::at_index at2; typedef typename at2::type at2t; typedef __gnu_cxx::typelist::at_index at3; typedef typename at3::type at3t; typedef __gnu_cxx::typelist::at_index at4; typedef typename at4::type at4t; typedef __gnu_cxx::typelist::at_index at5; typedef typename at5::type at5t; public: /// Dispatched type. typedef gp_ht_set type; }; } // namespace detail } // namespace __gnu_pbds #endif PK!%!!%8/ext/pb_ds/detail/debug_map_base.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file detail/debug_map_base.hpp * Contains a debug-mode base for all maps. */ #ifndef PB_DS_DEBUG_MAP_BASE_HPP #define PB_DS_DEBUG_MAP_BASE_HPP #ifdef _GLIBCXX_DEBUG #include #include #include #include #include #include namespace __gnu_pbds { namespace detail { // Need std::pair ostream extractor. template inline std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __out, const std::pair<_Tp1, _Tp2>& p) { return (__out << '(' << p.first << ',' << p.second << ')'); } #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ debug_map_base /// Debug base class. template class debug_map_base { private: typedef Const_Key_Reference key_const_reference; typedef std::_GLIBCXX_STD_C::list key_repository; typedef typename key_repository::size_type size_type; typedef typename key_repository::iterator iterator; typedef typename key_repository::const_iterator const_iterator; protected: debug_map_base(); debug_map_base(const PB_DS_CLASS_C_DEC&); ~debug_map_base(); inline void insert_new(key_const_reference); inline void erase_existing(key_const_reference); void clear(); inline void check_key_exists(key_const_reference, const char*, int) const; inline void check_key_does_not_exist(key_const_reference, const char*, int) const; inline void check_size(size_type, const char*, int) const; void swap(PB_DS_CLASS_C_DEC&); template void split(key_const_reference, Cmp_Fn, PB_DS_CLASS_C_DEC&); void join(PB_DS_CLASS_C_DEC&, bool with_cleanup = true); private: void assert_valid(const char*, int) const; const_iterator find(key_const_reference) const; iterator find(key_const_reference); key_repository m_keys; Eq_Fn m_eq; }; PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: debug_map_base() { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: debug_map_base(const PB_DS_CLASS_C_DEC& other) : m_keys(other.m_keys), m_eq(other.m_eq) { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~debug_map_base() { PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: insert_new(key_const_reference r_key) { PB_DS_ASSERT_VALID((*this)) if (find(r_key) != m_keys.end()) { std::cerr << "insert_new key already present " << r_key << std::endl; std::abort(); } __try { m_keys.push_back(r_key); } __catch(...) { std::cerr << "insert_new " << r_key << std::endl; std::abort(); } PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: erase_existing(key_const_reference r_key) { PB_DS_ASSERT_VALID((*this)) iterator it = find(r_key); if (it == m_keys.end()) { std::cerr << "erase_existing" << r_key << std::endl; std::abort(); } m_keys.erase(it); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: clear() { PB_DS_ASSERT_VALID((*this)) m_keys.clear(); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: check_key_exists(key_const_reference r_key, const char* __file, int __line) const { assert_valid(__file, __line); if (find(r_key) == m_keys.end()) { std::cerr << __file << ':' << __line << ": check_key_exists " << r_key << std::endl; std::abort(); } } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: check_key_does_not_exist(key_const_reference r_key, const char* __file, int __line) const { assert_valid(__file, __line); if (find(r_key) != m_keys.end()) { using std::cerr; using std::endl; cerr << __file << ':' << __line << ": check_key_does_not_exist " << r_key << endl; std::abort(); } } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: check_size(size_type size, const char* __file, int __line) const { assert_valid(__file, __line); const size_type keys_size = m_keys.size(); if (size != keys_size) { std::cerr << __file << ':' << __line << ": check_size " << size << " != " << keys_size << std::endl; std::abort(); } } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { PB_DS_ASSERT_VALID((*this)) m_keys.swap(other.m_keys); std::swap(m_eq, other.m_eq); PB_DS_ASSERT_VALID((*this)) } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::const_iterator PB_DS_CLASS_C_DEC:: find(key_const_reference r_key) const { PB_DS_ASSERT_VALID((*this)) typedef const_iterator iterator_type; for (iterator_type it = m_keys.begin(); it != m_keys.end(); ++it) if (m_eq(*it, r_key)) return it; return m_keys.end(); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::iterator PB_DS_CLASS_C_DEC:: find(key_const_reference r_key) { PB_DS_ASSERT_VALID((*this)) iterator it = m_keys.begin(); while (it != m_keys.end()) { if (m_eq(*it, r_key)) return it; ++it; } return it; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: assert_valid(const char* __file, int __line) const { const_iterator prime_it = m_keys.begin(); while (prime_it != m_keys.end()) { const_iterator sec_it = prime_it; ++sec_it; while (sec_it != m_keys.end()) { PB_DS_DEBUG_VERIFY(!m_eq(*sec_it, *prime_it)); PB_DS_DEBUG_VERIFY(!m_eq(*prime_it, *sec_it)); ++sec_it; } ++prime_it; } } PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: split(key_const_reference r_key, Cmp_Fn cmp_fn, PB_DS_CLASS_C_DEC& other) { other.clear(); iterator it = m_keys.begin(); while (it != m_keys.end()) if (cmp_fn(r_key, *it)) { other.insert_new(*it); it = m_keys.erase(it); } else ++it; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: join(PB_DS_CLASS_C_DEC& other, bool with_cleanup) { iterator it = other.m_keys.begin(); while (it != other.m_keys.end()) { insert_new(*it); if (with_cleanup) it = other.m_keys.erase(it); else ++it; } _GLIBCXX_DEBUG_ASSERT(!with_cleanup || other.m_keys.empty()); } #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC } // namespace detail } // namespace __gnu_pbds #endif #endif PK!Uc,,38/ext/pb_ds/detail/priority_queue_base_dispatch.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file detail/priority_queue_base_dispatch.hpp * Contains an pqiative container dispatching base. */ #ifndef PB_DS_PRIORITY_QUEUE_BASE_DS_DISPATCHER_HPP #define PB_DS_PRIORITY_QUEUE_BASE_DS_DISPATCHER_HPP #define PB_DS_ASSERT_VALID(X) \ _GLIBCXX_DEBUG_ONLY(X.assert_valid(__FILE__, __LINE__);) #define PB_DS_DEBUG_VERIFY(_Cond) \ _GLIBCXX_DEBUG_VERIFY_AT(_Cond, \ _M_message(#_Cond" assertion from %1;:%2;") \ ._M_string(__FILE__)._M_integer(__LINE__) \ ,__file,__line) #include #include #include #include #include #undef PB_DS_DEBUG_VERIFY #undef PB_DS_ASSERT_VALID namespace __gnu_pbds { namespace detail { /// Specialization for pairing_heap. template struct container_base_dispatch<_VTp, Cmp_Fn, _Alloc, pairing_heap_tag, null_type> { /// Dispatched type. typedef pairing_heap<_VTp, Cmp_Fn, _Alloc> type; }; /// Specialization for binomial_heap. template struct container_base_dispatch<_VTp, Cmp_Fn, _Alloc, binomial_heap_tag, null_type> { /// Dispatched type. typedef binomial_heap<_VTp, Cmp_Fn, _Alloc> type; }; /// Specialization for rc_binary_heap. template struct container_base_dispatch<_VTp, Cmp_Fn, _Alloc, rc_binomial_heap_tag, null_type> { /// Dispatched type. typedef rc_binomial_heap<_VTp, Cmp_Fn, _Alloc> type; }; /// Specialization for binary_heap. template struct container_base_dispatch<_VTp, Cmp_Fn, _Alloc, binary_heap_tag, null_type> { /// Dispatched type. typedef binary_heap<_VTp, Cmp_Fn, _Alloc> type; }; /// Specialization for thin_heap. template struct container_base_dispatch<_VTp, Cmp_Fn, _Alloc, thin_heap_tag, null_type> { /// Dispatched type. typedef thin_heap<_VTp, Cmp_Fn, _Alloc> type; }; //@} group pbds } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_PRIORITY_QUEUE_BASE_DS_DISPATCHER_HPP PK!b1(8/ext/pb_ds/detail/standard_policies.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file detail/standard_policies.hpp * Contains standard policies for containers. */ #ifndef PB_DS_STANDARD_POLICIES_HPP #define PB_DS_STANDARD_POLICIES_HPP #include #include #include #include #include #include #include #include namespace __gnu_pbds { namespace detail { /// Primary template, default_hash_fn. template struct default_hash_fn { /// Dispatched type. typedef std::tr1::hash type; }; /// Primary template, default_eq_fn. template struct default_eq_fn { /// Dispatched type. typedef std::equal_to type; }; /// Enumeration for default behavior of stored hash data. enum { default_store_hash = false }; /// Primary template, default_comb_hash_fn. struct default_comb_hash_fn { /// Dispatched type. typedef direct_mask_range_hashing<> type; }; /// Primary template, default_resize_policy. template struct default_resize_policy { private: typedef typename Comb_Hash_Fn::size_type size_type; typedef direct_mask_range_hashing default_fn; typedef is_same same_type; typedef hash_exponential_size_policy iftrue; typedef hash_prime_size_policy iffalse; typedef __conditional_type cond_type; typedef typename cond_type::__type size_policy_type; typedef hash_load_check_resize_trigger trigger; public: /// Dispatched type. typedef hash_standard_resize_policy type; }; /// Default update policy. struct default_update_policy { /// Dispatched type. typedef lu_move_to_front_policy<> type; }; /// Primary template, default_probe_fn. template struct default_probe_fn { private: typedef typename Comb_Probe_Fn::size_type size_type; typedef direct_mask_range_hashing default_fn; typedef is_same same_type; typedef linear_probe_fn iftrue; typedef quadratic_probe_fn iffalse; typedef __conditional_type cond_type; public: /// Dispatched type. typedef typename cond_type::__type type; }; /// Primary template, default_trie_access_traits. template struct default_trie_access_traits; #define __dtrie_alloc std::allocator #define __dtrie_string std::basic_string /// Partial specialization, default_trie_access_traits. template struct default_trie_access_traits<__dtrie_string> { private: typedef __dtrie_string string_type; public: /// Dispatched type. typedef trie_string_access_traits type; }; #undef __dtrie_alloc #undef __dtrie_string } // namespace detail } // namespace __gnu_pbds #endif // #ifndef PB_DS_STANDARD_POLICIES_HPP PK!{&8/ext/pb_ds/detail/tree_trace_base.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file detail/tree_trace_base.hpp * Contains tree-related policies. */ #ifndef PB_DS_TREE_TRACE_BASE_HPP #define PB_DS_TREE_TRACE_BASE_HPP #ifdef PB_DS_TREE_TRACE #include #include namespace __gnu_pbds { namespace detail { #ifdef PB_DS_TREE_TRACE #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ tree_trace_base #define PB_DS_TRACE_BASE \ branch_policy /// Tracing base class. template class tree_trace_base : private PB_DS_TRACE_BASE { public: void trace() const; private: typedef PB_DS_TRACE_BASE base_type; typedef Node_CItr node_const_iterator; typedef typename _Alloc::size_type size_type; void trace_node(node_const_iterator, size_type) const; virtual bool empty() const = 0; virtual node_const_iterator node_begin() const = 0; virtual node_const_iterator node_end() const = 0; static void print_node_pointer(Node_CItr, integral_constant); static void print_node_pointer(Node_CItr, integral_constant); template static void trace_it_metadata(Node_CItr, type_to_type); static void trace_it_metadata(Node_CItr, type_to_type); }; PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace() const { if (empty()) return; trace_node(node_begin(), 0); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace_node(node_const_iterator nd_it, size_type level) const { if (nd_it.get_r_child() != node_end()) trace_node(nd_it.get_r_child(), level + 1); for (size_type i = 0; i < level; ++i) std::cerr << ' '; print_node_pointer(nd_it, integral_constant()); std::cerr << base_type::extract_key(*(*nd_it)); typedef type_to_type m_type_ind_t; trace_it_metadata(nd_it, m_type_ind_t()); std::cerr << std::endl; if (nd_it.get_l_child() != node_end()) trace_node(nd_it.get_l_child(), level + 1); } PB_DS_CLASS_T_DEC template void PB_DS_CLASS_C_DEC:: trace_it_metadata(Node_CItr nd_it, type_to_type) { const unsigned long ul = static_cast(nd_it.get_metadata()); std::cerr << " (" << ul << ") "; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: trace_it_metadata(Node_CItr, type_to_type) { } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: print_node_pointer(Node_CItr nd_it, integral_constant) { std::cerr << nd_it.m_p_nd << " "; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: print_node_pointer(Node_CItr nd_it, integral_constant) { std::cerr << *nd_it << " "; } #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #undef PB_DS_TRACE_BASE #endif // #ifdef PB_DS_TREE_TRACE } // namespace detail } // namespace __gnu_pbds #endif // #ifdef PB_DS_TREE_TRACE #endif // #ifndef PB_DS_TREE_TRACE_BASE_HPP PK!%!!8/ext/pb_ds/detail/type_utils.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file detail/type_utils.hpp * Contains utilities for handnling types. All of these classes are based on * Modern C++ by Andrei Alxandrescu. */ #ifndef PB_DS_TYPE_UTILS_HPP #define PB_DS_TYPE_UTILS_HPP #include #include #include #include #include namespace __gnu_pbds { namespace detail { using std::tr1::is_same; using std::tr1::is_const; using std::tr1::is_pointer; using std::tr1::is_reference; using std::tr1::is_fundamental; using std::tr1::is_member_object_pointer; using std::tr1::is_member_pointer; using std::tr1::is_base_of; using std::tr1::remove_const; using std::tr1::remove_reference; // Need integral_const <-> integral_const, so // because of this use the following typedefs instead of importing // std::tr1's. using std::tr1::integral_constant; typedef std::tr1::integral_constant true_type; typedef std::tr1::integral_constant false_type; using __gnu_cxx::__conditional_type; using __gnu_cxx::__numeric_traits; template struct is_const_pointer { enum { value = is_const::value && is_pointer::value }; }; template struct is_const_reference { enum { value = is_const::value && is_reference::value }; }; template struct is_simple { enum { value = is_fundamental::type>::value || is_pointer::type>::value || is_member_pointer::value }; }; template class is_pair { private: template struct is_pair_imp { enum { value = 0 }; }; template struct is_pair_imp > { enum { value = 1 }; }; public: enum { value = is_pair_imp::value }; }; // Use C++11's static_assert if possible. #if __cplusplus >= 201103L #define PB_DS_STATIC_ASSERT(UNIQUE, E) static_assert(E, #UNIQUE) #else template struct __static_assert; template<> struct __static_assert { }; template struct __static_assert_dumclass { enum { v = 1 }; }; #define PB_DS_STATIC_ASSERT(UNIQUE, E) \ typedef __gnu_pbds::detail::__static_assert_dumclass)> UNIQUE##__static_assert_type #endif template struct type_to_type { typedef Type type; }; } // namespace detail } // namespace __gnu_pbds #endif PK!Vz*<''#8/ext/pb_ds/detail/types_traits.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file detail/types_traits.hpp * Contains a traits class of types used by containers. */ #ifndef PB_DS_TYPES_TRAITS_HPP #define PB_DS_TYPES_TRAITS_HPP #include #include #include #include #include namespace __gnu_pbds { namespace detail { /** * @addtogroup traits Traits * @{ */ /// Primary template. template struct no_throw_copies { static const bool __simple = is_simple::value && is_simple::value; typedef integral_constant indicator; }; /// Specialization. template struct no_throw_copies { typedef integral_constant::value> indicator; }; /// Stored value. template struct stored_value { typedef _Tv value_type; value_type m_value; }; /// Stored hash. template struct stored_hash { typedef _Th hash_type; hash_type m_hash; }; /// Primary template for representation of stored data. /// Two types of data can be stored: value and hash. template struct stored_data : public stored_value<_Tv>, public stored_hash<_Th> { }; /// Specialization for representation of stored data of just value type. template struct stored_data<_Tv, null_type> : public stored_value<_Tv> { }; /// Primary template. template struct type_base; /** * Specialization of type_base for the case where the hash value * is not stored alongside each value. */ template struct type_base { public: typedef typename _Alloc::size_type size_type; private: typedef typename _Alloc::template rebind __rebind_m; typedef typename __rebind_m::other __rebind_ma; typedef std::pair __value_type; typedef typename _Alloc::template rebind<__value_type> __rebind_v; typedef typename __rebind_v::other __rebind_va; public: typedef typename __rebind_ma::value_type mapped_type; typedef typename __rebind_ma::pointer mapped_pointer; typedef typename __rebind_ma::const_pointer mapped_const_pointer; typedef typename __rebind_ma::reference mapped_reference; typedef typename __rebind_ma::const_reference mapped_const_reference; typedef typename __rebind_va::value_type value_type; typedef typename __rebind_va::pointer pointer; typedef typename __rebind_va::const_pointer const_pointer; typedef typename __rebind_va::reference reference; typedef typename __rebind_va::const_reference const_reference; typedef stored_data stored_data_type; }; /** * Specialization of type_base for the case where the hash value * is stored alongside each value. */ template struct type_base { public: typedef typename _Alloc::size_type size_type; private: typedef typename _Alloc::template rebind __rebind_m; typedef typename __rebind_m::other __rebind_ma; typedef std::pair __value_type; typedef typename _Alloc::template rebind<__value_type> __rebind_v; typedef typename __rebind_v::other __rebind_va; public: typedef typename __rebind_ma::value_type mapped_type; typedef typename __rebind_ma::pointer mapped_pointer; typedef typename __rebind_ma::const_pointer mapped_const_pointer; typedef typename __rebind_ma::reference mapped_reference; typedef typename __rebind_ma::const_reference mapped_const_reference; typedef typename __rebind_va::value_type value_type; typedef typename __rebind_va::pointer pointer; typedef typename __rebind_va::const_pointer const_pointer; typedef typename __rebind_va::reference reference; typedef typename __rebind_va::const_reference const_reference; typedef stored_data stored_data_type; }; /** * Specialization of type_base for the case where the hash value * is not stored alongside each value. */ template struct type_base { public: typedef typename _Alloc::size_type size_type; typedef Key value_type; private: typedef typename _Alloc::template rebind __rebind_m; typedef typename __rebind_m::other __rebind_ma; typedef typename _Alloc::template rebind __rebind_v; typedef typename __rebind_v::other __rebind_va; public: typedef typename __rebind_ma::value_type mapped_type; typedef typename __rebind_ma::pointer mapped_pointer; typedef typename __rebind_ma::const_pointer mapped_const_pointer; typedef typename __rebind_ma::reference mapped_reference; typedef typename __rebind_ma::const_reference mapped_const_reference; typedef typename __rebind_va::pointer pointer; typedef typename __rebind_va::const_pointer const_pointer; typedef typename __rebind_va::reference reference; typedef typename __rebind_va::const_reference const_reference; typedef stored_data stored_data_type; static null_type s_null_type; }; template null_type type_base::s_null_type; /** * Specialization of type_base for the case where the hash value * is stored alongside each value. */ template struct type_base { public: typedef typename _Alloc::size_type size_type; typedef Key value_type; private: typedef typename _Alloc::template rebind __rebind_m; typedef typename __rebind_m::other __rebind_ma; typedef typename _Alloc::template rebind __rebind_v; typedef typename __rebind_v::other __rebind_va; public: typedef typename __rebind_ma::value_type mapped_type; typedef typename __rebind_ma::pointer mapped_pointer; typedef typename __rebind_ma::const_pointer mapped_const_pointer; typedef typename __rebind_ma::reference mapped_reference; typedef typename __rebind_ma::const_reference mapped_const_reference; typedef typename __rebind_va::pointer pointer; typedef typename __rebind_va::const_pointer const_pointer; typedef typename __rebind_va::reference reference; typedef typename __rebind_va::const_reference const_reference; typedef stored_data stored_data_type; static null_type s_null_type; }; template null_type type_base::s_null_type; /// Type base dispatch. template struct type_dispatch { typedef type_base type; }; /// Traits for abstract types. template struct types_traits : public type_dispatch::type { private: typedef no_throw_copies __nothrowcopy; typedef typename _Alloc::template rebind::other __rebind_a; public: typedef typename _Alloc::size_type size_type; typedef typename __rebind_a::value_type key_type; typedef typename __rebind_a::pointer key_pointer; typedef typename __rebind_a::const_pointer key_const_pointer; typedef typename __rebind_a::reference key_reference; typedef typename __rebind_a::const_reference key_const_reference; typedef std::pair comp_hash; typedef integral_constant store_extra; typedef typename __nothrowcopy::indicator no_throw_indicator; store_extra m_store_extra_indicator; no_throw_indicator m_no_throw_copies_indicator; }; //@} } // namespace detail } // namespace __gnu_pbds #endif PK!AƖuu8/ext/pb_ds/assoc_container.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file assoc_container.hpp * Contains associative containers. */ #ifndef PB_DS_ASSOC_CNTNR_HPP #define PB_DS_ASSOC_CNTNR_HPP #include #include #include #include #include #include namespace __gnu_pbds { /** * @defgroup containers-pbds Containers * @ingroup pbds * @{ */ /** * @defgroup hash-based Hash-Based * @ingroup containers-pbds * @{ */ #define PB_DS_HASH_BASE \ detail::container_base_dispatch >::type, Policy_Tl>::type>::type /** * @defgroup hash-detail Base and Policy Classes * @ingroup hash-based */ /** * A hashed container abstraction. * * @tparam Key Key type. * @tparam Mapped Map type. * @tparam Hash_Fn Hashing functor. * @tparam Eq_Fn Equal functor. * @tparam Resize_Policy Resizes hash. * @tparam Store_Hash Indicates whether the hash value * will be stored along with each key. * @tparam Tag Instantiating data structure type, * see container_tag. * @tparam Policy_TL Policy typelist. * @tparam _Alloc Allocator type. * * Base is dispatched at compile time via Tag, from the following * choices: cc_hash_tag, gp_hash_tag, and descendants of basic_hash_tag. * * Base choices are: detail::cc_ht_map, detail::gp_ht_map */ template class basic_hash_table : public PB_DS_HASH_BASE { private: typedef typename PB_DS_HASH_BASE base_type; public: virtual ~basic_hash_table() { } protected: basic_hash_table() { } basic_hash_table(const basic_hash_table& other) : base_type((const base_type&)other) { } template basic_hash_table(T0 t0) : base_type(t0) { } template basic_hash_table(T0 t0, T1 t1) : base_type(t0, t1) { } template basic_hash_table(T0 t0, T1 t1, T2 t2) : base_type(t0, t1, t2) { } template basic_hash_table(T0 t0, T1 t1, T2 t2, T3 t3) : base_type(t0, t1, t2, t3) { } template basic_hash_table(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4) : base_type(t0, t1, t2, t3, t4) { } template basic_hash_table(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) : base_type(t0, t1, t2, t3, t4, t5) { } template basic_hash_table(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6) : base_type(t0, t1, t2, t3, t4, t5, t6) { } template basic_hash_table(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7) : base_type(t0, t1, t2, t3, t4, t5, t6, t7) { } template basic_hash_table(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8) : base_type(t0, t1, t2, t3, t4, t5, t6, t7, t8) { } private: basic_hash_table& operator=(const base_type&); }; #undef PB_DS_HASH_BASE #define PB_DS_CC_HASH_BASE \ basic_hash_table::type, _Alloc> /** * A collision-chaining hash-based associative container. * * @tparam Key Key type. * @tparam Mapped Map type. * @tparam Hash_Fn Hashing functor. * @tparam Eq_Fn Equal functor. * @tparam Comb_Hash_Fn Combining hash functor. * If Hash_Fn is not null_type, then this * is the ranged-hash functor; otherwise, * this is the range-hashing functor. * XXX(See Design::Hash-Based Containers::Hash Policies.) * @tparam Resize_Policy Resizes hash. * @tparam Store_Hash Indicates whether the hash value * will be stored along with each key. * If Hash_Fn is null_type, then the * container will not compile if this * value is true * @tparam _Alloc Allocator type. * * Base tag choices are: cc_hash_tag. * * Base is basic_hash_table. */ template::type, typename Eq_Fn = typename detail::default_eq_fn::type, typename Comb_Hash_Fn = detail::default_comb_hash_fn::type, typename Resize_Policy = typename detail::default_resize_policy::type, bool Store_Hash = detail::default_store_hash, typename _Alloc = std::allocator > class cc_hash_table : public PB_DS_CC_HASH_BASE { private: typedef PB_DS_CC_HASH_BASE base_type; public: typedef cc_hash_tag container_category; typedef Hash_Fn hash_fn; typedef Eq_Fn eq_fn; typedef Resize_Policy resize_policy; typedef Comb_Hash_Fn comb_hash_fn; /// Default constructor. cc_hash_table() { } /// Constructor taking some policy objects. r_hash_fn will be /// copied by the Hash_Fn object of the container object. cc_hash_table(const hash_fn& h) : base_type(h) { } /// Constructor taking some policy objects. r_hash_fn will be /// copied by the hash_fn object of the container object, and /// r_eq_fn will be copied by the eq_fn object of the container /// object. cc_hash_table(const hash_fn& h, const eq_fn& e) : base_type(h, e) { } /// Constructor taking some policy objects. r_hash_fn will be /// copied by the hash_fn object of the container object, r_eq_fn /// will be copied by the eq_fn object of the container object, /// and r_comb_hash_fn will be copied by the comb_hash_fn object /// of the container object. cc_hash_table(const hash_fn& h, const eq_fn& e, const comb_hash_fn& ch) : base_type(h, e, ch) { } /// Constructor taking some policy objects. r_hash_fn will be /// copied by the hash_fn object of the container object, r_eq_fn /// will be copied by the eq_fn object of the container object, /// r_comb_hash_fn will be copied by the comb_hash_fn object of /// the container object, and r_resize_policy will be copied by /// the resize_policy object of the container object. cc_hash_table(const hash_fn& h, const eq_fn& e, const comb_hash_fn& ch, const resize_policy& rp) : base_type(h, e, ch, rp) { } /// Constructor taking __iterators to a range of value_types. The /// value_types between first_it and last_it will be inserted into /// the container object. template cc_hash_table(It first, It last) { base_type::copy_from_range(first, last); } /// Constructor taking __iterators to a range of value_types and /// some policy objects. The value_types between first_it and /// last_it will be inserted into the container object. template cc_hash_table(It first, It last, const hash_fn& h) : base_type(h) { this->copy_from_range(first, last); } /// Constructor taking __iterators to a range of value_types and /// some policy objects The value_types between first_it and /// last_it will be inserted into the container object. r_hash_fn /// will be copied by the hash_fn object of the container object, /// and r_eq_fn will be copied by the eq_fn object of the /// container object. template cc_hash_table(It first, It last, const hash_fn& h, const eq_fn& e) : base_type(h, e) { this->copy_from_range(first, last); } /// Constructor taking __iterators to a range of value_types and /// some policy objects The value_types between first_it and /// last_it will be inserted into the container object. r_hash_fn /// will be copied by the hash_fn object of the container object, /// r_eq_fn will be copied by the eq_fn object of the container /// object, and r_comb_hash_fn will be copied by the comb_hash_fn /// object of the container object. template cc_hash_table(It first, It last, const hash_fn& h, const eq_fn& e, const comb_hash_fn& ch) : base_type(h, e, ch) { this->copy_from_range(first, last); } /// Constructor taking __iterators to a range of value_types and /// some policy objects The value_types between first_it and /// last_it will be inserted into the container object. r_hash_fn /// will be copied by the hash_fn object of the container object, /// r_eq_fn will be copied by the eq_fn object of the container /// object, r_comb_hash_fn will be copied by the comb_hash_fn /// object of the container object, and r_resize_policy will be /// copied by the resize_policy object of the container object. template cc_hash_table(It first, It last, const hash_fn& h, const eq_fn& e, const comb_hash_fn& ch, const resize_policy& rp) : base_type(h, e, ch, rp) { this->copy_from_range(first, last); } cc_hash_table(const cc_hash_table& other) : base_type((const base_type&)other) { } virtual ~cc_hash_table() { } cc_hash_table& operator=(const cc_hash_table& other) { if (this != &other) { cc_hash_table tmp(other); swap(tmp); } return *this; } void swap(cc_hash_table& other) { base_type::swap(other); } }; #undef PB_DS_CC_HASH_BASE #define PB_DS_GP_HASH_BASE \ basic_hash_table::type, _Alloc> /** * A general-probing hash-based associative container. * * @tparam Key Key type. * @tparam Mapped Map type. * @tparam Hash_Fn Hashing functor. * @tparam Eq_Fn Equal functor. * @tparam Comb_Probe_Fn Combining probe functor. * If Hash_Fn is not null_type, then this * is the ranged-probe functor; otherwise, * this is the range-hashing functor. * XXX See Design::Hash-Based Containers::Hash Policies. * @tparam Probe_Fn Probe functor. * @tparam Resize_Policy Resizes hash. * @tparam Store_Hash Indicates whether the hash value * will be stored along with each key. * If Hash_Fn is null_type, then the * container will not compile if this * value is true * @tparam _Alloc Allocator type. * * Base tag choices are: gp_hash_tag. * * Base is basic_hash_table. */ template::type, typename Eq_Fn = typename detail::default_eq_fn::type, typename Comb_Probe_Fn = detail::default_comb_hash_fn::type, typename Probe_Fn = typename detail::default_probe_fn::type, typename Resize_Policy = typename detail::default_resize_policy::type, bool Store_Hash = detail::default_store_hash, typename _Alloc = std::allocator > class gp_hash_table : public PB_DS_GP_HASH_BASE { private: typedef PB_DS_GP_HASH_BASE base_type; public: typedef gp_hash_tag container_category; typedef Hash_Fn hash_fn; typedef Eq_Fn eq_fn; typedef Comb_Probe_Fn comb_probe_fn; typedef Probe_Fn probe_fn; typedef Resize_Policy resize_policy; /// Default constructor. gp_hash_table() { } /// Constructor taking some policy objects. r_hash_fn will be /// copied by the hash_fn object of the container object. gp_hash_table(const hash_fn& h) : base_type(h) { } /// Constructor taking some policy objects. r_hash_fn will be /// copied by the hash_fn object of the container object, and /// r_eq_fn will be copied by the eq_fn object of the container /// object. gp_hash_table(const hash_fn& h, const eq_fn& e) : base_type(h, e) { } /// Constructor taking some policy objects. r_hash_fn will be /// copied by the hash_fn object of the container object, r_eq_fn /// will be copied by the eq_fn object of the container object, /// and r_comb_probe_fn will be copied by the comb_probe_fn object /// of the container object. gp_hash_table(const hash_fn& h, const eq_fn& e, const comb_probe_fn& cp) : base_type(h, e, cp) { } /// Constructor taking some policy objects. r_hash_fn will be /// copied by the hash_fn object of the container object, r_eq_fn /// will be copied by the eq_fn object of the container object, /// r_comb_probe_fn will be copied by the comb_probe_fn object of /// the container object, and r_probe_fn will be copied by the /// probe_fn object of the container object. gp_hash_table(const hash_fn& h, const eq_fn& e, const comb_probe_fn& cp, const probe_fn& p) : base_type(h, e, cp, p) { } /// Constructor taking some policy objects. r_hash_fn will be /// copied by the hash_fn object of the container object, r_eq_fn /// will be copied by the eq_fn object of the container object, /// r_comb_probe_fn will be copied by the comb_probe_fn object of /// the container object, r_probe_fn will be copied by the /// probe_fn object of the container object, and r_resize_policy /// will be copied by the Resize_Policy object of the container /// object. gp_hash_table(const hash_fn& h, const eq_fn& e, const comb_probe_fn& cp, const probe_fn& p, const resize_policy& rp) : base_type(h, e, cp, p, rp) { } /// Constructor taking __iterators to a range of value_types. The /// value_types between first_it and last_it will be inserted into /// the container object. template gp_hash_table(It first, It last) { base_type::copy_from_range(first, last); } /// Constructor taking __iterators to a range of value_types and /// some policy objects. The value_types between first_it and /// last_it will be inserted into the container object. r_hash_fn /// will be copied by the hash_fn object of the container object. template gp_hash_table(It first, It last, const hash_fn& h) : base_type(h) { base_type::copy_from_range(first, last); } /// Constructor taking __iterators to a range of value_types and /// some policy objects. The value_types between first_it and /// last_it will be inserted into the container object. r_hash_fn /// will be copied by the hash_fn object of the container object, /// and r_eq_fn will be copied by the eq_fn object of the /// container object. template gp_hash_table(It first, It last, const hash_fn& h, const eq_fn& e) : base_type(h, e) { base_type::copy_from_range(first, last); } /// Constructor taking __iterators to a range of value_types and /// some policy objects. The value_types between first_it and /// last_it will be inserted into the container object. r_hash_fn /// will be copied by the hash_fn object of the container object, /// r_eq_fn will be copied by the eq_fn object of the container /// object, and r_comb_probe_fn will be copied by the /// comb_probe_fn object of the container object. template gp_hash_table(It first, It last, const hash_fn& h, const eq_fn& e, const comb_probe_fn& cp) : base_type(h, e, cp) { base_type::copy_from_range(first, last); } /// Constructor taking __iterators to a range of value_types and /// some policy objects. The value_types between first_it and /// last_it will be inserted into the container object. r_hash_fn /// will be copied by the hash_fn object of the container object, /// r_eq_fn will be copied by the eq_fn object of the container /// object, r_comb_probe_fn will be copied by the comb_probe_fn /// object of the container object, and r_probe_fn will be copied /// by the probe_fn object of the container object. template gp_hash_table(It first, It last, const hash_fn& h, const eq_fn& e, const comb_probe_fn& cp, const probe_fn& p) : base_type(h, e, cp, p) { base_type::copy_from_range(first, last); } /// Constructor taking __iterators to a range of value_types and /// some policy objects. The value_types between first_it and /// last_it will be inserted into the container object. r_hash_fn /// will be copied by the hash_fn object of the container object, /// r_eq_fn will be copied by the eq_fn object of the container /// object, r_comb_probe_fn will be copied by the comb_probe_fn /// object of the container object, r_probe_fn will be copied by /// the probe_fn object of the container object, and /// r_resize_policy will be copied by the resize_policy object of /// the container object. template gp_hash_table(It first, It last, const hash_fn& h, const eq_fn& e, const comb_probe_fn& cp, const probe_fn& p, const resize_policy& rp) : base_type(h, e, cp, p, rp) { base_type::copy_from_range(first, last); } gp_hash_table(const gp_hash_table& other) : base_type((const base_type&)other) { } virtual ~gp_hash_table() { } gp_hash_table& operator=(const gp_hash_table& other) { if (this != &other) { gp_hash_table tmp(other); swap(tmp); } return *this; } void swap(gp_hash_table& other) { base_type::swap(other); } }; //@} hash-based #undef PB_DS_GP_HASH_BASE /** * @defgroup branch-based Branch-Based * @ingroup containers-pbds * @{ */ #define PB_DS_BRANCH_BASE \ detail::container_base_dispatch::type /** * @defgroup branch-detail Base and Policy Classes * @ingroup branch-based */ /** * A branched, tree-like (tree, trie) container abstraction. * * @tparam Key Key type. * @tparam Mapped Map type. * @tparam Tag Instantiating data structure type, * see container_tag. * @tparam Node_Update Updates nodes, restores invariants. * @tparam Policy_TL Policy typelist. * @tparam _Alloc Allocator type. * * Base is dispatched at compile time via Tag, from the following * choices: tree_tag, trie_tag, and their descendants. * * Base choices are: detail::ov_tree_map, detail::rb_tree_map, * detail::splay_tree_map, and detail::pat_trie_map. */ template class basic_branch : public PB_DS_BRANCH_BASE { private: typedef typename PB_DS_BRANCH_BASE base_type; public: typedef Node_Update node_update; virtual ~basic_branch() { } protected: basic_branch() { } basic_branch(const basic_branch& other) : base_type((const base_type&)other) { } template basic_branch(T0 t0) : base_type(t0) { } template basic_branch(T0 t0, T1 t1) : base_type(t0, t1) { } template basic_branch(T0 t0, T1 t1, T2 t2) : base_type(t0, t1, t2) { } template basic_branch(T0 t0, T1 t1, T2 t2, T3 t3) : base_type(t0, t1, t2, t3) { } template basic_branch(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4) : base_type(t0, t1, t2, t3, t4) { } template basic_branch(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) : base_type(t0, t1, t2, t3, t4, t5) { } template basic_branch(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6) : base_type(t0, t1, t2, t3, t4, t5, t6) { } }; #undef PB_DS_BRANCH_BASE #define PB_DS_TREE_NODE_AND_IT_TRAITS \ detail::tree_traits #define PB_DS_TREE_BASE \ basic_branch::type, _Alloc> /** * A tree-based container. * * @tparam Key Key type. * @tparam Mapped Map type. * @tparam Cmp_Fn Comparison functor. * @tparam Tag Instantiating data structure type, * see container_tag. * @tparam Node_Update Updates tree internal-nodes, * restores invariants when invalidated. * XXX See design::tree-based-containers::node invariants. * @tparam _Alloc Allocator type. * * Base tag choices are: ov_tree_tag, rb_tree_tag, splay_tree_tag. * * Base is basic_branch. */ template, typename Tag = rb_tree_tag, template class Node_Update = null_node_update, typename _Alloc = std::allocator > class tree : public PB_DS_TREE_BASE { private: typedef PB_DS_TREE_BASE base_type; public: /// Comparison functor type. typedef Cmp_Fn cmp_fn; tree() { } /// Constructor taking some policy objects. r_cmp_fn will be /// copied by the Cmp_Fn object of the container object. tree(const cmp_fn& c) : base_type(c) { } /// Constructor taking __iterators to a range of value_types. The /// value_types between first_it and last_it will be inserted into /// the container object. template tree(It first, It last) { base_type::copy_from_range(first, last); } /// Constructor taking __iterators to a range of value_types and /// some policy objects The value_types between first_it and /// last_it will be inserted into the container object. r_cmp_fn /// will be copied by the cmp_fn object of the container object. template tree(It first, It last, const cmp_fn& c) : base_type(c) { base_type::copy_from_range(first, last); } tree(const tree& other) : base_type((const base_type&)other) { } virtual ~tree() { } tree& operator=(const tree& other) { if (this != &other) { tree tmp(other); swap(tmp); } return *this; } void swap(tree& other) { base_type::swap(other); } }; #undef PB_DS_TREE_BASE #undef PB_DS_TREE_NODE_AND_IT_TRAITS #define PB_DS_TRIE_NODE_AND_IT_TRAITS \ detail::trie_traits #define PB_DS_TRIE_BASE \ basic_branch::type, _Alloc> /** * A trie-based container. * * @tparam Key Key type. * @tparam Mapped Map type. * @tparam _ATraits Element access traits. * @tparam Tag Instantiating data structure type, * see container_tag. * @tparam Node_Update Updates trie internal-nodes, * restores invariants when invalidated. * XXX See design::tree-based-containers::node invariants. * @tparam _Alloc Allocator type. * * Base tag choice is pat_trie_tag. * * Base is basic_branch. */ template::type, typename Tag = pat_trie_tag, template class Node_Update = null_node_update, typename _Alloc = std::allocator > class trie : public PB_DS_TRIE_BASE { private: typedef PB_DS_TRIE_BASE base_type; public: /// Element access traits type. typedef _ATraits access_traits; trie() { } /// Constructor taking some policy objects. r_access_traits will /// be copied by the _ATraits object of the container object. trie(const access_traits& t) : base_type(t) { } /// Constructor taking __iterators to a range of value_types. The /// value_types between first_it and last_it will be inserted into /// the container object. template trie(It first, It last) { base_type::copy_from_range(first, last); } /// Constructor taking __iterators to a range of value_types and /// some policy objects. The value_types between first_it and /// last_it will be inserted into the container object. template trie(It first, It last, const access_traits& t) : base_type(t) { base_type::copy_from_range(first, last); } trie(const trie& other) : base_type((const base_type&)other) { } virtual ~trie() { } trie& operator=(const trie& other) { if (this != &other) { trie tmp(other); swap(tmp); } return *this; } void swap(trie& other) { base_type::swap(other); } }; //@} branch-based #undef PB_DS_TRIE_BASE #undef PB_DS_TRIE_NODE_AND_IT_TRAITS /** * @defgroup list-based List-Based * @ingroup containers-pbds * @{ */ #define PB_DS_LU_BASE \ detail::container_base_dispatch::type>::type /** * A list-update based associative container. * * @tparam Key Key type. * @tparam Mapped Map type. * @tparam Eq_Fn Equal functor. * @tparam Update_Policy Update policy, determines when an element * will be moved to the front of the list. * @tparam _Alloc Allocator type. * * Base is detail::lu_map. */ template::type, class Update_Policy = detail::default_update_policy::type, class _Alloc = std::allocator > class list_update : public PB_DS_LU_BASE { private: typedef typename PB_DS_LU_BASE base_type; public: typedef list_update_tag container_category; typedef Eq_Fn eq_fn; typedef Update_Policy update_policy; list_update() { } /// Constructor taking __iterators to a range of value_types. The /// value_types between first_it and last_it will be inserted into /// the container object. template list_update(It first, It last) { base_type::copy_from_range(first, last); } list_update(const list_update& other) : base_type((const base_type&)other) { } virtual ~list_update() { } list_update& operator=(const list_update& other) { if (this !=& other) { list_update tmp(other); swap(tmp); } return *this; } void swap(list_update& other) { base_type::swap(other); } }; //@} list-based #undef PB_DS_LU_BASE // @} group containers-pbds } // namespace __gnu_pbds #endif PK!Dq 8/ext/pb_ds/exception.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file exception.hpp * Contains exception classes. */ #ifndef PB_DS_EXCEPTION_HPP #define PB_DS_EXCEPTION_HPP #include #include #include namespace __gnu_pbds { /** * @defgroup exceptions-pbds Exceptions * @ingroup pbds * @{ */ /// Base class for exceptions. struct container_error : public std::logic_error { container_error() : std::logic_error(__N("__gnu_pbds::container_error")) { } }; /// An entry cannot be inserted into a container object for logical /// reasons (not, e.g., if memory is unabvailable, in which case /// the allocator_type's exception will be thrown). struct insert_error : public container_error { }; /// A join cannot be performed logical reasons (i.e., the ranges of /// the two container objects being joined overlaps. struct join_error : public container_error { }; /// A container cannot be resized. struct resize_error : public container_error { }; inline void __throw_container_error() { _GLIBCXX_THROW_OR_ABORT(container_error()); } inline void __throw_insert_error() { _GLIBCXX_THROW_OR_ABORT(insert_error()); } inline void __throw_join_error() { _GLIBCXX_THROW_OR_ABORT(join_error()); } inline void __throw_resize_error() { _GLIBCXX_THROW_OR_ABORT(resize_error()); } //@} } // namespace __gnu_pbds #endif PK!W^AA8/ext/pb_ds/hash_policy.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file hash_policy.hpp * Contains hash-related policies. */ #ifndef PB_DS_HASH_POLICY_HPP #define PB_DS_HASH_POLICY_HPP #include #include #include #include #include #include #include #include #include namespace __gnu_pbds { #define PB_DS_CLASS_T_DEC template #define PB_DS_CLASS_C_DEC linear_probe_fn /// A probe sequence policy using fixed increments. template class linear_probe_fn { public: typedef Size_Type size_type; void swap(PB_DS_CLASS_C_DEC& other); protected: /// Returns the i-th offset from the hash value. inline size_type operator()(size_type i) const; }; #include #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #define PB_DS_CLASS_T_DEC template #define PB_DS_CLASS_C_DEC quadratic_probe_fn /// A probe sequence policy using square increments. template class quadratic_probe_fn { public: typedef Size_Type size_type; void swap(PB_DS_CLASS_C_DEC& other); protected: /// Returns the i-th offset from the hash value. inline size_type operator()(size_type i) const; }; #include #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #define PB_DS_CLASS_T_DEC template #define PB_DS_CLASS_C_DEC direct_mask_range_hashing /// A mask range-hashing class (uses a bitmask). template class direct_mask_range_hashing : public detail::mask_based_range_hashing { private: typedef detail::mask_based_range_hashing mask_based_base; public: typedef Size_Type size_type; void swap(PB_DS_CLASS_C_DEC& other); protected: void notify_resized(size_type size); /// Transforms the __hash value hash into a ranged-hash value /// (using a bit-mask). inline size_type operator()(size_type hash) const; }; #include #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #define PB_DS_CLASS_T_DEC template #define PB_DS_CLASS_C_DEC direct_mod_range_hashing /// A mod range-hashing class (uses the modulo function). template class direct_mod_range_hashing : public detail::mod_based_range_hashing { public: typedef Size_Type size_type; void swap(PB_DS_CLASS_C_DEC& other); protected: void notify_resized(size_type size); /// Transforms the __hash value hash into a ranged-hash value /// (using a modulo operation). inline size_type operator()(size_type hash) const; private: typedef detail::mod_based_range_hashing mod_based_base; }; #include #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #define PB_DS_CLASS_T_DEC template #define PB_DS_CLASS_C_DEC hash_load_check_resize_trigger #define PB_DS_SIZE_BASE_C_DEC detail::hash_load_check_resize_trigger_size_base /// A resize trigger policy based on a load check. It keeps the /// load factor between some load factors load_min and load_max. template class hash_load_check_resize_trigger : private PB_DS_SIZE_BASE_C_DEC { public: typedef Size_Type size_type; enum { /// Specifies whether the load factor can be accessed /// externally. The two options have different trade-offs in /// terms of flexibility, genericity, and encapsulation. external_load_access = External_Load_Access }; /// Default constructor, or constructor taking load_min and /// load_max load factors between which this policy will keep the /// actual load. hash_load_check_resize_trigger(float load_min = 0.125, float load_max = 0.5); void swap(hash_load_check_resize_trigger& other); virtual ~hash_load_check_resize_trigger(); /// Returns a pair of the minimal and maximal loads, respectively. inline std::pair get_loads() const; /// Sets the loads through a pair of the minimal and maximal /// loads, respectively. void set_loads(std::pair load_pair); protected: inline void notify_insert_search_start(); inline void notify_insert_search_collision(); inline void notify_insert_search_end(); inline void notify_find_search_start(); inline void notify_find_search_collision(); inline void notify_find_search_end(); inline void notify_erase_search_start(); inline void notify_erase_search_collision(); inline void notify_erase_search_end(); /// Notifies an element was inserted. The total number of entries /// in the table is num_entries. inline void notify_inserted(size_type num_entries); inline void notify_erased(size_type num_entries); /// Notifies the table was cleared. void notify_cleared(); /// Notifies the table was resized as a result of this object's /// signifying that a resize is needed. void notify_resized(size_type new_size); void notify_externally_resized(size_type new_size); inline bool is_resize_needed() const; inline bool is_grow_needed(size_type size, size_type num_entries) const; private: virtual void do_resize(size_type new_size); typedef PB_DS_SIZE_BASE_C_DEC size_base; #ifdef _GLIBCXX_DEBUG void assert_valid(const char* file, int line) const; #endif float m_load_min; float m_load_max; size_type m_next_shrink_size; size_type m_next_grow_size; bool m_resize_needed; }; #include #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #undef PB_DS_SIZE_BASE_C_DEC #define PB_DS_CLASS_T_DEC template #define PB_DS_CLASS_C_DEC cc_hash_max_collision_check_resize_trigger /// A resize trigger policy based on collision checks. It keeps the /// simulated load factor lower than some given load factor. template class cc_hash_max_collision_check_resize_trigger { public: typedef Size_Type size_type; enum { /// Specifies whether the load factor can be accessed /// externally. The two options have different trade-offs in /// terms of flexibility, genericity, and encapsulation. external_load_access = External_Load_Access }; /// Default constructor, or constructor taking load, a __load /// factor which it will attempt to maintain. cc_hash_max_collision_check_resize_trigger(float load = 0.5); void swap(PB_DS_CLASS_C_DEC& other); /// Returns the current load. inline float get_load() const; /// Sets the load; does not resize the container. void set_load(float load); protected: /// Notifies an insert search started. inline void notify_insert_search_start(); /// Notifies a search encountered a collision. inline void notify_insert_search_collision(); /// Notifies a search ended. inline void notify_insert_search_end(); /// Notifies a find search started. inline void notify_find_search_start(); /// Notifies a search encountered a collision. inline void notify_find_search_collision(); /// Notifies a search ended. inline void notify_find_search_end(); /// Notifies an erase search started. inline void notify_erase_search_start(); /// Notifies a search encountered a collision. inline void notify_erase_search_collision(); /// Notifies a search ended. inline void notify_erase_search_end(); /// Notifies an element was inserted. inline void notify_inserted(size_type num_entries); /// Notifies an element was erased. inline void notify_erased(size_type num_entries); /// Notifies the table was cleared. void notify_cleared(); /// Notifies the table was resized as a result of this object's /// signifying that a resize is needed. void notify_resized(size_type new_size); /// Notifies the table was resized externally. void notify_externally_resized(size_type new_size); /// Queries whether a resize is needed. inline bool is_resize_needed() const; /// Queries whether a grow is needed. This method is called only /// if this object indicated is needed. inline bool is_grow_needed(size_type size, size_type num_entries) const; private: void calc_max_num_coll(); inline void calc_resize_needed(); float m_load; size_type m_size; size_type m_num_col; size_type m_max_col; bool m_resize_needed; }; #include #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #define PB_DS_CLASS_T_DEC template #define PB_DS_CLASS_C_DEC hash_exponential_size_policy /// A size policy whose sequence of sizes form an exponential /// sequence (typically powers of 2. template class hash_exponential_size_policy { public: typedef Size_Type size_type; /// Default constructor, or onstructor taking a start_size, or /// constructor taking a start size and grow_factor. The policy /// will use the sequence of sizes start_size, start_size* /// grow_factor, start_size* grow_factor^2, ... hash_exponential_size_policy(size_type start_size = 8, size_type grow_factor = 2); void swap(PB_DS_CLASS_C_DEC& other); protected: size_type get_nearest_larger_size(size_type size) const; size_type get_nearest_smaller_size(size_type size) const; private: size_type m_start_size; size_type m_grow_factor; }; #include #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #define PB_DS_CLASS_T_DEC #define PB_DS_CLASS_C_DEC hash_prime_size_policy /// A size policy whose sequence of sizes form a nearly-exponential /// sequence of primes. class hash_prime_size_policy { public: /// Size type. typedef std::size_t size_type; /// Default constructor, or onstructor taking a start_size The /// policy will use the sequence of sizes approximately /// start_size, start_size* 2, start_size* 2^2, ... hash_prime_size_policy(size_type start_size = 8); inline void swap(PB_DS_CLASS_C_DEC& other); protected: size_type get_nearest_larger_size(size_type size) const; size_type get_nearest_smaller_size(size_type size) const; private: size_type m_start_size; }; #include #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #define PB_DS_CLASS_T_DEC template #define PB_DS_CLASS_C_DEC hash_standard_resize_policy /// A resize policy which delegates operations to size and trigger policies. template, typename Trigger_Policy = hash_load_check_resize_trigger<>, bool External_Size_Access = false, typename Size_Type = std::size_t> class hash_standard_resize_policy : public Size_Policy, public Trigger_Policy { public: typedef Size_Type size_type; typedef Trigger_Policy trigger_policy; typedef Size_Policy size_policy; enum { external_size_access = External_Size_Access }; /// Default constructor. hash_standard_resize_policy(); /// constructor taking some policies r_size_policy will be copied /// by the Size_Policy object of this object. hash_standard_resize_policy(const Size_Policy& r_size_policy); /// constructor taking some policies. r_size_policy will be /// copied by the Size_Policy object of this /// object. r_trigger_policy will be copied by the Trigger_Policy /// object of this object. hash_standard_resize_policy(const Size_Policy& r_size_policy, const Trigger_Policy& r_trigger_policy); virtual ~hash_standard_resize_policy(); inline void swap(PB_DS_CLASS_C_DEC& other); /// Access to the Size_Policy object used. Size_Policy& get_size_policy(); /// Const access to the Size_Policy object used. const Size_Policy& get_size_policy() const; /// Access to the Trigger_Policy object used. Trigger_Policy& get_trigger_policy(); /// Access to the Trigger_Policy object used. const Trigger_Policy& get_trigger_policy() const; /// Returns the actual size of the container. inline size_type get_actual_size() const; /// Resizes the container to suggested_new_size, a suggested size /// (the actual size will be determined by the Size_Policy /// object). void resize(size_type suggested_new_size); protected: inline void notify_insert_search_start(); inline void notify_insert_search_collision(); inline void notify_insert_search_end(); inline void notify_find_search_start(); inline void notify_find_search_collision(); inline void notify_find_search_end(); inline void notify_erase_search_start(); inline void notify_erase_search_collision(); inline void notify_erase_search_end(); inline void notify_inserted(size_type num_e); inline void notify_erased(size_type num_e); void notify_cleared(); void notify_resized(size_type new_size); inline bool is_resize_needed() const; /// Queries what the new size should be, when the container is /// resized naturally. The current __size of the container is /// size, and the number of used entries within the container is /// num_used_e. size_type get_new_size(size_type size, size_type num_used_e) const; private: /// Resizes to new_size. virtual void do_resize(size_type new_size); typedef Trigger_Policy trigger_policy_base; typedef Size_Policy size_policy_base; size_type m_size; }; #include #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC } // namespace __gnu_pbds #endif PK! "8/ext/pb_ds/list_update_policy.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file list_update_policy.hpp * Contains policies for list update containers. */ #ifndef PB_DS_LU_POLICY_HPP #define PB_DS_LU_POLICY_HPP #include #include #include #include namespace __gnu_pbds { /** * A list-update policy that unconditionally moves elements to the * front of the list. A null type means that each link in a * list-based container does not actually need metadata. */ template > class lu_move_to_front_policy { public: typedef _Alloc allocator_type; /// Metadata on which this functor operates. typedef null_type metadata_type; private: typedef typename _Alloc::template rebind __rebind_m; public: /// Reference to metadata on which this functor operates. typedef typename __rebind_m::other::reference metadata_reference; /// Creates a metadata object. metadata_type operator()() const { return s_metadata; } /// Decides whether a metadata object should be moved to the front /// of the list. inline bool operator()(metadata_reference r_metadata) const { return true; } private: static null_type s_metadata; }; /** * A list-update policy that moves elements to the front of the * list based on the counter algorithm. */ template > class lu_counter_policy : private detail::lu_counter_policy_base { public: typedef _Alloc allocator_type; typedef typename allocator_type::size_type size_type; enum { /// When some element is accessed this number of times, it /// will be moved to the front of the list. max_count = Max_Count }; /// Metadata on which this functor operates. typedef detail::lu_counter_metadata metadata_type; private: typedef detail::lu_counter_policy_base base_type; typedef typename _Alloc::template rebind __rebind_m; public: /// Reference to metadata on which this functor operates. typedef typename __rebind_m::other::reference metadata_reference; /// Creates a metadata object. metadata_type operator()() const { return base_type::operator()(max_count); } /// Decides whether a metadata object should be moved to the front /// of the list. bool operator()(metadata_reference r_data) const { return base_type::operator()(r_data, max_count); } }; } // namespace __gnu_pbds #endif PK!q~~8/ext/pb_ds/priority_queue.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file priority_queue.hpp * Contains priority_queues. */ #ifndef PB_DS_PRIORITY_QUEUE_HPP #define PB_DS_PRIORITY_QUEUE_HPP #include #include #include #include namespace __gnu_pbds { /** * @defgroup heap-based Heap-Based * @ingroup containers-pbds * @{ */ /** * @defgroup heap-detail Base and Policy Classes * @ingroup heap-based */ /** * A priority queue composed of one specific heap policy. * * @tparam _Tv Value type. * @tparam Cmp_Fn Comparison functor. * @tparam Tag Instantiating data structure type, * see container_tag. * @tparam _Alloc Allocator type. * * Base is dispatched at compile time via Tag, from the following * choices: binary_heap_tag, binomial_heap_tag, pairing_heap_tag, * rc_binomial_heap_tag, thin_heap_tag * * Base choices are: detail::binary_heap, detail::binomial_heap, * detail::pairing_heap, detail::rc_binomial_heap, * detail::thin_heap. */ template, typename Tag = pairing_heap_tag, typename _Alloc = std::allocator > class priority_queue : public detail::container_base_dispatch<_Tv, Cmp_Fn, _Alloc, Tag>::type { public: typedef _Tv value_type; typedef Cmp_Fn cmp_fn; typedef Tag container_category; typedef _Alloc allocator_type; typedef typename allocator_type::size_type size_type; typedef typename allocator_type::difference_type difference_type; private: typedef typename detail::container_base_dispatch<_Tv, Cmp_Fn, _Alloc, Tag>::type base_type; typedef typename _Alloc::template rebind<_Tv> __rebind_v; typedef typename __rebind_v::other __rebind_va; public: typedef typename __rebind_va::reference reference; typedef typename __rebind_va::const_reference const_reference; typedef typename __rebind_va::pointer pointer; typedef typename __rebind_va::const_pointer const_pointer; typedef typename base_type::point_iterator point_iterator; typedef typename base_type::point_const_iterator point_const_iterator; typedef typename base_type::iterator iterator; typedef typename base_type::const_iterator const_iterator; priority_queue() { } /// Constructor taking some policy objects. r_cmp_fn will be /// copied by the Cmp_Fn object of the container object. priority_queue(const cmp_fn& r_cmp_fn) : base_type(r_cmp_fn) { } /// Constructor taking __iterators to a range of value_types. The /// value_types between first_it and last_it will be inserted into /// the container object. template priority_queue(It first_it, It last_it) { base_type::copy_from_range(first_it, last_it); } /// Constructor taking __iterators to a range of value_types and /// some policy objects The value_types between first_it and /// last_it will be inserted into the container object. r_cmp_fn /// will be copied by the cmp_fn object of the container object. template priority_queue(It first_it, It last_it, const cmp_fn& r_cmp_fn) : base_type(r_cmp_fn) { base_type::copy_from_range(first_it, last_it); } priority_queue(const priority_queue& other) : base_type((const base_type& )other) { } virtual ~priority_queue() { } priority_queue& operator=(const priority_queue& other) { if (this != &other) { priority_queue tmp(other); swap(tmp); } return *this; } void swap(priority_queue& other) { base_type::swap(other); } }; } // namespace __gnu_pbds //@} heap-based #endif PK!T9//8/ext/pb_ds/tag_and_trait.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file tag_and_trait.hpp * Contains tags and traits, e.g., ones describing underlying * data structures. */ #ifndef PB_DS_TAG_AND_TRAIT_HPP #define PB_DS_TAG_AND_TRAIT_HPP #include #include /** * @namespace __gnu_pbds * @brief GNU extensions for policy-based data structures for public use. */ namespace __gnu_pbds { /** @defgroup pbds Policy-Based Data Structures * @ingroup extensions * * This is a library of policy-based elementary data structures: * associative containers and priority queues. It is designed for * high-performance, flexibility, semantic safety, and conformance * to the corresponding containers in std (except for some points * where it differs by design). * * For details, see: * http://gcc.gnu.org/onlinedocs/libstdc++/ext/pb_ds/index.html * * @{ */ /** * @defgroup tags Tags * @{ */ /// A trivial iterator tag. Signifies that the iterators has none of /// std::iterators's movement abilities. struct trivial_iterator_tag { }; /// Prohibit moving trivial iterators. typedef void trivial_iterator_difference_type; /** * @defgroup invalidation_tags Invalidation Guarantees * @ingroup tags * @{ */ /** * Signifies a basic invalidation guarantee that any iterator, * pointer, or reference to a container object's mapped value type * is valid as long as the container is not modified. */ struct basic_invalidation_guarantee { }; /** * Signifies an invalidation guarantee that includes all those of * its base, and additionally, that any point-type iterator, * pointer, or reference to a container object's mapped value type * is valid as long as its corresponding entry has not be erased, * regardless of modifications to the container object. */ struct point_invalidation_guarantee : public basic_invalidation_guarantee { }; /** * Signifies an invalidation guarantee that includes all those of * its base, and additionally, that any range-type iterator * (including the returns of begin() and end()) is in the correct * relative positions to other range-type iterators as long as its * corresponding entry has not be erased, regardless of * modifications to the container object. */ struct range_invalidation_guarantee : public point_invalidation_guarantee { }; //@} /** * @defgroup ds_tags Data Structure Type * @ingroup tags * @{ */ /// Base data structure tag. struct container_tag { }; /// Basic sequence. struct sequence_tag : public container_tag { }; /// Basic string container, inclusive of strings, ropes, etc. struct string_tag : public sequence_tag { }; /// Basic associative-container. struct associative_tag : public container_tag { }; /// Basic hash structure. struct basic_hash_tag : public associative_tag { }; /// Collision-chaining hash. struct cc_hash_tag : public basic_hash_tag { }; /// General-probing hash. struct gp_hash_tag : public basic_hash_tag { }; /// Basic branch structure. struct basic_branch_tag : public associative_tag { }; /// Basic tree structure. struct tree_tag : public basic_branch_tag { }; /// Red-black tree. struct rb_tree_tag : public tree_tag { }; /// Splay tree. struct splay_tree_tag : public tree_tag { }; /// Ordered-vector tree. struct ov_tree_tag : public tree_tag { }; /// Basic trie structure. struct trie_tag : public basic_branch_tag { }; /// PATRICIA trie. struct pat_trie_tag : public trie_tag { }; /// List-update. struct list_update_tag : public associative_tag { }; /// Basic priority-queue. struct priority_queue_tag : public container_tag { }; /// Pairing-heap. struct pairing_heap_tag : public priority_queue_tag { }; /// Binomial-heap. struct binomial_heap_tag : public priority_queue_tag { }; /// Redundant-counter binomial-heap. struct rc_binomial_heap_tag : public priority_queue_tag { }; /// Binary-heap (array-based). struct binary_heap_tag : public priority_queue_tag { }; /// Thin heap. struct thin_heap_tag : public priority_queue_tag { }; //@} //@} /** * @defgroup traits Traits * @{ */ /** * @brief Represents no type, or absence of type, for template tricks. * * In a mapped-policy, indicates that an associative container is a set. * * In a list-update policy, indicates that each link does not need * metadata. * * In a hash policy, indicates that the combining hash function * is actually a ranged hash function. * * In a probe policy, indicates that the combining probe function * is actually a ranged probe function. */ struct null_type { }; /// A null node updator, indicating that no node updates are required. template struct null_node_update : public null_type { }; /// Primary template, container traits base. template struct container_traits_base; /// Specialization, cc hash. template<> struct container_traits_base { typedef cc_hash_tag container_category; typedef point_invalidation_guarantee invalidation_guarantee; enum { order_preserving = false, erase_can_throw = false, split_join_can_throw = false, reverse_iteration = false }; }; /// Specialization, gp hash. template<> struct container_traits_base { typedef gp_hash_tag container_category; typedef basic_invalidation_guarantee invalidation_guarantee; enum { order_preserving = false, erase_can_throw = false, split_join_can_throw = false, reverse_iteration = false }; }; /// Specialization, rb tree. template<> struct container_traits_base { typedef rb_tree_tag container_category; typedef range_invalidation_guarantee invalidation_guarantee; enum { order_preserving = true, erase_can_throw = false, split_join_can_throw = false, reverse_iteration = true }; }; /// Specialization, splay tree. template<> struct container_traits_base { typedef splay_tree_tag container_category; typedef range_invalidation_guarantee invalidation_guarantee; enum { order_preserving = true, erase_can_throw = false, split_join_can_throw = false, reverse_iteration = true }; }; /// Specialization, ov tree. template<> struct container_traits_base { typedef ov_tree_tag container_category; typedef basic_invalidation_guarantee invalidation_guarantee; enum { order_preserving = true, erase_can_throw = true, split_join_can_throw = true, reverse_iteration = false }; }; /// Specialization, pat trie. template<> struct container_traits_base { typedef pat_trie_tag container_category; typedef range_invalidation_guarantee invalidation_guarantee; enum { order_preserving = true, erase_can_throw = false, split_join_can_throw = true, reverse_iteration = true }; }; /// Specialization, list update. template<> struct container_traits_base { typedef list_update_tag container_category; typedef point_invalidation_guarantee invalidation_guarantee; enum { order_preserving = false, erase_can_throw = false, split_join_can_throw = false, reverse_iteration = false }; }; /// Specialization, pairing heap. template<> struct container_traits_base { typedef pairing_heap_tag container_category; typedef point_invalidation_guarantee invalidation_guarantee; enum { order_preserving = false, erase_can_throw = false, split_join_can_throw = false, reverse_iteration = false }; }; /// Specialization, thin heap. template<> struct container_traits_base { typedef thin_heap_tag container_category; typedef point_invalidation_guarantee invalidation_guarantee; enum { order_preserving = false, erase_can_throw = false, split_join_can_throw = false, reverse_iteration = false }; }; /// Specialization, binomial heap. template<> struct container_traits_base { typedef binomial_heap_tag container_category; typedef point_invalidation_guarantee invalidation_guarantee; enum { order_preserving = false, erase_can_throw = false, split_join_can_throw = false, reverse_iteration = false }; }; /// Specialization, rc binomial heap. template<> struct container_traits_base { typedef rc_binomial_heap_tag container_category; typedef point_invalidation_guarantee invalidation_guarantee; enum { order_preserving = false, erase_can_throw = false, split_join_can_throw = false, reverse_iteration = false }; }; /// Specialization, binary heap. template<> struct container_traits_base { typedef binary_heap_tag container_category; typedef basic_invalidation_guarantee invalidation_guarantee; enum { order_preserving = false, erase_can_throw = false, split_join_can_throw = true, reverse_iteration = false }; }; /// Container traits. // See Matt Austern for the name, S. Meyers MEFC++ #2, others. template struct container_traits : public container_traits_base { typedef Cntnr container_type; typedef typename Cntnr::container_category container_category; typedef container_traits_base base_type; typedef typename base_type::invalidation_guarantee invalidation_guarantee; enum { /// True only if Cntnr objects guarantee storing keys by order. order_preserving = base_type::order_preserving, /// True only if erasing a key can throw. erase_can_throw = base_type::erase_can_throw, /// True only if split or join operations can throw. split_join_can_throw = base_type::split_join_can_throw, /// True only reverse iterators are supported. reverse_iteration = base_type::reverse_iteration }; }; //@} namespace detail { /// Dispatch mechanism, primary template for associative types. template struct container_base_dispatch; } // namespace detail //@} } // namespace __gnu_pbds #endif PK!E8/ext/pb_ds/tree_policy.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file tree_policy.hpp * Contains tree-related policies. */ #ifndef PB_DS_TREE_POLICY_HPP #define PB_DS_TREE_POLICY_HPP #include #include #include #include namespace __gnu_pbds { #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ tree_order_statistics_node_update #define PB_DS_BRANCH_POLICY_BASE \ detail::branch_policy /// Functor updating ranks of entrees. template class tree_order_statistics_node_update : private PB_DS_BRANCH_POLICY_BASE { private: typedef PB_DS_BRANCH_POLICY_BASE base_type; public: typedef Cmp_Fn cmp_fn; typedef _Alloc allocator_type; typedef typename allocator_type::size_type size_type; typedef typename base_type::key_type key_type; typedef typename base_type::key_const_reference key_const_reference; typedef size_type metadata_type; typedef Node_CItr node_const_iterator; typedef Node_Itr node_iterator; typedef typename node_const_iterator::value_type const_iterator; typedef typename node_iterator::value_type iterator; /// Finds an entry by __order. Returns a const_iterator to the /// entry with the __order order, or a const_iterator to the /// container object's end if order is at least the size of the /// container object. inline const_iterator find_by_order(size_type) const; /// Finds an entry by __order. Returns an iterator to the entry /// with the __order order, or an iterator to the container /// object's end if order is at least the size of the container /// object. inline iterator find_by_order(size_type); /// Returns the order of a key within a sequence. For exapmle, if /// r_key is the smallest key, this method will return 0; if r_key /// is a key between the smallest and next key, this method will /// return 1; if r_key is a key larger than the largest key, this /// method will return the size of r_c. inline size_type order_of_key(key_const_reference) const; private: /// Const reference to the container's value-type. typedef typename base_type::const_reference const_reference; /// Const pointer to the container's value-type. typedef typename base_type::const_pointer const_pointer; typedef typename _Alloc::template rebind::other __rebind_m; /// Const metadata reference. typedef typename __rebind_m::const_reference metadata_const_reference; /// Metadata reference. typedef typename __rebind_m::reference metadata_reference; /// Returns the node_const_iterator associated with the tree's root node. virtual node_const_iterator node_begin() const = 0; /// Returns the node_iterator associated with the tree's root node. virtual node_iterator node_begin() = 0; /// Returns the node_const_iterator associated with a just-after leaf node. virtual node_const_iterator node_end() const = 0; /// Returns the node_iterator associated with a just-after leaf node. virtual node_iterator node_end() = 0; /// Access to the cmp_fn object. virtual cmp_fn& get_cmp_fn() = 0; protected: /// Updates the rank of a node through a node_iterator node_it; /// end_nd_it is the end node iterator. inline void operator()(node_iterator, node_const_iterator) const; virtual ~tree_order_statistics_node_update(); }; #include #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #undef PB_DS_BRANCH_POLICY_BASE } // namespace __gnu_pbds #endif PK!8p//8/ext/pb_ds/trie_policy.hppnu[// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file trie_policy.hpp * Contains trie-related policies. */ #ifndef PB_DS_TRIE_POLICY_HPP #define PB_DS_TRIE_POLICY_HPP #include #include #include #include namespace __gnu_pbds { #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ trie_string_access_traits /** * Element access traits for string types. * * @tparam String String type. * @tparam Min_E_Val Minimal element value. * @tparam Max_E_Val Maximum element value. * @tparam Reverse Reverse iteration should be used. * Default: false. * @tparam _Alloc Allocator type. */ template::__min, typename String::value_type Max_E_Val = detail::__numeric_traits::__max, bool Reverse = false, typename _Alloc = std::allocator > struct trie_string_access_traits { public: typedef typename _Alloc::size_type size_type; typedef String key_type; typedef typename _Alloc::template rebind __rebind_k; typedef typename __rebind_k::other::const_reference key_const_reference; enum { reverse = Reverse }; /// Element const iterator type. typedef typename detail::__conditional_type::__type const_iterator; /// Element type. typedef typename std::iterator_traits::value_type e_type; enum { min_e_val = Min_E_Val, max_e_val = Max_E_Val, max_size = max_e_val - min_e_val + 1 }; PB_DS_STATIC_ASSERT(min_max_size, max_size >= 2); /// Returns a const_iterator to the first element of /// key_const_reference agumnet. inline static const_iterator begin(key_const_reference); /// Returns a const_iterator to the after-last element of /// key_const_reference argument. inline static const_iterator end(key_const_reference); /// Maps an element to a position. inline static size_type e_pos(e_type e); private: inline static const_iterator begin_imp(key_const_reference, detail::false_type); inline static const_iterator begin_imp(key_const_reference, detail::true_type); inline static const_iterator end_imp(key_const_reference, detail::false_type); inline static const_iterator end_imp(key_const_reference, detail::true_type); static detail::integral_constant s_rev_ind; }; #include #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #define PB_DS_CLASS_T_DEC \ template #define PB_DS_CLASS_C_DEC \ trie_prefix_search_node_update #define PB_DS_TRIE_POLICY_BASE \ detail::trie_policy_base /// A node updator that allows tries to be searched for the range of /// values that match a certain prefix. template class trie_prefix_search_node_update : private PB_DS_TRIE_POLICY_BASE { private: typedef PB_DS_TRIE_POLICY_BASE base_type; public: typedef typename base_type::key_type key_type; typedef typename base_type::key_const_reference key_const_reference; /// Element access traits. typedef _ATraits access_traits; /// Const element iterator. typedef typename access_traits::const_iterator a_const_iterator; /// _Alloc type. typedef _Alloc allocator_type; /// Size type. typedef typename allocator_type::size_type size_type; typedef null_type metadata_type; typedef Node_Itr node_iterator; typedef Node_CItr node_const_iterator; typedef typename node_iterator::value_type iterator; typedef typename node_const_iterator::value_type const_iterator; /// Finds the const iterator range corresponding to all values /// whose prefixes match r_key. std::pair prefix_range(key_const_reference) const; /// Finds the iterator range corresponding to all values whose /// prefixes match r_key. std::pair prefix_range(key_const_reference); /// Finds the const iterator range corresponding to all values /// whose prefixes match [b, e). std::pair prefix_range(a_const_iterator, a_const_iterator) const; /// Finds the iterator range corresponding to all values whose /// prefixes match [b, e). std::pair prefix_range(a_const_iterator, a_const_iterator); protected: /// Called to update a node's metadata. inline void operator()(node_iterator node_it, node_const_iterator end_nd_it) const; private: node_iterator next_child(node_iterator, a_const_iterator, a_const_iterator, node_iterator, const access_traits&); /// Returns the const iterator associated with the just-after last element. virtual const_iterator end() const = 0; /// Returns the iterator associated with the just-after last element. virtual iterator end() = 0; /// Returns the node_const_iterator associated with the trie's root node. virtual node_const_iterator node_begin() const = 0; /// Returns the node_iterator associated with the trie's root node. virtual node_iterator node_begin() = 0; /// Returns the node_const_iterator associated with a just-after leaf node. virtual node_const_iterator node_end() const = 0; /// Returns the node_iterator associated with a just-after leaf node. virtual node_iterator node_end() = 0; /// Access to the cmp_fn object. virtual const access_traits& get_access_traits() const = 0; }; #include #undef PB_DS_CLASS_C_DEC #define PB_DS_CLASS_C_DEC \ trie_order_statistics_node_update /// Functor updating ranks of entrees. template class trie_order_statistics_node_update : private PB_DS_TRIE_POLICY_BASE { private: typedef PB_DS_TRIE_POLICY_BASE base_type; public: typedef _ATraits access_traits; typedef typename access_traits::const_iterator a_const_iterator; typedef _Alloc allocator_type; typedef typename allocator_type::size_type size_type; typedef typename base_type::key_type key_type; typedef typename base_type::key_const_reference key_const_reference; typedef size_type metadata_type; typedef Node_CItr node_const_iterator; typedef Node_Itr node_iterator; typedef typename node_const_iterator::value_type const_iterator; typedef typename node_iterator::value_type iterator; /// Finds an entry by __order. Returns a const_iterator to the /// entry with the __order order, or a const_iterator to the /// container object's end if order is at least the size of the /// container object. inline const_iterator find_by_order(size_type) const; /// Finds an entry by __order. Returns an iterator to the entry /// with the __order order, or an iterator to the container /// object's end if order is at least the size of the container /// object. inline iterator find_by_order(size_type); /// Returns the order of a key within a sequence. For exapmle, if /// r_key is the smallest key, this method will return 0; if r_key /// is a key between the smallest and next key, this method will /// return 1; if r_key is a key larger than the largest key, this /// method will return the size of r_c. inline size_type order_of_key(key_const_reference) const; /// Returns the order of a prefix within a sequence. For exapmle, /// if [b, e] is the smallest prefix, this method will return 0; if /// r_key is a key between the smallest and next key, this method /// will return 1; if r_key is a key larger than the largest key, /// this method will return the size of r_c. inline size_type order_of_prefix(a_const_iterator, a_const_iterator) const; protected: /// Updates the rank of a node through a node_iterator node_it; /// end_nd_it is the end node iterator. inline void operator()(node_iterator, node_const_iterator) const; private: typedef typename base_type::const_reference const_reference; typedef typename base_type::const_pointer const_pointer; typedef typename _Alloc::template rebind __rebind_m; typedef typename __rebind_m::other __rebind_ma; typedef typename __rebind_ma::const_reference metadata_const_reference; typedef typename __rebind_ma::reference metadata_reference; /// Returns true if the container is empty. virtual bool empty() const = 0; /// Returns the iterator associated with the trie's first element. virtual iterator begin() = 0; /// Returns the iterator associated with the trie's /// just-after-last element. virtual iterator end() = 0; /// Returns the node_const_iterator associated with the trie's root node. virtual node_const_iterator node_begin() const = 0; /// Returns the node_iterator associated with the trie's root node. virtual node_iterator node_begin() = 0; /// Returns the node_const_iterator associated with a just-after /// leaf node. virtual node_const_iterator node_end() const = 0; /// Returns the node_iterator associated with a just-after leaf node. virtual node_iterator node_end() = 0; /// Access to the cmp_fn object. virtual access_traits& get_access_traits() = 0; }; #include #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #undef PB_DS_TRIE_POLICY_BASE } // namespace __gnu_pbds #endif PK!igZKZK8/ext/algorithmnu[// Algorithm extensions -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file ext/algorithm * This file is a GNU extension to the Standard C++ Library (possibly * containing extensions from the HP/SGI STL subset). */ #ifndef _EXT_ALGORITHM #define _EXT_ALGORITHM 1 #pragma GCC system_header #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using std::ptrdiff_t; using std::min; using std::pair; using std::input_iterator_tag; using std::random_access_iterator_tag; using std::iterator_traits; //-------------------------------------------------- // copy_n (not part of the C++ standard) template pair<_InputIterator, _OutputIterator> __copy_n(_InputIterator __first, _Size __count, _OutputIterator __result, input_iterator_tag) { for ( ; __count > 0; --__count) { *__result = *__first; ++__first; ++__result; } return pair<_InputIterator, _OutputIterator>(__first, __result); } template inline pair<_RAIterator, _OutputIterator> __copy_n(_RAIterator __first, _Size __count, _OutputIterator __result, random_access_iterator_tag) { _RAIterator __last = __first + __count; return pair<_RAIterator, _OutputIterator>(__last, std::copy(__first, __last, __result)); } /** * @brief Copies the range [first,first+count) into [result,result+count). * @param __first An input iterator. * @param __count The number of elements to copy. * @param __result An output iterator. * @return A std::pair composed of first+count and result+count. * * This is an SGI extension. * This inline function will boil down to a call to @c memmove whenever * possible. Failing that, if random access iterators are passed, then the * loop count will be known (and therefore a candidate for compiler * optimizations such as unrolling). * @ingroup SGIextensions */ template inline pair<_InputIterator, _OutputIterator> copy_n(_InputIterator __first, _Size __count, _OutputIterator __result) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_InputIterator>::value_type>) return __gnu_cxx::__copy_n(__first, __count, __result, std::__iterator_category(__first)); } template int __lexicographical_compare_3way(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2) { while (__first1 != __last1 && __first2 != __last2) { if (*__first1 < *__first2) return -1; if (*__first2 < *__first1) return 1; ++__first1; ++__first2; } if (__first2 == __last2) return !(__first1 == __last1); else return -1; } inline int __lexicographical_compare_3way(const unsigned char* __first1, const unsigned char* __last1, const unsigned char* __first2, const unsigned char* __last2) { const ptrdiff_t __len1 = __last1 - __first1; const ptrdiff_t __len2 = __last2 - __first2; const int __result = __builtin_memcmp(__first1, __first2, min(__len1, __len2)); return __result != 0 ? __result : (__len1 == __len2 ? 0 : (__len1 < __len2 ? -1 : 1)); } inline int __lexicographical_compare_3way(const char* __first1, const char* __last1, const char* __first2, const char* __last2) { #if CHAR_MAX == SCHAR_MAX return __lexicographical_compare_3way((const signed char*) __first1, (const signed char*) __last1, (const signed char*) __first2, (const signed char*) __last2); #else return __lexicographical_compare_3way((const unsigned char*) __first1, (const unsigned char*) __last1, (const unsigned char*) __first2, (const unsigned char*) __last2); #endif } /** * @brief @c memcmp on steroids. * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __last2 An input iterator. * @return An int, as with @c memcmp. * * The return value will be less than zero if the first range is * lexigraphically less than the second, greater than zero * if the second range is lexigraphically less than the * first, and zero otherwise. * This is an SGI extension. * @ingroup SGIextensions */ template int lexicographical_compare_3way(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_InputIterator1>::value_type>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return __lexicographical_compare_3way(__first1, __last1, __first2, __last2); } // count and count_if: this version, whose return type is void, was present // in the HP STL, and is retained as an extension for backward compatibility. template void count(_InputIterator __first, _InputIterator __last, const _Tp& __value, _Size& __n) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_EqualityComparableConcept< typename iterator_traits<_InputIterator>::value_type >) __glibcxx_function_requires(_EqualityComparableConcept<_Tp>) __glibcxx_requires_valid_range(__first, __last); for ( ; __first != __last; ++__first) if (*__first == __value) ++__n; } template void count_if(_InputIterator __first, _InputIterator __last, _Predicate __pred, _Size& __n) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_UnaryPredicateConcept<_Predicate, typename iterator_traits<_InputIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); for ( ; __first != __last; ++__first) if (__pred(*__first)) ++__n; } // random_sample and random_sample_n (extensions, not part of the standard). /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template _OutputIterator random_sample_n(_ForwardIterator __first, _ForwardIterator __last, _OutputIterator __out, const _Distance __n) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); _Distance __remaining = std::distance(__first, __last); _Distance __m = min(__n, __remaining); while (__m > 0) { if ((std::rand() % __remaining) < __m) { *__out = *__first; ++__out; --__m; } --__remaining; ++__first; } return __out; } /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template _OutputIterator random_sample_n(_ForwardIterator __first, _ForwardIterator __last, _OutputIterator __out, const _Distance __n, _RandomNumberGenerator& __rand) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_function_requires(_UnaryFunctionConcept< _RandomNumberGenerator, _Distance, _Distance>) __glibcxx_requires_valid_range(__first, __last); _Distance __remaining = std::distance(__first, __last); _Distance __m = min(__n, __remaining); while (__m > 0) { if (__rand(__remaining) < __m) { *__out = *__first; ++__out; --__m; } --__remaining; ++__first; } return __out; } template _RandomAccessIterator __random_sample(_InputIterator __first, _InputIterator __last, _RandomAccessIterator __out, const _Distance __n) { _Distance __m = 0; _Distance __t = __n; for ( ; __first != __last && __m < __n; ++__m, ++__first) __out[__m] = *__first; while (__first != __last) { ++__t; _Distance __M = std::rand() % (__t); if (__M < __n) __out[__M] = *__first; ++__first; } return __out + __m; } template _RandomAccessIterator __random_sample(_InputIterator __first, _InputIterator __last, _RandomAccessIterator __out, _RandomNumberGenerator& __rand, const _Distance __n) { // concept requirements __glibcxx_function_requires(_UnaryFunctionConcept< _RandomNumberGenerator, _Distance, _Distance>) _Distance __m = 0; _Distance __t = __n; for ( ; __first != __last && __m < __n; ++__m, ++__first) __out[__m] = *__first; while (__first != __last) { ++__t; _Distance __M = __rand(__t); if (__M < __n) __out[__M] = *__first; ++__first; } return __out + __m; } /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template inline _RandomAccessIterator random_sample(_InputIterator __first, _InputIterator __last, _RandomAccessIterator __out_first, _RandomAccessIterator __out_last) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_valid_range(__out_first, __out_last); return __random_sample(__first, __last, __out_first, __out_last - __out_first); } /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template inline _RandomAccessIterator random_sample(_InputIterator __first, _InputIterator __last, _RandomAccessIterator __out_first, _RandomAccessIterator __out_last, _RandomNumberGenerator& __rand) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_valid_range(__out_first, __out_last); return __random_sample(__first, __last, __out_first, __rand, __out_last - __out_first); } #if __cplusplus >= 201103L using std::is_heap; #else /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template inline bool is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__is_heap(__first, __last - __first); } /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template inline bool is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _StrictWeakOrdering __comp) { // concept requirements __glibcxx_function_requires(_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_StrictWeakOrdering, typename iterator_traits<_RandomAccessIterator>::value_type, typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__is_heap(__first, __comp, __last - __first); } #endif #if __cplusplus >= 201103L using std::is_sorted; #else // is_sorted, a predicated testing whether a range is sorted in // nondescending order. This is an extension, not part of the C++ // standard. /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template bool is_sorted(_ForwardIterator __first, _ForwardIterator __last) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); if (__first == __last) return true; _ForwardIterator __next = __first; for (++__next; __next != __last; __first = __next, ++__next) if (*__next < *__first) return false; return true; } /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template bool is_sorted(_ForwardIterator __first, _ForwardIterator __last, _StrictWeakOrdering __comp) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_BinaryPredicateConcept<_StrictWeakOrdering, typename iterator_traits<_ForwardIterator>::value_type, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); if (__first == __last) return true; _ForwardIterator __next = __first; for (++__next; __next != __last; __first = __next, ++__next) if (__comp(*__next, *__first)) return false; return true; } #endif // C++11 /** * @brief Find the median of three values. * @param __a A value. * @param __b A value. * @param __c A value. * @return One of @p a, @p b or @p c. * * If @c {l,m,n} is some convolution of @p {a,b,c} such that @c l<=m<=n * then the value returned will be @c m. * This is an SGI extension. * @ingroup SGIextensions */ template const _Tp& __median(const _Tp& __a, const _Tp& __b, const _Tp& __c) { // concept requirements __glibcxx_function_requires(_LessThanComparableConcept<_Tp>) if (__a < __b) if (__b < __c) return __b; else if (__a < __c) return __c; else return __a; else if (__a < __c) return __a; else if (__b < __c) return __c; else return __b; } /** * @brief Find the median of three values using a predicate for comparison. * @param __a A value. * @param __b A value. * @param __c A value. * @param __comp A binary predicate. * @return One of @p a, @p b or @p c. * * If @c {l,m,n} is some convolution of @p {a,b,c} such that @p comp(l,m) * and @p comp(m,n) are both true then the value returned will be @c m. * This is an SGI extension. * @ingroup SGIextensions */ template const _Tp& __median(const _Tp& __a, const _Tp& __b, const _Tp& __c, _Compare __comp) { // concept requirements __glibcxx_function_requires(_BinaryFunctionConcept<_Compare, bool, _Tp, _Tp>) if (__comp(__a, __b)) if (__comp(__b, __c)) return __b; else if (__comp(__a, __c)) return __c; else return __a; else if (__comp(__a, __c)) return __a; else if (__comp(__b, __c)) return __c; else return __b; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _EXT_ALGORITHM */ PK!yK8/ext/aligned_buffer.hnu[// Aligned memory buffer -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/aligned_buffer.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _ALIGNED_BUFFER_H #define _ALIGNED_BUFFER_H 1 #pragma GCC system_header #if __cplusplus >= 201103L # include #else # include #endif namespace __gnu_cxx { // A utility type containing a POD object that can hold an object of type // _Tp initialized via placement new or allocator_traits::construct. // Intended for use as a data member subobject, use __aligned_buffer for // complete objects. template struct __aligned_membuf { // Target macro ADJUST_FIELD_ALIGN can produce different alignment for // types when used as class members. __aligned_membuf is intended // for use as a class member, so align the buffer as for a class member. // Since GCC 8 we could just use alignof(_Tp) instead, but older // versions of non-GNU compilers might still need this trick. struct _Tp2 { _Tp _M_t; }; alignas(__alignof__(_Tp2::_M_t)) unsigned char _M_storage[sizeof(_Tp)]; __aligned_membuf() = default; // Can be used to avoid value-initialization zeroing _M_storage. __aligned_membuf(std::nullptr_t) { } void* _M_addr() noexcept { return static_cast(&_M_storage); } const void* _M_addr() const noexcept { return static_cast(&_M_storage); } _Tp* _M_ptr() noexcept { return static_cast<_Tp*>(_M_addr()); } const _Tp* _M_ptr() const noexcept { return static_cast(_M_addr()); } }; #if _GLIBCXX_INLINE_VERSION template using __aligned_buffer = __aligned_membuf<_Tp>; #else // Similar to __aligned_membuf but aligned for complete objects, not members. // This type is used in , , // and , but ideally they would use __aligned_membuf // instead, as it has smaller size for some types on some targets. // This type is still used to avoid an ABI change. template struct __aligned_buffer : std::aligned_storage { typename std::aligned_storage::type _M_storage; __aligned_buffer() = default; // Can be used to avoid value-initialization __aligned_buffer(std::nullptr_t) { } void* _M_addr() noexcept { return static_cast(&_M_storage); } const void* _M_addr() const noexcept { return static_cast(&_M_storage); } _Tp* _M_ptr() noexcept { return static_cast<_Tp*>(_M_addr()); } const _Tp* _M_ptr() const noexcept { return static_cast(_M_addr()); } }; #endif } // namespace #endif /* _ALIGNED_BUFFER_H */ PK!FF8/ext/alloc_traits.hnu[// Allocator traits -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/alloc_traits.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _EXT_ALLOC_TRAITS_H #define _EXT_ALLOC_TRAITS_H 1 #pragma GCC system_header #if __cplusplus >= 201103L # include # include #else # include // for __alloc_swap #endif namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief Uniform interface to C++98 and C++11 allocators. * @ingroup allocators */ template struct __alloc_traits #if __cplusplus >= 201103L : std::allocator_traits<_Alloc> #endif { typedef _Alloc allocator_type; #if __cplusplus >= 201103L typedef std::allocator_traits<_Alloc> _Base_type; typedef typename _Base_type::value_type value_type; typedef typename _Base_type::pointer pointer; typedef typename _Base_type::const_pointer const_pointer; typedef typename _Base_type::size_type size_type; typedef typename _Base_type::difference_type difference_type; // C++11 allocators do not define reference or const_reference typedef value_type& reference; typedef const value_type& const_reference; using _Base_type::allocate; using _Base_type::deallocate; using _Base_type::construct; using _Base_type::destroy; using _Base_type::max_size; private: template using __is_custom_pointer = std::__and_, std::__not_>>; public: // overload construct for non-standard pointer types template static typename std::enable_if<__is_custom_pointer<_Ptr>::value>::type construct(_Alloc& __a, _Ptr __p, _Args&&... __args) { _Base_type::construct(__a, std::__to_address(__p), std::forward<_Args>(__args)...); } // overload destroy for non-standard pointer types template static typename std::enable_if<__is_custom_pointer<_Ptr>::value>::type destroy(_Alloc& __a, _Ptr __p) { _Base_type::destroy(__a, std::__to_address(__p)); } static _Alloc _S_select_on_copy(const _Alloc& __a) { return _Base_type::select_on_container_copy_construction(__a); } static void _S_on_swap(_Alloc& __a, _Alloc& __b) { std::__alloc_on_swap(__a, __b); } static constexpr bool _S_propagate_on_copy_assign() { return _Base_type::propagate_on_container_copy_assignment::value; } static constexpr bool _S_propagate_on_move_assign() { return _Base_type::propagate_on_container_move_assignment::value; } static constexpr bool _S_propagate_on_swap() { return _Base_type::propagate_on_container_swap::value; } static constexpr bool _S_always_equal() { return _Base_type::is_always_equal::value; } static constexpr bool _S_nothrow_move() { return _S_propagate_on_move_assign() || _S_always_equal(); } template struct rebind { typedef typename _Base_type::template rebind_alloc<_Tp> other; }; #else typedef typename _Alloc::pointer pointer; typedef typename _Alloc::const_pointer const_pointer; typedef typename _Alloc::value_type value_type; typedef typename _Alloc::reference reference; typedef typename _Alloc::const_reference const_reference; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; static pointer allocate(_Alloc& __a, size_type __n) { return __a.allocate(__n); } static void deallocate(_Alloc& __a, pointer __p, size_type __n) { __a.deallocate(__p, __n); } template static void construct(_Alloc& __a, pointer __p, const _Tp& __arg) { __a.construct(__p, __arg); } static void destroy(_Alloc& __a, pointer __p) { __a.destroy(__p); } static size_type max_size(const _Alloc& __a) { return __a.max_size(); } static const _Alloc& _S_select_on_copy(const _Alloc& __a) { return __a; } static void _S_on_swap(_Alloc& __a, _Alloc& __b) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 431. Swapping containers with unequal allocators. std::__alloc_swap<_Alloc>::_S_do_it(__a, __b); } template struct rebind { typedef typename _Alloc::template rebind<_Tp>::other other; }; #endif }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace __gnu_cxx #endif PK!}h  8/ext/array_allocator.hnu[// array allocator -*- C++ -*- // Copyright (C) 2004-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/array_allocator.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _ARRAY_ALLOCATOR_H #define _ARRAY_ALLOCATOR_H 1 #include #include #include #include #include #if __cplusplus >= 201103L #include #endif // Suppress deprecated warning for this file. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using std::size_t; using std::ptrdiff_t; /// Base class. template class array_allocator_base { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Tp* pointer; typedef const _Tp* const_pointer; typedef _Tp& reference; typedef const _Tp& const_reference; typedef _Tp value_type; pointer address(reference __x) const _GLIBCXX_NOEXCEPT { return std::__addressof(__x); } const_pointer address(const_reference __x) const _GLIBCXX_NOEXCEPT { return std::__addressof(__x); } void deallocate(pointer, size_type) { // Does nothing. } size_type max_size() const _GLIBCXX_USE_NOEXCEPT { return size_t(-1) / sizeof(_Tp); } #if __cplusplus >= 201103L template void construct(_Up* __p, _Args&&... __args) { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); } template void destroy(_Up* __p) { __p->~_Up(); } #else // _GLIBCXX_RESOLVE_LIB_DEFECTS // 402. wrong new expression in [some_] allocator::construct void construct(pointer __p, const _Tp& __val) { ::new((void *)__p) value_type(__val); } void destroy(pointer __p) { __p->~_Tp(); } #endif } _GLIBCXX_DEPRECATED; /** * @brief An allocator that uses previously allocated memory. * This memory can be externally, globally, or otherwise allocated. * @ingroup allocators */ template > class array_allocator : public array_allocator_base<_Tp> { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Tp* pointer; typedef const _Tp* const_pointer; typedef _Tp& reference; typedef const _Tp& const_reference; typedef _Tp value_type; typedef _Array array_type; #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2103. std::allocator propagate_on_container_move_assignment typedef std::true_type propagate_on_container_move_assignment; typedef std::true_type is_always_equal; #endif private: array_type* _M_array; size_type _M_used; public: template struct rebind { typedef array_allocator<_Tp1, _Array1> other _GLIBCXX_DEPRECATED; } _GLIBCXX_DEPRECATED; array_allocator(array_type* __array = 0) _GLIBCXX_USE_NOEXCEPT : _M_array(__array), _M_used(size_type()) { } array_allocator(const array_allocator& __o) _GLIBCXX_USE_NOEXCEPT : _M_array(__o._M_array), _M_used(__o._M_used) { } template array_allocator(const array_allocator<_Tp1, _Array1>&) _GLIBCXX_USE_NOEXCEPT : _M_array(0), _M_used(size_type()) { } ~array_allocator() _GLIBCXX_USE_NOEXCEPT { } pointer allocate(size_type __n, const void* = 0) { if (_M_array == 0 || _M_used + __n > _M_array->size()) std::__throw_bad_alloc(); pointer __ret = _M_array->begin() + _M_used; _M_used += __n; return __ret; } } _GLIBCXX_DEPRECATED; template inline bool operator==(const array_allocator<_Tp, _Array>&, const array_allocator<_Tp, _Array>&) { return true; } template inline bool operator!=(const array_allocator<_Tp, _Array>&, const array_allocator<_Tp, _Array>&) { return false; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #pragma GCC diagnostic pop #endif PK!bȝ 8/ext/atomicity.hnu[// Support for atomic operations -*- C++ -*- // Copyright (C) 2004-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/atomicity.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _GLIBCXX_ATOMICITY_H #define _GLIBCXX_ATOMICITY_H 1 #pragma GCC system_header #include #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Functions for portable atomic access. // To abstract locking primitives across all thread policies, use: // __exchange_and_add_dispatch // __atomic_add_dispatch #ifdef _GLIBCXX_ATOMIC_BUILTINS static inline _Atomic_word __exchange_and_add(volatile _Atomic_word* __mem, int __val) { return __atomic_fetch_add(__mem, __val, __ATOMIC_ACQ_REL); } static inline void __atomic_add(volatile _Atomic_word* __mem, int __val) { __atomic_fetch_add(__mem, __val, __ATOMIC_ACQ_REL); } #else _Atomic_word __attribute__ ((__unused__)) __exchange_and_add(volatile _Atomic_word*, int) throw (); void __attribute__ ((__unused__)) __atomic_add(volatile _Atomic_word*, int) throw (); #endif static inline _Atomic_word __exchange_and_add_single(_Atomic_word* __mem, int __val) { _Atomic_word __result = *__mem; *__mem += __val; return __result; } static inline void __atomic_add_single(_Atomic_word* __mem, int __val) { *__mem += __val; } static inline _Atomic_word __attribute__ ((__unused__)) __exchange_and_add_dispatch(_Atomic_word* __mem, int __val) { #ifdef __GTHREADS if (__gthread_active_p()) return __exchange_and_add(__mem, __val); else return __exchange_and_add_single(__mem, __val); #else return __exchange_and_add_single(__mem, __val); #endif } static inline void __attribute__ ((__unused__)) __atomic_add_dispatch(_Atomic_word* __mem, int __val) { #ifdef __GTHREADS if (__gthread_active_p()) __atomic_add(__mem, __val); else __atomic_add_single(__mem, __val); #else __atomic_add_single(__mem, __val); #endif } _GLIBCXX_END_NAMESPACE_VERSION } // namespace // Even if the CPU doesn't need a memory barrier, we need to ensure // that the compiler doesn't reorder memory accesses across the // barriers. #ifndef _GLIBCXX_READ_MEM_BARRIER #define _GLIBCXX_READ_MEM_BARRIER __atomic_thread_fence (__ATOMIC_ACQUIRE) #endif #ifndef _GLIBCXX_WRITE_MEM_BARRIER #define _GLIBCXX_WRITE_MEM_BARRIER __atomic_thread_fence (__ATOMIC_RELEASE) #endif #endif PK!6oN|N|8/ext/bitmap_allocator.hnu[// Bitmap Allocator. -*- C++ -*- // Copyright (C) 2004-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/bitmap_allocator.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _BITMAP_ALLOCATOR_H #define _BITMAP_ALLOCATOR_H 1 #include // For std::pair. #include // For __throw_bad_alloc(). #include // For greater_equal, and less_equal. #include // For operator new. #include // _GLIBCXX_DEBUG_ASSERT #include #include /** @brief The constant in the expression below is the alignment * required in bytes. */ #define _BALLOC_ALIGN_BYTES 8 namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using std::size_t; using std::ptrdiff_t; namespace __detail { /** @class __mini_vector bitmap_allocator.h bitmap_allocator.h * * @brief __mini_vector<> is a stripped down version of the * full-fledged std::vector<>. * * It is to be used only for built-in types or PODs. Notable * differences are: * * 1. Not all accessor functions are present. * 2. Used ONLY for PODs. * 3. No Allocator template argument. Uses ::operator new() to get * memory, and ::operator delete() to free it. * Caveat: The dtor does NOT free the memory allocated, so this a * memory-leaking vector! */ template class __mini_vector { __mini_vector(const __mini_vector&); __mini_vector& operator=(const __mini_vector&); public: typedef _Tp value_type; typedef _Tp* pointer; typedef _Tp& reference; typedef const _Tp& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef pointer iterator; private: pointer _M_start; pointer _M_finish; pointer _M_end_of_storage; size_type _M_space_left() const throw() { return _M_end_of_storage - _M_finish; } pointer allocate(size_type __n) { return static_cast(::operator new(__n * sizeof(_Tp))); } void deallocate(pointer __p, size_type) { ::operator delete(__p); } public: // Members used: size(), push_back(), pop_back(), // insert(iterator, const_reference), erase(iterator), // begin(), end(), back(), operator[]. __mini_vector() : _M_start(0), _M_finish(0), _M_end_of_storage(0) { } size_type size() const throw() { return _M_finish - _M_start; } iterator begin() const throw() { return this->_M_start; } iterator end() const throw() { return this->_M_finish; } reference back() const throw() { return *(this->end() - 1); } reference operator[](const size_type __pos) const throw() { return this->_M_start[__pos]; } void insert(iterator __pos, const_reference __x); void push_back(const_reference __x) { if (this->_M_space_left()) { *this->end() = __x; ++this->_M_finish; } else this->insert(this->end(), __x); } void pop_back() throw() { --this->_M_finish; } void erase(iterator __pos) throw(); void clear() throw() { this->_M_finish = this->_M_start; } }; // Out of line function definitions. template void __mini_vector<_Tp>:: insert(iterator __pos, const_reference __x) { if (this->_M_space_left()) { size_type __to_move = this->_M_finish - __pos; iterator __dest = this->end(); iterator __src = this->end() - 1; ++this->_M_finish; while (__to_move) { *__dest = *__src; --__dest; --__src; --__to_move; } *__pos = __x; } else { size_type __new_size = this->size() ? this->size() * 2 : 1; iterator __new_start = this->allocate(__new_size); iterator __first = this->begin(); iterator __start = __new_start; while (__first != __pos) { *__start = *__first; ++__start; ++__first; } *__start = __x; ++__start; while (__first != this->end()) { *__start = *__first; ++__start; ++__first; } if (this->_M_start) this->deallocate(this->_M_start, this->size()); this->_M_start = __new_start; this->_M_finish = __start; this->_M_end_of_storage = this->_M_start + __new_size; } } template void __mini_vector<_Tp>:: erase(iterator __pos) throw() { while (__pos + 1 != this->end()) { *__pos = __pos[1]; ++__pos; } --this->_M_finish; } template struct __mv_iter_traits { typedef typename _Tp::value_type value_type; typedef typename _Tp::difference_type difference_type; }; template struct __mv_iter_traits<_Tp*> { typedef _Tp value_type; typedef ptrdiff_t difference_type; }; enum { bits_per_byte = 8, bits_per_block = sizeof(size_t) * size_t(bits_per_byte) }; template _ForwardIterator __lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __val, _Compare __comp) { typedef typename __mv_iter_traits<_ForwardIterator>::difference_type _DistanceType; _DistanceType __len = __last - __first; _DistanceType __half; _ForwardIterator __middle; while (__len > 0) { __half = __len >> 1; __middle = __first; __middle += __half; if (__comp(*__middle, __val)) { __first = __middle; ++__first; __len = __len - __half - 1; } else __len = __half; } return __first; } /** @brief The number of Blocks pointed to by the address pair * passed to the function. */ template inline size_t __num_blocks(_AddrPair __ap) { return (__ap.second - __ap.first) + 1; } /** @brief The number of Bit-maps pointed to by the address pair * passed to the function. */ template inline size_t __num_bitmaps(_AddrPair __ap) { return __num_blocks(__ap) / size_t(bits_per_block); } // _Tp should be a pointer type. template class _Inclusive_between : public std::unary_function, bool> { typedef _Tp pointer; pointer _M_ptr_value; typedef typename std::pair<_Tp, _Tp> _Block_pair; public: _Inclusive_between(pointer __ptr) : _M_ptr_value(__ptr) { } bool operator()(_Block_pair __bp) const throw() { if (std::less_equal()(_M_ptr_value, __bp.second) && std::greater_equal()(_M_ptr_value, __bp.first)) return true; else return false; } }; // Used to pass a Functor to functions by reference. template class _Functor_Ref : public std::unary_function { _Functor& _M_fref; public: typedef typename _Functor::argument_type argument_type; typedef typename _Functor::result_type result_type; _Functor_Ref(_Functor& __fref) : _M_fref(__fref) { } result_type operator()(argument_type __arg) { return _M_fref(__arg); } }; /** @class _Ffit_finder bitmap_allocator.h bitmap_allocator.h * * @brief The class which acts as a predicate for applying the * first-fit memory allocation policy for the bitmap allocator. */ // _Tp should be a pointer type, and _Alloc is the Allocator for // the vector. template class _Ffit_finder : public std::unary_function, bool> { typedef typename std::pair<_Tp, _Tp> _Block_pair; typedef typename __detail::__mini_vector<_Block_pair> _BPVector; typedef typename _BPVector::difference_type _Counter_type; size_t* _M_pbitmap; _Counter_type _M_data_offset; public: _Ffit_finder() : _M_pbitmap(0), _M_data_offset(0) { } bool operator()(_Block_pair __bp) throw() { // Set the _rover to the last physical location bitmap, // which is the bitmap which belongs to the first free // block. Thus, the bitmaps are in exact reverse order of // the actual memory layout. So, we count down the bitmaps, // which is the same as moving up the memory. // If the used count stored at the start of the Bit Map headers // is equal to the number of Objects that the current Block can // store, then there is definitely no space for another single // object, so just return false. _Counter_type __diff = __detail::__num_bitmaps(__bp); if (*(reinterpret_cast (__bp.first) - (__diff + 1)) == __detail::__num_blocks(__bp)) return false; size_t* __rover = reinterpret_cast(__bp.first) - 1; for (_Counter_type __i = 0; __i < __diff; ++__i) { _M_data_offset = __i; if (*__rover) { _M_pbitmap = __rover; return true; } --__rover; } return false; } size_t* _M_get() const throw() { return _M_pbitmap; } _Counter_type _M_offset() const throw() { return _M_data_offset * size_t(bits_per_block); } }; /** @class _Bitmap_counter bitmap_allocator.h bitmap_allocator.h * * @brief The bitmap counter which acts as the bitmap * manipulator, and manages the bit-manipulation functions and * the searching and identification functions on the bit-map. */ // _Tp should be a pointer type. template class _Bitmap_counter { typedef typename __detail::__mini_vector > _BPVector; typedef typename _BPVector::size_type _Index_type; typedef _Tp pointer; _BPVector& _M_vbp; size_t* _M_curr_bmap; size_t* _M_last_bmap_in_block; _Index_type _M_curr_index; public: // Use the 2nd parameter with care. Make sure that such an // entry exists in the vector before passing that particular // index to this ctor. _Bitmap_counter(_BPVector& Rvbp, long __index = -1) : _M_vbp(Rvbp) { this->_M_reset(__index); } void _M_reset(long __index = -1) throw() { if (__index == -1) { _M_curr_bmap = 0; _M_curr_index = static_cast<_Index_type>(-1); return; } _M_curr_index = __index; _M_curr_bmap = reinterpret_cast (_M_vbp[_M_curr_index].first) - 1; _GLIBCXX_DEBUG_ASSERT(__index <= (long)_M_vbp.size() - 1); _M_last_bmap_in_block = _M_curr_bmap - ((_M_vbp[_M_curr_index].second - _M_vbp[_M_curr_index].first + 1) / size_t(bits_per_block) - 1); } // Dangerous Function! Use with extreme care. Pass to this // function ONLY those values that are known to be correct, // otherwise this will mess up big time. void _M_set_internal_bitmap(size_t* __new_internal_marker) throw() { _M_curr_bmap = __new_internal_marker; } bool _M_finished() const throw() { return(_M_curr_bmap == 0); } _Bitmap_counter& operator++() throw() { if (_M_curr_bmap == _M_last_bmap_in_block) { if (++_M_curr_index == _M_vbp.size()) _M_curr_bmap = 0; else this->_M_reset(_M_curr_index); } else --_M_curr_bmap; return *this; } size_t* _M_get() const throw() { return _M_curr_bmap; } pointer _M_base() const throw() { return _M_vbp[_M_curr_index].first; } _Index_type _M_offset() const throw() { return size_t(bits_per_block) * ((reinterpret_cast(this->_M_base()) - _M_curr_bmap) - 1); } _Index_type _M_where() const throw() { return _M_curr_index; } }; /** @brief Mark a memory address as allocated by re-setting the * corresponding bit in the bit-map. */ inline void __bit_allocate(size_t* __pbmap, size_t __pos) throw() { size_t __mask = 1 << __pos; __mask = ~__mask; *__pbmap &= __mask; } /** @brief Mark a memory address as free by setting the * corresponding bit in the bit-map. */ inline void __bit_free(size_t* __pbmap, size_t __pos) throw() { size_t __mask = 1 << __pos; *__pbmap |= __mask; } } // namespace __detail /** @brief Generic Version of the bsf instruction. */ inline size_t _Bit_scan_forward(size_t __num) { return static_cast(__builtin_ctzl(__num)); } /** @class free_list bitmap_allocator.h bitmap_allocator.h * * @brief The free list class for managing chunks of memory to be * given to and returned by the bitmap_allocator. */ class free_list { public: typedef size_t* value_type; typedef __detail::__mini_vector vector_type; typedef vector_type::iterator iterator; typedef __mutex __mutex_type; private: struct _LT_pointer_compare { bool operator()(const size_t* __pui, const size_t __cui) const throw() { return *__pui < __cui; } }; #if defined __GTHREADS __mutex_type& _M_get_mutex() { static __mutex_type _S_mutex; return _S_mutex; } #endif vector_type& _M_get_free_list() { static vector_type _S_free_list; return _S_free_list; } /** @brief Performs validation of memory based on their size. * * @param __addr The pointer to the memory block to be * validated. * * Validates the memory block passed to this function and * appropriately performs the action of managing the free list of * blocks by adding this block to the free list or deleting this * or larger blocks from the free list. */ void _M_validate(size_t* __addr) throw() { vector_type& __free_list = _M_get_free_list(); const vector_type::size_type __max_size = 64; if (__free_list.size() >= __max_size) { // Ok, the threshold value has been reached. We determine // which block to remove from the list of free blocks. if (*__addr >= *__free_list.back()) { // Ok, the new block is greater than or equal to the // last block in the list of free blocks. We just free // the new block. ::operator delete(static_cast(__addr)); return; } else { // Deallocate the last block in the list of free lists, // and insert the new one in its correct position. ::operator delete(static_cast(__free_list.back())); __free_list.pop_back(); } } // Just add the block to the list of free lists unconditionally. iterator __temp = __detail::__lower_bound (__free_list.begin(), __free_list.end(), *__addr, _LT_pointer_compare()); // We may insert the new free list before _temp; __free_list.insert(__temp, __addr); } /** @brief Decides whether the wastage of memory is acceptable for * the current memory request and returns accordingly. * * @param __block_size The size of the block available in the free * list. * * @param __required_size The required size of the memory block. * * @return true if the wastage incurred is acceptable, else returns * false. */ bool _M_should_i_give(size_t __block_size, size_t __required_size) throw() { const size_t __max_wastage_percentage = 36; if (__block_size >= __required_size && (((__block_size - __required_size) * 100 / __block_size) < __max_wastage_percentage)) return true; else return false; } public: /** @brief This function returns the block of memory to the * internal free list. * * @param __addr The pointer to the memory block that was given * by a call to the _M_get function. */ inline void _M_insert(size_t* __addr) throw() { #if defined __GTHREADS __scoped_lock __bfl_lock(_M_get_mutex()); #endif // Call _M_validate to decide what should be done with // this particular free list. this->_M_validate(reinterpret_cast(__addr) - 1); // See discussion as to why this is 1! } /** @brief This function gets a block of memory of the specified * size from the free list. * * @param __sz The size in bytes of the memory required. * * @return A pointer to the new memory block of size at least * equal to that requested. */ size_t* _M_get(size_t __sz) _GLIBCXX_THROW(std::bad_alloc); /** @brief This function just clears the internal Free List, and * gives back all the memory to the OS. */ void _M_clear(); }; // Forward declare the class. template class bitmap_allocator; // Specialize for void: template<> class bitmap_allocator { public: typedef void* pointer; typedef const void* const_pointer; // Reference-to-void members are impossible. typedef void value_type; template struct rebind { typedef bitmap_allocator<_Tp1> other; }; }; /** * @brief Bitmap Allocator, primary template. * @ingroup allocators */ template class bitmap_allocator : private free_list { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Tp* pointer; typedef const _Tp* const_pointer; typedef _Tp& reference; typedef const _Tp& const_reference; typedef _Tp value_type; typedef free_list::__mutex_type __mutex_type; template struct rebind { typedef bitmap_allocator<_Tp1> other; }; #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2103. propagate_on_container_move_assignment typedef std::true_type propagate_on_container_move_assignment; #endif private: template struct aligned_size { enum { modulus = _BSize % _AlignSize, value = _BSize + (modulus ? _AlignSize - (modulus) : 0) }; }; struct _Alloc_block { char __M_unused[aligned_size::value]; }; typedef typename std::pair<_Alloc_block*, _Alloc_block*> _Block_pair; typedef typename __detail::__mini_vector<_Block_pair> _BPVector; typedef typename _BPVector::iterator _BPiter; template static _BPiter _S_find(_Predicate __p) { _BPiter __first = _S_mem_blocks.begin(); while (__first != _S_mem_blocks.end() && !__p(*__first)) ++__first; return __first; } #if defined _GLIBCXX_DEBUG // Complexity: O(lg(N)). Where, N is the number of block of size // sizeof(value_type). void _S_check_for_free_blocks() throw() { typedef typename __detail::_Ffit_finder<_Alloc_block*> _FFF; _BPiter __bpi = _S_find(_FFF()); _GLIBCXX_DEBUG_ASSERT(__bpi == _S_mem_blocks.end()); } #endif /** @brief Responsible for exponentially growing the internal * memory pool. * * @throw std::bad_alloc. If memory can not be allocated. * * Complexity: O(1), but internally depends upon the * complexity of the function free_list::_M_get. The part where * the bitmap headers are written has complexity: O(X),where X * is the number of blocks of size sizeof(value_type) within * the newly acquired block. Having a tight bound. */ void _S_refill_pool() _GLIBCXX_THROW(std::bad_alloc) { #if defined _GLIBCXX_DEBUG _S_check_for_free_blocks(); #endif const size_t __num_bitmaps = (_S_block_size / size_t(__detail::bits_per_block)); const size_t __size_to_allocate = sizeof(size_t) + _S_block_size * sizeof(_Alloc_block) + __num_bitmaps * sizeof(size_t); size_t* __temp = reinterpret_cast(this->_M_get(__size_to_allocate)); *__temp = 0; ++__temp; // The Header information goes at the Beginning of the Block. _Block_pair __bp = std::make_pair(reinterpret_cast<_Alloc_block*> (__temp + __num_bitmaps), reinterpret_cast<_Alloc_block*> (__temp + __num_bitmaps) + _S_block_size - 1); // Fill the Vector with this information. _S_mem_blocks.push_back(__bp); for (size_t __i = 0; __i < __num_bitmaps; ++__i) __temp[__i] = ~static_cast(0); // 1 Indicates all Free. _S_block_size *= 2; } static _BPVector _S_mem_blocks; static size_t _S_block_size; static __detail::_Bitmap_counter<_Alloc_block*> _S_last_request; static typename _BPVector::size_type _S_last_dealloc_index; #if defined __GTHREADS static __mutex_type _S_mut; #endif public: /** @brief Allocates memory for a single object of size * sizeof(_Tp). * * @throw std::bad_alloc. If memory can not be allocated. * * Complexity: Worst case complexity is O(N), but that * is hardly ever hit. If and when this particular case is * encountered, the next few cases are guaranteed to have a * worst case complexity of O(1)! That's why this function * performs very well on average. You can consider this * function to have a complexity referred to commonly as: * Amortized Constant time. */ pointer _M_allocate_single_object() _GLIBCXX_THROW(std::bad_alloc) { #if defined __GTHREADS __scoped_lock __bit_lock(_S_mut); #endif // The algorithm is something like this: The last_request // variable points to the last accessed Bit Map. When such a // condition occurs, we try to find a free block in the // current bitmap, or succeeding bitmaps until the last bitmap // is reached. If no free block turns up, we resort to First // Fit method. // WARNING: Do not re-order the condition in the while // statement below, because it relies on C++'s short-circuit // evaluation. The return from _S_last_request->_M_get() will // NOT be dereference able if _S_last_request->_M_finished() // returns true. This would inevitably lead to a NULL pointer // dereference if tinkered with. while (_S_last_request._M_finished() == false && (*(_S_last_request._M_get()) == 0)) _S_last_request.operator++(); if (__builtin_expect(_S_last_request._M_finished() == true, false)) { // Fall Back to First Fit algorithm. typedef typename __detail::_Ffit_finder<_Alloc_block*> _FFF; _FFF __fff; _BPiter __bpi = _S_find(__detail::_Functor_Ref<_FFF>(__fff)); if (__bpi != _S_mem_blocks.end()) { // Search was successful. Ok, now mark the first bit from // the right as 0, meaning Allocated. This bit is obtained // by calling _M_get() on __fff. size_t __nz_bit = _Bit_scan_forward(*__fff._M_get()); __detail::__bit_allocate(__fff._M_get(), __nz_bit); _S_last_request._M_reset(__bpi - _S_mem_blocks.begin()); // Now, get the address of the bit we marked as allocated. pointer __ret = reinterpret_cast (__bpi->first + __fff._M_offset() + __nz_bit); size_t* __puse_count = reinterpret_cast (__bpi->first) - (__detail::__num_bitmaps(*__bpi) + 1); ++(*__puse_count); return __ret; } else { // Search was unsuccessful. We Add more memory to the // pool by calling _S_refill_pool(). _S_refill_pool(); // _M_Reset the _S_last_request structure to the first // free block's bit map. _S_last_request._M_reset(_S_mem_blocks.size() - 1); // Now, mark that bit as allocated. } } // _S_last_request holds a pointer to a valid bit map, that // points to a free block in memory. size_t __nz_bit = _Bit_scan_forward(*_S_last_request._M_get()); __detail::__bit_allocate(_S_last_request._M_get(), __nz_bit); pointer __ret = reinterpret_cast (_S_last_request._M_base() + _S_last_request._M_offset() + __nz_bit); size_t* __puse_count = reinterpret_cast (_S_mem_blocks[_S_last_request._M_where()].first) - (__detail:: __num_bitmaps(_S_mem_blocks[_S_last_request._M_where()]) + 1); ++(*__puse_count); return __ret; } /** @brief Deallocates memory that belongs to a single object of * size sizeof(_Tp). * * Complexity: O(lg(N)), but the worst case is not hit * often! This is because containers usually deallocate memory * close to each other and this case is handled in O(1) time by * the deallocate function. */ void _M_deallocate_single_object(pointer __p) throw() { #if defined __GTHREADS __scoped_lock __bit_lock(_S_mut); #endif _Alloc_block* __real_p = reinterpret_cast<_Alloc_block*>(__p); typedef typename _BPVector::iterator _Iterator; typedef typename _BPVector::difference_type _Difference_type; _Difference_type __diff; long __displacement; _GLIBCXX_DEBUG_ASSERT(_S_last_dealloc_index >= 0); __detail::_Inclusive_between<_Alloc_block*> __ibt(__real_p); if (__ibt(_S_mem_blocks[_S_last_dealloc_index])) { _GLIBCXX_DEBUG_ASSERT(_S_last_dealloc_index <= _S_mem_blocks.size() - 1); // Initial Assumption was correct! __diff = _S_last_dealloc_index; __displacement = __real_p - _S_mem_blocks[__diff].first; } else { _Iterator _iter = _S_find(__ibt); _GLIBCXX_DEBUG_ASSERT(_iter != _S_mem_blocks.end()); __diff = _iter - _S_mem_blocks.begin(); __displacement = __real_p - _S_mem_blocks[__diff].first; _S_last_dealloc_index = __diff; } // Get the position of the iterator that has been found. const size_t __rotate = (__displacement % size_t(__detail::bits_per_block)); size_t* __bitmapC = reinterpret_cast (_S_mem_blocks[__diff].first) - 1; __bitmapC -= (__displacement / size_t(__detail::bits_per_block)); __detail::__bit_free(__bitmapC, __rotate); size_t* __puse_count = reinterpret_cast (_S_mem_blocks[__diff].first) - (__detail::__num_bitmaps(_S_mem_blocks[__diff]) + 1); _GLIBCXX_DEBUG_ASSERT(*__puse_count != 0); --(*__puse_count); if (__builtin_expect(*__puse_count == 0, false)) { _S_block_size /= 2; // We can safely remove this block. // _Block_pair __bp = _S_mem_blocks[__diff]; this->_M_insert(__puse_count); _S_mem_blocks.erase(_S_mem_blocks.begin() + __diff); // Reset the _S_last_request variable to reflect the // erased block. We do this to protect future requests // after the last block has been removed from a particular // memory Chunk, which in turn has been returned to the // free list, and hence had been erased from the vector, // so the size of the vector gets reduced by 1. if ((_Difference_type)_S_last_request._M_where() >= __diff--) _S_last_request._M_reset(__diff); // If the Index into the vector of the region of memory // that might hold the next address that will be passed to // deallocated may have been invalidated due to the above // erase procedure being called on the vector, hence we // try to restore this invariant too. if (_S_last_dealloc_index >= _S_mem_blocks.size()) { _S_last_dealloc_index =(__diff != -1 ? __diff : 0); _GLIBCXX_DEBUG_ASSERT(_S_last_dealloc_index >= 0); } } } public: bitmap_allocator() _GLIBCXX_USE_NOEXCEPT { } bitmap_allocator(const bitmap_allocator&) _GLIBCXX_USE_NOEXCEPT { } template bitmap_allocator(const bitmap_allocator<_Tp1>&) _GLIBCXX_USE_NOEXCEPT { } ~bitmap_allocator() _GLIBCXX_USE_NOEXCEPT { } pointer allocate(size_type __n) { if (__n > this->max_size()) std::__throw_bad_alloc(); #if __cpp_aligned_new if (alignof(value_type) > __STDCPP_DEFAULT_NEW_ALIGNMENT__) { const size_type __b = __n * sizeof(value_type); std::align_val_t __al = std::align_val_t(alignof(value_type)); return static_cast(::operator new(__b, __al)); } #endif if (__builtin_expect(__n == 1, true)) return this->_M_allocate_single_object(); else { const size_type __b = __n * sizeof(value_type); return reinterpret_cast(::operator new(__b)); } } pointer allocate(size_type __n, typename bitmap_allocator::const_pointer) { return allocate(__n); } void deallocate(pointer __p, size_type __n) throw() { if (__builtin_expect(__p != 0, true)) { #if __cpp_aligned_new // Types with extended alignment are handled by operator delete. if (alignof(value_type) > __STDCPP_DEFAULT_NEW_ALIGNMENT__) { ::operator delete(__p, std::align_val_t(alignof(value_type))); return; } #endif if (__builtin_expect(__n == 1, true)) this->_M_deallocate_single_object(__p); else ::operator delete(__p); } } pointer address(reference __r) const _GLIBCXX_NOEXCEPT { return std::__addressof(__r); } const_pointer address(const_reference __r) const _GLIBCXX_NOEXCEPT { return std::__addressof(__r); } size_type max_size() const _GLIBCXX_USE_NOEXCEPT { return size_type(-1) / sizeof(value_type); } #if __cplusplus >= 201103L template void construct(_Up* __p, _Args&&... __args) { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); } template void destroy(_Up* __p) { __p->~_Up(); } #else void construct(pointer __p, const_reference __data) { ::new((void *)__p) value_type(__data); } void destroy(pointer __p) { __p->~value_type(); } #endif }; template bool operator==(const bitmap_allocator<_Tp1>&, const bitmap_allocator<_Tp2>&) throw() { return true; } template bool operator!=(const bitmap_allocator<_Tp1>&, const bitmap_allocator<_Tp2>&) throw() { return false; } // Static member definitions. template typename bitmap_allocator<_Tp>::_BPVector bitmap_allocator<_Tp>::_S_mem_blocks; template size_t bitmap_allocator<_Tp>::_S_block_size = 2 * size_t(__detail::bits_per_block); template typename bitmap_allocator<_Tp>::_BPVector::size_type bitmap_allocator<_Tp>::_S_last_dealloc_index = 0; template __detail::_Bitmap_counter ::_Alloc_block*> bitmap_allocator<_Tp>::_S_last_request(_S_mem_blocks); #if defined __GTHREADS template typename bitmap_allocator<_Tp>::__mutex_type bitmap_allocator<_Tp>::_S_mut; #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace __gnu_cxx #endif PK!__ 8/ext/cast.hnu[// -*- C++ -*- // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/cast.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ext/pointer.h} */ #ifndef _GLIBCXX_CAST_H #define _GLIBCXX_CAST_H 1 namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * These functions are here to allow containers to support non standard * pointer types. For normal pointers, these resolve to the use of the * standard cast operation. For other types the functions will perform * the appropriate cast to/from the custom pointer class so long as that * class meets the following conditions: * 1) has a typedef element_type which names tehe type it points to. * 2) has a get() const method which returns element_type*. * 3) has a constructor which can take one element_type* argument. */ /** * This type supports the semantics of the pointer cast operators (below.) */ template struct _Caster { typedef typename _ToType::element_type* type; }; template struct _Caster<_ToType*> { typedef _ToType* type; }; /** * Casting operations for cases where _FromType is not a standard pointer. * _ToType can be a standard or non-standard pointer. Given that _FromType * is not a pointer, it must have a get() method that returns the standard * pointer equivalent of the address it points to, and must have an * element_type typedef which names the type it points to. */ template inline _ToType __static_pointer_cast(const _FromType& __arg) { return _ToType(static_cast:: type>(__arg.get())); } template inline _ToType __dynamic_pointer_cast(const _FromType& __arg) { return _ToType(dynamic_cast:: type>(__arg.get())); } template inline _ToType __const_pointer_cast(const _FromType& __arg) { return _ToType(const_cast:: type>(__arg.get())); } template inline _ToType __reinterpret_pointer_cast(const _FromType& __arg) { return _ToType(reinterpret_cast:: type>(__arg.get())); } /** * Casting operations for cases where _FromType is a standard pointer. * _ToType can be a standard or non-standard pointer. */ template inline _ToType __static_pointer_cast(_FromType* __arg) { return _ToType(static_cast:: type>(__arg)); } template inline _ToType __dynamic_pointer_cast(_FromType* __arg) { return _ToType(dynamic_cast:: type>(__arg)); } template inline _ToType __const_pointer_cast(_FromType* __arg) { return _ToType(const_cast:: type>(__arg)); } template inline _ToType __reinterpret_pointer_cast(_FromType* __arg) { return _ToType(reinterpret_cast:: type>(__arg)); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _GLIBCXX_CAST_H PK!z 8/ext/cmathnu[// Math extensions -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/cmath * This file is a GNU extension to the Standard C++ Library. */ #ifndef _EXT_CMATH #define _EXT_CMATH 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // A class for math constants. template struct __math_constants { static_assert(std::is_floating_point<_RealType>::value, "template argument not a floating point type"); // Constant @f$ \pi @f$. static constexpr _RealType __pi = 3.1415926535897932384626433832795029L; // Constant @f$ \pi / 2 @f$. static constexpr _RealType __pi_half = 1.5707963267948966192313216916397514L; // Constant @f$ \pi / 3 @f$. static constexpr _RealType __pi_third = 1.0471975511965977461542144610931676L; // Constant @f$ \pi / 4 @f$. static constexpr _RealType __pi_quarter = 0.7853981633974483096156608458198757L; // Constant @f$ \sqrt(\pi / 2) @f$. static constexpr _RealType __root_pi_div_2 = 1.2533141373155002512078826424055226L; // Constant @f$ 1 / \pi @f$. static constexpr _RealType __one_div_pi = 0.3183098861837906715377675267450287L; // Constant @f$ 2 / \pi @f$. static constexpr _RealType __two_div_pi = 0.6366197723675813430755350534900574L; // Constant @f$ 2 / \sqrt(\pi) @f$. static constexpr _RealType __two_div_root_pi = 1.1283791670955125738961589031215452L; // Constant Euler's number @f$ e @f$. static constexpr _RealType __e = 2.7182818284590452353602874713526625L; // Constant @f$ 1 / e @f$. static constexpr _RealType __one_div_e = 0.36787944117144232159552377016146087L; // Constant @f$ \log_2(e) @f$. static constexpr _RealType __log2_e = 1.4426950408889634073599246810018921L; // Constant @f$ \log_10(e) @f$. static constexpr _RealType __log10_e = 0.4342944819032518276511289189166051L; // Constant @f$ \ln(2) @f$. static constexpr _RealType __ln_2 = 0.6931471805599453094172321214581766L; // Constant @f$ \ln(3) @f$. static constexpr _RealType __ln_3 = 1.0986122886681096913952452369225257L; // Constant @f$ \ln(10) @f$. static constexpr _RealType __ln_10 = 2.3025850929940456840179914546843642L; // Constant Euler-Mascheroni @f$ \gamma_E @f$. static constexpr _RealType __gamma_e = 0.5772156649015328606065120900824024L; // Constant Golden Ratio @f$ \phi @f$. static constexpr _RealType __phi = 1.6180339887498948482045868343656381L; // Constant @f$ \sqrt(2) @f$. static constexpr _RealType __root_2 = 1.4142135623730950488016887242096981L; // Constant @f$ \sqrt(3) @f$. static constexpr _RealType __root_3 = 1.7320508075688772935274463415058724L; // Constant @f$ \sqrt(5) @f$. static constexpr _RealType __root_5 = 2.2360679774997896964091736687312762L; // Constant @f$ \sqrt(7) @f$. static constexpr _RealType __root_7 = 2.6457513110645905905016157536392604L; // Constant @f$ 1 / \sqrt(2) @f$. static constexpr _RealType __one_div_root_2 = 0.7071067811865475244008443621048490L; }; // And the template definitions for the constants. template constexpr _RealType __math_constants<_RealType>::__pi; template constexpr _RealType __math_constants<_RealType>::__pi_half; template constexpr _RealType __math_constants<_RealType>::__pi_third; template constexpr _RealType __math_constants<_RealType>::__pi_quarter; template constexpr _RealType __math_constants<_RealType>::__root_pi_div_2; template constexpr _RealType __math_constants<_RealType>::__one_div_pi; template constexpr _RealType __math_constants<_RealType>::__two_div_pi; template constexpr _RealType __math_constants<_RealType>::__two_div_root_pi; template constexpr _RealType __math_constants<_RealType>::__e; template constexpr _RealType __math_constants<_RealType>::__one_div_e; template constexpr _RealType __math_constants<_RealType>::__log2_e; template constexpr _RealType __math_constants<_RealType>::__log10_e; template constexpr _RealType __math_constants<_RealType>::__ln_2; template constexpr _RealType __math_constants<_RealType>::__ln_3; template constexpr _RealType __math_constants<_RealType>::__ln_10; template constexpr _RealType __math_constants<_RealType>::__gamma_e; template constexpr _RealType __math_constants<_RealType>::__phi; template constexpr _RealType __math_constants<_RealType>::__root_2; template constexpr _RealType __math_constants<_RealType>::__root_3; template constexpr _RealType __math_constants<_RealType>::__root_5; template constexpr _RealType __math_constants<_RealType>::__root_7; template constexpr _RealType __math_constants<_RealType>::__one_div_root_2; _GLIBCXX_END_NAMESPACE_VERSION } // namespace __gnu_cxx #endif // C++11 #endif // _EXT_CMATH PK!*v?2??8/ext/codecvt_specializations.hnu[// Locale support (codecvt) -*- C++ -*- // Copyright (C) 2000-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // // ISO C++ 14882: 22.2.1.5 Template class codecvt // // Written by Benjamin Kosnik /** @file ext/codecvt_specializations.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _EXT_CODECVT_SPECIALIZATIONS_H #define _EXT_CODECVT_SPECIALIZATIONS_H 1 #include #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CXX11 /// Extension to use iconv for dealing with character encodings. // This includes conversions and comparisons between various character // sets. This object encapsulates data that may need to be shared between // char_traits, codecvt and ctype. class encoding_state { public: // Types: // NB: A conversion descriptor subsumes and enhances the // functionality of a simple state type such as mbstate_t. typedef iconv_t descriptor_type; protected: // Name of internal character set encoding. std::string _M_int_enc; // Name of external character set encoding. std::string _M_ext_enc; // Conversion descriptor between external encoding to internal encoding. descriptor_type _M_in_desc; // Conversion descriptor between internal encoding to external encoding. descriptor_type _M_out_desc; // The byte-order marker for the external encoding, if necessary. int _M_ext_bom; // The byte-order marker for the internal encoding, if necessary. int _M_int_bom; // Number of external bytes needed to construct one complete // character in the internal encoding. // NB: -1 indicates variable, or stateful, encodings. int _M_bytes; public: explicit encoding_state() : _M_in_desc(0), _M_out_desc(0), _M_ext_bom(0), _M_int_bom(0), _M_bytes(0) { } explicit encoding_state(const char* __int, const char* __ext, int __ibom = 0, int __ebom = 0, int __bytes = 1) : _M_int_enc(__int), _M_ext_enc(__ext), _M_in_desc(0), _M_out_desc(0), _M_ext_bom(__ebom), _M_int_bom(__ibom), _M_bytes(__bytes) { init(); } // 21.1.2 traits typedefs // p4 // typedef STATE_T state_type // requires: state_type shall meet the requirements of // CopyConstructible types (20.1.3) // NB: This does not preserve the actual state of the conversion // descriptor member, but it does duplicate the encoding // information. encoding_state(const encoding_state& __obj) : _M_in_desc(0), _M_out_desc(0) { construct(__obj); } // Need assignment operator as well. encoding_state& operator=(const encoding_state& __obj) { construct(__obj); return *this; } ~encoding_state() { destroy(); } bool good() const throw() { const descriptor_type __err = (iconv_t)(-1); bool __test = _M_in_desc && _M_in_desc != __err; __test &= _M_out_desc && _M_out_desc != __err; return __test; } int character_ratio() const { return _M_bytes; } const std::string internal_encoding() const { return _M_int_enc; } int internal_bom() const { return _M_int_bom; } const std::string external_encoding() const { return _M_ext_enc; } int external_bom() const { return _M_ext_bom; } const descriptor_type& in_descriptor() const { return _M_in_desc; } const descriptor_type& out_descriptor() const { return _M_out_desc; } protected: void init() { const descriptor_type __err = (iconv_t)(-1); const bool __have_encodings = _M_int_enc.size() && _M_ext_enc.size(); if (!_M_in_desc && __have_encodings) { _M_in_desc = iconv_open(_M_int_enc.c_str(), _M_ext_enc.c_str()); if (_M_in_desc == __err) std::__throw_runtime_error(__N("encoding_state::_M_init " "creating iconv input descriptor failed")); } if (!_M_out_desc && __have_encodings) { _M_out_desc = iconv_open(_M_ext_enc.c_str(), _M_int_enc.c_str()); if (_M_out_desc == __err) std::__throw_runtime_error(__N("encoding_state::_M_init " "creating iconv output descriptor failed")); } } void construct(const encoding_state& __obj) { destroy(); _M_int_enc = __obj._M_int_enc; _M_ext_enc = __obj._M_ext_enc; _M_ext_bom = __obj._M_ext_bom; _M_int_bom = __obj._M_int_bom; _M_bytes = __obj._M_bytes; init(); } void destroy() throw() { const descriptor_type __err = (iconv_t)(-1); if (_M_in_desc && _M_in_desc != __err) { iconv_close(_M_in_desc); _M_in_desc = 0; } if (_M_out_desc && _M_out_desc != __err) { iconv_close(_M_out_desc); _M_out_desc = 0; } } }; /// encoding_char_traits // Custom traits type with encoding_state for the state type, and the // associated fpos for the position type, all other // bits equivalent to the required char_traits instantiations. template struct encoding_char_traits : public std::char_traits<_CharT> { typedef encoding_state state_type; typedef typename std::fpos pos_type; }; _GLIBCXX_END_NAMESPACE_CXX11 _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using __gnu_cxx::encoding_state; /// codecvt specialization. // This partial specialization takes advantage of iconv to provide // code conversions between a large number of character encodings. template class codecvt<_InternT, _ExternT, encoding_state> : public __codecvt_abstract_base<_InternT, _ExternT, encoding_state> { public: // Types: typedef codecvt_base::result result; typedef _InternT intern_type; typedef _ExternT extern_type; typedef __gnu_cxx::encoding_state state_type; typedef state_type::descriptor_type descriptor_type; // Data Members: static locale::id id; explicit codecvt(size_t __refs = 0) : __codecvt_abstract_base(__refs) { } explicit codecvt(state_type& __enc, size_t __refs = 0) : __codecvt_abstract_base(__refs) { } protected: virtual ~codecvt() { } virtual result do_out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const; virtual int do_encoding() const throw(); virtual bool do_always_noconv() const throw(); virtual int do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const; virtual int do_max_length() const throw(); }; template locale::id codecvt<_InternT, _ExternT, encoding_state>::id; // This adaptor works around the signature problems of the second // argument to iconv(): SUSv2 and others use 'const char**', but glibc 2.2 // uses 'char**', which matches the POSIX 1003.1-2001 standard. // Using this adaptor, g++ will do the work for us. template inline size_t __iconv_adaptor(size_t(*__func)(iconv_t, _Tp, size_t*, char**, size_t*), iconv_t __cd, char** __inbuf, size_t* __inbytes, char** __outbuf, size_t* __outbytes) { return __func(__cd, (_Tp)__inbuf, __inbytes, __outbuf, __outbytes); } template codecvt_base::result codecvt<_InternT, _ExternT, encoding_state>:: do_out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { result __ret = codecvt_base::error; if (__state.good()) { const descriptor_type& __desc = __state.out_descriptor(); const size_t __fmultiple = sizeof(intern_type); size_t __fbytes = __fmultiple * (__from_end - __from); const size_t __tmultiple = sizeof(extern_type); size_t __tbytes = __tmultiple * (__to_end - __to); // Argument list for iconv specifies a byte sequence. Thus, // all to/from arrays must be brutally casted to char*. char* __cto = reinterpret_cast(__to); char* __cfrom; size_t __conv; // Some encodings need a byte order marker as the first item // in the byte stream, to designate endian-ness. The default // value for the byte order marker is NULL, so if this is // the case, it's not necessary and we can just go on our // merry way. int __int_bom = __state.internal_bom(); if (__int_bom) { size_t __size = __from_end - __from; intern_type* __cfixed = static_cast (__builtin_alloca(sizeof(intern_type) * (__size + 1))); __cfixed[0] = static_cast(__int_bom); char_traits::copy(__cfixed + 1, __from, __size); __cfrom = reinterpret_cast(__cfixed); __conv = __iconv_adaptor(iconv, __desc, &__cfrom, &__fbytes, &__cto, &__tbytes); } else { intern_type* __cfixed = const_cast(__from); __cfrom = reinterpret_cast(__cfixed); __conv = __iconv_adaptor(iconv, __desc, &__cfrom, &__fbytes, &__cto, &__tbytes); } if (__conv != size_t(-1)) { __from_next = reinterpret_cast(__cfrom); __to_next = reinterpret_cast(__cto); __ret = codecvt_base::ok; } else { if (__fbytes < __fmultiple * (__from_end - __from)) { __from_next = reinterpret_cast(__cfrom); __to_next = reinterpret_cast(__cto); __ret = codecvt_base::partial; } else __ret = codecvt_base::error; } } return __ret; } template codecvt_base::result codecvt<_InternT, _ExternT, encoding_state>:: do_unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { result __ret = codecvt_base::error; if (__state.good()) { const descriptor_type& __desc = __state.in_descriptor(); const size_t __tmultiple = sizeof(intern_type); size_t __tlen = __tmultiple * (__to_end - __to); // Argument list for iconv specifies a byte sequence. Thus, // all to/from arrays must be brutally casted to char*. char* __cto = reinterpret_cast(__to); size_t __conv = __iconv_adaptor(iconv,__desc, 0, 0, &__cto, &__tlen); if (__conv != size_t(-1)) { __to_next = reinterpret_cast(__cto); if (__tlen == __tmultiple * (__to_end - __to)) __ret = codecvt_base::noconv; else if (__tlen == 0) __ret = codecvt_base::ok; else __ret = codecvt_base::partial; } else __ret = codecvt_base::error; } return __ret; } template codecvt_base::result codecvt<_InternT, _ExternT, encoding_state>:: do_in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { result __ret = codecvt_base::error; if (__state.good()) { const descriptor_type& __desc = __state.in_descriptor(); const size_t __fmultiple = sizeof(extern_type); size_t __flen = __fmultiple * (__from_end - __from); const size_t __tmultiple = sizeof(intern_type); size_t __tlen = __tmultiple * (__to_end - __to); // Argument list for iconv specifies a byte sequence. Thus, // all to/from arrays must be brutally casted to char*. char* __cto = reinterpret_cast(__to); char* __cfrom; size_t __conv; // Some encodings need a byte order marker as the first item // in the byte stream, to designate endian-ness. The default // value for the byte order marker is NULL, so if this is // the case, it's not necessary and we can just go on our // merry way. int __ext_bom = __state.external_bom(); if (__ext_bom) { size_t __size = __from_end - __from; extern_type* __cfixed = static_cast (__builtin_alloca(sizeof(extern_type) * (__size + 1))); __cfixed[0] = static_cast(__ext_bom); char_traits::copy(__cfixed + 1, __from, __size); __cfrom = reinterpret_cast(__cfixed); __conv = __iconv_adaptor(iconv, __desc, &__cfrom, &__flen, &__cto, &__tlen); } else { extern_type* __cfixed = const_cast(__from); __cfrom = reinterpret_cast(__cfixed); __conv = __iconv_adaptor(iconv, __desc, &__cfrom, &__flen, &__cto, &__tlen); } if (__conv != size_t(-1)) { __from_next = reinterpret_cast(__cfrom); __to_next = reinterpret_cast(__cto); __ret = codecvt_base::ok; } else { if (__flen < static_cast(__from_end - __from)) { __from_next = reinterpret_cast(__cfrom); __to_next = reinterpret_cast(__cto); __ret = codecvt_base::partial; } else __ret = codecvt_base::error; } } return __ret; } template int codecvt<_InternT, _ExternT, encoding_state>:: do_encoding() const throw() { int __ret = 0; if (sizeof(_ExternT) <= sizeof(_InternT)) __ret = sizeof(_InternT) / sizeof(_ExternT); return __ret; } template bool codecvt<_InternT, _ExternT, encoding_state>:: do_always_noconv() const throw() { return false; } template int codecvt<_InternT, _ExternT, encoding_state>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { return std::min(__max, static_cast(__end - __from)); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 74. Garbled text for codecvt::do_max_length template int codecvt<_InternT, _ExternT, encoding_state>:: do_max_length() const throw() { return 1; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!pл8/ext/concurrence.hnu[// Support for concurrent programing -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/concurrence.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _CONCURRENCE_H #define _CONCURRENCE_H 1 #pragma GCC system_header #include #include #include #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Available locking policies: // _S_single single-threaded code that doesn't need to be locked. // _S_mutex multi-threaded code that requires additional support // from gthr.h or abstraction layers in concurrence.h. // _S_atomic multi-threaded code using atomic operations. enum _Lock_policy { _S_single, _S_mutex, _S_atomic }; // Compile time constant that indicates prefered locking policy in // the current configuration. static const _Lock_policy __default_lock_policy = #ifdef __GTHREADS #if (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2) \ && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)) _S_atomic; #else _S_mutex; #endif #else _S_single; #endif // NB: As this is used in libsupc++, need to only depend on // exception. No stdexception classes, no use of std::string. class __concurrence_lock_error : public std::exception { public: virtual char const* what() const throw() { return "__gnu_cxx::__concurrence_lock_error"; } }; class __concurrence_unlock_error : public std::exception { public: virtual char const* what() const throw() { return "__gnu_cxx::__concurrence_unlock_error"; } }; class __concurrence_broadcast_error : public std::exception { public: virtual char const* what() const throw() { return "__gnu_cxx::__concurrence_broadcast_error"; } }; class __concurrence_wait_error : public std::exception { public: virtual char const* what() const throw() { return "__gnu_cxx::__concurrence_wait_error"; } }; // Substitute for concurrence_error object in the case of -fno-exceptions. inline void __throw_concurrence_lock_error() { _GLIBCXX_THROW_OR_ABORT(__concurrence_lock_error()); } inline void __throw_concurrence_unlock_error() { _GLIBCXX_THROW_OR_ABORT(__concurrence_unlock_error()); } #ifdef __GTHREAD_HAS_COND inline void __throw_concurrence_broadcast_error() { _GLIBCXX_THROW_OR_ABORT(__concurrence_broadcast_error()); } inline void __throw_concurrence_wait_error() { _GLIBCXX_THROW_OR_ABORT(__concurrence_wait_error()); } #endif class __mutex { private: #if __GTHREADS && defined __GTHREAD_MUTEX_INIT __gthread_mutex_t _M_mutex = __GTHREAD_MUTEX_INIT; #else __gthread_mutex_t _M_mutex; #endif __mutex(const __mutex&); __mutex& operator=(const __mutex&); public: __mutex() { #if __GTHREADS && ! defined __GTHREAD_MUTEX_INIT if (__gthread_active_p()) __GTHREAD_MUTEX_INIT_FUNCTION(&_M_mutex); #endif } #if __GTHREADS && ! defined __GTHREAD_MUTEX_INIT ~__mutex() { if (__gthread_active_p()) __gthread_mutex_destroy(&_M_mutex); } #endif void lock() { #if __GTHREADS if (__gthread_active_p()) { if (__gthread_mutex_lock(&_M_mutex) != 0) __throw_concurrence_lock_error(); } #endif } void unlock() { #if __GTHREADS if (__gthread_active_p()) { if (__gthread_mutex_unlock(&_M_mutex) != 0) __throw_concurrence_unlock_error(); } #endif } __gthread_mutex_t* gthread_mutex(void) { return &_M_mutex; } }; class __recursive_mutex { private: #if __GTHREADS && defined __GTHREAD_RECURSIVE_MUTEX_INIT __gthread_recursive_mutex_t _M_mutex = __GTHREAD_RECURSIVE_MUTEX_INIT; #else __gthread_recursive_mutex_t _M_mutex; #endif __recursive_mutex(const __recursive_mutex&); __recursive_mutex& operator=(const __recursive_mutex&); public: __recursive_mutex() { #if __GTHREADS && ! defined __GTHREAD_RECURSIVE_MUTEX_INIT if (__gthread_active_p()) __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION(&_M_mutex); #endif } #if __GTHREADS && ! defined __GTHREAD_RECURSIVE_MUTEX_INIT ~__recursive_mutex() { if (__gthread_active_p()) __gthread_recursive_mutex_destroy(&_M_mutex); } #endif void lock() { #if __GTHREADS if (__gthread_active_p()) { if (__gthread_recursive_mutex_lock(&_M_mutex) != 0) __throw_concurrence_lock_error(); } #endif } void unlock() { #if __GTHREADS if (__gthread_active_p()) { if (__gthread_recursive_mutex_unlock(&_M_mutex) != 0) __throw_concurrence_unlock_error(); } #endif } __gthread_recursive_mutex_t* gthread_recursive_mutex(void) { return &_M_mutex; } }; /// Scoped lock idiom. // Acquire the mutex here with a constructor call, then release with // the destructor call in accordance with RAII style. class __scoped_lock { public: typedef __mutex __mutex_type; private: __mutex_type& _M_device; __scoped_lock(const __scoped_lock&); __scoped_lock& operator=(const __scoped_lock&); public: explicit __scoped_lock(__mutex_type& __name) : _M_device(__name) { _M_device.lock(); } ~__scoped_lock() throw() { _M_device.unlock(); } }; #ifdef __GTHREAD_HAS_COND class __cond { private: #if __GTHREADS && defined __GTHREAD_COND_INIT __gthread_cond_t _M_cond = __GTHREAD_COND_INIT; #else __gthread_cond_t _M_cond; #endif __cond(const __cond&); __cond& operator=(const __cond&); public: __cond() { #if __GTHREADS && ! defined __GTHREAD_COND_INIT if (__gthread_active_p()) __GTHREAD_COND_INIT_FUNCTION(&_M_cond); #endif } #if __GTHREADS && ! defined __GTHREAD_COND_INIT ~__cond() { if (__gthread_active_p()) __gthread_cond_destroy(&_M_cond); } #endif void broadcast() { #if __GTHREADS if (__gthread_active_p()) { if (__gthread_cond_broadcast(&_M_cond) != 0) __throw_concurrence_broadcast_error(); } #endif } void wait(__mutex *mutex) { #if __GTHREADS { if (__gthread_cond_wait(&_M_cond, mutex->gthread_mutex()) != 0) __throw_concurrence_wait_error(); } #endif } void wait_recursive(__recursive_mutex *mutex) { #if __GTHREADS { if (__gthread_cond_wait_recursive(&_M_cond, mutex->gthread_recursive_mutex()) != 0) __throw_concurrence_wait_error(); } #endif } }; #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!TT8/ext/debug_allocator.hnu[// Allocators -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * Copyright (c) 1996-1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file ext/debug_allocator.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _DEBUG_ALLOCATOR_H #define _DEBUG_ALLOCATOR_H 1 #include #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using std::size_t; /** * @brief A meta-allocator with debugging bits. * @ingroup allocators * * This is precisely the allocator defined in the C++03 Standard. */ template class debug_allocator { template friend class debug_allocator; typedef __alloc_traits<_Alloc> _Traits; public: typedef typename _Traits::size_type size_type; typedef typename _Traits::difference_type difference_type; typedef typename _Traits::pointer pointer; typedef typename _Traits::const_pointer const_pointer; typedef typename _Traits::reference reference; typedef typename _Traits::const_reference const_reference; typedef typename _Traits::value_type value_type; template class rebind { typedef typename _Traits::template rebind<_Up>::other __other; public: typedef debug_allocator<__other> other; }; private: // _M_extra is the number of objects that correspond to the // extra space where debug information is stored. size_type _M_extra; _Alloc _M_allocator; template::other> struct __convertible { }; template struct __convertible<_Alloc2, _Alloc> { typedef void* __type; }; size_type _S_extra() { const size_t __obj_size = sizeof(value_type); return (sizeof(size_type) + __obj_size - 1) / __obj_size; } public: debug_allocator() : _M_extra(_S_extra()) { } template debug_allocator(const debug_allocator<_Alloc2>& __a2, typename __convertible<_Alloc2>::__type = 0) : _M_allocator(__a2._M_allocator), _M_extra(_S_extra()) { } debug_allocator(const _Alloc& __a) : _M_allocator(__a), _M_extra(_S_extra()) { } pointer allocate(size_type __n) { pointer __res = _M_allocator.allocate(__n + _M_extra); size_type* __ps = reinterpret_cast(__res); *__ps = __n; return __res + _M_extra; } pointer allocate(size_type __n, const void* __hint) { pointer __res = _M_allocator.allocate(__n + _M_extra, __hint); size_type* __ps = reinterpret_cast(__res); *__ps = __n; return __res + _M_extra; } void deallocate(pointer __p, size_type __n) { using std::__throw_runtime_error; if (__p) { pointer __real_p = __p - _M_extra; if (*reinterpret_cast(__real_p) != __n) __throw_runtime_error("debug_allocator::deallocate wrong size"); _M_allocator.deallocate(__real_p, __n + _M_extra); } else __throw_runtime_error("debug_allocator::deallocate null pointer"); } void construct(pointer __p, const value_type& __val) { _Traits::construct(_M_allocator, __p, __val); } #if __cplusplus >= 201103L template void construct(_Tp* __p, _Args&&... __args) { _Traits::construct(_M_allocator, __p, std::forward<_Args>(__args)...); } #endif template void destroy(_Tp* __p) { _Traits::destroy(_M_allocator, __p); } size_type max_size() const throw() { return _Traits::max_size(_M_allocator) - _M_extra; } friend bool operator==(const debug_allocator& __lhs, const debug_allocator& __rhs) { return __lhs._M_allocator == __rhs._M_allocator; } }; template inline bool operator!=(const debug_allocator<_Alloc>& __lhs, const debug_allocator<_Alloc>& __rhs) { return !(__lhs == __rhs); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!]'8/ext/enc_filebuf.hnu[// filebuf with encoding state type -*- C++ -*- // Copyright (C) 2002-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/enc_filebuf.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _EXT_ENC_FILEBUF_H #define _EXT_ENC_FILEBUF_H 1 #include #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /// class enc_filebuf. template class enc_filebuf : public std::basic_filebuf<_CharT, encoding_char_traits<_CharT> > { public: typedef encoding_char_traits<_CharT> traits_type; typedef typename traits_type::state_type state_type; typedef typename traits_type::pos_type pos_type; enc_filebuf(state_type& __state) : std::basic_filebuf<_CharT, encoding_char_traits<_CharT> >() { this->_M_state_beg = __state; } private: // concept requirements: // Set state type to something useful. // Something more than copyconstructible is needed here, so // require default and copy constructible + assignment operator. __glibcxx_class_requires(state_type, _SGIAssignableConcept) }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!q--8/ext/extptr_allocator.hnu[// -*- C++ -*- // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file ext/extptr_allocator.h * This file is a GNU extension to the Standard C++ Library. * * @author Bob Walters * * An example allocator which uses an alternative pointer type from * bits/pointer.h. Supports test cases which confirm container support * for alternative pointers. */ #ifndef _EXTPTR_ALLOCATOR_H #define _EXTPTR_ALLOCATOR_H 1 #include #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief An example allocator which uses a non-standard pointer type. * @ingroup allocators * * This allocator specifies that containers use a 'relative pointer' as it's * pointer type. (See ext/pointer.h) Memory allocation in this example * is still performed using std::allocator. */ template class _ExtPtr_allocator { public: typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; // Note the non-standard pointer types. typedef _Pointer_adapter<_Relative_pointer_impl<_Tp> > pointer; typedef _Pointer_adapter<_Relative_pointer_impl > const_pointer; typedef _Tp& reference; typedef const _Tp& const_reference; typedef _Tp value_type; template struct rebind { typedef _ExtPtr_allocator<_Up> other; }; _ExtPtr_allocator() _GLIBCXX_USE_NOEXCEPT : _M_real_alloc() { } _ExtPtr_allocator(const _ExtPtr_allocator& __rarg) _GLIBCXX_USE_NOEXCEPT : _M_real_alloc(__rarg._M_real_alloc) { } template _ExtPtr_allocator(const _ExtPtr_allocator<_Up>& __rarg) _GLIBCXX_USE_NOEXCEPT : _M_real_alloc(__rarg._M_getUnderlyingImp()) { } ~_ExtPtr_allocator() _GLIBCXX_USE_NOEXCEPT { } pointer address(reference __x) const _GLIBCXX_NOEXCEPT { return std::__addressof(__x); } const_pointer address(const_reference __x) const _GLIBCXX_NOEXCEPT { return std::__addressof(__x); } pointer allocate(size_type __n, void* __hint = 0) { return _M_real_alloc.allocate(__n,__hint); } void deallocate(pointer __p, size_type __n) { _M_real_alloc.deallocate(__p.get(), __n); } size_type max_size() const _GLIBCXX_USE_NOEXCEPT { return __numeric_traits::__max / sizeof(_Tp); } #if __cplusplus >= 201103L template void construct(_Up* __p, _Args&&... __args) { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); } template void construct(pointer __p, _Args&&... __args) { construct(__p.get(), std::forward<_Args>(__args)...); } template void destroy(_Up* __p) { __p->~_Up(); } void destroy(pointer __p) { destroy(__p.get()); } #else void construct(pointer __p, const _Tp& __val) { ::new(__p.get()) _Tp(__val); } void destroy(pointer __p) { __p->~_Tp(); } #endif template inline bool operator==(const _ExtPtr_allocator<_Up>& __rarg) { return _M_real_alloc == __rarg._M_getUnderlyingImp(); } inline bool operator==(const _ExtPtr_allocator& __rarg) { return _M_real_alloc == __rarg._M_real_alloc; } template inline bool operator!=(const _ExtPtr_allocator<_Up>& __rarg) { return _M_real_alloc != __rarg._M_getUnderlyingImp(); } inline bool operator!=(const _ExtPtr_allocator& __rarg) { return _M_real_alloc != __rarg._M_real_alloc; } template inline friend void swap(_ExtPtr_allocator<_Up>&, _ExtPtr_allocator<_Up>&); // A method specific to this implementation. const std::allocator<_Tp>& _M_getUnderlyingImp() const { return _M_real_alloc; } private: std::allocator<_Tp> _M_real_alloc; }; // _ExtPtr_allocator specialization. template<> class _ExtPtr_allocator { public: typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef void value_type; // Note the non-standard pointer types typedef _Pointer_adapter<_Relative_pointer_impl > pointer; typedef _Pointer_adapter<_Relative_pointer_impl > const_pointer; template struct rebind { typedef _ExtPtr_allocator<_Up> other; }; private: std::allocator _M_real_alloc; }; template inline void swap(_ExtPtr_allocator<_Tp>& __larg, _ExtPtr_allocator<_Tp>& __rarg) { std::allocator<_Tp> __tmp( __rarg._M_real_alloc ); __rarg._M_real_alloc = __larg._M_real_alloc; __larg._M_real_alloc = __tmp; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _EXTPTR_ALLOCATOR_H */ PK!,y1778/ext/functionalnu[// Functional extensions -*- C++ -*- // Copyright (C) 2002-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file ext/functional * This file is a GNU extension to the Standard C++ Library (possibly * containing extensions from the HP/SGI STL subset). */ #ifndef _EXT_FUNCTIONAL #define _EXT_FUNCTIONAL 1 #pragma GCC system_header #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using std::size_t; using std::unary_function; using std::binary_function; using std::mem_fun1_t; using std::const_mem_fun1_t; using std::mem_fun1_ref_t; using std::const_mem_fun1_ref_t; /** The @c identity_element functions are not part of the C++ * standard; SGI provided them as an extension. Its argument is an * operation, and its return value is the identity element for that * operation. It is overloaded for addition and multiplication, * and you can overload it for your own nefarious operations. * * @addtogroup SGIextensions * @{ */ /// An \link SGIextensions SGI extension \endlink. template inline _Tp identity_element(std::plus<_Tp>) { return _Tp(0); } /// An \link SGIextensions SGI extension \endlink. template inline _Tp identity_element(std::multiplies<_Tp>) { return _Tp(1); } /** @} */ /** As an extension to the binders, SGI provided composition functors and * wrapper functions to aid in their creation. The @c unary_compose * functor is constructed from two functions/functors, @c f and @c g. * Calling @c operator() with a single argument @c x returns @c f(g(x)). * The function @c compose1 takes the two functions and constructs a * @c unary_compose variable for you. * * @c binary_compose is constructed from three functors, @c f, @c g1, * and @c g2. Its @c operator() returns @c f(g1(x),g2(x)). The function * compose2 takes f, g1, and g2, and constructs the @c binary_compose * instance for you. For example, if @c f returns an int, then * \code * int answer = (compose2(f,g1,g2))(x); * \endcode * is equivalent to * \code * int temp1 = g1(x); * int temp2 = g2(x); * int answer = f(temp1,temp2); * \endcode * But the first form is more compact, and can be passed around as a * functor to other algorithms. * * @addtogroup SGIextensions * @{ */ /// An \link SGIextensions SGI extension \endlink. template class unary_compose : public unary_function { protected: _Operation1 _M_fn1; _Operation2 _M_fn2; public: unary_compose(const _Operation1& __x, const _Operation2& __y) : _M_fn1(__x), _M_fn2(__y) {} typename _Operation1::result_type operator()(const typename _Operation2::argument_type& __x) const { return _M_fn1(_M_fn2(__x)); } }; /// An \link SGIextensions SGI extension \endlink. template inline unary_compose<_Operation1, _Operation2> compose1(const _Operation1& __fn1, const _Operation2& __fn2) { return unary_compose<_Operation1,_Operation2>(__fn1, __fn2); } /// An \link SGIextensions SGI extension \endlink. template class binary_compose : public unary_function { protected: _Operation1 _M_fn1; _Operation2 _M_fn2; _Operation3 _M_fn3; public: binary_compose(const _Operation1& __x, const _Operation2& __y, const _Operation3& __z) : _M_fn1(__x), _M_fn2(__y), _M_fn3(__z) { } typename _Operation1::result_type operator()(const typename _Operation2::argument_type& __x) const { return _M_fn1(_M_fn2(__x), _M_fn3(__x)); } }; /// An \link SGIextensions SGI extension \endlink. template inline binary_compose<_Operation1, _Operation2, _Operation3> compose2(const _Operation1& __fn1, const _Operation2& __fn2, const _Operation3& __fn3) { return binary_compose<_Operation1, _Operation2, _Operation3> (__fn1, __fn2, __fn3); } /** @} */ /** As an extension, SGI provided a functor called @c identity. When a * functor is required but no operations are desired, this can be used as a * pass-through. Its @c operator() returns its argument unchanged. * * @addtogroup SGIextensions */ template struct identity : public std::_Identity<_Tp> {}; /** @c select1st and @c select2nd are extensions provided by SGI. Their * @c operator()s * take a @c std::pair as an argument, and return either the first member * or the second member, respectively. They can be used (especially with * the composition functors) to @a strip data from a sequence before * performing the remainder of an algorithm. * * @addtogroup SGIextensions * @{ */ /// An \link SGIextensions SGI extension \endlink. template struct select1st : public std::_Select1st<_Pair> {}; /// An \link SGIextensions SGI extension \endlink. template struct select2nd : public std::_Select2nd<_Pair> {}; /** @} */ // extension documented next template struct _Project1st : public binary_function<_Arg1, _Arg2, _Arg1> { _Arg1 operator()(const _Arg1& __x, const _Arg2&) const { return __x; } }; template struct _Project2nd : public binary_function<_Arg1, _Arg2, _Arg2> { _Arg2 operator()(const _Arg1&, const _Arg2& __y) const { return __y; } }; /** The @c operator() of the @c project1st functor takes two arbitrary * arguments and returns the first one, while @c project2nd returns the * second one. They are extensions provided by SGI. * * @addtogroup SGIextensions * @{ */ /// An \link SGIextensions SGI extension \endlink. template struct project1st : public _Project1st<_Arg1, _Arg2> {}; /// An \link SGIextensions SGI extension \endlink. template struct project2nd : public _Project2nd<_Arg1, _Arg2> {}; /** @} */ // extension documented next template struct _Constant_void_fun { typedef _Result result_type; result_type _M_val; _Constant_void_fun(const result_type& __v) : _M_val(__v) {} const result_type& operator()() const { return _M_val; } }; template struct _Constant_unary_fun { typedef _Argument argument_type; typedef _Result result_type; result_type _M_val; _Constant_unary_fun(const result_type& __v) : _M_val(__v) {} const result_type& operator()(const _Argument&) const { return _M_val; } }; template struct _Constant_binary_fun { typedef _Arg1 first_argument_type; typedef _Arg2 second_argument_type; typedef _Result result_type; _Result _M_val; _Constant_binary_fun(const _Result& __v) : _M_val(__v) {} const result_type& operator()(const _Arg1&, const _Arg2&) const { return _M_val; } }; /** These three functors are each constructed from a single arbitrary * variable/value. Later, their @c operator()s completely ignore any * arguments passed, and return the stored value. * - @c constant_void_fun's @c operator() takes no arguments * - @c constant_unary_fun's @c operator() takes one argument (ignored) * - @c constant_binary_fun's @c operator() takes two arguments (ignored) * * The helper creator functions @c constant0, @c constant1, and * @c constant2 each take a @a result argument and construct variables of * the appropriate functor type. * * @addtogroup SGIextensions * @{ */ /// An \link SGIextensions SGI extension \endlink. template struct constant_void_fun : public _Constant_void_fun<_Result> { constant_void_fun(const _Result& __v) : _Constant_void_fun<_Result>(__v) {} }; /// An \link SGIextensions SGI extension \endlink. template struct constant_unary_fun : public _Constant_unary_fun<_Result, _Argument> { constant_unary_fun(const _Result& __v) : _Constant_unary_fun<_Result, _Argument>(__v) {} }; /// An \link SGIextensions SGI extension \endlink. template struct constant_binary_fun : public _Constant_binary_fun<_Result, _Arg1, _Arg2> { constant_binary_fun(const _Result& __v) : _Constant_binary_fun<_Result, _Arg1, _Arg2>(__v) {} }; /// An \link SGIextensions SGI extension \endlink. template inline constant_void_fun<_Result> constant0(const _Result& __val) { return constant_void_fun<_Result>(__val); } /// An \link SGIextensions SGI extension \endlink. template inline constant_unary_fun<_Result, _Result> constant1(const _Result& __val) { return constant_unary_fun<_Result, _Result>(__val); } /// An \link SGIextensions SGI extension \endlink. template inline constant_binary_fun<_Result,_Result,_Result> constant2(const _Result& __val) { return constant_binary_fun<_Result, _Result, _Result>(__val); } /** @} */ /** The @c subtractive_rng class is documented on * SGI's site. * Note that this code assumes that @c int is 32 bits. * * @ingroup SGIextensions */ class subtractive_rng : public unary_function { private: unsigned int _M_table[55]; size_t _M_index1; size_t _M_index2; public: /// Returns a number less than the argument. unsigned int operator()(unsigned int __limit) { _M_index1 = (_M_index1 + 1) % 55; _M_index2 = (_M_index2 + 1) % 55; _M_table[_M_index1] = _M_table[_M_index1] - _M_table[_M_index2]; return _M_table[_M_index1] % __limit; } void _M_initialize(unsigned int __seed) { unsigned int __k = 1; _M_table[54] = __seed; size_t __i; for (__i = 0; __i < 54; __i++) { size_t __ii = (21 * (__i + 1) % 55) - 1; _M_table[__ii] = __k; __k = __seed - __k; __seed = _M_table[__ii]; } for (int __loop = 0; __loop < 4; __loop++) { for (__i = 0; __i < 55; __i++) _M_table[__i] = _M_table[__i] - _M_table[(1 + __i + 30) % 55]; } _M_index1 = 0; _M_index2 = 31; } /// Ctor allowing you to initialize the seed. subtractive_rng(unsigned int __seed) { _M_initialize(__seed); } /// Default ctor; initializes its state with some number you don't see. subtractive_rng() { _M_initialize(161803398u); } }; // Mem_fun adaptor helper functions mem_fun1 and mem_fun1_ref, // provided for backward compatibility, they are no longer part of // the C++ standard. template inline mem_fun1_t<_Ret, _Tp, _Arg> mem_fun1(_Ret (_Tp::*__f)(_Arg)) { return mem_fun1_t<_Ret, _Tp, _Arg>(__f); } template inline const_mem_fun1_t<_Ret, _Tp, _Arg> mem_fun1(_Ret (_Tp::*__f)(_Arg) const) { return const_mem_fun1_t<_Ret, _Tp, _Arg>(__f); } template inline mem_fun1_ref_t<_Ret, _Tp, _Arg> mem_fun1_ref(_Ret (_Tp::*__f)(_Arg)) { return mem_fun1_ref_t<_Ret, _Tp, _Arg>(__f); } template inline const_mem_fun1_ref_t<_Ret, _Tp, _Arg> mem_fun1_ref(_Ret (_Tp::*__f)(_Arg) const) { return const_mem_fun1_ref_t<_Ret, _Tp, _Arg>(__f); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!oEoE8/ext/hash_mapnu[// Hashing map implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * */ /** @file backward/hash_map * This file is a GNU extension to the Standard C++ Library (possibly * containing extensions from the HP/SGI STL subset). */ #ifndef _BACKWARD_HASH_MAP #define _BACKWARD_HASH_MAP 1 #ifndef _GLIBCXX_PERMIT_BACKWARD_HASH #include "backward_warning.h" #endif #include #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using std::equal_to; using std::allocator; using std::pair; using std::_Select1st; /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template, class _EqualKey = equal_to<_Key>, class _Alloc = allocator<_Tp> > class hash_map { private: typedef hashtable,_Key, _HashFn, _Select1st >, _EqualKey, _Alloc> _Ht; _Ht _M_ht; public: typedef typename _Ht::key_type key_type; typedef _Tp data_type; typedef _Tp mapped_type; typedef typename _Ht::value_type value_type; typedef typename _Ht::hasher hasher; typedef typename _Ht::key_equal key_equal; typedef typename _Ht::size_type size_type; typedef typename _Ht::difference_type difference_type; typedef typename _Ht::pointer pointer; typedef typename _Ht::const_pointer const_pointer; typedef typename _Ht::reference reference; typedef typename _Ht::const_reference const_reference; typedef typename _Ht::iterator iterator; typedef typename _Ht::const_iterator const_iterator; typedef typename _Ht::allocator_type allocator_type; hasher hash_funct() const { return _M_ht.hash_funct(); } key_equal key_eq() const { return _M_ht.key_eq(); } allocator_type get_allocator() const { return _M_ht.get_allocator(); } hash_map() : _M_ht(100, hasher(), key_equal(), allocator_type()) {} explicit hash_map(size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) {} hash_map(size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) {} hash_map(size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) {} template hash_map(_InputIterator __f, _InputIterator __l) : _M_ht(100, hasher(), key_equal(), allocator_type()) { _M_ht.insert_unique(__f, __l); } template hash_map(_InputIterator __f, _InputIterator __l, size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) { _M_ht.insert_unique(__f, __l); } template hash_map(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) { _M_ht.insert_unique(__f, __l); } template hash_map(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) { _M_ht.insert_unique(__f, __l); } size_type size() const { return _M_ht.size(); } size_type max_size() const { return _M_ht.max_size(); } bool empty() const { return _M_ht.empty(); } void swap(hash_map& __hs) { _M_ht.swap(__hs._M_ht); } template friend bool operator== (const hash_map<_K1, _T1, _HF, _EqK, _Al>&, const hash_map<_K1, _T1, _HF, _EqK, _Al>&); iterator begin() { return _M_ht.begin(); } iterator end() { return _M_ht.end(); } const_iterator begin() const { return _M_ht.begin(); } const_iterator end() const { return _M_ht.end(); } pair insert(const value_type& __obj) { return _M_ht.insert_unique(__obj); } template void insert(_InputIterator __f, _InputIterator __l) { _M_ht.insert_unique(__f, __l); } pair insert_noresize(const value_type& __obj) { return _M_ht.insert_unique_noresize(__obj); } iterator find(const key_type& __key) { return _M_ht.find(__key); } const_iterator find(const key_type& __key) const { return _M_ht.find(__key); } _Tp& operator[](const key_type& __key) { return _M_ht.find_or_insert(value_type(__key, _Tp())).second; } size_type count(const key_type& __key) const { return _M_ht.count(__key); } pair equal_range(const key_type& __key) { return _M_ht.equal_range(__key); } pair equal_range(const key_type& __key) const { return _M_ht.equal_range(__key); } size_type erase(const key_type& __key) {return _M_ht.erase(__key); } void erase(iterator __it) { _M_ht.erase(__it); } void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); } void clear() { _M_ht.clear(); } void resize(size_type __hint) { _M_ht.resize(__hint); } size_type bucket_count() const { return _M_ht.bucket_count(); } size_type max_bucket_count() const { return _M_ht.max_bucket_count(); } size_type elems_in_bucket(size_type __n) const { return _M_ht.elems_in_bucket(__n); } }; template inline bool operator==(const hash_map<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm1, const hash_map<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm2) { return __hm1._M_ht == __hm2._M_ht; } template inline bool operator!=(const hash_map<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm1, const hash_map<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm2) { return !(__hm1 == __hm2); } template inline void swap(hash_map<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm1, hash_map<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm2) { __hm1.swap(__hm2); } /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template, class _EqualKey = equal_to<_Key>, class _Alloc = allocator<_Tp> > class hash_multimap { // concept requirements __glibcxx_class_requires(_Key, _SGIAssignableConcept) __glibcxx_class_requires(_Tp, _SGIAssignableConcept) __glibcxx_class_requires3(_HashFn, size_t, _Key, _UnaryFunctionConcept) __glibcxx_class_requires3(_EqualKey, _Key, _Key, _BinaryPredicateConcept) private: typedef hashtable, _Key, _HashFn, _Select1st >, _EqualKey, _Alloc> _Ht; _Ht _M_ht; public: typedef typename _Ht::key_type key_type; typedef _Tp data_type; typedef _Tp mapped_type; typedef typename _Ht::value_type value_type; typedef typename _Ht::hasher hasher; typedef typename _Ht::key_equal key_equal; typedef typename _Ht::size_type size_type; typedef typename _Ht::difference_type difference_type; typedef typename _Ht::pointer pointer; typedef typename _Ht::const_pointer const_pointer; typedef typename _Ht::reference reference; typedef typename _Ht::const_reference const_reference; typedef typename _Ht::iterator iterator; typedef typename _Ht::const_iterator const_iterator; typedef typename _Ht::allocator_type allocator_type; hasher hash_funct() const { return _M_ht.hash_funct(); } key_equal key_eq() const { return _M_ht.key_eq(); } allocator_type get_allocator() const { return _M_ht.get_allocator(); } hash_multimap() : _M_ht(100, hasher(), key_equal(), allocator_type()) {} explicit hash_multimap(size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) {} hash_multimap(size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) {} hash_multimap(size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) {} template hash_multimap(_InputIterator __f, _InputIterator __l) : _M_ht(100, hasher(), key_equal(), allocator_type()) { _M_ht.insert_equal(__f, __l); } template hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) { _M_ht.insert_equal(__f, __l); } template hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) { _M_ht.insert_equal(__f, __l); } template hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) { _M_ht.insert_equal(__f, __l); } size_type size() const { return _M_ht.size(); } size_type max_size() const { return _M_ht.max_size(); } bool empty() const { return _M_ht.empty(); } void swap(hash_multimap& __hs) { _M_ht.swap(__hs._M_ht); } template friend bool operator==(const hash_multimap<_K1, _T1, _HF, _EqK, _Al>&, const hash_multimap<_K1, _T1, _HF, _EqK, _Al>&); iterator begin() { return _M_ht.begin(); } iterator end() { return _M_ht.end(); } const_iterator begin() const { return _M_ht.begin(); } const_iterator end() const { return _M_ht.end(); } iterator insert(const value_type& __obj) { return _M_ht.insert_equal(__obj); } template void insert(_InputIterator __f, _InputIterator __l) { _M_ht.insert_equal(__f,__l); } iterator insert_noresize(const value_type& __obj) { return _M_ht.insert_equal_noresize(__obj); } iterator find(const key_type& __key) { return _M_ht.find(__key); } const_iterator find(const key_type& __key) const { return _M_ht.find(__key); } size_type count(const key_type& __key) const { return _M_ht.count(__key); } pair equal_range(const key_type& __key) { return _M_ht.equal_range(__key); } pair equal_range(const key_type& __key) const { return _M_ht.equal_range(__key); } size_type erase(const key_type& __key) { return _M_ht.erase(__key); } void erase(iterator __it) { _M_ht.erase(__it); } void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); } void clear() { _M_ht.clear(); } void resize(size_type __hint) { _M_ht.resize(__hint); } size_type bucket_count() const { return _M_ht.bucket_count(); } size_type max_bucket_count() const { return _M_ht.max_bucket_count(); } size_type elems_in_bucket(size_type __n) const { return _M_ht.elems_in_bucket(__n); } }; template inline bool operator==(const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm1, const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm2) { return __hm1._M_ht == __hm2._M_ht; } template inline bool operator!=(const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm1, const hash_multimap<_Key, _Tp, _HF, _EqKey, _Alloc>& __hm2) { return !(__hm1 == __hm2); } template inline void swap(hash_multimap<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm1, hash_multimap<_Key, _Tp, _HashFn, _EqlKey, _Alloc>& __hm2) { __hm1.swap(__hm2); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Specialization of insert_iterator so that it will work for hash_map // and hash_multimap. template class insert_iterator<__gnu_cxx::hash_map<_Key, _Tp, _HashFn, _EqKey, _Alloc> > { protected: typedef __gnu_cxx::hash_map<_Key, _Tp, _HashFn, _EqKey, _Alloc> _Container; _Container* container; public: typedef _Container container_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; insert_iterator(_Container& __x) : container(&__x) {} insert_iterator(_Container& __x, typename _Container::iterator) : container(&__x) {} insert_iterator<_Container>& operator=(const typename _Container::value_type& __value) { container->insert(__value); return *this; } insert_iterator<_Container>& operator*() { return *this; } insert_iterator<_Container>& operator++() { return *this; } insert_iterator<_Container>& operator++(int) { return *this; } }; template class insert_iterator<__gnu_cxx::hash_multimap<_Key, _Tp, _HashFn, _EqKey, _Alloc> > { protected: typedef __gnu_cxx::hash_multimap<_Key, _Tp, _HashFn, _EqKey, _Alloc> _Container; _Container* container; typename _Container::iterator iter; public: typedef _Container container_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; insert_iterator(_Container& __x) : container(&__x) {} insert_iterator(_Container& __x, typename _Container::iterator) : container(&__x) {} insert_iterator<_Container>& operator=(const typename _Container::value_type& __value) { container->insert(__value); return *this; } insert_iterator<_Container>& operator*() { return *this; } insert_iterator<_Container>& operator++() { return *this; } insert_iterator<_Container>& operator++(int) { return *this; } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!+C+C8/ext/hash_setnu[// Hashing set implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * */ /** @file backward/hash_set * This file is a GNU extension to the Standard C++ Library (possibly * containing extensions from the HP/SGI STL subset). */ #ifndef _BACKWARD_HASH_SET #define _BACKWARD_HASH_SET 1 #ifndef _GLIBCXX_PERMIT_BACKWARD_HASH #include "backward_warning.h" #endif #include #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using std::equal_to; using std::allocator; using std::pair; using std::_Identity; /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template, class _EqualKey = equal_to<_Value>, class _Alloc = allocator<_Value> > class hash_set { // concept requirements __glibcxx_class_requires(_Value, _SGIAssignableConcept) __glibcxx_class_requires3(_HashFcn, size_t, _Value, _UnaryFunctionConcept) __glibcxx_class_requires3(_EqualKey, _Value, _Value, _BinaryPredicateConcept) private: typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>, _EqualKey, _Alloc> _Ht; _Ht _M_ht; public: typedef typename _Ht::key_type key_type; typedef typename _Ht::value_type value_type; typedef typename _Ht::hasher hasher; typedef typename _Ht::key_equal key_equal; typedef typename _Ht::size_type size_type; typedef typename _Ht::difference_type difference_type; typedef typename _Alloc::pointer pointer; typedef typename _Alloc::const_pointer const_pointer; typedef typename _Alloc::reference reference; typedef typename _Alloc::const_reference const_reference; typedef typename _Ht::const_iterator iterator; typedef typename _Ht::const_iterator const_iterator; typedef typename _Ht::allocator_type allocator_type; hasher hash_funct() const { return _M_ht.hash_funct(); } key_equal key_eq() const { return _M_ht.key_eq(); } allocator_type get_allocator() const { return _M_ht.get_allocator(); } hash_set() : _M_ht(100, hasher(), key_equal(), allocator_type()) {} explicit hash_set(size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) {} hash_set(size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) {} hash_set(size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) {} template hash_set(_InputIterator __f, _InputIterator __l) : _M_ht(100, hasher(), key_equal(), allocator_type()) { _M_ht.insert_unique(__f, __l); } template hash_set(_InputIterator __f, _InputIterator __l, size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) { _M_ht.insert_unique(__f, __l); } template hash_set(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) { _M_ht.insert_unique(__f, __l); } template hash_set(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) { _M_ht.insert_unique(__f, __l); } size_type size() const { return _M_ht.size(); } size_type max_size() const { return _M_ht.max_size(); } bool empty() const { return _M_ht.empty(); } void swap(hash_set& __hs) { _M_ht.swap(__hs._M_ht); } template friend bool operator==(const hash_set<_Val, _HF, _EqK, _Al>&, const hash_set<_Val, _HF, _EqK, _Al>&); iterator begin() const { return _M_ht.begin(); } iterator end() const { return _M_ht.end(); } pair insert(const value_type& __obj) { pair __p = _M_ht.insert_unique(__obj); return pair(__p.first, __p.second); } template void insert(_InputIterator __f, _InputIterator __l) { _M_ht.insert_unique(__f, __l); } pair insert_noresize(const value_type& __obj) { pair __p = _M_ht.insert_unique_noresize(__obj); return pair(__p.first, __p.second); } iterator find(const key_type& __key) const { return _M_ht.find(__key); } size_type count(const key_type& __key) const { return _M_ht.count(__key); } pair equal_range(const key_type& __key) const { return _M_ht.equal_range(__key); } size_type erase(const key_type& __key) {return _M_ht.erase(__key); } void erase(iterator __it) { _M_ht.erase(__it); } void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); } void clear() { _M_ht.clear(); } void resize(size_type __hint) { _M_ht.resize(__hint); } size_type bucket_count() const { return _M_ht.bucket_count(); } size_type max_bucket_count() const { return _M_ht.max_bucket_count(); } size_type elems_in_bucket(size_type __n) const { return _M_ht.elems_in_bucket(__n); } }; template inline bool operator==(const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs1, const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs2) { return __hs1._M_ht == __hs2._M_ht; } template inline bool operator!=(const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs1, const hash_set<_Value, _HashFcn, _EqualKey, _Alloc>& __hs2) { return !(__hs1 == __hs2); } template inline void swap(hash_set<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1, hash_set<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2) { __hs1.swap(__hs2); } /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template, class _EqualKey = equal_to<_Value>, class _Alloc = allocator<_Value> > class hash_multiset { // concept requirements __glibcxx_class_requires(_Value, _SGIAssignableConcept) __glibcxx_class_requires3(_HashFcn, size_t, _Value, _UnaryFunctionConcept) __glibcxx_class_requires3(_EqualKey, _Value, _Value, _BinaryPredicateConcept) private: typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>, _EqualKey, _Alloc> _Ht; _Ht _M_ht; public: typedef typename _Ht::key_type key_type; typedef typename _Ht::value_type value_type; typedef typename _Ht::hasher hasher; typedef typename _Ht::key_equal key_equal; typedef typename _Ht::size_type size_type; typedef typename _Ht::difference_type difference_type; typedef typename _Alloc::pointer pointer; typedef typename _Alloc::const_pointer const_pointer; typedef typename _Alloc::reference reference; typedef typename _Alloc::const_reference const_reference; typedef typename _Ht::const_iterator iterator; typedef typename _Ht::const_iterator const_iterator; typedef typename _Ht::allocator_type allocator_type; hasher hash_funct() const { return _M_ht.hash_funct(); } key_equal key_eq() const { return _M_ht.key_eq(); } allocator_type get_allocator() const { return _M_ht.get_allocator(); } hash_multiset() : _M_ht(100, hasher(), key_equal(), allocator_type()) {} explicit hash_multiset(size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) {} hash_multiset(size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) {} hash_multiset(size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) {} template hash_multiset(_InputIterator __f, _InputIterator __l) : _M_ht(100, hasher(), key_equal(), allocator_type()) { _M_ht.insert_equal(__f, __l); } template hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n) : _M_ht(__n, hasher(), key_equal(), allocator_type()) { _M_ht.insert_equal(__f, __l); } template hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf) : _M_ht(__n, __hf, key_equal(), allocator_type()) { _M_ht.insert_equal(__f, __l); } template hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n, const hasher& __hf, const key_equal& __eql, const allocator_type& __a = allocator_type()) : _M_ht(__n, __hf, __eql, __a) { _M_ht.insert_equal(__f, __l); } size_type size() const { return _M_ht.size(); } size_type max_size() const { return _M_ht.max_size(); } bool empty() const { return _M_ht.empty(); } void swap(hash_multiset& hs) { _M_ht.swap(hs._M_ht); } template friend bool operator==(const hash_multiset<_Val, _HF, _EqK, _Al>&, const hash_multiset<_Val, _HF, _EqK, _Al>&); iterator begin() const { return _M_ht.begin(); } iterator end() const { return _M_ht.end(); } iterator insert(const value_type& __obj) { return _M_ht.insert_equal(__obj); } template void insert(_InputIterator __f, _InputIterator __l) { _M_ht.insert_equal(__f,__l); } iterator insert_noresize(const value_type& __obj) { return _M_ht.insert_equal_noresize(__obj); } iterator find(const key_type& __key) const { return _M_ht.find(__key); } size_type count(const key_type& __key) const { return _M_ht.count(__key); } pair equal_range(const key_type& __key) const { return _M_ht.equal_range(__key); } size_type erase(const key_type& __key) { return _M_ht.erase(__key); } void erase(iterator __it) { _M_ht.erase(__it); } void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); } void clear() { _M_ht.clear(); } void resize(size_type __hint) { _M_ht.resize(__hint); } size_type bucket_count() const { return _M_ht.bucket_count(); } size_type max_bucket_count() const { return _M_ht.max_bucket_count(); } size_type elems_in_bucket(size_type __n) const { return _M_ht.elems_in_bucket(__n); } }; template inline bool operator==(const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1, const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2) { return __hs1._M_ht == __hs2._M_ht; } template inline bool operator!=(const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1, const hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2) { return !(__hs1 == __hs2); } template inline void swap(hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs1, hash_multiset<_Val, _HashFcn, _EqualKey, _Alloc>& __hs2) { __hs1.swap(__hs2); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Specialization of insert_iterator so that it will work for hash_set // and hash_multiset. template class insert_iterator<__gnu_cxx::hash_set<_Value, _HashFcn, _EqualKey, _Alloc> > { protected: typedef __gnu_cxx::hash_set<_Value, _HashFcn, _EqualKey, _Alloc> _Container; _Container* container; public: typedef _Container container_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; insert_iterator(_Container& __x) : container(&__x) {} insert_iterator(_Container& __x, typename _Container::iterator) : container(&__x) {} insert_iterator<_Container>& operator=(const typename _Container::value_type& __value) { container->insert(__value); return *this; } insert_iterator<_Container>& operator*() { return *this; } insert_iterator<_Container>& operator++() { return *this; } insert_iterator<_Container>& operator++(int) { return *this; } }; template class insert_iterator<__gnu_cxx::hash_multiset<_Value, _HashFcn, _EqualKey, _Alloc> > { protected: typedef __gnu_cxx::hash_multiset<_Value, _HashFcn, _EqualKey, _Alloc> _Container; _Container* container; typename _Container::iterator iter; public: typedef _Container container_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; insert_iterator(_Container& __x) : container(&__x) {} insert_iterator(_Container& __x, typename _Container::iterator) : container(&__x) {} insert_iterator<_Container>& operator=(const typename _Container::value_type& __value) { container->insert(__value); return *this; } insert_iterator<_Container>& operator*() { return *this; } insert_iterator<_Container>& operator++() { return *this; } insert_iterator<_Container>& operator++(int) { return *this; } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!t 8/ext/iteratornu[// HP/SGI iterator extensions -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996-1998 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file ext/iterator * This file is a GNU extension to the Standard C++ Library (possibly * containing extensions from the HP/SGI STL subset). */ #ifndef _EXT_ITERATOR #define _EXT_ITERATOR 1 #pragma GCC system_header #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // There are two signatures for distance. In addition to the one // taking two iterators and returning a result, there is another // taking two iterators and a reference-to-result variable, and // returning nothing. The latter seems to be an SGI extension. // -- pedwards template inline void __distance(_InputIterator __first, _InputIterator __last, _Distance& __n, std::input_iterator_tag) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) while (__first != __last) { ++__first; ++__n; } } template inline void __distance(_RandomAccessIterator __first, _RandomAccessIterator __last, _Distance& __n, std::random_access_iterator_tag) { // concept requirements __glibcxx_function_requires(_RandomAccessIteratorConcept< _RandomAccessIterator>) __n += __last - __first; } /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template inline void distance(_InputIterator __first, _InputIterator __last, _Distance& __n) { // concept requirements -- taken care of in __distance __distance(__first, __last, __n, std::__iterator_category(__first)); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!ς.8/ext/malloc_allocator.hnu[// Allocator that wraps "C" malloc -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/malloc_allocator.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _MALLOC_ALLOCATOR_H #define _MALLOC_ALLOCATOR_H 1 #include #include #include #include #include #if __cplusplus >= 201103L #include #endif namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using std::size_t; using std::ptrdiff_t; /** * @brief An allocator that uses malloc. * @ingroup allocators * * This is precisely the allocator defined in the C++ Standard. * - all allocation calls malloc * - all deallocation calls free */ template class malloc_allocator { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Tp* pointer; typedef const _Tp* const_pointer; typedef _Tp& reference; typedef const _Tp& const_reference; typedef _Tp value_type; template struct rebind { typedef malloc_allocator<_Tp1> other; }; #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2103. propagate_on_container_move_assignment typedef std::true_type propagate_on_container_move_assignment; #endif malloc_allocator() _GLIBCXX_USE_NOEXCEPT { } malloc_allocator(const malloc_allocator&) _GLIBCXX_USE_NOEXCEPT { } template malloc_allocator(const malloc_allocator<_Tp1>&) _GLIBCXX_USE_NOEXCEPT { } ~malloc_allocator() _GLIBCXX_USE_NOEXCEPT { } pointer address(reference __x) const _GLIBCXX_NOEXCEPT { return std::__addressof(__x); } const_pointer address(const_reference __x) const _GLIBCXX_NOEXCEPT { return std::__addressof(__x); } // NB: __n is permitted to be 0. The C++ standard says nothing // about what the return value is when __n == 0. pointer allocate(size_type __n, const void* = 0) { if (__n > this->max_size()) std::__throw_bad_alloc(); pointer __ret = 0; #if __cpp_aligned_new #if __cplusplus > 201402L && _GLIBCXX_HAVE_ALIGNED_ALLOC if (alignof(_Tp) > alignof(std::max_align_t)) { __ret = static_cast<_Tp*>(::aligned_alloc(alignof(_Tp), __n * sizeof(_Tp))); } #else # define _GLIBCXX_CHECK_MALLOC_RESULT #endif #endif if (!__ret) __ret = static_cast<_Tp*>(std::malloc(__n * sizeof(_Tp))); if (!__ret) std::__throw_bad_alloc(); #ifdef _GLIBCXX_CHECK_MALLOC_RESULT #undef _GLIBCXX_CHECK_MALLOC_RESULT if (reinterpret_cast(__ret) % alignof(_Tp)) { // Memory returned by malloc is not suitably aligned for _Tp. deallocate(__ret, __n); std::__throw_bad_alloc(); } #endif return __ret; } // __p is not permitted to be a null pointer. void deallocate(pointer __p, size_type) { std::free(static_cast(__p)); } size_type max_size() const _GLIBCXX_USE_NOEXCEPT { return size_t(-1) / sizeof(_Tp); } #if __cplusplus >= 201103L template void construct(_Up* __p, _Args&&... __args) { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); } template void destroy(_Up* __p) { __p->~_Up(); } #else // _GLIBCXX_RESOLVE_LIB_DEFECTS // 402. wrong new expression in [some_] allocator::construct void construct(pointer __p, const _Tp& __val) { ::new((void *)__p) value_type(__val); } void destroy(pointer __p) { __p->~_Tp(); } #endif }; template inline bool operator==(const malloc_allocator<_Tp>&, const malloc_allocator<_Tp>&) { return true; } template inline bool operator!=(const malloc_allocator<_Tp>&, const malloc_allocator<_Tp>&) { return false; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!  8/ext/memorynu[// Memory extensions -*- C++ -*- // Copyright (C) 2002-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file ext/memory * This file is a GNU extension to the Standard C++ Library (possibly * containing extensions from the HP/SGI STL subset). */ #ifndef _EXT_MEMORY #define _EXT_MEMORY 1 #pragma GCC system_header #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using std::ptrdiff_t; using std::pair; using std::__iterator_category; using std::_Temporary_buffer; template pair<_InputIter, _ForwardIter> __uninitialized_copy_n(_InputIter __first, _Size __count, _ForwardIter __result, std::input_iterator_tag) { _ForwardIter __cur = __result; __try { for (; __count > 0 ; --__count, ++__first, ++__cur) std::_Construct(&*__cur, *__first); return pair<_InputIter, _ForwardIter>(__first, __cur); } __catch(...) { std::_Destroy(__result, __cur); __throw_exception_again; } } template inline pair<_RandomAccessIter, _ForwardIter> __uninitialized_copy_n(_RandomAccessIter __first, _Size __count, _ForwardIter __result, std::random_access_iterator_tag) { _RandomAccessIter __last = __first + __count; return (pair<_RandomAccessIter, _ForwardIter> (__last, std::uninitialized_copy(__first, __last, __result))); } template inline pair<_InputIter, _ForwardIter> __uninitialized_copy_n(_InputIter __first, _Size __count, _ForwardIter __result) { return __gnu_cxx::__uninitialized_copy_n(__first, __count, __result, __iterator_category(__first)); } /** * @brief Copies the range [first,last) into result. * @param __first An input iterator. * @param __count Length * @param __result An output iterator. * @return __result + (__first + __count) * @ingroup SGIextensions * * Like copy(), but does not require an initialized output range. */ template inline pair<_InputIter, _ForwardIter> uninitialized_copy_n(_InputIter __first, _Size __count, _ForwardIter __result) { return __gnu_cxx::__uninitialized_copy_n(__first, __count, __result, __iterator_category(__first)); } // An alternative version of uninitialized_copy_n that constructs // and destroys objects with a user-provided allocator. template pair<_InputIter, _ForwardIter> __uninitialized_copy_n_a(_InputIter __first, _Size __count, _ForwardIter __result, _Allocator __alloc) { _ForwardIter __cur = __result; __try { for (; __count > 0 ; --__count, ++__first, ++__cur) __alloc.construct(&*__cur, *__first); return pair<_InputIter, _ForwardIter>(__first, __cur); } __catch(...) { std::_Destroy(__result, __cur, __alloc); __throw_exception_again; } } template inline pair<_InputIter, _ForwardIter> __uninitialized_copy_n_a(_InputIter __first, _Size __count, _ForwardIter __result, std::allocator<_Tp>) { return __gnu_cxx::uninitialized_copy_n(__first, __count, __result); } /** * This class provides similar behavior and semantics of the standard * functions get_temporary_buffer() and return_temporary_buffer(), but * encapsulated in a type vaguely resembling a standard container. * * By default, a temporary_buffer stores space for objects of * whatever type the Iter iterator points to. It is constructed from a * typical [first,last) range, and provides the begin(), end(), size() * functions, as well as requested_size(). For non-trivial types, copies * of *first will be used to initialize the storage. * * @c malloc is used to obtain underlying storage. * * Like get_temporary_buffer(), not all the requested memory may be * available. Ideally, the created buffer will be large enough to hold a * copy of [first,last), but if size() is less than requested_size(), * then this didn't happen. * * @ingroup SGIextensions */ template ::value_type > struct temporary_buffer : public _Temporary_buffer<_ForwardIterator, _Tp> { /// Requests storage large enough to hold a copy of [first,last). temporary_buffer(_ForwardIterator __first, _ForwardIterator __last) : _Temporary_buffer<_ForwardIterator, _Tp>(__first, __last) { } /// Destroys objects and frees storage. ~temporary_buffer() { } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif PK!.[[8/ext/mt_allocator.hnu[// MT-optimized allocator -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/mt_allocator.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _MT_ALLOCATOR_H #define _MT_ALLOCATOR_H 1 #include #include #include #include #include #if __cplusplus >= 201103L #include #endif namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using std::size_t; using std::ptrdiff_t; typedef void (*__destroy_handler)(void*); /// Base class for pool object. struct __pool_base { // Using short int as type for the binmap implies we are never // caching blocks larger than 32768 with this allocator. typedef unsigned short int _Binmap_type; // Variables used to configure the behavior of the allocator, // assigned and explained in detail below. struct _Tune { // Compile time constants for the default _Tune values. enum { _S_align = 8 }; enum { _S_max_bytes = 128 }; enum { _S_min_bin = 8 }; enum { _S_chunk_size = 4096 - 4 * sizeof(void*) }; enum { _S_max_threads = 4096 }; enum { _S_freelist_headroom = 10 }; // Alignment needed. // NB: In any case must be >= sizeof(_Block_record), that // is 4 on 32 bit machines and 8 on 64 bit machines. size_t _M_align; // Allocation requests (after round-up to power of 2) below // this value will be handled by the allocator. A raw new/ // call will be used for requests larger than this value. // NB: Must be much smaller than _M_chunk_size and in any // case <= 32768. size_t _M_max_bytes; // Size in bytes of the smallest bin. // NB: Must be a power of 2 and >= _M_align (and of course // much smaller than _M_max_bytes). size_t _M_min_bin; // In order to avoid fragmenting and minimize the number of // new() calls we always request new memory using this // value. Based on previous discussions on the libstdc++ // mailing list we have chosen the value below. // See http://gcc.gnu.org/ml/libstdc++/2001-07/msg00077.html // NB: At least one order of magnitude > _M_max_bytes. size_t _M_chunk_size; // The maximum number of supported threads. For // single-threaded operation, use one. Maximum values will // vary depending on details of the underlying system. (For // instance, Linux 2.4.18 reports 4070 in // /proc/sys/kernel/threads-max, while Linux 2.6.6 reports // 65534) size_t _M_max_threads; // Each time a deallocation occurs in a threaded application // we make sure that there are no more than // _M_freelist_headroom % of used memory on the freelist. If // the number of additional records is more than // _M_freelist_headroom % of the freelist, we move these // records back to the global pool. size_t _M_freelist_headroom; // Set to true forces all allocations to use new(). bool _M_force_new; explicit _Tune() : _M_align(_S_align), _M_max_bytes(_S_max_bytes), _M_min_bin(_S_min_bin), _M_chunk_size(_S_chunk_size), _M_max_threads(_S_max_threads), _M_freelist_headroom(_S_freelist_headroom), _M_force_new(std::getenv("GLIBCXX_FORCE_NEW") ? true : false) { } explicit _Tune(size_t __align, size_t __maxb, size_t __minbin, size_t __chunk, size_t __maxthreads, size_t __headroom, bool __force) : _M_align(__align), _M_max_bytes(__maxb), _M_min_bin(__minbin), _M_chunk_size(__chunk), _M_max_threads(__maxthreads), _M_freelist_headroom(__headroom), _M_force_new(__force) { } }; struct _Block_address { void* _M_initial; _Block_address* _M_next; }; const _Tune& _M_get_options() const { return _M_options; } void _M_set_options(_Tune __t) { if (!_M_init) _M_options = __t; } bool _M_check_threshold(size_t __bytes) { return __bytes > _M_options._M_max_bytes || _M_options._M_force_new; } size_t _M_get_binmap(size_t __bytes) { return _M_binmap[__bytes]; } size_t _M_get_align() { return _M_options._M_align; } explicit __pool_base() : _M_options(_Tune()), _M_binmap(0), _M_init(false) { } explicit __pool_base(const _Tune& __options) : _M_options(__options), _M_binmap(0), _M_init(false) { } private: explicit __pool_base(const __pool_base&); __pool_base& operator=(const __pool_base&); protected: // Configuration options. _Tune _M_options; _Binmap_type* _M_binmap; // Configuration of the pool object via _M_options can happen // after construction but before initialization. After // initialization is complete, this variable is set to true. bool _M_init; }; /** * @brief Data describing the underlying memory pool, parameterized on * threading support. */ template class __pool; /// Specialization for single thread. template<> class __pool : public __pool_base { public: union _Block_record { // Points to the block_record of the next free block. _Block_record* _M_next; }; struct _Bin_record { // An "array" of pointers to the first free block. _Block_record** _M_first; // A list of the initial addresses of all allocated blocks. _Block_address* _M_address; }; void _M_initialize_once() { if (__builtin_expect(_M_init == false, false)) _M_initialize(); } void _M_destroy() throw(); char* _M_reserve_block(size_t __bytes, const size_t __thread_id); void _M_reclaim_block(char* __p, size_t __bytes) throw (); size_t _M_get_thread_id() { return 0; } const _Bin_record& _M_get_bin(size_t __which) { return _M_bin[__which]; } void _M_adjust_freelist(const _Bin_record&, _Block_record*, size_t) { } explicit __pool() : _M_bin(0), _M_bin_size(1) { } explicit __pool(const __pool_base::_Tune& __tune) : __pool_base(__tune), _M_bin(0), _M_bin_size(1) { } private: // An "array" of bin_records each of which represents a specific // power of 2 size. Memory to this "array" is allocated in // _M_initialize(). _Bin_record* _M_bin; // Actual value calculated in _M_initialize(). size_t _M_bin_size; void _M_initialize(); }; #ifdef __GTHREADS /// Specialization for thread enabled, via gthreads.h. template<> class __pool : public __pool_base { public: // Each requesting thread is assigned an id ranging from 1 to // _S_max_threads. Thread id 0 is used as a global memory pool. // In order to get constant performance on the thread assignment // routine, we keep a list of free ids. When a thread first // requests memory we remove the first record in this list and // stores the address in a __gthread_key. When initializing the // __gthread_key we specify a destructor. When this destructor // (i.e. the thread dies) is called, we return the thread id to // the front of this list. struct _Thread_record { // Points to next free thread id record. NULL if last record in list. _Thread_record* _M_next; // Thread id ranging from 1 to _S_max_threads. size_t _M_id; }; union _Block_record { // Points to the block_record of the next free block. _Block_record* _M_next; // The thread id of the thread which has requested this block. size_t _M_thread_id; }; struct _Bin_record { // An "array" of pointers to the first free block for each // thread id. Memory to this "array" is allocated in // _S_initialize() for _S_max_threads + global pool 0. _Block_record** _M_first; // A list of the initial addresses of all allocated blocks. _Block_address* _M_address; // An "array" of counters used to keep track of the amount of // blocks that are on the freelist/used for each thread id. // - Note that the second part of the allocated _M_used "array" // actually hosts (atomic) counters of reclaimed blocks: in // _M_reserve_block and in _M_reclaim_block those numbers are // subtracted from the first ones to obtain the actual size // of the "working set" of the given thread. // - Memory to these "arrays" is allocated in _S_initialize() // for _S_max_threads + global pool 0. size_t* _M_free; size_t* _M_used; // Each bin has its own mutex which is used to ensure data // integrity while changing "ownership" on a block. The mutex // is initialized in _S_initialize(). __gthread_mutex_t* _M_mutex; }; // XXX GLIBCXX_ABI Deprecated void _M_initialize(__destroy_handler); void _M_initialize_once() { if (__builtin_expect(_M_init == false, false)) _M_initialize(); } void _M_destroy() throw(); char* _M_reserve_block(size_t __bytes, const size_t __thread_id); void _M_reclaim_block(char* __p, size_t __bytes) throw (); const _Bin_record& _M_get_bin(size_t __which) { return _M_bin[__which]; } void _M_adjust_freelist(const _Bin_record& __bin, _Block_record* __block, size_t __thread_id) { if (__gthread_active_p()) { __block->_M_thread_id = __thread_id; --__bin._M_free[__thread_id]; ++__bin._M_used[__thread_id]; } } // XXX GLIBCXX_ABI Deprecated void _M_destroy_thread_key(void*) throw (); size_t _M_get_thread_id(); explicit __pool() : _M_bin(0), _M_bin_size(1), _M_thread_freelist(0) { } explicit __pool(const __pool_base::_Tune& __tune) : __pool_base(__tune), _M_bin(0), _M_bin_size(1), _M_thread_freelist(0) { } private: // An "array" of bin_records each of which represents a specific // power of 2 size. Memory to this "array" is allocated in // _M_initialize(). _Bin_record* _M_bin; // Actual value calculated in _M_initialize(). size_t _M_bin_size; _Thread_record* _M_thread_freelist; void* _M_thread_freelist_initial; void _M_initialize(); }; #endif template