Parker Schuh | 6691f19 | 2017-01-14 17:01:02 -0800 | [diff] [blame] | 1 | #ifndef _AOS_VISION_REGION_ALLOC_H_ |
| 2 | #define _AOS_VISION_REGION_ALLOC_H_ |
| 3 | |
Tyler Chatow | bf0609c | 2021-07-31 16:13:27 -0700 | [diff] [blame] | 4 | #include <cstdint> |
| 5 | #include <cstdio> |
| 6 | #include <cstdlib> |
Parker Schuh | 6691f19 | 2017-01-14 17:01:02 -0800 | [diff] [blame] | 7 | #include <memory> |
| 8 | #include <new> |
| 9 | #include <utility> |
| 10 | #include <vector> |
| 11 | |
Stephan Pleines | d99b1ee | 2024-02-02 20:56:44 -0800 | [diff] [blame] | 12 | namespace aos::vision { |
Parker Schuh | 6691f19 | 2017-01-14 17:01:02 -0800 | [diff] [blame] | 13 | |
| 14 | // Region based allocator. Used for arena allocations in vision code. |
| 15 | // Example use: Storing contour nodes. |
| 16 | class AnalysisAllocator { |
| 17 | public: |
| 18 | template <typename T, typename... Args> |
Tyler Chatow | bf0609c | 2021-07-31 16:13:27 -0700 | [diff] [blame] | 19 | T *cons_obj(Args &&...args) { |
Parker Schuh | 6691f19 | 2017-01-14 17:01:02 -0800 | [diff] [blame] | 20 | uint8_t *ptr = NULL; |
| 21 | if (sizeof(T) + alignof(T) > block_size_) { |
Brian Silverman | 58899fd | 2019-03-24 11:03:11 -0700 | [diff] [blame] | 22 | __builtin_trap(); |
Parker Schuh | 6691f19 | 2017-01-14 17:01:02 -0800 | [diff] [blame] | 23 | } |
| 24 | while (ptr == NULL) { |
| 25 | if (next_free_ >= memory_.size()) { |
| 26 | if (next_free_ >= 1024) { |
Brian Silverman | 58899fd | 2019-03-24 11:03:11 -0700 | [diff] [blame] | 27 | __builtin_trap(); |
Parker Schuh | 6691f19 | 2017-01-14 17:01:02 -0800 | [diff] [blame] | 28 | } |
| 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 Pleines | d99b1ee | 2024-02-02 20:56:44 -0800 | [diff] [blame] | 54 | } // namespace aos::vision |
Parker Schuh | 6691f19 | 2017-01-14 17:01:02 -0800 | [diff] [blame] | 55 | |
| 56 | #endif // _AOS_VISION_IMAGE_REGION_ALLOC_H_ |