Skip to main content

p2panda_core/operation/
body.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3use crate::hash::Hash;
4use crate::operation::PayloadSize;
5
6/// Body of a p2panda operation containing arbitrary bytes.
7#[derive(Clone, Debug, PartialEq, Eq)]
8pub struct Body(Vec<u8>);
9
10impl Body {
11    /// Construct a body from a byte slice.
12    pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Self {
13        Self(bytes.as_ref().to_vec())
14    }
15
16    /// Access the underlying body bytes.
17    pub fn to_bytes(&self) -> Vec<u8> {
18        self.0.clone()
19    }
20
21    pub fn as_bytes(&self) -> &[u8] {
22        &self.0
23    }
24
25    /// BLAKE3 hash of the body bytes.
26    pub fn hash(&self) -> Hash {
27        Hash::digest(&self.0)
28    }
29
30    /// Size of body bytes.
31    pub fn size(&self) -> PayloadSize {
32        self.0.len() as PayloadSize
33    }
34
35    #[cfg(any(test, feature = "test_utils"))]
36    pub fn to_hex(&self) -> String {
37        hex::encode(&self.0)
38    }
39}
40
41impl AsRef<[u8]> for Body {
42    fn as_ref(&self) -> &[u8] {
43        &self.0
44    }
45}
46
47impl From<&[u8]> for Body {
48    fn from(value: &[u8]) -> Self {
49        Body::from_bytes(value)
50    }
51}
52
53impl From<Vec<u8>> for Body {
54    fn from(value: Vec<u8>) -> Self {
55        Body(value)
56    }
57}