rune/runtime/to_value.rs
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 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
use crate::alloc::prelude::*;
use crate::alloc::{self, HashMap};
use crate::any::AnyMarker;
use super::{AnyObj, Object, RuntimeError, Value, VmResult};
/// Derive macro for the [`ToValue`] trait for converting types into the dynamic
/// `Value` container.
///
/// # Examples
///
/// ```
/// use rune::{ToValue, Vm};
/// use std::sync::Arc;
///
/// #[derive(ToValue)]
/// struct Foo {
/// field: u64,
/// }
///
/// let mut sources = rune::sources! {
/// entry => {
/// pub fn main(foo) {
/// foo.field + 1
/// }
/// }
/// };
///
/// let unit = rune::prepare(&mut sources).build()?;
///
/// let mut vm = Vm::without_runtime(Arc::new(unit));
/// let value = vm.call(["main"], (Foo { field: 42 },))?;
/// let value: u64 = rune::from_value(value)?;
///
/// assert_eq!(value, 43);
/// # Ok::<_, rune::support::Error>(())
/// ```
pub use rune_macros::ToValue;
/// Convert something into the dynamic [`Value`].
///
/// # Examples
///
/// ```
/// use rune::{ToValue, Vm};
/// use std::sync::Arc;
///
/// #[derive(ToValue)]
/// struct Foo {
/// field: u64,
/// }
///
/// let mut sources = rune::sources! {
/// entry => {
/// pub fn main(foo) {
/// foo.field + 1
/// }
/// }
/// };
///
/// let unit = rune::prepare(&mut sources).build()?;
///
/// let mut vm = Vm::without_runtime(Arc::new(unit));
/// let foo = vm.call(["main"], (Foo { field: 42 },))?;
/// let foo: u64 = rune::from_value(foo)?;
///
/// assert_eq!(foo, 43);
/// # Ok::<_, rune::support::Error>(())
/// ```
pub fn to_value(value: impl ToValue) -> Result<Value, RuntimeError> {
value.to_value()
}
/// Trait for converting types into the dynamic [`Value`] container.
///
/// # Examples
///
/// ```
/// use rune::{ToValue, Vm};
/// use std::sync::Arc;
///
/// #[derive(ToValue)]
/// struct Foo {
/// field: u64,
/// }
///
/// let mut sources = rune::sources! {
/// entry => {
/// pub fn main(foo) {
/// foo.field + 1
/// }
/// }
/// };
///
/// let unit = rune::prepare(&mut sources).build()?;
///
/// let mut vm = Vm::without_runtime(Arc::new(unit));
/// let foo = vm.call(["main"], (Foo { field: 42 },))?;
/// let foo: u64 = rune::from_value(foo)?;
///
/// assert_eq!(foo, 43);
/// # Ok::<_, rune::support::Error>(())
/// ```
pub trait ToValue: Sized {
/// Convert into a value.
fn to_value(self) -> Result<Value, RuntimeError>;
}
/// Trait governing things that can be returned from native functions.
pub trait ToReturn: Sized {
/// Convert something into a return value.
fn to_return(self) -> VmResult<Value>;
}
impl<T> ToReturn for VmResult<T>
where
T: ToValue,
{
#[inline]
fn to_return(self) -> VmResult<Value> {
match self {
VmResult::Ok(value) => VmResult::Ok(vm_try!(value.to_value())),
VmResult::Err(error) => VmResult::Err(error),
}
}
}
impl<T> ToReturn for T
where
T: ToValue,
{
#[inline]
fn to_return(self) -> VmResult<Value> {
VmResult::Ok(vm_try!(T::to_value(self)))
}
}
impl ToValue for Value {
#[inline]
fn to_value(self) -> Result<Value, RuntimeError> {
Ok(self)
}
}
/// Trait for converting types into values.
pub trait UnsafeToValue: Sized {
/// The type used to guard the unsafe value conversion.
type Guard: 'static;
/// Convert into a value.
///
/// # Safety
///
/// The value returned must not be used after the guard associated with it
/// has been dropped.
unsafe fn unsafe_to_value(self) -> Result<(Value, Self::Guard), RuntimeError>;
}
impl<T> ToValue for T
where
T: AnyMarker,
{
#[inline]
fn to_value(self) -> Result<Value, RuntimeError> {
Ok(Value::from(AnyObj::new(self)?))
}
}
impl<T> UnsafeToValue for T
where
T: ToValue,
{
type Guard = ();
#[inline]
unsafe fn unsafe_to_value(self) -> Result<(Value, Self::Guard), RuntimeError> {
Ok((self.to_value()?, ()))
}
}
impl ToValue for &Value {
#[inline]
fn to_value(self) -> Result<Value, RuntimeError> {
Ok(self.clone())
}
}
// Option impls
impl<T> ToValue for Option<T>
where
T: ToValue,
{
fn to_value(self) -> Result<Value, RuntimeError> {
let option = match self {
Some(some) => Some(some.to_value()?),
None => None,
};
Ok(Value::try_from(option)?)
}
}
// String impls
impl ToValue for alloc::Box<str> {
fn to_value(self) -> Result<Value, RuntimeError> {
let this = alloc::String::from(self);
Ok(Value::new(this)?)
}
}
impl ToValue for &str {
fn to_value(self) -> Result<Value, RuntimeError> {
let this = alloc::String::try_from(self)?;
Ok(Value::new(this)?)
}
}
#[cfg(feature = "alloc")]
impl ToValue for ::rust_alloc::boxed::Box<str> {
fn to_value(self) -> Result<Value, RuntimeError> {
let this = self.try_to_string()?;
Ok(Value::new(this)?)
}
}
#[cfg(feature = "alloc")]
impl ToValue for ::rust_alloc::string::String {
fn to_value(self) -> Result<Value, RuntimeError> {
let string = alloc::String::try_from(self)?;
Ok(Value::new(string)?)
}
}
impl<T, E> ToValue for Result<T, E>
where
T: ToValue,
E: ToValue,
{
fn to_value(self) -> Result<Value, RuntimeError> {
let result = match self {
Ok(ok) => Ok(ok.to_value()?),
Err(err) => Err(err.to_value()?),
};
Ok(Value::try_from(result)?)
}
}
// map impls
macro_rules! impl_map {
($ty:ty) => {
impl<T> ToValue for $ty
where
T: ToValue,
{
fn to_value(self) -> Result<Value, RuntimeError> {
let mut output = Object::with_capacity(self.len())?;
for (key, value) in self {
let key = alloc::String::try_from(key)?;
let value = value.to_value()?;
output.insert(key, value)?;
}
Ok(Value::try_from(output)?)
}
}
};
}
impl_map!(HashMap<::rust_alloc::string::String, T>);
impl_map!(HashMap<alloc::String, T>);
cfg_std! {
impl_map!(::std::collections::HashMap<::rust_alloc::string::String, T>);
impl_map!(::std::collections::HashMap<alloc::String, T>);
}