Skip to content

Instantly share code, notes, and snippets.

@segfo
Last active June 26, 2019 15:54
Show Gist options
  • Save segfo/66e5f8919909fd405cef700013f915e1 to your computer and use it in GitHub Desktop.
Save segfo/66e5f8919909fd405cef700013f915e1 to your computer and use it in GitHub Desktop.
汎用デシリアライザ
use std::marker::PhantomData;
use serde_derive::{Serialize,Deserialize};
use serde::de::DeserializeOwned;
struct TomlConfigDeserializer<T>{
_t:PhantomData<T>
}
use std::fs::OpenOptions;
use std::io::{BufReader,prelude::*};
impl<T> TomlConfigDeserializer<T> where T:DeserializeOwned{
fn from_file(filepath:&str)->Result<T,Box<std::error::Error>>{
let f = OpenOptions::new()
.read(true).write(false).create_new(false)
.open(filepath)?;
TomlConfigDeserializer::from_reader(f)
}
fn from_reader<R>(rdr:R)->Result<T,Box<std::error::Error>> where R:Read{
let mut br = BufReader::new(rdr);
let mut buf = String::new();
br.read_to_string(&mut buf);
let t = toml::from_str(&buf)?;
Ok(t)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment