#![warn(missing_docs)]
#![cfg_attr(not(doctest), doc = include_str!("../README.md"))]
#![cfg_attr(doc_cfg, feature(doc_cfg))]
#![cfg_attr(not(feature = "use-std"), no_std)]
use serde::{Deserialize, Serialize};
pub mod accumulator;
#[cfg(feature = "codec")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "codec")))]
pub mod codec;
#[cfg(not(feature = "use-std"))]
extern crate core as std;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
#[cfg_attr(feature = "use-std", derive(thiserror::Error))]
#[cfg_attr(feature = "use-defmt", derive(defmt::Format))]
pub enum Error {
#[cfg(feature = "codec")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "codec")))]
#[error("{0}")]
Io(#[from] std::io::Error),
#[cfg_attr(feature = "use-std", error("JSON deserialization error"))]
DeserializeJson,
#[cfg_attr(feature = "use-std", error("JSON serialization error"))]
SerializeJson,
#[cfg_attr(feature = "use-std", error("newline in JSON data"))]
NewlineInData,
}
pub fn from_bytes<'a, T>(s: &'a mut [u8]) -> Result<T>
where
T: Deserialize<'a>,
{
let (t, used) = serde_json_core::from_slice(s).map_err(|_| Error::DeserializeJson)?;
if used == s.len() {
Ok(t)
} else {
Err(Error::DeserializeJson)
}
}
pub fn to_slice<'a, 'b, T>(value: &'b T, buf: &'a mut [u8]) -> Result<&'a mut [u8]>
where
T: Serialize + ?Sized,
{
let nbytes = serde_json_core::to_slice(&value, buf).map_err(|_| Error::SerializeJson)?;
let encoded = &mut buf[..nbytes];
if encoded.iter().position(|&i| i == b'\n').is_some() {
return Err(Error::NewlineInData);
}
Ok(encoded)
}
pub fn to_slice_newline<'a, 'b, T>(value: &'b T, buf: &'a mut [u8]) -> Result<&'a mut [u8]>
where
T: Serialize + ?Sized,
{
let encoded = to_slice(value, buf)?;
let nbytes = encoded.len();
let (used, _drop) = buf.split_at_mut(nbytes + 1);
used[nbytes] = b'\n';
Ok(used)
}