I'm building a Redis Module in Rust. I've found some good examples, but I'm stuck when dealing with interfacing a C function that is supposed to accept variadic arguments.
The Redis Module C SDK has a function called RedisModule_Call
which accepts a few specific arguments then n
arguments that represent a Redis command. From the Redis Module SDK documentation (in C):
RedisModuleCallReply *reply;
reply = RedisModule_Call(ctx,"INCR","sc",argv[1],"10");
RedisModule_Call
's first three arguments are specific, but the rest represent Redis commands that could easily have hundreds of arguments.
In Rust, I'm following the patterns in Redis-Cell which is a Redis module implemented (successfully) in Rust. The module is fantastic but has a very limited way of dealing with this particular problem. Effectively, it accepts up to three arguments in a somewhat brute force way:
pub fn call(&self, command: &str, args: &[&str]) -> Result<Reply, CellError> {
// ... code ...
let raw_reply = match args.len() {
1 => raw::call1::call(/* ... */),
2 => raw::call2::call(/* ... */),
// ...
These call1
and call2
functions are practically just stubs that handle the different argument lengths:
pub mod call2 {
use redis::raw;
pub fn call(
ctx: *mut raw::RedisModuleCtx,
cmdname: *const u8,
fmt: *const u8,
arg0: *mut raw::RedisModuleString,
arg1: *mut raw::RedisModuleString,
) -> *mut raw::RedisModuleCallReply {
unsafe { RedisModule_Call(ctx, cmdname, fmt, arg0, arg1) }
}
#[allow(improper_ctypes)]
extern "C" {
pub static RedisModule_Call: extern "C" fn(
ctx: *mut raw::RedisModuleCtx,
cmdname: *const u8,
fmt: *const u8,
arg0: *mut raw::RedisModuleString,
arg1: *mut raw::RedisModuleString,
) -> *mut raw::RedisModuleCallReply;
}
}
I need to be able to pass in n
arguments, with n
being determined at run time, so this method of hard coding isn't practical. I know Rust has limited support for variadic functions and I've been doing some reading about RFC 2137, but I'm not sure this applies.
I'm looking for a way to apply an argument vector to the end of RedisModule_Call
or something like a spread syntax for the arguments. I'm relatively new to Rust but I've searched and searched and I can't seem to find any way to scratch this itch in Rust.
To clarify - I can pass arguments into RedisModule_Call
(which is variadic) no problem, but I can't find a syntactical way to pass in a variable number of arguments in Rust into the C function. What I'm trying to accomplish is something like this:
impl Redis {
pub fn call(&self, command: &str, args: &[&str]) -> Result<Reply, CellError> {
/* ... */
unsafe { RedisModule_Call(ctx, cmdname, fmt, ...args) }
/* ... */
Where ...args
is some sort of black magic to that would allow args to represent 1 argument or 100 which would be the equivalent of RedisModule_Call(ctx, cmdname, fmt, args[0], args[1] /* ... and so on */)
.
See Question&Answers more detail:
os