Sourcemeta Core 0.0.0
Loading...
Searching...
No Matches
io_fileview.h
1#ifndef SOURCEMETA_CORE_IO_FILEVIEW_H_
2#define SOURCEMETA_CORE_IO_FILEVIEW_H_
3
4#ifndef SOURCEMETA_CORE_IO_EXPORT
5#include <sourcemeta/core/io_export.h>
6#endif
7
8#include <cassert> // assert
9#include <cstddef> // std::size_t
10#include <cstdint> // std::uint8_t
11#include <filesystem> // std::filesystem::path
12#include <span> // std::span
13
14namespace sourcemeta::core {
15
32class SOURCEMETA_CORE_IO_EXPORT FileView {
33public:
35 FileView(const std::filesystem::path &path);
36 ~FileView();
37
38 // Disable copying and moving
39 FileView(const FileView &) = delete;
40 FileView(FileView &&) = delete;
41 auto operator=(const FileView &) -> FileView & = delete;
42 auto operator=(FileView &&) -> FileView & = delete;
43
45 [[nodiscard]] auto size() const noexcept -> std::size_t;
46
58 [[nodiscard]] auto bytes() const noexcept -> std::span<const std::uint8_t> {
59 return {this->data_, this->size_};
60 }
61
65 template <typename T>
66 [[nodiscard]] auto as(const std::size_t offset = 0) const noexcept
67 -> const T * {
68 assert(offset + sizeof(T) <= this->size_);
69 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
70 return reinterpret_cast<const T *>(this->data_ + offset);
71 }
72
73private:
74 const std::uint8_t *data_{nullptr};
75 std::size_t size_{0};
76#if defined(_WIN32)
77 void *file_handle_{nullptr};
78 void *mapping_handle_{nullptr};
79#else
80 int file_descriptor_{-1};
81#endif
82};
83
84} // namespace sourcemeta::core
85
86#endif
FileView(const std::filesystem::path &path)
Memory-map the file at the given path.
auto bytes() const noexcept -> std::span< const std::uint8_t >
Definition io_fileview.h:58
auto as(const std::size_t offset=0) const noexcept -> const T *
Definition io_fileview.h:66
auto size() const noexcept -> std::size_t
The size of the memory-mapped data in bytes.