sqlite_rs/header/
database_text_encoding.rs1use crate::traits::{Name, ParseBytes};
2use crate::{
3 field_parsing_error, impl_name,
4 result::{SqliteError, SqliteResult},
5};
6use core::fmt::Display;
7
8#[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}