Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hget macro alternative #101

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions src/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use crate::redismodule::REDIS_OK;
use crate::RedisError;
use crate::RedisResult;
use crate::RedisString;
use std::collections::HashMap;

/// `RedisKey` is an abstraction over a Redis key that allows readonly
/// operations.
Expand Down Expand Up @@ -81,13 +82,12 @@ impl RedisKey {
Ok(val)
}

pub fn hash_get(&self, field: &str) -> Result<Option<RedisString>, RedisError> {
let val = if self.is_null() {
None
} else {
hash_get_key(self.ctx, self.key_inner, field)
};
Ok(val)
pub fn hash_get(&self, fields: &[&str]) -> Result<HashMap<String, RedisString>, RedisError> {
if self.is_null() {
return Ok(HashMap::new());
}
let res = raw::hash_get_multi(self.ctx, self.key_inner, fields);
Ok(res)
}
}

Expand Down
42 changes: 42 additions & 0 deletions src/raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use std::slice;
pub use crate::redisraw::bindings::*;
use crate::RedisBuffer;
use crate::RedisString;
use std::collections::HashMap;

bitflags! {
pub struct KeyMode: c_int {
Expand Down Expand Up @@ -246,6 +247,47 @@ pub fn hash_get(key: *mut RedisModuleKey, field: &str) -> *mut RedisModuleString
res
}

pub fn hash_get_multi(
ctx: *mut RedisModuleCtx,
key: *mut RedisModuleKey,
fields: &[&str],
) -> HashMap<String, RedisString> {
// let res: *mut RedisModuleString = ptr::null_mut();
let values = vec![ptr::null_mut::<RedisModuleString>(); fields.len()];

match fields {
&[f0] => unsafe {
RedisModule_HashGet.unwrap()(
key,
REDISMODULE_HASH_CFIELDS as i32,
CString::new(f0).unwrap().as_ptr(),
&values[0],
ptr::null::<RedisModuleString>(),
);
},
&[f0, f1] => unsafe {
RedisModule_HashGet.unwrap()(
key,
REDISMODULE_HASH_CFIELDS as i32,
CString::new(f0).unwrap().as_ptr(),
&values[0],
CString::new(f1).unwrap().as_ptr(),
&values[1],
ptr::null::<RedisModuleString>(),
);
},
// Repeat for more fields using a macro
&[] => { /* TODO: Return empty result? */ }
&[_, ..] => { /* TODO: Panic? */ }
}

fields
.iter()
.zip(values.iter())
.map(|(&k, &v)| (k.to_string(), RedisString::new(ctx, v)))
.collect()
}

pub fn hash_set(key: *mut RedisModuleKey, field: &str, value: *mut RedisModuleString) -> Status {
unsafe {
RedisModule_HashSet.unwrap()(
Expand Down