Skip to content

Add FromResp impl for HashMap #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 16, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 64 additions & 1 deletion src/resp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

//! An implementation of the RESP protocol

use std::collections::HashMap;
use std::hash::Hash;
use std::io;
use std::str;

Expand Down Expand Up @@ -187,6 +189,30 @@ impl<T: FromResp> FromResp for Vec<T> {
}
}

impl<K: FromResp + Hash + Eq, T: FromResp> FromResp for HashMap<K, T> {
fn from_resp_int(resp: RespValue) -> Result<HashMap<K, T>, Error> {
match resp {
RespValue::Array(ary) => {
let mut map = HashMap::new();
let mut items = ary.into_iter();

while let Some(k) = items.next() {
let key = K::from_resp(k)?;
let value = T::from_resp(items.next().ok_or(error::resp(
"Cannot convert an odd number of elements into a hashmap",
"".into(),
))?)?;

map.insert(key, value);
}

Ok(map)
}
_ => Err(error::resp("Cannot be converted into a hashmap", resp)),
}
}
}

impl FromResp for () {
fn from_resp_int(resp: RespValue) -> Result<(), Error> {
match resp {
Expand Down Expand Up @@ -613,11 +639,13 @@ impl Decoder for RespCodec {

#[cfg(test)]
mod tests {
use std::collections::HashMap;

use bytes::BytesMut;

use tokio_io::codec::{Decoder, Encoder};

use super::{FromResp, RespCodec, RespValue};
use super::{Error, FromResp, RespCodec, RespValue};

#[test]
fn test_bulk_string() {
Expand Down Expand Up @@ -675,4 +703,39 @@ mod tests {
let resp_object = RespValue::Integer(50);
assert_eq!(u32::from_resp(resp_object).unwrap(), 50);
}

#[test]
fn test_hashmap_conversion() {
let mut expected = HashMap::new();
expected.insert("KEY1".to_string(), "VALUE1".to_string());
expected.insert("KEY2".to_string(), "VALUE2".to_string());

let resp_object = RespValue::Array(vec![
"KEY1".into(),
"VALUE1".into(),
"KEY2".into(),
"VALUE2".into(),
]);
assert_eq!(
HashMap::<String, String>::from_resp(resp_object).unwrap(),
expected
);
}

#[test]
fn test_hashmap_conversion_fails_with_odd_length_array() {
let resp_object = RespValue::Array(vec![
"KEY1".into(),
"VALUE1".into(),
"KEY2".into(),
"VALUE2".into(),
"KEY3".into(),
]);
let res = HashMap::<String, String>::from_resp(resp_object);

match res {
Err(Error::RESP(_, _)) => {}
_ => panic!("Should not be able to convert an odd number of elements to a hashmap"),
}
}
}