1
0

mod.rs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. //! # Redis Value
  2. //!
  3. //! All redis internal data structures and values are abstracted in this mod.
  4. pub mod checksum;
  5. pub mod cursor;
  6. pub mod expiration;
  7. pub mod float;
  8. pub mod locked;
  9. pub mod typ;
  10. use crate::{cmd::now, error::Error, value_try_from, value_vec_try_from};
  11. use bytes::{Bytes, BytesMut};
  12. use redis_zero_protocol_parser::Value as ParsedValue;
  13. use sha2::{Digest, Sha256};
  14. use std::{
  15. collections::{HashMap, HashSet, VecDeque},
  16. convert::{TryFrom, TryInto},
  17. str::FromStr,
  18. time::Duration,
  19. };
  20. /// Redis Value.
  21. ///
  22. /// This enum represents all data structures that are supported by Redis
  23. #[derive(Debug, PartialEq, Clone)]
  24. pub enum Value {
  25. /// Hash. This type cannot be serialized
  26. Hash(locked::Value<HashMap<Bytes, Bytes>>),
  27. /// List. This type cannot be serialized
  28. List(locked::Value<VecDeque<checksum::Value>>),
  29. /// Set. This type cannot be serialized
  30. Set(locked::Value<HashSet<Bytes>>),
  31. /// Vector/Array of values
  32. Array(Vec<Value>),
  33. /// Bytes/Strings/Binary data
  34. Blob(BytesMut),
  35. /// String. This type does not allow new lines
  36. String(String),
  37. /// An error
  38. Err(String, String),
  39. /// Integer
  40. Integer(i64),
  41. /// Boolean
  42. Boolean(bool),
  43. /// Float number
  44. Float(f64),
  45. /// Big number
  46. BigInteger(i128),
  47. /// Null
  48. Null,
  49. /// The command has been Queued
  50. Queued,
  51. /// Ok
  52. Ok,
  53. /// Empty response that is not send to the client
  54. Ignore,
  55. }
  56. impl Default for Value {
  57. fn default() -> Self {
  58. Self::Null
  59. }
  60. }
  61. /// Value debug struct
  62. #[derive(Debug)]
  63. pub struct VDebug {
  64. /// Value encoding
  65. pub encoding: &'static str,
  66. /// Length of serialized value
  67. pub serialize_len: usize,
  68. }
  69. impl From<VDebug> for Value {
  70. fn from(v: VDebug) -> Self {
  71. Value::Blob(format!(
  72. "Value at:0x6000004a8840 refcount:1 encoding:{} serializedlength:{} lru:13421257 lru_seconds_idle:367",
  73. v.encoding, v.serialize_len
  74. ).as_str().into()
  75. )
  76. }
  77. }
  78. impl Value {
  79. /// Creates a new Redis value from a stream of bytes
  80. pub fn new(value: &[u8]) -> Self {
  81. Self::Blob(value.into())
  82. }
  83. /// Returns the internal encoding of the redis
  84. pub fn encoding(&self) -> &'static str {
  85. match self {
  86. Self::Hash(_) | Self::Set(_) => "hashtable",
  87. Self::List(_) => "linkedlist",
  88. Self::Array(_) => "vector",
  89. _ => "embstr",
  90. }
  91. }
  92. /// Is the current value an error?
  93. pub fn is_err(&self) -> bool {
  94. match self {
  95. Self::Err(..) => true,
  96. _ => false,
  97. }
  98. }
  99. /// Return debug information for the type
  100. pub fn debug(&self) -> VDebug {
  101. let bytes: Vec<u8> = self.into();
  102. VDebug {
  103. encoding: self.encoding(),
  104. serialize_len: bytes.len(),
  105. }
  106. }
  107. /// Returns the hash of the value
  108. pub fn digest(&self) -> Vec<u8> {
  109. let bytes: Vec<u8> = self.into();
  110. let mut hasher = Sha256::new();
  111. hasher.update(&bytes);
  112. hasher.finalize().to_vec()
  113. }
  114. }
  115. impl From<&Value> for Vec<u8> {
  116. fn from(value: &Value) -> Vec<u8> {
  117. match value {
  118. Value::Ignore => b"".to_vec(),
  119. Value::Null => b"*-1\r\n".to_vec(),
  120. Value::Array(x) => {
  121. let mut s: Vec<u8> = format!("*{}\r\n", x.len()).into();
  122. for i in x.iter() {
  123. let b: Vec<u8> = i.into();
  124. s.extend(b);
  125. }
  126. s
  127. }
  128. Value::Integer(x) => format!(":{}\r\n", x).into(),
  129. Value::BigInteger(x) => format!("({}\r\n", x).into(),
  130. Value::Float(x) => format!(",{}\r\n", x).into(),
  131. Value::Blob(x) => {
  132. let s = format!("${}\r\n", x.len());
  133. let mut s: BytesMut = s.as_str().as_bytes().into();
  134. s.extend_from_slice(x);
  135. s.extend_from_slice(b"\r\n");
  136. s.to_vec()
  137. }
  138. Value::Err(x, y) => format!("-{} {}\r\n", x, y).into(),
  139. Value::String(x) => format!("+{}\r\n", x).into(),
  140. Value::Queued => "+QUEUED\r\n".into(),
  141. Value::Ok => "+OK\r\n".into(),
  142. _ => b"-WRONGTYPE Operation against a key holding the wrong kind of value\r\n".to_vec(),
  143. }
  144. }
  145. }
  146. impl TryFrom<&Value> for i64 {
  147. type Error = Error;
  148. fn try_from(val: &Value) -> Result<Self, Self::Error> {
  149. match val {
  150. Value::BigInteger(x) => (*x).try_into().map_err(|_| Error::NotANumber),
  151. Value::Integer(x) => Ok(*x),
  152. Value::Blob(x) => bytes_to_number::<i64>(&x),
  153. Value::String(x) => x.parse::<i64>().map_err(|_| Error::NotANumber),
  154. _ => Err(Error::NotANumber),
  155. }
  156. }
  157. }
  158. impl TryFrom<&Value> for f64 {
  159. type Error = Error;
  160. fn try_from(val: &Value) -> Result<Self, Self::Error> {
  161. match val {
  162. Value::Float(x) => Ok(*x),
  163. Value::Blob(x) => bytes_to_number::<f64>(x),
  164. Value::String(x) => x.parse::<f64>().map_err(|_| Error::NotANumber),
  165. _ => Err(Error::NotANumber),
  166. }
  167. }
  168. }
  169. /// Tries to convert bytes data into a number
  170. ///
  171. /// If the conversion fails a Error::NotANumber error is returned.
  172. #[inline]
  173. pub fn bytes_to_number<T: FromStr>(bytes: &[u8]) -> Result<T, Error> {
  174. let x = String::from_utf8_lossy(bytes);
  175. x.parse::<T>().map_err(|_| Error::NotANumber)
  176. }
  177. /// Tries to convert bytes data into an integer number
  178. #[inline]
  179. pub fn bytes_to_int<T: FromStr>(bytes: &[u8]) -> Result<T, Error> {
  180. let x = String::from_utf8_lossy(bytes);
  181. x.parse::<T>()
  182. .map_err(|_| Error::NotANumberType("an integer".to_owned()))
  183. }
  184. impl<'a> From<&ParsedValue<'a>> for Value {
  185. fn from(value: &ParsedValue) -> Self {
  186. match value {
  187. ParsedValue::String(x) => Self::String((*x).to_string()),
  188. ParsedValue::Blob(x) => Self::new(*x),
  189. ParsedValue::Array(x) => Self::Array(x.iter().map(|x| x.into()).collect()),
  190. ParsedValue::Boolean(x) => Self::Boolean(*x),
  191. ParsedValue::BigInteger(x) => Self::BigInteger(*x),
  192. ParsedValue::Integer(x) => Self::Integer(*x),
  193. ParsedValue::Float(x) => Self::Float(*x),
  194. ParsedValue::Error(x, y) => Self::Err((*x).to_string(), (*y).to_string()),
  195. ParsedValue::Null => Self::Null,
  196. }
  197. }
  198. }
  199. value_try_from!(f64, Value::Float);
  200. value_try_from!(i32, Value::Integer);
  201. value_try_from!(u32, Value::Integer);
  202. value_try_from!(i64, Value::Integer);
  203. value_try_from!(i128, Value::BigInteger);
  204. impl From<usize> for Value {
  205. fn from(value: usize) -> Value {
  206. Value::Integer(value as i64)
  207. }
  208. }
  209. impl From<Value> for Vec<u8> {
  210. fn from(value: Value) -> Vec<u8> {
  211. (&value).into()
  212. }
  213. }
  214. impl From<Option<&Bytes>> for Value {
  215. fn from(v: Option<&Bytes>) -> Self {
  216. if let Some(v) = v {
  217. v.into()
  218. } else {
  219. Value::Null
  220. }
  221. }
  222. }
  223. impl From<&Bytes> for Value {
  224. fn from(v: &Bytes) -> Self {
  225. Value::new(v)
  226. }
  227. }
  228. impl From<&str> for Value {
  229. fn from(value: &str) -> Value {
  230. Value::Blob(value.as_bytes().into())
  231. }
  232. }
  233. impl From<HashMap<Bytes, Bytes>> for Value {
  234. fn from(value: HashMap<Bytes, Bytes>) -> Value {
  235. Value::Hash(locked::Value::new(value))
  236. }
  237. }
  238. impl From<VecDeque<checksum::Value>> for Value {
  239. fn from(value: VecDeque<checksum::Value>) -> Value {
  240. Value::List(locked::Value::new(value))
  241. }
  242. }
  243. impl From<HashSet<Bytes>> for Value {
  244. fn from(value: HashSet<Bytes>) -> Value {
  245. Value::Set(locked::Value::new(value))
  246. }
  247. }
  248. value_vec_try_from!(&str);
  249. impl From<String> for Value {
  250. fn from(value: String) -> Value {
  251. value.as_str().into()
  252. }
  253. }
  254. impl From<Vec<Value>> for Value {
  255. fn from(value: Vec<Value>) -> Value {
  256. Value::Array(value)
  257. }
  258. }
  259. impl TryInto<Vec<Value>> for Value {
  260. type Error = Error;
  261. fn try_into(self) -> Result<Vec<Value>, Self::Error> {
  262. match self {
  263. Self::Array(x) => Ok(x),
  264. _ => Err(Error::Internal),
  265. }
  266. }
  267. }