Skip to main content

redis_tower_commands/
hyperloglog.rs

1//! Probabilistic cardinality estimation with HyperLogLog.
2//!
3//! [`PfAdd`] reports whether registers changed, [`PfCount`] returns an
4//! estimated cardinality, and [`PfMerge`] combines sketches. Values are
5//! binary-safe; estimates are intentionally approximate.
6//!
7//! ```
8//! use redis_tower_commands::{PfAdd, PfCount};
9//! use redis_tower_core::Command;
10//!
11//! let add = PfAdd::new("visitors", "user:1");
12//! let count = PfCount::new("visitors");
13//! assert_eq!((add.name(), count.name()), ("PFADD", "PFCOUNT"));
14//! ```
15//!
16//! See the [command cookbook] for typed execution and response handling.
17//!
18//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#typed-commands-and-response-shapes
19
20use crate::CommandArg;
21use redis_tower_core::{Command, Frame, RedisError};
22use redis_tower_protocol::helpers::{array, bulk};
23
24/// PFADD key element [element ...]
25///
26/// Adds the specified elements to the HyperLogLog at `key`.
27/// Returns `true` if the internal representation was altered (i.e., the
28/// estimated cardinality changed), `false` otherwise.
29#[derive(Clone)]
30pub struct PfAdd {
31    key: CommandArg,
32    elements: Vec<CommandArg>,
33}
34
35impl PfAdd {
36    /// Create a new [`PfAdd`] command.
37    pub fn new(key: impl Into<CommandArg>, element: impl Into<CommandArg>) -> Self {
38        Self {
39            key: key.into(),
40            elements: vec![element.into()],
41        }
42    }
43
44    /// Create the [`PfAdd`] command for the supplied elements.
45    pub fn elements(
46        key: impl Into<CommandArg>,
47        elements: impl IntoIterator<Item = impl Into<CommandArg>>,
48    ) -> Self {
49        Self {
50            key: key.into(),
51            elements: elements.into_iter().map(Into::into).collect(),
52        }
53    }
54}
55
56impl Command for PfAdd {
57    type Response = bool;
58
59    fn to_frame(&self) -> Frame {
60        let mut args = vec![bulk("PFADD"), bulk(&self.key)];
61        for element in &self.elements {
62            args.push(bulk(element));
63        }
64        array(args)
65    }
66
67    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
68        match frame {
69            Frame::Integer(n) => Ok(n == 1),
70            Frame::Boolean(b) => Ok(b),
71            other => Err(RedisError::UnexpectedResponse {
72                expected: "integer or boolean",
73                actual: format!("{other:?}"),
74            }),
75        }
76    }
77
78    fn name(&self) -> &str {
79        "PFADD"
80    }
81}
82
83/// PFCOUNT key [key ...]
84///
85/// Returns the approximate cardinality of the set(s) observed by the
86/// HyperLogLog at the specified key(s). When called with multiple keys,
87/// returns the approximate cardinality of the union.
88#[derive(Clone)]
89pub struct PfCount {
90    keys: Vec<CommandArg>,
91}
92
93impl PfCount {
94    /// Create a new [`PfCount`] command.
95    pub fn new(key: impl Into<CommandArg>) -> Self {
96        Self {
97            keys: vec![key.into()],
98        }
99    }
100
101    /// Create the [`PfCount`] command for the supplied keys.
102    pub fn keys(keys: impl IntoIterator<Item = impl Into<CommandArg>>) -> Self {
103        Self {
104            keys: keys.into_iter().map(Into::into).collect(),
105        }
106    }
107}
108
109impl Command for PfCount {
110    type Response = i64;
111
112    fn to_frame(&self) -> Frame {
113        let mut args = vec![bulk("PFCOUNT")];
114        for key in &self.keys {
115            args.push(bulk(key));
116        }
117        array(args)
118    }
119
120    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
121        match frame {
122            Frame::Integer(n) => Ok(n),
123            other => Err(RedisError::UnexpectedResponse {
124                expected: "integer",
125                actual: format!("{other:?}"),
126            }),
127        }
128    }
129
130    fn name(&self) -> &str {
131        "PFCOUNT"
132    }
133}
134
135/// PFMERGE destkey sourcekey [sourcekey ...]
136///
137/// Merges one or more HyperLogLog values into a single key.
138/// The destination key will hold the union of the source keys.
139#[derive(Clone)]
140pub struct PfMerge {
141    destkey: CommandArg,
142    sourcekeys: Vec<CommandArg>,
143}
144
145impl PfMerge {
146    /// Create a new [`PfMerge`] command.
147    pub fn new(
148        destkey: impl Into<CommandArg>,
149        sourcekeys: impl IntoIterator<Item = impl Into<CommandArg>>,
150    ) -> Self {
151        Self {
152            destkey: destkey.into(),
153            sourcekeys: sourcekeys.into_iter().map(Into::into).collect(),
154        }
155    }
156}
157
158impl Command for PfMerge {
159    type Response = ();
160
161    fn to_frame(&self) -> Frame {
162        let mut args = vec![bulk("PFMERGE"), bulk(&self.destkey)];
163        for key in &self.sourcekeys {
164            args.push(bulk(key));
165        }
166        array(args)
167    }
168
169    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
170        match frame {
171            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
172            other => Err(RedisError::UnexpectedResponse {
173                expected: "OK",
174                actual: format!("{other:?}"),
175            }),
176        }
177    }
178
179    fn name(&self) -> &str {
180        "PFMERGE"
181    }
182}