use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::limits::JOB_BYTES;
use crate::{Error, Result};
pub(crate) const MAX_VALUE: usize = JOB_BYTES.bound as usize;
const INLINE_VALUE: usize = 512;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Kept {
Inline(Vec<u8>),
Spilled(Vec<u8>),
}
impl Kept {
pub(crate) fn of(encoded: Vec<u8>) -> Kept {
if encoded.len() > INLINE_VALUE { Kept::Spilled(encoded) } else { Kept::Inline(encoded) }
}
pub(crate) fn inline(&self) -> Option<&[u8]> {
match self {
Kept::Inline(bytes) => Some(bytes),
Kept::Spilled(_) => None,
}
}
pub(crate) fn bytes(&self) -> &[u8] {
match self {
Kept::Inline(bytes) | Kept::Spilled(bytes) => bytes,
}
}
pub(crate) fn len(&self) -> usize {
match self {
Kept::Inline(bytes) | Kept::Spilled(bytes) => bytes.len(),
}
}
}
pub(crate) fn encode<V: Serialize>(value: &V) -> Result<Vec<u8>> {
let encoded =
serde_json::to_vec(value).map_err(|error| Error::invalid("a value JSON cannot write").with_source(error))?;
check_size(encoded.len(), "a value")?;
Ok(encoded)
}
pub(crate) fn decode<V: DeserializeOwned>(encoded: &[u8]) -> Result<V> {
serde_json::from_slice(encoded).map_err(|error| {
Error::invalid(format!("a value that no longer reads as {}", std::any::type_name::<V>())).with_source(error)
})
}
pub(crate) fn check_size(bytes: usize, what: &str) -> Result<()> {
if bytes > MAX_VALUE {
return Err(JOB_BYTES.refuse(bytes as u64, format!("{what} of {bytes} bytes, past {MAX_VALUE}")));
}
Ok(())
}