Skip to main content

ArrayBytesVariableLength

Struct ArrayBytesVariableLength 

Source
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] for 0 <= 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>

Source

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.

Source

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.

Source

pub fn bytes(&self) -> &Cow<'a, [u8]>

Get the underlying bytes.

Source

pub fn offsets(&self) -> &ArrayBytesOffsets<'a>

Get the underlying offsets.

Source

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
Hide additional 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>

Source§

fn clone(&self) -> ArrayBytesVariableLength<'a>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a> Debug for ArrayBytesVariableLength<'a>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<'a> From<ArrayBytesVariableLength<'a>> for ArrayBytes<'a>

Source§

fn from(value: ArrayBytesVariableLength<'a>) -> ArrayBytes<'a>

Converts to this type from the input type.
Source§

impl<'a> PartialEq for ArrayBytesVariableLength<'a>

Source§

fn eq(&self, other: &ArrayBytesVariableLength<'a>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a> Eq for ArrayBytesVariableLength<'a>

Source§

impl<'a> StructuralPartialEq for ArrayBytesVariableLength<'a>

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.