forma_sif 0.1.0

SIF serialization and deserialization for forma_core.
Documentation
//! SIF serialization and deserialization for the Forma framework.
//!
//! # Quick start
//!
//! ```
//! use forma_sif::{from_str, to_string};
//! use forma_derive::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize, Debug, PartialEq)]
//! struct Row {
//!     id: u64,
//!     name: String,
//!     active: bool,
//! }
//!
//! // Serialize
//! let rows = vec![
//!     Row { id: 1, name: "alice".into(), active: true },
//!     Row { id: 2, name: "bob".into(), active: false },
//! ];
//! let sif = to_string(&rows).unwrap();
//! assert!(sif.contains("#schema"));
//!
//! // Deserialize
//! let back: Vec<Row> = from_str(&sif).unwrap();
//! assert_eq!(back, rows);
//! ```

pub mod de;
pub mod error;
pub mod ser;

pub use error::Error;

use forma_core::de::{Deserialize, DeserializeOwned};
use forma_core::ser::Serialize;

/// Deserialize a sequence of records from a SIF string.
///
/// This function parses the SIF text and deserializes the result in one step.
/// The deserialized type must be `DeserializeOwned` (no borrowed data) since
/// the parsed document is an intermediate owned value.
pub fn from_str<T: DeserializeOwned>(s: &str) -> Result<T, Error> {
    let doc = sif::parse(s)?;
    from_document(&doc)
}

/// Deserialize from a pre-parsed SIF document.
///
/// Use this when you already have a parsed `Document` and want to avoid
/// re-parsing. The deserialized type may borrow from the document.
pub fn from_document<'de, T: Deserialize<'de>>(doc: &'de sif::Document) -> Result<T, Error> {
    let mut de = de::Deserializer::new(doc);
    T::deserialize(&mut de)
}

/// Serialize a value to a SIF string.
pub fn to_string<T: Serialize>(value: &T) -> Result<String, Error> {
    ser::to_string(value)
}

/// Serialize a value as SIF into a writer.
pub fn to_writer<W: std::io::Write, T: Serialize>(writer: W, value: &T) -> Result<(), Error> {
    ser::to_writer(writer, value)
}