Skip to main content

align_ext/
lib.rs

1// SPDX-License-Identifier: MPL-2.0
2#![allow(unused_macros)]
3#![cfg_attr(not(test), no_std)]
4#![allow(rustdoc::invalid_rust_codeblocks)]
5#![allow(rustdoc::invalid_html_tags)]
6#![allow(rustdoc::broken_intra_doc_links)]
7
8use vstd::{
9    arithmetic::{div_mod::*, mul::*, power::pow, power2::*},
10    bits::*,
11    pervasive::trigger,
12    prelude::*,
13};
14use vstd_extra::prelude::*;
15
16/// An extension trait for Rust integer types, including `u8`, `u16`, `u32`,
17/// `u64`, and `usize`, to provide methods to make integers aligned to a
18/// power of two.
19pub trait AlignExt {
20    /// Returns to the smallest number that is greater than or equal to
21    /// `self` and is a multiple of the given power of two.
22    ///
23    /// The method panics if `power_of_two` is not a
24    /// power of two or is smaller than 2 or the calculation overflows
25    /// because `self` is too large.
26    ///
27    /// # Examples
28    ///
29    /// ```
30    /// use crate::align_ext::AlignExt;
31    /// assert_eq!(12usize.align_up(2), 12);
32    /// assert_eq!(12usize.align_up(4), 12);
33    /// assert_eq!(12usize.align_up(8), 16);
34    /// assert_eq!(12usize.align_up(16), 16);
35    /// ```
36    fn align_up(self, power_of_two: Self) -> Self;
37
38    /// Returns to the greatest number that is smaller than or equal to
39    /// `self` and is a multiple of the given power of two.
40    ///
41    /// The method panics if `power_of_two` is not a
42    /// power of two or is smaller than 2 or the calculation overflows
43    /// because `self` is too large. In release mode,
44    ///
45    /// # Examples
46    ///
47    /// ```
48    /// use crate::align_ext::AlignExt;
49    /// assert_eq!(12usize.align_down(2), 12);
50    /// assert_eq!(12usize.align_down(4), 12);
51    /// assert_eq!(12usize.align_down(8), 8);
52    /// assert_eq!(12usize.align_down(16), 0);
53    /// ```
54    fn align_down(self, power_of_two: Self) -> Self;
55}
56
57macro_rules! call_lemma_low_bits_mask_is_mod {
58    (u8, $x:expr, $n:expr) => {
59        lemma_u8_low_bits_mask_is_mod($x, $n)
60    };
61    (u16, $x:expr, $n:expr) => {
62        lemma_u16_low_bits_mask_is_mod($x, $n)
63    };
64    (u32, $x:expr, $n:expr) => {
65        lemma_u32_low_bits_mask_is_mod($x, $n)
66    };
67    (u64, $x:expr, $n:expr) => {
68        lemma_u64_low_bits_mask_is_mod($x, $n)
69    };
70    (usize, $x:expr, $n:expr) => {
71        lemma_usize_low_bits_mask_is_mod($x, $n)
72    };
73}
74
75macro_rules! impl_align_ext {
76    ($( $uint_type:ty ),+,) => {
77        $(
78            /// # Verified Properties
79            /// ## Safety
80            /// The implementation is written in safe Rust and there is no undefined behavior.
81            /// ## Functional correctness
82            /// The implementation meets the specification given in the trait `AlignExt`.
83            #[verus_verify]
84            impl AlignExt for $uint_type {
85                /// ## Preconditions
86                /// - `self + (align - 1)` does not overflow.
87                /// - `align` is a power of two `>= 2`.
88                /// ## Postconditions
89                /// - The return value is the smallest number that is greater
90                ///   than or equal to `self` and is a multiple of `align`.
91                #[inline]
92                #[verus_spec(ret =>
93                    requires
94                        self + (align - 1) <= $uint_type::MAX,
95                        align >= 2,
96                        is_pow2(align as int),
97                    ensures
98                        ret >= self,
99                        ret % align == 0,
100                        ret == nat_align_up(self as nat, align as nat),
101                        forall |n: nat| !(n>=self && #[trigger] (n % align as nat) == 0) || (ret <= n),
102                )]
103                fn align_up(self, align: Self) -> Self {
104                    assert!(align.is_power_of_two() && align >= 2);
105                    proof!{
106                        is_pow2_equiv(align as int);
107                        let x_int = self + align - 1;
108                        let x = x_int as Self;
109                        if self as int % align as int == 0 {
110                            assert((align - 1) % align as int == align - 1) by {
111                                lemma_small_mod((align - 1) as nat, align as nat);
112                            }
113                            assert(x_int % align as int == align - 1) by {
114                                lemma_mod_adds(self as int, align - 1, align as int);
115                            }
116                        } else {
117                            let q = self as int / align as int;
118                            let r = self as int % align as int;
119                            lemma_fundamental_div_mod(self as int, align as int);
120                            assert(self == q * align + r) by {
121                                lemma_mul_is_commutative(align as int, q);
122                            }
123
124                            assert((q + 1) * align == q * align + align) by {
125                                lemma_mul_is_distributive_add_other_way(align as int, q, 1);
126                            }
127                            assert(((q + 1) * align) % align as int == 0) by {
128                                lemma_mod_multiples_basic(q + 1, align as int);
129                            }
130                            assert((r - 1) % align as int == r - 1) by {
131                                lemma_small_mod((r - 1) as nat, align as nat);
132                            }
133                            assert(x_int == (q + 1) * align + (r - 1));
134                            assert(x_int % align as int == (r - 1)) by {
135                                lemma_mod_adds((q + 1) * align, r - 1, align as int);
136                            }
137                        }
138
139                        lemma_low_bits_mask_values();
140                        let mask = (align - 1) as Self;
141                        let e = choose |e: nat| pow(2, e) == align;
142                        lemma_pow2(e);
143                        assert(e < $uint_type::BITS) by {
144                            if e >= $uint_type::BITS {
145                                lemma_pow2_strictly_increases($uint_type::BITS as nat, e);
146                                lemma2_to64();
147                            }
148                        }
149                        call_lemma_low_bits_mask_is_mod!($uint_type, x, e);
150                        assert(x == (x & mask) + (x & !mask)) by (bit_vector);
151                        lemma_nat_align_up_sound(self as nat, align as nat);
152                    }
153                    self.checked_add(align - 1).unwrap() & !(align - 1)
154                }
155
156                /// ## Preconditions
157                /// - `align` is a power of two `>= 2`.
158                /// ## Postconditions
159                /// - The return value is the greatest number that is smaller than or equal to `self` and is a multiple of `align`.
160                #[inline]
161                #[verus_spec(ret =>
162                    requires
163                        align >= 2,
164                        is_pow2(align as int),
165                    ensures
166                        ret <= self,
167                        ret % align == 0,
168                        ret == nat_align_down(self as nat, align as nat),
169                        forall |n: nat|  !(n<=self && #[trigger] (n % align as nat) == 0) || (ret >= n),
170                )]
171                fn align_down(self, align: Self) -> Self {
172                    assert!(align.is_power_of_two() && align >= 2);
173                    proof!{
174                        is_pow2_equiv(align as int);
175                        lemma_low_bits_mask_values();
176                        let mask = (align - 1) as Self;
177                        let e = choose |e: nat| pow(2, e) == align;
178                        lemma_pow2(e);
179                        assert(e < $uint_type::BITS) by {
180                            if e >= $uint_type::BITS {
181                                lemma_pow2_strictly_increases($uint_type::BITS as nat, e);
182                                lemma2_to64();
183                            }
184                        }
185                        call_lemma_low_bits_mask_is_mod!($uint_type, self, e);
186                        assert(self == (self & mask) + (self & !mask)) by (bit_vector);
187                        assert((self & !mask) as nat == nat_align_down(self as nat, align as nat));
188                        lemma_nat_align_down_sound(self as nat, align as nat);
189                    }
190                    self & !(align - 1)
191                }
192        }
193            )*
194    }
195}
196
197impl_align_ext! {
198    u8,
199    u16,
200    u32,
201    u64,
202    usize,
203}
204
205#[cfg(test)]
206mod test {
207    use super::*;
208
209    #[test]
210    fn align_up() {
211        let input_ns = [0usize, 1, 2, 9, 15, 21, 32, 47, 50];
212        let input_as = [2usize, 2, 2, 2, 4, 4, 8, 8, 8];
213        let output_ns = [0usize, 2, 2, 10, 16, 24, 32, 48, 56];
214
215        for i in 0..input_ns.len() {
216            let n = input_ns[i];
217            let a = input_as[i];
218            let n2 = output_ns[i];
219            assert!(n.align_up(a) == n2);
220        }
221    }
222
223    #[test]
224    fn align_down() {
225        let input_ns = [0usize, 1, 2, 9, 15, 21, 32, 47, 50];
226        let input_as = [2usize, 2, 2, 2, 4, 4, 8, 8, 8];
227        let output_ns = [0usize, 0, 2, 8, 12, 20, 32, 40, 48];
228
229        for i in 0..input_ns.len() {
230            let n = input_ns[i];
231            let a = input_as[i];
232            let n2 = output_ns[i];
233            assert!(n.align_down(a) == n2);
234        }
235    }
236}