blob: 101ee6a1097806bd6c48c1c5df83c4281988a425 [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
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -080012namespace aos::vision {
Parker Schuh6691f192017-01-14 17:01:02 -080013
14// Region based allocator. Used for arena allocations in vision code.
15// Example use: Storing contour nodes.
16class AnalysisAllocator {
17 public:
18 template <typename T, typename... Args>
Tyler Chatowbf0609c2021-07-31 16:13:27 -070019 T *cons_obj(Args &&...args) {
Parker Schuh6691f192017-01-14 17:01:02 -080020 uint8_t *ptr = NULL;
21 if (sizeof(T) + alignof(T) > block_size_) {
Brian Silverman58899fd2019-03-24 11:03:11 -070022 __builtin_trap();
Parker Schuh6691f192017-01-14 17:01:02 -080023 }
24 while (ptr == NULL) {
25 if (next_free_ >= memory_.size()) {
26 if (next_free_ >= 1024) {
Brian Silverman58899fd2019-03-24 11:03:11 -070027 __builtin_trap();
Parker Schuh6691f192017-01-14 17:01:02 -080028 }
29 memory_.emplace_back(new uint8_t[block_size_]);
30 } else if ((used_size_ % alignof(T)) != 0) {
31 used_size_ += alignof(T) - (used_size_ % alignof(T));
32 } else if ((used_size_ + sizeof(T)) <= block_size_) {
33 ptr = &memory_[next_free_][used_size_];
34 used_size_ += sizeof(T);
35 } else {
36 used_size_ = 0;
37 next_free_++;
38 }
39 }
40 return new (ptr) T(std::forward<Args>(args)...);
41 }
42 void reset() {
43 next_free_ = 0;
44 used_size_ = 0;
45 }
46
47 private:
48 std::vector<std::unique_ptr<uint8_t[]>> memory_;
49 size_t next_free_ = 0;
50 size_t block_size_ = 1024 * 4;
51 size_t used_size_ = 0;
52};
53
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -080054} // namespace aos::vision
Parker Schuh6691f192017-01-14 17:01:02 -080055
56#endif // _AOS_VISION_IMAGE_REGION_ALLOC_H_