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
use crate::prelude::*;
use crate::{
    casper_types::{
        bytesrepr::{FromBytes, ToBytes},
        CLTyped
    },
    module::{ModuleComponent, ModulePrimitive},
    ContractEnv
};
use num_traits::{Num, One, Zero};

use crate::Var;

/// A module that stores a single value in the storage that can be read or incremented.
pub struct Sequence<T>
where
    T: Num + One + ToBytes + FromBytes + CLTyped
{
    env: Rc<ContractEnv>,
    index: u8,
    value: Var<T>
}

impl<T> Sequence<T>
where
    T: Num + One + Zero + Default + Copy + ToBytes + FromBytes + CLTyped
{
    /// Returns the current value of the sequence.
    pub fn get_current_value(&self) -> T {
        self.value.get().unwrap_or_default()
    }

    /// Increments the value of the sequence and returns the new value.
    pub fn next_value(&mut self) -> T {
        match self.value.get() {
            None => {
                self.value.set(T::zero());
                T::zero()
            }
            Some(value) => {
                let next = value + T::one();
                self.value.set(next);
                next
            }
        }
    }
}

impl<T: Num + One + Zero + Default + Copy + ToBytes + FromBytes + CLTyped> Sequence<T> {
    /// Returns the ContractEnv.
    pub fn env(&self) -> ContractEnv {
        self.env.child(self.index)
    }
}

/// Implements the `ModuleComponent` trait for the `Sequence` struct.
impl<T: Num + One + Zero + Default + Copy + ToBytes + FromBytes + CLTyped> ModuleComponent
    for Sequence<T>
{
    /// Creates a new instance of `Sequence` with the given environment and index.
    fn instance(env: Rc<ContractEnv>, index: u8) -> Self {
        Self {
            env: env.clone(),
            index,
            value: Var::instance(env.child(index).into(), 0)
        }
    }
}

impl<T: Num + One + Zero + Default + Copy + ToBytes + FromBytes + CLTyped> ModulePrimitive
    for Sequence<T>
{
}