Created
July 15, 2019 23:04
-
-
Save azdle/2428c4367328c810bdbdc2d421a766ab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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