blob: d5fab025c9d08fa6f77902c6800a6b13bab956b2 [file] [log] [blame]
Marshall Clow98760c12014-01-16 16:58:45 +00001//===----------------------------------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is dual licensed under the MIT and the University of Illinois Open
6// Source Licenses. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000010#ifndef STACK_ALLOCATOR_H
11#define STACK_ALLOCATOR_H
12
13#include <cstddef>
14#include <new>
15
16template <class T, std::size_t N>
17class stack_allocator
18{
19 char buf_[sizeof(T)*N];
20 char* ptr_;
21public:
22 typedef T value_type;
23 typedef value_type* pointer;
24 typedef const value_type* const_pointer;
25 typedef value_type& reference;
26 typedef const value_type& const_reference;
27 typedef std::size_t size_type;
28 typedef std::ptrdiff_t difference_type;
29
30 template <class U> struct rebind {typedef stack_allocator<U, N> other;};
31
32 stack_allocator() : ptr_(buf_) {}
33
34private:
35 stack_allocator(const stack_allocator&);// = delete;
36 stack_allocator& operator=(const stack_allocator&);// = delete;
37
38public:
39 pointer allocate(size_type n, const void* = 0)
40 {
Howard Hinnant9976b552013-03-23 17:27:16 +000041 if (n > N - (ptr_ - buf_) / sizeof(value_type)) {
42#ifndef _LIBCPP_NO_EXCEPTIONS
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000043 throw std::bad_alloc();
Howard Hinnant9976b552013-03-23 17:27:16 +000044#else
45 std::terminate();
46#endif
47 }
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000048 pointer r = (T*)ptr_;
49 ptr_ += n * sizeof(T);
50 return r;
51 }
52 void deallocate(pointer p, size_type n)
53 {
54 if ((char*)(p + n) == ptr_)
55 ptr_ = (char*)p;
56 }
57
58 size_type max_size() const {return N;}
59};
60
61template <class T, std::size_t N>
62inline
63void
64swap(stack_allocator<T, N>& x, stack_allocator<T, N>& y) {}
65
Howard Hinnant6046ace2010-08-22 00:15:28 +000066#endif // STACK_ALLOCATOR_H