sqlite_rs/header/
database_text_encoding.rs

1use crate::traits::{Name, ParseBytes};
2use crate::{
3  field_parsing_error, impl_name,
4  result::{SqliteError, SqliteResult},
5};
6use core::fmt::Display;
7
8/// # Text encoding (4 Bytes)
9///
10///  The 4-byte big-endian integer at offset 56 determines the encoding used for
11/// all text strings stored in the database. A value of 1 means UTF-8. A value
12/// of 2 means UTF-16le. A value of 3 means UTF-16be. No other values are
13/// allowed. The sqlite3.h header file defines C-preprocessor macros
14/// SQLITE_UTF8 as 1, SQLITE_UTF16LE as 2, and SQLITE_UTF16BE as 3, to use in
15/// place of the numeric codes for the text encoding.
16#[derive(Debug, Default)]
17pub enum DatabaseTextEncoding {
18  #[default]
19  Utf8,
20  Utf16Le,
21  Utf16Be,
22}
23
24impl From<&DatabaseTextEncoding> for u32 {
25  fn from(value: &DatabaseTextEncoding) -> Self {
26    match value {
27      DatabaseTextEncoding::Utf8 => 1,
28      DatabaseTextEncoding::Utf16Le => 2,
29      DatabaseTextEncoding::Utf16Be => 3,
30    }
31  }
32}
33
34impl TryFrom<u32> for DatabaseTextEncoding {
35  type Error = SqliteError;
36
37  fn try_from(value: u32) -> Result<Self, Self::Error> {
38    match value {
39      1 => Ok(Self::Utf8),
40      2 => Ok(Self::Utf16Le),
41      3 => Ok(Self::Utf16Be),
42      _ => Err(field_parsing_error! {Self::NAME.into()}),
43    }
44  }
45}
46
47impl Display for DatabaseTextEncoding {
48  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
49    let number = u32::from(self);
50    let name = match self {
51      DatabaseTextEncoding::Utf8 => "utf8",
52      DatabaseTextEncoding::Utf16Le => "utf16le",
53      DatabaseTextEncoding::Utf16Be => "utf16le",
54    };
55    write!(f, "{number} ({name})")
56  }
57}
58
59impl_name! {DatabaseTextEncoding}
60
61impl ParseBytes for DatabaseTextEncoding {
62  const LENGTH_BYTES: usize = 4;
63
64  fn parsing_handler(bytes: &[u8]) -> SqliteResult<Self> {
65    let buf: [u8; Self::LENGTH_BYTES] = bytes.try_into()?;
66
67    let value = u32::from_be_bytes(buf);
68
69    value.try_into()
70  }
71}