spin_serde/
version.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
67
68
use serde::{Deserialize, Serialize};

/// FixedVersion represents a version integer field with a const value.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(into = "usize", try_from = "usize")]
pub struct FixedVersion<const V: usize>;

impl<const V: usize> From<FixedVersion<V>> for usize {
    fn from(_: FixedVersion<V>) -> usize {
        V
    }
}

impl<const V: usize> TryFrom<usize> for FixedVersion<V> {
    type Error = String;

    fn try_from(value: usize) -> Result<Self, Self::Error> {
        if value != V {
            return Err(format!("invalid version {} != {}", value, V));
        }
        Ok(Self)
    }
}

/// FixedVersion represents a version integer field with a const value,
/// but accepts lower versions during deserialisation.
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(into = "usize", try_from = "usize")]
pub struct FixedVersionBackwardCompatible<const V: usize>;

impl<const V: usize> From<FixedVersionBackwardCompatible<V>> for usize {
    fn from(_: FixedVersionBackwardCompatible<V>) -> usize {
        V
    }
}

impl<const V: usize> TryFrom<usize> for FixedVersionBackwardCompatible<V> {
    type Error = String;

    fn try_from(value: usize) -> Result<Self, Self::Error> {
        if value > V {
            return Err(format!("invalid version {} > {}", value, V));
        }
        Ok(Self)
    }
}

/// FixedStringVersion represents a version string field with a const value.
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(into = "String", try_from = "String")]
pub struct FixedStringVersion<const V: usize>;

impl<const V: usize> From<FixedStringVersion<V>> for String {
    fn from(_: FixedStringVersion<V>) -> String {
        V.to_string()
    }
}

impl<const V: usize> TryFrom<String> for FixedStringVersion<V> {
    type Error = String;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        if value.parse() != Ok(V) {
            return Err(format!("invalid version {value:?} != \"{V}\""));
        }
        Ok(Self)
    }
}