commonware_utils/sequence/
mod.rs

1use commonware_codec::{Codec, EncodeFixed};
2use core::{
3    cmp::{Ord, PartialOrd},
4    error::Error as CoreError,
5    fmt::{Debug, Display},
6    hash::Hash,
7    ops::Deref,
8};
9use thiserror::Error;
10
11pub mod fixed_bytes;
12pub use fixed_bytes::FixedBytes;
13pub mod u64;
14pub use u64::U64;
15pub mod prefixed_u64;
16pub mod u32;
17pub use u32::U32;
18pub mod unit;
19pub use unit::Unit;
20
21/// Errors returned by the `Array` trait's functions.
22#[derive(Error, Debug, PartialEq)]
23pub enum Error<E: CoreError + Send + Sync + 'static> {
24    #[error("invalid bytes")]
25    InsufficientBytes,
26    #[error("other: {0}")]
27    Other(E),
28}
29
30/// Types that can be read from a variable-size byte sequence.
31///
32/// `Span` is typically used to parse things like requests from an untrusted
33/// network connection (with variable-length fields). Once parsed, these types
34/// are assumed to be well-formed (which prevents duplicate validation).
35pub trait Span:
36    Clone
37    + Send
38    + Sync
39    + 'static
40    + Eq
41    + PartialEq
42    + Ord
43    + PartialOrd
44    + Debug
45    + Hash
46    + Display
47    + Codec<Cfg = ()>
48{
49}
50
51impl Span for u8 {}
52impl Span for u16 {}
53impl Span for u32 {}
54impl Span for u64 {}
55impl Span for u128 {}
56impl Span for i8 {}
57impl Span for i16 {}
58impl Span for i32 {}
59impl Span for i64 {}
60impl Span for i128 {}
61
62/// Types that can be fallibly read from a fixed-size byte sequence.
63///
64/// `Array` is typically used to parse things like `PublicKeys` and `Signatures`
65/// from an untrusted network connection. Once parsed, these types are assumed
66/// to be well-formed (which prevents duplicate validation).
67pub trait Array: Span + EncodeFixed + AsRef<[u8]> + Deref<Target = [u8]> {}