1
use super::*;
2
use wasmtime::{FieldType, Mutability, StorageType, StructRefPre, StructType, ValType};
3

            
4
6
fn ratio_anyref(store: &mut Store<()>, numer: i64, denom: i64) -> Rooted<AnyRef> {
5
6
    let field = FieldType::new(Mutability::Const, StorageType::ValType(ValType::I64));
6
6
    let ty = StructType::new(store.engine(), [field.clone(), field]).unwrap();
7
6
    let pre = StructRefPre::new(&mut *store, ty);
8
6
    let ratio = StructRef::new(&mut *store, &pre, &[Val::I64(numer), Val::I64(denom)]).unwrap();
9
6
    ratio.to_anyref()
10
6
}
11

            
12
6
fn decode(numer: i64, denom: i64) -> wasmtime::Result<EvalValue> {
13
6
    let engine = build_engine(EngineOpts::baseline()).unwrap();
14
6
    let mut store: Store<()> = Store::new(&engine, ());
15
6
    let t = AnyRef::from_i31(&mut store, wasmtime::I31::wrapping_i32(0));
16
6
    let handles = TypeHandles {
17
6
        t,
18
6
        ratio: wasmtime::HeapType::Any,
19
6
        commodity: wasmtime::HeapType::Any,
20
6
        pair: wasmtime::HeapType::Any,
21
6
        string: wasmtime::HeapType::Any,
22
6
        symbol: wasmtime::HeapType::Any,
23
6
        structure: wasmtime::HeapType::Any,
24
6
        entities: Vec::new(),
25
6
    };
26
6
    let ratio = ratio_anyref(&mut store, numer, denom);
27
6
    decode_eval_result(
28
6
        &mut store,
29
6
        Some(ratio),
30
6
        Some(nomiscript::WasmType::Ratio),
31
6
        &handles,
32
6
    )
33
6
}
34

            
35
#[test]
36
1
fn a_guest_ratio_decodes() {
37
1
    assert_eq!(
38
1
        decode(1, 2).unwrap(),
39
1
        EvalValue::Ratio { numer: 1, denom: 2 }
40
    );
41
1
}
42

            
43
#[test]
44
1
fn a_guest_ratio_with_a_non_positive_denominator_is_a_decode_error() {
45
1
    for (numer, denom) in [(1, 0), (1, i64::MIN), (i64::MIN, -1)] {
46
3
        let err = decode(numer, denom).unwrap_err();
47
3
        assert!(
48
3
            err.to_string().contains("non-positive denominator"),
49
            "{err}"
50
        );
51
    }
52
1
}
53

            
54
#[test]
55
1
fn a_host_result_prints_with_its_kind() {
56
1
    let whole = nomiscript::Value::from(decode(2, 1).unwrap());
57
1
    assert_eq!(nomiscript::format_value(&whole), "2/1");
58
1
    let fraction = nomiscript::Value::from(decode(1, 4).unwrap());
59
1
    assert_eq!(nomiscript::format_value(&fraction), "1/4");
60
1
    let index = nomiscript::Value::from(EvalValue::I32(2));
61
1
    assert_eq!(nomiscript::format_value(&index), "2");
62
1
}