vector_var_imp_vec/
vector_var_imp_vec.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use orx_imp_vec::*;
use std::fmt::{Display, Formatter, Result};
use std::ops::Index;

struct Vector<'a> {
    symbol: String,
    created_vars: ImpVec<Var<'a>>,
}

impl<'a> Vector<'a> {
    fn new(symbol: &str) -> Self {
        Self {
            symbol: symbol.into(),
            created_vars: Default::default(),
        }
    }
}

impl<'a> Index<usize> for &'a Vector<'a> {
    type Output = Var<'a>;

    fn index(&self, index: usize) -> &Self::Output {
        let var = Var {
            index,
            vector: self,
        };
        self.created_vars.imp_push_get_ref(var)
    }
}

#[derive(Clone, Copy)]
struct Var<'a> {
    vector: &'a Vector<'a>,
    index: usize,
}

impl<'a> Display for Var<'a> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        write!(f, "{}[{}]", &self.vector.symbol, self.index)
    }
}

fn main() {
    let x = &Vector::new("x");

    // good

    let x0: Var = x[0];
    assert_eq!(x0.to_string(), "x[0]");

    // also good

    let vars1: Vec<Var> = (0..1000).map(|i| x[i]).collect();

    for (i, x) in vars1.iter().enumerate() {
        assert_eq!(x.to_string(), format!("x[{}]", i));
    }

    // still good

    let vars2: Vec<&Var> = (0..1000).map(|i| &x[i]).collect();

    for (i, x) in vars2.iter().enumerate() {
        assert_eq!(x.to_string(), format!("x[{}]", i));
    }
}