unified_bridge/
rollup_id.rs1use std::{fmt::Display, num::NonZeroU32};
2
3use serde::{Deserialize, Serialize};
4
5use crate::{NetworkId, RollupIndex};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Hash)]
11#[cfg_attr(feature = "testutils", derive(arbitrary::Arbitrary))]
12#[repr(transparent)]
13pub struct RollupId(NonZeroU32);
14
15impl Display for RollupId {
16 #[inline]
17 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18 self.0.fmt(f)
19 }
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
23#[error("Invalid rollup id")]
24pub struct InvalidRollupIdError;
25
26impl RollupId {
27 pub const BITS: usize = u32::BITS as usize;
28
29 #[inline]
30 pub const fn new(value: u32) -> Result<RollupId, InvalidRollupIdError> {
31 match NonZeroU32::new(value) {
32 Some(v) => Ok(RollupId(v)),
33 None => Err(InvalidRollupIdError),
34 }
35 }
36
37 #[inline]
38 pub const fn to_u32(self) -> u32 {
39 self.0.get()
40 }
41
42 #[inline]
43 pub const fn to_be_bytes(self) -> [u8; 4] {
44 self.0.get().to_be_bytes()
45 }
46
47 #[inline]
48 pub const fn to_le_bytes(self) -> [u8; 4] {
49 self.0.get().to_le_bytes()
50 }
51}
52
53impl TryFrom<u32> for RollupId {
54 type Error = InvalidRollupIdError;
55
56 #[inline]
57 fn try_from(value: u32) -> Result<Self, Self::Error> {
58 Self::new(value)
59 }
60}
61
62impl From<RollupId> for u32 {
63 #[inline]
64 fn from(value: RollupId) -> Self {
65 value.0.get()
66 }
67}
68
69impl TryFrom<NetworkId> for RollupId {
70 type Error = InvalidRollupIdError;
71
72 #[inline]
73 fn try_from(value: NetworkId) -> Result<Self, Self::Error> {
74 RollupId::new(value.to_u32())
75 }
76}
77
78impl From<RollupId> for NetworkId {
79 #[inline]
80 fn from(value: RollupId) -> Self {
81 NetworkId::new(value.0.get())
82 }
83}
84
85impl From<RollupIndex> for RollupId {
86 #[inline]
87 fn from(value: RollupIndex) -> Self {
88 RollupId(NonZeroU32::new(value.to_u32() + 1).unwrap())
89 }
90}