Skip to main content

jam_primitives/
utils.rs

1//! # Utilities for JAM Protocol
2//!
3//! This module provides utility functions and re-exports commonly used traits.
4
5/// Codec module re-exporting parity-scale-codec traits
6pub mod codec {
7    pub use parity_scale_codec::{Compact, Decode, Encode, Input};
8
9    /// Codec trait combining Encode and Decode (re-exported from parity-scale-codec)
10    pub trait Codec: Encode + Decode {}
11
12    /// Blanket impl for re-use where required
13    impl<T: Encode + Decode> Codec for T {}
14
15    /// Encode a compact u32 (using parity-scale-codec)
16    pub fn encode_compact_u32(value: u32) -> Vec<u8> {
17        Compact(value).encode()
18    }
19
20    /// Decode a compact u32 (using parity-scale-codec)
21    pub fn decode_compact_u32<I: Input>(input: &mut I) -> anyhow::Result<u32> {
22        let compact = Compact::<u32>::decode(input)?;
23        Ok(compact.0)
24    }
25}
26
27// Re-export commonly used codec traits at the utils level
28pub use codec::{Codec, Decode, Encode};
29
30// Basic tests for codec use
31#[cfg(test)]
32mod codec_tests {
33    use super::codec::*;
34
35    #[test]
36    fn test_basic_codec() {
37        let value = 42u32;
38        let encoded = value.encode();
39        let decoded = u32::decode(&mut &encoded[..]).unwrap();
40        assert_eq!(decoded, value);
41    }
42
43    #[test]
44    fn test_compact_codec() {
45        let value = 42u32;
46        let encoded = encode_compact_u32(value);
47        let decoded = decode_compact_u32(&mut &encoded[..]).unwrap();
48        assert_eq!(decoded, value);
49    }
50}