blob: d25fc484d388352b3632db73b09b07fb549781d1 [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//
Howard Hinnantb64f8b02010-11-16 22:09:02 +00006// This file is dual licensed under the MIT and the University of Illinois Open
7// Source Licenses. See LICENSE.TXT for details.
Howard Hinnantbc8d3f92010-05-11 19:42:16 +00008//
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
Howard Hinnant333f50d2010-09-21 20:16:37 +000067 _LIBCPP_INLINE_VISIBILITY
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000068 bool operator==(__sso_allocator& __a) const {return &buf_ == &__a.buf_;}
Howard Hinnant333f50d2010-09-21 20:16:37 +000069 _LIBCPP_INLINE_VISIBILITY
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000070 bool operator!=(__sso_allocator& __a) const {return &buf_ != &__a.buf_;}
71};
72
73_LIBCPP_END_NAMESPACE_STD
74
75#endif // _LIBCPP___SSO_ALLOCATOR