| 1 | //===----------------------------------------------------------------------===// |
|---|---|
| 2 | // DuckDB |
| 3 | // |
| 4 | // duckdb/common/serializer/buffered_file_writer.hpp |
| 5 | // |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #pragma once |
| 10 | |
| 11 | #include "duckdb/common/serializer.hpp" |
| 12 | #include "duckdb/common/file_system.hpp" |
| 13 | |
| 14 | namespace duckdb { |
| 15 | |
| 16 | #define FILE_BUFFER_SIZE 4096 |
| 17 | |
| 18 | class BufferedFileWriter : public Serializer { |
| 19 | public: |
| 20 | static constexpr uint8_t DEFAULT_OPEN_FLAGS = FileFlags::FILE_FLAGS_WRITE | FileFlags::FILE_FLAGS_FILE_CREATE; |
| 21 | |
| 22 | //! Serializes to a buffer allocated by the serializer, will expand when |
| 23 | //! writing past the initial threshold |
| 24 | DUCKDB_API BufferedFileWriter(FileSystem &fs, const string &path, uint8_t open_flags = DEFAULT_OPEN_FLAGS); |
| 25 | |
| 26 | FileSystem &fs; |
| 27 | string path; |
| 28 | unsafe_unique_array<data_t> data; |
| 29 | idx_t offset; |
| 30 | idx_t total_written; |
| 31 | unique_ptr<FileHandle> handle; |
| 32 | |
| 33 | public: |
| 34 | DUCKDB_API void WriteData(const_data_ptr_t buffer, uint64_t write_size) override; |
| 35 | //! Flush the buffer to disk and sync the file to ensure writing is completed |
| 36 | DUCKDB_API void Sync(); |
| 37 | //! Flush the buffer to the file (without sync) |
| 38 | DUCKDB_API void Flush(); |
| 39 | //! Returns the current size of the file |
| 40 | DUCKDB_API int64_t GetFileSize(); |
| 41 | //! Truncate the size to a previous size (given that size <= GetFileSize()) |
| 42 | DUCKDB_API void Truncate(int64_t size); |
| 43 | |
| 44 | DUCKDB_API idx_t GetTotalWritten(); |
| 45 | }; |
| 46 | |
| 47 | } // namespace duckdb |
| 48 |