dfw/
util.rs

1// Copyright Pit Kleyersburg <pitkley@googlemail.com>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified or distributed
8// except according to those terms.
9
10//! Utilities module
11
12use crate::errors::*;
13
14use glob::glob;
15use lazy_static::lazy_static;
16use serde::de::DeserializeOwned;
17use std::{
18    fs::File,
19    future::Future,
20    io::{prelude::*, BufReader},
21};
22use tokio::runtime::Runtime;
23
24lazy_static! {
25    static ref RUNTIME: Runtime = Runtime::new().unwrap();
26}
27
28/// Load single TOML-file from path and deserialize it into type `T`.
29pub fn load_file<T>(file: &str) -> Result<T>
30where
31    T: DeserializeOwned,
32{
33    let mut contents = String::new();
34    let mut file = BufReader::new(File::open(file)?);
35    file.read_to_string(&mut contents)?;
36    Ok(toml::from_str(&contents)?)
37}
38
39/// Load all TOML-files from a path, concatenate their contents and deserialize the result into
40/// type `T`.
41pub fn load_path<T>(path: &str) -> Result<T>
42where
43    T: DeserializeOwned,
44{
45    let mut contents = String::new();
46    for entry in glob(&format!("{}/*.toml", path)).expect("Failed to read glob pattern") {
47        match entry {
48            Ok(path) => {
49                let mut file = BufReader::new(File::open(path)?);
50                file.read_to_string(&mut contents)?;
51            }
52            Err(e) => println!("{:?}", e),
53        }
54    }
55
56    Ok(toml::from_str(&contents)?)
57}
58
59/// An extension trait for `Future` allowing synchronized execution of the future.
60pub trait FutureExt: Future
61where
62    Self: Sized,
63{
64    /// Execute future synchronously, blocking until a result can be returned.
65    fn sync(self) -> Self::Output {
66        RUNTIME.block_on(self)
67    }
68}
69
70impl<F> FutureExt for F where F: Future + Sized {}