ab_core_primitives/
shard.rs

1//! Shard-related primitives
2
3use ab_io_type::trivial_type::TrivialType;
4use core::num::{NonZeroU32, NonZeroU128};
5use derive_more::Display;
6
7/// Shard index
8#[derive(Debug, Display, Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq, TrivialType)]
9#[repr(transparent)]
10pub struct ShardIndex(u32);
11
12impl ShardIndex {
13    /// Max possible shard index
14    pub const MAX_SHARD_INDEX: u32 = Self::MAX_SHARDS.get() - 1;
15    /// Max possible number of shards
16    pub const MAX_SHARDS: NonZeroU32 = NonZeroU32::new(2u32.pow(20)).expect("Not zero; qed");
17    /// Max possible number of addresses per shard
18    pub const MAX_ADDRESSES_PER_SHARD: NonZeroU128 =
19        NonZeroU128::new((u128::MAX / 2 + 1) / (Self::MAX_SHARDS.get() as u128 / 2))
20            .expect("Not zero; qed");
21
22    // TODO: Remove once traits work in const environment and `From` could be used
23    /// Create shard index from `u32`.
24    ///
25    /// Returns `None` if `shard_index > ShardIndex::MAX_SHARD_INDEX`
26    ///
27    /// This is typically only necessary for low-level code.
28    #[inline(always)]
29    pub const fn new(shard_index: u32) -> Option<Self> {
30        if shard_index > Self::MAX_SHARD_INDEX {
31            return None;
32        }
33
34        Some(Self(shard_index))
35    }
36
37    // TODO: Remove once traits work in const environment and `From` could be used
38    /// Convert shard index to `u32`.
39    ///
40    /// This is typically only necessary for low-level code.
41    #[inline(always)]
42    pub const fn as_u32(self) -> u32 {
43        self.0
44    }
45}