Implement string functions with to_string/to_debug.

This commit is contained in:
Stephen Chung
2021-04-02 19:26:55 +08:00
parent 1866331e7b
commit a738f750f9
10 changed files with 97 additions and 44 deletions

View File

@@ -222,6 +222,40 @@ fn test_string_substring() -> Result<(), Box<EvalAltResult>> {
Ok(())
}
#[test]
fn test_string_format() -> Result<(), Box<EvalAltResult>> {
#[derive(Debug, Clone)]
struct TestStruct {
field: i64,
}
let mut engine = Engine::new();
engine
.register_type_with_name::<TestStruct>("TestStruct")
.register_fn("new_ts", || TestStruct { field: 42 })
.register_fn("to_string", |ts: TestStruct| format!("TS={}", ts.field))
.register_fn("to_debug", |ts: TestStruct| {
format!("!!!TS={}!!!", ts.field)
});
assert_eq!(
engine.eval::<String>(r#"let x = new_ts(); "foo" + x"#)?,
"fooTS=42"
);
assert_eq!(
engine.eval::<String>(r#"let x = new_ts(); x + "foo""#)?,
"TS=42foo"
);
#[cfg(not(feature = "no_index"))]
assert_eq!(
engine.eval::<String>(r#"let x = [new_ts()]; "foo" + x"#)?,
"foo[!!!TS=42!!!]"
);
Ok(())
}
#[test]
fn test_string_fn() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();