| 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 |
| 11 | #define _LIBCPP___SSO_ALLOCATOR |
| 12 | |
| 13 | #include <__config> |
| 14 | #include <type_traits> |
| 15 | #include <new> |
| 16 | |
| 17 | #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) |
| 18 | #pragma GCC system_header |
| 19 | #endif |
| 20 | |
| 21 | _LIBCPP_BEGIN_NAMESPACE_STD |
| 22 | |
| 23 | template <class _Tp, size_t _Np> class _LIBCPP_HIDDEN __sso_allocator; |
| 24 | |
| 25 | template <size_t _Np> |
| 26 | class _LIBCPP_HIDDEN __sso_allocator<void, _Np> |
| 27 | { |
| 28 | public: |
| 29 | typedef const void* const_pointer; |
| 30 | typedef void value_type; |
| 31 | }; |
| 32 | |
| 33 | template <class _Tp, size_t _Np> |
| 34 | class _LIBCPP_HIDDEN __sso_allocator |
| 35 | { |
| 36 | typename aligned_storage<sizeof(_Tp) * _Np>::type buf_; |
| 37 | bool __allocated_; |
| 38 | public: |
| 39 | typedef size_t size_type; |
| 40 | typedef _Tp* pointer; |
| 41 | typedef _Tp value_type; |
| 42 | |
| 43 | _LIBCPP_INLINE_VISIBILITY __sso_allocator() throw() : __allocated_(false) {} |
| 44 | _LIBCPP_INLINE_VISIBILITY __sso_allocator(const __sso_allocator&) throw() : __allocated_(false) {} |
| 45 | template <class _Up> _LIBCPP_INLINE_VISIBILITY __sso_allocator(const __sso_allocator<_Up, _Np>&) throw() |
| 46 | : __allocated_(false) {} |
| 47 | private: |
| 48 | __sso_allocator& operator=(const __sso_allocator&); |
| 49 | public: |
| 50 | _LIBCPP_INLINE_VISIBILITY pointer allocate(size_type __n, typename __sso_allocator<void, _Np>::const_pointer = 0) |
| 51 | { |
| 52 | if (!__allocated_ && __n <= _Np) |
| 53 | { |
| 54 | __allocated_ = true; |
| 55 | return (pointer)&buf_; |
| 56 | } |
| 57 | return static_cast<pointer>(_VSTD::__libcpp_allocate(__n * sizeof(_Tp), _LIBCPP_ALIGNOF(_Tp))); |
| 58 | } |
| 59 | _LIBCPP_INLINE_VISIBILITY void deallocate(pointer __p, size_type __n) |
| 60 | { |
| 61 | if (__p == (pointer)&buf_) |
| 62 | __allocated_ = false; |
| 63 | else |
| 64 | _VSTD::__libcpp_deallocate(__p, __n * sizeof(_Tp), _LIBCPP_ALIGNOF(_Tp)); |
| 65 | } |
| 66 | _LIBCPP_INLINE_VISIBILITY size_type max_size() const throw() {return size_type(~0) / sizeof(_Tp);} |
| 67 | |
| 68 | _LIBCPP_INLINE_VISIBILITY |
| 69 | bool operator==(__sso_allocator& __a) const {return &buf_ == &__a.buf_;} |
| 70 | _LIBCPP_INLINE_VISIBILITY |
| 71 | bool operator!=(__sso_allocator& __a) const {return &buf_ != &__a.buf_;} |
| 72 | }; |
| 73 | |
| 74 | _LIBCPP_END_NAMESPACE_STD |
| 75 | |
| 76 | #endif // _LIBCPP___SSO_ALLOCATOR |
| 77 | |