use std::borrow::{Borrow, Cow}; use crate::{FromLua, Function, IntoLuaVec, State}; pub struct Chunk<'a> { state: &'a State, name: String, data: Cow<'a, [u8]>, func: Function<'a>, } impl<'a> Chunk<'a> { pub(crate) fn new(state: &'a State, name: String, data: Cow<'a, [u8]>, func: Function<'a>) -> Self { Self { state, name, data, func, } } /// Construct a Lua Chunk from bytes /* pub fn from_bytes(name: &'a str, bytes: &'a [u8]) -> Self { Self { name, data: bytes } } /// Construct a Lua Chunk from a string pub fn from_str(name: &'a str, text: &'a str) -> Self { Self { name, data: text.as_bytes(), } } */ /// Execute the chunk in the Lua context pub fn execute(&'a self, args: A) -> crate::Result where A: IntoLuaVec<'a>, R: FromLua<'a> { self.state.execute_chunk::(self, args) } /// Returns the name of the Chunk pub fn name(&self) -> &str { &self.name } /// Returns the data of the chunk pub fn data(&self) -> &[u8] { self.data.borrow() } /// Returns a handle to the chunk's executable function pub fn function(&self) -> Function { self.func.clone() } } pub trait IntoChunkData<'a> { fn into_chunk(self) -> Cow<'a, [u8]>; } impl<'a> IntoChunkData<'a> for &'a str { fn into_chunk(self) -> Cow<'a, [u8]> { Cow::Borrowed(self.as_bytes()) } } impl<'a> IntoChunkData<'a> for &'a [u8] { fn into_chunk(self) -> Cow<'a, [u8]> { Cow::Borrowed(self) } }