runestick/modules/
result.rs

1//! The `std::result` module.
2
3use crate::{ContextError, Function, Module, Value, VmError};
4
5/// Construct the `std::result` module.
6pub fn module() -> Result<Module, ContextError> {
7    let mut module = Module::with_crate_item("std", &["result"]);
8    // Sorted for ease of finding
9    module.result(&["Result"])?;
10    module.inst_fn("ok", ok)?;
11    module.inst_fn("is_ok", is_ok)?;
12    module.inst_fn("is_err", is_err)?;
13    module.inst_fn("unwrap", unwrap_impl)?;
14    module.inst_fn("expect", expect_impl)?;
15    module.inst_fn("and_then", and_then_impl)?;
16    module.inst_fn("map", map_impl)?;
17    Ok(module)
18}
19
20fn ok(result: &Result<Value, Value>) -> Option<Value> {
21    result.as_ref().ok().cloned()
22}
23
24fn is_ok(result: &Result<Value, Value>) -> bool {
25    result.is_ok()
26}
27
28fn is_err(result: &Result<Value, Value>) -> bool {
29    result.is_err()
30}
31
32fn unwrap_impl(result: Result<Value, Value>) -> Result<Value, VmError> {
33    result.map_err(|err| {
34        VmError::panic(format!(
35            "called `Result::unwrap()` on an `Err` value: {:?}",
36            err
37        ))
38    })
39}
40
41fn expect_impl(result: Result<Value, Value>, message: &str) -> Result<Value, VmError> {
42    result.map_err(|err| VmError::panic(format!("{}: {:?}", message, err)))
43}
44
45fn and_then_impl(
46    this: &Result<Value, Value>,
47    then: Function,
48) -> Result<Result<Value, Value>, VmError> {
49    match this {
50        // No need to clone v, passing the same reference forward
51        Ok(v) => Ok(then.call::<_, _>((v,))?),
52        Err(e) => Ok(Err(e.clone())),
53    }
54}
55
56fn map_impl(this: &Result<Value, Value>, then: Function) -> Result<Result<Value, Value>, VmError> {
57    match this {
58        // No need to clone v, passing the same reference forward
59        Ok(v) => Ok(Ok(then.call::<_, _>((v,))?)),
60        Err(e) => Ok(Err(e.clone())),
61    }
62}