use Cow for d-r-y (Static...)

This commit is contained in:
Andy Weidenbaum
2021-06-15 07:28:46 +10:00
parent 10391c419a
commit 1bb9236f7b
2 changed files with 80 additions and 336 deletions

View File

@@ -1,4 +1,5 @@
use rlua::{Context, Function, MetaMethod, RegistryKey, Table, UserData, UserDataMethods, Value};
use std::borrow::Cow;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
@@ -9,8 +10,10 @@ use crate::types::Result;
/// Stores Lua modules indexed by module name, and provides an `rlua::MetaMethod`
/// to enable `require`ing the stored modules by name in an `rlua::Context`.
struct Searcher {
/// A `HashMap` of Lua modules in `String` representation, indexed by module name.
modules: HashMap<String, String>,
/// A `HashMap` of Lua modules in string representation, indexed by module name.
///
/// Uses `Cow<'static, str>` types to allow both `&'static str` and owned `String`.
modules: HashMap<Cow<'static, str>, Cow<'static, str>>,
/// An `rlua::RegistryKey` whose value is the Lua environment within which the
/// user made the request to instantiate a `Searcher` for `modules`.
@@ -18,7 +21,7 @@ struct Searcher {
}
impl Searcher {
fn new(modules: HashMap<String, String>, globals: RegistryKey) -> Self {
fn new(modules: HashMap<Cow<'static, str>, Cow<'static, str>>, globals: RegistryKey) -> Self {
Self { modules, globals }
}
}
@@ -29,47 +32,21 @@ impl UserData for Searcher {
M: UserDataMethods<'lua, Self>,
{
methods.add_meta_method(MetaMethod::Call, |lua_ctx, this, name: String| {
let name = Cow::from(name);
match this.modules.get(&name) {
Some(content) => Ok(Value::Function(
lua_ctx
.load(content)
.set_name(&name)?
.set_environment(lua_ctx.registry_value::<Table>(&this.globals)?)?
.into_function()?,
)),
None => Ok(Value::Nil),
}
});
}
}
/// Like `Searcher`, but with `modules` keys and values encoded as `&'static str`
/// to facilitate compile-time includes of Lua source code.
struct StaticSearcher {
modules: HashMap<&'static str, &'static str>,
globals: RegistryKey,
}
impl StaticSearcher {
fn new(modules: HashMap<&'static str, &'static str>, globals: RegistryKey) -> Self {
Self { modules, globals }
}
}
impl UserData for StaticSearcher {
fn add_methods<'lua, M>(methods: &mut M)
where
M: UserDataMethods<'lua, Self>,
{
methods.add_meta_method(MetaMethod::Call, |lua_ctx, this, name: String| {
match this.modules.get(name.as_str()) {
Some(content) => Ok(Value::Function(
lua_ctx
.load(content)
.set_name(&name)?
.set_environment(lua_ctx.registry_value::<Table>(&this.globals)?)?
.into_function()?,
)),
Some(content) => {
let content = match content {
Cow::Borrowed(content) => content,
Cow::Owned(content) => content.as_str(),
};
Ok(Value::Function(
lua_ctx
.load(content)
.set_name(name.as_ref())?
.set_environment(lua_ctx.registry_value::<Table>(&this.globals)?)?
.into_function()?,
))
}
None => Ok(Value::Nil),
}
});
@@ -85,7 +62,7 @@ struct PathSearcherPoly<P>
where
P: 'static + AsRef<Path> + Send,
{
modules: HashMap<String, P>,
modules: HashMap<Cow<'static, str>, P>,
globals: RegistryKey,
/// Function to read file content as Lua source code.
@@ -97,7 +74,7 @@ where
P: 'static + AsRef<Path> + Send,
{
fn new(
modules: HashMap<String, P>,
modules: HashMap<Cow<'static, str>, P>,
globals: RegistryKey,
transform: Box<dyn Fn(PathBuf) -> rlua::Result<String> + Send>,
) -> Self {
@@ -118,6 +95,7 @@ where
M: UserDataMethods<'lua, Self>,
{
methods.add_meta_method(MetaMethod::Call, |lua_ctx, this, name: String| {
let name = Cow::from(name);
match this.modules.get(&name) {
Some(ref path) => {
let path = path.as_ref().to_path_buf();
@@ -125,7 +103,7 @@ where
Ok(Value::Function(
lua_ctx
.load(&content)
.set_name(&name)?
.set_name(name.as_ref())?
.set_environment(lua_ctx.registry_value::<Table>(&this.globals)?)?
.into_function()?,
))
@@ -153,7 +131,7 @@ pub struct ClosureSearcher {
/// Closures must return an `rlua::Result`-wrapped `Function`. This `Function`
/// acts as the module loader.
modules: HashMap<
String,
Cow<'static, str>,
Box<
dyn for<'ctx> Fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>
+ Send,
@@ -166,7 +144,7 @@ pub struct ClosureSearcher {
impl ClosureSearcher {
pub fn new(
modules: HashMap<
String,
Cow<'static, str>,
Box<
dyn for<'ctx> Fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>
+ Send,
@@ -186,62 +164,12 @@ impl UserData for ClosureSearcher {
methods.add_meta_method(
MetaMethod::Call,
|lua_ctx: Context<'lua>, this, name: String| {
let name = name.as_str();
match this.modules.get(name) {
let name = Cow::from(name);
match this.modules.get(&name) {
Some(ref closure) => Ok(Value::Function(closure(
lua_ctx,
lua_ctx.registry_value::<Table>(&this.globals)?,
name,
)?)),
None => Ok(Value::Nil),
}
},
);
}
}
/// Like `ClosureSearcher`, but with `&'static str` keys in `modules`.
pub struct StaticClosureSearcher {
modules: HashMap<
&'static str,
Box<
dyn for<'ctx> Fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>
+ Send,
>,
>,
globals: RegistryKey,
}
impl StaticClosureSearcher {
pub fn new(
modules: HashMap<
&'static str,
Box<
dyn for<'ctx> Fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>
+ Send,
>,
>,
globals: RegistryKey,
) -> Self {
Self { modules, globals }
}
}
impl UserData for StaticClosureSearcher {
fn add_methods<'lua, M>(methods: &mut M)
where
M: UserDataMethods<'lua, Self>,
{
methods.add_meta_method(
MetaMethod::Call,
|lua_ctx: Context<'lua>, this, name: String| {
let name = name.as_str();
match this.modules.get(name) {
Some(ref closure) => Ok(Value::Function(closure(
lua_ctx,
lua_ctx.registry_value::<Table>(&this.globals)?,
name,
name.as_ref(),
)?)),
None => Ok(Value::Nil),
}
@@ -267,7 +195,7 @@ pub struct FunctionSearcher {
/// Functions must return an `rlua::Result`-wrapped `Function`. This `Function`
/// acts as the module loader.
modules: HashMap<
String,
Cow<'static, str>,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
>,
@@ -277,7 +205,7 @@ pub struct FunctionSearcher {
impl FunctionSearcher {
pub fn new(
modules: HashMap<
String,
Cow<'static, str>,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
>,
globals: RegistryKey,
@@ -294,56 +222,12 @@ impl UserData for FunctionSearcher {
methods.add_meta_method(
MetaMethod::Call,
|lua_ctx: Context<'lua>, this, name: String| {
let name = name.as_str();
match this.modules.get(name) {
let name = Cow::from(name);
match this.modules.get(&name) {
Some(ref function) => Ok(Value::Function(function(
lua_ctx,
lua_ctx.registry_value::<Table>(&this.globals)?,
name,
)?)),
None => Ok(Value::Nil),
}
},
);
}
}
/// Like `FunctionSearcher`, but with `&'static str` keys in `modules`.
pub struct StaticFunctionSearcher {
modules: HashMap<
&'static str,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
>,
globals: RegistryKey,
}
impl StaticFunctionSearcher {
pub fn new(
modules: HashMap<
&'static str,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
>,
globals: RegistryKey,
) -> Self {
Self { modules, globals }
}
}
impl UserData for StaticFunctionSearcher {
fn add_methods<'lua, M>(methods: &mut M)
where
M: UserDataMethods<'lua, Self>,
{
methods.add_meta_method(
MetaMethod::Call,
|lua_ctx: Context<'lua>, this, name: String| {
let name = name.as_str();
match this.modules.get(name) {
Some(ref function) => Ok(Value::Function(function(
lua_ctx,
lua_ctx.registry_value::<Table>(&this.globals)?,
name,
name.as_ref(),
)?)),
None => Ok(Value::Nil),
}
@@ -357,15 +241,11 @@ pub trait AddSearcher {
/// Add a `HashMap` of Lua modules indexed by module name to Luas
/// `package.searchers` table in an `rlua::Context`, with lookup functionality
/// provided by the `rlua_searcher::Searcher` struct.
fn add_searcher(&self, modules: HashMap<String, String>) -> Result<()>;
/// Like `add_searcher`, but with Fennel source code encoded as `&'static str`
/// to facilitate compile-time includes.
fn add_static_searcher(&self, modules: HashMap<&'static str, &'static str>) -> Result<()>;
fn add_searcher(&self, modules: HashMap<Cow<'static, str>, Cow<'static, str>>) -> Result<()>;
/// Like `add_searcher`, but with `modules` values given as paths to files containing
/// Lua source code to facilitate module reloading.
fn add_path_searcher<P>(&self, modules: HashMap<String, P>) -> Result<()>
fn add_path_searcher<P>(&self, modules: HashMap<Cow<'static, str>, P>) -> Result<()>
where
P: 'static + AsRef<Path> + Send;
@@ -373,7 +253,7 @@ pub trait AddSearcher {
/// source code to Lua.
fn add_path_searcher_poly<P>(
&self,
modules: HashMap<String, P>,
modules: HashMap<Cow<'static, str>, P>,
transform: Box<dyn Fn(PathBuf) -> rlua::Result<String> + Send>,
) -> Result<()>
where
@@ -383,19 +263,7 @@ pub trait AddSearcher {
fn add_closure_searcher(
&self,
modules: HashMap<
String,
Box<
dyn for<'ctx> Fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>
+ Send,
>,
>,
) -> Result<()>;
/// Like `add_closure_searcher`, but with `&'static str` keys in `modules`.
fn add_static_closure_searcher(
&self,
modules: HashMap<
&'static str,
Cow<'static, str>,
Box<
dyn for<'ctx> Fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>
+ Send,
@@ -407,23 +275,14 @@ pub trait AddSearcher {
fn add_function_searcher(
&self,
modules: HashMap<
String,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
>,
) -> Result<()>;
/// Like `add_function_searcher`, but with `&'static str` keys in `modules`.
fn add_static_function_searcher(
&self,
modules: HashMap<
&'static str,
Cow<'static, str>,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
>,
) -> Result<()>;
}
impl<'a> AddSearcher for Context<'a> {
fn add_searcher(&self, modules: HashMap<String, String>) -> Result<()> {
fn add_searcher(&self, modules: HashMap<Cow<'static, str>, Cow<'static, str>>) -> Result<()> {
let globals = self.globals();
let searchers: Table = globals.get::<_, Table>("package")?.get("searchers")?;
let registry_key = self.create_registry_value(globals)?;
@@ -433,17 +292,7 @@ impl<'a> AddSearcher for Context<'a> {
.map_err(|e| e.into())
}
fn add_static_searcher(&self, modules: HashMap<&'static str, &'static str>) -> Result<()> {
let globals = self.globals();
let searchers: Table = globals.get::<_, Table>("package")?.get("searchers")?;
let registry_key = self.create_registry_value(globals)?;
let searcher = StaticSearcher::new(modules, registry_key);
searchers
.set(searchers.len()? + 1, searcher)
.map_err(|e| e.into())
}
fn add_path_searcher<P>(&self, modules: HashMap<String, P>) -> Result<()>
fn add_path_searcher<P>(&self, modules: HashMap<Cow<'static, str>, P>) -> Result<()>
where
P: 'static + AsRef<Path> + Send,
{
@@ -460,7 +309,7 @@ impl<'a> AddSearcher for Context<'a> {
fn add_path_searcher_poly<P>(
&self,
modules: HashMap<String, P>,
modules: HashMap<Cow<'static, str>, P>,
transform: Box<dyn Fn(PathBuf) -> rlua::Result<String> + Send>,
) -> Result<()>
where
@@ -478,7 +327,7 @@ impl<'a> AddSearcher for Context<'a> {
fn add_closure_searcher(
&self,
modules: HashMap<
String,
Cow<'static, str>,
Box<
dyn for<'ctx> Fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>
+ Send,
@@ -494,29 +343,10 @@ impl<'a> AddSearcher for Context<'a> {
.map_err(|e| e.into())
}
fn add_static_closure_searcher(
&self,
modules: HashMap<
&'static str,
Box<
dyn for<'ctx> Fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>
+ Send,
>,
>,
) -> Result<()> {
let globals = self.globals();
let searchers: Table = globals.get::<_, Table>("package")?.get("searchers")?;
let registry_key = self.create_registry_value(globals)?;
let searcher = StaticClosureSearcher::new(modules, registry_key);
searchers
.set(searchers.len()? + 1, searcher)
.map_err(|e| e.into())
}
fn add_function_searcher(
&self,
modules: HashMap<
String,
Cow<'static, str>,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
>,
) -> Result<()> {
@@ -528,20 +358,4 @@ impl<'a> AddSearcher for Context<'a> {
.set(searchers.len()? + 1, searcher)
.map_err(|e| e.into())
}
fn add_static_function_searcher(
&self,
modules: HashMap<
&'static str,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
>,
) -> Result<()> {
let globals = self.globals();
let searchers: Table = globals.get::<_, Table>("package")?.get("searchers")?;
let registry_key = self.create_registry_value(globals)?;
let searcher = StaticFunctionSearcher::new(modules, registry_key);
searchers
.set(searchers.len()? + 1, searcher)
.map_err(|e| e.into())
}
}