serializer.rs
2.1 kB · rust · 61 lines
1use super::models::dtype_for;2use mrlycore::errors::{value_error, MrlyError, Result};3use mrlycore::tensor::Tensor;4use mrlycore::Json;5use serde::Deserialize;67/// Parses JSON text into a value tree, or a parse error.8pub fn parse(text: &str) -> Result<Json> {9 mrlycore::json::parse(text)10}1112/// Returns the types field of the data, or an error when it is missing.13pub fn types_field(data: &Json) -> Result<&Json> {14 data.get("types")15 .ok_or_else(|| MrlyError::Value("missing types.".to_string()))16}1718/// Reads a nested JSON array into rows of bytes.19pub fn byte_grid(value: &Json) -> Result<Vec<Vec<u8>>> {20 Ok(Vec::deserialize(value)?)21}2223/// Reads a triply nested JSON array into layers of byte rows.24pub fn byte_cube(value: &Json) -> Result<Vec<Vec<Vec<u8>>>> {25 Ok(Vec::deserialize(value)?)26}2728/// Reads a nested JSON array of counts into one flat run; a count must fit in thirty-two bits.29pub fn count_grid(value: &Json) -> Result<Vec<i64>> {30 let rows: Vec<Vec<u32>> = Vec::deserialize(value)?;31 Ok(rows.concat().into_iter().map(i64::from).collect())32}3334/// Reads a triply nested JSON array of counts into one flat run; a count must fit in thirty-two bits.35pub fn count_cube(value: &Json) -> Result<Vec<i64>> {36 let planes: Vec<Vec<Vec<u32>>> = Vec::deserialize(value)?;37 Ok(planes38 .concat()39 .concat()40 .into_iter()41 .map(i64::from)42 .collect())43}4445/// Packs a flat run of counts into a tensor of the shape, at the narrowest dtype that holds them.46pub fn tag_layer(counts: &[i64], shape: Vec<usize>) -> Result<Tensor> {47 if counts.len() != shape.iter().product::<usize>() {48 return value_error("tags must match the cell's shape.");49 }50 let peak = counts.iter().copied().max().unwrap_or(0);51 let mut tags = Tensor::typed(shape, dtype_for(peak));52 for (flat, &value) in counts.iter().enumerate() {53 tags.put(flat, value);54 }55 Ok(tags)56}5758/// Reads a nested JSON array into rows of four-channel colors.59pub fn color_grid(value: &Json) -> Result<Vec<Vec<[u8; 4]>>> {60 Ok(Vec::deserialize(value)?)61}