Skip to main content

DataType

Struct DataType 

Source
pub struct DataType(/* private fields */);
Expand description

A data type implementing DataTypeTraits.

Implementations§

Source§

impl DataType

Source

pub fn new<T>(data_type: T) -> DataType
where T: DataTypeTraits + 'static,

Create a data type.

Source

pub fn from_metadata<'a>( metadata: impl Into<DataTypeMetadata<'a>>, ) -> Result<DataType, PluginCreateError>

Create a data type from metadata.

§Errors

Returns PluginCreateError if the metadata is invalid or not associated with a registered codec plugin.

Source

pub fn is<T>(&self) -> bool
where T: 'static,

Returns true if this data type is of type T.

Examples found in repository?
examples/custom_data_type_fixed_size.rs (line 107)
105    fn validate_data_type(data_type: &DataType) -> Result<(), ElementError> {
106        data_type
107            .is::<CustomDataTypeFixedSize>()
108            .then_some(())
109            .ok_or(ElementError::IncompatibleElementType)
110    }
More examples
Hide additional examples
examples/custom_data_type_float8_e3m4.rs (line 160)
158    fn validate_data_type(data_type: &DataType) -> Result<(), ElementError> {
159        data_type
160            .is::<CustomDataTypeFloat8e3m4>()
161            .then_some(())
162            .ok_or(ElementError::IncompatibleElementType)
163    }
examples/custom_data_type_variable_size.rs (line 33)
31    fn validate_data_type(data_type: &DataType) -> Result<(), ElementError> {
32        data_type
33            .is::<CustomDataTypeVariableSize>()
34            .then_some(())
35            .ok_or(ElementError::IncompatibleElementType)
36    }
examples/custom_data_type_uint4.rs (line 152)
149    fn validate_data_type(data_type: &DataType) -> Result<(), ElementError> {
150        // Check if the data type matches our custom data type
151        data_type
152            .is::<CustomDataTypeUInt4>()
153            .then_some(())
154            .ok_or(ElementError::IncompatibleElementType)
155    }
examples/custom_data_type_uint12.rs (line 150)
147    fn validate_data_type(data_type: &DataType) -> Result<(), ElementError> {
148        // Check if the data type matches our custom data type
149        data_type
150            .is::<CustomDataTypeUInt12>()
151            .then_some(())
152            .ok_or(ElementError::IncompatibleElementType)
153    }
Source

pub fn downcast_ref<T>(&self) -> Option<&T>
where T: 'static,

Downcast this data type to type T.

Source

pub fn fixed_size(&self) -> Option<usize>

Returns the size in bytes of a fixed-size data type, otherwise returns None.

Source

pub fn is_fixed(&self) -> bool

Returns true if the data type has a fixed size.

Source

pub fn is_variable(&self) -> bool

Returns true if the data type has a variable size.

Source

pub fn is_optional(&self) -> bool

Returns true if this is an optional data type.

Source

pub fn as_optional(&self) -> Option<&OptionalDataType>

Returns the optional type wrapper if this is an optional data type.

Source

pub fn optional_inner(&self) -> Option<&DataType>

For optional types: returns the inner data type.

Returns None if this is not an optional type.

Source

pub fn to_optional(&self) -> DataType

Wrap this data type in an optional type.

Examples found in repository?
examples/data_type_optional_nested.rs (line 22)
11fn main() -> Result<(), Box<dyn std::error::Error>> {
12    // Create an in-memory store
13    // let store = Arc::new(zarrs::filesystem::FilesystemStore::new(
14    //     "zarrs/tests/data/v3/array_optional_nested.zarr",
15    // )?);
16    let store = Arc::new(zarrs::storage::store::MemoryStore::new());
17
18    // Build the codec chains for the optional codec
19    let array = ArrayBuilder::new(
20        vec![4, 4],                                     // 4x4 array
21        vec![2, 2],                                     // 2x2 chunks
22        data_type::uint8().to_optional().to_optional(), // Optional optional uint8 => Option<Option<u8>>
23        FillValue::new_optional_null().into_optional(), // Fill value => Some(None)
24    )
25    .dimension_names(["y", "x"].into())
26    .attributes(
27        serde_json::json!({
28            "description": r#"A 4x4 array of optional optional uint8 values with some missing data.
29The fill value is null on the inner optional layer, i.e. Some(None).
30N marks missing (`None`=`null`) values. SN marks `Some(None)`=`[null]` values:
31  N  SN   2   3 
32  N   5   N   7 
33 SN  SN   N   N 
34 SN  SN   N   N"#,
35        })
36        .as_object()
37        .unwrap()
38        .clone(),
39    )
40    .build(store.clone(), "/array")?;
41    array.store_metadata_opt(
42        &zarrs::array::ArrayMetadataOptions::default().with_include_zarrs_metadata(false),
43    )?;
44
45    println!("Array metadata:\n{}", array.metadata().to_string_pretty());
46
47    // Create some data with missing values
48    let data = ndarray::array![
49        [None, Some(None), Some(Some(2u8)), Some(Some(3u8))],
50        [None, Some(Some(5u8)), None, Some(Some(7u8))],
51        [Some(None), Some(None), None, None],
52        [Some(None), Some(None), None, None],
53    ]
54    .into_dyn();
55
56    // Write the data
57    array.store_array_subset(&array.subset_all(), data.clone())?;
58    println!("Data written to array.");
59
60    // Read back the data
61    let data_read: ArrayD<Option<Option<u8>>> = array.retrieve_array_subset(&array.subset_all())?;
62
63    // Verify data integrity
64    assert_eq!(data, data_read);
65
66    // Display the data in a grid format
67    println!(
68        "Data grid. N marks missing (`None`=`null`) values. SN marks `Some(None)`=`[null]` values"
69    );
70    println!("    0   1   2   3");
71    for y in 0..4 {
72        print!("{} ", y);
73        for x in 0..4 {
74            match data_read[[y, x]] {
75                Some(Some(value)) => print!("{:3} ", value),
76                Some(None) => print!(" SN "),
77                None => print!("  N "),
78            }
79        }
80        println!();
81    }
82    Ok(())
83}
More examples
Hide additional examples
examples/data_type_optional.rs (line 29)
18fn main() -> Result<(), Box<dyn std::error::Error>> {
19    // Create an in-memory store
20    // let store = Arc::new(zarrs::filesystem::FilesystemStore::new(
21    //     "zarrs/tests/data/v3/array_optional.zarr",
22    // )?);
23    let store = Arc::new(zarrs::storage::store::MemoryStore::new());
24
25    // Build the codec chains for the optional codec
26    let array = ArrayBuilder::new(
27        vec![4, 4],                       // 4x4 array
28        vec![2, 2],                       // 2x2 chunks
29        data_type::uint8().to_optional(), // Optional uint8
30        FillValue::new_optional_null(),   // Null fill value: [0]
31    )
32    .dimension_names(["y", "x"].into())
33    .attributes(
34        serde_json::json!({
35            "description": r#"A 4x4 array of optional uint8 values with some missing data.
36N marks missing (`None`=`null`) values:
37 0  N  2  3 
38 N  5  N  7 
39 8  9  N  N 
4012  N  N  N"#,
41        })
42        .as_object()
43        .unwrap()
44        .clone(),
45    )
46    .build(store.clone(), "/array")?;
47    array.store_metadata_opt(
48        &zarrs::array::ArrayMetadataOptions::default().with_include_zarrs_metadata(false),
49    )?;
50
51    println!("Array metadata:\n{}", array.metadata().to_string_pretty());
52
53    // Create some data with missing values
54    let data = ndarray::array![
55        [Some(0u8), None, Some(2u8), Some(3u8)],
56        [None, Some(5u8), None, Some(7u8)],
57        [Some(8u8), Some(9u8), None, None],
58        [Some(12u8), None, None, None],
59    ]
60    .into_dyn();
61
62    // Write the data
63    array.store_array_subset(&array.subset_all(), data.clone())?;
64
65    // Read back the data
66    let data_read: ArrayD<Option<u8>> = array.retrieve_array_subset(&array.subset_all())?;
67
68    // Verify data integrity
69    assert_eq!(data, data_read);
70
71    // Display the data in a grid format
72    println!("Data grid, N marks missing (`None`=`null`) values");
73    println!("   0  1  2  3");
74    for y in 0..4 {
75        print!("{} ", y);
76        for x in 0..4 {
77            match data_read[[y, x]] {
78                Some(value) => print!("{:2} ", value),
79                None => print!(" N "),
80            }
81        }
82        println!();
83    }
84
85    // Print the raw bytes in all chunks
86    println!("Raw bytes in all chunks:");
87    let chunk_grid_shape = array.chunk_grid_shape();
88    for chunk_y in 0..chunk_grid_shape[0] {
89        for chunk_x in 0..chunk_grid_shape[1] {
90            let chunk_indices = vec![chunk_y, chunk_x];
91            let chunk_key = array.chunk_key(&chunk_indices);
92            println!("  Chunk [{}, {}] (key: {}):", chunk_y, chunk_x, chunk_key);
93
94            if let Some(chunk_bytes) = store.get(&chunk_key)? {
95                println!("    Size: {} bytes", chunk_bytes.len());
96
97                if chunk_bytes.len() >= 16 {
98                    // Parse first 8 bytes as mask size (little-endian u64)
99                    let mask_size = u64::from_le_bytes([
100                        chunk_bytes[0],
101                        chunk_bytes[1],
102                        chunk_bytes[2],
103                        chunk_bytes[3],
104                        chunk_bytes[4],
105                        chunk_bytes[5],
106                        chunk_bytes[6],
107                        chunk_bytes[7],
108                    ]) as usize;
109
110                    // Parse second 8 bytes as data size (little-endian u64)
111                    let data_size = u64::from_le_bytes([
112                        chunk_bytes[8],
113                        chunk_bytes[9],
114                        chunk_bytes[10],
115                        chunk_bytes[11],
116                        chunk_bytes[12],
117                        chunk_bytes[13],
118                        chunk_bytes[14],
119                        chunk_bytes[15],
120                    ]) as usize;
121
122                    // Display mask size header with raw bytes
123                    print!("    Mask size: 0b");
124                    for byte in &chunk_bytes[0..8] {
125                        print!("{:08b}", byte);
126                    }
127                    println!(" -> {} bytes", mask_size);
128
129                    // Display data size header with raw bytes
130                    print!("    Data size: 0b");
131                    for byte in &chunk_bytes[8..16] {
132                        print!("{:08b}", byte);
133                    }
134                    println!(" -> {} bytes", data_size);
135
136                    // Show mask and data sections separately
137                    if chunk_bytes.len() >= 16 + mask_size + data_size {
138                        let mask_start = 16;
139                        let data_start = 16 + mask_size;
140
141                        // Show mask as binary
142                        if mask_size > 0 {
143                            println!("    Mask (binary):");
144                            print!("      ");
145                            for byte in &chunk_bytes[mask_start..mask_start + mask_size] {
146                                print!("0b{:08b} ", byte);
147                            }
148                            println!();
149                        }
150
151                        // Show data as binary
152                        if data_size > 0 {
153                            println!("    Data (binary):");
154                            print!("      ");
155                            for byte in &chunk_bytes[data_start..data_start + data_size] {
156                                print!("0b{:08b} ", byte);
157                            }
158                            println!();
159                        }
160                    }
161                } else {
162                    panic!("    Chunk too small to parse headers");
163                }
164            } else {
165                println!("    Chunk missing (fill value chunk)");
166            }
167        }
168    }
169    Ok(())
170}

Trait Implementations§

Source§

impl BitroundDataTypeExt for DataType

Source§

fn codec_bitround( &self, ) -> Result<&dyn BitroundDataTypeTraits, DataTypeCodecError>

Get bitround codec support for this data type. Read more
Source§

impl BytesDataTypeExt for DataType

Source§

fn codec_bytes(&self) -> Result<&dyn BytesDataTypeTraits, DataTypeCodecError>

Get bytes codec support for this data type. Read more
Source§

impl Clone for DataType

Source§

fn clone(&self) -> DataType

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 Debug for DataType

Source§

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

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

impl Deref for DataType

Source§

type Target = Arc<dyn DataTypeTraits>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &<DataType as Deref>::Target

Dereferences the value.
Source§

impl Display for DataType

Source§

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

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

impl ExtensionName for DataType

Source§

fn name(&self, version: ZarrVersion) -> Option<Cow<'static, str>>

Get the name for this extension instance for the given Zarr version. Read more
Source§

fn name_v3(&self) -> Option<Cow<'static, str>>

Get the name for this extension instance for Zarr V3. Read more
Source§

fn name_v2(&self) -> Option<Cow<'static, str>>

Get the name for this extension instance for Zarr V2. Read more
Source§

impl FixedScaleOffsetDataTypeExt for DataType

Source§

fn codec_fixedscaleoffset( &self, ) -> Result<&dyn FixedScaleOffsetDataTypeTraits, DataTypeCodecError>

Get fixedscaleoffset codec support for this data type. Read more
Source§

impl<T> From<Arc<T>> for DataType
where T: DataTypeTraits + 'static,

Source§

fn from(data_type: Arc<T>) -> DataType

Converts to this type from the input type.
Source§

impl From<Arc<dyn DataTypeTraits>> for DataType

Source§

fn from(value: Arc<dyn DataTypeTraits>) -> DataType

Converts to this type from the input type.
Source§

impl From<DataType> for ArrayBuilderDataType

Source§

fn from(value: DataType) -> Self

Converts to this type from the input type.
Source§

impl PackBitsDataTypeExt for DataType

Source§

fn codec_packbits( &self, ) -> Result<&dyn PackBitsDataTypeTraits, DataTypeCodecError>

Get packbits codec support for this data type. Read more
Source§

impl PartialEq for DataType

Source§

fn eq(&self, other: &DataType) -> 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 PcodecDataTypeExt for DataType

Source§

fn codec_pcodec(&self) -> Result<&dyn PcodecDataTypeTraits, DataTypeCodecError>

Get pcodec codec support for this data type. Read more
Source§

impl ZfpDataTypeExt for DataType

Source§

fn codec_zfp(&self) -> Result<&dyn ZfpDataTypeTraits, DataTypeCodecError>

Get zfp codec support for this data type. Read more
Source§

impl Eq for DataType

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<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.