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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
/*!
# bc (An arbitrary precision calculator language)

Use `bc` in the Rust Programming Language.

## Examples

```rust
#[macro_use] extern crate bc;

let result = bc!("2 + 6");

assert_eq!("8", result.unwrap());
```

```rust
#[macro_use] extern crate bc;

let result = bc!("2.5 + 6");

assert_eq!("8.5", result.unwrap());
```

```rust
#[macro_use] extern crate bc;

let result = bc_timeout!("99^99");

assert_eq!("369729637649726772657187905628805440595668764281741102430259972423552570455277523421410650010128232727940978889548326540119429996769494359451621570193644014418071060667659301384999779999159200499899", result.unwrap());
```

```rust
#[macro_use] extern crate bc;

let result = bc_timeout!(20, "99^99");

assert_eq!("369729637649726772657187905628805440595668764281741102430259972423552570455277523421410650010128232727940978889548326540119429996769494359451621570193644014418071060667659301384999779999159200499899", result.unwrap());
```
*/

pub extern crate subprocess;

use std::path::Path;

use subprocess::{Exec, PopenError, Redirection, ExitStatus};

#[derive(Debug)]
pub enum BCError {
    PopenError(PopenError),
    NoResult,
    Timeout,
    /// Maybe it is a syntax error.
    Error(String),
}


/// Call `bc`.
pub fn bc<P: AsRef<Path>, S: AsRef<str>>(bc_path: P, statement: S) -> Result<String, BCError> {
    let process = Exec::cmd(bc_path.as_ref().as_os_str()).arg("-l").arg("-q")
        .stdin(format!("{}\n", statement.as_ref()).as_str())
        .stdout(Redirection::Pipe)
        .stderr(Redirection::Pipe);

    let capture = process.capture().map_err(|err| BCError::PopenError(err))?;

    let stderr = capture.stderr_str();

    if stderr.is_empty() {
        let stdout = capture.stdout_str();

        if stdout.is_empty() {
            Err(BCError::NoResult)
        } else {
            Ok(handle_output(stdout))
        }
    } else {
        Err(BCError::Error(handle_output(stderr)))
    }
}


/// Call `bc` with `timeout`.
pub fn bc_timeout<PT: AsRef<Path>, P: AsRef<Path>, S: AsRef<str>>(timeout_path: PT, timeout_secs: u32, bc_path: P, statement: S) -> Result<String, BCError> {
    let process = Exec::cmd(timeout_path.as_ref().as_os_str()).arg(format!("{}s", timeout_secs)).arg(bc_path.as_ref().as_os_str()).arg("-l").arg("-q")
        .stdin(format!("{}\n", statement.as_ref()).as_str())
        .stdout(Redirection::Pipe)
        .stderr(Redirection::Pipe);

    let capture = process.capture().map_err(|err| BCError::PopenError(err))?;

    if let ExitStatus::Exited(status) = capture.exit_status {
        if status == 124 {
            return Err(BCError::Timeout);
        }
    }

    let stderr = capture.stderr_str();

    if stderr.is_empty() {
        let stdout = capture.stdout_str();

        if stdout.is_empty() {
            Err(BCError::NoResult)
        } else {
            Ok(handle_output(stdout))
        }
    } else {
        Err(BCError::Error(handle_output(stderr)))
    }
}

fn handle_output(output: String) -> String {
    let len = output.len();

    let mut output = output.into_bytes();

    let output = unsafe {
        output.set_len(len - 1);

        String::from_utf8_unchecked(output)
    };

    match output.find("\\\n") {
        Some(index) => {
            let mut s = String::from(&output[..index]);

            s.push_str(&output[(index + 2)..].replace("\\\n", ""));

            s
        }
        None => output
    }
}

/// Call `bc`.
#[macro_export]
macro_rules! bc {
    ($statement:expr) => {
        ::bc::bc("bc", $statement)
    };
    ($bc_path:expr, $statement:expr) => {
        ::bc::bc($bc_path, $statement)
    };
}

/// Call `bc` with `timeout`.
#[macro_export]
macro_rules! bc_timeout {
    ($statement:expr) => {
        ::bc::bc_timeout("timeout", 15, "bc", $statement)
    };
    ($timeout:expr, $statement:expr) => {
        ::bc::bc_timeout("timeout", $timeout, "bc", $statement)
    };
    ($timeout_path:expr, $timeout:expr, $bc_path:expr, $statement:expr) => {
        ::bc::bc_timeout($timeout_path, $timeout, $bc_path, $statement)
    };
}