1
0

value.rs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. use crate::{value_try_from, value_vec_try_from};
  2. use redis_zero_parser::Value as ParsedValue;
  3. use bytes::{Bytes, BytesMut};
  4. use std::convert::TryFrom;
  5. #[derive(Debug, PartialEq, Clone)]
  6. pub enum Value {
  7. Array(Vec<Value>),
  8. Blob(Bytes),
  9. String(String),
  10. Err(String, String),
  11. Integer(i64),
  12. Boolean(bool),
  13. Float(f64),
  14. BigInteger(i128),
  15. Null,
  16. }
  17. impl From<&Value> for Vec<u8> {
  18. fn from(value: &Value) -> Vec<u8> {
  19. match value {
  20. Value::Null => b"*-1\r\n".to_vec(),
  21. Value::Array(x) => {
  22. let mut s: Vec<u8> = format!("*{}\r\n", x.len()).into();
  23. for i in x.iter() {
  24. let b: Vec<u8> = i.into();
  25. s.extend(b);
  26. }
  27. s.to_vec()
  28. }
  29. Value::Integer(x) => format!(":{}\r\n", x).into(),
  30. Value::BigInteger(x) => format!("({}\r\n", x).into(),
  31. Value::Blob(x) => {
  32. let s = format!("${}\r\n", x.len());
  33. let mut s: BytesMut = s.as_str().as_bytes().into();
  34. s.extend_from_slice(&x);
  35. s.extend_from_slice(b"\r\n");
  36. s.to_vec()
  37. }
  38. _ => b"*-1\r\n".to_vec(),
  39. }
  40. }
  41. }
  42. impl From<Value> for Vec<u8> {
  43. fn from(value: Value) -> Vec<u8> {
  44. (&value).into()
  45. }
  46. }
  47. impl<'a> TryFrom<&ParsedValue<'a>> for Value {
  48. type Error = &'static str;
  49. fn try_from(value: &ParsedValue) -> Result<Self, Self::Error> {
  50. Ok(match value {
  51. ParsedValue::String(x) => Self::String(x.to_string()),
  52. ParsedValue::Blob(x) => Self::Blob(Bytes::copy_from_slice(*x)),
  53. ParsedValue::Array(x) => {
  54. Self::Array(x.iter().map(|x| Value::try_from(x).unwrap()).collect())
  55. }
  56. ParsedValue::Boolean(x) => Self::Boolean(*x),
  57. ParsedValue::BigInteger(x) => Self::BigInteger(*x),
  58. ParsedValue::Integer(x) => Self::Integer(*x),
  59. ParsedValue::Float(x) => Self::Float(*x),
  60. ParsedValue::Error(x, y) => Self::Err(x.to_string(), y.to_string()),
  61. ParsedValue::Null => Self::Null,
  62. })
  63. }
  64. }
  65. value_try_from!(i64, Value::Integer);
  66. value_try_from!(i128, Value::BigInteger);
  67. impl From<&str> for Value {
  68. fn from(value: &str) -> Value {
  69. Value::Blob(Bytes::copy_from_slice(value.as_bytes()))
  70. }
  71. }
  72. value_vec_try_from!(&str);