add toml helpers to data.rs

master
Paul Woolcock 6 years ago
parent ce69407e38
commit 384d3d2c41
  1. 88
      src/data.rs
  2. 19
      src/errors.rs
  3. 6
      src/lib.rs

@ -16,4 +16,92 @@ pub struct Data {
pub token: Cow<'static, str>, pub token: Cow<'static, str>,
} }
#[cfg(feature = "toml")]
/// Helpers for serializing to/deserializing from toml
///
/// In order to use this module, set the "toml" feature in your Cargo.toml:
///
/// ```toml,ignore
/// [dependencies.elefren]
/// version = "0.12"
/// features = ["toml"]
/// ```
pub mod toml {
use super::Data;
use std::{
fs::{File, OpenOptions},
io::{BufWriter, Read, Write},
path::Path,
};
use Result;
use tomlcrate;
/// Attempts to deserialize a Data struct from a string
pub fn from_str(s: &str) -> Result<Data> {
Ok(tomlcrate::from_str(s)?)
}
/// Attempts to deserialize a Data struct from a slice of bytes
pub fn from_slice(s: &[u8]) -> Result<Data> {
Ok(tomlcrate::from_slice(s)?)
}
/// Attempts to deserialize a Data struct from something that implements
/// the std::io::Read trait
pub fn from_reader<R: Read>(mut r: R) -> Result<Data> {
let mut buffer = Vec::new();
r.read_to_end(&mut buffer)?;
from_slice(&buffer)
}
/// Attempts to deserialize a Data struct from a file
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Data> {
let path = path.as_ref();
let file = File::open(path)?;
Ok(from_reader(file)?)
}
/// Attempts to serialize a Data struct to a String
pub fn to_string(data: &Data) -> Result<String> {
Ok(tomlcrate::to_string_pretty(data)?)
}
/// Attempts to serialize a Data struct to a Vec of bytes
pub fn to_vec(data: &Data) -> Result<Vec<u8>> {
Ok(tomlcrate::to_vec(data)?)
}
/// Attempts to serialize a Data struct to something that implements the
/// std::io::Write trait
pub fn to_writer<W: Write>(data: &Data, writer: W) -> Result<()> {
let mut buf_writer = BufWriter::new(writer);
let vec = to_vec(data)?;
buf_writer.write(&vec)?;
Ok(())
}
/// Attempts to serialize a Data struct to a file
///
/// When opening the file, this will set the `.write(true)` and
/// `.truncate(true)` options, use the next method for more
/// fine-grained control
pub fn to_file<P: AsRef<Path>>(data: &Data, path: P) -> Result<()> {
let mut options = OpenOptions::new();
options.write(true).truncate(true);
to_file_with_options(data, path, options)?;
Ok(())
}
/// Attempts to serialize a Data struct to a file
pub fn to_file_with_options<P: AsRef<Path>>(
data: &Data,
path: P,
options: OpenOptions,
) -> Result<()> {
let path = path.as_ref();
let file = options.open(path)?;
to_writer(data, file)?;
Ok(())
}
}

@ -2,6 +2,10 @@ use std::{error, fmt, io::Error as IoError};
use json::Error as SerdeError; use json::Error as SerdeError;
use reqwest::{Error as HttpError, StatusCode}; use reqwest::{Error as HttpError, StatusCode};
#[cfg(feature = "toml")]
use tomlcrate::de::Error as TomlDeError;
#[cfg(feature = "toml")]
use tomlcrate::ser::Error as TomlSerError;
use url::ParseError as UrlError; use url::ParseError as UrlError;
/// Convience type over `std::result::Result` with `Error` as the error type. /// Convience type over `std::result::Result` with `Error` as the error type.
@ -36,6 +40,12 @@ pub enum Error {
DataMissing, DataMissing,
/// AppBuilder error /// AppBuilder error
MissingField(&'static str), MissingField(&'static str),
#[cfg(feature = "toml")]
/// Error serializing to toml
TomlSer(TomlSerError),
#[cfg(feature = "toml")]
/// Error deserializing from toml
TomlDe(TomlDeError),
} }
impl fmt::Display for Error { impl fmt::Display for Error {
@ -65,6 +75,10 @@ impl error::Error for Error {
Error::AccessTokenRequired => "AccessTokenRequired", Error::AccessTokenRequired => "AccessTokenRequired",
Error::DataMissing => "DataMissing", Error::DataMissing => "DataMissing",
Error::MissingField(_) => "MissingField", Error::MissingField(_) => "MissingField",
#[cfg(feature = "toml")]
Error::TomlSer(ref e) => e.description(),
#[cfg(feature = "toml")]
Error::TomlDe(ref e) => e.description(),
} }
} }
} }
@ -79,8 +93,9 @@ pub struct ApiError {
} }
macro_rules! from { macro_rules! from {
($($typ:ident, $variant:ident,)*) => { ($($(#[$met:meta])* $typ:ident, $variant:ident,)*) => {
$( $(
$(#[$met])*
impl From<$typ> for Error { impl From<$typ> for Error {
fn from(from: $typ) -> Self { fn from(from: $typ) -> Self {
use Error::*; use Error::*;
@ -97,4 +112,6 @@ from! {
SerdeError, Serde, SerdeError, Serde,
UrlError, Url, UrlError, Url,
ApiError, Api, ApiError, Api,
#[cfg(feature = "toml")] TomlSerError, TomlSer,
#[cfg(feature = "toml")] TomlDeError, TomlDe,
} }

@ -41,6 +41,9 @@ extern crate serde;
extern crate try_from; extern crate try_from;
extern crate url; extern crate url;
#[cfg(feature = "toml")]
extern crate toml as tomlcrate;
use std::{borrow::Cow, ops}; use std::{borrow::Cow, ops};
use reqwest::{ use reqwest::{
@ -60,7 +63,8 @@ pub use status_builder::StatusBuilder;
/// Registering your App /// Registering your App
pub mod apps; pub mod apps;
mod data; /// Working with client auth data
pub mod data;
/// Entities returned from the API /// Entities returned from the API
pub mod entities; pub mod entities;
/// Errors /// Errors

Loading…
Cancel
Save