1 // -*- C++ -*- 2 //===----------------------------------------------------------------------===// 3 // 4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 5 // See https://llvm.org/LICENSE.txt for license information. 6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 7 // 8 //===----------------------------------------------------------------------===// 9 10 #ifndef _LIBCPP_SSO_ALLOCATOR_H 11 #define _LIBCPP_SSO_ALLOCATOR_H 12 13 #include <__config> 14 #include <cstddef> 15 #include <memory> 16 #include <new> 17 #include <type_traits> 18 19 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) 20 #pragma GCC system_header 21 #endif 22 23 _LIBCPP_BEGIN_NAMESPACE_STD 24 25 template <class _Tp, size_t _Np> class _LIBCPP_HIDDEN __sso_allocator; 26 27 template <size_t _Np> 28 class _LIBCPP_HIDDEN __sso_allocator<void, _Np> 29 { 30 public: 31 typedef const void* const_pointer; 32 typedef void value_type; 33 }; 34 35 template <class _Tp, size_t _Np> 36 class _LIBCPP_HIDDEN __sso_allocator 37 { 38 alignas(_Tp) std::byte buf_[sizeof(_Tp) * _Np]; 39 bool __allocated_; 40 public: 41 typedef size_t size_type; 42 typedef _Tp* pointer; 43 typedef _Tp value_type; 44 45 template <class U> 46 struct rebind { 47 using other = __sso_allocator<U, _Np>; 48 }; 49 __sso_allocator()50 _LIBCPP_INLINE_VISIBILITY __sso_allocator() throw() : __allocated_(false) {} __sso_allocator(const __sso_allocator &)51 _LIBCPP_INLINE_VISIBILITY __sso_allocator(const __sso_allocator&) throw() : __allocated_(false) {} __sso_allocator(const __sso_allocator<_Up,_Np> &)52 template <class _Up> _LIBCPP_INLINE_VISIBILITY __sso_allocator(const __sso_allocator<_Up, _Np>&) throw() 53 : __allocated_(false) {} 54 private: 55 __sso_allocator& operator=(const __sso_allocator&); 56 public: 57 _LIBCPP_INLINE_VISIBILITY pointer allocate(size_type __n, typename __sso_allocator<void, _Np>::const_pointer = nullptr) 58 { 59 if (!__allocated_ && __n <= _Np) 60 { 61 __allocated_ = true; 62 return (pointer)&buf_; 63 } 64 return allocator<_Tp>().allocate(__n); 65 } deallocate(pointer __p,size_type __n)66 _LIBCPP_INLINE_VISIBILITY void deallocate(pointer __p, size_type __n) 67 { 68 if (__p == (pointer)&buf_) 69 __allocated_ = false; 70 else 71 allocator<_Tp>().deallocate(__p, __n); 72 } max_size()73 _LIBCPP_INLINE_VISIBILITY size_type max_size() const throw() {return size_type(~0) / sizeof(_Tp);} 74 75 _LIBCPP_INLINE_VISIBILITY 76 bool operator==(const __sso_allocator& __a) const {return &buf_ == &__a.buf_;} 77 _LIBCPP_INLINE_VISIBILITY 78 bool operator!=(const __sso_allocator& __a) const {return &buf_ != &__a.buf_;} 79 }; 80 81 _LIBCPP_END_NAMESPACE_STD 82 83 #endif // _LIBCPP_SSO_ALLOCATOR_H 84