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/// It is derived from the content of the chunk
17#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, Debug)]
18pub struct ChunkAddress(XorName);
19
20impl ChunkAddress {
21 /// Creates a new ChunkAddress.
22 pub fn new(xor_name: XorName) -> Self {
23 Self(xor_name)
24 }
25
26 /// Returns the XorName
27 pub fn xorname(&self) -> &XorName {
28 &self.0
29 }
30
31 /// Returns the hex string representation of the address.
32 pub fn to_hex(&self) -> String {
33 hex::encode(self.0)
34 }
35
36 /// Creates a new ChunkAddress from a hex string.
37 pub fn try_from_hex(hex: &str) -> Result<Self, AddressParseError> {
38 let bytes = hex::decode(hex)?;
39 let xor = XorName(
40 bytes
41 .try_into()
42 .map_err(|_| AddressParseError::InvalidLength)?,
43 );
44 Ok(Self(xor))
45 }
46}
47
48impl std::fmt::Display for ChunkAddress {
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50 write!(f, "{}", &self.to_hex())
51 }
52}