blob: 17e232925da456d9c37e5ef030728e0815127161 [file] [log] [blame]
Howard Hinnantbc8d3f92010-05-11 19:42:16 +00001// -*- C++ -*-
2//===----------------------------------------------------------------------===//
3//
Howard Hinnantf5256e12010-05-11 21:36:01 +00004// The LLVM Compiler Infrastructure
Howard Hinnantbc8d3f92010-05-11 19:42:16 +00005//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
8//
9//===----------------------------------------------------------------------===//
10
11#ifndef _LIBCPP___SSO_ALLOCATOR
12#define _LIBCPP___SSO_ALLOCATOR
13
14#include <__config>
15#include <type_traits>
16#include <new>
17
18#pragma GCC system_header
19
20_LIBCPP_BEGIN_NAMESPACE_STD
21
22template <class _Tp, size_t _N> class _LIBCPP_HIDDEN __sso_allocator;
23
24template <size_t _N>
25class _LIBCPP_HIDDEN __sso_allocator<void, _N>
26{
27public:
28 typedef const void* const_pointer;
29 typedef void value_type;
30};
31
32template <class _Tp, size_t _N>
33class _LIBCPP_HIDDEN __sso_allocator
34{
35 typename aligned_storage<sizeof(_Tp) * _N>::type buf_;
36 bool __allocated_;
37public:
38 typedef size_t size_type;
39 typedef _Tp* pointer;
40 typedef _Tp value_type;
41
42 _LIBCPP_INLINE_VISIBILITY __sso_allocator() throw() : __allocated_(false) {}
43 _LIBCPP_INLINE_VISIBILITY __sso_allocator(const __sso_allocator&) throw() : __allocated_(false) {}
44 template <class _Up> _LIBCPP_INLINE_VISIBILITY __sso_allocator(const __sso_allocator<_Up, _N>&) throw()
45 : __allocated_(false) {}
46private:
47 __sso_allocator& operator=(const __sso_allocator&);
48public:
49 _LIBCPP_INLINE_VISIBILITY pointer allocate(size_type __n, typename __sso_allocator<void, _N>::const_pointer = 0)
50 {
51 if (!__allocated_ && __n <= _N)
52 {
53 __allocated_ = true;
54 return (pointer)&buf_;
55 }
56 return static_cast<pointer>(::operator new(__n * sizeof(_Tp)));
57 }
58 _LIBCPP_INLINE_VISIBILITY void deallocate(pointer __p, size_type)
59 {
60 if (__p == (pointer)&buf_)
61 __allocated_ = false;
62 else
63 ::operator delete(__p);
64 }
65 _LIBCPP_INLINE_VISIBILITY size_type max_size() const throw() {return size_type(~0) / sizeof(_Tp);}
66
67 bool operator==(__sso_allocator& __a) const {return &buf_ == &__a.buf_;}
68 bool operator!=(__sso_allocator& __a) const {return &buf_ != &__a.buf_;}
69};
70
71_LIBCPP_END_NAMESPACE_STD
72
73#endif // _LIBCPP___SSO_ALLOCATOR