serializer.rs

2.6 kB · rust · 93 lines

1use super::models::dtype_for;2use crate::core::error::{value_error, Error, Result};3use crate::core::tensor::Tensor;4use crate::core::Json;5use serde::Deserialize;67/// Parses JSON text into a value tree.8///9/// # Errors10///11/// Errors when the text is not JSON.12pub fn parse(text: &str) -> Result<Json> {13    crate::core::error::parse(text)14}1516/// Returns the types field of the data.17///18/// # Errors19///20/// Errors when the types field is missing.21pub fn types_field(data: &Json) -> Result<&Json> {22    data.get("types")23        .ok_or_else(|| Error::Value("missing types.".to_string()))24}2526/// Reads a nested JSON array into rows of bytes.27///28/// # Errors29///30/// Errors when the value is not a grid of bytes.31pub fn byte_grid(value: &Json) -> Result<Vec<Vec<u8>>> {32    Ok(Vec::deserialize(value)?)33}3435/// Reads a triply nested JSON array into layers of byte rows.36///37/// # Errors38///39/// Errors when the value is not a cube of bytes.40pub fn byte_cube(value: &Json) -> Result<Vec<Vec<Vec<u8>>>> {41    Ok(Vec::deserialize(value)?)42}4344/// Reads a nested JSON array of counts into one flat run; a count must fit in thirty-two bits.45///46/// # Errors47///48/// Errors when the value is not a grid of counts.49pub fn count_grid(value: &Json) -> Result<Vec<i64>> {50    let rows: Vec<Vec<u32>> = Vec::deserialize(value)?;51    Ok(rows.concat().into_iter().map(i64::from).collect())52}5354/// Reads a triply nested JSON array of counts into one flat run; a count must fit in thirty-two bits.55///56/// # Errors57///58/// Errors when the value is not a cube of counts.59pub fn count_cube(value: &Json) -> Result<Vec<i64>> {60    let planes: Vec<Vec<Vec<u32>>> = Vec::deserialize(value)?;61    Ok(planes62        .concat()63        .concat()64        .into_iter()65        .map(i64::from)66        .collect())67}6869/// Packs a flat run of counts into a tensor of the shape, at the narrowest dtype that holds them.70///71/// # Errors72///73/// Errors when the counts do not match the shape.74pub fn tag_layer(counts: &[i64], shape: Vec<usize>) -> Result<Tensor> {75    if counts.len() != shape.iter().product::<usize>() {76        return value_error("tags must match the cell's shape.");77    }78    let peak = counts.iter().copied().max().unwrap_or(0);79    let mut tags = Tensor::typed(shape, dtype_for(peak));80    for (flat, &value) in counts.iter().enumerate() {81        tags.put(flat, value);82    }83    Ok(tags)84}8586/// Reads a nested JSON array into rows of four-channel colors.87///88/// # Errors89///90/// Errors when the value is not a grid of RGBA quadruples.91pub fn color_grid(value: &Json) -> Result<Vec<Vec<[u8; 4]>>> {92    Ok(Vec::deserialize(value)?)93}