ant_protocol/storage/
chunks.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 super::ChunkAddress;
10use crate::NetworkAddress;
11use bytes::Bytes;
12use serde::{Deserialize, Deserializer, Serialize, Serializer};
13
14use xor_name::XorName;
15
16/// Chunk, an immutable chunk of data
17#[derive(Hash, Eq, PartialEq, PartialOrd, Ord, Clone, custom_debug::Debug)]
18pub struct Chunk {
19    /// Network address. Omitted when serialising and
20    /// calculated from the `value` when deserialising.
21    pub address: ChunkAddress,
22    /// Contained data.
23    #[debug(skip)]
24    pub value: Bytes,
25}
26
27impl Chunk {
28    /// The default maximum size of a chunk is 1MB
29    pub const DEFAULT_MAX_SIZE: usize = 1024 * 1024;
30
31    /// Creates a new instance of `Chunk`.
32    pub fn new(value: Bytes) -> Self {
33        Self {
34            address: ChunkAddress::new(XorName::from_content(value.as_ref())),
35            value,
36        }
37    }
38
39    /// Returns the value.
40    pub fn value(&self) -> &Bytes {
41        &self.value
42    }
43
44    /// Returns the address.
45    pub fn address(&self) -> &ChunkAddress {
46        &self.address
47    }
48
49    /// Returns the NetworkAddress
50    pub fn network_address(&self) -> NetworkAddress {
51        NetworkAddress::ChunkAddress(self.address)
52    }
53
54    /// Returns the name.
55    pub fn name(&self) -> &XorName {
56        self.address.xorname()
57    }
58
59    /// Returns size of this chunk after serialisation.
60    pub fn size(&self) -> usize {
61        self.value.len()
62    }
63
64    /// Returns true if the chunk is too big
65    pub fn is_too_big(&self) -> bool {
66        self.size() > Self::DEFAULT_MAX_SIZE
67    }
68}
69
70impl Serialize for Chunk {
71    fn serialize<S: Serializer>(&self, serialiser: S) -> Result<S::Ok, S::Error> {
72        // Address is omitted since it's derived from value
73        self.value.serialize(serialiser)
74    }
75}
76
77impl<'de> Deserialize<'de> for Chunk {
78    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
79        let value = Deserialize::deserialize(deserializer)?;
80        Ok(Self::new(value))
81    }
82}