Marshall Clow | 98760c1 | 2014-01-16 16:58:45 +0000 | [diff] [blame] | 1 | //===----------------------------------------------------------------------===// |
| 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 Hinnant | bc8d3f9 | 2010-05-11 19:42:16 +0000 | [diff] [blame] | 10 | #ifndef STACK_ALLOCATOR_H |
| 11 | #define STACK_ALLOCATOR_H |
| 12 | |
| 13 | #include <cstddef> |
| 14 | #include <new> |
| 15 | |
| 16 | template <class T, std::size_t N> |
| 17 | class stack_allocator |
| 18 | { |
| 19 | char buf_[sizeof(T)*N]; |
| 20 | char* ptr_; |
| 21 | public: |
| 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 | |
| 34 | private: |
| 35 | stack_allocator(const stack_allocator&);// = delete; |
| 36 | stack_allocator& operator=(const stack_allocator&);// = delete; |
| 37 | |
| 38 | public: |
| 39 | pointer allocate(size_type n, const void* = 0) |
| 40 | { |
Howard Hinnant | 9976b55 | 2013-03-23 17:27:16 +0000 | [diff] [blame] | 41 | if (n > N - (ptr_ - buf_) / sizeof(value_type)) { |
| 42 | #ifndef _LIBCPP_NO_EXCEPTIONS |
Howard Hinnant | bc8d3f9 | 2010-05-11 19:42:16 +0000 | [diff] [blame] | 43 | throw std::bad_alloc(); |
Howard Hinnant | 9976b55 | 2013-03-23 17:27:16 +0000 | [diff] [blame] | 44 | #else |
| 45 | std::terminate(); |
| 46 | #endif |
| 47 | } |
Howard Hinnant | bc8d3f9 | 2010-05-11 19:42:16 +0000 | [diff] [blame] | 48 | 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 | |
| 61 | template <class T, std::size_t N> |
| 62 | inline |
| 63 | void |
| 64 | swap(stack_allocator<T, N>& x, stack_allocator<T, N>& y) {} |
| 65 | |
Howard Hinnant | 6046ace | 2010-08-22 00:15:28 +0000 | [diff] [blame] | 66 | #endif // STACK_ALLOCATOR_H |