Skip to content

Commit

Permalink
Implement FromValue trait for byte arrays. (#1463)
Browse files Browse the repository at this point in the history
* Implement FromValue trait for byte arrays.

* Add test for array serialization (and deserialization).
  • Loading branch information
ignatz committed Jun 11, 2024
1 parent 7a16a8d commit 74cbe91
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 0 deletions.
2 changes: 2 additions & 0 deletions libsql/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ pub enum Error {
InvalidTlsConfiguration(std::io::Error),
#[error("Transactional batch error: {0}")]
TransactionalBatchError(String),
#[error("Invalid blob size, expected {0}")]
InvalidBlobSize(usize),
}

#[cfg(feature = "hrana")]
Expand Down
13 changes: 13 additions & 0 deletions libsql/src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,3 +329,16 @@ macro_rules! named_params {
[$(($param_name, $value.into_value())),*]
}};
}

#[cfg(test)]
mod tests {
use crate::Value;

#[test]
fn test_serialize_array() {
assert_eq!(
params!([0; 16])[0].as_ref().unwrap(),
&Value::Blob(vec![0; 16])
);
}
}
13 changes: 13 additions & 0 deletions libsql/src/rows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,19 @@ impl FromValue for Vec<u8> {
}
impl Sealed for Vec<u8> {}

impl<const N: usize> FromValue for [u8; N] {
fn from_sql(val: Value) -> Result<Self> {
match val {
Value::Null => Err(crate::Error::NullValue),
Value::Blob(blob) => blob
.try_into()
.map_err(|_| crate::Error::InvalidBlobSize(N)),
_ => unreachable!("invalid value type"),
}
}
}
impl<const N: usize> Sealed for [u8; N] {}

impl FromValue for String {
fn from_sql(val: Value) -> Result<Self> {
match val {
Expand Down
2 changes: 2 additions & 0 deletions libsql/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,8 @@ mod serde_ {
assert!(de::<Vec<u8>>(Value::Null).is_err());
assert!(de::<f64>(Value::Blob(b"abc".to_vec())).is_err());
assert!(de::<MyEnum>(Value::Text("C".to_string())).is_err());

assert_eq!(de::<[u8; 2]>(Value::Blob(b"aa".to_vec())), Ok([97, 97]));
}
}
}

0 comments on commit 74cbe91

Please sign in to comment.