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
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
#![allow(clippy::len_without_is_empty)]
use bytes::Bytes;
use std::fmt;

use crate::{Compression, CompressionError, HashSum};

/// A single chunk.
///
/// Represents a single chunk of a file. Is not compressed.
#[derive(Debug, Clone, PartialEq)]
pub struct Chunk(pub(crate) Bytes);

impl<T> From<T> for Chunk
where
    T: Into<bytes::Bytes>,
{
    fn from(b: T) -> Self {
        Self(b.into())
    }
}

impl Chunk {
    /// Chunk data.
    #[inline]
    pub fn data(&self) -> &[u8] {
        &self.0[..]
    }
    /// Size of chunk.
    #[inline]
    pub fn len(&self) -> usize {
        self.0.len()
    }
    /// Create a verified chunk by calculating a hash sum for it.
    #[inline]
    pub fn verify(self) -> VerifiedChunk {
        VerifiedChunk::from(self)
    }
    #[cfg(feature = "compress")]
    /// Create a compressed chunk.
    #[inline]
    pub fn compress(self, compression: Compression) -> Result<CompressedChunk, CompressionError> {
        CompressedChunk::try_compress(compression, self)
    }
    #[inline]
    pub fn into_inner(self) -> Bytes {
        self.0
    }
}

/// A chunk with verified hash sum.
#[derive(Debug, Clone)]
pub struct VerifiedChunk {
    pub(crate) chunk: Chunk,
    pub(crate) hash_sum: HashSum,
}

impl From<Chunk> for VerifiedChunk {
    fn from(chunk: Chunk) -> Self {
        Self::new(chunk)
    }
}

impl VerifiedChunk {
    /// Create a new verified chunk by calculating a hash of it.
    pub fn new(chunk: Chunk) -> Self {
        Self {
            hash_sum: HashSum::b2_digest(&chunk.data()),
            chunk,
        }
    }
    /// Size of chunk.
    #[inline]
    pub fn len(&self) -> usize {
        self.chunk.len()
    }
    /// Get chunk.
    #[inline]
    pub fn chunk(&self) -> &Chunk {
        &self.chunk
    }
    /// Get chunk data.
    #[inline]
    pub fn data(&self) -> &[u8] {
        self.chunk.data()
    }
    /// Get hash sum of chunk.
    #[inline]
    pub fn hash(&self) -> &HashSum {
        &self.hash_sum
    }
    /// Split into hash and chunk.
    #[inline]
    pub fn into_parts(self) -> (HashSum, Chunk) {
        (self.hash_sum, self.chunk)
    }
}

/// A compressed chunk.
#[derive(Debug, Clone)]
pub struct CompressedChunk {
    pub(crate) data: Bytes,
    pub(crate) source_size: usize,
    pub(crate) compression: Compression,
}

impl CompressedChunk {
    /// Create a compressed chunk.
    #[cfg(feature = "compress")]
    pub fn try_compress(
        compression: Compression,
        chunk: Chunk,
    ) -> Result<CompressedChunk, CompressionError> {
        compression.compress(chunk)
    }
    /// Chunk data.
    #[inline]
    pub fn data(&self) -> &[u8] {
        &self.data[..]
    }
    /// Size of chunk.
    #[inline]
    pub fn len(&self) -> usize {
        self.data.len()
    }
    /// Decompress the chunk.
    pub fn decompress(self) -> Result<Chunk, CompressionError> {
        Compression::decompress(self)
    }
    /// Compression used for chunk.
    #[inline]
    pub fn compression(&self) -> Compression {
        self.compression
    }
    #[inline]
    pub fn into_inner(self) -> (Compression, Bytes) {
        (self.compression, self.data)
    }
}

/// A possibly compressed chunk fetched from archive.
///
/// Chunk might be compressed and needs to be decompressed before being verified.
#[derive(Debug, Clone)]
pub struct CompressedArchiveChunk {
    pub(crate) chunk: CompressedChunk,
    pub(crate) expected_hash: HashSum,
}

impl CompressedArchiveChunk {
    /// Size of chunk.
    pub fn len(&self) -> usize {
        self.chunk.len()
    }
    /// Decompress the chunk.
    pub fn decompress(self) -> Result<ArchiveChunk, CompressionError> {
        Ok(ArchiveChunk {
            chunk: self.chunk.decompress()?,
            expected_hash: self.expected_hash,
        })
    }
}

#[derive(Debug)]
pub struct HashSumMismatchError {
    expected: HashSum,
    got: HashSum,
    pub invalid_chunk: Chunk,
}
impl std::error::Error for HashSumMismatchError {}
impl fmt::Display for HashSumMismatchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "expected hash {} but got {}", self.expected, self.got)
    }
}

/// An unverified chunk fetched from archive.
#[derive(Debug, Clone)]
pub struct ArchiveChunk {
    pub(crate) chunk: Chunk,
    pub(crate) expected_hash: HashSum,
}

impl ArchiveChunk {
    /// Size of chunk.
    pub fn len(&self) -> usize {
        self.chunk.len()
    }
    /// Verify an unverified chunk.
    ///
    /// Results in a verified chunk or an error if the chunk hash sum doesn't
    /// match with the expected one.
    pub fn verify(self) -> Result<VerifiedChunk, HashSumMismatchError> {
        let hash_sum = HashSum::b2_digest(self.chunk.data());
        if hash_sum != self.expected_hash {
            Err(HashSumMismatchError {
                expected: self.expected_hash,
                got: hash_sum,
                invalid_chunk: self.chunk,
            })
        } else {
            Ok(VerifiedChunk {
                chunk: self.chunk,
                hash_sum,
            })
        }
    }
}