ra8-firmware 0.1.0
Bare-metal firmware for the Renesas RA8 family (RA8D2 / RA8P1)
Loading...
Searching...
No Matches
ra8_img_arena.c
Go to the documentation of this file.
1
19
20#include "ra8_img_arena.h"
21
22#include <stddef.h>
23#include <stdint.h>
24#include <string.h>
25
30typedef enum : uint32_t {
34
36static ra8_img_arena_t* s_arena = nullptr;
37
39{
40 s_arena = arena;
41 if (arena != nullptr) {
42 arena->offset = 0U;
43 arena->live = 0U;
44 }
45}
46
48{
49 s_arena = nullptr;
50}
51
52void* ra8_img_arena_malloc(size_t n)
53{
54 ra8_img_arena_t* const a = s_arena;
55 if (a == nullptr) {
56 return nullptr;
57 }
58 /* Reject requests too large to ever fit; this also prevents the alignment
59 * round-up below from overflowing. */
60 if (n > a->cap) {
61 return nullptr;
62 }
63 const size_t aligned = (n + (size_t)k_ra8_img_align_mask) & ~(size_t)k_ra8_img_align_mask;
64 if (aligned > (a->cap - a->offset)) {
65 return nullptr;
66 }
67 void* const block = &a->base[a->offset];
68 a->offset += aligned;
69 a->live += 1U;
70 return block;
71}
72
73void ra8_img_arena_free(void* p)
74{
75 ra8_img_arena_t* const a = s_arena;
76 if ((p == nullptr) || (a == nullptr)) {
77 return;
78 }
79 if (a->live > 0U) {
80 a->live -= 1U;
81 }
82 if (a->live == 0U) {
83 a->offset = 0U;
84 }
85}
86
87void* ra8_img_arena_realloc_sized(void* p, size_t oldsz, size_t newsz)
88{
89 if (p == nullptr) {
90 return ra8_img_arena_malloc(newsz);
91 }
92 /* A bump arena cannot grow in place: allocate fresh, copy, release old. */
93 void* const fresh = ra8_img_arena_malloc(newsz);
94 if (fresh == nullptr) {
95 return nullptr;
96 }
97 const size_t copy = (oldsz < newsz) ? oldsz : newsz;
98 if (copy > 0U) {
99 (void)memcpy(fresh, p, copy);
100 }
102 return fresh;
103}
static uint8_t s_arena[k_c6_cam_arena_bytes]
Definition c6_cam_app.c:43
void * memcpy(void *dst, const void *src, size_t n)
Copy memory area between non-overlapping regions.
void ra8_img_arena_free(void *p)
stb_image STBI_FREE hook: release a block; auto-reset when none live.
void * ra8_img_arena_realloc_sized(void *p, size_t oldsz, size_t newsz)
stb_image STBI_REALLOC_SIZED hook: fresh-allocate, copy, free old.
void ra8_img_arena_bind(ra8_img_arena_t *arena)
Bind arena as the active scratch for subsequent decode allocations.
ra8_img_arena_consts_t
Arena alignment knobs (no magic numbers).
@ k_ra8_img_align_mask
k_ra8_img_align - 1 (round-up mask).
@ k_ra8_img_align
Allocation alignment, bytes.
void * ra8_img_arena_malloc(size_t n)
stb_image STBI_MALLOC hook: bump n bytes from the bound arena.
void ra8_img_arena_unbind(void)
Unbind the active arena; subsequent allocation hooks fail with nullptr.
Heap-free scratch allocator hooks for the stb_image single-TU build.
Caller-owned bump arena backing a single image decode.
size_t offset
Current bump offset.
uint8_t * base
Caller-owned scratch buffer.
size_t cap
Scratch capacity, bytes.
size_t live
Live (allocated, not freed) blocks.