summaryrefslogtreecommitdiff
path: root/src/parameter.rs
blob: e2d48ddde62d729ddf87ced7f6a21db72412c9b1 (plain)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179

use serde_json::{Value, json};
use crate::{
	Template,
	components::interactable::Interactable,
	Pos,
	PResult,
	perr
};



macro_rules! parameters {
	($($name: ident ($typ: ty) $stringname: ident, $v: ident ($fromjson: expr) ($tojson: expr));*;) => {
		#[derive(Debug, PartialEq, Clone)]
		pub enum Parameter {
			$(
				$name($typ),
			)*
		}
		impl Parameter {
			pub fn from_typed_json(typ: ParameterType, val: &Value) -> PResult<Parameter>{
				match typ {
					$(
						ParameterType::$name => Ok(Self::$name({
							let $v = val;
							$fromjson
						})),
					)*
				}
			}
			pub fn paramtype(&self) -> ParameterType {
				match self {
					$(
						Self::$name(_) => ParameterType::$name,
					)*
				}
			}
			pub fn to_json(&self) -> Value {
				match self {
					$(
						Self::$name($v) => $tojson,
					)*
				}
			}
		}

		#[derive(Debug, Clone, Copy, PartialEq, Eq)]
		pub enum ParameterType {
			$(
				$name,
			)*
		}
		impl ParameterType {
			pub fn from_str(typename: &str) -> Option<Self>{
				match typename {
					$(
						stringify!($stringname) => Some(Self::$name),
					)*
					_ => None
				}
			}
		}
	}
}

parameters!(
	String (String) string, v (v.as_str().ok_or(perr!("{:?} not a string", v))?.to_string()) (json!(v));
	Int (i64) int, v (v.as_i64().ok_or(perr!("{:?} not an int", v))?) (json!(v));
	Pos (Pos) pos, v (Pos::from_json(v).ok_or(perr!("{:?} not a pos", v))?) (json!(v));
	Float (f64) float, v (v.as_f64().ok_or(perr!("{:?} not an float", v))?) (json!(v));
	Template (Template) template, v (Template::from_json(v)?) (json!(["template", v.to_json()]));
	Interaction (Interactable) interaction, _v (Interactable::from_json(_v).ok_or(perr!("{:?} not an interactable", _v))?) (panic!("interactions can't be serialized"));
	Bool (bool) bool, v (v.as_bool().ok_or(perr!("{:?} not a bool", v))?) (json!(v));
	List (Vec<Parameter>) list, v 
		({
			v
				.as_array().ok_or(perr!("{:?} not an array", v))?
				.iter()
				.map(|item| Parameter::guess_from_json(item))
				.collect::<PResult<Vec<Parameter>>>()?
		})
		(json!(["list", v.iter().map(Parameter::to_json).collect::<Vec<Value>>()]));
);


impl Parameter {
	#[allow(dead_code)]
	pub fn string(string: &str) -> Self {
		Self::String(string.to_string())
	}
	
	pub fn guess_from_json(val: &Value) -> PResult<Parameter> {
		if let Some(arr) = val.as_array() {
			if arr.len() == 2 && arr[0].is_string() {
				let typestr = arr[0].as_str().unwrap();
				let typ = ParameterType::from_str(typestr).ok_or(perr!("invalid parameter type {}", typestr))?;
				return Self::from_typed_json(typ, &arr[1]);
			}
		}
		let typ = 
			if val.is_string() {
				ParameterType::String
			} else if val.is_u64() || val.is_i64() {
				ParameterType::Int
			} else if val.is_f64() {
				ParameterType::Float
			} else if val.is_boolean(){
				ParameterType::Bool
			} else if val.is_object(){
				ParameterType::Template
			} else {
				return Err(perr!("can't guess the type of parameter {:?}", val));
			};
		Self::from_typed_json(typ, val)
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use serde_json::json;
	
	macro_rules! gfj { // guess from json
		($($j:tt)*) => {Parameter::guess_from_json(&json!($($j)*)).unwrap()}
	}
	
	#[test]
	fn can_guess_json() {
		Parameter::guess_from_json(&json!(3)).unwrap();
	}
	
	#[test]
	fn guess_json() {
		assert_eq!(gfj!("charles"), Parameter::string("charles"));
		assert_eq!(gfj!("1"), Parameter::string("1"));
		assert_eq!(gfj!(""), Parameter::string(""));
		assert_eq!(gfj!(3), Parameter::Int(3));
		assert_eq!(gfj!(-3), Parameter::Int(-3));
		assert_eq!(gfj!(0), Parameter::Int(0));
		assert_eq!(gfj!(-0), Parameter::Int(0));
		assert_eq!(gfj!(3.5), Parameter::Float(3.5));
		assert_eq!(gfj!(3.0), Parameter::Float(3.0));
		assert_eq!(gfj!(-3.0), Parameter::Float(-3.0));
		assert_eq!(gfj!(0.0), Parameter::Float(0.0));
		assert_eq!(gfj!(-0.0), Parameter::Float(0.0));
		assert_eq!(gfj!(true), Parameter::Bool(true));
		
		assert_eq!(gfj!(["int", 3]), Parameter::Int(3));
	}
	
	#[test]
	fn guess_json_none() {
		assert!(Parameter::guess_from_json(&json!([2, 5])).is_none());
		assert!(Parameter::guess_from_json(&json!({"hello": "world"})).is_none());
	}
	
	#[test]
	fn parse_list() {
		assert_eq!(
				gfj!(["list", [5, 3, 1, 2]]),
			Parameter::List(vec![
				Parameter::Int(5),
				Parameter::Int(3),
				Parameter::Int(1),
				Parameter::Int(2)
			])
		);
		assert_eq!(
				gfj!(["list", [5, 3.0, "Hello", true]]),
			Parameter::List(vec![
				Parameter::Int(5),
				Parameter::Float(3.0),
				Parameter::string("Hello"),
				Parameter::Bool(true)
			])
		);
	}
}