summaryrefslogtreecommitdiffstats
path: root/src/utils.rs
blob: b966a3b7d99c811dc9943e514fe2eb64c788d108 (plain)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use Filter;

use cli::EqualizerConfFormat;
use parsing::EqualizerApoParser;

use failure::Error;
use lalrpop_util;

use std::fmt;
use std::fs::File;
use std::io;

#[derive(Fail, Debug)]
#[fail(
    display = "Could not parse using the {} format: {}",
    format,
    message
)]
struct ParseError {
    format: EqualizerConfFormat,
    message: String,
}

pub fn read_filearg_to_str(file: &str) -> Result<String, Error> {
    use std::io::Read;

    let mut buffer = String::new();
    if file == "-" {
        debug!("Reading file from the command line");
        let stdin = io::stdin();
        let mut handle = stdin.lock();
        handle.read_to_string(&mut buffer)?;
    } else {
        let mut file = File::open(file)?;
        file.read_to_string(&mut buffer)?;
    }
    Ok(buffer)
}

pub fn read_filter_from_arg(file: &str) -> Result<Filter, Error> {
    info!("Reading filter from '{}' in the EqualizerAPO format", file);
    let content = read_filearg_to_str(file)?;
    parse_filter(&content)
}

pub fn parse_filter(content: &str) -> Result<Filter, Error> {
    // TODO: lifetime issue when "throwing" parse error
    let filter = EqualizerApoParser::new()
        .parse(&content)
        .map_err(|e| convert_parse_error(EqualizerConfFormat::EqualizerAPO, &e))?;
    trace!("Parsed filter: {:?}", filter);

    Ok(filter)
}

fn convert_parse_error<L, T, E>(
    format: EqualizerConfFormat,
    error: &lalrpop_util::ParseError<L, T, E>,
) -> ParseError
where
    L: fmt::Display,
    T: fmt::Display,
    E: fmt::Display,
{
    ParseError {
        format,
        message: format!("{}", error),
    }
}

pub fn decibel_to_ratio(decibel: f64) -> f64 {
    10f64.powf(decibel / 10f64).sqrt()
}

/*
fn introspect(conn: &dbus::ConnPath<&Connection>) {
    let mut thing = conn
        .method_call_with_args(
            &"org.freedesktop.DBus.Introspectable".into(),
            &"Introspect".into(),
            |_| {},
        ).unwrap();
    thing.as_result().unwrap();

    println!("{}", thing.iter_init().read::<String>().unwrap());
}
*/

#[cfg(test)]
mod tests {

    #[test]
    fn decibel_to_ratio() {
        assert_eq!(super::decibel_to_ratio(0f64), 1f64);
        assert_eq!(super::decibel_to_ratio(20f64), 10f64);
        assert_eq!(super::decibel_to_ratio(40f64), 100f64);
        assert_eq!(super::decibel_to_ratio(60f64), 1000f64);
    }

}