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 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 stack_allocator()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 { 41 if (n > N - (ptr_ - buf_) / sizeof(value_type)) { 42 #ifndef _LIBCPP_NO_EXCEPTIONS 43 throw std::bad_alloc(); 44 #else 45 std::terminate(); 46 #endif 47 } 48 pointer r = (T*)ptr_; 49 ptr_ += n * sizeof(T); 50 return r; 51 } deallocate(pointer p,size_type n)52 void deallocate(pointer p, size_type n) 53 { 54 if ((char*)(p + n) == ptr_) 55 ptr_ = (char*)p; 56 } 57 max_size()58 size_type max_size() const {return N;} 59 }; 60 61 template <class T, std::size_t N> 62 inline 63 void swap(stack_allocator<T,N> & x,stack_allocator<T,N> & y)64 swap(stack_allocator<T, N>& x, stack_allocator<T, N>& y) {} 65 66 #endif // STACK_ALLOCATOR_H 67