blob: 3275f3ef65a14fcd8aa77673daf606b55a169fbd [file] [log] [blame]
Parker Schuh6691f192017-01-14 17:01:02 -08001#ifndef _AOS_VISION_REGION_ALLOC_H_
2#define _AOS_VISION_REGION_ALLOC_H_
3
Tyler Chatowbf0609c2021-07-31 16:13:27 -07004#include <cstdint>
5#include <cstdio>
6#include <cstdlib>
Parker Schuh6691f192017-01-14 17:01:02 -08007#include <memory>
8#include <new>
9#include <utility>
10#include <vector>
11
Parker Schuh6691f192017-01-14 17:01:02 -080012namespace aos {
13namespace vision {
14
15// Region based allocator. Used for arena allocations in vision code.
16// Example use: Storing contour nodes.
17class AnalysisAllocator {
18 public:
19 template <typename T, typename... Args>
Tyler Chatowbf0609c2021-07-31 16:13:27 -070020 T *cons_obj(Args &&...args) {
Parker Schuh6691f192017-01-14 17:01:02 -080021 uint8_t *ptr = NULL;
22 if (sizeof(T) + alignof(T) > block_size_) {
Brian Silverman58899fd2019-03-24 11:03:11 -070023 __builtin_trap();
Parker Schuh6691f192017-01-14 17:01:02 -080024 }
25 while (ptr == NULL) {
26 if (next_free_ >= memory_.size()) {
27 if (next_free_ >= 1024) {
Brian Silverman58899fd2019-03-24 11:03:11 -070028 __builtin_trap();
Parker Schuh6691f192017-01-14 17:01:02 -080029 }
30 memory_.emplace_back(new uint8_t[block_size_]);
31 } else if ((used_size_ % alignof(T)) != 0) {
32 used_size_ += alignof(T) - (used_size_ % alignof(T));
33 } else if ((used_size_ + sizeof(T)) <= block_size_) {
34 ptr = &memory_[next_free_][used_size_];
35 used_size_ += sizeof(T);
36 } else {
37 used_size_ = 0;
38 next_free_++;
39 }
40 }
41 return new (ptr) T(std::forward<Args>(args)...);
42 }
43 void reset() {
44 next_free_ = 0;
45 used_size_ = 0;
46 }
47
48 private:
49 std::vector<std::unique_ptr<uint8_t[]>> memory_;
50 size_t next_free_ = 0;
51 size_t block_size_ = 1024 * 4;
52 size_t used_size_ = 0;
53};
54
55} // namespace vision
56} // namespace aos
57
58#endif // _AOS_VISION_IMAGE_REGION_ALLOC_H_