Skip to main content

utopia_balancer/
candidate.rs

1//! [`Candidate`]: one option a balancer can choose, described by its state.
2
3use php_std::types::KeyRef;
4use php_std::{Array, Value};
5
6/// One option to balance between, described by a bag of named values (its
7/// state): a hostname, whether it is online, its load.
8///
9/// Keys follow PHP array rules: a decimal key such as `"0"` is stored as the
10/// integer `0`, so [`Candidate::states`] is the array PHP would hold.
11///
12/// PHP: `Utopia\Balancer\Option`.
13///
14/// ```
15/// use php_std::Value;
16/// use utopia_balancer::Candidate;
17///
18/// let mut worker = Candidate::default();
19/// worker.set("hostname", Value::from("worker-1")).set("cpu", Value::from(35));
20///
21/// assert_eq!(worker.get("cpu"), Some(&Value::Int(35)));
22/// assert_eq!(worker.get_or("memory", &Value::Int(0)), &Value::Int(0));
23/// assert_eq!(worker.states().len(), 2);
24/// ```
25///
26/// ```php
27/// use Utopia\Balancer\Option;
28///
29/// $worker = new Option([]);
30/// $worker->setState('hostname', 'worker-1')->setState('cpu', 35);
31///
32/// var_dump($worker->getState('cpu'));         // int(35)
33/// var_dump($worker->getState('memory', 0));   // int(0)
34/// var_dump(\count($worker->getStates()));     // int(2)
35/// ```
36#[derive(Debug, Clone, Default, PartialEq)]
37pub struct Candidate {
38    state: Array,
39}
40
41impl Candidate {
42    /// A candidate with this initial state.
43    ///
44    /// PHP: `new Option($state)`.
45    pub fn new(state: Array) -> Self {
46        Candidate { state }
47    }
48
49    /// The value of `key`, or `None` when it is missing or `null`.
50    ///
51    /// PHP: `getState($key)`, which returns `null` for both.
52    pub fn get(&self, key: &str) -> Option<&Value> {
53        self.state.get_ref(KeyRef::normalize(key.as_bytes())).filter(|v| !matches!(v, Value::Null))
54    }
55
56    /// The value of `key`, or `default` when it is missing or `null`.
57    ///
58    /// PHP: `getState($key, $default)` (`$state[$key] ?? $default`).
59    pub fn get_or<'a>(&'a self, key: &str, default: &'a Value) -> &'a Value {
60        self.get(key).unwrap_or(default)
61    }
62
63    /// Sets `key` to `value`, replacing any previous value in place.
64    ///
65    /// PHP: `setState($key, $value)`.
66    pub fn set(&mut self, key: &str, value: Value) -> &mut Self {
67        self.state.set(KeyRef::normalize(key.as_bytes()).to_owned(), value);
68        self
69    }
70
71    /// Removes `key`, if present.
72    ///
73    /// PHP: `deleteState($key)`.
74    pub fn remove(&mut self, key: &str) -> &mut Self {
75        self.state.remove(&KeyRef::normalize(key.as_bytes()).to_owned());
76        self
77    }
78
79    /// Every value, in the order the keys were first set.
80    ///
81    /// PHP: `getStates()`.
82    pub fn states(&self) -> &Array {
83        &self.state
84    }
85}
86
87impl<const N: usize> From<[(&str, Value); N]> for Candidate {
88    /// A candidate from `(key, value)` pairs, in order.
89    fn from(pairs: [(&str, Value); N]) -> Self {
90        let mut candidate = Candidate::default();
91        for (key, value) in pairs {
92            candidate.set(key, value);
93        }
94        candidate
95    }
96}
97
98impl From<Array> for Candidate {
99    /// A candidate with this state.
100    fn from(state: Array) -> Self {
101        Candidate::new(state)
102    }
103}