Skip to content

Commit cacb276

Browse files
authored
Merge pull request #693 from siningma/u8_array
Add serialize/deserialize support for [u8; N]
2 parents 8108bba + f58bc1a commit cacb276

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

scylla-cql/src/frame/response/cql_to_rust.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,13 @@ impl_from_cql_value_from_method!(BigDecimal, into_decimal); // BigDecimal::from_
137137
impl_from_cql_value_from_method!(Duration, as_duration); // Duration::from_cql<CqlValue>
138138
impl_from_cql_value_from_method!(CqlDuration, as_cql_duration); // CqlDuration::from_cql<CqlValue>
139139

140+
impl<const N: usize> FromCqlVal<CqlValue> for [u8; N] {
141+
fn from_cql(cql_val: CqlValue) -> Result<Self, FromCqlValError> {
142+
let val = cql_val.into_blob().ok_or(FromCqlValError::BadCqlType)?;
143+
val.try_into().map_err(|_| FromCqlValError::BadVal)
144+
}
145+
}
146+
140147
impl FromCqlVal<CqlValue> for crate::frame::value::Date {
141148
fn from_cql(cql_val: CqlValue) -> Result<Self, FromCqlValError> {
142149
match cql_val {
@@ -409,6 +416,12 @@ mod tests {
409416
);
410417
}
411418

419+
#[test]
420+
fn u8_array_from_cql() {
421+
let val = [1u8; 4];
422+
assert_eq!(Ok(val), <[u8; 4]>::from_cql(CqlValue::Blob(val.to_vec())));
423+
}
424+
412425
#[test]
413426
fn ip_addr_from_cql() {
414427
let ip_addr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

scylla-cql/src/frame/value.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,17 @@ impl Value for Vec<u8> {
470470
}
471471
}
472472

473+
impl<const N: usize> Value for [u8; N] {
474+
fn serialize(&self, buf: &mut Vec<u8>) -> Result<(), ValueTooBig> {
475+
let val_len: i32 = self.len().try_into().map_err(|_| ValueTooBig)?;
476+
buf.put_i32(val_len);
477+
478+
buf.extend_from_slice(self);
479+
480+
Ok(())
481+
}
482+
}
483+
473484
impl Value for IpAddr {
474485
fn serialize(&self, buf: &mut Vec<u8>) -> Result<(), ValueTooBig> {
475486
match self {

scylla-cql/src/frame/value_tests.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ fn basic_serialization() {
2929
assert_eq!(serialized("abc".to_string()), vec![0, 0, 0, 3, 97, 98, 99]);
3030
}
3131

32+
#[test]
33+
fn u8_array_serialization() {
34+
let val = [1u8; 4];
35+
assert_eq!(serialized(val), vec![0, 0, 0, 4, 1, 1, 1, 1]);
36+
}
37+
3238
#[test]
3339
fn naive_date_serialization() {
3440
// 1970-01-31 is 2^31

0 commit comments

Comments
 (0)