use super::{hash_encoded, ValSignature};
use bounded_collections::Get;
use codec::{ConstEncodedLen, Decode, Encode, MaxEncodedLen};
use jam_types::{core_count, opaque, CoreIndex, FixedVec, HeaderHash};
pub fn bitfield_byte_count() -> usize {
(core_count() + 7) as usize / 8
}
#[derive(Copy, Clone, Eq, PartialEq, Default, Debug)]
pub struct BitfieldByteCount;
impl Get<u32> for BitfieldByteCount {
fn get() -> u32 {
bitfield_byte_count() as u32
}
}
#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, MaxEncodedLen)]
pub struct AvailabilityBitfield(FixedVec<u8, BitfieldByteCount>);
impl AvailabilityBitfield {
pub fn new() -> Self {
Self(FixedVec::default())
}
pub fn set(&mut self, i: CoreIndex) {
self.0[i as usize / 8] |= 1 << (i % 8);
}
pub fn clear(&mut self, i: CoreIndex) {
self.0[i as usize / 8] &= !(1 << (i % 8));
}
pub fn get(&self, i: CoreIndex) -> bool {
self.0[i as usize / 8] & (1 << (i % 8)) != 0
}
pub fn is_all_unset(&self) -> bool {
self.0.iter().all(|&b| b == 0)
}
pub fn count_ones(&self) -> u32 {
self.0.iter().map(|&b| b.count_ones()).sum()
}
}
impl ConstEncodedLen for AvailabilityBitfield {}
impl<T: std::borrow::Borrow<[CoreIndex]>> From<T> for AvailabilityBitfield {
fn from(value: T) -> Self {
let mut r = Self::new();
for i in value.borrow() {
r.set(*i);
}
r
}
}
#[derive(Clone, Encode, Decode, Debug, PartialEq, Eq, MaxEncodedLen)]
pub struct AvailabilityStatement {
pub anchor: HeaderHash,
pub bitfield: AvailabilityBitfield,
}
impl ConstEncodedLen for AvailabilityStatement {}
opaque! { pub struct AvailabilityStatementHash(pub [u8; 32]); }
impl AvailabilityStatement {
pub fn hash(&self) -> AvailabilityStatementHash {
hash_encoded(self).into()
}
}
#[derive(Clone, Encode, Decode, Debug, MaxEncodedLen)]
pub struct AvailabilityAssurance {
pub statement: AvailabilityStatement,
pub signature: ValSignature,
}
impl ConstEncodedLen for AvailabilityAssurance {}
opaque! { pub struct ErasureRoot(pub [u8; 32]); }