commit 1.2
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
module;
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
module io;
|
||||
|
||||
import std;
|
||||
|
||||
namespace brc {
|
||||
|
||||
std::string read_file(const std::filesystem::path& path) {
|
||||
auto file = std::ifstream(path);
|
||||
if (!file.is_open()) {
|
||||
throw std::runtime_error(std::format("could not open file: {}", path.string()));
|
||||
}
|
||||
auto stream = std::stringstream();
|
||||
stream << file.rdbuf();
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
mapped_file::mapped_file(const std::filesystem::path& path) {
|
||||
const auto file_size = std::filesystem::file_size(path);
|
||||
|
||||
fd = open(path.generic_string().data(), O_RDONLY);
|
||||
data = mmap(nullptr, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
|
||||
length = file_size;
|
||||
|
||||
if (data == MAP_FAILED) {
|
||||
close(fd);
|
||||
throw std::runtime_error("failed to map file");
|
||||
}
|
||||
}
|
||||
|
||||
mapped_file::mapped_file(mapped_file&& other) noexcept
|
||||
: fd(other.fd), data(std::exchange(other.data, nullptr)), length(other.length) {}
|
||||
|
||||
mapped_file& mapped_file::operator=(mapped_file&& other) noexcept {
|
||||
if (&other == this) {
|
||||
return *this;
|
||||
}
|
||||
|
||||
auto moved = std::move(other);
|
||||
|
||||
std::swap(moved.fd, this->fd);
|
||||
std::swap(moved.data, this->data);
|
||||
std::swap(moved.length, this->length);
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
mapped_file::~mapped_file() {
|
||||
if (data != nullptr) {
|
||||
munmap(data, length);
|
||||
close(fd);
|
||||
}
|
||||
}
|
||||
|
||||
mapped_file::operator std::string_view() const noexcept {
|
||||
return std::string_view(reinterpret_cast<const char*>(data), length);
|
||||
}
|
||||
|
||||
std::size_t mapped_file::size() const noexcept { return length; }
|
||||
|
||||
} // namespace brc
|
||||
Reference in New Issue
Block a user