|
| 1 | +#[macro_use] |
| 2 | +extern crate redis_module; |
| 3 | + |
| 4 | +use redis_module::{Context, RedisError, RedisResult, RedisValue}; |
| 5 | + |
| 6 | +fn keys_pos(ctx: &Context, args: Vec<String>) -> RedisResult { |
| 7 | + // Number of args (excluding command name) must be even |
| 8 | + if (args.len() - 1) % 2 != 0 { |
| 9 | + return Err(RedisError::WrongArity); |
| 10 | + } |
| 11 | + |
| 12 | + if ctx.is_keys_position_request() { |
| 13 | + for i in 1..args.len() { |
| 14 | + if (i - 1) % 2 == 0 { |
| 15 | + ctx.key_at_pos(i as i32); |
| 16 | + } |
| 17 | + } |
| 18 | + return Ok(RedisValue::NoReply); |
| 19 | + } |
| 20 | + |
| 21 | + let reply: Vec<_> = args.iter().skip(1).step_by(2).collect(); |
| 22 | + |
| 23 | + return Ok(reply.into()); |
| 24 | +} |
| 25 | + |
| 26 | +////////////////////////////////////////////////////// |
| 27 | + |
| 28 | +redis_module! { |
| 29 | + name: "keys_pos", |
| 30 | + version: 1, |
| 31 | + data_types: [], |
| 32 | + commands: [ |
| 33 | + ["keys_pos", keys_pos, "getkeys-api", 1, 1, 1], |
| 34 | + ], |
| 35 | +} |
| 36 | + |
| 37 | +////////////////////////////////////////////////////// |
| 38 | + |
| 39 | +#[cfg(test)] |
| 40 | +mod tests { |
| 41 | + use super::*; |
| 42 | + use redis_module::RedisValue; |
| 43 | + |
| 44 | + fn into_string_vec(args: &[&str]) -> Vec<String> { |
| 45 | + args.iter().map(|v| String::from(*v)).collect() |
| 46 | + } |
| 47 | + |
| 48 | + fn into_redisvalue_vec(args: &[&str]) -> Vec<RedisValue> { |
| 49 | + args.iter() |
| 50 | + .map(|&s| RedisValue::BulkString(s.to_string())) |
| 51 | + .collect() |
| 52 | + } |
| 53 | + |
| 54 | + #[test] |
| 55 | + fn test_keys_pos() { |
| 56 | + let result = keys_pos( |
| 57 | + &Context::dummy(), |
| 58 | + into_string_vec(&["keys_pos", "a", "1", "b", "2"]), |
| 59 | + ); |
| 60 | + |
| 61 | + match result { |
| 62 | + Ok(RedisValue::Array(v)) => { |
| 63 | + assert_eq!(v, into_redisvalue_vec(&["a", "b"])); |
| 64 | + } |
| 65 | + _ => assert!(false, "Bad result: {:?}", result), |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + #[test] |
| 70 | + fn test_keys_pos_bad_args() { |
| 71 | + let result = keys_pos( |
| 72 | + &Context::dummy(), |
| 73 | + into_string_vec(&["keys_pos", "a", "1", "b"]), |
| 74 | + ); |
| 75 | + |
| 76 | + match result { |
| 77 | + Err(RedisError::WrongArity) => (), |
| 78 | + _ => assert!(false, "Bad result: {:?}", result), |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments