Skip to content

Commit c907a24

Browse files
committed
Add stack_alloc.h
1 parent f596876 commit c907a24

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

Diff for: stack_alloc.h

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
#ifndef STACK_ALLOC_H
2+
#define STACK_ALLOC_H
3+
4+
#define HAS_TYPE_TRAITS 0
5+
6+
#include <cstddef>
7+
8+
#if HAS_TYPE_TRAITS
9+
#include <type_traits>
10+
#else
11+
#include <tr1/type_traits>
12+
#endif
13+
14+
template <class T, std::size_t N> class stack_alloc;
15+
16+
template <std::size_t N>
17+
class stack_alloc<void, N>
18+
{
19+
public:
20+
typedef const void* const_pointer;
21+
typedef void value_type;
22+
};
23+
24+
template <class T, std::size_t N>
25+
class stack_alloc
26+
{
27+
public:
28+
typedef std::size_t size_type;
29+
typedef T value_type;
30+
typedef value_type* pointer;
31+
typedef const value_type* const_pointer;
32+
typedef value_type& reference;
33+
typedef const value_type& const_reference;
34+
35+
private:
36+
#if HAS_TYPE_TRAITS
37+
typename std::aligned_storage<sizeof(T) * N, 16>::type buf_;
38+
#else
39+
typename std::tr1::aligned_storage<sizeof(T) * N, 16>::type buf_;
40+
#endif
41+
pointer ptr_;
42+
43+
public:
44+
stack_alloc() throw() : ptr_((pointer)&buf_) {}
45+
stack_alloc(const stack_alloc&) throw() : ptr_((pointer)&buf_) {}
46+
template <class U> stack_alloc(const stack_alloc<U, N>&) throw()
47+
: ptr_((pointer)&buf_) {}
48+
49+
template <class U> struct rebind {typedef stack_alloc<U, N> other;};
50+
private:
51+
stack_alloc& operator=(const stack_alloc&);
52+
public:
53+
pointer allocate(size_type n, typename stack_alloc<void, N>::const_pointer = 0)
54+
{
55+
if ((pointer)&buf_ + N - ptr_ >= n)
56+
{
57+
pointer r = ptr_;
58+
ptr_ += n;
59+
return r;
60+
}
61+
return static_cast<pointer>(::operator new(n * sizeof(T)));
62+
}
63+
void deallocate(pointer p, size_type n)
64+
{
65+
if ((pointer)&buf_ <= p && p < (pointer)&buf_ + N)
66+
{
67+
if (p + n == ptr_)
68+
ptr_ = p;
69+
}
70+
else
71+
::operator delete(p);
72+
}
73+
size_type max_size() const throw() {return size_type(~0) / sizeof(T);}
74+
75+
void destroy(T* p) {p->~T();}
76+
77+
void
78+
construct(pointer p)
79+
{
80+
::new((void*)p) T();
81+
}
82+
83+
template <class A0>
84+
void
85+
construct(pointer p, const A0& a0)
86+
{
87+
::new((void*)p) T(a0);
88+
}
89+
90+
bool operator==(stack_alloc& a) const {return &buf_ == &a.buf_;}
91+
bool operator!=(stack_alloc& a) const {return &buf_ != &a.buf_;}
92+
};
93+
94+
#endif // STACK_ALLOC_H

0 commit comments

Comments
 (0)