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
use crate::*;
pub use extism_convert_macros::FromBytes;
/// `FromBytes` is used to define how a type should be decoded when working with
/// Extism memory. It is used for plugin output and host function input.
///
/// `FromBytes` can be derived by delegating encoding to generic type implementing
/// `FromBytes`, e.g., [`Json`], [`Msgpack`].
///
/// ```
/// use extism_convert::{Json, FromBytes};
/// use serde::Deserialize;
///
/// #[derive(FromBytes, Deserialize, PartialEq, Debug)]
/// #[encoding(Json)]
/// struct Struct {
/// hello: String,
/// }
///
/// assert_eq!(Struct::from_bytes(br#"{"hello":"hi"}"#)?, Struct { hello: "hi".into() });
/// # Ok::<(), extism_convert::Error>(())
/// ```
///
/// Custom encodings can also be used, through new-types with a single generic
/// argument, i.e., `Type<T>(T)`, that implement `FromBytesOwned` for the struct.
///
/// ```
/// use std::str::{self, FromStr};
/// use std::convert::Infallible;
/// use extism_convert::{Error, FromBytes, FromBytesOwned};
///
/// // Custom serialization using `FromStr`
/// struct StringEnc<T>(T);
/// impl<T: FromStr> FromBytesOwned for StringEnc<T> where Error: From<<T as FromStr>::Err> {
/// fn from_bytes_owned(data: &[u8]) -> Result<Self, Error> {
/// Ok(Self(str::from_utf8(data)?.parse()?))
/// }
/// }
///
/// #[derive(FromBytes, PartialEq, Debug)]
/// #[encoding(StringEnc)]
/// struct Struct {
/// hello: String,
/// }
///
/// impl FromStr for Struct {
/// type Err = Infallible;
/// fn from_str(s: &str) -> Result<Self, Infallible> {
/// Ok(Self { hello: s.to_owned() })
/// }
/// }
///
/// assert_eq!(Struct::from_bytes(b"hi")?, Struct { hello: "hi".into() });
/// # Ok::<(), extism_convert::Error>(())
/// ```
pub trait FromBytes<'a>: Sized {
/// Decode a value from a slice of bytes
fn from_bytes(data: &'a [u8]) -> Result<Self, Error>;
}
/// `FromBytesOwned` is similar to [`FromBytes`] but it doesn't borrow from the input slice.
/// [`FromBytes`] is automatically implemented for all types that implement `FromBytesOwned`.
///
/// `FromBytesOwned` can be derived through [`#[derive(FromBytes)]`](FromBytes).
pub trait FromBytesOwned: Sized {
/// Decode a value from a slice of bytes, the resulting value should not borrow the input
/// data.
fn from_bytes_owned(data: &[u8]) -> Result<Self, Error>;
}
impl<'a> FromBytes<'a> for &'a [u8] {
fn from_bytes(data: &'a [u8]) -> Result<Self, Error> {
Ok(data)
}
}
impl<'a> FromBytes<'a> for &'a str {
fn from_bytes(data: &'a [u8]) -> Result<Self, Error> {
Ok(std::str::from_utf8(data)?)
}
}
impl<'a, T: FromBytesOwned> FromBytes<'a> for T {
fn from_bytes(data: &'a [u8]) -> Result<Self, Error> {
T::from_bytes_owned(data)
}
}
impl FromBytesOwned for Box<[u8]> {
fn from_bytes_owned(data: &[u8]) -> Result<Self, Error> {
Ok(data.to_vec().into_boxed_slice())
}
}
impl FromBytesOwned for Vec<u8> {
fn from_bytes_owned(data: &[u8]) -> Result<Self, Error> {
Ok(data.to_vec())
}
}
impl FromBytesOwned for String {
fn from_bytes_owned(data: &[u8]) -> Result<Self, Error> {
Ok(std::str::from_utf8(data)?.to_string())
}
}
impl FromBytesOwned for f64 {
fn from_bytes_owned(data: &[u8]) -> Result<Self, Error> {
Ok(Self::from_le_bytes(data.try_into()?))
}
}
impl FromBytesOwned for f32 {
fn from_bytes_owned(data: &[u8]) -> Result<Self, Error> {
Ok(Self::from_le_bytes(data.try_into()?))
}
}
impl FromBytesOwned for i64 {
fn from_bytes_owned(data: &[u8]) -> Result<Self, Error> {
Ok(Self::from_le_bytes(data.try_into()?))
}
}
impl FromBytesOwned for i32 {
fn from_bytes_owned(data: &[u8]) -> Result<Self, Error> {
Ok(Self::from_le_bytes(data.try_into()?))
}
}
impl FromBytesOwned for u64 {
fn from_bytes_owned(data: &[u8]) -> Result<Self, Error> {
Ok(Self::from_le_bytes(data.try_into()?))
}
}
impl FromBytesOwned for u32 {
fn from_bytes_owned(data: &[u8]) -> Result<Self, Error> {
Ok(Self::from_le_bytes(data.try_into()?))
}
}
impl FromBytesOwned for () {
fn from_bytes_owned(_: &[u8]) -> Result<Self, Error> {
Ok(())
}
}
impl<'a, T: FromBytes<'a>> FromBytes<'a> for std::io::Cursor<T> {
fn from_bytes(data: &'a [u8]) -> Result<Self, Error> {
Ok(std::io::Cursor::new(T::from_bytes(data)?))
}
}
impl<'a, T: FromBytes<'a>> FromBytes<'a> for Option<T> {
fn from_bytes(data: &'a [u8]) -> Result<Self, Error> {
if data.is_empty() {
return Ok(None);
}
T::from_bytes(data).map(Some)
}
}