khive_pack_session/mirror/
raw_codec.rs1use std::borrow::Cow;
7use std::fmt;
8
9use khive_storage::SqlValue;
10
11#[derive(Debug)]
13pub enum RawCodecError {
14 UnsupportedValue(&'static str),
15 EmptyBlob,
16 UnsupportedPrefix(u8),
17 Compression(std::io::Error),
18 Decompression(std::io::Error),
19 InvalidUtf8(std::str::Utf8Error),
20}
21
22impl fmt::Display for RawCodecError {
23 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24 match self {
25 Self::UnsupportedValue(kind) => {
26 write!(f, "session raw codec requires TEXT or BLOB, got {kind}")
27 }
28 Self::EmptyBlob => f.write_str("session raw BLOB has no format prefix"),
29 Self::UnsupportedPrefix(prefix) => {
30 write!(f, "unsupported session raw BLOB prefix 0x{prefix:02x}")
31 }
32 Self::Compression(error) => write!(f, "session raw compression failed: {error}"),
33 Self::Decompression(error) => write!(f, "session raw decompression failed: {error}"),
34 Self::InvalidUtf8(error) => write!(f, "decoded session raw is not UTF-8: {error}"),
35 }
36 }
37}
38
39impl std::error::Error for RawCodecError {
40 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
41 match self {
42 Self::Compression(error) | Self::Decompression(error) => Some(error),
43 Self::InvalidUtf8(error) => Some(error),
44 _ => None,
45 }
46 }
47}
48
49pub fn encode_raw(raw: &str) -> Result<SqlValue, RawCodecError> {
53 let frame = zstd::bulk::compress(raw.as_bytes(), 3).map_err(RawCodecError::Compression)?;
54 let mut blob = Vec::with_capacity(frame.len() + 1);
55 blob.push(0x01);
56 blob.extend_from_slice(&frame);
57 Ok(SqlValue::Blob(blob))
58}
59
60pub fn decode_raw(
66 value: &SqlValue,
67 max_decoded_blob_bytes: usize,
68) -> Result<Cow<'_, str>, RawCodecError> {
69 match value {
70 SqlValue::Text(text) => Ok(Cow::Borrowed(text)),
71 SqlValue::Blob(blob) => {
72 let (&prefix, frame) = blob.split_first().ok_or(RawCodecError::EmptyBlob)?;
73 if prefix != 0x01 {
74 return Err(RawCodecError::UnsupportedPrefix(prefix));
75 }
76 if frame.is_empty() {
79 return Err(RawCodecError::Decompression(std::io::Error::new(
80 std::io::ErrorKind::UnexpectedEof,
81 "session raw zstd frame is empty",
82 )));
83 }
84 let bytes = zstd::bulk::decompress(frame, max_decoded_blob_bytes)
85 .map_err(RawCodecError::Decompression)?;
86 let text = String::from_utf8(bytes)
87 .map_err(|error| RawCodecError::InvalidUtf8(error.utf8_error()))?;
88 Ok(Cow::Owned(text))
89 }
90 SqlValue::Null => Err(RawCodecError::UnsupportedValue("Null")),
91 SqlValue::Bool(_) => Err(RawCodecError::UnsupportedValue("Bool")),
92 SqlValue::Integer(_) => Err(RawCodecError::UnsupportedValue("Integer")),
93 SqlValue::Float(_) => Err(RawCodecError::UnsupportedValue("Float")),
94 SqlValue::Json(_) => Err(RawCodecError::UnsupportedValue("Json")),
95 SqlValue::Uuid(_) => Err(RawCodecError::UnsupportedValue("Uuid")),
96 SqlValue::Timestamp(_) => Err(RawCodecError::UnsupportedValue("Timestamp")),
97 }
98}