Skip to main content

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