rust_hdf5/attribute.rs
1//! Attribute support.
2//!
3//! Attributes are small metadata items attached to datasets (or groups).
4//! They are created via the [`AttrBuilder`] API obtained from
5//! [`H5Dataset::new_attr`](crate::dataset::H5Dataset::new_attr).
6//!
7//! # Example
8//!
9//! ```no_run
10//! use rust_hdf5::H5File;
11//! use rust_hdf5::types::VarLenUnicode;
12//!
13//! let file = H5File::create("attrs.h5").unwrap();
14//! let ds = file.new_dataset::<f32>().shape(&[10]).create("data").unwrap();
15//! let attr = ds.new_attr::<VarLenUnicode>().shape(()).create("units").unwrap();
16//! attr.write_scalar(&VarLenUnicode("meters".to_string())).unwrap();
17//! ```
18
19use std::marker::PhantomData;
20
21use crate::format::messages::attribute::AttributeMessage;
22use crate::format::messages::datatype::DatatypeMessage;
23
24use crate::error::{Hdf5Error, Result};
25use crate::file::{borrow_inner_mut, clone_inner, H5FileInner, SharedInner};
26use crate::types::VarLenUnicode;
27
28/// A handle to an HDF5 attribute.
29///
30/// After creating an attribute via [`AttrBuilder::create`], use
31/// [`write_scalar`](Self::write_scalar) or [`write_string`](Self::write_string)
32/// to set its value.
33///
34/// In read mode, use [`read_string`](Self::read_string) to read string attributes.
35pub struct H5Attribute {
36 file_inner: SharedInner,
37 ds_index: usize,
38 name: String,
39 /// Dimensions for write-mode array attributes (empty = scalar). Set from
40 /// [`AttrBuilder::shape`] and consumed by [`write_array`](Self::write_array).
41 write_dims: Vec<usize>,
42 /// The decoded attribute message for read-mode handles (carries the
43 /// datatype, needed to resolve variable-length string values).
44 read_attr: Option<AttributeMessage>,
45}
46
47impl H5Attribute {
48 /// Create a read-mode attribute handle from a decoded attribute message.
49 pub(crate) fn new_reader(file_inner: SharedInner, attr_msg: AttributeMessage) -> Self {
50 Self {
51 file_inner,
52 ds_index: usize::MAX,
53 name: attr_msg.name.clone(),
54 write_dims: Vec::new(),
55 read_attr: Some(attr_msg),
56 }
57 }
58
59 /// Return the attribute name.
60 pub fn name(&self) -> &str {
61 &self.name
62 }
63
64 /// Write a scalar value to the attribute.
65 ///
66 /// For `VarLenUnicode`, this writes a fixed-length string attribute
67 /// whose size is determined by the string value.
68 pub fn write_scalar(&self, value: &VarLenUnicode) -> Result<()> {
69 let attr_msg = AttributeMessage::scalar_string(&self.name, &value.0);
70
71 let mut inner = borrow_inner_mut(&self.file_inner);
72 match &mut *inner {
73 H5FileInner::Writer(writer) => {
74 writer.add_dataset_attribute(self.ds_index, attr_msg)?;
75 Ok(())
76 }
77 H5FileInner::Reader(_) => Err(Hdf5Error::InvalidState(
78 "cannot write attributes in read mode".into(),
79 )),
80 H5FileInner::Closed => Err(Hdf5Error::InvalidState("file is closed".into())),
81 }
82 }
83
84 /// Write a string value to the attribute (convenience method).
85 pub fn write_string(&self, value: &str) -> Result<()> {
86 self.write_scalar(&VarLenUnicode(value.to_string()))
87 }
88
89 /// Write a numeric scalar attribute.
90 ///
91 /// ```no_run
92 /// # use rust_hdf5::H5File;
93 /// let file = H5File::create("num_attr.h5").unwrap();
94 /// let ds = file.new_dataset::<f32>().shape(&[10]).create("data").unwrap();
95 /// ds.write_raw(&[0.0f32; 10]).unwrap();
96 /// let attr = ds.new_attr::<f64>().shape(()).create("scale").unwrap();
97 /// attr.write_numeric(&3.14f64).unwrap();
98 /// ```
99 pub fn write_numeric<T: crate::types::H5Type>(&self, value: &T) -> Result<()> {
100 let es = T::element_size();
101 let raw = unsafe { std::slice::from_raw_parts(value as *const T as *const u8, es) };
102 let attr_msg = AttributeMessage::scalar_numeric(&self.name, T::hdf5_type(), raw.to_vec());
103
104 let mut inner = borrow_inner_mut(&self.file_inner);
105 match &mut *inner {
106 H5FileInner::Writer(writer) => {
107 writer.add_dataset_attribute(self.ds_index, attr_msg)?;
108 Ok(())
109 }
110 H5FileInner::Reader(_) => Err(Hdf5Error::InvalidState(
111 "cannot write attributes in read mode".into(),
112 )),
113 H5FileInner::Closed => Err(Hdf5Error::InvalidState("file is closed".into())),
114 }
115 }
116
117 /// Write a numeric array attribute.
118 ///
119 /// The number of `values` must equal the product of the dimensions set
120 /// via [`AttrBuilder::shape`]; if no shape was set the attribute is a
121 /// scalar and exactly one value is required. The on-disk datatype is
122 /// `T::hdf5_type()` and the dataspace is the simple dataspace described by
123 /// the shape — matching the 1-D `int32` array attributes AreaDetector
124 /// writes (e.g. `NDArrayDimOffset`, `Binning`, `Reverse`).
125 ///
126 /// ```no_run
127 /// # use rust_hdf5::H5File;
128 /// let file = H5File::create("arr_attr.h5").unwrap();
129 /// let ds = file.new_dataset::<f32>().shape(&[10]).create("data").unwrap();
130 /// ds.write_raw(&[0.0f32; 10]).unwrap();
131 /// let attr = ds.new_attr::<i32>().shape([3]).create("dim_offset").unwrap();
132 /// attr.write_array(&[0i32, 4, 8]).unwrap();
133 /// ```
134 pub fn write_array<T: crate::types::H5Type>(&self, values: &[T]) -> Result<()> {
135 // Product of an empty shape is 1 (a scalar holds one element).
136 let expected: usize = self.write_dims.iter().product();
137 if values.len() != expected {
138 return Err(Hdf5Error::InvalidState(format!(
139 "attribute '{}' shape {:?} needs {} elements, got {}",
140 self.name,
141 self.write_dims,
142 expected,
143 values.len()
144 )));
145 }
146
147 let es = T::element_size();
148 // Safety: `T: H5Type` is a `Copy` numeric primitive with a defined
149 // byte representation; `element_size()` matches `size_of::<T>()`. The
150 // slice borrows `values` only for this call.
151 let raw =
152 unsafe { std::slice::from_raw_parts(values.as_ptr() as *const u8, values.len() * es) };
153 let dims_u64: Vec<u64> = self.write_dims.iter().map(|&d| d as u64).collect();
154 let attr_msg =
155 AttributeMessage::array_numeric(&self.name, T::hdf5_type(), &dims_u64, raw.to_vec());
156
157 let mut inner = borrow_inner_mut(&self.file_inner);
158 match &mut *inner {
159 H5FileInner::Writer(writer) => {
160 writer.add_dataset_attribute(self.ds_index, attr_msg)?;
161 Ok(())
162 }
163 H5FileInner::Reader(_) => Err(Hdf5Error::InvalidState(
164 "cannot write attributes in read mode".into(),
165 )),
166 H5FileInner::Closed => Err(Hdf5Error::InvalidState("file is closed".into())),
167 }
168 }
169
170 /// Read a numeric scalar attribute.
171 ///
172 /// ```no_run
173 /// # use rust_hdf5::H5File;
174 /// let file = H5File::open("num_attr.h5").unwrap();
175 /// let ds = file.dataset("data").unwrap();
176 /// let attr = ds.attr("scale").unwrap();
177 /// let val: f64 = attr.read_numeric().unwrap();
178 /// ```
179 pub fn read_numeric<T: crate::types::H5Type>(&self) -> Result<T> {
180 let data = self
181 .read_attr
182 .as_ref()
183 .map(|a| &a.data)
184 .ok_or_else(|| Hdf5Error::InvalidState("attribute has no read data".into()))?;
185 let es = T::element_size();
186 if data.len() < es {
187 return Err(Hdf5Error::TypeMismatch(format!(
188 "attribute data {} bytes, need {} for type",
189 data.len(),
190 es
191 )));
192 }
193 unsafe {
194 let mut val = std::mem::MaybeUninit::<T>::uninit();
195 std::ptr::copy_nonoverlapping(data.as_ptr(), val.as_mut_ptr() as *mut u8, es);
196 Ok(val.assume_init())
197 }
198 }
199
200 /// Read the attribute value as a string.
201 ///
202 /// Handles both fixed-length string attributes and variable-length
203 /// string attributes (h5py's default), resolving a vlen value through
204 /// the global heap.
205 pub fn read_string(&self) -> Result<String> {
206 let attr = self.read_attr.as_ref().ok_or_else(|| {
207 Hdf5Error::InvalidState("attribute has no read data (write-mode handle?)".into())
208 })?;
209 let mut inner = borrow_inner_mut(&self.file_inner);
210 match &mut *inner {
211 H5FileInner::Reader(reader) => Ok(reader.attr_string_value(attr)?),
212 _ => {
213 // No reader available — fall back to the raw fixed-length
214 // interpretation.
215 let end = attr
216 .data
217 .iter()
218 .position(|&b| b == 0)
219 .unwrap_or(attr.data.len());
220 Ok(String::from_utf8_lossy(&attr.data[..end]).to_string())
221 }
222 }
223 }
224
225 /// Return the attribute datatype as parsed from the file (read mode only).
226 ///
227 /// Mirrors [`H5Dataset::datatype`](crate::dataset::H5Dataset::datatype):
228 /// it exposes the full datatype — class (integer vs floating-point vs
229 /// string vs compound …), signedness, byte order and bit precision — so
230 /// callers mapping an attribute to a NumPy / Arrow dtype need not infer a
231 /// type from the byte width, which cannot distinguish `u8` from `i8` (both
232 /// 1 byte) or `i32` from `f32` (both 4 bytes).
233 ///
234 /// # Errors
235 ///
236 /// Returns an error for a write-mode handle, which carries no decoded
237 /// attribute message.
238 ///
239 /// ```no_run
240 /// # use rust_hdf5::{H5File, DatatypeMessage};
241 /// let file = H5File::open("data.h5").unwrap();
242 /// let ds = file.dataset("image").unwrap();
243 /// let attr = ds.attr("scale").unwrap();
244 /// match attr.datatype().unwrap() {
245 /// DatatypeMessage::FloatingPoint { size, .. } => println!("float: {size} bytes"),
246 /// other => println!("other type: {other}"),
247 /// }
248 /// ```
249 pub fn datatype(&self) -> Result<DatatypeMessage> {
250 self.read_attr
251 .as_ref()
252 .map(|a| a.datatype.clone())
253 .ok_or_else(|| {
254 Hdf5Error::InvalidState("attribute has no read data (write-mode handle?)".into())
255 })
256 }
257
258 /// Read the raw attribute data bytes.
259 pub fn read_raw(&self) -> Result<Vec<u8>> {
260 self.read_attr
261 .as_ref()
262 .map(|a| a.data.clone())
263 .ok_or_else(|| {
264 Hdf5Error::InvalidState("attribute has no read data (write-mode handle?)".into())
265 })
266 }
267}
268
269/// Shapes accepted by [`AttrBuilder::shape`].
270///
271/// `()` selects a scalar attribute (rank 0). A slice, array, or `Vec` of
272/// `usize` selects a simple dataspace with those dimension sizes — e.g.
273/// `[3]` for a 1-D array attribute of length 3.
274pub trait AttrShape {
275 /// Dimension sizes for the attribute; empty for a scalar.
276 fn attr_dims(&self) -> Vec<usize>;
277}
278
279impl AttrShape for () {
280 fn attr_dims(&self) -> Vec<usize> {
281 Vec::new()
282 }
283}
284
285impl AttrShape for &[usize] {
286 fn attr_dims(&self) -> Vec<usize> {
287 self.to_vec()
288 }
289}
290
291impl<const N: usize> AttrShape for [usize; N] {
292 fn attr_dims(&self) -> Vec<usize> {
293 self.to_vec()
294 }
295}
296
297impl<const N: usize> AttrShape for &[usize; N] {
298 fn attr_dims(&self) -> Vec<usize> {
299 self.to_vec()
300 }
301}
302
303impl AttrShape for Vec<usize> {
304 fn attr_dims(&self) -> Vec<usize> {
305 self.clone()
306 }
307}
308
309/// A fluent builder for creating attributes on datasets.
310///
311/// Obtained from [`H5Dataset::new_attr::<T>()`](crate::dataset::H5Dataset::new_attr).
312pub struct AttrBuilder<'a, T> {
313 file_inner: &'a SharedInner,
314 ds_index: usize,
315 dims: Vec<usize>,
316 _marker: PhantomData<T>,
317}
318
319impl<'a, T> AttrBuilder<'a, T> {
320 pub(crate) fn new(file_inner: &'a SharedInner, ds_index: usize) -> Self {
321 Self {
322 file_inner,
323 ds_index,
324 dims: Vec::new(),
325 _marker: PhantomData,
326 }
327 }
328
329 /// Set the attribute shape.
330 ///
331 /// Use `()` for a scalar attribute, or an array/slice of dimension sizes
332 /// for an array attribute (e.g. `[3]` for a 1-D array of length 3). The
333 /// shape is consumed by [`H5Attribute::write_array`]; the scalar writers
334 /// ([`write_scalar`](H5Attribute::write_scalar),
335 /// [`write_numeric`](H5Attribute::write_numeric)) ignore it.
336 #[must_use]
337 pub fn shape<S: AttrShape>(mut self, shape: S) -> Self {
338 self.dims = shape.attr_dims();
339 self
340 }
341
342 /// Create the attribute with the given name.
343 ///
344 /// The attribute is created but does not yet have a value.
345 /// Call [`H5Attribute::write_scalar`] or
346 /// [`H5Attribute::write_array`] to set the value.
347 pub fn create(self, name: &str) -> Result<H5Attribute> {
348 Ok(H5Attribute {
349 file_inner: clone_inner(self.file_inner),
350 ds_index: self.ds_index,
351 name: name.to_string(),
352 write_dims: self.dims,
353 read_attr: None,
354 })
355 }
356}