#include "io.hpp" #include namespace bio { Session::State Session::fold() const { State state; for (Number i = 0; i < 4; ++i) { state.slots[i].id = i; } for (const Event& e : events_) { state.last = Code::Ok; if (e.id < 0 || e.id > 3) { state.last = Code::BadId; continue; } if (e.op == 0 && (e.a < 1 || e.a > 8)) { state.last = Code::BadCapacity; continue; } if (e.op == 1 && (e.a < 0 || e.a > 255)) { state.last = Code::BadByte; continue; } if (e.op == 1 && (e.b < 0 || e.b > 16)) { state.last = Code::BadCount; continue; } if (e.op == 2 && (e.a < 1 || e.a > 3)) { state.last = Code::BadStage; continue; } if (e.op == 2 && (e.b < 0 || e.b > 1)) { state.last = Code::BadEnabled; continue; } View& v = state.slots[e.id]; if (e.op == 0) { if (v.live) { state.last = Code::Exists; continue; } View fresh; fresh.id = e.id; fresh.code = Code::Ok; fresh.seen = true; fresh.live = true; fresh.capacity = e.a; v = fresh; ++state.totals.opened; ++state.totals.live; continue; } if (!v.live) { state.last = Code::Missing; continue; } if (e.op == 2) { v.faults[e.a-1] = e.b != 0; continue; } auto drain = [&]() { while (v.pending.size()) { ++v.writes; ++state.totals.writes; v.history.push_back('W'); if (v.faults[0]) { return Code::WriteError; } const auto count = std::min(2, v.pending.size()); v.durable.append(v.pending.substr(0, count)); v.pending = v.pending.substr(count); } return Code::Ok; }; if (e.op == 1) { Number remaining = e.b; while (remaining > 0) { const Number space = v.capacity - static_cast(v.pending.size()); if (space == 0) { state.last = drain(); if (state.last != Code::Ok) { break; } } else { const Number amount = std::min(space, remaining); v.pending.append(static_cast(amount), static_cast(e.a)); remaining -= amount; } } v.last = state.last; continue; } state.last = drain(); if (state.last == Code::Ok) { ++v.flushes; ++state.totals.flushes; v.history.push_back('F'); if (v.faults[1]) { state.last = Code::FlushError; } } if (e.op == 4) { ++v.closes; ++state.totals.closes; v.history.push_back('C'); if (state.last == Code::Ok && v.faults[2]) { state.last = Code::CloseError; } v.pending.clear(); v.live = false; --state.totals.live; ++state.totals.closed; } v.last = state.last; } return state; } Code Session::record(int op, Number id, Number a, Number b) { events_.push_back({op,id,a,b}); return fold().last; } Code Session::open(Number id, Number capacity) { return record(0,id,capacity); } Code Session::put(Number id, Number byte, Number count) { return record(1,id,byte,count); } Code Session::arm(Number id, Number stage, Number enabled) { return record(2,id,stage,enabled); } Code Session::flush(Number id) { return record(3,id); } Code Session::close(Number id) { return record(4,id); } View Session::view(Number id) const { View result; result.id = id; if (id < 0 || id > 3) { result.code = Code::BadId; return result; } return fold().slots[id]; } Stats Session::stats() const { return fold().totals; } }