#include "segment_bank.hpp" #include namespace segment { Bank::Attachment *Bank::attachment(int handle) { for (auto &entry : handles_) { if (entry.number == handle) { return &entry; } } return nullptr; } const Bank::Attachment *Bank::attachment(int handle) const { for (const auto &entry : handles_) { if (entry.number == handle) { return &entry; } } return nullptr; } int Bank::attach(int id, int readonly) { const Object *entry = object(id); if (entry == nullptr || entry->removed) { return -2; } if (readonly != 0 && readonly != 1) { return -22; } if (handles_.size() == 16) { return -28; } int number = 0; while (attachment(number) != nullptr) { ++number; } handles_.push_back(Attachment{number, id, readonly == 1}); return number; } int Bank::detach(int handle) { const Attachment *entry = attachment(handle); if (entry == nullptr) { return -9; } int id = entry->id; auto at = std::remove_if(handles_.begin(), handles_.end(), [handle](const Attachment &item) { return item.number == handle; }); handles_.erase(at, handles_.end()); collect(id); return 0; } int Bank::view(int handle, ViewInfo &out) const { const Attachment *entry = attachment(handle); if (entry == nullptr || !retained(entry->id)) { return -9; } ViewInfo value; value.segment = describe(*object(entry->id)); value.readonly = entry->readonly ? 1 : 0; out = value; return 0; } int Bank::check_range(std::size_t size, std::size_t offset, std::size_t length) const { if (offset > size) { return -22; } if (length > size - offset) { return -22; } return 0; } int Bank::read(int handle, std::size_t offset, std::size_t length, Bytes &out) const { const Attachment *entry = attachment(handle); if (entry == nullptr || !retained(entry->id)) { return -9; } const Bytes &data = object(entry->id)->data; if (check_range(data.size(), offset, length) != 0) { return -22; } Bytes result; result.reserve(length); for (std::size_t index = 0; index < length; ++index) { result.push_back(data[offset + index]); } out.swap(result); return 0; } int Bank::write(int handle, std::size_t offset, const Bytes &input) { Attachment *entry = attachment(handle); if (entry == nullptr || !retained(entry->id)) { return -9; } if (entry->readonly) { return -13; } Bytes &data = object(entry->id)->data; if (check_range(data.size(), offset, input.size()) != 0) { return -22; } for (std::size_t index = 0; index < input.size(); ++index) { data[offset + index] = input[index]; } return 0; } int Bank::fill(int handle, std::size_t offset, std::size_t length, unsigned char byte) { Attachment *entry = attachment(handle); if (entry == nullptr || !retained(entry->id)) { return -9; } if (entry->readonly) { return -13; } Bytes &data = object(entry->id)->data; if (check_range(data.size(), offset, length) != 0) { return -22; } for (std::size_t index = 0; index < length; ++index) { data[offset + index] = byte; } return 0; } }