pub struct ArrayBytesVariableLength<'a> { /* private fields */ }Expand description
Variable length array bytes composed of bytes and element bytes offsets.
The bytes and offsets are modeled on the Apache Arrow Variable-size Binary Layout.
- The offsets buffer contains length + 1
signed integers (either 32-bit or 64-bit, depending on the data type)usize integers. - Offsets must be monotonically increasing, that is
offsets[j+1] >= offsets[j]for0 <= j < length, even for null slots. Thus, the bytes represent C-contiguous elements with padding permitted. - The final offset must be less than or equal to the length of the bytes buffer.
Implementations§
Source§impl<'a> ArrayBytesVariableLength<'a>
impl<'a> ArrayBytesVariableLength<'a>
Sourcepub fn new(
bytes: impl Into<Cow<'a, [u8]>>,
offsets: ArrayBytesOffsets<'a>,
) -> Result<ArrayBytesVariableLength<'a>, ArrayBytesRawOffsetsOutOfBoundsError>
pub fn new( bytes: impl Into<Cow<'a, [u8]>>, offsets: ArrayBytesOffsets<'a>, ) -> Result<ArrayBytesVariableLength<'a>, ArrayBytesRawOffsetsOutOfBoundsError>
Create a new variable length bytes from bytes and offsets.
§Errors
Returns a ArrayBytesRawOffsetsOutOfBoundsError if the last offset is out of bounds of the bytes or if the offsets are not monotonically increasing.
Sourcepub unsafe fn new_unchecked(
bytes: impl Into<Cow<'a, [u8]>>,
offsets: ArrayBytesOffsets<'a>,
) -> ArrayBytesVariableLength<'a>
pub unsafe fn new_unchecked( bytes: impl Into<Cow<'a, [u8]>>, offsets: ArrayBytesOffsets<'a>, ) -> ArrayBytesVariableLength<'a>
Create a new variable length bytes from bytes and offsets.
§Safety
The last offset must be less than or equal to the length of the bytes.
Sourcepub fn offsets(&self) -> &ArrayBytesOffsets<'a>
pub fn offsets(&self) -> &ArrayBytesOffsets<'a>
Get the underlying offsets.
Sourcepub fn into_parts(self) -> (Cow<'a, [u8]>, ArrayBytesOffsets<'a>)
pub fn into_parts(self) -> (Cow<'a, [u8]>, ArrayBytesOffsets<'a>)
Consume self and return the bytes and offsets.
Examples found in repository?
examples/custom_data_type_variable_size.rs (line 74)
69 fn from_array_bytes(
70 data_type: &DataType,
71 bytes: ArrayBytes<'_>,
72 ) -> Result<Vec<Self>, ElementError> {
73 Self::validate_data_type(data_type)?;
74 let (bytes, offsets) = bytes.into_variable()?.into_parts();
75
76 let mut elements = Vec::with_capacity(offsets.len().saturating_sub(1));
77 for (curr, next) in offsets.iter().tuple_windows() {
78 let bytes = &bytes[*curr..*next];
79 if let Ok(bytes) = <[u8; 4]>::try_from(bytes) {
80 let value = f32::from_le_bytes(bytes);
81 elements.push(CustomDataTypeVariableSizeElement(Some(value)));
82 } else if bytes.is_empty() {
83 elements.push(CustomDataTypeVariableSizeElement(None));
84 } else {
85 panic!()
86 }
87 }
88
89 Ok(elements)
90 }More examples
examples/array_write_read_string.rs (line 96)
8fn array_write_read() -> Result<(), Box<dyn std::error::Error>> {
9 use std::sync::Arc;
10
11 use zarrs::array::{ArrayBytes, data_type};
12 use zarrs::storage::store;
13
14 // Create a store
15 // let path = tempfile::TempDir::new()?;
16 // let mut store: ReadableWritableListableStorage =
17 // Arc::new(zarrs::filesystem::FilesystemStore::new(path.path())?);
18 // let mut store: ReadableWritableListableStorage = Arc::new(
19 // zarrs::filesystem::FilesystemStore::new("zarrs/tests/data/array_write_read.zarr")?,
20 // );
21 let mut store: ReadableWritableListableStorage = Arc::new(store::MemoryStore::new());
22 if let Some(arg1) = std::env::args().collect::<Vec<_>>().get(1)
23 && arg1 == "--usage-log"
24 {
25 let log_writer = Arc::new(std::sync::Mutex::new(
26 // std::io::BufWriter::new(
27 std::io::stdout(),
28 // )
29 ));
30 store = Arc::new(UsageLogStorageAdapter::new(store, log_writer, || {
31 chrono::Utc::now().format("[%T%.3f] ").to_string()
32 }));
33 }
34
35 // Create the root group
36 zarrs::group::GroupBuilder::new()
37 .build(store.clone(), "/")?
38 .store_metadata()?;
39
40 // Create a group with attributes
41 let group_path = "/group";
42 let mut group = zarrs::group::GroupBuilder::new().build(store.clone(), group_path)?;
43 group
44 .attributes_mut()
45 .insert("foo".into(), serde_json::Value::String("bar".into()));
46 group.store_metadata()?;
47
48 println!(
49 "The group metadata is:\n{}\n",
50 group.metadata().to_string_pretty()
51 );
52
53 // Create an array
54 let array_path = "/group/array";
55 let array = zarrs::array::ArrayBuilder::new(
56 vec![4, 4], // array shape
57 vec![2, 2], // regular chunk shape
58 data_type::string(),
59 "_",
60 )
61 // .bytes_to_bytes_codecs(vec![]) // uncompressed
62 .dimension_names(["y", "x"].into())
63 // .storage_transformers(vec![].into())
64 .build(store.clone(), array_path)?;
65
66 // Write array metadata to store
67 array.store_metadata()?;
68
69 println!(
70 "The array metadata is:\n{}\n",
71 array.metadata().to_string_pretty()
72 );
73
74 // Write some chunks
75 array.store_chunk(
76 &[0, 0],
77 ArrayD::<&str>::from_shape_vec(vec![2, 2], vec!["a", "bb", "ccc", "dddd"]).unwrap(),
78 )?;
79 array.store_chunk(
80 &[0, 1],
81 ArrayD::<&str>::from_shape_vec(vec![2, 2], vec!["4444", "333", "22", "1"]).unwrap(),
82 )?;
83 let subset_all = array.subset_all();
84 let data_all: ArrayD<String> = array.retrieve_array_subset(&subset_all)?;
85 println!("store_chunk [0, 0] and [0, 1]:\n{data_all}\n");
86
87 // Write a subset spanning multiple chunks, including updating chunks already written
88 let ndarray_subset: Array2<&str> = array![["!", "@@"], ["###", "$$$$"]];
89 array.store_array_subset(&[1..3, 1..3], ndarray_subset)?;
90 let data_all: ArrayD<String> = array.retrieve_array_subset(&subset_all)?;
91 println!("store_array_subset [1..3, 1..3]:\nndarray::ArrayD<String>\n{data_all}");
92
93 // Retrieve bytes directly, convert into a single string allocation, create a &str ndarray
94 // TODO: Add a convenience function for this?
95 let data_all: ArrayBytes = array.retrieve_array_subset(&subset_all)?;
96 let (bytes, offsets) = data_all.into_variable()?.into_parts();
97 let string = String::from_utf8(bytes.into_owned())?;
98 let elements = offsets
99 .iter()
100 .tuple_windows()
101 .map(|(&curr, &next)| &string[curr..next])
102 .collect::<Vec<&str>>();
103 let ndarray = ArrayD::<&str>::from_shape_vec(subset_all.shape_usize(), elements)?;
104 println!("ndarray::ArrayD<&str>:\n{ndarray}");
105
106 Ok(())
107}Trait Implementations§
Source§impl<'a> Clone for ArrayBytesVariableLength<'a>
impl<'a> Clone for ArrayBytesVariableLength<'a>
Source§fn clone(&self) -> ArrayBytesVariableLength<'a>
fn clone(&self) -> ArrayBytesVariableLength<'a>
Returns a duplicate of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moreSource§impl<'a> Debug for ArrayBytesVariableLength<'a>
impl<'a> Debug for ArrayBytesVariableLength<'a>
Source§impl<'a> From<ArrayBytesVariableLength<'a>> for ArrayBytes<'a>
impl<'a> From<ArrayBytesVariableLength<'a>> for ArrayBytes<'a>
Source§fn from(value: ArrayBytesVariableLength<'a>) -> ArrayBytes<'a>
fn from(value: ArrayBytesVariableLength<'a>) -> ArrayBytes<'a>
Converts to this type from the input type.
Source§impl<'a> PartialEq for ArrayBytesVariableLength<'a>
impl<'a> PartialEq for ArrayBytesVariableLength<'a>
Source§fn eq(&self, other: &ArrayBytesVariableLength<'a>) -> bool
fn eq(&self, other: &ArrayBytesVariableLength<'a>) -> bool
Tests for
self and other values to be equal, and is used by ==.impl<'a> Eq for ArrayBytesVariableLength<'a>
impl<'a> StructuralPartialEq for ArrayBytesVariableLength<'a>
Auto Trait Implementations§
impl<'a> Freeze for ArrayBytesVariableLength<'a>
impl<'a> Send for ArrayBytesVariableLength<'a>
impl<'a> Sync for ArrayBytesVariableLength<'a>
impl<'a> RefUnwindSafe for ArrayBytesVariableLength<'a>
impl<'a> Unpin for ArrayBytesVariableLength<'a>
impl<'a> UnsafeUnpin for ArrayBytesVariableLength<'a>
impl<'a> UnwindSafe for ArrayBytesVariableLength<'a>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
Compare self to
key and return true if they are equal.Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
Converts
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
Converts
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more