celestia_types/share/
info_byte.rs

1use crate::consts::appconsts;
2use crate::{Error, Result};
3
4/// The part of [`Share`] containing the `version` and `sequence_start` information.
5///
6/// [`InfoByte`] is a single byte with the following structure:
7///
8///  - the first 7 bits are reserved for version information in big endian form
9///  - last bit is a `sequence_start` flag. If it's set then this [`Share`] is
10///    a first of a sequence, otherwise it's a continuation share.
11///
12///  [`Share`]: crate::Share
13#[repr(transparent)]
14#[derive(Debug, PartialEq)]
15pub struct InfoByte(u8);
16
17impl InfoByte {
18    /// Create a new [`InfoByte`] with given version and `sequence_start`.
19    pub fn new(version: u8, is_sequence_start: bool) -> Result<Self> {
20        if version > appconsts::MAX_SHARE_VERSION {
21            Err(Error::MaxShareVersionExceeded(version))
22        } else {
23            let prefix = version << 1;
24            let sequence_start = if is_sequence_start { 1 } else { 0 };
25            Ok(Self(prefix + sequence_start))
26        }
27    }
28
29    /// Get the `version`.
30    pub fn version(&self) -> u8 {
31        self.0 >> 1
32    }
33
34    /// Get the `sequence_start` indicator.
35    pub fn is_sequence_start(&self) -> bool {
36        self.0 % 2 == 1
37    }
38
39    /// Convert the [`InfoByte`] to a byte.
40    pub fn as_u8(&self) -> u8 {
41        self.0
42    }
43
44    pub(crate) fn from_raw(byte: u8) -> Result<Self> {
45        let version = byte >> 1;
46        if version > appconsts::MAX_SHARE_VERSION {
47            Err(Error::MaxShareVersionExceeded(version))
48        } else {
49            Ok(InfoByte(byte))
50        }
51    }
52
53    pub(crate) fn from_raw_unchecked(byte: u8) -> Self {
54        InfoByte(byte)
55    }
56}