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())
}
}

View File

@ -1,5 +1,6 @@
use rlua::{Context, Function, Lua, Table, UserData, UserDataMethods, Value};
use rlua_searcher::{AddSearcher, Result};
use std::borrow::Cow;
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
@ -7,10 +8,17 @@ use std::path::PathBuf;
#[test]
fn add_searcher_works() {
let lume = read_lume_to_string();
let name = "lume".to_string();
// These should end up in the same hash slot.
let name_owned = Cow::from("lume".to_string());
let name_ref = Cow::from("lume");
// `lume_ref` should overwrite `lume_owned`.
let lume_owned = Cow::from(read_lume_to_string());
let lume_ref = Cow::from(read_lume_to_str());
let mut map = HashMap::new();
map.insert(name, lume);
map.insert(name_owned, lume_owned);
map.insert(name_ref, lume_ref);
let lua = Lua::new();
@ -21,31 +29,37 @@ fn add_searcher_works() {
})
.unwrap();
assert_eq!("hello lume", hello);
}
assert_eq!("hello ref", hello);
// Repeat the experiment, but with an additional overwrite.
let name_owned = Cow::from("lume".to_string());
let name_ref = Cow::from("lume");
let lume_owned = Cow::from(read_lume_to_string());
let lume_ref = Cow::from(read_lume_to_str());
#[test]
fn add_static_searcher_works() {
let lume = read_lume_to_str();
let name = "lume";
let mut map = HashMap::new();
map.insert(name, lume);
map.insert(name_owned, lume_owned);
map.insert(name_ref, lume_ref);
let name_owned = Cow::from("lume".to_string());
let lume_owned = Cow::from(read_lume_to_string());
map.insert(name_owned, lume_owned);
let lua = Lua::new();
let hello = lua
.context::<_, Result<String>>(|lua_ctx| {
lua_ctx.add_static_searcher(map)?;
lua_ctx.add_searcher(map)?;
Ok(lua_ctx.load(r#"return require("lume")"#).eval()?)
})
.unwrap();
assert_eq!("hello lume", hello);
assert_eq!("hello owned", hello);
}
#[test]
fn add_path_searcher_works() {
let name = "lume".to_string();
let name = Cow::from("lume".to_string());
let path = PathBuf::new()
.join(std::env::var("CARGO_MANIFEST_DIR").unwrap())
.join("tests")
@ -68,7 +82,7 @@ fn add_path_searcher_works() {
#[test]
fn module_reloading_works() {
let name = "lume".to_string();
let name = Cow::from("lume".to_string());
let path = PathBuf::new()
.join(std::env::var("CARGO_MANIFEST_DIR").unwrap())
.join("tests")
@ -116,7 +130,7 @@ fn module_reloading_works() {
lua.context::<_, rlua::Result<()>>(|lua_ctx| {
let globals = lua_ctx.globals();
let loaded: Table = globals.get::<_, Table>("package")?.get("loaded")?;
loaded.set(name.clone(), Value::Nil)
loaded.set(name.as_ref(), Value::Nil)
})
.unwrap();
@ -146,7 +160,7 @@ fn module_reloading_works() {
lua.context::<_, rlua::Result<()>>(|lua_ctx| {
let globals = lua_ctx.globals();
let loaded: Table = globals.get::<_, Table>("package")?.get("loaded")?;
loaded.set(name, Value::Nil)
loaded.set(name.as_ref(), Value::Nil)
})
.unwrap();
@ -161,11 +175,11 @@ fn module_reloading_works() {
}
fn read_lume_to_string() -> String {
r#"return "hello lume""#.to_string()
r#"return "hello owned""#.to_string()
}
fn read_lume_to_str() -> &'static str {
r#"return "hello lume""#
r#"return "hello ref""#
}
#[test]
@ -173,7 +187,7 @@ fn add_closure_searcher_works() {
let lua = Lua::new();
let mut modules: HashMap<
String,
Cow<'static, str>,
Box<
dyn for<'ctx> Fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>
+ Send,
@ -197,7 +211,7 @@ fn add_closure_searcher_works() {
.into_function()?)
});
modules.insert("instrument".to_string(), instrument_loader);
modules.insert(Cow::from("instrument".to_string()), instrument_loader);
let sound = lua
.context::<_, Result<String>>(|lua_ctx| {
@ -220,58 +234,6 @@ fn add_closure_searcher_works() {
assert_eq!(sound, "The ukulele goes twang");
}
#[test]
fn add_static_closure_searcher_works() {
let lua = Lua::new();
let mut modules: HashMap<
&'static str,
Box<
dyn for<'ctx> Fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>
+ Send,
>,
> = HashMap::new();
let instrument_loader: Box<
dyn for<'ctx> Fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>> + Send,
> = Box::new(|lua_ctx, env, name| {
let globals = lua_ctx.globals();
let new = lua_ctx.create_function(|_, (name, sound): (String, String)| {
Ok(Instrument::new(name, sound))
})?;
let tbl = lua_ctx.create_table()?;
tbl.set("new", new)?;
globals.set("instrument", tbl)?;
Ok(lua_ctx
.load("return instrument")
.set_name(name)?
.set_environment(env)?
.into_function()?)
});
modules.insert("instrument", instrument_loader);
let sound = lua
.context::<_, Result<String>>(|lua_ctx| {
lua_ctx.add_static_closure_searcher(modules)?;
// Ensure global variable `instrument` is unset.
let nil: String = lua_ctx.load("return type(instrument)").eval()?;
assert_eq!(nil, "nil");
Ok(lua_ctx
.load(
r#"local instrument = require("instrument")
local ukulele = instrument.new("ukulele", "twang")
return ukulele:play()"#,
)
.eval()?)
})
.unwrap();
assert_eq!(sound, "The ukulele goes twang");
}
struct Instrument {
name: String,
sound: String,
@ -301,11 +263,11 @@ fn add_function_searcher_works() {
let lua = Lua::new();
let mut modules: HashMap<
String,
Cow<'static, str>,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
> = HashMap::new();
modules.insert("cartridge".to_string(), cartridge_loader);
modules.insert(Cow::from("cartridge".to_string()), cartridge_loader);
let title = lua
.context::<_, Result<String>>(|lua_ctx| {
@ -328,38 +290,6 @@ fn add_function_searcher_works() {
assert_eq!(title, "Super Smash Brothers 64");
}
#[test]
fn add_static_function_searcher_works() {
let lua = Lua::new();
let mut modules: HashMap<
&'static str,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
> = HashMap::new();
modules.insert("cartridge", cartridge_loader);
let title = lua
.context::<_, Result<String>>(|lua_ctx| {
lua_ctx.add_static_function_searcher(modules)?;
// Ensure global variable `cartridge` is unset.
let nil: String = lua_ctx.load("return type(cartridge)").eval()?;
assert_eq!(nil, "nil");
Ok(lua_ctx
.load(
r#"local cartridge = require("cartridge")
local smash = cartridge.pick()
return smash:play()"#,
)
.eval()?)
})
.unwrap();
assert_eq!(title, "Super Smash Brothers 64");
}
struct Cartridge {
title: String,
}