Skip to main content

hapi_rs/attribute/
mod.rs

1//! Typed handles for geometry attributes.
2//!
3//! Attribute handles are bound to a node, part, owner, and name when they are
4//! created or looked up. Consequently, [`Attribute::get`] and
5//! [`Attribute::set`] do not accept a part id: use a separate lookup to obtain
6//! a handle for another part. HAPI part ids are indices that can change after a
7//! cook, so reacquire handles after a cook that may change the part layout.
8//!
9//! The shape marker distinguishes ordinary fixed-tuple attributes from HAPI
10//! array attributes:
11//!
12//! - [`Attribute<T, Fixed>`](Attribute) reads and writes a flat `Vec<T>` whose
13//!   length is `count * tuple_size`.
14//! - [`Attribute<T, Jagged>`](Attribute) uses [`JaggedArrayData<T>`], containing
15//!   flattened values plus one array size for every owned element.
16//! - [`StringAttribute`] and [`DictionaryAttribute`] follow the same
17//!   [`Fixed`]/[`Jagged`] distinction.
18//!
19//! Fixed attributes also expose checked range operations. Range indices refer
20//! to owned geometry elements, not flattened tuple values.
21
22mod array;
23#[cfg(feature = "async-cooking")]
24mod async_;
25
26pub use crate::ffi::AttributeInfo;
27pub use crate::ffi::enums::StorageType;
28pub use array::{JaggedArrayData, JaggedArrayIter, StringJaggedArrayData, StringJaggedArrayIter};
29#[cfg(feature = "async-cooking")]
30pub use async_::{
31    AsyncAttributeAccess, AsyncFixedAttributeAccess, AsyncJob, AsyncStringAttributeAccess,
32    AsyncStringAttributeWrite,
33};
34
35use crate::errors::{HapiError, Result};
36#[doc(hidden)]
37pub use crate::ffi::NumericPrimitive;
38use crate::ffi::enums::AttributeOwner;
39use crate::node::HoudiniNode;
40use crate::stringhandle::StringArray;
41use std::borrow::Cow;
42use std::ffi::{CStr, CString};
43use std::marker::PhantomData;
44use std::ops::Range;
45
46#[derive(Debug, Clone, Copy)]
47/// Marker for an ordinary HAPI attribute with a fixed tuple size.
48pub struct Fixed;
49#[derive(Debug, Clone, Copy)]
50/// Marker for a HAPI array attribute whose entries may have different lengths.
51pub struct Jagged;
52
53mod private {
54    pub trait Sealed {}
55}
56impl private::Sealed for Fixed {}
57impl private::Sealed for Jagged {}
58
59/// Sealed mapping from an attribute shape and numeric Rust type to HAPI storage.
60///
61/// Implemented by [`Fixed`] and [`Jagged`]. It is primarily used as a generic
62/// bound on typed lookup and creation methods.
63pub trait AttributeShape: private::Sealed + Send + 'static {
64    fn storage<T: NumericPrimitive>() -> StorageType;
65}
66impl AttributeShape for Fixed {
67    fn storage<T: NumericPrimitive>() -> StorageType {
68        T::FIXED_STORAGE
69    }
70}
71impl AttributeShape for Jagged {
72    fn storage<T: NumericPrimitive>() -> StorageType {
73        T::JAGGED_STORAGE
74    }
75}
76
77#[derive(Debug, Clone)]
78struct Handle {
79    info: AttributeInfo,
80    name: CString,
81    node: HoudiniNode,
82    part_id: i32,
83    owner: AttributeOwner,
84}
85
86impl Handle {
87    fn new(name: CString, info: AttributeInfo, node: HoudiniNode, part_id: i32) -> Self {
88        let owner = info.owner();
89        Self {
90            info,
91            name,
92            node,
93            part_id,
94            owner,
95        }
96    }
97
98    fn refresh(&mut self, expected: StorageType) -> Result<()> {
99        let info = AttributeInfo::new(&self.node, self.part_id, self.owner, &self.name)?;
100        if !info.exists() {
101            return Err(HapiError::Internal(format!(
102                "attribute {:?} no longer exists on part {} for owner {:?}",
103                self.name, self.part_id, self.owner
104            )));
105        }
106        if info.storage() != expected {
107            return Err(HapiError::Internal(format!(
108                "attribute {:?} storage changed from {:?} to {:?}",
109                self.name,
110                expected,
111                info.storage()
112            )));
113        }
114        self.info = info;
115        Ok(())
116    }
117
118    fn expected_fixed_len(info: &AttributeInfo) -> Result<usize> {
119        let len = info
120            .count()
121            .checked_mul(info.tuple_size())
122            .ok_or_else(|| HapiError::Internal("attribute buffer length overflow".into()))?;
123        usize::try_from(len)
124            .map_err(|_| HapiError::Internal("attribute buffer length is negative".into()))
125    }
126
127    fn checked_fixed_range(&self, range: Range<usize>) -> Result<(i32, i32, usize)> {
128        if range.start > range.end {
129            return Err(HapiError::Internal(format!(
130                "attribute {:?} range start {} exceeds end {}",
131                self.name, range.start, range.end
132            )));
133        }
134        let count = usize::try_from(self.info.count())
135            .map_err(|_| HapiError::Internal("negative attribute count".into()))?;
136        if range.end > count {
137            return Err(HapiError::Internal(format!(
138                "attribute {:?} range end {} exceeds count {count}",
139                self.name, range.end
140            )));
141        }
142        let tuple_size = usize::try_from(self.info.tuple_size())
143            .map_err(|_| HapiError::Internal("negative attribute tuple size".into()))?;
144        let value_len = (range.end - range.start)
145            .checked_mul(tuple_size)
146            .ok_or_else(|| HapiError::Internal("attribute range length overflow".into()))?;
147        let start = i32::try_from(range.start)
148            .map_err(|_| HapiError::Internal("attribute range start exceeds i32".into()))?;
149        let count = i32::try_from(range.end - range.start)
150            .map_err(|_| HapiError::Internal("attribute range length exceeds i32".into()))?;
151        Ok((start, count, value_len))
152    }
153}
154
155fn validate_string_indices(value_count: usize, indices: &[i32]) -> Result<()> {
156    for (position, &index) in indices.iter().enumerate() {
157        let index = usize::try_from(index).map_err(|_| {
158            HapiError::Internal(format!(
159                "indexed string index at position {position} is negative: {index}"
160            ))
161        })?;
162        if index >= value_count {
163            return Err(HapiError::Internal(format!(
164                "indexed string index at position {position} is {index}, but the value table has {value_count} entries"
165            )));
166        }
167    }
168    Ok(())
169}
170
171#[derive(Debug, Clone)]
172/// A typed numeric geometry attribute handle.
173///
174/// `T` determines the numeric primitive storage and `S` determines whether the
175/// attribute is fixed-tuple or jagged. The handle retains its node, part,
176/// owner, and name identity. Data operations use cached metadata so they do not
177/// add a hidden HAPI query to hot paths.
178pub struct Attribute<T: NumericPrimitive, S: AttributeShape> {
179    handle: Handle,
180    marker: PhantomData<(T, S)>,
181}
182
183impl<T: NumericPrimitive, S: AttributeShape> Attribute<T, S> {
184    pub(crate) fn new(name: CString, info: AttributeInfo, node: HoudiniNode, part_id: i32) -> Self {
185        Self {
186            handle: Handle::new(name, info, node, part_id),
187            marker: PhantomData,
188        }
189    }
190    /// Returns the currently cached metadata.
191    #[must_use]
192    pub fn info(&self) -> &AttributeInfo {
193        &self.handle.info
194    }
195    /// Returns the attribute name.
196    #[must_use]
197    pub fn name(&self) -> &CStr {
198        &self.handle.name
199    }
200    /// Returns the HAPI part to which this handle is bound.
201    #[must_use]
202    pub fn part_id(&self) -> i32 {
203        self.handle.part_id
204    }
205    /// Returns the element owner of this attribute.
206    #[must_use]
207    pub fn owner(&self) -> AttributeOwner {
208        self.handle.owner
209    }
210    /// Returns the HAPI storage implied by `T` and `S`.
211    #[must_use]
212    pub fn storage(&self) -> StorageType {
213        S::storage::<T>()
214    }
215    /// Refreshes cached metadata from HAPI.
216    ///
217    /// Call this after cooking or otherwise changing geometry when the
218    /// attribute's count, tuple size, or array element total may have changed.
219    /// The cache is updated only if the attribute still exists and retains the
220    /// numeric storage implied by `T` and `S`.
221    pub fn refresh(&mut self) -> Result<()> {
222        self.handle.refresh(S::storage::<T>())
223    }
224    /// Deletes this attribute from its bound node and part.
225    pub fn delete(self) -> Result<()> {
226        crate::ffi::delete_attribute(
227            &self.handle.node,
228            self.handle.part_id,
229            &self.handle.name,
230            &self.handle.info.0,
231        )
232    }
233}
234
235impl<T: NumericPrimitive> Attribute<T, Fixed> {
236    /// Reads the complete fixed-tuple attribute as a flat vector.
237    ///
238    /// The result length is `count * tuple_size` using cached metadata.
239    pub fn get(&self) -> Result<Vec<T>> {
240        let info = &self.handle.info;
241        let mut data = vec![T::default(); Handle::expected_fixed_len(info)?];
242        T::get_fixed(
243            &self.handle.node,
244            self.handle.part_id,
245            &self.handle.name,
246            &info.0,
247            &mut data,
248            0,
249            info.count(),
250        )?;
251        Ok(data)
252    }
253
254    /// Reads the complete attribute into a reusable vector.
255    ///
256    /// `data` is resized to `count * tuple_size` before the HAPI call.
257    pub fn read_into(&self, data: &mut Vec<T>) -> Result<()> {
258        let info = &self.handle.info;
259        data.resize(Handle::expected_fixed_len(info)?, T::default());
260        T::get_fixed(
261            &self.handle.node,
262            self.handle.part_id,
263            &self.handle.name,
264            &info.0,
265            data,
266            0,
267            info.count(),
268        )
269    }
270
271    /// Reads a range of owned elements as flattened tuples.
272    pub fn get_range(&self, range: Range<usize>) -> Result<Vec<T>> {
273        let (start, count, value_len) = self.handle.checked_fixed_range(range)?;
274        let mut data = vec![T::default(); value_len];
275        if count == 0 {
276            return Ok(data);
277        }
278        T::get_fixed(
279            &self.handle.node,
280            self.handle.part_id,
281            &self.handle.name,
282            &self.handle.info.0,
283            &mut data,
284            start,
285            count,
286        )?;
287        Ok(data)
288    }
289
290    /// Reads a range of owned elements into a reusable flattened vector.
291    pub fn read_range_into(&self, range: Range<usize>, data: &mut Vec<T>) -> Result<()> {
292        let (start, count, value_len) = self.handle.checked_fixed_range(range)?;
293        data.resize(value_len, T::default());
294        if count == 0 {
295            return Ok(());
296        }
297        T::get_fixed(
298            &self.handle.node,
299            self.handle.part_id,
300            &self.handle.name,
301            &self.handle.info.0,
302            data,
303            start,
304            count,
305        )
306    }
307
308    /// Replaces the complete fixed-tuple attribute.
309    ///
310    /// Returns an error unless `data.len() == count * tuple_size`.
311    pub fn set(&self, data: &[T]) -> Result<()> {
312        let info = &self.handle.info;
313        let expected = Handle::expected_fixed_len(info)?;
314        if data.len() != expected {
315            return Err(HapiError::Internal(format!(
316                "attribute {:?} needs {expected} values, got {}",
317                self.handle.name,
318                data.len()
319            )));
320        }
321        T::set_fixed(
322            &self.handle.node,
323            self.handle.part_id,
324            &self.handle.name,
325            &info.0,
326            data,
327            0,
328            info.count(),
329        )
330    }
331
332    /// Replaces a range of owned elements from flattened tuples.
333    pub fn set_range(&self, range: Range<usize>, data: &[T]) -> Result<()> {
334        let (start, count, expected) = self.handle.checked_fixed_range(range)?;
335        if data.len() != expected {
336            return Err(HapiError::Internal(format!(
337                "attribute {:?} range needs {expected} values, got {}",
338                self.handle.name,
339                data.len()
340            )));
341        }
342        if count == 0 {
343            return Ok(());
344        }
345        T::set_fixed(
346            &self.handle.node,
347            self.handle.part_id,
348            &self.handle.name,
349            &self.handle.info.0,
350            data,
351            start,
352            count,
353        )
354    }
355
356    /// Assigns the same tuple value to every element of the attribute.
357    ///
358    /// `value` must contain exactly `tuple_size` numeric values.
359    pub fn set_unique(&self, value: &[T]) -> Result<()> {
360        let info = &self.handle.info;
361        let expected = usize::try_from(info.tuple_size())
362            .map_err(|_| HapiError::Internal("negative tuple size".into()))?;
363        if value.len() != expected {
364            return Err(HapiError::Internal(format!(
365                "unique value needs {expected} tuple values, got {}",
366                value.len()
367            )));
368        }
369        T::set_unique(
370            &self.handle.node,
371            self.handle.part_id,
372            &self.handle.name,
373            &info.0,
374            value,
375        )
376    }
377}
378
379impl<T: NumericPrimitive> Attribute<T, Jagged> {
380    /// Reads the complete HAPI array attribute.
381    pub fn get(&self) -> Result<JaggedArrayData<T>> {
382        let info = &self.handle.info;
383        let total = usize::try_from(info.total_array_elements())
384            .map_err(|_| HapiError::Internal("negative jagged element count".into()))?;
385        let count = usize::try_from(info.count())
386            .map_err(|_| HapiError::Internal("negative attribute count".into()))?;
387        let mut data = vec![T::default(); total];
388        let mut sizes = vec![0; count];
389        T::get_jagged(
390            &self.handle.node,
391            self.handle.part_id,
392            &self.handle.name,
393            &info.0,
394            &mut data,
395            &mut sizes,
396        )?;
397        JaggedArrayData::from_hapi(data, sizes)
398    }
399
400    /// Replaces the complete HAPI array attribute.
401    ///
402    /// The number of sizes must equal the cached attribute count. The
403    /// [`JaggedArrayData`] constructor additionally guarantees that sizes are
404    /// nonnegative and sum to the flattened data length.
405    pub fn set(&self, values: &JaggedArrayData<T>) -> Result<()> {
406        let info = &self.handle.info;
407        let expected = usize::try_from(info.count())
408            .map_err(|_| HapiError::Internal("negative attribute count".into()))?;
409        if values.sizes().len() != expected {
410            return Err(HapiError::Internal(format!(
411                "attribute {:?} needs {expected} array sizes, got {}",
412                self.handle.name,
413                values.sizes().len()
414            )));
415        }
416        T::set_jagged(
417            &self.handle.node,
418            self.handle.part_id,
419            &self.handle.name,
420            &info.0,
421            values.data(),
422            values.sizes(),
423        )
424    }
425}
426
427#[derive(Debug, Clone)]
428/// A typed string attribute handle.
429///
430/// Use [`Fixed`] for ordinary string tuples and [`Jagged`] for HAPI string
431/// array attributes.
432pub struct StringAttribute<S: AttributeShape> {
433    handle: Handle,
434    marker: PhantomData<S>,
435}
436#[derive(Debug, Clone)]
437/// A typed JSON dictionary attribute handle.
438///
439/// Use [`Fixed`] for ordinary dictionary tuples and [`Jagged`] for HAPI
440/// dictionary array attributes.
441pub struct DictionaryAttribute<S: AttributeShape> {
442    handle: Handle,
443    marker: PhantomData<S>,
444}
445
446macro_rules! common_handle {
447    ($type:ident) => {
448        impl<S: AttributeShape> $type<S> {
449            pub(crate) fn new(
450                name: CString,
451                info: AttributeInfo,
452                node: HoudiniNode,
453                part_id: i32,
454            ) -> Self {
455                Self {
456                    handle: Handle::new(name, info, node, part_id),
457                    marker: PhantomData,
458                }
459            }
460            /// Returns the currently cached metadata.
461            #[must_use]
462            pub fn info(&self) -> &AttributeInfo {
463                &self.handle.info
464            }
465            /// Returns the attribute name.
466            #[must_use]
467            pub fn name(&self) -> &CStr {
468                &self.handle.name
469            }
470            /// Returns the HAPI part to which this handle is bound.
471            #[must_use]
472            pub fn part_id(&self) -> i32 {
473                self.handle.part_id
474            }
475            /// Returns the element owner of this attribute.
476            #[must_use]
477            pub fn owner(&self) -> AttributeOwner {
478                self.handle.owner
479            }
480            /// Returns the HAPI storage type.
481            #[must_use]
482            pub fn storage(&self) -> StorageType {
483                self.handle.info.storage()
484            }
485            /// Deletes this attribute from its bound node and part.
486            pub fn delete(self) -> Result<()> {
487                crate::ffi::delete_attribute(
488                    &self.handle.node,
489                    self.handle.part_id,
490                    &self.handle.name,
491                    &self.handle.info.0,
492                )
493            }
494        }
495    };
496}
497common_handle!(StringAttribute);
498common_handle!(DictionaryAttribute);
499
500impl StringAttribute<Fixed> {
501    /// Refreshes cached metadata, requiring fixed string storage.
502    pub fn refresh(&mut self) -> Result<()> {
503        self.handle.refresh(StorageType::String)
504    }
505}
506
507impl StringAttribute<Jagged> {
508    /// Refreshes cached metadata, requiring jagged string storage.
509    pub fn refresh(&mut self) -> Result<()> {
510        self.handle.refresh(StorageType::StringArray)
511    }
512}
513
514impl DictionaryAttribute<Fixed> {
515    /// Refreshes cached metadata, requiring fixed dictionary storage.
516    pub fn refresh(&mut self) -> Result<()> {
517        self.handle.refresh(StorageType::Dictionary)
518    }
519}
520
521impl DictionaryAttribute<Jagged> {
522    /// Refreshes cached metadata, requiring jagged dictionary storage.
523    pub fn refresh(&mut self) -> Result<()> {
524        self.handle.refresh(StorageType::DictionaryArray)
525    }
526}
527
528macro_rules! fixed_string_impl {
529    ($type:ident, $storage:expr, $dictionary:expr) => {
530        impl $type<Fixed> {
531            /// Reads the complete fixed-tuple attribute.
532            pub fn get(&self) -> Result<StringArray> {
533                let info = &self.handle.info;
534                crate::ffi::get_string_attribute_data(
535                    &self.handle.node,
536                    self.handle.part_id,
537                    &self.handle.name,
538                    &info.0,
539                    $dictionary,
540                    0,
541                    info.count(),
542                )
543            }
544            /// Reads a range of owned elements as flattened string tuples.
545            pub fn get_range(&self, range: Range<usize>) -> Result<StringArray> {
546                let (start, count, _) = self.handle.checked_fixed_range(range)?;
547                if count == 0 {
548                    return Ok(StringArray::empty());
549                }
550                crate::ffi::get_string_attribute_data(
551                    &self.handle.node,
552                    self.handle.part_id,
553                    &self.handle.name,
554                    &self.handle.info.0,
555                    $dictionary,
556                    start,
557                    count,
558                )
559            }
560            /// Replaces the complete fixed-tuple attribute.
561            ///
562            /// The value count must equal `count * tuple_size`.
563            pub fn set(&self, values: &[impl AsRef<CStr>]) -> Result<()> {
564                let info = &self.handle.info;
565                let expected = Handle::expected_fixed_len(info)?;
566                if values.len() != expected {
567                    return Err(HapiError::Internal(format!(
568                        "attribute {:?} needs {expected} strings, got {}",
569                        self.handle.name,
570                        values.len()
571                    )));
572                }
573                let ptrs: Vec<_> = values.iter().map(|v| v.as_ref().as_ptr()).collect();
574                crate::ffi::set_string_attribute_data(
575                    &self.handle.node,
576                    self.handle.part_id,
577                    &self.handle.name,
578                    &info.0,
579                    &ptrs,
580                    $dictionary,
581                    0,
582                    info.count(),
583                )
584            }
585            /// Replaces a range of owned elements from flattened string tuples.
586            pub fn set_range(
587                &self,
588                range: Range<usize>,
589                values: &[impl AsRef<CStr>],
590            ) -> Result<()> {
591                let (start, count, expected) = self.handle.checked_fixed_range(range)?;
592                if values.len() != expected {
593                    return Err(HapiError::Internal(format!(
594                        "attribute {:?} range needs {expected} strings, got {}",
595                        self.handle.name,
596                        values.len()
597                    )));
598                }
599                if count == 0 {
600                    return Ok(());
601                }
602                let ptrs: Vec<_> = values.iter().map(|v| v.as_ref().as_ptr()).collect();
603                crate::ffi::set_string_attribute_data(
604                    &self.handle.node,
605                    self.handle.part_id,
606                    &self.handle.name,
607                    &self.handle.info.0,
608                    &ptrs,
609                    $dictionary,
610                    start,
611                    count,
612                )
613            }
614        }
615    };
616}
617fixed_string_impl!(StringAttribute, StorageType::String, false);
618fixed_string_impl!(DictionaryAttribute, StorageType::Dictionary, true);
619
620impl StringAttribute<Fixed> {
621    /// Assigns one string value to every element of the attribute.
622    pub fn set_unique(&self, value: &CStr) -> Result<()> {
623        let info = &self.handle.info;
624        crate::ffi::set_string_unique_attribute_data(
625            &self.handle.node,
626            self.handle.part_id,
627            &self.handle.name,
628            &info.0,
629            value,
630        )
631    }
632    /// Sets the complete attribute using a table of unique strings and indices.
633    ///
634    /// `indices` must contain `count * tuple_size` entries. Each index is
635    /// interpreted by HAPI as an entry in `values`.
636    pub fn set_indexed(&self, values: &[impl AsRef<CStr>], indices: &[i32]) -> Result<()> {
637        let info = &self.handle.info;
638        let expected = Handle::expected_fixed_len(info)?;
639        if indices.len() != expected {
640            return Err(HapiError::Internal(format!(
641                "attribute {:?} needs {expected} indices, got {}",
642                self.handle.name,
643                indices.len()
644            )));
645        }
646        validate_string_indices(values.len(), indices)?;
647        let ptrs: Vec<_> = values.iter().map(|v| v.as_ref().as_ptr()).collect();
648        crate::ffi::set_indexed_string_attribute_data(
649            &self.handle.node,
650            self.handle.part_id,
651            &self.handle.name,
652            &info.0,
653            &ptrs,
654            indices,
655        )
656    }
657}
658
659macro_rules! jagged_string_impl {
660    ($type:ident, $storage:expr, $dictionary:expr) => {
661        impl $type<Jagged> {
662            /// Reads the complete string or dictionary array attribute.
663            pub fn get(&self) -> Result<StringJaggedArrayData> {
664                let info = &self.handle.info;
665                let (values, sizes) = crate::ffi::get_string_jagged_attribute_data(
666                    &self.handle.node,
667                    self.handle.part_id,
668                    &self.handle.name,
669                    &info.0,
670                    $dictionary,
671                )?;
672                StringJaggedArrayData::from_hapi(values, sizes)
673            }
674            /// Replaces the complete string or dictionary array attribute.
675            ///
676            /// Sizes must be nonnegative, sum to `values.len()`, and contain
677            /// one entry for every owned geometry element.
678            pub fn set(&self, values: &[impl AsRef<CStr>], sizes: &[i32]) -> Result<()> {
679                let info = &self.handle.info;
680                let validated =
681                    JaggedArrayData::new(values.iter().map(|_| ()).collect(), sizes.to_vec())?;
682                let expected = usize::try_from(info.count())
683                    .map_err(|_| HapiError::Internal("negative attribute count".into()))?;
684                if validated.sizes().len() != expected {
685                    return Err(HapiError::Internal(format!(
686                        "attribute {:?} needs {expected} array sizes, got {}",
687                        self.handle.name,
688                        sizes.len()
689                    )));
690                }
691                let ptrs: Vec<_> = values.iter().map(|v| v.as_ref().as_ptr()).collect();
692                crate::ffi::set_string_jagged_attribute_data(
693                    &self.handle.node,
694                    self.handle.part_id,
695                    &self.handle.name,
696                    &info.0,
697                    &ptrs,
698                    sizes,
699                    $dictionary,
700                )
701            }
702        }
703    };
704}
705jagged_string_impl!(StringAttribute, StorageType::StringArray, false);
706jagged_string_impl!(DictionaryAttribute, StorageType::DictionaryArray, true);
707
708#[derive(Debug, Clone)]
709/// Exhaustive runtime representation of every supported HAPI attribute storage.
710///
711/// Returned by [`crate::geometry::Geometry::get_attribute`] when the caller
712/// does not know the storage in advance. Match a variant to obtain its typed
713/// handle, or use the common identity and deletion methods directly.
714pub enum AnyAttribute {
715    /// A fixed `i32` attribute.
716    Int(Attribute<i32, Fixed>),
717    /// A fixed `i64` attribute.
718    Int64(Attribute<i64, Fixed>),
719    /// A fixed `f32` attribute.
720    Float(Attribute<f32, Fixed>),
721    /// A fixed `f64` attribute.
722    Float64(Attribute<f64, Fixed>),
723    /// A fixed string attribute.
724    String(StringAttribute<Fixed>),
725    /// A fixed `u8` attribute.
726    Uint8(Attribute<u8, Fixed>),
727    /// A fixed `i8` attribute.
728    Int8(Attribute<i8, Fixed>),
729    /// A fixed `i16` attribute.
730    Int16(Attribute<i16, Fixed>),
731    /// A jagged `i32` array attribute.
732    IntArray(Attribute<i32, Jagged>),
733    /// A jagged `i64` array attribute.
734    Int64Array(Attribute<i64, Jagged>),
735    /// A jagged `f32` array attribute.
736    FloatArray(Attribute<f32, Jagged>),
737    /// A jagged `f64` array attribute.
738    Float64Array(Attribute<f64, Jagged>),
739    /// A jagged string array attribute.
740    StringArray(StringAttribute<Jagged>),
741    /// A jagged `u8` array attribute.
742    Uint8Array(Attribute<u8, Jagged>),
743    /// A jagged `i8` array attribute.
744    Int8Array(Attribute<i8, Jagged>),
745    /// A jagged `i16` array attribute.
746    Int16Array(Attribute<i16, Jagged>),
747    /// A fixed JSON dictionary attribute.
748    Dictionary(DictionaryAttribute<Fixed>),
749    /// A jagged JSON dictionary array attribute.
750    DictionaryArray(DictionaryAttribute<Jagged>),
751}
752
753impl AnyAttribute {
754    fn handle(&self) -> &Handle {
755        match self {
756            Self::Int(v) => &v.handle,
757            Self::Int64(v) => &v.handle,
758            Self::Float(v) => &v.handle,
759            Self::Float64(v) => &v.handle,
760            Self::String(v) => &v.handle,
761            Self::Uint8(v) => &v.handle,
762            Self::Int8(v) => &v.handle,
763            Self::Int16(v) => &v.handle,
764            Self::IntArray(v) => &v.handle,
765            Self::Int64Array(v) => &v.handle,
766            Self::FloatArray(v) => &v.handle,
767            Self::Float64Array(v) => &v.handle,
768            Self::StringArray(v) => &v.handle,
769            Self::Uint8Array(v) => &v.handle,
770            Self::Int8Array(v) => &v.handle,
771            Self::Int16Array(v) => &v.handle,
772            Self::Dictionary(v) => &v.handle,
773            Self::DictionaryArray(v) => &v.handle,
774        }
775    }
776    /// Returns the attribute name, replacing invalid UTF-8 if necessary.
777    #[must_use]
778    pub fn name(&self) -> Cow<'_, str> {
779        self.handle().name.to_string_lossy()
780    }
781    /// Returns the currently cached metadata.
782    #[must_use]
783    pub fn info(&self) -> &AttributeInfo {
784        &self.handle().info
785    }
786    /// Returns the HAPI storage represented by the enum variant.
787    #[must_use]
788    pub fn storage(&self) -> StorageType {
789        self.handle().info.storage()
790    }
791    /// Returns the HAPI part to which this handle is bound.
792    #[must_use]
793    pub fn part_id(&self) -> i32 {
794        self.handle().part_id
795    }
796    /// Returns the element owner of this attribute.
797    #[must_use]
798    pub fn owner(&self) -> AttributeOwner {
799        self.handle().owner
800    }
801    /// Refreshes the variant's cached metadata from HAPI.
802    ///
803    /// The enum variant and cache remain unchanged if the attribute is missing
804    /// or its storage no longer matches the typed handle.
805    pub fn refresh(&mut self) -> Result<()> {
806        match self {
807            Self::Int(v) => v.refresh(),
808            Self::Int64(v) => v.refresh(),
809            Self::Float(v) => v.refresh(),
810            Self::Float64(v) => v.refresh(),
811            Self::String(v) => v.refresh(),
812            Self::Uint8(v) => v.refresh(),
813            Self::Int8(v) => v.refresh(),
814            Self::Int16(v) => v.refresh(),
815            Self::IntArray(v) => v.refresh(),
816            Self::Int64Array(v) => v.refresh(),
817            Self::FloatArray(v) => v.refresh(),
818            Self::Float64Array(v) => v.refresh(),
819            Self::StringArray(v) => v.refresh(),
820            Self::Uint8Array(v) => v.refresh(),
821            Self::Int8Array(v) => v.refresh(),
822            Self::Int16Array(v) => v.refresh(),
823            Self::Dictionary(v) => v.refresh(),
824            Self::DictionaryArray(v) => v.refresh(),
825        }
826    }
827    /// Deletes this attribute from its bound node and part.
828    pub fn delete(self) -> Result<()> {
829        let h = self.handle();
830        crate::ffi::delete_attribute(&h.node, h.part_id, &h.name, &h.info.0)
831    }
832}