1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use crate::{
    bytesrepr::{Error, FromBytes, ToBytes},
    CLType, CLTyped,
};

/// Max bytes of an [`Address`] internal representation.
pub const ADDRESS_LENGTH: usize = 64;

/// Blockchain-agnostic address representation.
#[derive(Clone, Copy, PartialEq, Hash, Eq)]
pub struct Address {
    data: [u8; ADDRESS_LENGTH],
}

impl Address {
    /// Creates a new Address from bytes.
    ///
    /// If takes less than [`ADDRESS_LENGTH`], the remaining bytes are zeroed.
    /// If takes more and [`ADDRESS_LENGTH`] excess bytes are discarded.
    pub fn new(bytes: &[u8]) -> Address {
        let mut bytes_vec = bytes.to_vec();
        bytes_vec.resize(ADDRESS_LENGTH, 0);

        let mut bytes = [0u8; ADDRESS_LENGTH];
        bytes.copy_from_slice(bytes_vec.as_slice());
        Address { data: bytes }
    }

    /// Returns a slice containing the entire array of bytes.
    pub fn bytes(&self) -> &[u8] {
        self.data.as_slice()
    }
}

impl CLTyped for Address {
    fn cl_type() -> casper_types::CLType {
        CLType::Any
    }
}

impl ToBytes for Address {
    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
        Ok(self.data.to_vec())
    }

    fn serialized_length(&self) -> usize {
        self.data.len()
    }
}

impl FromBytes for Address {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
        let (data, remainder) = bytes.split_at(ADDRESS_LENGTH);
        Ok((Address::new(data), remainder))
    }
}

impl core::fmt::Debug for Address {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = hex::encode(&self.data);
        f.debug_struct("Address").field("data", &name).finish()
    }
}