pub trait TulispConvertible {
// Required methods
fn from_tulisp(value: &TulispObject) -> Result<Self, Error>
where Self: Sized;
fn into_tulisp(self) -> TulispObject;
}Expand description
Bidirectional conversion between Rust types and TulispObject.
This trait is the bridge between Rust and Lisp values. Every argument type
and return type used with TulispContext::defun must implement it.
§Built-in implementations
| Rust type | Lisp type |
|---|---|
i64 | integer |
f64 | float |
bool | t / nil |
String | string |
Number | integer or float |
Vec<T> | list |
TulispObject | any (pass-through) |
Shared<dyn TulispAny> | any (to support custom types that implement TulispConvertible) |
§Implementing for custom types
For structs that map to Lisp plists, use the AsPlist! macro instead of
implementing this trait by hand.
For arbitrary Rust types that have no natural Lisp representation, store the
value as an opaque TulispAny object using Shared::new. Any type
that implements Clone, Display, and Any qualifies (the blanket impl of
TulispAny covers all of these automatically).
into_tulisp: wrap withShared::newand call.into().from_tulisp: callTulispObject::as_anyto retrieve theShared<dyn TulispAny>, thendowncast_refto recover the concrete type.
use std::fmt;
use tulisp::{TulispConvertible, TulispObject, Shared, Error};
#[derive(Clone)]
struct Point { x: i64, y: i64 }
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "(Point {} {})", self.x, self.y)
}
}
impl TulispConvertible for Point {
fn from_tulisp(value: &TulispObject) -> Result<Self, Error> {
value
.as_any()
.ok()
.and_then(|v| v.downcast_ref::<Point>().cloned())
.ok_or_else(|| Error::type_mismatch("Expected Point"))
}
fn into_tulisp(self) -> TulispObject {
Shared::new(self).into()
}
}
let mut ctx = tulisp::TulispContext::new();
ctx.defun("make-point", |x: i64, y: i64| Point { x, y });
ctx.defun("point-x", |p: Point| p.x);
assert_eq!(ctx.eval_string("(point-x (make-point 3 4))").unwrap().to_string(), "3");Required Methods§
Sourcefn from_tulisp(value: &TulispObject) -> Result<Self, Error>where
Self: Sized,
fn from_tulisp(value: &TulispObject) -> Result<Self, Error>where
Self: Sized,
Converts a Lisp value into this Rust type.
Returns an error if the value has the wrong Lisp type.
Sourcefn into_tulisp(self) -> TulispObject
fn into_tulisp(self) -> TulispObject
Converts this Rust value into a Lisp value.