1use crate::{
41 component::{Address, Component, single},
42 error::{Error, Result},
43 types::Side,
44 value::Value,
45};
46
47#[derive(Clone, Debug, PartialEq, Eq, Hash)]
49pub struct PatternProvider(pub Address);
50
51impl Component for PatternProvider {
52 const KIND: &'static str = "pattern_provider";
53 fn from_address(address: Address) -> Self {
54 Self(address)
55 }
56 fn address(&self) -> &Address {
57 &self.0
58 }
59}
60
61#[derive(Clone, Debug, PartialEq, Eq)]
63pub struct Stack {
64 pub name: String,
66 pub count: i64,
68 pub fluid: bool,
69 pub key: Option<String>,
74 pub label: Option<String>,
76}
77
78impl Stack {
79 pub fn item(name: impl Into<String>, count: i64) -> Stack {
80 Stack { name: name.into(), count, fluid: false, key: None, label: None }
81 }
82
83 pub fn fluid(name: impl Into<String>, millibuckets: i64) -> Stack {
85 Stack { name: name.into(), count: millibuckets, fluid: true, key: None, label: None }
86 }
87
88 fn to_value(&self) -> Value {
89 let mut entries = vec![
90 ("name".into(), self.name.as_str().into()),
91 ("count".into(), self.count.into()),
92 ("fluid".into(), self.fluid.into()),
93 ];
94 if let Some(key) = &self.key {
95 entries.push(("key".into(), key.as_str().into()));
96 }
97 Value::Map(entries)
98 }
99
100 fn from_value(value: &Value) -> Option<Stack> {
101 Some(Stack {
102 name: value.get("name")?.as_str()?.to_owned(),
103 count: value.get("count")?.as_i64()?,
104 fluid: value.get("fluid").and_then(Value::as_bool).unwrap_or(false),
105 key: value.get("key").and_then(Value::as_str).map(str::to_owned),
106 label: value.get("label").and_then(Value::as_str).map(str::to_owned),
107 })
108 }
109}
110
111#[derive(Clone, Debug, PartialEq, Eq)]
115pub struct Pattern {
116 pub inputs: Vec<Stack>,
117 pub outputs: Vec<Stack>,
118}
119
120impl Pattern {
121 pub fn new(inputs: Vec<Stack>, outputs: Vec<Stack>) -> Pattern {
122 Pattern { inputs, outputs }
123 }
124
125 fn to_value(&self) -> Value {
126 Value::Map(vec![
127 ("inputs".into(), stacks_value(&self.inputs)),
128 ("outputs".into(), stacks_value(&self.outputs)),
129 ])
130 }
131
132 fn from_value(value: &Value) -> Option<Pattern> {
133 Some(Pattern { inputs: stacks(value.get("inputs")?)?, outputs: stacks(value.get("outputs")?)? })
134 }
135}
136
137#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct Job {
140 pub id: i64,
141 pub pattern: i64,
143 pub inputs: Vec<Stack>,
145 pub outputs: Vec<Stack>,
147}
148
149impl Job {
150 fn from_value(value: &Value) -> Option<Job> {
151 Some(Job {
152 id: value.get("id")?.as_i64()?,
153 pattern: value.get("pattern")?.as_i64()?,
154 inputs: stacks(value.get("inputs")?)?,
155 outputs: stacks(value.get("outputs")?)?,
156 })
157 }
158}
159
160fn stacks_value(stacks: &[Stack]) -> Value {
161 Value::Array(stacks.iter().map(Stack::to_value).collect())
162}
163
164fn stacks(value: &Value) -> Option<Vec<Stack>> {
165 if matches!(value, Value::Map(m) if m.is_empty()) {
167 return Some(Vec::new());
168 }
169 value.as_array()?.into_iter().map(Stack::from_value).collect()
170}
171
172fn list<T>(reply: Vec<Value>, what: &str, parse: impl Fn(&Value) -> Option<T>) -> Result<Vec<T>> {
173 let value: Value = single(reply)?;
174 if matches!(&value, Value::Map(m) if m.is_empty()) {
175 return Ok(Vec::new());
176 }
177 value
178 .as_array()
179 .and_then(|items| items.into_iter().map(parse).collect())
180 .ok_or_else(|| Error::UnexpectedReply(format!("expected a list of {what}, got {value:?}")))
181}
182
183fn job(reply: Vec<Value>) -> Result<Option<Job>> {
184 match single::<Value>(reply)? {
185 Value::Nil => Ok(None),
186 value => Job::from_value(&value)
187 .map(Some)
188 .ok_or_else(|| Error::UnexpectedReply(format!("expected a job, got {value:?}"))),
189 }
190}
191
192macro_rules! methods {
193 ($(
194 $(#[$doc:meta])*
195 fn $name:ident / $name_async:ident ($($arg:ident: $ty:ty),*) -> $ret:ty =
196 $lua:literal [$($value:expr),*] => $decode:expr;
197 )*) => {
198 impl PatternProvider {$(
199 $(#[$doc])*
200 pub fn $name(&self, $($arg: $ty),*) -> Result<$ret> {
201 let reply = self.invoke($lua, vec![$($value),*])?;
202 ($decode)(reply)
203 }
204
205 #[doc = concat!("[`Self::", stringify!($name), "`] without blocking; see [`crate::task`].")]
206 #[cfg(feature = "async")]
207 pub async fn $name_async(&self, $($arg: $ty),*) -> Result<$ret> {
208 let reply = self.invoke_async($lua, vec![$($value),*]).await?;
209 ($decode)(reply)
210 }
211 )*}
212 };
213}
214
215methods! {
216 fn set_patterns / set_patterns_async(patterns: &[Pattern]) -> usize =
218 "setPatterns" [Value::Array(patterns.iter().map(Pattern::to_value).collect())]
219 => |r| single::<crate::Number>(r).map(|n| n.as_i64() as usize);
220
221 fn add_pattern / add_pattern_async(pattern: &Pattern) -> i64 =
223 "addPattern" [stacks_value(&pattern.inputs), stacks_value(&pattern.outputs)]
224 => |r| single::<crate::Number>(r).map(|n| n.as_i64());
225
226 fn remove_pattern / remove_pattern_async(index: i64) -> bool =
229 "removePattern" [index.into()] => single::<bool>;
230
231 fn patterns / patterns_async() -> Vec<Pattern> =
233 "getPatterns" [] => |r| list(r, "patterns", Pattern::from_value);
234
235 fn jobs / jobs_async() -> Vec<Job> =
237 "getJobs" [] => |r| list(r, "jobs", Job::from_value);
238
239 fn job / job_async(id: i64) -> Option<Job> =
241 "getJob" [id.into()] => job;
242
243 fn push_inputs / push_inputs_async(id: i64, side: Side) -> bool =
247 "pushInputs" [id.into(), side.into()] => single::<bool>;
248
249 fn cancel_job / cancel_job_async(id: i64) -> bool =
253 "cancelJob" [id.into()] => single::<bool>;
254
255 fn is_online / is_online_async() -> bool =
257 "isOnline" [] => single::<bool>;
258}
259
260#[cfg(test)]
261mod tests {
262 use super::*;
263
264 #[test]
265 fn stacks_round_trip() {
266 let stack = Stack { key: Some("{id:\"x\"}".into()), ..Stack::fluid("minecraft:water", 1000) };
267 assert_eq!(Stack::from_value(&stack.to_value()), Some(stack));
268 }
269
270 #[test]
271 fn jobs_decode_from_lua_style_tables() {
272 let stack = |n: &str| Value::Map(vec![("name".into(), n.into()), ("count".into(), 2.into())]);
273 let job = Value::Map(vec![
274 ("id".into(), 7.into()),
275 ("pattern".into(), 1.into()),
276 ("inputs".into(), Value::Map(vec![(1.into(), stack("minecraft:cobblestone"))])),
277 ("outputs".into(), Value::Array(vec![stack("minecraft:stone")])),
278 ]);
279 let job = Job::from_value(&job).unwrap();
280 assert_eq!((job.id, job.inputs[0].name.as_str(), job.outputs[0].count), (7, "minecraft:cobblestone", 2));
281 assert_eq!(list(vec![Value::Map(vec![])], "jobs", Job::from_value), Ok(vec![]));
282 }
283}