quant_iron/components/parametric/
parameter.rs

1use std::sync::{Arc, Mutex};
2
3/// A struct representing a set of mutable parameters for a parametrised gate.
4/// Cloning this struct is cheap and allows multiple gates to share the same underlying parameters.
5///
6/// # Fields
7/// - `values`: An `Arc<Mutex<[f64; N]>>` that holds the parameter values.
8///
9/// # Generic Parameters
10/// - `N`: The number of values in the parameter array.
11#[derive(Clone)]
12pub struct Parameter<const N: usize> {
13    /// The values of the parameters
14    values: Arc<Mutex<[f64; N]>>,
15}
16
17impl<const N: usize> Parameter<N> {
18    /// Creates a new `Parameter` instance with the given initial values.
19    ///
20    /// # Arguments
21    ///
22    /// * `initial_values` - An array of initial parameter values.
23    ///
24    /// # Returns
25    ///
26    /// A new `Parameter` instance.
27    pub fn new(initial_values: [f64; N]) -> Self {
28        Self {
29            values: Arc::new(Mutex::new(initial_values)),
30        }
31    }
32
33    /// Creates a new `Parameter` instance as an independent copy of the given parameter.
34    ///
35    /// # Returns
36    ///
37    /// A new `Parameter` instance.
38    pub fn deep_clone(&self) -> Self {
39        Self {
40            values: Arc::new(Mutex::new(self.get())),
41        }
42    }
43
44    /// Gets the current values of the parameters.
45    /// This will lock the underlying mutex.
46    ///
47    /// # Returns
48    ///
49    /// The current parameter values.
50    ///
51    /// If the mutex is poisoned, the function will return the current values.
52    pub fn get(&self) -> [f64; N] {
53        match self.values.lock() {
54            Ok(guard) => *guard,
55            Err(poisoned) => *poisoned.into_inner(),
56        }
57    }
58
59    /// Sets the values of the parameters.
60    /// This will lock the underlying mutex.
61    pub fn set(&self, new_values: [f64; N]) {
62        let mut guard = match self.values.lock() {
63            Ok(guard) => guard,
64            Err(poisoned) => poisoned.into_inner(),
65        };
66        *guard = new_values;
67    }
68}
69
70impl<const N: usize> std::fmt::Debug for Parameter<N> {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        let values = self.get();
73        write!(f, "Parameter({:?})", values)
74    }
75}