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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
//! [Instruction] nonce parameter.
//!
//! [Instruction]: super::Instruction

use crate::{Error, Unit};
use enum_as_inner::EnumAsInner;
use generic_array::{
    typenum::consts::{U12, U16},
    GenericArray,
};
use libipld::{multibase::Base::Base32HexLower, Ipld};
use serde::{Deserialize, Serialize};
use std::fmt;
use uuid::Uuid;

type Nonce96 = GenericArray<u8, U12>;
type Nonce128 = GenericArray<u8, U16>;

/// Enumeration over allowed `nonce` types.
#[derive(Clone, Debug, PartialEq, EnumAsInner, Serialize, Deserialize)]
pub enum Nonce {
    /// 96-bit, 12-byte nonce, e.g. [xid].
    Nonce96(Nonce96),
    /// 128-bit, 16-byte nonce.
    Nonce128(Nonce128),
    /// No Nonce attributed.
    Empty,
}

impl Nonce {
    /// Default generator, outputting a [xid] nonce, which is a 96-bit, 12-byte
    /// nonce.
    pub fn generate() -> Self {
        Nonce::Nonce96(*GenericArray::from_slice(xid::new().as_bytes()))
    }

    /// Generate a default, 128-bit, 16-byte nonce via [Uuid::new_v4()].
    pub fn generate_128() -> Self {
        Nonce::Nonce128(*GenericArray::from_slice(Uuid::new_v4().as_bytes()))
    }
}

impl fmt::Display for Nonce {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Nonce::Nonce96(nonce) => {
                write!(f, "{}", Base32HexLower.encode(nonce.as_slice()))
            }
            Nonce::Nonce128(nonce) => {
                write!(f, "{}", Base32HexLower.encode(nonce.as_slice()))
            }
            Nonce::Empty => write!(f, ""),
        }
    }
}

impl From<Nonce> for Ipld {
    fn from(nonce: Nonce) -> Self {
        match nonce {
            Nonce::Nonce96(nonce) => Ipld::Bytes(nonce.to_vec()),
            Nonce::Nonce128(nonce) => Ipld::Bytes(nonce.to_vec()),
            Nonce::Empty => Ipld::String("".to_string()),
        }
    }
}

impl TryFrom<Ipld> for Nonce {
    type Error = Error<Unit>;

    fn try_from(ipld: Ipld) -> Result<Self, Self::Error> {
        if let Ipld::Bytes(v) = ipld {
            match v.len() {
                12 => Ok(Nonce::Nonce96(*GenericArray::from_slice(&v))),
                16 => Ok(Nonce::Nonce128(*GenericArray::from_slice(&v))),
                other_ipld => Err(Error::unexpected_ipld(other_ipld.to_owned().into())),
            }
        } else {
            Ok(Nonce::Empty)
        }
    }
}

impl TryFrom<&Ipld> for Nonce {
    type Error = Error<Unit>;

    fn try_from(ipld: &Ipld) -> Result<Self, Self::Error> {
        TryFrom::try_from(ipld.to_owned())
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn ipld_roundtrip_12() {
        let gen = Nonce::generate();
        let ipld = Ipld::from(gen.clone());

        let inner = if let Nonce::Nonce96(nonce) = gen {
            Ipld::Bytes(nonce.to_vec())
        } else {
            panic!("No conversion!")
        };

        assert_eq!(ipld, inner);
        assert_eq!(gen, ipld.try_into().unwrap());
    }

    #[test]
    fn ipld_roundtrip_16() {
        let gen = Nonce::generate_128();
        let ipld = Ipld::from(gen.clone());

        let inner = if let Nonce::Nonce128(nonce) = gen {
            Ipld::Bytes(nonce.to_vec())
        } else {
            panic!("No conversion!")
        };

        assert_eq!(ipld, inner);
        assert_eq!(gen, ipld.try_into().unwrap());
    }

    #[test]
    fn ser_de() {
        let gen = Nonce::generate_128();
        let ser = serde_json::to_string(&gen).unwrap();
        let de = serde_json::from_str(&ser).unwrap();

        assert_eq!(gen, de);
    }
}