#include "minor_router.hpp" #include namespace minorio { bool Router::valid_minor(int minor) { return minor >= 0 && minor < 8; } int Router::free_handle() const { for (int fd = 3; fd <= 18; ++fd) { if (handles_.find(fd) == handles_.end()) { return fd; } } return -24; } std::shared_ptr Router::find_session(int fd) const { const auto position = handles_.find(fd); if (position == handles_.end()) { return {}; } return position->second; } std::shared_ptr Router::route(int minor) const { const auto position = routes_.find(minor); if (position == routes_.end()) { return {}; } return position->second; } int Router::create(int minor, std::uint64_t capacity) { if (!valid_minor(minor)) { return -22; } if (capacity == 0 || capacity > 4096) { return -22; } if (routes_.find(minor) != routes_.end()) { return -17; } auto object = std::make_shared(); object->minor = minor; object->capacity = static_cast(capacity); object->generation = generations_[minor] + 1; object->linked = true; object->data.reserve(object->capacity); routes_.emplace(minor, object); generations_[minor] = object->generation; return 0; } int Router::remove(int minor) { if (!valid_minor(minor)) { return -22; } const auto position = routes_.find(minor); if (position == routes_.end()) { return -2; } position->second->linked = false; routes_.erase(position); return 0; } int Router::open(int minor, int mode, int append) { if (!valid_minor(minor)) { return -22; } if (mode < 1 || mode > 3) { return -22; } if (append != 0 && append != 1) { return -22; } auto object = route(minor); if (!object) { return -2; } const int fd = free_handle(); if (fd < 0) { return fd; } auto value = std::make_shared(); value->object = object; value->cursor = 0; value->mode = mode; value->append = append != 0; handles_.emplace(fd, std::move(value)); return fd; } int Router::duplicate(int fd) { auto value = find_session(fd); if (!value) { return -9; } const int result = free_handle(); if (result < 0) { return result; } handles_.emplace(result, std::move(value)); return result; } int Router::close(int fd) { const auto position = handles_.find(fd); if (position == handles_.end()) { return -9; } handles_.erase(position); return 0; } int Router::set_append(int fd, int enabled) { auto value = find_session(fd); if (!value) { return -9; } if (enabled != 0 && enabled != 1) { return -22; } value->append = enabled != 0; return 0; } int Router::readable(int fd, std::shared_ptr &value) const { const auto found = find_session(fd); if (!found) { return -9; } if ((found->mode & 1) == 0) { return -13; } value = found; return 0; } int Router::writable(int fd, std::shared_ptr &value) const { const auto found = find_session(fd); if (!found) { return -9; } if ((found->mode & 2) == 0) { return -13; } value = found; return 0; } void Router::reset() { handles_.clear(); routes_.clear(); generations_.clear(); } }