#include "model_internal.hpp" #include namespace ps { Model::Model() : state(new Impl) { } Model::~Model() = default; void Model::reset() { state.reset(new Impl); } bool valid_device(int device) { return device >= 0 && device < 4; } bool valid_actor(int actor) { return actor >= 0 && actor < 8; } int device_error(const Impl &state, int device) { if (!valid_device(device)) { return -22; } if (!state.devices[device].live) { return -19; } return 0; } int watch_error(const Impl &state, int actor, std::uint64_t token) { if (!valid_actor(actor)) { return -22; } const auto &watch = state.actors[actor].view; if (watch.phase == IDLE || watch.token != token) { return -116; } return 0; } unsigned readiness(const Device &device) { unsigned result = device.flags; if (device.size != 0) { result |= READ; } if (device.credits != 0 && !(device.flags & HUP)) { result |= WRITE; } return result; } unsigned filter_ready(unsigned bits, unsigned requested) { return (bits & requested & (READ | WRITE)) | (bits & (ERROR | HUP)); } bool is_terminal(int phase) { return phase >= READY && phase <= GONE; } int terminal_result(const WatchView &watch) { switch (watch.phase) { case READY: return 1; case CANCELLED: return -125; case INTERRUPTED: return -4; case GONE: return -19; default: return 0; } } void subscribe(Impl &state, int actor) { auto &watch = state.actors[actor].view; if (watch.registered) { return; } auto &listeners = state.devices[watch.device].listeners; listeners.push_back(actor); std::sort(listeners.begin(), listeners.end()); watch.registered = 1; } void unsubscribe(Impl &state, int actor) { auto &watch = state.actors[actor].view; if (!watch.registered) { return; } auto &listeners = state.devices[watch.device].listeners; listeners.erase(std::remove(listeners.begin(), listeners.end(), actor), listeners.end()); watch.registered = 0; } int finish_watch(Impl &state, int actor, int phase) { auto &watch = state.actors[actor].view; unsubscribe(state, actor); watch.phase = phase; watch.ready = 0; watch.pending = 0; return 0; } std::vector queue_data(const Device &device) { std::vector output; output.reserve(device.size); for (int offset = 0; offset < device.size; ++offset) { int position = (device.head + offset) % device.capacity; output.push_back(device.buffer[position]); } return output; } void queue_append(Device &device, const std::vector &data) { for (auto value : data) { int tail = (device.head + device.size) % device.capacity; device.buffer[tail] = value; ++device.size; } } void queue_consume(Device &device, int count) { if (count == 0) { return; } if (count == device.size) { device.head = 0; device.size = 0; return; } device.head = (device.head + count) % device.capacity; device.size -= count; } }