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(Debug, 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    /// Gets the current values of the parameters.
34    /// This will lock the underlying mutex.
35    ///
36    /// # Returns
37    ///
38    /// The current parameter values.
39    ///
40    /// If the mutex is poisoned, the function will return the current values.
41    pub fn get(&self) -> [f64; N] {
42        match self.values.lock() {
43            Ok(guard) => *guard,
44            Err(poisoned) => *poisoned.into_inner(),
45        }
46    }
47
48    /// Sets the values of the parameters.
49    /// This will lock the underlying mutex.
50    pub fn set(&self, new_values: [f64; N]) {
51        let mut guard = match self.values.lock() {
52            Ok(guard) => guard,
53            Err(poisoned) => poisoned.into_inner(),
54        };
55        *guard = new_values;
56    }
57}