22#ifndef MMAPPED_VECTOR_HPP
23#define MMAPPED_VECTOR_HPP
42 fd=open(filename, O_CREAT|(read_only?O_RDONLY:O_RDWR), 0600);
44 throw std::runtime_error(strerror(errno));
46 auto length = lseek(fd, 0, SEEK_END);
47 lseek(fd, 0, SEEK_SET);
53 length=offsetof(
data_t, d)+
sizeof(T)*STARTING_CAPACITY;
54 if(ftruncate(fd, length))
55 throw std::runtime_error(strerror(errno));
58 mmap(length, read_only);
61 data->capacity = STARTING_CAPACITY;
62 data->nb_elements = 0;
69 data =
reinterpret_cast<data_t *
>(::mmap(
72 PROT_READ|(read_only?0:PROT_WRITE),
76 if(data == MAP_FAILED)
77 throw std::runtime_error(strerror(errno));
84 auto new_capacity = data->capacity*2;
85 munmap(data, offsetof(
data_t,d)+
sizeof(T)*data->capacity);
87 auto new_length = offsetof(data_t,d)+
sizeof(T)*new_capacity;
88 if(ftruncate(fd, new_length))
89 throw std::runtime_error(strerror(errno));
90 mmap(new_length,
false);
92 data->capacity = new_capacity;
98 munmap(data, offsetof(
data_t,d)+
sizeof(T)*data->capacity);
117 if(data->nb_elements == data->capacity)
120 data->d[data->nb_elements++] = value;
126 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.
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.
void grow()
Double the backing file and remap.
const T & operator[](unsigned long k) const
Read-only element access by index.
void sync()
Flush dirty pages to the backing file with msync().
MMappedVector(const char *filename, bool read_only)
Open (or create) the mmap-backed vector.
On-disk layout stored at the start of the backing file.