#include "buffer_port.h" #include "render_api.h" #include struct allocation { int live; size_t capacity; unsigned char bytes[TEXT_LIMIT]; }; static struct allocation allocations[PORT_SLOTS]; static struct port_observation counters; static int fail_allocate; static int fail_sink; static uint32_t append_digest(uint32_t value, unsigned char byte) { return value * UINT32_C(33) + byte + UINT32_C(1); } void port_begin(int allocation_failure, int sink_failure) { fail_allocate = allocation_failure; fail_sink = sink_failure; counters.output_length = 0; memset(counters.output, 0, sizeof(counters.output)); } char *port_allocate(size_t capacity) { counters.allocation_attempts++; if (fail_allocate || capacity == 0 || capacity > TEXT_LIMIT) { return NULL; } for (unsigned slot = 0; slot < PORT_SLOTS; slot++) { if (!allocations[slot].live) { allocations[slot].live = 1; allocations[slot].capacity = capacity; memset(allocations[slot].bytes, 0xa5, TEXT_LIMIT); counters.allocated++; return (char *)allocations[slot].bytes; } } return NULL; } int port_release(char *buffer) { for (unsigned slot = 0; slot < PORT_SLOTS; slot++) { if (buffer == (char *)allocations[slot].bytes) { if (!allocations[slot].live) { counters.invalid++; return 0; } allocations[slot].live = 0; memset(allocations[slot].bytes, 0xdd, TEXT_LIMIT); counters.released++; return 1; } } counters.invalid++; return 0; } int port_publish(const char *buffer, size_t length) { counters.sink_attempts++; for (unsigned slot = 0; slot < PORT_SLOTS; slot++) { struct allocation *allocation = &allocations[slot]; if (buffer != (const char *)allocation->bytes) { continue; } if (!allocation->live || length >= allocation->capacity || allocation->bytes[length] != 0) { counters.invalid++; return 0; } if (fail_sink) { return 0; } counters.published++; counters.output_length = length; memcpy(counters.output, allocation->bytes, length); return 1; } counters.invalid++; return 0; } struct port_observation port_observe(void) { struct port_observation observation = counters; observation.live = 0; observation.live_digest = 0; for (unsigned slot = 0; slot < PORT_SLOTS; slot++) { const struct allocation *allocation = &allocations[slot]; if (allocation->live) { observation.live++; observation.live_digest = append_digest(observation.live_digest, (unsigned char)slot); observation.live_digest = append_digest(observation.live_digest, (unsigned char)(allocation->capacity & 255U)); observation.live_digest = append_digest(observation.live_digest, (unsigned char)(allocation->capacity >> 8)); for (size_t index = 0; index < allocation->capacity; index++) { observation.live_digest = append_digest(observation.live_digest, allocation->bytes[index]); } } } return observation; }