sqlite_rs/header/
page_size.rs

1use crate::traits::ParseBytes;
2use crate::{
3  impl_name,
4  result::{SqliteError, SqliteResult},
5};
6
7/// # Page Size (2 Bytes)
8///
9///  The two-byte value beginning at offset 16 determines the page size of the
10/// database. For Sqlite versions 3.7.0.1 (2010-08-04) and earlier, this value
11/// is interpreted as a big-endian integer and must be a power of two between
12/// 512 and 32768, inclusive. Beginning with Sqlite version 3.7.1 (2010-08-23),
13/// a page size of 65536 bytes is supported. The value 65536 will not fit in a
14/// two-byte integer, so to specify a 65536-byte page size, the value at offset
15/// 16 is 0x00 0x01. This value can be interpreted as a big-endian 1 and
16/// thought of as a magic number to represent the 65536 page size. Or one can
17/// view the two-byte field as a little endian number and say that it
18/// represents the page size divided by 256. These two interpretations of the
19/// page-size field are equivalent.
20#[derive(Debug, Default, PartialEq, Eq, Clone)]
21pub enum PageSize {
22  L512,
23  L1024,
24  L2048,
25  /// Reference: https://www.sqlite.org/pragma.html#pragma_page_size
26  #[default]
27  L4096,
28  L8192,
29  L16384,
30  L32768,
31  L65536,
32}
33
34impl PageSize {
35  pub const MAX: Self = Self::L65536;
36
37  pub const fn as_usize(&self) -> usize {
38    match self {
39      PageSize::L512 => 512,
40      PageSize::L1024 => 1024,
41      PageSize::L2048 => 2048,
42      PageSize::L4096 => 4096,
43      PageSize::L8192 => 8192,
44      PageSize::L16384 => 16384,
45      PageSize::L32768 => 32768,
46      PageSize::L65536 => 65536,
47    }
48  }
49}
50
51impl From<&PageSize> for u32 {
52  fn from(value: &PageSize) -> Self {
53    match *value {
54      PageSize::L512 => 512,
55      PageSize::L1024 => 1024,
56      PageSize::L2048 => 2048,
57      PageSize::L4096 => 4096,
58      PageSize::L8192 => 8192,
59      PageSize::L16384 => 16384,
60      PageSize::L32768 => 32768,
61      PageSize::L65536 => 65536,
62    }
63  }
64}
65
66impl_name! {PageSize}
67
68impl ParseBytes for PageSize {
69  const LENGTH_BYTES: usize = 2;
70
71  fn parsing_handler(bytes: &[u8]) -> SqliteResult<Self> {
72    let buf: [u8; Self::LENGTH_BYTES] = bytes.try_into()?;
73
74    let page_size = u16::from_be_bytes(buf);
75
76    match page_size {
77      0 | 2..=511 => Err(SqliteError::Custom(
78        "PageSize can't be less than 512".into(),
79      )),
80      512 => Ok(Self::L512),
81      1024 => Ok(Self::L1024),
82      2048 => Ok(Self::L2048),
83      4096 => Ok(Self::L4096),
84      8192 => Ok(Self::L8192),
85      16384 => Ok(Self::L16384),
86      32768 => Ok(Self::L32768),
87      1 => Ok(Self::L65536),
88      _ => Err(SqliteError::Custom("PageSize must be power of two".into())),
89    }
90  }
91}