qfall_math/utils/factorization/
ownership.rs

1// Copyright © 2023 Marcel Luca Schmidt
2//
3// This file is part of qFALL-math.
4//
5// qFALL-math is free software: you can redistribute it and/or modify it under
6// the terms of the Mozilla Public License Version 2.0 as published by the
7// Mozilla Foundation. See <https://mozilla.org/en-US/MPL/2.0/>.
8
9//! Implementations for factorizations of [`Z`](crate::integer::Z) values.
10
11use super::Factorization;
12use flint_sys::fmpz_factor::fmpz_factor_clear;
13
14impl Drop for Factorization {
15    /// Drops the given [`Factorization`] value and frees the allocated memory.
16    ///
17    /// # Examples
18    /// ```
19    /// use qfall_math::utils::Factorization;
20    /// {
21    ///     let fac = Factorization::from((8, 3));
22    /// } // as fac's scope ends here, it get's dropped
23    /// ```
24    ///
25    /// ```
26    /// use qfall_math::utils::Factorization;
27    ///
28    /// let fac = Factorization::from((8, 3));
29    /// drop(fac); // explicitly drops fac's value
30    /// ```
31    fn drop(&mut self) {
32        unsafe { fmpz_factor_clear(&mut self.factors) }
33    }
34}
35
36/// Test that the [`Drop`] trait is correctly implemented.
37#[cfg(test)]
38mod test_drop {
39    use crate::utils::Factorization;
40
41    /// Check whether freed memory is reused afterwards.
42    #[test]
43    fn free_memory() {
44        let a = Factorization::from(u64::MAX);
45        let a_p = a.factors.p;
46        let _ = Factorization::from(u64::MAX);
47        drop(a);
48        let c = Factorization::from(u64::MAX);
49        drop(c);
50
51        // Instantiate new [`Factorization`] value to check if memory slot is reused for new value.
52        let d = Factorization::from(u64::MAX);
53        let d_p = d.factors.p;
54
55        assert_eq!(a_p, d_p);
56    }
57}