bee_block/output/
foundry_id.rs

1// Copyright 2022 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use packable::{packer::SlicePacker, Packable};
5
6use crate::{
7    address::{Address, AliasAddress},
8    output::{AliasId, TokenId},
9};
10
11impl_id!(pub FoundryId, 38, "Defines the unique identifier of a foundry.");
12
13#[cfg(feature = "serde")]
14string_serde_impl!(FoundryId);
15
16impl From<TokenId> for FoundryId {
17    fn from(token_id: TokenId) -> Self {
18        FoundryId::new(*token_id)
19    }
20}
21
22impl FoundryId {
23    /// Builds a new [`FoundryId`] from its components.
24    pub fn build(alias_address: &AliasAddress, serial_number: u32, token_scheme_kind: u8) -> Self {
25        let mut bytes = [0u8; FoundryId::LENGTH];
26        let mut packer = SlicePacker::new(&mut bytes);
27
28        // PANIC: packing to an array of the correct length can't fail.
29        Address::Alias(*alias_address).pack(&mut packer).unwrap();
30        serial_number.pack(&mut packer).unwrap();
31        token_scheme_kind.pack(&mut packer).unwrap();
32
33        FoundryId::new(bytes)
34    }
35
36    /// Returns the [`AliasAddress`] of the [`FoundryId`].
37    pub fn alias_address(&self) -> AliasAddress {
38        // PANIC: the lengths are known.
39        AliasAddress::from(AliasId::new(self.0[1..AliasId::LENGTH + 1].try_into().unwrap()))
40    }
41
42    /// Returns the serial number of the [`FoundryId`].
43    pub fn serial_number(&self) -> u32 {
44        // PANIC: the lengths are known.
45        u32::from_le_bytes(
46            self.0[AliasId::LENGTH + 1..AliasId::LENGTH + 1 + core::mem::size_of::<u32>()]
47                .try_into()
48                .unwrap(),
49        )
50    }
51
52    /// Returns the [`TokenScheme`](crate::output::TokenScheme) kind of the [`FoundryId`].
53    pub fn token_scheme_kind(&self) -> u8 {
54        // PANIC: the lengths are known.
55        *self.0.last().unwrap()
56    }
57}