elua/src/chunk.rs

108 lines
2.4 KiB
Rust
Raw Normal View History

use std::borrow::{Borrow, Cow};
2024-02-19 04:23:59 +00:00
use crate::{FromLuaVec, 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, R>(&'a self, args: A) -> crate::Result<R>
where
A: IntoLuaVec<'a>,
R: FromLuaVec<'a>
{
self.state.execute_chunk::<A, R>(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]> {
if self.ends_with("\n") {
Cow::Borrowed(self.as_bytes())
} else {
let s = format!("{}\n", self);
Cow::Owned(s.as_bytes().to_vec())
}
}
}
impl<'a> IntoChunkData<'a> for &'a String {
fn into_chunk(self) -> Cow<'a, [u8]> {
let s = format!("{}\n", self);
Cow::Owned(s.as_bytes().to_vec())
}
}
impl<'a> IntoChunkData<'a> for String {
fn into_chunk(self) -> Cow<'a, [u8]> {
let s = if self.ends_with("\n") {
self
} else {
format!("{self}\n")
};
Cow::Owned(s.as_bytes().to_vec())
}
}
impl<'a> IntoChunkData<'a> for &'a [u8] {
fn into_chunk(self) -> Cow<'a, [u8]> {
if self.ends_with("\n".as_bytes()) {
Cow::Borrowed(self)
} else {
let mut v = self.to_vec();
v.extend_from_slice("\n".as_bytes());
Cow::Owned(v)
}
}
}