blob: e6af473816ad582e3939f005ca3a92b26852835c [file] [log] [blame]
Howard Hinnantbc8d3f92010-05-11 19:42:16 +00001#ifndef STACK_ALLOCATOR_H
2#define STACK_ALLOCATOR_H
3
4#include <cstddef>
5#include <new>
6
7template <class T, std::size_t N>
8class stack_allocator
9{
10 char buf_[sizeof(T)*N];
11 char* ptr_;
12public:
13 typedef T value_type;
14 typedef value_type* pointer;
15 typedef const value_type* const_pointer;
16 typedef value_type& reference;
17 typedef const value_type& const_reference;
18 typedef std::size_t size_type;
19 typedef std::ptrdiff_t difference_type;
20
21 template <class U> struct rebind {typedef stack_allocator<U, N> other;};
22
23 stack_allocator() : ptr_(buf_) {}
24
25private:
26 stack_allocator(const stack_allocator&);// = delete;
27 stack_allocator& operator=(const stack_allocator&);// = delete;
28
29public:
30 pointer allocate(size_type n, const void* = 0)
31 {
Howard Hinnant9976b552013-03-23 17:27:16 +000032 if (n > N - (ptr_ - buf_) / sizeof(value_type)) {
33#ifndef _LIBCPP_NO_EXCEPTIONS
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000034 throw std::bad_alloc();
Howard Hinnant9976b552013-03-23 17:27:16 +000035#else
36 std::terminate();
37#endif
38 }
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000039 pointer r = (T*)ptr_;
40 ptr_ += n * sizeof(T);
41 return r;
42 }
43 void deallocate(pointer p, size_type n)
44 {
45 if ((char*)(p + n) == ptr_)
46 ptr_ = (char*)p;
47 }
48
49 size_type max_size() const {return N;}
50};
51
52template <class T, std::size_t N>
53inline
54void
55swap(stack_allocator<T, N>& x, stack_allocator<T, N>& y) {}
56
Howard Hinnant6046ace2010-08-22 00:15:28 +000057#endif // STACK_ALLOCATOR_H