midenc_hir_type/
array_type.rs

1use super::{Alignable, Type};
2
3/// A fixed-size, homogenous vector type.
4#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
6pub struct ArrayType {
7    pub ty: Type,
8    pub len: usize,
9}
10
11impl ArrayType {
12    /// Create a new [ArrayType] of length `len` and element type of `ty`
13    pub fn new(ty: Type, len: usize) -> Self {
14        Self { ty, len }
15    }
16
17    /// Get the size of this array type
18    #[allow(clippy::len_without_is_empty)]
19    pub fn len(&self) -> usize {
20        self.len
21    }
22
23    /// Get the element type of this array type
24    pub fn element_type(&self) -> &Type {
25        &self.ty
26    }
27
28    /// Returns true if this array type represents a zero-sized type
29    pub fn is_zst(&self) -> bool {
30        self.len == 0 || self.ty.is_zst()
31    }
32
33    /// Returns the minimum alignment required by this type
34    pub fn min_alignment(&self) -> usize {
35        self.ty.min_alignment()
36    }
37
38    /// Returns the size in bits of this array type
39    pub fn size_in_bits(&self) -> usize {
40        match self.len {
41            // Zero-sized arrays have no size in memory
42            0 => 0,
43            // An array of one element is the same as just the element
44            1 => self.ty.size_in_bits(),
45            // All other arrays require alignment padding between elements
46            n => {
47                let min_align = self.ty.min_alignment() * 8;
48                let element_size = self.ty.size_in_bits();
49                let padded_element_size = element_size.align_up(min_align);
50                element_size + (padded_element_size * (n - 1))
51            }
52        }
53    }
54}
55
56impl core::fmt::Display for ArrayType {
57    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
58        use miden_formatting::prettier::PrettyPrint;
59        self.pretty_print(f)
60    }
61}
62
63impl miden_formatting::prettier::PrettyPrint for ArrayType {
64    fn render(&self) -> miden_formatting::prettier::Document {
65        use miden_formatting::prettier::*;
66
67        const_text("[") + self.ty.render() + const_text("; ") + self.len.render() + const_text("]")
68    }
69}