strict_types/typesys/
id.rs1use std::fmt::{self, Display, Formatter};
25use std::str::FromStr;
26
27use amplify::{ByteArray, Bytes32};
28use baid64::{Baid64ParseError, DisplayBaid64, FromBaid64Str};
29use encoding::StrictEncode;
30use sha2::{Digest, Sha256};
31use strict_encoding::STRICT_TYPES_LIB;
32
33use crate::ast::SemCommit;
34use crate::{CommitConsume, TypeSystem};
35
36pub const TYPESYS_ID_TAG: [u8; 32] = *b"urn:ubideco:strict-types:sys:v01";
37
38#[derive(Wrapper, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug, From)]
39#[wrapper(Deref, BorrowSlice, Hex, Index, RangeOps)]
40#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
41#[strict_type(lib = STRICT_TYPES_LIB)]
42#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(transparent))]
43pub struct TypeSysId(
44 #[from]
45 #[from([u8; 32])]
46 Bytes32,
47);
48
49impl DisplayBaid64 for TypeSysId {
50 const HRI: &'static str = "sts";
51 const CHUNKING: bool = true;
52 const PREFIX: bool = true;
53 const EMBED_CHECKSUM: bool = false;
54 const MNEMONIC: bool = true;
55 fn to_baid64_payload(&self) -> [u8; 32] { self.to_byte_array() }
56}
57impl FromBaid64Str for TypeSysId {}
58impl FromStr for TypeSysId {
59 type Err = Baid64ParseError;
60 fn from_str(s: &str) -> Result<Self, Self::Err> { Self::from_baid64_str(s) }
61}
62impl Display for TypeSysId {
63 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.fmt_baid64(f) }
64}
65
66impl SemCommit for TypeSystem {
67 fn sem_commit(&self, hasher: &mut impl CommitConsume) {
68 hasher.commit_consume(self.len_u24().to_le_bytes());
69 for sem_id in self.keys() {
70 sem_id.sem_commit(hasher);
71 }
72 }
73}
74
75impl TypeSystem {
76 pub fn id(&self) -> TypeSysId {
77 let tag = Sha256::new_with_prefix(TYPESYS_ID_TAG).finalize();
78 let mut hasher = Sha256::new();
79 hasher.commit_consume(tag);
80 hasher.commit_consume(tag);
81 self.sem_commit(&mut hasher);
82 TypeSysId::from_byte_array(hasher.finalize())
83 }
84}