Overflow detection, span-based signatures, flatten control flow

This commit is contained in:
Ian Gulliver
2026-04-10 23:02:07 +09:00
parent 8408603390
commit 76c519c17a
7 changed files with 67 additions and 56 deletions

View File

@@ -31,7 +31,7 @@ void dispatch_schedule_ms(uint32_t ms, std::function<void()> fn) {
static static_vector<uint8_t, 256> usb_rx_buf;
static std::array<uint8_t, 1514> tx_buf;
net_set_handler([&](std::span<const uint8_t> payload, span_writer &out) -> size_t {
net_set_handler([&](std::span<const uint8_t> payload, span_writer &out) -> msgpack::result<size_t> {
auto msg = try_decode(payload.data(), payload.size());
if (!msg) return 0;
auto it = handler_map.find(msg->type_id);
@@ -62,20 +62,19 @@ void dispatch_schedule_ms(uint32_t ms, std::function<void()> fn) {
usb_rx_buf.clear();
auto it = handler_map.find(msg->type_id);
if (it != handler_map.end()) {
span_writer out(tx_buf);
size_t resp_len = it->second(msg->message_id, msg->payload, out);
if (resp_len > 0) {
if (resp_len > usb.tx.free()) {
span_writer err_out(tx_buf);
size_t err_len = encode_response_into(err_out, msg->message_id,
DeviceError{2, "response too large: " + std::to_string(resp_len)});
usb.send(std::span<const uint8_t>{tx_buf.data(), err_len});
} else {
usb.send(std::span<const uint8_t>{tx_buf.data(), resp_len});
}
}
if (it == handler_map.end()) continue;
span_writer out(tx_buf);
auto resp = it->second(msg->message_id, msg->payload, out);
if (!resp || *resp == 0) continue;
size_t resp_len = *resp;
if (resp_len <= usb.tx.free()) {
usb.send(std::span<const uint8_t>{tx_buf.data(), resp_len});
continue;
}
span_writer err_out(tx_buf);
auto err = encode_response_into(err_out, msg->message_id,
DeviceError{2, "response too large: " + std::to_string(resp_len)});
if (err) usb.send(std::span<const uint8_t>{tx_buf.data(), *err});
}
__wfi();