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> |
26 | class _LIBCPP_HIDDEN __sso_allocator; |
27 | |
28 | template <size_t _Np> |
29 | class _LIBCPP_HIDDEN __sso_allocator<void, _Np> { |
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 | alignas(_Tp) std::byte buf_[sizeof(_Tp) * _Np]; |
38 | bool __allocated_; |
39 | |
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 | |
50 | _LIBCPP_HIDE_FROM_ABI __sso_allocator() throw() : __allocated_(false) {} |
51 | _LIBCPP_HIDE_FROM_ABI __sso_allocator(const __sso_allocator&) throw() : __allocated_(false) {} |
52 | template <class _Up> |
53 | _LIBCPP_HIDE_FROM_ABI __sso_allocator(const __sso_allocator<_Up, _Np>&) throw() : __allocated_(false) {} |
54 | |
55 | private: |
56 | __sso_allocator& operator=(const __sso_allocator&); |
57 | |
58 | public: |
59 | _LIBCPP_HIDE_FROM_ABI pointer allocate(size_type __n, typename __sso_allocator<void, _Np>::const_pointer = nullptr) { |
60 | if (!__allocated_ && __n <= _Np) { |
61 | __allocated_ = true; |
62 | return (pointer)&buf_; |
63 | } |
64 | return allocator<_Tp>().allocate(__n); |
65 | } |
66 | _LIBCPP_HIDE_FROM_ABI void deallocate(pointer __p, size_type __n) { |
67 | if (__p == (pointer)&buf_) |
68 | __allocated_ = false; |
69 | else |
70 | allocator<_Tp>().deallocate(__p, __n); |
71 | } |
72 | _LIBCPP_HIDE_FROM_ABI size_type max_size() const throw() { return size_type(~0) / sizeof(_Tp); } |
73 | |
74 | _LIBCPP_HIDE_FROM_ABI bool operator==(const __sso_allocator& __a) const { return &buf_ == &__a.buf_; } |
75 | _LIBCPP_HIDE_FROM_ABI bool operator!=(const __sso_allocator& __a) const { return &buf_ != &__a.buf_; } |
76 | }; |
77 | |
78 | _LIBCPP_END_NAMESPACE_STD |
79 | |
80 | #endif // _LIBCPP_SSO_ALLOCATOR_H |
81 | |