frontmatter/src/frontmatter.rs

115 lines
2.9 KiB
Rust

use serde_json::{Map,Value};
use serde::{Serialize, Deserialize};
use std::convert::Into;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct GenericFrontmatter {
map: Map<String,Value>,
}
impl Into<serde_json::Value> for GenericFrontmatter {
fn into(self) -> serde_json::Value {
self.map.into()
}
}
impl GenericFrontmatter {
pub fn from_yaml(text: &str) -> Result<GenericFrontmatter, DeserializationError> {
let maybe: Result<Map<String,Value>, serde_yaml::Error> = serde_yaml::from_str(text);
maybe.map(|f| f.into())
.map_err(|e| e.into())
}
pub fn from_toml(text: &str) -> Result<GenericFrontmatter, DeserializationError> {
let maybe: Result<Map<String,Value>, toml::de::Error> = toml::from_str(text);
maybe.map(|f| f.into())
.map_err(|e| e.into())
}
}
impl From<Map<String,Value>> for GenericFrontmatter {
fn from(m: Map<String,Value>) -> GenericFrontmatter {
GenericFrontmatter { map: m }
}
}
#[derive(Debug)]
pub enum Error {
Deserialization(DeserializationError),
//Specialization(serde_json::Error),
Serialization(SerializationError)
}
impl Into<Error> for SerializationError {
fn into(self) -> Error {
Error::Serialization(self)
}
}
impl Into<Error> for DeserializationError {
fn into(self) -> Error {
Error::Deserialization(self)
}
}
#[derive(Debug)]
pub enum DeserializationError {
TOML(toml::de::Error),
YAML(serde_yaml::Error),
JSON(serde_json::Error)
}
impl From<serde_yaml::Error> for DeserializationError {
fn from(e: serde_yaml::Error) -> Self {
DeserializationError::YAML(e)
}
}
impl From<toml::de::Error> for DeserializationError {
fn from(e: toml::de::Error) -> Self {
DeserializationError::TOML(e)
}
}
impl From<serde_json::Error> for DeserializationError {
fn from(e: serde_json::Error) -> Self {
DeserializationError::JSON(e)
}
}
#[derive(Debug)]
pub enum SerializationError {
TOML(toml::ser::Error),
YAML(serde_yaml::Error),
JSON(serde_json::Error)
}
impl From<serde_yaml::Error> for SerializationError {
fn from (e: serde_yaml::Error) -> Self {
SerializationError::YAML(e)
}
}
impl From<toml::ser::Error> for SerializationError {
fn from(e: toml::ser::Error) -> Self {
SerializationError::TOML(e)
}
}
impl From<serde_json::Error> for SerializationError {
fn from(e: serde_json:: Error) -> Self {
SerializationError::JSON(e)
}
}
/* For future tests
fn main() {
let body = "test: lol\ntest2: lol\nextra:\n extra_key: value";
let body2 = "test = \"lol\"\n[extra]\nextra_key = \"value\"";
let body3 = "test: lol\nextra:\n extra_key: value\ntest2: lol\ntest3: lol2";
let frontmatter = GenericFrontmatter::from_yaml(&body).expect("FAIL");
let special: PageFrontmatter = serde_json::from_value(frontmatter.into()).expect("FAIL2");
println!("{:?}", special);
}*/