redis_module/
redismodule.rs

1use std::borrow::Borrow;
2use std::convert::TryFrom;
3use std::ffi::CString;
4use std::fmt::Display;
5use std::ops::Deref;
6use std::os::raw::{c_char, c_int, c_void};
7use std::ptr::NonNull;
8use std::slice;
9use std::str;
10use std::str::Utf8Error;
11use std::string::FromUtf8Error;
12use std::{fmt, ptr};
13
14use serde::de::{Error, SeqAccess};
15
16pub use crate::raw;
17pub use crate::rediserror::RedisError;
18pub use crate::redisvalue::RedisValue;
19use crate::Context;
20
21/// A short-hand type that stores a [std::result::Result] with custom
22/// type and [RedisError].
23pub type RedisResult<T = RedisValue> = Result<T, RedisError>;
24/// A [RedisResult] with [RedisValue].
25pub type RedisValueResult = RedisResult<RedisValue>;
26
27impl From<RedisValue> for RedisValueResult {
28    fn from(v: RedisValue) -> Self {
29        Ok(v)
30    }
31}
32
33impl From<RedisError> for RedisValueResult {
34    fn from(v: RedisError) -> Self {
35        Err(v)
36    }
37}
38
39pub const REDIS_OK: RedisValueResult = Ok(RedisValue::SimpleStringStatic("OK"));
40pub const TYPE_METHOD_VERSION: u64 = raw::REDISMODULE_TYPE_METHOD_VERSION as u64;
41
42pub trait NextArg {
43    fn next_arg(&mut self) -> Result<RedisString, RedisError>;
44    fn next_string(&mut self) -> Result<String, RedisError>;
45    fn next_str<'a>(&mut self) -> Result<&'a str, RedisError>;
46    fn next_i64(&mut self) -> Result<i64, RedisError>;
47    fn next_u64(&mut self) -> Result<u64, RedisError>;
48    fn next_f64(&mut self) -> Result<f64, RedisError>;
49    fn done(&mut self) -> Result<(), RedisError>;
50}
51
52impl<T> NextArg for T
53where
54    T: Iterator<Item = RedisString>,
55{
56    #[inline]
57    fn next_arg(&mut self) -> Result<RedisString, RedisError> {
58        self.next().ok_or(RedisError::WrongArity)
59    }
60
61    #[inline]
62    fn next_string(&mut self) -> Result<String, RedisError> {
63        self.next()
64            .map_or(Err(RedisError::WrongArity), |v| Ok(v.to_string_lossy()))
65    }
66
67    #[inline]
68    fn next_str<'a>(&mut self) -> Result<&'a str, RedisError> {
69        self.next()
70            .map_or(Err(RedisError::WrongArity), |v| v.try_as_str())
71    }
72
73    #[inline]
74    fn next_i64(&mut self) -> Result<i64, RedisError> {
75        self.next()
76            .map_or(Err(RedisError::WrongArity), |v| v.parse_integer())
77    }
78
79    #[inline]
80    fn next_u64(&mut self) -> Result<u64, RedisError> {
81        self.next()
82            .map_or(Err(RedisError::WrongArity), |v| v.parse_unsigned_integer())
83    }
84
85    #[inline]
86    fn next_f64(&mut self) -> Result<f64, RedisError> {
87        self.next()
88            .map_or(Err(RedisError::WrongArity), |v| v.parse_float())
89    }
90
91    /// Return an error if there are any more arguments
92    #[inline]
93    fn done(&mut self) -> Result<(), RedisError> {
94        self.next().map_or(Ok(()), |_| Err(RedisError::WrongArity))
95    }
96}
97
98#[allow(clippy::not_unsafe_ptr_arg_deref)]
99pub fn decode_args(
100    ctx: *mut raw::RedisModuleCtx,
101    argv: *mut *mut raw::RedisModuleString,
102    argc: c_int,
103) -> Vec<RedisString> {
104    if argv.is_null() {
105        return Vec::new();
106    }
107    unsafe { slice::from_raw_parts(argv, argc as usize) }
108        .iter()
109        .map(|&arg| RedisString::new(NonNull::new(ctx), arg))
110        .collect()
111}
112
113///////////////////////////////////////////////////
114
115#[derive(Debug)]
116pub struct RedisString {
117    ctx: *mut raw::RedisModuleCtx,
118    pub inner: *mut raw::RedisModuleString,
119}
120
121impl RedisString {
122    pub(crate) fn take(mut self) -> *mut raw::RedisModuleString {
123        let inner = self.inner;
124        self.inner = std::ptr::null_mut();
125        inner
126    }
127
128    pub fn new(
129        ctx: Option<NonNull<raw::RedisModuleCtx>>,
130        inner: *mut raw::RedisModuleString,
131    ) -> Self {
132        let ctx = ctx.map_or(std::ptr::null_mut(), |v| v.as_ptr());
133        raw::string_retain_string(ctx, inner);
134        Self { ctx, inner }
135    }
136
137    /// In general, [RedisModuleString] is none atomic ref counted object.
138    /// So it is not safe to clone it if Redis GIL is not held.
139    /// [Self::safe_clone] gets a context reference which indicates that Redis GIL is held.
140    pub fn safe_clone(&self, _ctx: &Context) -> Self {
141        // RedisString are *not* atomic ref counted, so we must get a lock indicator to clone them.
142        // Alos notice that Redis allows us to create RedisModuleString with NULL context
143        // so we use [std::ptr::null_mut()] instead of the curren RedisString context.
144        // We do this because we can not promise the new RedisString will not outlive the current
145        // context and we want them to be independent.
146        raw::string_retain_string(ptr::null_mut(), self.inner);
147        Self {
148            ctx: ptr::null_mut(),
149            inner: self.inner,
150        }
151    }
152
153    #[allow(clippy::not_unsafe_ptr_arg_deref)]
154    pub fn create<T: Into<Vec<u8>>>(ctx: Option<NonNull<raw::RedisModuleCtx>>, s: T) -> Self {
155        let ctx = ctx.map_or(std::ptr::null_mut(), |v| v.as_ptr());
156        let str = CString::new(s).unwrap();
157        let inner = unsafe {
158            raw::RedisModule_CreateString.unwrap()(ctx, str.as_ptr(), str.as_bytes().len())
159        };
160
161        Self { ctx, inner }
162    }
163
164    #[allow(clippy::not_unsafe_ptr_arg_deref)]
165    pub fn create_from_slice(ctx: *mut raw::RedisModuleCtx, s: &[u8]) -> Self {
166        let inner = unsafe {
167            raw::RedisModule_CreateString.unwrap()(ctx, s.as_ptr().cast::<c_char>(), s.len())
168        };
169
170        Self { ctx, inner }
171    }
172
173    pub const fn from_redis_module_string(
174        ctx: *mut raw::RedisModuleCtx,
175        inner: *mut raw::RedisModuleString,
176    ) -> Self {
177        // Need to avoid string_retain_string
178        Self { ctx, inner }
179    }
180
181    #[allow(clippy::not_unsafe_ptr_arg_deref)]
182    pub fn from_ptr<'a>(ptr: *const raw::RedisModuleString) -> Result<&'a str, Utf8Error> {
183        str::from_utf8(Self::string_as_slice(ptr))
184    }
185
186    pub fn append(&mut self, s: &str) -> raw::Status {
187        raw::string_append_buffer(self.ctx, self.inner, s)
188    }
189
190    #[must_use]
191    pub fn len(&self) -> usize {
192        let mut len: usize = 0;
193        raw::string_ptr_len(self.inner, &mut len);
194        len
195    }
196
197    #[must_use]
198    pub fn is_empty(&self) -> bool {
199        let mut len: usize = 0;
200        raw::string_ptr_len(self.inner, &mut len);
201        len == 0
202    }
203
204    pub fn try_as_str<'a>(&self) -> Result<&'a str, RedisError> {
205        Self::from_ptr(self.inner).map_err(|_| RedisError::Str("Couldn't parse as UTF-8 string"))
206    }
207
208    #[must_use]
209    pub fn as_slice(&self) -> &[u8] {
210        Self::string_as_slice(self.inner)
211    }
212
213    #[allow(clippy::not_unsafe_ptr_arg_deref)]
214    pub fn string_as_slice<'a>(ptr: *const raw::RedisModuleString) -> &'a [u8] {
215        let mut len: libc::size_t = 0;
216        let bytes = unsafe { raw::RedisModule_StringPtrLen.unwrap()(ptr, &mut len) };
217
218        unsafe { slice::from_raw_parts(bytes.cast::<u8>(), len) }
219    }
220
221    /// Performs lossy conversion of a `RedisString` into an owned `String. This conversion
222    /// will replace any invalid UTF-8 sequences with U+FFFD REPLACEMENT CHARACTER, which
223    /// looks like this: �.
224    ///
225    /// # Panics
226    ///
227    /// Will panic if `RedisModule_StringPtrLen` is missing in redismodule.h
228    #[must_use]
229    pub fn to_string_lossy(&self) -> String {
230        String::from_utf8_lossy(self.as_slice()).into_owned()
231    }
232
233    pub fn parse_unsigned_integer(&self) -> Result<u64, RedisError> {
234        let val = self.parse_integer()?;
235        u64::try_from(val)
236            .map_err(|_| RedisError::Str("Couldn't parse negative number as unsigned integer"))
237    }
238
239    pub fn parse_integer(&self) -> Result<i64, RedisError> {
240        let mut val: i64 = 0;
241        match raw::string_to_longlong(self.inner, &mut val) {
242            raw::Status::Ok => Ok(val),
243            raw::Status::Err => Err(RedisError::Str("Couldn't parse as integer")),
244        }
245    }
246
247    pub fn parse_float(&self) -> Result<f64, RedisError> {
248        let mut val: f64 = 0.0;
249        match raw::string_to_double(self.inner, &mut val) {
250            raw::Status::Ok => Ok(val),
251            raw::Status::Err => Err(RedisError::Str("Couldn't parse as float")),
252        }
253    }
254
255    // TODO: Redis allows storing and retrieving any arbitrary bytes.
256    // However rust's String and str can only store valid UTF-8.
257    // Implement these to allow non-utf8 bytes to be consumed:
258    // pub fn into_bytes(self) -> Vec<u8> {}
259    // pub fn as_bytes(&self) -> &[u8] {}
260}
261
262impl Drop for RedisString {
263    fn drop(&mut self) {
264        if !self.inner.is_null() {
265            unsafe {
266                raw::RedisModule_FreeString.unwrap()(self.ctx, self.inner);
267            }
268        }
269    }
270}
271
272impl PartialEq for RedisString {
273    fn eq(&self, other: &Self) -> bool {
274        self.cmp(other).is_eq()
275    }
276}
277
278impl Eq for RedisString {}
279
280impl PartialOrd for RedisString {
281    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
282        Some(self.cmp(other))
283    }
284}
285
286impl Ord for RedisString {
287    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
288        raw::string_compare(self.inner, other.inner)
289    }
290}
291
292impl core::hash::Hash for RedisString {
293    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
294        self.as_slice().hash(state);
295    }
296}
297
298impl Display for RedisString {
299    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
300        write!(f, "{}", self.to_string_lossy())
301    }
302}
303
304impl Borrow<str> for RedisString {
305    fn borrow(&self) -> &str {
306        // RedisString might not be UTF-8 safe
307        self.try_as_str().unwrap_or("<Invalid UTF-8 data>")
308    }
309}
310
311impl Clone for RedisString {
312    fn clone(&self) -> Self {
313        let inner =
314            // Redis allows us to create RedisModuleString with NULL context
315            // so we use [std::ptr::null_mut()] instead of the curren RedisString context.
316            // We do this because we can not promise the new RedisString will not outlive the current
317            // context and we want them to be independent.
318            unsafe { raw::RedisModule_CreateStringFromString.unwrap()(ptr::null_mut(), self.inner) };
319        Self::from_redis_module_string(ptr::null_mut(), inner)
320    }
321}
322
323impl From<RedisString> for String {
324    fn from(rs: RedisString) -> Self {
325        rs.to_string_lossy()
326    }
327}
328
329impl Deref for RedisString {
330    type Target = [u8];
331
332    fn deref(&self) -> &Self::Target {
333        self.as_slice()
334    }
335}
336
337impl From<RedisString> for Vec<u8> {
338    fn from(rs: RedisString) -> Self {
339        rs.as_slice().to_vec()
340    }
341}
342
343impl serde::Serialize for RedisString {
344    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
345    where
346        S: serde::Serializer,
347    {
348        serializer.serialize_bytes(self.as_slice())
349    }
350}
351
352struct RedisStringVisitor;
353
354impl<'de> serde::de::Visitor<'de> for RedisStringVisitor {
355    type Value = RedisString;
356
357    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
358        formatter.write_str("A bytes buffer")
359    }
360
361    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
362    where
363        E: Error,
364    {
365        Ok(RedisString::create(None, v))
366    }
367
368    fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
369    where
370        V: SeqAccess<'de>,
371    {
372        let mut v = if let Some(size_hint) = visitor.size_hint() {
373            Vec::with_capacity(size_hint)
374        } else {
375            Vec::new()
376        };
377        while let Some(elem) = visitor.next_element()? {
378            v.push(elem);
379        }
380
381        Ok(RedisString::create(None, v.as_slice()))
382    }
383}
384
385impl<'de> serde::Deserialize<'de> for RedisString {
386    fn deserialize<D>(deserializer: D) -> Result<RedisString, D::Error>
387    where
388        D: serde::Deserializer<'de>,
389    {
390        deserializer.deserialize_bytes(RedisStringVisitor)
391    }
392}
393
394///////////////////////////////////////////////////
395
396#[derive(Debug)]
397pub struct RedisBuffer {
398    buffer: *mut c_char,
399    len: usize,
400}
401
402impl RedisBuffer {
403    pub const fn new(buffer: *mut c_char, len: usize) -> Self {
404        Self { buffer, len }
405    }
406
407    pub fn to_string(&self) -> Result<String, FromUtf8Error> {
408        String::from_utf8(self.as_ref().to_vec())
409    }
410}
411
412impl AsRef<[u8]> for RedisBuffer {
413    fn as_ref(&self) -> &[u8] {
414        unsafe { slice::from_raw_parts(self.buffer as *const u8, self.len) }
415    }
416}
417
418impl Drop for RedisBuffer {
419    fn drop(&mut self) {
420        unsafe {
421            raw::RedisModule_Free.unwrap()(self.buffer.cast::<c_void>());
422        }
423    }
424}