1use redis::ToRedisArgs;
2use std::borrow::Cow;
3use std::fmt::{Debug, Display, Write};
4
5#[derive(Debug, Clone)]
6#[non_exhaustive]
7pub enum Key<'a> {
8 String(String),
9 Str(&'a str),
10 Usize(usize),
11 Isize(isize),
12 #[cfg(feature = "uuid")]
13 #[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
14 Uuid(uuid::Uuid),
15 Pair(Cow<'a, str>, Cow<'a, str>),
16 Triple(Cow<'a, str>, Cow<'a, str>, Cow<'a, str>),
17}
18
19impl<'a> Key<'a> {
20 pub fn pair(value1: impl Into<Cow<'a, str>>, value2: impl Into<Cow<'a, str>>) -> Self {
21 Self::Pair(value1.into(), value2.into())
22 }
23
24 pub fn triple(
25 value1: impl Into<Cow<'a, str>>,
26 value2: impl Into<Cow<'a, str>>,
27 value3: impl Into<Cow<'a, str>>,
28 ) -> Self {
29 Self::Triple(value1.into(), value2.into(), value3.into())
30 }
31}
32
33impl<'a> From<&'a str> for Key<'a> {
34 fn from(value: &'a str) -> Self {
35 Self::Str(value)
36 }
37}
38
39impl From<String> for Key<'_> {
40 fn from(value: String) -> Self {
41 Self::String(value)
42 }
43}
44
45impl From<usize> for Key<'_> {
46 fn from(value: usize) -> Self {
47 Self::Usize(value)
48 }
49}
50
51impl From<isize> for Key<'_> {
52 fn from(value: isize) -> Self {
53 Self::Isize(value)
54 }
55}
56
57impl Display for Key<'_> {
58 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59 match self {
60 Self::String(value) => Display::fmt(value, f),
61 Self::Str(value) => Display::fmt(*value, f),
62 Self::Usize(value) => Display::fmt(value, f),
63 Self::Isize(value) => Display::fmt(value, f),
64 #[cfg(feature = "uuid")]
65 Self::Uuid(value) => Display::fmt(value, f),
66 Self::Pair(value1, value2) => {
67 f.write_char('(')?;
68 Display::fmt(value1.as_ref(), f)?;
69 f.write_str(", ")?;
70 Display::fmt(value2.as_ref(), f)?;
71 f.write_char(')')
72 }
73 Self::Triple(value1, value2, value3) => {
74 f.write_char('(')?;
75 Display::fmt(value1.as_ref(), f)?;
76 f.write_str(", ")?;
77 Display::fmt(value2.as_ref(), f)?;
78 f.write_str(", ")?;
79 Display::fmt(value3.as_ref(), f)?;
80 f.write_char(')')
81 }
82 }
83 }
84}
85
86impl ToRedisArgs for Key<'_> {
87 fn write_redis_args<W>(&self, out: &mut W)
88 where
89 W: ?Sized + redis::RedisWrite,
90 {
91 match self {
92 Self::String(value) => value.write_redis_args(out),
93 Self::Str(value) => (*value).write_redis_args(out),
94 Self::Usize(value) => value.write_redis_args(out),
95 Self::Isize(value) => value.write_redis_args(out),
96 #[cfg(feature = "uuid")]
97 Self::Uuid(value) => value.write_redis_args(out),
98 impl_display => out.write_arg_fmt(impl_display),
99 }
100 }
101}