valkey_module/
digest.rs

1use crate::{raw, ValkeyString};
2
3use std::os::raw::{c_char, c_int, c_longlong};
4
5/// `Digest` is a high-level rust interface to the Valkey module C API
6/// abstracting away the raw C ffi calls.
7pub struct Digest {
8    pub dig: *mut raw::RedisModuleDigest,
9}
10
11impl Digest {
12    pub const fn new(dig: *mut raw::RedisModuleDigest) -> Self {
13        Self { dig }
14    }
15
16    /// Returns the key name of this [`Digest`].
17    ///
18    /// # Panics
19    ///
20    /// Will panic if `RedisModule_GetKeyNameFromDigest` is missing in redismodule.h
21    pub fn get_key_name(&self) -> ValkeyString {
22        ValkeyString::new(None, unsafe {
23            raw::RedisModule_GetKeyNameFromDigest
24                .expect("RedisModule_GetKeyNameFromDigest is not available.")(self.dig)
25            .cast_mut()
26        })
27    }
28
29    /// Returns the database ID of this [`Digest`].
30    ///
31    /// # Panics
32    ///
33    /// Will panic if `RedisModule_GetDbIdFromDigest` is missing in redismodule.h
34    pub fn get_db_id(&self) -> c_int {
35        unsafe {
36            raw::RedisModule_GetDbIdFromDigest
37                .expect("RedisModule_GetDbIdFromDigest is not available.")(self.dig)
38        }
39    }
40
41    /// Adds a new element to this [`Digest`].
42    ///
43    /// # Panics
44    ///
45    /// Will panic if `RedisModule_DigestAddStringBuffer` is missing in redismodule.h
46    pub fn add_string_buffer(&mut self, ele: &[u8]) {
47        unsafe {
48            raw::RedisModule_DigestAddStringBuffer
49                .expect("RedisModule_DigestAddStringBuffer is not available.")(
50                self.dig,
51                ele.as_ptr().cast::<c_char>(),
52                ele.len(),
53            )
54        }
55    }
56
57    /// Similar to [`Digest::add_string_buffer`], but takes [`i64`].
58    ///
59    /// # Panics
60    ///
61    /// Will panic if `RedisModule_DigestAddLongLong` is missing in redismodule.h
62    pub fn add_long_long(&mut self, ll: c_longlong) {
63        unsafe {
64            raw::RedisModule_DigestAddLongLong
65                .expect("RedisModule_DigestAddLongLong is not available.")(self.dig, ll)
66        }
67    }
68
69    /// Ends the current sequence in this [`Digest`].
70    ///
71    /// # Panics
72    ///
73    /// Will panic if `RedisModule_DigestEndSequence` is missing in redismodule.h
74    pub fn end_sequence(&mut self) {
75        unsafe {
76            raw::RedisModule_DigestEndSequence
77                .expect("RedisModule_DigestEndSequence is not available.")(self.dig)
78        }
79    }
80}