blob: df33fed8e10cb0fca1fb233327a8b428d103e132 [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
4#include <stdint.h>
5#include <stdio.h>
6#include <stdlib.h>
7#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>
20 T *cons_obj(Args &&... args) {
21 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_