1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//! Configuration for Drone, an Embedded Operating System.

#![warn(missing_docs, unsafe_op_in_unsafe_fn)]
#![warn(clippy::pedantic)]
#![allow(clippy::missing_errors_doc, clippy::module_name_repetitions, clippy::must_use_candidate)]

mod config;
mod format;

pub use crate::{config::*, format::*};

use anyhow::{anyhow, bail, Result};
use std::{env, fs::File, io::prelude::*, path::Path};

/// The name of the Drone configuration file.
pub const CONFIG_NAME: &str = "Drone.toml";

impl Config {
    /// Reads the configuration file from the current working directory and
    /// returns a parsed object.
    pub fn read_from_current_dir() -> Result<Self> {
        Self::read(Path::new("."))
    }

    /// Reads the configuration file from the `CARGO_MANIFEST_DIR` environment
    /// variable path and returns a parsed object.
    ///
    /// If `CARGO_MANIFEST_DIR_OVERRIDE` environment variable is set, the
    /// function will parse its value directly.
    pub fn read_from_cargo_manifest_dir() -> Result<Self> {
        if let Ok(string) = env::var("CARGO_MANIFEST_DIR_OVERRIDE") {
            Self::parse(&string)
        } else {
            Self::read(
                env::var_os("CARGO_MANIFEST_DIR")
                    .ok_or_else(|| anyhow!("`CARGO_MANIFEST_DIR` is not set"))?
                    .as_ref(),
            )
        }
    }

    /// Reads the configuration file at `crate_root` and returns a parsed
    /// object.
    pub fn read(crate_root: &Path) -> Result<Self> {
        let crate_root = crate_root.canonicalize()?;
        let path = crate_root.join(CONFIG_NAME);
        if !path.exists() {
            bail!("`{}` not exists in `{}", CONFIG_NAME, crate_root.display());
        }
        let mut buffer = String::new();
        let mut file = File::open(&path)?;
        file.read_to_string(&mut buffer)?;
        Self::parse(&buffer)
    }

    /// Parses config from the `string`.
    pub fn parse(string: &str) -> Result<Self> {
        let config = toml::from_str::<Self>(&string)?;
        config.check_heaps()?;
        Ok(config)
    }

    fn check_heaps(&self) -> Result<()> {
        let Self { heap: Heap { main, extra }, .. } = self;
        main.check_pools()?;
        for heap in extra.values() {
            heap.block.check_pools()?;
        }
        Ok(())
    }
}

impl HeapBlock {
    fn check_pools(&self) -> Result<()> {
        let Self { size, pools } = self;
        let used: u32 = pools.iter().map(|pool| pool.block * pool.capacity).sum();
        if used != *size {
            bail!("{}: `heap.pools` adds up to {}, but `heap.size = {}", CONFIG_NAME, used, size);
        }
        Ok(())
    }
}