22#ifndef MMAPPED_VECTOR_HPP
23#define MMAPPED_VECTOR_HPP
44 fd=open(filename, O_CREAT|(read_only?O_RDONLY:O_RDWR), 0600);
46 throw std::runtime_error(strerror(errno));
48 auto length = lseek(
fd, 0, SEEK_END);
49 lseek(
fd, 0, SEEK_SET);
56 if(ftruncate(
fd, length))
57 throw std::runtime_error(strerror(errno));
60 mmap(length, read_only);
63 data->magic = magic_value;
65 data->elem_size =
static_cast<uint16_t
>(
sizeof(T));
68 data->nb_elements = 0;
70 if(data->magic != magic_value)
71 throw std::runtime_error(
"ProvSQL mmap: wrong file type (magic mismatch)");
72 if(data->version != 1)
73 throw std::runtime_error(
"ProvSQL mmap: unsupported format version "
74 + std::to_string(data->version));
75 if(data->elem_size !=
sizeof(T))
76 throw std::runtime_error(
"ProvSQL mmap: element size mismatch (recompile required)");
86 PROT_READ|(read_only?0:PROT_WRITE),
90 if(
data == MAP_FAILED)
91 throw std::runtime_error(strerror(errno));
98 auto new_capacity =
data->capacity*2;
101 auto new_length = offsetof(
data_t,d)+
sizeof(T)*new_capacity;
102 if(ftruncate(
fd, new_length))
103 throw std::runtime_error(strerror(errno));
104 mmap(new_length,
false);
106 data->capacity = new_capacity;
131 if(
data->nb_elements ==
data->capacity)
134 data->d[
data->nb_elements++] = value;
140 msync(
data, offsetof(
data_t,d)+
sizeof(T)*
data->capacity, MS_SYNC);
Append-only vector template backed by a memory-mapped file.
~MMappedVector()
Sync and unmap the file.
data_t * data
Pointer to the memory-mapped data header.
static constexpr unsigned STARTING_CAPACITY
Initial number of element slots allocated.
void add(const T &value)
Append an element to the end of the vector.
void mmap(size_t length, bool read_only)
Map length bytes from the backing file.
int fd
File descriptor of the backing mmap file.
void grow()
Double the backing file and remap.
MMappedVector(const char *filename, bool read_only, uint64_t magic)
Open (or create) the mmap-backed vector.
const T & operator[](unsigned long k) const
Read-only element access by index.
void sync()
Flush dirty pages to the backing file with msync().
On-disk layout stored at the start of the backing file.