Skip to main content

miden_core/utils/
mod.rs

1use alloc::vec::Vec;
2use core::ops::{Bound, Range};
3
4// RE-EXPORTS
5// ================================================================================================
6#[cfg(feature = "std")]
7pub use miden_crypto::utils::ReadAdapter;
8pub use miden_crypto::utils::{
9    assume_init_vec, flatten_slice_elements, flatten_vector_elements, group_slice_elements,
10    uninit_vector,
11};
12pub use miden_formatting::hex::{DisplayHex, ToHex, to_hex};
13pub use miden_utils_indexing::{
14    DenseIdMap, Idx, IndexVec, IndexedVecError, LookupByIdx, newtype_id,
15};
16pub use p3_matrix::{Matrix, dense::RowMajorMatrix};
17
18use crate::{Felt, Word, crypto::hash::Blake3_256, field::PrimeCharacteristicRing};
19
20// TO ELEMENTS
21// ================================================================================================
22
23pub trait ToElements {
24    fn to_elements(&self) -> Vec<Felt>;
25}
26
27impl<const N: usize> ToElements for [u64; N] {
28    fn to_elements(&self) -> Vec<Felt> {
29        self.iter().map(|&v| Felt::from_u64(v)).collect()
30    }
31}
32
33impl ToElements for Vec<u64> {
34    fn to_elements(&self) -> Vec<Felt> {
35        self.iter().map(|&v| Felt::from_u64(v)).collect()
36    }
37}
38
39// TO WORD
40// ================================================================================================
41
42/// Hashes the provided string using the BLAKE3 hash function and converts the resulting digest into
43/// a [`Word`].
44pub fn hash_string_to_word<'a>(value: impl Into<&'a str>) -> Word {
45    let digest_bytes: [u8; 32] = Blake3_256::hash(value.into().as_bytes()).into();
46    [
47        Felt::new_unchecked(u64::from_le_bytes(digest_bytes[0..8].try_into().unwrap())),
48        Felt::new_unchecked(u64::from_le_bytes(digest_bytes[8..16].try_into().unwrap())),
49        Felt::new_unchecked(u64::from_le_bytes(digest_bytes[16..24].try_into().unwrap())),
50        Felt::new_unchecked(u64::from_le_bytes(digest_bytes[24..32].try_into().unwrap())),
51    ]
52    .into()
53}
54
55// INTO BYTES
56// ================================================================================================
57
58pub trait IntoBytes<const N: usize> {
59    fn into_bytes(self) -> [u8; N];
60}
61
62impl IntoBytes<32> for [Felt; 4] {
63    fn into_bytes(self) -> [u8; 32] {
64        let mut result = [0; 32];
65
66        result[..8].copy_from_slice(&self[0].as_canonical_u64().to_le_bytes());
67        result[8..16].copy_from_slice(&self[1].as_canonical_u64().to_le_bytes());
68        result[16..24].copy_from_slice(&self[2].as_canonical_u64().to_le_bytes());
69        result[24..].copy_from_slice(&self[3].as_canonical_u64().to_le_bytes());
70
71        result
72    }
73}
74
75// RANGE
76// ================================================================================================
77
78/// Returns a [Range] initialized with the specified `start` and with `end` set to `start` + `len`.
79pub const fn range(start: usize, len: usize) -> Range<usize> {
80    Range { start, end: start + len }
81}
82
83/// Converts and parses a [Bound] into an included u64 value.
84///
85/// Returns `None` if the bound cannot be represented as an inclusive `u64` (e.g. an excluded start
86/// bound at `u64::MAX` or an excluded end bound at `0`).
87pub fn bound_into_included_u64<I>(bound: Bound<&I>, is_start: bool) -> Option<u64>
88where
89    I: Clone + Into<u64>,
90{
91    match bound {
92        Bound::Excluded(i) => {
93            let val = i.clone().into();
94            if is_start {
95                val.checked_add(1)
96            } else {
97                val.checked_sub(1)
98            }
99        },
100        Bound::Included(i) => Some(i.clone().into()),
101        Bound::Unbounded => {
102            if is_start {
103                Some(0)
104            } else {
105                Some(u64::MAX)
106            }
107        },
108    }
109}
110
111// BYTE CONVERSIONS
112// ================================================================================================
113
114/// Number of bytes packed into each u32 field element.
115///
116/// Used for converting between byte arrays and u32-packed field elements in memory.
117const BYTES_PER_U32: usize = size_of::<u32>();
118
119/// Converts bytes to field elements using u32 packing in little-endian format.
120///
121/// Each field element contains a u32 value representing up to 4 bytes. If the byte length
122/// is not a multiple of 4, the final field element is zero-padded.
123///
124/// This is commonly used by precompile handlers (Keccak256, ECDSA) to convert byte data
125/// into field element commitments.
126///
127/// # Arguments
128/// - `bytes`: The byte slice to convert
129///
130/// # Returns
131/// A vector of field elements, each containing 4 bytes packed in little-endian order.
132///
133/// # Examples
134/// ```
135/// # use miden_core::{Felt, utils::bytes_to_packed_u32_elements, field::PrimeCharacteristicRing};
136/// let bytes = vec![0x01, 0x02, 0x03, 0x04, 0x05];
137/// let felts = bytes_to_packed_u32_elements(&bytes);
138/// assert_eq!(felts, vec![Felt::from_u32(0x04030201_u32), Felt::from_u32(0x00000005_u32)]);
139/// ```
140pub fn bytes_to_packed_u32_elements(bytes: &[u8]) -> Vec<Felt> {
141    bytes
142        .chunks(BYTES_PER_U32)
143        .map(|chunk| {
144            // Pack up to 4 bytes into a u32 in little-endian format
145            let mut packed = [0u8; BYTES_PER_U32];
146            packed[..chunk.len()].copy_from_slice(chunk);
147            Felt::from_u32(u32::from_le_bytes(packed))
148        })
149        .collect()
150}
151
152/// Converts u32-packed field elements back to bytes in little-endian format.
153///
154/// This is the inverse of [`bytes_to_packed_u32_elements`]. Each field element is expected
155/// to contain a u32 value, which is unpacked into 4 bytes.
156///
157/// # Arguments
158/// - `elements`: The field elements to convert
159///
160/// # Returns
161/// A vector of bytes representing the unpacked data.
162///
163/// # Examples
164/// ```
165/// # use miden_core::{Felt, utils::{bytes_to_packed_u32_elements, packed_u32_elements_to_bytes}};
166/// let original = vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];
167/// let elements = bytes_to_packed_u32_elements(&original);
168/// let bytes = packed_u32_elements_to_bytes(&elements);
169/// assert_eq!(bytes, original);
170/// ```
171pub fn packed_u32_elements_to_bytes(elements: &[Felt]) -> Vec<u8> {
172    elements
173        .iter()
174        .flat_map(|felt| {
175            let value = felt.as_canonical_u64() as u32;
176            value.to_le_bytes()
177        })
178        .collect()
179}
180
181// TESTS
182// ================================================================================================
183
184#[cfg(test)]
185mod tests {
186    use alloc::vec::Vec;
187
188    use proptest::prelude::*;
189
190    use super::*;
191
192    proptest! {
193        #[test]
194        fn proptest_packed_u32_elements_roundtrip(values in prop::collection::vec(any::<u32>(), 0..100)) {
195            // Convert u32 values to Felts
196            let felts: Vec<Felt> = values.iter().map(|&v| Felt::from_u32(v)).collect();
197
198            // Roundtrip: Felts -> bytes -> Felts
199            let bytes = packed_u32_elements_to_bytes(&felts);
200            let roundtrip_felts = bytes_to_packed_u32_elements(&bytes);
201
202            // Should be equal
203            prop_assert_eq!(felts, roundtrip_felts);
204        }
205    }
206
207    #[test]
208    fn test_bound_into_included_u64() {
209        let val = 10u64;
210        assert_eq!(bound_into_included_u64(Bound::Included(&val), true), Some(10));
211        assert_eq!(bound_into_included_u64(Bound::Included(&val), false), Some(10));
212        assert_eq!(bound_into_included_u64(Bound::Excluded(&val), true), Some(11));
213        assert_eq!(bound_into_included_u64(Bound::Excluded(&val), false), Some(9));
214        assert_eq!(bound_into_included_u64(Bound::<&u64>::Unbounded, true), Some(0));
215        assert_eq!(bound_into_included_u64(Bound::<&u64>::Unbounded, false), Some(u64::MAX));
216
217        // Edge cases: excluded endpoints that yield empty bounds
218        let max_val = u64::MAX;
219        assert_eq!(bound_into_included_u64(Bound::Excluded(&max_val), true), None);
220        assert_eq!(bound_into_included_u64(Bound::Excluded(&max_val), false), Some(u64::MAX - 1));
221
222        let zero_val = 0u64;
223        assert_eq!(bound_into_included_u64(Bound::Excluded(&zero_val), true), Some(1));
224        assert_eq!(bound_into_included_u64(Bound::Excluded(&zero_val), false), None);
225    }
226
227    #[test]
228    #[should_panic]
229    fn debug_assert_is_checked() {
230        // enforce the release checks to always have `RUSTFLAGS="-C debug-assertions".
231        //
232        // some upstream tests are performed with `debug_assert`, and we want to assert its
233        // correctness downstream.
234        //
235        // for reference, check
236        // https://github.com/0xMiden/miden-vm/issues/433
237        debug_assert!(false);
238    }
239}