Skip to content

Commit a12fa13

Browse files
authored
Merge pull request redis-rs#456 from tdyas/bytes_conversion_support
add support for converting binary data to bytes::Bytes
2 parents 92ac4f8 + 259cb3e commit a12fa13

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/types.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1242,6 +1242,16 @@ impl<T: FromRedisValue> FromRedisValue for Option<T> {
12421242
}
12431243
}
12441244

1245+
#[cfg(feature = "bytes")]
1246+
impl FromRedisValue for bytes::Bytes {
1247+
fn from_redis_value(v: &Value) -> RedisResult<Self> {
1248+
match v {
1249+
Value::Data(bytes_vec) => Ok(bytes::Bytes::copy_from_slice(bytes_vec.as_ref())),
1250+
_ => invalid_type_error!(v, "Not binary data"),
1251+
}
1252+
}
1253+
}
1254+
12451255
/// A shortcut function to invoke `FromRedisValue::from_redis_value`
12461256
/// to make the API slightly nicer.
12471257
pub fn from_redis_value<T: FromRedisValue>(v: &Value) -> RedisResult<T> {

tests/test_types.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,35 @@ fn test_bool() {
163163
assert_eq!(v, Ok(true));
164164
}
165165

166+
#[cfg(feature = "bytes")]
167+
#[test]
168+
fn test_bytes() {
169+
use bytes::Bytes;
170+
use redis::{ErrorKind, FromRedisValue, RedisResult, Value};
171+
172+
let content: &[u8] = b"\x01\x02\x03\x04";
173+
let content_vec: Vec<u8> = Vec::from(content);
174+
let content_bytes = Bytes::from_static(content);
175+
176+
let v: RedisResult<Bytes> = FromRedisValue::from_redis_value(&Value::Data(content_vec));
177+
assert_eq!(v, Ok(content_bytes));
178+
179+
let v: RedisResult<Bytes> = FromRedisValue::from_redis_value(&Value::Status("garbage".into()));
180+
assert_eq!(v.unwrap_err().kind(), ErrorKind::TypeError);
181+
182+
let v: RedisResult<Bytes> = FromRedisValue::from_redis_value(&Value::Okay);
183+
assert_eq!(v.unwrap_err().kind(), ErrorKind::TypeError);
184+
185+
let v: RedisResult<Bytes> = FromRedisValue::from_redis_value(&Value::Nil);
186+
assert_eq!(v.unwrap_err().kind(), ErrorKind::TypeError);
187+
188+
let v: RedisResult<Bytes> = FromRedisValue::from_redis_value(&Value::Int(0));
189+
assert_eq!(v.unwrap_err().kind(), ErrorKind::TypeError);
190+
191+
let v: RedisResult<Bytes> = FromRedisValue::from_redis_value(&Value::Int(42));
192+
assert_eq!(v.unwrap_err().kind(), ErrorKind::TypeError);
193+
}
194+
166195
#[test]
167196
fn test_types_to_redis_args() {
168197
use redis::ToRedisArgs;

0 commit comments

Comments
 (0)