Skip to main content

oximo_core/
indexed.rs

1use std::ops::Index;
2
3use oximo_expr::Expr;
4use rustc_hash::FxHashMap;
5
6use crate::set::IndexKey;
7
8/// Sparse indexed variable: maps an `IndexKey` to a single-variable `Expr`.
9///
10/// Constructed by [`crate::Model::indexed_var`]. Implements [`Index`] so
11/// `flow[idx]` returns the variable's expression handle directly.
12#[derive(Clone, Debug)]
13pub struct IndexedVar<'a> {
14    pub(crate) entries: FxHashMap<IndexKey, Expr<'a>>,
15}
16
17impl<'a> IndexedVar<'a> {
18    pub fn len(&self) -> usize {
19        self.entries.len()
20    }
21
22    pub fn is_empty(&self) -> bool {
23        self.entries.is_empty()
24    }
25
26    pub fn iter(&self) -> impl Iterator<Item = (&IndexKey, &Expr<'a>)> {
27        self.entries.iter()
28    }
29
30    pub fn get<K: Into<IndexKey>>(&self, key: K) -> Option<Expr<'a>> {
31        self.entries.get(&key.into()).copied()
32    }
33}
34
35impl<'a, K: Into<IndexKey> + Clone> Index<K> for IndexedVar<'a> {
36    type Output = Expr<'a>;
37    fn index(&self, key: K) -> &Self::Output {
38        self.entries.get(&key.into()).expect("IndexedVar: key not present")
39    }
40}
41
42impl<'a> Index<&IndexKey> for IndexedVar<'a> {
43    type Output = Expr<'a>;
44    fn index(&self, key: &IndexKey) -> &Self::Output {
45        self.entries.get(key).expect("IndexedVar: key not present")
46    }
47}