Skip to content

Instantly share code, notes, and snippets.

@azdle
Created July 15, 2019 23:04
Show Gist options
  • Save azdle/2428c4367328c810bdbdc2d421a766ab to your computer and use it in GitHub Desktop.
Save azdle/2428c4367328c810bdbdc2d421a766ab to your computer and use it in GitHub Desktop.
/// This is a marker type that allows us to mark a Vec<u8> as one that should be converted into
/// a Lua string type.
#[derive(Clone, Debug)]
pub struct ByteString(Vec<u8>);
impl From<Vec<u8>> for ByteString {
fn from(vec: Vec<u8>) -> Self {
ByteString(vec)
}
}
impl From<String> for ByteString {
fn from(string: String) -> Self {
ByteString(string.into())
}
}
impl Into<Vec<u8>> for ByteString {
fn into(self) -> Vec<u8> {
self.0
}
}
impl<'lua, 'a> rlua::ToLua<'lua> for ByteString {
fn to_lua(self, lua: rlua::Context<'lua>) -> rlua::Result<rlua::Value<'lua>> {
Ok(rlua::Value::String(lua.create_string(&self.0)?))
}
}
impl<'lua> rlua::FromLua<'lua> for ByteString {
fn from_lua(value: rlua::Value<'lua>, lua: rlua::Context<'lua>) -> rlua::Result<Self> {
Ok(ByteString(
lua.coerce_string(value)?
.ok_or_else(|| rlua::Error::FromLuaConversionError {
from: "???",
to: "String",
message: Some("expected string or number".to_string()),
})?
.as_bytes().into(),
))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment