Skip to main content

melior/ir/attribute/
dense_i64_array.rs

1use super::{Attribute, AttributeLike};
2use crate::{Context, Error};
3use mlir_sys::{
4    mlirDenseArrayGetNumElements, mlirDenseI64ArrayGet, mlirDenseI64ArrayGetElement, MlirAttribute,
5};
6
7/// A dense i64 array attribute.
8#[derive(Clone, Copy)]
9pub struct DenseI64ArrayAttribute<'c> {
10    attribute: Attribute<'c>,
11}
12
13impl<'c> DenseI64ArrayAttribute<'c> {
14    /// Creates a dense i64 array attribute.
15    pub fn new(context: &'c Context, values: &[i64]) -> Self {
16        unsafe {
17            Self::from_raw(mlirDenseI64ArrayGet(
18                context.to_raw(),
19                values.len() as isize,
20                values.as_ptr(),
21            ))
22        }
23    }
24
25    /// Returns a length.
26    pub fn len(&self) -> usize {
27        (unsafe { mlirDenseArrayGetNumElements(self.attribute.to_raw()) }) as usize
28    }
29
30    /// Checks if an array is empty.
31    pub fn is_empty(&self) -> bool {
32        self.len() == 0
33    }
34
35    /// Returns an element.
36    pub fn element(&self, index: usize) -> Result<i64, Error> {
37        if index < self.len() {
38            Ok(unsafe { mlirDenseI64ArrayGetElement(self.attribute.to_raw(), index as isize) })
39        } else {
40            Err(Error::PositionOutOfBounds {
41                name: "array element",
42                value: self.to_string(),
43                index,
44            })
45        }
46    }
47}
48
49attribute_traits!(
50    DenseI64ArrayAttribute,
51    is_dense_i64_array,
52    "dense i64 array"
53);
54
55#[cfg(test)]
56mod tests {
57    use crate::test::create_test_context;
58
59    use super::*;
60
61    #[test]
62    fn element() {
63        let context = create_test_context();
64        let attribute = DenseI64ArrayAttribute::new(&context, &[1, 2, 3]);
65
66        assert_eq!(attribute.element(0).unwrap(), 1);
67        assert_eq!(attribute.element(1).unwrap(), 2);
68        assert_eq!(attribute.element(2).unwrap(), 3);
69        assert!(matches!(
70            attribute.element(3),
71            Err(Error::PositionOutOfBounds { .. })
72        ));
73    }
74
75    #[test]
76    fn len() {
77        let context = create_test_context();
78        let attribute = DenseI64ArrayAttribute::new(&context, &[1, 2, 3]);
79
80        assert_eq!(attribute.len(), 3);
81    }
82}