Skip to main content

wackasm_opencomputers/
component.rs

1//! Finding components and calling them.
2//!
3//! Every typed wrapper in [`crate::components`] implements [`Component`].
4//! The untyped way, for anything the wrappers don't cover (another mod's
5//! components, say), is [`Proxy`] or [`invoke`].
6
7use std::fmt;
8
9use crate::{
10    error::{Error, Result},
11    sys,
12    value::{Handle, Number, OcString, Value},
13};
14
15/// A component's address (a UUID string).
16#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct Address(pub String);
18
19impl Address {
20    pub fn as_str(&self) -> &str {
21        &self.0
22    }
23}
24
25/// So an address can be passed wherever a method takes one as a string.
26impl AsRef<[u8]> for Address {
27    fn as_ref(&self) -> &[u8] {
28        self.0.as_bytes()
29    }
30}
31
32impl fmt::Display for Address {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        f.write_str(&self.0)
35    }
36}
37
38impl fmt::Debug for Address {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        write!(f, "Address({})", self.0)
41    }
42}
43
44impl From<&str> for Address {
45    fn from(s: &str) -> Self {
46        Address(s.to_owned())
47    }
48}
49
50impl From<String> for Address {
51    fn from(s: String) -> Self {
52        Address(s)
53    }
54}
55
56impl From<&Address> for Value {
57    fn from(a: &Address) -> Self {
58        Value::from(a.0.as_str())
59    }
60}
61
62impl From<Address> for Value {
63    fn from(a: Address) -> Self {
64        Value::from(a.0)
65    }
66}
67
68/// Calls `method` on the component at `address`.
69pub fn invoke(address: &str, method: &str, args: Vec<Value>) -> Result<Vec<Value>> {
70    let args = Value::Array(args).encode();
71    let status = unsafe {
72        sys::invoke(address.as_ptr(), address.len(), method.as_ptr(), method.len(), args.as_ptr(), args.len())
73    };
74    reply(status)
75}
76
77/// Calls `method` on a userdata value, such as the request object
78/// `internet.request` returns (Lua's `handle.read()`). A value that was
79/// released is [`Error::NoSuchComponent`].
80pub fn invoke_value(value: Handle, method: &str, args: Vec<Value>) -> Result<Vec<Value>> {
81    let args = Value::Array(args).encode();
82    let status = unsafe { sys::invoke_value(value.0, method.as_ptr(), method.len(), args.as_ptr(), args.len()) };
83    reply(status)
84}
85
86/// Like [`invoke`], but without blocking: queues the call and returns a future
87/// for its result. Must be awaited inside [`crate::task::run`]. Requires the
88/// `async` feature.
89#[cfg(feature = "async")]
90pub fn invoke_async(address: &str, method: &str, args: Vec<Value>) -> crate::task::Call {
91    crate::task::Call::new(crate::task::Target::Component(address.to_owned()), method, args)
92}
93
94/// Like [`invoke_value`], but without blocking; see [`invoke_async`].
95#[cfg(feature = "async")]
96pub fn invoke_value_async(value: Handle, method: &str, args: Vec<Value>) -> crate::task::Call {
97    crate::task::Call::new(crate::task::Target::Value(value.0), method, args)
98}
99
100/// Tells the host this program is done with `value`. The host disposes of it
101/// (an open socket is closed) and the handle stops working. Values that are
102/// never released stay alive until the computer stops.
103pub fn release_value(value: Handle) {
104    unsafe { sys::release_value(value.0) };
105}
106
107fn reply(status: i32) -> Result<Vec<Value>> {
108    decode_reply(status, sys::response())
109}
110
111/// A call's result from its status and response bytes (also used for the
112/// results of async calls).
113pub(crate) fn decode_reply(status: i32, reply: Vec<u8>) -> Result<Vec<Value>> {
114    match status {
115        sys::STATUS_OK => match Value::decode(&reply) {
116            Some(Value::Array(items)) => Ok(items),
117            Some(Value::Nil) | None if reply.is_empty() => Ok(Vec::new()),
118            Some(other) => Ok(vec![other]),
119            None => Err(Error::UnexpectedReply("malformed value".into())),
120        },
121        sys::STATUS_NO_SUCH_COMPONENT => Err(Error::NoSuchComponent),
122        sys::STATUS_NO_SUCH_METHOD => Err(Error::NoSuchMethod),
123        _ => Err(Error::Failed(String::from_utf8_lossy(&reply).into_owned())),
124    }
125}
126
127/// Every component whose type contains `filter` (all of them for `""`), as
128/// `(address, type)` pairs sorted by address.
129pub fn list(filter: &str) -> Vec<(Address, String)> {
130    if unsafe { sys::components(filter.as_ptr(), filter.len()) } != sys::STATUS_OK {
131        return Vec::new();
132    }
133    let mut found: Vec<(Address, String)> = match Value::decode(&sys::response()) {
134        Some(Value::Map(entries)) => entries
135            .into_iter()
136            .filter_map(|(k, v)| Some((Address(k.as_str()?.to_owned()), v.as_str()?.to_owned())))
137            .collect(),
138        _ => Vec::new(),
139    };
140    found.sort();
141    found
142}
143
144/// A method's attributes, from [`methods`].
145#[derive(Clone, Debug)]
146pub struct MethodInfo {
147    pub name: String,
148    /// Direct calls run immediately but draw on the per-tick call budget;
149    /// others wait for the next server tick.
150    pub direct: bool,
151    pub doc: String,
152}
153
154/// The methods a component offers, sorted by name.
155pub fn methods(address: &str) -> Result<Vec<MethodInfo>> {
156    match unsafe { sys::methods(address.as_ptr(), address.len()) } {
157        sys::STATUS_OK => {}
158        sys::STATUS_NO_SUCH_COMPONENT => return Err(Error::NoSuchComponent),
159        _ => return Err(Error::Failed(String::from_utf8_lossy(&sys::response()).into_owned())),
160    }
161    let Some(Value::Map(entries)) = Value::decode(&sys::response()) else {
162        return Err(Error::UnexpectedReply("methods".into()));
163    };
164    let mut methods: Vec<MethodInfo> = entries
165        .into_iter()
166        .filter_map(|(name, info)| {
167            Some(MethodInfo {
168                name: name.as_str()?.to_owned(),
169                direct: info.get("direct").and_then(Value::as_bool).unwrap_or(false),
170                doc: info.get("doc").and_then(Value::as_str).unwrap_or_default().to_owned(),
171            })
172        })
173        .collect();
174    methods.sort_by(|a, b| a.name.cmp(&b.name));
175    Ok(methods)
176}
177
178/// A typed component wrapper.
179pub trait Component: Sized {
180    /// The OpenComputers component type, such as `"gpu"`.
181    const KIND: &'static str;
182
183    /// Wraps an address without checking what is there.
184    fn from_address(address: Address) -> Self;
185
186    fn address(&self) -> &Address;
187
188    /// The first component of this type, by address order.
189    fn first() -> Option<Self> {
190        Self::all().into_iter().next()
191    }
192
193    /// Every component of this type, by address order.
194    fn all() -> Vec<Self> {
195        list(Self::KIND)
196            .into_iter()
197            .filter(|(_, kind)| kind == Self::KIND)
198            .map(|(address, _)| Self::from_address(address))
199            .collect()
200    }
201
202    /// The component at `address`, if it is of this type.
203    fn at(address: impl Into<Address>) -> Option<Self> {
204        let address = address.into();
205        list(Self::KIND)
206            .into_iter()
207            .any(|(a, kind)| a == address && kind == Self::KIND)
208            .then(|| Self::from_address(address))
209    }
210
211    /// An untyped call, for methods the wrapper doesn't know.
212    fn invoke(&self, method: &str, args: Vec<Value>) -> Result<Vec<Value>> {
213        invoke(self.address().as_str(), method, args)
214    }
215
216    /// [`Component::invoke`] without blocking; see [`invoke_async`].
217    #[cfg(feature = "async")]
218    fn invoke_async(&self, method: &str, args: Vec<Value>) -> crate::task::Call {
219        invoke_async(self.address().as_str(), method, args)
220    }
221}
222
223/// Any component, called by method name.
224#[derive(Clone, Debug, PartialEq, Eq, Hash)]
225pub struct Proxy {
226    pub address: Address,
227    pub kind: String,
228}
229
230impl Proxy {
231    pub fn all() -> Vec<Proxy> {
232        list("").into_iter().map(|(address, kind)| Proxy { address, kind }).collect()
233    }
234
235    pub fn invoke(&self, method: &str, args: Vec<Value>) -> Result<Vec<Value>> {
236        invoke(self.address.as_str(), method, args)
237    }
238
239    pub fn methods(&self) -> Result<Vec<MethodInfo>> {
240        methods(self.address.as_str())
241    }
242}
243
244// ---------------------------------------------------------------- replies
245
246/// Turns a reply into a method's documented return type. OpenComputers
247/// methods report failure as `nil, "reason"` (or `false, "reason"` for some
248/// boolean methods); decoding into a non-optional type turns the first into
249/// [`Error::Failed`].
250pub trait FromReply: Sized {
251    fn from_reply(reply: Vec<Value>) -> Result<Self>;
252}
253
254/// One returned value.
255pub trait FromValue: Sized {
256    const EXPECTED: &'static str;
257    fn from_value(value: Value) -> Option<Self>;
258}
259
260impl FromValue for Value {
261    const EXPECTED: &'static str = "any";
262    fn from_value(value: Value) -> Option<Self> {
263        Some(value)
264    }
265}
266
267impl FromValue for bool {
268    const EXPECTED: &'static str = "boolean";
269    fn from_value(value: Value) -> Option<Self> {
270        value.as_bool()
271    }
272}
273
274impl FromValue for Number {
275    const EXPECTED: &'static str = "number";
276    fn from_value(value: Value) -> Option<Self> {
277        value.as_number()
278    }
279}
280
281impl FromValue for OcString {
282    const EXPECTED: &'static str = "string";
283    fn from_value(value: Value) -> Option<Self> {
284        match value {
285            Value::String(s) => Some(s),
286            _ => None,
287        }
288    }
289}
290
291impl FromValue for Handle {
292    const EXPECTED: &'static str = "userdata";
293    fn from_value(value: Value) -> Option<Self> {
294        value.as_handle()
295    }
296}
297
298impl<T: FromValue> FromValue for Option<T> {
299    const EXPECTED: &'static str = T::EXPECTED;
300    fn from_value(value: Value) -> Option<Self> {
301        match value {
302            Value::Nil => Some(None),
303            v => T::from_value(v).map(Some),
304        }
305    }
306}
307
308fn failure(reply: &[Value]) -> Option<Error> {
309    match reply {
310        [Value::Nil | Value::Bool(false), Value::String(reason), ..] => Some(Error::Failed(reason.to_string_lossy())),
311        _ => None,
312    }
313}
314
315fn take<T: FromValue>(reply: &[Value], index: usize) -> Result<T> {
316    let value = reply.get(index).cloned().unwrap_or_default();
317    if let Some(v) = T::from_value(value.clone()) {
318        return Ok(v);
319    }
320    if let Some(error) = failure(reply) {
321        return Err(error);
322    }
323    Err(Error::UnexpectedReply(format!("expected {} at position {}, got {value:?}", T::EXPECTED, index + 1)))
324}
325
326impl FromReply for () {
327    fn from_reply(reply: Vec<Value>) -> Result<Self> {
328        match failure(&reply) {
329            Some(error) if matches!(reply.first(), Some(Value::Nil)) => Err(error),
330            _ => Ok(()),
331        }
332    }
333}
334
335impl FromReply for Vec<Value> {
336    fn from_reply(reply: Vec<Value>) -> Result<Self> {
337        Ok(reply)
338    }
339}
340
341macro_rules! reply_tuple {
342    ($($t:ident $i:tt),+) => {
343        impl<$($t: FromValue),+> FromReply for ($($t,)+) {
344            fn from_reply(reply: Vec<Value>) -> Result<Self> {
345                Ok(($(take::<$t>(&reply, $i)?,)+))
346            }
347        }
348    };
349}
350reply_tuple!(A 0);
351reply_tuple!(A 0, B 1);
352reply_tuple!(A 0, B 1, C 2);
353reply_tuple!(A 0, B 1, C 2, D 3);
354reply_tuple!(A 0, B 1, C 2, D 3, E 4);
355
356/// Single-value replies decode straight into `T`, not `(T,)`.
357pub(crate) fn single<T: FromValue>(reply: Vec<Value>) -> Result<T> {
358    take(&reply, 0)
359}
360
361/// Builds an argument list, dropping trailing omitted optionals so the
362/// component applies its own defaults.
363pub(crate) fn args(values: Vec<Option<Value>>) -> Vec<Value> {
364    let keep = values.iter().rposition(Option::is_some).map_or(0, |i| i + 1);
365    values.into_iter().take(keep).map(Option::unwrap_or_default).collect()
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371
372    #[test]
373    fn failures_become_errors() {
374        let reply = vec![Value::Nil, "no space".into()];
375        assert_eq!(single::<Number>(reply.clone()), Err(Error::Failed("no space".into())));
376        assert_eq!(single::<Option<Number>>(reply), Ok(None));
377        let refused = vec![false.into(), "blocked".into()];
378        assert_eq!(single::<bool>(refused), Ok(false));
379    }
380
381    #[test]
382    fn tuples_and_trailing_optionals() {
383        let reply = vec![50.into(), 16.into()];
384        let (w, h): (Number, Number) = FromReply::from_reply(reply).unwrap();
385        assert_eq!((w.as_i64(), h.as_i64()), (50, 16));
386        assert_eq!(args(vec![Some(1.into()), None, Some(2.into()), None]), vec![1.into(), Value::Nil, 2.into()]);
387    }
388}