calimero_primitives/
blobs.rs1use core::fmt::{self, Display, Formatter};
2use core::ops::Deref;
3use core::str::FromStr;
4
5use serde::{Deserialize, Serialize};
6use thiserror::Error as ThisError;
7
8use crate::hash::{Hash, HashError};
9
10#[derive(Copy, Clone, Debug, Deserialize, Eq, Ord, Hash, PartialEq, PartialOrd, Serialize)]
11#[cfg_attr(
12 feature = "borsh",
13 derive(borsh::BorshDeserialize, borsh::BorshSerialize)
14)]
15pub struct BlobId(Hash);
16
17impl BlobId {
18 #[must_use]
19 pub fn as_str(&self) -> &str {
20 self.0.as_str()
21 }
22}
23
24impl From<[u8; 32]> for BlobId {
25 fn from(id: [u8; 32]) -> Self {
26 Self(id.into())
27 }
28}
29
30impl AsRef<[u8; 32]> for BlobId {
31 fn as_ref(&self) -> &[u8; 32] {
32 &self.0
33 }
34}
35
36impl Deref for BlobId {
37 type Target = [u8; 32];
38
39 fn deref(&self) -> &Self::Target {
40 &self.0
41 }
42}
43
44impl Display for BlobId {
45 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
46 f.pad(self.as_str())
47 }
48}
49
50impl From<BlobId> for String {
51 fn from(id: BlobId) -> Self {
52 id.as_str().to_owned()
53 }
54}
55
56impl From<&BlobId> for String {
57 fn from(id: &BlobId) -> Self {
58 id.as_str().to_owned()
59 }
60}
61
62#[derive(Clone, Copy, Debug, ThisError)]
63#[error(transparent)]
64pub struct InvalidBlobId(HashError);
65
66impl FromStr for BlobId {
67 type Err = InvalidBlobId;
68
69 fn from_str(s: &str) -> Result<Self, Self::Err> {
70 Ok(Self(s.parse().map_err(InvalidBlobId)?))
71 }
72}
73
74#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
76pub struct BlobInfo {
77 pub blob_id: BlobId,
79 pub size: u64,
81}
82
83#[derive(Debug, Serialize, Deserialize)]
85pub struct BlobMetadata {
86 pub blob_id: BlobId,
87 pub size: u64,
88 pub hash: [u8; 32],
89 pub mime_type: String,
90}