ogl_beamforming

Ultrasound Beamforming Implemented with OpenGL
git clone anongit@rnpnr.xyz:ogl_beamforming.git
Log | Files | Refs | Feed | Submodules | README | LICENSE

util.c (26122B)


      1 /* See LICENSE for license details. */
      2 #if   COMPILER_CLANG
      3   #pragma GCC diagnostic ignored "-Winitializer-overrides"
      4 #elif COMPILER_GCC
      5   #pragma GCC diagnostic ignored "-Woverride-init"
      6 #endif
      7 
      8 #define zero_struct(s) memory_clear((s), 0, sizeof(*(s)))
      9 function void *
     10 memory_clear(void *restrict p_, u8 c, u64 size)
     11 {
     12 	u8 *p = p_;
     13 	while (size > 0) p[--size] = c;
     14 	return p;
     15 }
     16 
     17 function b32
     18 memory_equal(void *restrict left, void *restrict right, u64 n)
     19 {
     20 	u8 *a = left, *b = right;
     21 	b32 result = 1;
     22 	for (; result && n; n--)
     23 		result &= *a++ == *b++;
     24 	return result;
     25 }
     26 
     27 function void
     28 memory_copy(void *restrict dest, void *restrict src, u64 n)
     29 {
     30 	u8 *s = src, *d = dest;
     31 	#ifdef __AVX512BW__
     32 	{
     33 		for (; n >= 64; n -= 64, s += 64, d += 64)
     34 			_mm512_storeu_epi8(d, _mm512_loadu_epi8(s));
     35 		__mmask64 k = _cvtu64_mask64(_bzhi_u64(-1ULL, n));
     36 		_mm512_mask_storeu_epi8(d, k, _mm512_maskz_loadu_epi8(k, s));
     37 	}
     38 	#else
     39 		for (; n; n--) *d++ = *s++;
     40 	#endif
     41 }
     42 
     43 /* IMPORTANT: this function may fault if dest, src, and n are not multiples of 64 */
     44 function void
     45 memory_copy_non_temporal(void *restrict dest, void *restrict src, u64 n)
     46 {
     47 	assume(((u64)dest & 63) == 0);
     48 	assume(((u64)src  & 63) == 0);
     49 	assume(((u64)n    & 63) == 0);
     50 	u8 *s = src, *d = dest;
     51 
     52 	#if defined(__AVX512BW__)
     53 	{
     54 		for (; n >= 64; n -= 64, s += 64, d += 64)
     55 			_mm512_stream_si512((__m512i *)d, _mm512_stream_load_si512((__m512i *)s));
     56 	}
     57 	#elif defined(__AVX2__)
     58 	{
     59 		for (; n >= 32; n -= 32, s += 32, d += 32)
     60 			_mm256_stream_si256((__m256i *)d, _mm256_stream_load_si256((__m256i *)s));
     61 	}
     62 	#elif ARCH_ARM64 && !COMPILER_MSVC
     63 	{
     64 		asm volatile (
     65 			"cbz  %2, 2f\n"
     66 			"1: ldnp q0, q1, [%1]\n"
     67 			"subs %2, %2, #32\n"
     68 			"add  %1, %1, #32\n"
     69 			"stnp q0, q1, [%0]\n"
     70 			"add  %0, %0, #32\n"
     71 			"b.ne 1b\n"
     72 			"2:"
     73 			:  "+r"(d), "+r"(s), "+r"(n)
     74 			:: "memory", "v0", "v1"
     75 		);
     76 	}
     77 	#else
     78 		memory_copy(d, s, n);
     79 	#endif
     80 }
     81 
     82 function void
     83 memory_move(void *dest, void *src, u64 n)
     84 {
     85 	u8 *d = dest, *s = src;
     86 	if (d < s) memory_copy(d, s, n);
     87 	else            while (n) { n--; d[n] = s[n]; }
     88 }
     89 
     90 function void *
     91 memory_scan_backwards(void *memory, u8 byte, i64 n)
     92 {
     93 	void *result = 0;
     94 	u8   *s      = memory;
     95 	while (n > 0) if (s[--n] == byte) { result = s + n; break; }
     96 	return result;
     97 }
     98 
     99 /* NOTE(rnp): from Hacker's Delight */
    100 function force_inline u64
    101 round_down_power_of_two(u64 a)
    102 {
    103 	u64 result = 0x8000000000000000ULL >> clz_u64(a);
    104 	return result;
    105 }
    106 
    107 function force_inline u64
    108 round_up_power_of_two(u64 a)
    109 {
    110 	u64 result = 0x8000000000000000ULL >> (clz_u64(a - 1) - 1);
    111 	return result;
    112 }
    113 
    114 function force_inline i64
    115 round_up_to(i64 value, i64 multiple)
    116 {
    117 	i64 result = value;
    118 	if (value % multiple != 0)
    119 		result += multiple - value % multiple;
    120 	return result;
    121 }
    122 
    123 function u8 *
    124 arena_commit(Arena *a, i64 size)
    125 {
    126 	Arena *current = a->current;
    127 	assert(current->committed - current->position >= (u64)size);
    128 	u8 *result = (u8 *)current + current->position;
    129 	current->position += size;
    130 	return result;
    131 }
    132 
    133 typedef enum {
    134 	ArenaAllocateFlags_NoZero = 1 << 0,
    135 } ArenaAllocateFlags;
    136 
    137 typedef struct {
    138 	i64 size;
    139 	u64 align;
    140 	i64 count;
    141 	ArenaAllocateFlags flags;
    142 } ArenaAllocateInfo;
    143 
    144 #define arena_alloc(a, ...)         arena_alloc_(a, (ArenaAllocateInfo){.align = 8, .count = 1, ##__VA_ARGS__})
    145 #define push_array(a, t, n)         (t *)arena_alloc(a, .size = sizeof(t), .align = alignof(t), .count = n)
    146 #define push_array_no_zero(a, t, n) (t *)arena_alloc(a, .size = sizeof(t), .align = alignof(t), .count = n, .flags = ArenaAllocateFlags_NoZero)
    147 #define push_struct(a, t)           push_array(a, t, 1)
    148 #define push_struct_no_zero(a, t)   push_array_no_zero(a, t, 1)
    149 
    150 #define arena_create(...) arena_create_((ArenaParameters){\
    151 	.reserve_size = MB(64),\
    152 	.commit_size  = KB(64),\
    153 	.flags        = 0,\
    154 	.allocation_site_file = __FILE__,\
    155 	.allocation_site_line = __LINE__,\
    156 	__VA_ARGS__})
    157 
    158 function Arena *
    159 arena_create_(ArenaParameters ap)
    160 {
    161 	void *base = ap.optional_backing_store;
    162 	if (base == 0) {
    163 		ap.commit_size  = round_up_to(ap.commit_size,  os_system_info()->page_size);
    164 		ap.reserve_size = round_up_to(ap.reserve_size, os_system_info()->page_size);
    165 
    166 		base = os_memory_reserve(ap.reserve_size);
    167 		os_memory_commit(base, ap.commit_size);
    168 	}
    169 
    170 	Arena *result     = base;
    171 	result->current   = result;
    172 	result->position  = sizeof(*result);
    173 	result->reserved  = ap.reserve_size;
    174 	result->committed = ap.commit_size;
    175 	result->flags     = ap.flags;
    176 
    177 	result->reserve_size = ap.reserve_size;
    178 	result->commit_size  = ap.commit_size;
    179 
    180 	result->name                 = ap.name;
    181 	result->allocation_site_file = ap.allocation_site_file;
    182 	result->allocation_site_line = ap.allocation_site_line;
    183 
    184 	return result;
    185 }
    186 
    187 function void
    188 arena_destroy(Arena *arena)
    189 {
    190 	for (Arena *a = arena->current, *prev = 0; a; a = prev) {
    191 		prev = a->prev;
    192 		os_memory_release(a, a->reserved);
    193 	}
    194 }
    195 
    196 function void
    197 arena_seal(Arena *arena)
    198 {
    199 	assert(arena == arena->current);
    200 	u64 position = round_up_to(arena->position, os_system_info()->page_size);
    201 	if (arena->committed > position) {
    202 		os_memory_uncommit((u8 *)arena + position, arena->committed - position);
    203 		arena->committed = position;
    204 	}
    205 	if (arena->reserved > arena->committed) {
    206 		os_memory_release((u8 *)arena + arena->committed, arena->reserved - arena->committed);
    207 		arena->reserved = arena->committed;
    208 	}
    209 	os_memory_seal(arena, arena->reserved);
    210 }
    211 
    212 #define arena_alloc(a, ...)         arena_alloc_(a, (ArenaAllocateInfo){.align = 8, .count = 1, ##__VA_ARGS__})
    213 #define push_array(a, t, n)         (t *)arena_alloc(a, .size = sizeof(t), .align = alignof(t), .count = n)
    214 #define push_array_no_zero(a, t, n) (t *)arena_alloc(a, .size = sizeof(t), .align = alignof(t), .count = n, .flags = ArenaAllocateFlags_NoZero)
    215 #define push_struct(a, t)           push_array(a, t, 1)
    216 #define push_struct_no_zero(a, t)   push_array_no_zero(a, t, 1)
    217 
    218 function void *
    219 arena_alloc_(Arena *arena, ArenaAllocateInfo info)
    220 {
    221 	Arena *current = arena->current;
    222 	u64 size          = info.count * info.size;
    223 	u64 pre_position  = AlignUpPowerOfTwo(current->position, info.align);
    224 	u64 post_position = pre_position + size;
    225 	u64 zero_size     = Min(current->committed, post_position) - pre_position;
    226 
    227 	if (current->reserved < post_position && (current->flags & ArenaFlag_NoChain) == 0) {
    228 		u64 reserve_size = current->reserve_size;
    229 		u64 commit_size  = current->commit_size;
    230 		if (size + AlignUpPowerOfTwo(sizeof(*arena), info.align) > reserve_size) {
    231 			reserve_size = size + AlignUpPowerOfTwo(sizeof(*arena), info.align);
    232 			commit_size  = size + AlignUpPowerOfTwo(sizeof(*arena), info.align);
    233 		}
    234 		Arena *new_arena = arena_create(.reserve_size         = reserve_size,
    235 		                                .commit_size          = commit_size,
    236 		                                .flags                = current->flags,
    237 		                                .allocation_site_file = current->allocation_site_file,
    238 		                                .allocation_site_line = current->allocation_site_line,
    239 		                                .name                 = current->name);
    240 		zero_size = 0;
    241 
    242 		new_arena->base_position = current->base_position + current->reserved;
    243 		SLLStackPush(arena->current, new_arena, prev);
    244 		current = new_arena;
    245 		pre_position  = AlignUpPowerOfTwo(current->position, info.align);
    246 		post_position = pre_position + size;
    247 	}
    248 
    249 	if (current->committed < post_position) {
    250 		u64 commit_post = post_position + current->commit_size - 1;
    251 		commit_post -= commit_post % current->commit_size;
    252 		commit_post  = Min(commit_post, current->reserved);
    253 		os_memory_commit((u8 *)current + current->committed, commit_post - current->committed);
    254 		current->committed = commit_post;
    255 	}
    256 
    257 	void *result = 0;
    258 	if (current->committed >= post_position) {
    259 		result = (u8 *)current + pre_position;
    260 		current->position = post_position;
    261 		if ((info.flags & ArenaAllocateFlags_NoZero) == 0)
    262 			result = memory_clear(result, 0, zero_size);
    263 	}
    264 
    265 	assert(result);
    266 
    267 	return result;
    268 }
    269 
    270 function u64
    271 arena_position(Arena *arena)
    272 {
    273 	Arena *current = arena->current;
    274 	u64 result = current->base_position + current->position;
    275 	return result;
    276 }
    277 
    278 function void
    279 arena_pop_to(Arena *arena, u64 position)
    280 {
    281 	position = Max(position, sizeof(*arena));
    282 	Arena *current = arena->current;
    283 	for (Arena *prev = 0; current->base_position >= position; current = prev) {
    284 		prev = current->prev;
    285 		os_memory_release(current, current->reserved);
    286 	}
    287 	arena->current = current;
    288 	u64 new_position = position - current->base_position;
    289 	assert(new_position <= current->position);
    290 	current->position = new_position;
    291 }
    292 
    293 function void
    294 arena_pop(Arena *arena, u64 size)
    295 {
    296 	u64 old_position = arena_position(arena);
    297 	u64 new_position = old_position;
    298 	if (size < old_position)
    299 		new_position = old_position - size;
    300 	arena_pop_to(arena, new_position);
    301 }
    302 
    303 function void
    304 arena_clear(Arena *arena)
    305 {
    306 	arena_pop_to(arena, 0);
    307 }
    308 
    309 function void
    310 arena_pre_align(Arena *arena, u64 align)
    311 {
    312 	assert(IsPowerOfTwo(align));
    313 	Arena *current = arena->current;
    314 	u8 *start = (u8 *)current + current->position;
    315 	u8 *desired_start = (u8 *)AlignUpPowerOfTwo((u64)start, align);
    316 	current->position += (u64)(desired_start - start);
    317 }
    318 
    319 function Temp
    320 temp_begin(Arena *arena)
    321 {
    322 	Temp result = {.arena = arena, .position = arena_position(arena)};
    323 	return result;
    324 }
    325 
    326 function void
    327 temp_end(Temp t)
    328 {
    329 	arena_pop_to(t.arena, t.position);
    330 }
    331 
    332 enum { DA_INITIAL_CAP = 16 };
    333 
    334 #define da_index(it, s) ((it) - (s)->data)
    335 #define da_reserve(a, s, n) \
    336   (s)->data = da_reserve_((a), (s)->data, &(s)->capacity, (s)->count + n, \
    337                           _Alignof(typeof(*(s)->data)), sizeof(*(s)->data))
    338 
    339 #define da_append_count(a, s, items, item_count) do { \
    340 	da_reserve((a), (s), (item_count)); \
    341 	memory_copy((s)->data + (s)->count, (items), sizeof(*(items)) * (u64)(item_count)); \
    342 	(s)->count += (item_count); \
    343 } while (0)
    344 
    345 #define da_push(a, s) \
    346   ((typeof((s)->data))memory_clear((s)->count == (s)->capacity  \
    347     ? da_reserve(a, s, 1),      \
    348       (s)->data + (s)->count++  \
    349     : (s)->data + (s)->count++, 0, sizeof(*(s)->data)))
    350 
    351 
    352 /* NOTE(rnp): handles both 0 initialized DAs and DAs that need to be moved (they started
    353  * on the stack or someone allocated something in the middle of the arena during usage) */
    354 function void *
    355 da_reserve_(Arena *a, void *data, da_count *capacity, da_count needed, u64 align, i64 size)
    356 {
    357 	da_count cap = *capacity;
    358 	if (!cap) cap = DA_INITIAL_CAP;
    359 	while (cap < needed) cap *= 2;
    360 
    361 	Arena *current = a->current;
    362 	u64 needed_size = cap * size;
    363 	u64 old_size    = *capacity * size;
    364 	b32 can_extend  = data && (u8 *)current + current->position == (u8 *)data + old_size &&
    365 	                  (current->reserved - current->position) >= (needed_size - old_size);
    366 	b32 needs_copy  = data && !can_extend;
    367 
    368 	u64 alloc_cap = cap;
    369 	if (can_extend) alloc_cap -= *capacity;
    370 
    371 	void *new = arena_alloc(a, .size = size, .align = align, .count = alloc_cap);
    372 
    373 	if (needs_copy)
    374 		memory_copy(new, data, (u64)(*capacity * size));
    375 
    376 	if (!can_extend)
    377 		data = new;
    378 
    379 	*capacity = cap;
    380 
    381 	return data;
    382 }
    383 
    384 function u32
    385 utf8_encode(u8 *out, u32 cp)
    386 {
    387 	u32 result = 1;
    388 	if (cp <= 0x7F) {
    389 		out[0] = cp & 0x7F;
    390 	} else if (cp <= 0x7FF) {
    391 		result = 2;
    392 		out[0] = ((cp >>  6) & 0x1F) | 0xC0;
    393 		out[1] = ((cp >>  0) & 0x3F) | 0x80;
    394 	} else if (cp <= 0xFFFF) {
    395 		result = 3;
    396 		out[0] = ((cp >> 12) & 0x0F) | 0xE0;
    397 		out[1] = ((cp >>  6) & 0x3F) | 0x80;
    398 		out[2] = ((cp >>  0) & 0x3F) | 0x80;
    399 	} else if (cp <= 0x10FFFF) {
    400 		result = 4;
    401 		out[0] = ((cp >> 18) & 0x07) | 0xF0;
    402 		out[1] = ((cp >> 12) & 0x3F) | 0x80;
    403 		out[2] = ((cp >>  6) & 0x3F) | 0x80;
    404 		out[3] = ((cp >>  0) & 0x3F) | 0x80;
    405 	} else {
    406 		out[0] = '?';
    407 	}
    408 	return result;
    409 }
    410 
    411 function UnicodeDecode
    412 utf16_decode(u16 *data, i64 length)
    413 {
    414 	UnicodeDecode result = {.cp = U32_MAX};
    415 	if (length) {
    416 		result.consumed = 1;
    417 		result.cp = data[0];
    418 		if (length > 1 && Between(data[0], 0xD800u, 0xDBFFu)
    419 		               && Between(data[1], 0xDC00u, 0xDFFFu))
    420 		{
    421 			result.consumed = 2;
    422 			result.cp = ((data[0] - 0xD800u) << 10u) | ((data[1] - 0xDC00u) + 0x10000u);
    423 		}
    424 	}
    425 	return result;
    426 }
    427 
    428 function u32
    429 utf16_encode(u16 *out, u32 cp)
    430 {
    431 	u32 result = 1;
    432 	if (cp == U32_MAX) {
    433 		out[0] = '?';
    434 	} else if (cp < 0x10000u) {
    435 		out[0] = (u16)cp;
    436 	} else {
    437 		u32 value = cp - 0x10000u;
    438 		out[0] = (u16)(0xD800u + (value >> 10u));
    439 		out[1] = (u16)(0xDC00u + (value & 0x3FFu));
    440 		result = 2;
    441 	}
    442 	return result;
    443 }
    444 
    445 function Stream
    446 stream_from_buffer(u8 *buffer, u32 capacity)
    447 {
    448 	Stream result = {.data = buffer, .cap = (i32)capacity};
    449 	return result;
    450 }
    451 
    452 function Stream
    453 stream_alloc(Arena *a, i32 cap)
    454 {
    455 	Stream result = stream_from_buffer(push_array_no_zero(a, u8, cap), (u32)cap);
    456 	return result;
    457 }
    458 
    459 function str8
    460 stream_to_str8(Stream *s)
    461 {
    462 	str8 result = str8("");
    463 	if (!s->errors) result = (str8){.length = s->widx, .data = s->data};
    464 	return result;
    465 }
    466 
    467 function void
    468 stream_reset(Stream *s, i32 index)
    469 {
    470 	s->errors = s->cap <= index;
    471 	if (!s->errors)
    472 		s->widx = index;
    473 }
    474 
    475 function void
    476 stream_append(Stream *s, void *data, i64 count)
    477 {
    478 	s->errors |= (s->cap - s->widx) < count;
    479 	if (!s->errors) {
    480 		memory_copy(s->data + s->widx, data, (u64)count);
    481 		s->widx += (i32)count;
    482 	}
    483 }
    484 
    485 function void
    486 stream_append_codepoint(Stream *s, u32 codepoint)
    487 {
    488 	u8 buffer[4];
    489 	stream_append(s, buffer, utf8_encode(buffer, codepoint));
    490 }
    491 
    492 // TODO(rnp): replace with handwritten version
    493 #include <stdarg.h>
    494 #include <stdio.h>
    495 function void
    496 stream_appendfv(Stream *s, const char *format, va_list args)
    497 {
    498 	i32 written = vsnprintf((char *)s->data + s->widx, s->cap - s->widx, format, args);
    499 	s->errors |= written > (s->cap - s->widx);
    500 	if (!s->errors) s->widx += written;
    501 }
    502 
    503 function print_format(2, 3) void
    504 stream_appendf(Stream *s, const char *format, ...)
    505 {
    506 	va_list args;
    507 	va_start(args, format);
    508 	stream_appendfv(s, format, args);
    509 	va_end(args);
    510 }
    511 
    512 function void
    513 stream_append_byte(Stream *s, u8 b)
    514 {
    515 	stream_append(s, &b, 1);
    516 }
    517 
    518 function void
    519 stream_pad(Stream *s, u8 b, i32 n)
    520 {
    521 	while (n > 0) stream_append_byte(s, b), n--;
    522 }
    523 
    524 function void
    525 stream_append_str8(Stream *s, str8 str)
    526 {
    527 	stream_append(s, str.data, str.length);
    528 }
    529 
    530 #define stream_append_str8s(s, ...) stream_append_str8s_(s, arg_list(str8, ##__VA_ARGS__))
    531 function void
    532 stream_append_str8s_(Stream *s, str8 *strs, i64 count)
    533 {
    534 	for (i64 i = 0; i < count; i++)
    535 		stream_append(s, strs[i].data, strs[i].length);
    536 }
    537 
    538 function void
    539 stream_append_u64_width(Stream *s, u64 n, u64 min_width)
    540 {
    541 	u8 tmp[64];
    542 	u8 *end = tmp + sizeof(tmp);
    543 	u8 *beg = end;
    544 	min_width = Min(sizeof(tmp), min_width);
    545 
    546 	do { *--beg = (u8)('0' + (n % 10)); } while (n /= 10);
    547 	while (end - beg > 0 && (u64)(end - beg) < min_width)
    548 		*--beg = '0';
    549 
    550 	stream_append(s, beg, end - beg);
    551 }
    552 
    553 function void
    554 stream_append_u64(Stream *s, u64 n)
    555 {
    556 	stream_append_u64_width(s, n, 0);
    557 }
    558 
    559 function void
    560 stream_append_hex_u64_width(Stream *s, u64 n, i64 width)
    561 {
    562 	assert(width <= 16);
    563 	if (!s->errors) {
    564 		u8  buf[16];
    565 		u8 *end = buf + sizeof(buf);
    566 		u8 *beg = end;
    567 		while (n) {
    568 			*--beg = (u8)"0123456789abcdef"[n & 0x0F];
    569 			n >>= 4;
    570 		}
    571 		while (end - beg < width)
    572 			*--beg = '0';
    573 		stream_append(s, beg, end - beg);
    574 	}
    575 }
    576 
    577 function void
    578 stream_append_hex_u64(Stream *s, u64 n)
    579 {
    580 	stream_append_hex_u64_width(s, n, 2);
    581 }
    582 
    583 function void
    584 stream_append_i64(Stream *s, i64 n)
    585 {
    586 	if (n < 0) {
    587 		stream_append_byte(s, '-');
    588 		n *= -1;
    589 	}
    590 	stream_append_u64(s, (u64)n);
    591 }
    592 
    593 function void
    594 stream_append_f64(Stream *s, f64 f, u64 prec)
    595 {
    596 	if (f < 0) {
    597 		stream_append_byte(s, '-');
    598 		f *= -1;
    599 	}
    600 
    601 	/* NOTE: round last digit */
    602 	f += 0.5f / (f64)prec;
    603 
    604 	if (f >= (f64)(-1UL >> 1)) {
    605 		stream_append_str8(s, str8("inf"));
    606 	} else {
    607 		u64 integral = (u64)f;
    608 		u64 fraction = (u64)((f - (f64)integral) * (f64)prec);
    609 		stream_append_u64(s, integral);
    610 		stream_append_byte(s, '.');
    611 		for (u64 i = prec / 10; i > 1; i /= 10) {
    612 			if (i > fraction)
    613 				stream_append_byte(s, '0');
    614 		}
    615 		stream_append_u64(s, fraction);
    616 	}
    617 }
    618 
    619 function void
    620 stream_append_f64_e(Stream *s, f64 f)
    621 {
    622 	/* TODO: there should be a better way of doing this */
    623 	#if 0
    624 	/* NOTE: we ignore subnormal numbers for now */
    625 	union { f64 f; u64 u; } u = {.f = f};
    626 	i32 exponent = ((u.u >> 52) & 0x7ff) - 1023;
    627 	f32 log_10_of_2 = 0.301f;
    628 	i32 scale       = (exponent * log_10_of_2);
    629 	/* NOTE: normalize f */
    630 	for (i32 i = ABS(scale); i > 0; i--)
    631 		f *= (scale > 0)? 0.1f : 10.0f;
    632 	#else
    633 	f32 sign = Sign(f);
    634 	f *= sign;
    635 	i32 scale = 0;
    636 	if (f != 0) {
    637 		while (f > 1) {
    638 			f *= 0.1f;
    639 			scale++;
    640 		}
    641 		while (f < 1) {
    642 			f *= 10.0f;
    643 			scale--;
    644 		}
    645 	}
    646 	#endif
    647 
    648 	u32 prec = 100;
    649 	stream_append_f64(s, sign * f, prec);
    650 	stream_append_byte(s, 'e');
    651 	stream_append_byte(s, scale >= 0? '+' : '-');
    652 	for (u32 i = prec / 10; i > 1; i /= 10)
    653 		stream_append_byte(s, '0');
    654 	stream_append_u64(s, (u64)Abs(scale));
    655 }
    656 
    657 function void
    658 stream_append_struct_member(Stream *s, MetaStructMember *m, void *struct_base)
    659 {
    660 	switch (m->type_id) {
    661 	InvalidDefaultCase;
    662 	case MetaKind_F32:{
    663 		f32 value;
    664 		memory_copy(&value, ((u8 *)struct_base + m->offset), sizeof(value));
    665 		stream_append_f64_e(s, value);
    666 	}break;
    667 	case MetaKind_B32:{
    668 		b32 value;
    669 		memory_copy(&value, ((u8 *)struct_base + m->offset), sizeof(value));
    670 		stream_append_str8(s, value ? str8("True") : str8("False"));
    671 	}break;
    672 	case MetaKind_U32:{
    673 		u32 value;
    674 		memory_copy(&value, ((u8 *)struct_base + m->offset), sizeof(value));
    675 		stream_append_u64(s, value);
    676 	}break;
    677 	case MetaKind_S32:{
    678 		i32 value;
    679 		memory_copy(&value, ((u8 *)struct_base + m->offset), sizeof(value));
    680 		stream_append_i64(s, value);
    681 	}break;
    682 	}
    683 }
    684 
    685 function Stream
    686 arena_stream(Arena *a)
    687 {
    688 	Arena *current = a->current;
    689 	Stream result = {0};
    690 	result.data   = (u8 *)current + current->position;
    691 	result.cap    = (i32)(current->committed - current->position);
    692 
    693 	/* TODO(rnp): no idea what to do here if we want to maintain the ergonomics */
    694 	asan_unpoison_region(result.data, result.cap);
    695 
    696 	return result;
    697 }
    698 
    699 function str8
    700 arena_stream_commit(Arena *a, Stream *s)
    701 {
    702 	Arena *current = a->current;
    703 	assert(s->data == (u8 *)current + current->position);
    704 	str8 result = stream_to_str8(s);
    705 	arena_commit(a, result.length);
    706 	return result;
    707 }
    708 
    709 function str8
    710 arena_stream_commit_zero(Arena *a, Stream *s)
    711 {
    712 	b32 error = s->errors || s->widx == s->cap;
    713 	if (!error)
    714 		s->data[s->widx] = 0;
    715 	str8 result = stream_to_str8(s);
    716 	arena_commit(a, result.length + 1);
    717 	return result;
    718 }
    719 
    720 function str8
    721 arena_stream_commit_and_reset(Arena *arena, Stream *s)
    722 {
    723 	str8 result = arena_stream_commit_zero(arena, s);
    724 	*s = arena_stream(arena);
    725 	return result;
    726 }
    727 
    728 #if !defined(XXH_IMPLEMENTATION)
    729 # define XXH_INLINE_ALL
    730 # define XXH_IMPLEMENTATION
    731 # define XXH_STATIC_LINKING_ONLY
    732 # include "external/xxhash.h"
    733 #endif
    734 
    735 function u128
    736 u128_hash_from_data(void *data, u64 size)
    737 {
    738 	u128 result = {0};
    739 	XXH128_hash_t hash = XXH3_128bits_withSeed(data, size, 4969);
    740 	memory_copy(&result, &hash, sizeof(result));
    741 	return result;
    742 }
    743 
    744 function u64
    745 u64_hash_from_str8_seed(str8 string, u64 seed)
    746 {
    747 	u64 result = XXH3_64bits_withSeed(string.data, (u64)string.length, seed);
    748 	return result;
    749 }
    750 
    751 function u64
    752 u64_hash_from_str8(str8 v)
    753 {
    754 	u64 result = u64_hash_from_str8_seed(v, 4969);
    755 	return result;
    756 }
    757 
    758 function str8
    759 str8_from_c_str(char *cstr)
    760 {
    761 	str8 result = {.data = (u8 *)cstr};
    762 	if (cstr) while (*cstr) cstr++;
    763 	result.length = (u8 *)cstr - result.data;
    764 	return result;
    765 }
    766 
    767 function str8
    768 str8_range(u8 *start, u8 *one_past_last)
    769 {
    770 	str8 result;
    771 	result.data   = start;
    772 	result.length = one_past_last - start;
    773 	return result;
    774 }
    775 
    776 function str8
    777 str8_skip(str8 s, i64 count)
    778 {
    779 	str8 result = s;
    780 	if (count > 0) {
    781 		result.data   += count;
    782 		result.length -= count;
    783 	}
    784 	return result;
    785 }
    786 
    787 function b32
    788 str8_equal(str8 a, str8 b)
    789 {
    790 	b32 result = a.length == b.length;
    791 	for (i64 i = 0; result && i < a.length; i++)
    792 		result = a.data[i] == b.data[i];
    793 	return result;
    794 }
    795 
    796 /* NOTE(rnp): returns < 0 if byte is not found */
    797 function i64
    798 str8_scan_backwards(str8 s, u8 byte)
    799 {
    800 	i64 result = (u8 *)memory_scan_backwards(s.data, byte, s.length) - s.data;
    801 	return result;
    802 }
    803 
    804 function str8
    805 str8_cut_head(str8 s, i64 cut)
    806 {
    807 	str8 result = s;
    808 	if (cut > 0) {
    809 		result.data   += cut;
    810 		result.length -= cut;
    811 	}
    812 	result.length = Max(0, result.length);
    813 	return result;
    814 }
    815 
    816 function b32
    817 str8_match(str8 a, str8 b, StringMatchFlags flags)
    818 {
    819 	b32 result = 0;
    820 	if (flags == 0) {
    821 		result = str8_equal(a, b);
    822 	} else if (a.length == b.length || (flags & StringMatchFlag_SloppySize)) {
    823 		result = 1;
    824 		i64 length = Min(a.length, b.length);
    825 		for (i64 it = 0; it < length && result; it++) {
    826 			u8 ab = a.data[it], bb = b.data[it];
    827 			if (flags & StringMatchFlag_CaseInsensitive) {
    828 				ab |= 0x20;
    829 				bb |= 0x20;
    830 			}
    831 			result &= ab == bb;
    832 		}
    833 	}
    834 	return result;
    835 }
    836 
    837 function i64
    838 str8_find_needle(str8 string, str8 needle, StringMatchFlags flags)
    839 {
    840 	u8 *s  = string.data;
    841 	u8 *se = string.data + Max(string.length + 1, needle.length) - needle.length;
    842 	if (needle.length > 0) {
    843 		flags |= StringMatchFlag_SloppySize;
    844 
    845 		u8 nb = needle.data[0];
    846 		if (flags & StringMatchFlag_CaseInsensitive)
    847 			nb |= 0x20;
    848 
    849 		str8 needle_tail = str8_skip(needle, 1);
    850 		u8 *s_opl = string.data + string.length;
    851 		for (; s < se; s++) {
    852 			u8 sb = *s;
    853 			if (flags & StringMatchFlag_CaseInsensitive)
    854 				sb |= 0x20;
    855 
    856 			if (sb == nb && str8_match(str8_range(s + 1, s_opl), needle_tail, flags))
    857 				break;
    858 		}
    859 	}
    860 
    861 	i64 result = string.length;
    862 	if (s < se)
    863 		result = s - string.data;
    864 	return result;
    865 }
    866 
    867 
    868 function str8
    869 str8_alloc(Arena *a, i64 length)
    870 {
    871 	str8 result = {.data = push_array(a, u8, length), .length = length};
    872 	return result;
    873 }
    874 
    875 function str8
    876 str8_from_str16(Arena *a, str16 in)
    877 {
    878 	str8 result = str8("");
    879 	if (in.length) {
    880 		i64 commit = in.length * 4;
    881 		i64 length = 0;
    882 		u8  *data = push_array_no_zero(a, u8, commit + 1);
    883 		u16 *beg  = in.data;
    884 		u16 *end  = in.data + in.length;
    885 		while (beg < end) {
    886 			UnicodeDecode decode = utf16_decode(beg, end - beg);
    887 			length += utf8_encode(data + length, decode.cp);
    888 			beg    += decode.consumed;
    889 		}
    890 		data[length] = 0;
    891 		result = (str8){.length = length, .data = data};
    892 		arena_pop(a, commit - length);
    893 	}
    894 	return result;
    895 }
    896 
    897 function str16
    898 str16_from_str8(Arena *a, str8 in)
    899 {
    900 	str16 result = {0};
    901 	if (in.length) {
    902 		i64  length   = 0;
    903 		i64  required = 2 * in.length + 1;
    904 		u16 *data     = push_array(a, u16, required);
    905 		/* TODO(rnp): utf8_decode */
    906 		for (i64 i = 0; i < in.length; i++) {
    907 			u32 cp  = in.data[i];
    908 			length += utf16_encode(data + length, cp);
    909 		}
    910 		result = (str16){.length = length, .data = data};
    911 		arena_pop(a, required - length);
    912 	}
    913 	return result;
    914 }
    915 
    916 #define push_str8_from_parts(a, j, ...) push_str8_from_parts_((a), (j), arg_list(str8, __VA_ARGS__))
    917 function str8
    918 push_str8_from_parts_(Arena *arena, str8 joiner, str8 *parts, i64 count)
    919 {
    920 	i64 length = joiner.length * (count - 1);
    921 	for (i64 i = 0; i < count; i++)
    922 		length += parts[i].length;
    923 
    924 	str8 result = {.length = length, .data = push_array_no_zero(arena, u8, length + 1)};
    925 
    926 	i64 offset = 0;
    927 	for (i64 i = 0; i < count; i++) {
    928 		if (i != 0) {
    929 			memory_copy(result.data + offset, joiner.data, (u64)joiner.length);
    930 			offset += joiner.length;
    931 		}
    932 		memory_copy(result.data + offset, parts[i].data, (u64)parts[i].length);
    933 		offset += parts[i].length;
    934 	}
    935 	result.data[result.length] = 0;
    936 
    937 	return result;
    938 }
    939 
    940 function str8
    941 push_str8(Arena *a, str8 str)
    942 {
    943 	str8 result    = str8_alloc(a, str.length + 1);
    944 	result.length -= 1;
    945 	memory_copy(result.data, str.data, (u64)result.length);
    946 	return result;
    947 }
    948 
    949 // TODO(rnp): replace with handwritten version
    950 function str8
    951 push_str8_fv(Arena *arena, const char *format, va_list args)
    952 {
    953 	Stream sb = arena_stream(arena);
    954 	stream_appendfv(&sb, format, args);
    955 	str8 result = arena_stream_commit(arena, &sb);
    956 	return result;
    957 }
    958 
    959 function NumberConversion
    960 integer_from_str8(str8 raw)
    961 {
    962 	read_only local_persist alignas(64) i8 lut[64] = {
    963 		 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
    964 		-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    965 		-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    966 		-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    967 	};
    968 
    969 	NumberConversion result = {.unparsed = raw};
    970 
    971 	i64 i     = 0;
    972 	i64 scale = 1;
    973 	if (raw.length > 0 && raw.data[0] == '-') {
    974 		scale = -1;
    975 		i     =  1;
    976 	}
    977 
    978 	b32 hex = 0;
    979 	if (raw.length - i > 2 && raw.data[i] == '0' && (raw.data[1] == 'x' || raw.data[1] == 'X')) {
    980 		hex = 1;
    981 		i += 2;
    982 	}
    983 
    984 	#define integer_conversion_body(radix, clamp) do {\
    985 		for (; i < raw.length; i++) {\
    986 			i64 value = lut[Min((u8)(raw.data[i] - (u8)'0'), clamp)];\
    987 			if (value >= 0) {\
    988 				if (result.U64 > (U64_MAX - (u64)value) / radix) {\
    989 					result.result = NumberConversionResult_OutOfRange;\
    990 					result.U64    = U64_MAX;\
    991 					return result;\
    992 				} else {\
    993 					result.U64 = radix * result.U64 + (u64)value;\
    994 				}\
    995 			} else {\
    996 				break;\
    997 			}\
    998 		}\
    999 	} while (0)
   1000 
   1001 	if (hex) integer_conversion_body(16u, 63u);
   1002 	else     integer_conversion_body(10u, 15u);
   1003 
   1004 	#undef integer_conversion_body
   1005 
   1006 	result.unparsed = (str8){.length = raw.length - i, .data = raw.data + i};
   1007 	result.result   = i > 0 ? NumberConversionResult_Success : NumberConversionResult_Invalid;
   1008 	result.kind     = NumberConversionKind_Integer;
   1009 	if (scale < 0) result.U64 = 0 - result.U64;
   1010 
   1011 	return result;
   1012 }
   1013 
   1014 function NumberConversion
   1015 number_from_str8(str8 s)
   1016 {
   1017 	NumberConversion result  = {.unparsed = s};
   1018 	NumberConversion integer = integer_from_str8(s);
   1019 	if (integer.result == NumberConversionResult_Success) {
   1020 		if (integer.unparsed.length != 0 && integer.unparsed.data[0] == '.') {
   1021 			s = integer.unparsed;
   1022 			s.data++;
   1023 			s.length--;
   1024 
   1025 			while (s.length > 0 && s.data[s.length - 1] == '0') s.length--;
   1026 
   1027 			NumberConversion fractional = integer_from_str8(s);
   1028 			if (fractional.result == NumberConversionResult_Success || s.length == 0) {
   1029 				result.F64 = (f64)fractional.U64;
   1030 
   1031 				u64 divisor = (u64)(fractional.unparsed.data - s.data);
   1032 				while (divisor > 0) { result.F64 /= 10.0; divisor--; }
   1033 
   1034 				result.F64 += (f64)integer.S64;
   1035 
   1036 				result.result   = NumberConversionResult_Success;
   1037 				result.kind     = NumberConversionKind_Float;
   1038 				result.unparsed = fractional.unparsed;
   1039 			}
   1040 		} else {
   1041 			result = integer;
   1042 		}
   1043 	}
   1044 	return result;
   1045 }