Skip to main content

sqlrite/sql/pager/
file.rs

1//! Page-indexed file I/O: read/write whole pages by page number, plus the
2//! special page-0 header. Deliberately thin — this is the only place that
3//! touches `std::fs`, so higher layers deal in pages, not offsets.
4
5use std::fs::File;
6use std::io::{Read, Seek, SeekFrom, Write};
7
8use crate::error::Result;
9use crate::sql::pager::header::{DbHeader, decode_header, encode_header};
10use crate::sql::pager::page::PAGE_SIZE;
11
12pub struct FileStorage {
13    file: File,
14}
15
16impl FileStorage {
17    pub fn new(file: File) -> Self {
18        Self { file }
19    }
20
21    pub fn read_header(&mut self) -> Result<DbHeader> {
22        self.file.seek(SeekFrom::Start(0))?;
23        let mut buf = [0u8; PAGE_SIZE];
24        self.file.read_exact(&mut buf)?;
25        decode_header(&buf)
26    }
27
28    pub fn write_header(&mut self, header: &DbHeader) -> Result<()> {
29        let buf = encode_header(header);
30        self.file.seek(SeekFrom::Start(0))?;
31        self.file.write_all(&buf)?;
32        Ok(())
33    }
34
35    pub fn flush(&mut self) -> Result<()> {
36        self.file.flush()?;
37        self.file.sync_all()?;
38        Ok(())
39    }
40
41    /// Low-level byte I/O helpers used by the `Pager` to bypass the per-page
42    /// encoding when it's managing its own raw buffers.
43
44    pub fn seek_to(&mut self, offset: u64) -> Result<()> {
45        self.file.seek(SeekFrom::Start(offset))?;
46        Ok(())
47    }
48
49    pub fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
50        self.file.read_exact(buf)?;
51        Ok(())
52    }
53
54    pub fn write_all(&mut self, buf: &[u8]) -> Result<()> {
55        self.file.write_all(buf)?;
56        Ok(())
57    }
58
59    /// Shrinks the backing file to `page_count` pages. Any bytes beyond the
60    /// new length are discarded.
61    pub fn truncate_to_pages(&mut self, page_count: u32) -> Result<()> {
62        self.file
63            .set_len((page_count as u64) * (PAGE_SIZE as u64))?;
64        Ok(())
65    }
66}