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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
 * AquaVM Workflow Engine
 *
 * Copyright (C) 2024 Fluence DAO
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

use serde::Deserialize;
use serde::Serialize;

use std::cmp::Ordering;
use std::fmt::Debug;
use std::fmt::Display;

type GenerationIdxType = u32;

#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
#[repr(transparent)]
#[derive(::rkyv::Archive, ::rkyv::Serialize, ::rkyv::Deserialize)]
#[archive(check_bytes)]
pub struct GenerationIdx(GenerationIdxType);

impl GenerationIdx {
    pub fn checked_add(self, other: Self) -> Option<Self> {
        self.0.checked_add(other.0).map(Self)
    }

    pub fn checked_sub(self, other: Self) -> Option<Self> {
        self.0.checked_sub(other.0).map(Self)
    }

    pub fn next(self) -> Self {
        // TODO: check for overflow
        Self::from(self.0 as usize + 1)
    }

    pub fn prev(self) -> Self {
        // TODO: check for overflow
        Self::from(self.0 as usize - 1)
    }

    pub fn stub() -> Self {
        const GENERATION_STUB: GenerationIdxType = 0xCAFEBABE;
        Self(GENERATION_STUB)
    }
}

impl PartialOrd<usize> for GenerationIdx {
    fn partial_cmp(&self, other: &usize) -> Option<Ordering> {
        let self_as_usize: usize = (*self).into();
        self_as_usize.partial_cmp(other)
    }
}

impl PartialEq<usize> for GenerationIdx {
    fn eq(&self, other: &usize) -> bool {
        let self_as_usize: usize = (*self).into();
        self_as_usize == *other
    }
}

//TODO: replace these two traits with try-* versions
impl From<usize> for GenerationIdx {
    fn from(value: usize) -> Self {
        GenerationIdx(value as u32)
    }
}

impl From<GenerationIdx> for usize {
    fn from(value: GenerationIdx) -> Self {
        value.0 as usize
    }
}

impl Debug for GenerationIdx {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&self.0, f)
    }
}

impl Display for GenerationIdx {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.0, f)
    }
}