ant_protocol/storage/address/
chunk.rs

1// Copyright 2024 MaidSafe.net limited.
2//
3// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
4// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
5// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
6// KIND, either express or implied. Please review the Licences for the specific language governing
7// permissions and limitations relating to use of the SAFE Network Software.
8
9use serde::{Deserialize, Serialize};
10use std::hash::Hash;
11use xor_name::XorName;
12
13use super::AddressParseError;
14
15/// Address of a [`crate::storage::chunks::Chunk`].
16///
17/// It is derived from the content of the chunk.
18#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
19pub struct ChunkAddress(XorName);
20
21impl ChunkAddress {
22    /// Creates a new ChunkAddress.
23    pub fn new(xor_name: XorName) -> Self {
24        Self(xor_name)
25    }
26
27    /// Returns the XorName
28    pub fn xorname(&self) -> &XorName {
29        &self.0
30    }
31
32    /// Returns the hex string representation of the address.
33    pub fn to_hex(&self) -> String {
34        hex::encode(self.0)
35    }
36
37    /// Creates a new ChunkAddress from a hex string.
38    pub fn from_hex(hex: &str) -> Result<Self, AddressParseError> {
39        let bytes = hex::decode(hex)?;
40        let xor = XorName(
41            bytes
42                .try_into()
43                .map_err(|_| AddressParseError::InvalidLength)?,
44        );
45        Ok(Self(xor))
46    }
47}
48
49impl std::fmt::Display for ChunkAddress {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        write!(f, "{}", &self.to_hex())
52    }
53}
54
55impl std::fmt::Debug for ChunkAddress {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        write!(f, "{}", &self.to_hex())
58    }
59}