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
67
68
69
70
71
72
73
74
75
76
77
78
use iter::TryIter;
use std::fmt::{self, Debug};
use std::cell::UnsafeCell;
use std::sync::mpsc;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
use std::cmp::PartialEq;

pub struct Parameter<'a, T>{
    iter: UnsafeCell<TryIter<'a, T>>,
    value: UnsafeCell<T>,
}

impl<'a, T: Debug> Debug for Parameter<'a,T>{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result{
        fmt.debug_struct("Parameter<T>")
            .field("value", unsafe{ &*self.value.get() })
            .finish()
    }
}

impl<'a, T> Parameter<'a,T> {
    pub(crate) fn from_parent(parent: TryIter<'a,T>, initial: T) -> Parameter<'a,T>{
        let iter = UnsafeCell::new(parent);
        let value = UnsafeCell::new(initial);
        Parameter{
            iter,
            value
        }
    }

    pub fn from_mpsc(receiver: mpsc::Receiver<T>, initial: T) -> Parameter<'static, T>{
        Parameter{
            iter: UnsafeCell::new(TryIter::from_mpsc(receiver)),
            value: UnsafeCell::new(initial),
        }
    }

    pub fn get(&self) -> &T {
        let iter = unsafe{ &mut *self.iter.get() };
        let value = unsafe{ &mut *self.value.get() };
        if let Some(t) = iter.last(){
            *value = t
        }
        value
    }

    pub fn last_value(&mut self) -> Option<&T> {
        let iter = unsafe{ &mut *self.iter.get() };
        let value = unsafe{ &mut *self.value.get() };
        if let Some(t) = iter.last(){
            *value = t;
            Some(value)
        }else{
            None
        }
    }

    pub fn into_value(self) -> T {
        let iter = unsafe{ &mut *self.iter.get() };
        if let Some(t) = iter.last(){
            t
        }else{
            self.value.into_inner()
        }
    }
}

impl<'a,T: Clone + Serialize + 'a> Serialize for Parameter<'a,T>{
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>{
        (*self.get()).serialize(serializer)
    }
}

impl<'a, T: PartialEq + Clone> PartialEq for Parameter<'a, T>{
    fn eq(&self, other: &Parameter<'a,T>) -> bool{
        unsafe{ *self.value.get() == *other.value.get() }
    }
}