blob: 4bc41568ca9393be4e8bf906c77d7f0c6ebea8d1 [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
12#include "aos/common/logging/logging.h"
13
14namespace aos {
15namespace vision {
16
17// Region based allocator. Used for arena allocations in vision code.
18// Example use: Storing contour nodes.
19class AnalysisAllocator {
20 public:
21 template <typename T, typename... Args>
22 T *cons_obj(Args &&... args) {
23 uint8_t *ptr = NULL;
24 if (sizeof(T) + alignof(T) > block_size_) {
25 LOG(FATAL, "allocating %d too much\n", (int)sizeof(T));
26 }
27 while (ptr == NULL) {
28 if (next_free_ >= memory_.size()) {
29 if (next_free_ >= 1024) {
30 LOG(FATAL, "too much alloc\n");
31 }
32 memory_.emplace_back(new uint8_t[block_size_]);
33 } else if ((used_size_ % alignof(T)) != 0) {
34 used_size_ += alignof(T) - (used_size_ % alignof(T));
35 } else if ((used_size_ + sizeof(T)) <= block_size_) {
36 ptr = &memory_[next_free_][used_size_];
37 used_size_ += sizeof(T);
38 } else {
39 used_size_ = 0;
40 next_free_++;
41 }
42 }
43 return new (ptr) T(std::forward<Args>(args)...);
44 }
45 void reset() {
46 next_free_ = 0;
47 used_size_ = 0;
48 }
49
50 private:
51 std::vector<std::unique_ptr<uint8_t[]>> memory_;
52 size_t next_free_ = 0;
53 size_t block_size_ = 1024 * 4;
54 size_t used_size_ = 0;
55};
56
57} // namespace vision
58} // namespace aos
59
60#endif // _AOS_VISION_IMAGE_REGION_ALLOC_H_