20 if (chunk_size == 0) {
21 throw std::invalid_argument(
"chunk_size must be positive");
41 fs::create_directories(path.parent_path());
43 if (!file && !read_only)
46 LogError(
"Unable to open file %s", fs::PathToString(path));
50 LogError(
"Unable to seek to position %u of %s", pos.
nPos, fs::PathToString(path));
51 if (fclose(file) != 0) {
52 LogError(
"Unable to close file %s", fs::PathToString(path));
63 uint64_t n_old_chunks =
CeilDiv(pos.
nPos, uint64_t{m_chunk_size});
64 uint64_t n_new_chunks =
CeilDiv(pos.
nPos + add_size, uint64_t{m_chunk_size});
65 if (n_new_chunks > n_old_chunks) {
66 uint64_t old_size = pos.
nPos;
68 size_t inc_size = new_size - old_size;
71 FILE *file =
Open(pos);
75 if (fclose(file) != 0) {
76 LogError(
"Cannot close file %s%05u.dat after extending it with %u bytes",
m_prefix, pos.
nFile, new_size);
92 LogError(
"%s: failed to open file %d\n", __func__, pos.
nFile);
96 LogError(
"%s: failed to truncate file %d\n", __func__, pos.
nFile);
97 if (fclose(file) != 0) {
103 LogError(
"%s: failed to commit file %d\n", __func__, pos.
nFile);
104 if (fclose(file) != 0) {
111 if (fclose(file) != 0) {
FILE * Open(const FlatFilePos &pos, bool read_only=false) const
Open a handle to the file at the given position.
fs::path FileName(const FlatFilePos &pos) const
Get the name of the file at the given position.
bool Flush(const FlatFilePos &pos, bool finalize=false) const
Commit a file to disk, and optionally truncate off extra pre-allocated bytes if final.
size_t Allocate(const FlatFilePos &pos, size_t add_size, bool &out_of_space) const
Allocate additional space in a file after the given starting position.
const size_t m_chunk_size
const char *const m_prefix
FlatFileSeq(fs::path dir, const char *prefix, size_t chunk_size)
Constructor.
bool TruncateFile(FILE *file, uint64_t length)
void DirectoryCommit(const fs::path &dirname)
Sync directory contents.
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
void AllocateFileRange(FILE *file, uint64_t offset, unsigned int length)
this function tries to make a particular range of a file allocated (corresponding to disk space) it i...
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
int FileSeek64(FILE *file, int64_t offset, int origin)
64-bit-clean file positioning.
#define LogDebug(category,...)
FILE * fopen(const fs::path &p, const char *mode)
constexpr auto CeilDiv(const Dividend dividend, const Divisor divisor)
Integer ceiling division (for unsigned values).
std::string ToString() const