ccp_shared/types/
global_nonce.rs

1/*
2 * Copyright 2024 Fluence DAO
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use std::str::FromStr;
18
19use hex::FromHex;
20use hex::ToHex;
21use serde_with::DeserializeFromStr;
22use serde_with::SerializeDisplay;
23
24pub type GlobalNonceInner = [u8; 32];
25
26#[derive(Copy, Clone, Hash, PartialEq, Eq, SerializeDisplay, DeserializeFromStr)]
27#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
28#[repr(transparent)]
29pub struct GlobalNonce(GlobalNonceInner);
30
31impl GlobalNonce {
32    pub const fn new(inner: GlobalNonceInner) -> Self {
33        Self(inner)
34    }
35}
36
37impl AsRef<GlobalNonceInner> for GlobalNonce {
38    fn as_ref(&self) -> &GlobalNonceInner {
39        &self.0
40    }
41}
42
43impl FromHex for GlobalNonce {
44    type Error = <[u8; 32] as FromHex>::Error;
45
46    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
47        GlobalNonceInner::from_hex(hex).map(Self)
48    }
49}
50
51impl ToHex for GlobalNonce {
52    fn encode_hex<T: std::iter::FromIterator<char>>(&self) -> T {
53        ToHex::encode_hex(&self.0)
54    }
55
56    fn encode_hex_upper<T: std::iter::FromIterator<char>>(&self) -> T {
57        ToHex::encode_hex_upper(&self.0)
58    }
59}
60
61impl FromStr for GlobalNonce {
62    type Err = hex::FromHexError;
63
64    fn from_str(s: &str) -> Result<Self, Self::Err> {
65        FromHex::from_hex(s)
66    }
67}
68
69use std::fmt;
70
71impl fmt::Display for GlobalNonce {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.write_str(&self.encode_hex::<String>())
74    }
75}
76
77impl fmt::Debug for GlobalNonce {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        f.debug_tuple("GlobalNonce")
80            .field(&self.to_string())
81            .finish()
82    }
83}