use crate::decode;
use crate::encode;
use crate::error::TsonError;
use alloc::{string::String, vec, vec::Vec};
#[allow(unused_imports)]
pub use crate::structure::{
TsonChunk, TsonData, TsonDefinition, TsonDocument, TsonHeader, TsonType,
};
pub use crate::stream::TsonStreamReader;
#[cfg(feature = "json")]
#[allow(dead_code)]
pub fn emit(data: &TsonData) -> Result<Vec<u8>, TsonError> {
let chunk = TsonChunk {
definition_index: 0,
data: data.clone(),
};
let doc = crate::compile::compile_from_data(&[chunk])?;
encode::encode_document(&doc)
}
#[allow(dead_code)]
pub fn emit_value(data: &TsonData) -> Result<Vec<u8>, TsonError> {
encode::encode_value(data)
}
#[allow(dead_code)]
pub fn emit_with_context(
data: &TsonData,
defs: &[TsonDefinition],
dict: &[String],
) -> Result<Vec<u8>, TsonError> {
let def_index = def_index_for_value(data);
let doc = TsonDocument {
header: TsonHeader::new(1, TsonHeader::SIZE as u32, 0, 0),
definitions: defs.to_vec(),
dict: dict.to_vec(),
data: vec![TsonChunk {
definition_index: def_index,
data: data.clone(),
}],
};
encode::encode_document(&doc)
}
fn def_index_for_value(data: &TsonData) -> u16 {
match data {
TsonData::Null => 0,
TsonData::Bool(_) => 1,
TsonData::Int(_) => 2,
TsonData::UInt(_) => 3,
TsonData::Float(_) => 4,
TsonData::String(_) | TsonData::StrRef(_) => 5,
TsonData::Array(def, _, _) => *def,
TsonData::Object(def, _) => *def,
}
}
pub fn to_bytes(doc: &TsonDocument) -> Result<Vec<u8>, TsonError> {
encode::encode_document(doc)
}
#[allow(dead_code)]
pub fn from_bytes(bytes: &[u8]) -> Result<TsonDocument, TsonError> {
decode::decode_document(bytes)
}
#[allow(dead_code)]
pub fn decode_definitions(bytes: &[u8]) -> Result<Vec<TsonDefinition>, TsonError> {
decode::decode_definitions(bytes)
}
#[cfg(feature = "json")]
#[allow(dead_code)]
pub fn compile_json(json_text: &str) -> Result<TsonDocument, TsonError> {
crate::compile::compile_json_str(json_text)
}
#[cfg(feature = "json")]
#[allow(dead_code)]
pub fn compile_value(value: &serde_json::Value) -> Result<TsonDocument, TsonError> {
crate::compile::compile_json(value)
}
#[cfg(feature = "json")]
#[allow(dead_code)]
pub fn decompile_to_value(doc: &TsonDocument) -> Result<serde_json::Value, TsonError> {
crate::decompile::decompile_document(doc)
}
#[cfg(feature = "json")]
pub fn compile_json_file(file: std::fs::File) -> Result<TsonDocument, TsonError> {
use std::io::Read;
let mut reader = std::io::BufReader::new(file);
let mut text = String::new();
reader
.read_to_string(&mut text)
.map_err(TsonError::IoError)?;
crate::compile::compile_json_str(&text)
}
#[cfg(feature = "json")]
pub fn decompile_tson_file(file: std::fs::File) -> Result<serde_json::Value, TsonError> {
use std::io::Read;
let mut reader = std::io::BufReader::new(file);
let mut buf = Vec::new();
reader.read_to_end(&mut buf).map_err(TsonError::IoError)?;
let doc = decode::decode_document(&buf)?;
crate::decompile::decompile_document(&doc)
}