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
//! Contains the Interpretable trait, which provides a common interface for running a Brainfuck
//! program.

use std::io::{Cursor, Read, Write, stdin, stdout};

use common::BfResult;
use state::State;

pub use rle::RleCompilable;
pub use peephole::PeepholeCompilable;
pub use bytecode::BytecodeCompilable;
#[cfg(feature = "jit")]
pub use jit::JitCompilable;
#[cfg(feature = "llvm")]
pub use llvm::LlvmCompilable;

/// Program forms that can be interpreted.
pub trait Interpretable {
    /// Interprets a program against the given state.
    fn interpret_state<R: Read, W: Write>(&self, state: State,
                                          input: R, output: W)
        -> BfResult<()>;

    /// Interprets a program. If the given `size` is `None`, the default memory size.
    fn interpret<R: Read, W: Write>(
        &self, size: Option<usize>, input: R, output: W) -> BfResult<()>
    {
        let state = size.map(State::with_capacity).unwrap_or_else(State::new);
        self.interpret_state(state, input, output)
    }

    /// Interprets a program using stdin and stdout for input and output.
    fn interpret_stdin(&self, size: Option<usize>) -> BfResult<()> {
        self.interpret(size, stdin(), stdout())
    }

    /// Interprets a program from memory, returning a vector of its output.
    fn interpret_memory(&self, size: Option<usize>, input: &[u8]) -> BfResult<Vec<u8>> {
        let input = Cursor::new(input);
        let mut output = Cursor::new(Vec::new());

        self.interpret(size, input, &mut output)?;
        Ok(output.into_inner())
    }
}

/// For converting smaller numeric types into `usize`.
pub trait IntoUsize {
    fn into_usize(self) -> usize;
}

impl IntoUsize for usize {
    fn into_usize(self) -> usize { self }
}

impl IntoUsize for u64 {
    fn into_usize(self) -> usize { self as usize }
}

impl IntoUsize for u32 {
    fn into_usize(self) -> usize { self as usize }
}

impl IntoUsize for u16 {
    fn into_usize(self) -> usize { self as usize }
}

impl IntoUsize for u8 {
    fn into_usize(self) -> usize { self as usize }
}