Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add BYTE_STREAM_SPLIT encoder/decoder (fixes #208) #221

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions src/encoding/byte_stream_split/decoder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use std::marker::PhantomData;
use crate::error::Error;
use crate::types::NativeType;

/// Decodes according to [Byte Stream Split](https://github.com/apache/parquet-format/blob/master/Encodings.md#byte-stream-split-byte_stream_split--9).
/// # Implementation
/// This struct does not allocate on the heap.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does? It holds a buffer of Vec<u8>.

#[derive(Debug)]
pub struct Decoder<'a, T: NativeType> {
values: &'a [u8],
buffer: Vec<u8>,
ritchie46 marked this conversation as resolved.
Show resolved Hide resolved
num_elements: usize,
current: usize,
element_size: usize,
element_type: PhantomData<T>
}

impl<'a, T: NativeType> Decoder<'a, T> {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we maybe make this const on mem::size_of::<T>? Then we can use an array: [u8; Size] instead of a heap allocation.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I'm new to rust, but if I understand you correctly, I'd need to use:

#![feature(generic_const_exprs)]

and add a where clause, akin to:
https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=d8088113ef4552d7f96b987ec4d31c95

Are we ok to depend on non-stable features, or is there a better way to do this?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If using an unstable feature isn't okay, an alternative approach could be adding an extra type parameter, but this does make the consumer API a little more verbose. Eg: adamreeve@a513845

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need a new const type parameter for that. I can take a look later if you want.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes please, that would be great.

pub fn try_new(values: &'a [u8]) -> Result<Self, Error> {
let element_size = std::mem::size_of::<T>();
let values_size = values.len();
if values_size % element_size != 0 {
return Err(Error::oos("Value array is not a multiple of element size"));
}
let num_elements = values.len() / element_size;
Ok(Self {
values,
buffer: vec![0_u8; element_size],
ritchie46 marked this conversation as resolved.
Show resolved Hide resolved
num_elements,
current: 0,
element_size,
element_type: PhantomData
})
}
}

impl<'a, T: NativeType> Iterator for Decoder<'a, T> {
type Item = Result<T, Error>;

#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.current >= self.num_elements {
return None
}

for n in 0..self.element_size {
ritchie46 marked this conversation as resolved.
Show resolved Hide resolved
self.buffer[n] = self.values[(self.num_elements * n) + self.current]
}

let value = T::from_le_bytes(self.buffer.as_slice().try_into().unwrap());

self.current += 1;

return Some(Ok(value));
}

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(self.num_elements, Some(self.num_elements))
}
}
17 changes: 17 additions & 0 deletions src/encoding/byte_stream_split/encoder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use crate::types::NativeType;

/// Encodes an array of NativeType according to BYTE_STREAM_SPLIT
pub fn encode<T: NativeType>(data: &[T], buffer: &mut Vec<u8>) {
let element_size = std::mem::size_of::<T>();
let num_elements = data.len();
let total_length = element_size * num_elements;
buffer.resize(total_length, 0);

for (i, v) in data.iter().enumerate() {
let value_bytes = v.to_le_bytes();
let value_bytes_ref = value_bytes.as_ref();
for n in 0..element_size {
buffer[(num_elements * n) + i] = value_bytes_ref[n];
}
}
}
49 changes: 49 additions & 0 deletions src/encoding/byte_stream_split/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
mod decoder;
mod encoder;

pub use decoder::Decoder;
pub use encoder::encode;

#[cfg(test)]
mod tests {
use super::*;
use crate::error::Error;

#[test]
fn basic() -> Result<(), Error> {
let data = vec![1.0_f32, 2.0_f32, 3.0_f32];
let mut buffer = vec![];
encode(&data, &mut buffer);

let mut decoder = Decoder::<f32>::try_new(&buffer)?;
let values = decoder.by_ref().collect::<Result<Vec<_>, _>>()?;

assert_eq!(data, values);

Ok(())
}

#[test]
fn pyarrow_integration() -> Result<(), Error> {
let buffer = vec![
0, 205, 0, 205, 0, 0, 204, 0, 204, 0, 128, 140, 0, 140, 128, 255, 191, 0, 63, 127
];

let mut decoder = Decoder::<f32>::try_new(&buffer)?;
let values = decoder.by_ref().collect::<Result<Vec<_>, _>>()?;

assert_eq!(values, vec![-f32::INFINITY, -1.1, 0.0, 1.1, f32::INFINITY]);

Ok(())
}

#[test]
fn fails_for_bad_size() -> Result<(), Error> {
let buffer = vec![0; 12];

let result = Decoder::<f64>::try_new(&buffer);
assert!(result.is_err());

Ok(())
}
}
1 change: 1 addition & 0 deletions src/encoding/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::convert::TryInto;

pub mod bitpacked;
pub mod byte_stream_split;
pub mod delta_bitpacked;
pub mod delta_byte_array;
pub mod delta_length_byte_array;
Expand Down