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
use super::{Chunker, ChunkerError};

use std::io::{BufReader, Bytes, Read};

/// Settings for a static chunk length `Chunker`
///
/// This is a pretty simple chunker, it simply splits the contents into `len` sized
/// chunks. Has a comparatively poor reduplication ratio, due to the boundary shift
/// problem, but it has more performance than just about anything else out there.
#[derive(Clone, Copy)]
pub struct StaticSize {
    pub len: usize,
}

impl Chunker for StaticSize {
    type Chunks = StaticSizeChunker;
    fn chunk_boxed(&self, read: Box<dyn Read + Send + 'static>) -> Self::Chunks {
        StaticSizeChunker {
            settings: *self,
            internal: BufReader::new(read).bytes(),
            next: None,
        }
    }
}

impl Default for StaticSize {
    /// Provides default settings with a chunk size of 64kiB
    fn default() -> Self {
        StaticSize { len: 65_536 }
    }
}

pub struct StaticSizeChunker {
    /// Settings for this `Chunker`
    settings: StaticSize,
    /// `Read` this `Chunker` is slicing over
    internal: Bytes<BufReader<Box<dyn Read + Send + 'static>>>,
    next: Option<std::io::Result<u8>>,
}

impl Iterator for StaticSizeChunker {
    type Item = Result<Vec<u8>, ChunkerError>;
    fn next(&mut self) -> Option<Self::Item> {
        let mut buffer = Vec::new();
        let mut next = if self.next.is_some() {
            self.next.take()
        } else {
            self.internal.next()
        };
        while next.is_some() && buffer.len() < self.settings.len {
            // This unwrap is safe because we just verified that it is a Some(T)
            let byte = next.unwrap();
            let byte = match byte {
                Ok(byte) => byte,
                Err(err) => return Some(Err(err.into())),
            };
            buffer.push(byte);
            next = self.internal.next();
        }
        if buffer.is_empty() {
            None
        } else {
            self.next = next;
            Some(Ok(buffer))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::prelude::*;
    use std::io::Cursor;

    // Provides a test slice 10 times the default max size in length
    fn get_test_data() -> Vec<u8> {
        let size = StaticSize::default().len * 10 + 10_000;
        let mut vec = vec![0_u8; size as usize];
        rand::thread_rng().fill_bytes(&mut vec);
        vec
    }

    // Data should be split into one or more chunks
    #[test]
    fn one_or_more_chunks() {
        let data = get_test_data();
        let cursor = Cursor::new(data);
        let chunker = StaticSize::default();

        assert!(
            chunker
                .chunk(cursor)
                .map(std::result::Result::unwrap)
                .count()
                > 1
        );
    }

    // Data should be identical after reassembaly by simple concatenation
    #[test]
    fn reassemble_data() {
        let data = get_test_data();
        let cursor = Cursor::new(data.clone());
        let chunks = StaticSize::default()
            .chunk(cursor)
            .map(std::result::Result::unwrap)
            .collect::<Vec<_>>();
        let rebuilt: Vec<u8> = chunks.concat();
        assert_eq!(data, rebuilt);
    }

    // Running the chunker over the same data twice should result in identical chunks
    #[test]
    fn identical_chunks() {
        let data = get_test_data();
        let cursor1 = Cursor::new(data.clone());
        let chunks1 = StaticSize::default()
            .chunk(cursor1)
            .map(std::result::Result::unwrap)
            .collect::<Vec<_>>();
        let cursor2 = Cursor::new(data);
        let chunks2 = StaticSize::default()
            .chunk(cursor2)
            .map(std::result::Result::unwrap)
            .collect::<Vec<_>>();
        assert_eq!(chunks1, chunks2);
    }

    // Verifies that this `Chunker` does not produce chunks larger than its max size
    #[test]
    fn max_size() {
        let data = get_test_data();
        let max_size = StaticSize::default().len;

        let chunks = StaticSize::default()
            .chunk(Cursor::new(data))
            .map(std::result::Result::unwrap)
            .collect::<Vec<_>>();

        for chunk in chunks {
            assert!(chunk.len() <= max_size);
        }
    }

    // Verifies that this `Chunker`, at most, produces 1 under-sized chunk
    #[test]
    fn min_size() {
        let data = get_test_data();
        let min_size = StaticSize::default().len;

        let chunks = StaticSize::default()
            .chunk(Cursor::new(data))
            .map(std::result::Result::unwrap)
            .collect::<Vec<_>>();

        let mut undersized_count = 0;
        for chunk in chunks {
            if chunk.len() < min_size {
                undersized_count += 1;
            }
        }

        assert!(undersized_count <= 1);
    }
}