-
Notifications
You must be signed in to change notification settings - Fork 13
/
utils.rs
240 lines (201 loc) Β· 5.8 KB
/
utils.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
use crate::error::{RedisParseError, RedisProtocolError, RedisProtocolErrorKind};
use core::str;
use crc16::{State, XMODEM};
use crate::types::REDIS_CLUSTER_SLOTS;
#[cfg(feature = "bytes")]
use bytes::BytesMut;
/// Returns the number of bytes necessary to encode a string representation of `d`.
#[cfg(feature = "std")]
pub fn digits_in_number(d: usize) -> usize {
if d == 0 {
return 1;
}
((d as f64).log10()).floor() as usize + 1
}
/// Returns the number of bytes necessary to encode a string representation of `d`.
#[cfg(feature = "libm")]
pub fn digits_in_number(d: usize) -> usize {
if d == 0 {
return 1;
}
libm::floor(libm::log10(d as f64)) as usize + 1
}
pub fn isize_to_usize<T>(val: isize) -> Result<usize, RedisParseError<T>> {
if val >= 0 {
Ok(val as usize)
} else {
Err(RedisParseError::new_custom("isize_to_usize", "Invalid length."))
}
}
/// Extend the buffer by `amt`.
#[cfg(feature = "bytes")]
#[cfg_attr(docsrs, doc(cfg(feature = "bytes")))]
pub fn zero_extend(buf: &mut BytesMut, amt: usize) {
buf.resize(buf.len() + amt, 0);
}
/// Whether an error payload is a `MOVED` or `ASK` redirection.
pub(crate) fn is_redirection(payload: &str) -> bool {
if payload.starts_with("MOVED") || payload.starts_with("ASK") {
payload.split(' ').count() == 3
} else {
false
}
}
/// Perform a crc16 XMODEM operation against a string slice.
fn crc16_xmodem(key: &[u8]) -> u16 {
State::<XMODEM>::calculate(key) % REDIS_CLUSTER_SLOTS
}
/// Map a key to the corresponding cluster key slot.
///
/// ```ignore
/// $ redis-cli cluster keyslot "8xjx7vWrfPq54mKfFD3Y1CcjjofpnAcQ"
/// (integer) 5458
/// ```
///
/// ```
/// # use redis_protocol::redis_keyslot;
/// assert_eq!(redis_keyslot(b"8xjx7vWrfPq54mKfFD3Y1CcjjofpnAcQ"), 5458);
/// ```
pub fn redis_keyslot(key: &[u8]) -> u16 {
let (mut i, mut j): (Option<usize>, Option<usize>) = (None, None);
for (idx, c) in key.iter().enumerate() {
if *c == b'{' {
i = Some(idx);
break;
}
}
if i.is_none() || (i.is_some() && i.unwrap() == key.len() - 1) {
return crc16_xmodem(key);
}
let i = i.unwrap();
for (idx, c) in key[i + 1 ..].iter().enumerate() {
if *c == b'}' {
j = Some(idx);
break;
}
}
if j.is_none() {
return crc16_xmodem(key);
}
let j = j.unwrap();
if i + j == key.len() || j == 0 {
crc16_xmodem(key)
} else {
crc16_xmodem(&key[i + 1 .. i + j + 1])
}
}
/// Convert a string to a double, supporting "nan", "+inf" and "-inf".
pub fn str_to_f64(s: &str) -> Result<f64, RedisProtocolError> {
// this is changing in newer versions of redis to lose the "+" prefix
match s {
"+inf" | "inf" => Ok(f64::INFINITY),
"-inf" => Ok(f64::NEG_INFINITY),
"nan" => Ok(f64::NAN),
_ => s.parse::<f64>().map_err(|_| {
RedisProtocolError::new(
RedisProtocolErrorKind::Unknown,
"Could not convert to floating point value.",
)
}),
}
}
/// Convert bytes to a boolean.
pub(crate) fn bytes_to_bool(b: &[u8]) -> Option<bool> {
match b {
b"true" | b"TRUE" | b"t" | b"T" | b"1" => Some(true),
b"false" | b"FALSE" | b"f" | b"F" | b"0" => Some(false),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec::Vec;
fn read_kitten_file() -> Vec<u8> {
include_bytes!("../tests/kitten.jpeg").to_vec()
}
#[test]
fn should_crc16_123456789() {
let key = "123456789";
// 31C3
let expected: u16 = 12739;
let actual = redis_keyslot(key.as_bytes());
assert_eq!(actual, expected);
}
#[test]
fn should_crc16_with_brackets() {
let key = "foo{123456789}bar";
// 31C3
let expected: u16 = 12739;
let actual = redis_keyslot(key.as_bytes());
assert_eq!(actual, expected);
}
#[test]
fn should_crc16_with_brackets_no_padding() {
let key = "{123456789}";
// 31C3
let expected: u16 = 12739;
let actual = redis_keyslot(key.as_bytes());
assert_eq!(actual, expected);
}
#[test]
fn should_crc16_with_invalid_brackets_lhs() {
let key = "foo{123456789";
// 288A
let expected: u16 = 10378;
let actual = redis_keyslot(key.as_bytes());
assert_eq!(actual, expected);
}
#[test]
fn should_crc16_with_invalid_brackets_rhs() {
let key = "foo}123456789";
// 5B35 = 23349, 23349 % 16384 = 6965
let expected: u16 = 6965;
let actual = redis_keyslot(key.as_bytes());
assert_eq!(actual, expected);
}
#[test]
fn should_crc16_with_random_string() {
let key = "8xjx7vWrfPq54mKfFD3Y1CcjjofpnAcQ";
// 127.0.0.1:30001> cluster keyslot 8xjx7vWrfPq54mKfFD3Y1CcjjofpnAcQ
// (integer) 5458
let expected: u16 = 5458;
let actual = redis_keyslot(key.as_bytes());
assert_eq!(actual, expected);
}
#[test]
fn should_hash_non_ascii_string_bytes() {
let key = "π© π» π β οΈ π½ πΎ";
// 127.0.0.1:30001> cluster keyslot "π© π» π β οΈ π½ πΎ"
// (integer) 13954
let expected: u16 = 13954;
let actual = redis_keyslot(key.as_bytes());
assert_eq!(actual, expected);
}
#[test]
fn should_hash_non_ascii_string_bytes_with_tag() {
let key = "π© π» π{123456789}β οΈ π½ πΎ";
// 127.0.0.1:30001> cluster keyslot "π© π» π{123456789}β οΈ π½ πΎ"
// (integer) 12739
let expected: u16 = 12739;
let actual = redis_keyslot(key.as_bytes());
assert_eq!(actual, expected);
}
#[test]
fn should_hash_non_utf8_string_bytes() {
let key = read_kitten_file();
let expected: u16 = 1589;
let actual = redis_keyslot(&key);
assert_eq!(actual, expected)
}
#[test]
fn should_hash_non_utf8_string_bytes_with_tag() {
let mut key = read_kitten_file();
for (idx, c) in "{123456789}".as_bytes().iter().enumerate() {
key[242 + idx] = *c;
}
let expected: u16 = 12739;
let actual = redis_keyslot(&key);
assert_eq!(actual, expected)
}
}