summaryrefslogtreecommitdiff
path: root/a6/stack_new.cc
blob: 49f234f959cd4480bea13d918f4bab3390f168a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <iostream>
#include <string>
#include <functional>
#include <stdexcept>

#include "generator.h"

// Universal allocator
namespace memory
{
	void* ptr{};
	std::size_t n{};
}

void* operator new(std::size_t n)// throw(std::bad_alloc)
{
	std::cout << "new (" << n << " bytes from "
	          << memory::ptr << " which is size " << memory::n << ")\n";

	if(memory::ptr == nullptr) throw std::bad_alloc();
	if(n > memory::n) throw std::bad_alloc();

	auto ptr = memory::ptr;
	memory::ptr = nullptr; // use only once
	memory::n = 0;

	return ptr;
}

void operator delete(void*) throw()
{
	std::cout << "delete\n";
	// Do nothing. actual memory is allocated on the stack
}

void operator delete(void*, std::size_t) throw()
{
	std::cout << "delete[]\n";
	// Do nothing. actual memory is allocated on the stack
}

template<std::size_t S, typename T = char>
class StackNew
{
public:
	StackNew()
	{
		std::cout << "StackNew ptr=" << (void*)buf
		          << " of size " << S * sizeof(T) << '\n';
		memory::ptr = buf;
		memory::n = S * sizeof(T);
	}

private:
	T buf[S];
};

template<typename T>
Generator<T> iota(T start)
{
	while(true)
	{
		co_yield start++;
	}
}

int main()
{
	std::cout << " ** std::string:\n";
	{
		StackNew<100> buffer;
		std::string str{"hello allocating string world"};

		try
		{
			str.reserve(50); // no stack buffer supplied so throws std::bad_alloc
		}
		catch(std::bad_alloc &e)
		{
			std::cout << "Stack buffer missing!\n";
		}
	}
	std::cout << '\n';


	std::cout << " ** std::vector:\n";
	{
		StackNew<10, int> buffer;
		std::vector<int> vec{1,2,3,4,5,6,7,8,9,10};

		StackNew<20, int> buffer2;
		try
		{
			vec.resize(21); // throws std::bad_alloc
		}
		catch(std::bad_alloc &e)
		{
			std::cout << "Stack buffer was too small!\n";
		}
	}
	std::cout << '\n';


	std::cout << " ** std::function:\n";
	{
		std::function<int()> f;
		{
			StackNew<32> buffer;
			char foo[32]{};
			f = [foo]()
			    {
				    int i = 0;
				    for(auto v : foo)
				    {
					    i += v;
				    }
				    return i;
			    };
		}
		[[maybe_unused]]auto x = f();
	}
	std::cout << '\n';


	std::cout << " ** co-routines:\n";
	{
		StackNew<100> buffer;
		auto gen = iota(0);
		while(true)
		{
			auto i = gen();
			if(i > 10) break;
			std::cout << i << " ";
		}
		std::cout << '\n';
	}
	std::cout << '\n';

}