minisql/storage_engine/src/binary_coding.rs
Yuriy Dupyn 588db169f8 Linting
2024-02-05 23:35:49 +01:00

51 lines
1.5 KiB
Rust

use bincode::config::{BigEndian, Configuration, Fixint};
use bincode::{Decode, Encode};
const BIN_CONFIG: Configuration<BigEndian, Fixint> = bincode::config::standard()
.with_big_endian()
.with_fixed_int_encoding();
pub fn encode<T: Encode>(t: &T) -> Result<Vec<u8>, bincode::error::EncodeError> {
bincode::encode_to_vec(t, BIN_CONFIG)
}
pub fn decode<T: Decode>(bytes: &[u8]) -> Result<(T, usize), bincode::error::DecodeError> {
bincode::decode_from_slice(bytes, BIN_CONFIG)
}
// 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> {
let mut result = vec![];
for t in ts {
result.append(&mut encode(&t)?);
}
Ok(result)
}
pub fn encode_sequence_with_sizes<T: Encode>(
ts: &[T],
) -> Result<(Vec<u8>, Vec<usize>), bincode::error::EncodeError> {
let mut result_bytes = vec![];
let mut sizes = Vec::with_capacity(ts.len());
for t in ts {
let mut bytes = encode(&t)?;
sizes.push(bytes.len());
result_bytes.append(&mut bytes);
}
Ok((result_bytes, sizes))
}
pub fn decode_sequence<T: Decode>(
len: usize,
bytes: &[u8],
) -> Result<Vec<T>, bincode::error::DecodeError> {
let mut result: Vec<T> = Vec::with_capacity(len);
let mut offset = 0;
for _ in 0..len {
let (x, bytes_consumed) = decode::<T>(&bytes[offset..])?;
offset += bytes_consumed;
result.push(x);
}
Ok(result)
}