cassandra_proto/query/
query_values.rs1use std::collections::HashMap;
2use std::hash::Hash;
3
4use crate::frame::IntoBytes;
5use crate::types::CString;
6use crate::types::value::Value;
7
8#[derive(Debug, Clone)]
12pub enum QueryValues {
13 SimpleValues(Vec<Value>),
14 NamedValues(HashMap<String, Value>),
15}
16
17impl QueryValues {
18 pub fn with_names(&self) -> bool {
20 match *self {
21 QueryValues::SimpleValues(_) => false,
22 _ => true,
23 }
24 }
25
26 pub fn len(&self) -> usize {
28 match *self {
29 QueryValues::SimpleValues(ref v) => v.len(),
30 QueryValues::NamedValues(ref m) => m.len(),
31 }
32 }
33
34 fn named_value_into_bytes_fold(mut bytes: Vec<u8>, vals: (&String, &Value)) -> Vec<u8> {
35 let mut name_bytes = CString::new(vals.0.clone()).into_cbytes();
36 let mut vals_bytes = vals.1.into_cbytes();
37 bytes.append(&mut name_bytes);
38 bytes.append(&mut vals_bytes);
39 bytes
40 }
41
42 fn value_into_bytes_fold(mut bytes: Vec<u8>, val: &Value) -> Vec<u8> {
43 let mut val_bytes = val.into_cbytes();
44 bytes.append(&mut val_bytes);
45 bytes
46 }
47}
48
49impl<T: Into<Value> + Clone> From<Vec<T>> for QueryValues {
50 fn from(values: Vec<T>) -> QueryValues {
52 let vals = values.iter().map(|v| v.clone().into());
53 QueryValues::SimpleValues(vals.collect())
54 }
55}
56
57impl<'a, T: Into<Value> + Clone> From<&'a [T]> for QueryValues {
58 fn from(values: &'a [T]) -> QueryValues {
60 let vals = values.iter().map(|v| v.clone().into());
61 QueryValues::SimpleValues(vals.collect())
62 }
63}
64
65impl<S: ToString + Hash + Eq, V: Into<Value> + Clone> From<HashMap<S, V>> for QueryValues {
66 fn from(values: HashMap<S, V>) -> QueryValues {
68 let map: HashMap<String, Value> = HashMap::with_capacity(values.len());
69 let _values = values.iter().fold(map, |mut acc, v| {
70 let name = v.0;
71 let val = v.1;
72 acc.insert(name.to_string(), val.clone().into());
73 acc
74 });
75 QueryValues::NamedValues(_values)
76 }
77}
78
79impl IntoBytes for QueryValues {
80 fn into_cbytes(&self) -> Vec<u8> {
81 let bytes: Vec<u8> = vec![];
82 match *self {
83 QueryValues::SimpleValues(ref v) => v.iter().fold(bytes, QueryValues::value_into_bytes_fold),
84 QueryValues::NamedValues(ref v) => {
85 v.iter().fold(bytes, QueryValues::named_value_into_bytes_fold)
86 }
87 }
88 }
89}