Add docs and tests for switch.

This commit is contained in:
Stephen Chung
2020-11-14 09:38:16 +08:00
parent b0c66eb5e5
commit 83c7c101d1
5 changed files with 155 additions and 14 deletions

View File

@@ -1,4 +1,4 @@
use rhai::{Engine, EvalAltResult, Scope, INT};
use rhai::{Dynamic, Engine, EvalAltResult, Scope, INT};
#[test]
fn test_switch() -> Result<(), Box<EvalAltResult>> {
@@ -62,3 +62,58 @@ fn test_switch() -> Result<(), Box<EvalAltResult>> {
Ok(())
}
#[cfg(not(feature = "no_index"))]
mod test_switch_enum {
use super::*;
use rhai::Array;
#[derive(Debug, Clone)]
enum MyEnum {
Foo,
Bar(i64),
Baz(String, bool),
}
impl MyEnum {
fn get_enum_data(&mut self) -> Array {
match self {
Self::Foo => vec!["Foo".into()] as Array,
Self::Bar(num) => vec!["Bar".into(), (*num).into()] as Array,
Self::Baz(name, option) => {
vec!["Baz".into(), name.clone().into(), (*option).into()] as Array
}
}
}
}
#[test]
fn test_switch_enum() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
engine
.register_type_with_name::<MyEnum>("MyEnum")
.register_get("get_data", MyEnum::get_enum_data);
let mut scope = Scope::new();
scope.push("x", MyEnum::Baz("hello".to_string(), true));
assert_eq!(
engine.eval_with_scope::<INT>(
&mut scope,
r#"
switch x.get_data {
["Foo"] => 1,
["Bar", 42] => 2,
["Bar", 123] => 3,
["Baz", "hello", false] => 4,
["Baz", "hello", true] => 5,
_ => 9
}
"#
)?,
5
);
Ok(())
}
}