terset 0.9.0

A compact text format for JSON records in LLM prompts. Same data, fewer input tokens.
Documentation
use crate::codec::{decode, encode_with, EncodeOptions};
use crate::error::Error;
use crate::value::{JsonObject, JsonString, JsonValue};

impl TryFrom<&serde_json::Value> for JsonValue {
    type Error = Error;

    fn try_from(value: &serde_json::Value) -> Result<Self, Self::Error> {
        match value {
            serde_json::Value::Null => Ok(JsonValue::Null),
            serde_json::Value::Bool(b) => Ok(JsonValue::Bool(*b)),
            serde_json::Value::Number(n) => {
                let f = n.as_f64().ok_or_else(|| {
                    Error::invalid_input("Numbers must be finite binary64 values.")
                })?;
                if !f.is_finite() || (f == 0.0 && f.is_sign_negative()) {
                    return Err(Error::invalid_input(
                        "Numbers must be finite and must not be negative zero.",
                    ));
                }
                Ok(JsonValue::Number(f))
            }
            serde_json::Value::String(s) => Ok(JsonValue::String(JsonString::from(s.as_str()))),
            serde_json::Value::Array(arr) => {
                let mut out = Vec::with_capacity(arr.len());
                for item in arr {
                    out.push(JsonValue::try_from(item)?);
                }
                Ok(JsonValue::Array(out))
            }
            serde_json::Value::Object(map) => {
                let mut obj = JsonObject::with_capacity(map.len());
                for (k, v) in map {
                    obj.push_unique(JsonString::from(k.as_str()), JsonValue::try_from(v)?);
                }
                Ok(JsonValue::Object(obj))
            }
        }
    }
}

impl TryFrom<JsonValue> for serde_json::Value {
    type Error = Error;

    fn try_from(value: JsonValue) -> Result<Self, Self::Error> {
        match value {
            JsonValue::Null => Ok(serde_json::Value::Null),
            JsonValue::Bool(b) => Ok(serde_json::Value::Bool(b)),
            JsonValue::Number(n) => {
                if n.fract() == 0.0 && n.abs() <= 9_007_199_254_740_991.0 {
                    Ok(serde_json::Value::Number(serde_json::Number::from(
                        n as i64,
                    )))
                } else {
                    let num = serde_json::Number::from_f64(n)
                        .ok_or_else(|| Error::invalid_input("Numbers must be finite."))?;
                    Ok(serde_json::Value::Number(num))
                }
            }
            JsonValue::String(s) => {
                let st = s.as_str().ok_or_else(|| {
                    Error::invalid_input(
                        "serde_json::Value cannot represent strings with lone UTF-16 surrogates.",
                    )
                })?;
                Ok(serde_json::Value::String(st.to_owned()))
            }
            JsonValue::Array(arr) => {
                let mut out = Vec::with_capacity(arr.len());
                for item in arr {
                    out.push(serde_json::Value::try_from(item)?);
                }
                Ok(serde_json::Value::Array(out))
            }
            JsonValue::Object(obj) => {
                let mut map = serde_json::Map::with_capacity(obj.len());
                for (k, v) in obj {
                    let ks = k.as_str().ok_or_else(|| {
                        Error::invalid_input(
                            "serde_json::Value cannot represent object keys with lone UTF-16 surrogates.",
                        )
                    })?;
                    map.insert(ks.to_owned(), serde_json::Value::try_from(v)?);
                }
                Ok(serde_json::Value::Object(map))
            }
        }
    }
}

/// Encodes a [`serde_json::Value`] as Terset text using the given [`EncodeOptions`].
pub fn encode_serde(value: &serde_json::Value, options: EncodeOptions) -> Result<String, Error> {
    let jv = JsonValue::try_from(value)?;
    encode_with(&jv, options)
}

/// Decodes canonical Terset text into a [`serde_json::Value`].
pub fn decode_serde(text: &str) -> Result<serde_json::Value, Error> {
    let jv = decode(text)?;
    serde_json::Value::try_from(jv)
}

/// Serializes any [`serde::Serialize`] value as Terset text using the given [`EncodeOptions`].
pub fn to_string_with<T: serde::Serialize>(
    value: &T,
    options: EncodeOptions,
) -> Result<String, Error> {
    let sv = serde_json::to_value(value)
        .map_err(|e| Error::invalid_input(format!("Serialization error: {}", e)))?;
    encode_serde(&sv, options)
}

/// Serializes any [`serde::Serialize`] value as Terset text using the default format (`1.6`).
pub fn to_string<T: serde::Serialize>(value: &T) -> Result<String, Error> {
    to_string_with(value, EncodeOptions::default())
}

/// Deserializes canonical Terset text into any [`serde::de::DeserializeOwned`] type.
pub fn from_str<T: serde::de::DeserializeOwned>(text: &str) -> Result<T, Error> {
    let sv = decode_serde(text)?;
    serde_json::from_value(sv).map_err(|e| Error::syntax(format!("Deserialization error: {}", e)))
}