This commit is contained in:
Yuriy Dupyn 2024-02-05 23:35:49 +01:00
parent c25c6edc6a
commit 588db169f8
8 changed files with 15 additions and 55 deletions

View file

@ -1,7 +1,5 @@
use bincode;
use bincode::config::{BigEndian, Configuration, Fixint};
use bincode::{Decode, Encode};
use std::mem::size_of;
const BIN_CONFIG: Configuration<BigEndian, Fixint> = bincode::config::standard()
.with_big_endian()
@ -15,27 +13,6 @@ pub fn decode<T: Decode>(bytes: &[u8]) -> Result<(T, usize), bincode::error::Dec
bincode::decode_from_slice(bytes, BIN_CONFIG)
}
pub fn encode_vector<T: Encode>(ts: &[T]) -> Result<Vec<u8>, bincode::error::EncodeError> {
let size: usize = ts.len();
let mut result = encode(&size)?;
for t in ts {
result.append(&mut encode(&t)?);
}
Ok(result)
}
pub fn decode_vector<T: Decode>(bytes: &[u8]) -> Result<Vec<T>, bincode::error::DecodeError> {
let mut offset = size_of::<usize>();
let result_len: usize = decode(&bytes[..offset])?.0;
let mut result: Vec<T> = Vec::with_capacity(result_len);
for _ in 0..result_len {
let (x, bytes_consumed) = decode::<T>(&bytes[offset..])?;
offset += bytes_consumed;
result.push(x);
}
Ok(result)
}
// We don't care about encoding the length here (since it will be used for a row with known column
// size)
pub fn encode_sequence<T: Encode>(ts: &[T]) -> Result<Vec<u8>, bincode::error::EncodeError> {
@ -72,20 +49,3 @@ pub fn decode_sequence<T: Decode>(
}
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_encoding_decoding() {
let xs: Vec<String> = vec!["foo".to_string(), "bar".to_string()];
let exs = encode_vector(&xs[..]).unwrap();
// WARNING: Don't forget to specify the type here
let dxs = decode_vector::<String>(&exs[..]).unwrap();
assert!(dxs == xs);
}
}