Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
mapped_file.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cstddef>
4#include <cstdint>
5#include <string>
6
7namespace slick::trader {
8
9// A file mapped into memory, read-write: state that has to outlive the process.
10//
11// Writing to it is a store to memory - no system call, nothing to wait for - so the thread
12// that owns the state keeps it on disk without ever blocking on the disk. The operating
13// system writes the pages out in its own time, and still does when the process dies: what
14// was stored before a crash or a kill is in the file. Only the machine itself going down
15// (power, kernel) can lose the last moments, which flush() narrows.
16//
17// Not thread-safe, and not for two processes at once: one owner.
19public:
20 MappedFile() = default;
21
22 // Maps `path`, creating it and any missing directories. A new file is `size` bytes of
23 // zeros; an existing one is grown, with zeros, if it is smaller, and otherwise mapped
24 // whole. Throws std::runtime_error when the file cannot be opened or mapped.
25 MappedFile(const std::string& path, std::size_t size);
27
28 MappedFile(MappedFile&& other) noexcept;
29 MappedFile& operator=(MappedFile&& other) noexcept;
30 MappedFile(const MappedFile&) = delete;
31 MappedFile& operator=(const MappedFile&) = delete;
32
33 std::uint8_t* data() noexcept { return data_; }
34 const std::uint8_t* data() const noexcept { return data_; }
35 std::size_t size() const noexcept { return size_; }
36 bool is_open() const noexcept { return data_ != nullptr; }
37
38 // True when the constructor created the file: there was nothing to restore.
39 bool created() const noexcept { return created_; }
40
41 // Asks the operating system to write the mapped pages to disk now. Blocks on the disk:
42 // not for a latency-sensitive thread.
43 void flush() noexcept;
44
45 void close() noexcept;
46
47private:
48 std::uint8_t* data_{nullptr};
49 std::size_t size_{0};
50 bool created_{false};
51#if defined(_WIN32) || defined(_WIN64)
52 void* file_{nullptr}; // HANDLE
53 void* mapping_{nullptr}; // HANDLE
54#else
55 int fd_{-1};
56#endif
57};
58
59} // namespace slick::trader
MappedFile & operator=(const MappedFile &)=delete
std::size_t size() const noexcept
MappedFile(const MappedFile &)=delete
bool created() const noexcept
MappedFile & operator=(MappedFile &&other) noexcept
std::uint8_t * data() noexcept
bool is_open() const noexcept
const std::uint8_t * data() const noexcept