huff_coding 1.0.0

An implementation of the Huffman coding algorithm, enabling one to create a Huffman tree with any alphabet they choose.
Documentation
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
pub use self::byte_weights::ByteWeights;

use super::tree::letter::HuffLetter;

use std::{
    collections::{
        HashMap,
        hash_map::RandomState,
    },
    hash::{
        Hash, 
        BuildHasher
    },
};

/// Trait signifying that the struct stores the weights of a certain type (letter), so that
/// for any stored letter there is a corresponding `usize`(weight).
/// 
/// Implemented by default for [`HashMap<L, usize>`][std::collections::HashMap] and
/// for [`ByteWeights`][byte_weights::ByteWeights]
/// 
/// Needed implementations:
/// * Traits:
///  * [`Eq`][Eq]
///  * [`Clone`][Clone]
///  * [`IntoIterator<Item = (L, usize)>`][IntoIterator]
/// * Methods:
///  * `fn get(&self, letter: &L) -> Option<&usize>`
///  * `fn get_mut(&mut self, letter: &L) -> Option<&mut usize>`
///  * `fn len(&self) -> usize`
///  * `fn is_empty(&self) -> bool`
/// 
/// In order to build with a [`HuffTree`][crate::tree::HuffTree] `L` must implement [`HuffLetter`][crate::tree::letter::HuffLetter]
pub trait Weights<L>: Eq + Clone + IntoIterator<Item = (L, usize)>{
    fn get(&self, letter: &L) -> Option<&usize>;
    fn get_mut(&mut self, letter: &L) -> Option<&mut usize>;
    fn len(&self) -> usize;
    fn is_empty(&self) -> bool;
}

impl<L: Eq + Clone + Hash> Weights<L> for HashMap<L, usize>{
    fn get(&self, letter: &L) -> Option<&usize>{
        self.get(letter)
    }
    fn get_mut(&mut self, letter: &L) -> Option<&mut usize>{
        self.get_mut(letter)
    }
    fn len(&self) -> usize{
        self.len()
    }
    fn is_empty(&self) -> bool{
        self.is_empty()
    }
}

/// Count every letter in the provided slice Returning a [`HashMap`][std::collections::HashMap]
/// of letters to their counts (weights)
/// 
/// # Example
/// ---
/// ```
/// use huff_coding::weights::build_weights_map;
/// 
/// let weights = build_weights_map(&[12, -543, 12, 66, 66, 66]);
/// 
/// assert_eq!(weights.get(&-543), Some(&1));
/// assert_eq!(weights.get(&12), Some(&2));
/// assert_eq!(weights.get(&66), Some(&3));
/// ```
/// The resulting [`HashMap`][std::collections::HashMap] 
/// can be used to build a [`HuffTree`][crate::tree::HuffTree]:
/// ```
/// use huff_coding::prelude::{
///     HuffTree,
///     build_weights_map,
/// };
/// 
/// let weights = build_weights_map(&['a', 'a', 'a', 'b', 'b', 'c']);
/// 
/// let tree = HuffTree::from_weights(weights);
/// ```
pub fn build_weights_map<L: HuffLetter>(letters: &[L]) -> HashMap<L, usize>{
    build_weights_map_with_hasher(letters, RandomState::default())
}

/// Count every letter in the provided slice Returning a [`HashMap`][std::collections::HashMap]
/// of letters to their counts (weights), with the provided hash builder.
/// 
/// # Example
/// ---
/// ```
/// use huff_coding::weights::build_weights_map;
/// 
/// let weights = build_weights_map(&[8, 6, 8, 12, 12, 12]);
/// 
/// assert_eq!(weights.get(&6), Some(&1));
/// assert_eq!(weights.get(&8), Some(&2));
/// assert_eq!(weights.get(&12), Some(&3));
/// ```
/// The resulting [`HashMap`][std::collections::HashMap] 
/// can be used to build a [`HuffTree`][crate::tree::HuffTree]:
/// ```
/// use huff_coding::prelude::{
///     HuffTree,
///     build_weights_map_with_hasher,
/// };
/// use std::collections::hash_map::RandomState;
/// 
/// let weights = build_weights_map_with_hasher(
///     &['d', 'd', 'd', 'e', 'e', 'f'],
///     RandomState::default()
/// );
/// 
/// let tree = HuffTree::from_weights(weights);
/// ```
pub fn build_weights_map_with_hasher<L: HuffLetter, S: BuildHasher>(letters: &[L], hash_builder: S) -> HashMap<L, usize, S>{
    let mut map = HashMap::with_hasher(hash_builder);
    for l in letters{
        let entry = map.entry(l.clone()).or_insert(0);
        *entry += 1;
    }
    map
}

/// Struct storing the number of occurences of each byte in
/// a provided byte slice.
pub mod byte_weights{
    use crate::utils::ration_vec;
    use super::Weights;

    use std::{
        ops::{Add, AddAssign},
        thread,
    };

    /// Struct storing the number of occurences of each byte in
    /// a provided byte slice.
    /// 
    /// A [`HuffTree`][crate::tree::HuffTree] can be initialized with it,
    /// as `ByteWeights` implements the [`Weights`][crate::weights::Weights] trait.
    /// 
    /// # Examples
    /// ---
    /// Initialization and interfacing:
    /// ```
    /// use huff_coding::prelude::ByteWeights;
    /// 
    /// let byte_weights = ByteWeights::from_bytes(b"fffff");
    /// assert_eq!(*byte_weights.get(&b'f').unwrap(), 5);
    /// assert_eq!(byte_weights.len(), 1);
    /// ```
    /// Iteration:
    /// ```
    /// use huff_coding::prelude::ByteWeights;
    /// 
    /// let byte_weights = ByteWeights::from_bytes(&[0, 1, 1, 2, 2, 2]);
    /// for (byte, weight) in byte_weights{
    ///     assert_eq!(byte as usize, weight - 1);
    /// }
    /// ```
    /// Adding two `ByteWeights`:
    /// ```
    /// use huff_coding::prelude::ByteWeights;
    /// 
    /// let mut byte_weights = ByteWeights::from_bytes(b"aabbb");
    /// let other = ByteWeights::from_bytes(b"aaabbc");
    /// 
    /// byte_weights += other;
    /// 
    /// assert_eq!(*byte_weights.get(&b'a').unwrap(), 5);
    /// assert_eq!(*byte_weights.get(&b'b').unwrap(), 5);
    /// assert_eq!(*byte_weights.get(&b'c').unwrap(), 1);
    /// ```
    #[derive(Clone, Copy, Eq)]
    pub struct ByteWeights{
        weights: [usize; 256],
        len: usize,
    }

    impl Weights<u8> for ByteWeights{
        fn get(&self, byte: &u8) -> Option<&usize>{
            self.get(byte)
        }

        fn get_mut(&mut self, byte: &u8) -> Option<&mut usize>{
            self.get_mut(byte)
        }

        fn len(&self) -> usize{
            self.len()
        }

        fn is_empty(&self) -> bool{
            self.is_empty()
        }
    }

    impl IntoIterator for ByteWeights{
        type Item = (u8, usize);
        type IntoIter = IntoIter;

        fn into_iter(self) -> IntoIter{
            IntoIter{weights: self, current_index: 0}
        }   
    }

    impl <'a> IntoIterator for &'a ByteWeights{
        type Item = (u8, usize);
        type IntoIter = Iter<'a>;

        fn into_iter(self) -> Iter<'a>{
            Iter{weights: &self, current_index: 0}
        }   
    }

    impl PartialEq for ByteWeights{
        fn eq(&self, other: &Self) -> bool {
            self.weights == other.weights
        }
    }

    impl Add for ByteWeights{
        type Output = Self;

        fn add(mut self, other: Self) -> Self {
            self.add_byte_weights(&other);
            self
        }
    }

    impl AddAssign for ByteWeights{
        fn add_assign(&mut self, other: Self){
            self.add_byte_weights(&other);
        }
    }

    impl Default for ByteWeights{
        fn default() -> Self{
            Self::new()
        }
    }

    impl ByteWeights{
        /// Initialize new empty `ByteWeights`
        pub fn new() -> Self{
            Self{
                weights: [0;256],
                len: 0,
            }
        }

        /// Initialize new `ByteWeights` from the given [`&[u8]`][u8]
        /// 
        /// This algorithm is inherently O(n), therefore for
        /// larger collections [`threaded_from_bytes`](#method.threaded_from_bytes) is faster.
        /// 
        /// # Example
        /// ---
        /// ```
        /// use huff_coding::prelude::ByteWeights;
        /// 
        /// let byte_weights = ByteWeights::from_bytes(b"aaaaa");
        /// assert_eq!(*byte_weights.get(&b'a').unwrap(), 5);
        /// ```
        pub fn from_bytes(bytes: &[u8]) -> Self{
            // count bytes into an array
            let mut weights: [usize; 256] = [0;256];
            let mut len = 0;

            for byte in bytes{
                if weights[*byte as usize] == 0{len += 1;}
                weights[*byte as usize] += 1;
            }
 
            ByteWeights{
                weights,
                len,
            }
        }

        /// Initialize new `ByteWeights` from the given [`&[u8]`][u8], but
        /// using the specified number of threads to speed up the
        /// process.
        /// 
        /// # Example
        /// ---
        /// ```
        /// use huff_coding::prelude::ByteWeights;
        /// 
        /// let byte_weights = ByteWeights::threaded_from_bytes(b"aaaaa", 12);
        /// assert_eq!(*byte_weights.get(&b'a').unwrap(), 5)
        /// ```
        pub fn threaded_from_bytes(bytes: &[u8], thread_num: usize) -> Self{
            // divide the bytes into rations per thread
            let byte_rations = ration_vec(bytes, thread_num);

            // create ByteWeights from every ration
            let mut handles = Vec::with_capacity(thread_num);
            for ration in byte_rations{
                let handle = thread::spawn(move || {
                    ByteWeights::from_bytes(&ration)
                });
                handles.push(handle);
            }

            // push all created ByteWeights into a Vec 
            let mut weights_vec: Vec<ByteWeights> = Vec::with_capacity(thread_num);
            for handle in handles{
                weights_vec.push(handle.join().unwrap());
            }

            // add all ByteWeights into one
            let mut weights = weights_vec.pop().unwrap();
            for weights_other in weights_vec{
                weights += weights_other;
            }

            weights
        }

        /// Return a reference to the weight corresponding
        /// to the given byte.
        pub fn get(&self, byte: &u8) -> Option<&usize>{
            let weight = self.weights.get(*byte as usize)?;
            if *weight == 0{
                return None
            }
            Some(weight)
        }

        /// Return a mutable reference to the weight corresponding
        /// to the given byte.
        pub fn get_mut(&mut self, byte: &u8) -> Option<&mut usize>{
            let weight = self.weights.get_mut(*byte as usize)?;
            if *weight == 0{
                return None
            }
            Some(weight)
        }

        /// Return the number of different counted bytes stored in the `ByteWeights`
        pub fn len(&self) -> usize{
            self.len
        }

        /// Return true if len == 0
        pub fn is_empty(&self) -> bool{
            self.len == 0
        }

        /// Returns an iterator over the bytes to their weights `(u8, usize)`
        pub fn iter(&self) -> Iter{
            self.into_iter()
        }

        /// Add another `ByteWeights` to self, like so:
        /// * if a byte is present in self & other, add their weights
        /// * if a byte is present in other, but not in self, add it to self with other's weight
        /// 
        /// # Example
        /// –––
        /// ```
        /// use huff_coding::prelude::ByteWeights;
        /// 
        /// let mut byte_weights = ByteWeights::from_bytes(b"aabbb");
        /// let other = ByteWeights::from_bytes(b"aaabbc");
        /// 
        /// byte_weights.add_byte_weights(&other);
        /// 
        /// assert_eq!(*byte_weights.get(&b'a').unwrap(), 5);
        /// assert_eq!(*byte_weights.get(&b'b').unwrap(), 5);
        /// assert_eq!(*byte_weights.get(&b'c').unwrap(), 1);
        /// ```
        pub fn add_byte_weights(&mut self, other: &ByteWeights){
            for (b, f) in other{
                let self_entry = self.get_mut(&b);
                match self_entry{
                    Some(self_entry) =>{
                        *self_entry += f;
                    }
                    None =>{
                        self.weights[b as usize] = f;
                        self.len += 1;
                    }
                }
            }
        }
    }

    /// Consuming iterator over the contents (`(u8, usize)`) of `ByteWeights`
    pub struct IntoIter{
        weights: ByteWeights,
        current_index: usize,
    }
    
    impl Iterator for IntoIter{
        type Item = (u8, usize);

        fn next(&mut self) -> Option<Self::Item>{
            if self.current_index == 256{
                return None
            }

            while self.weights.get(&(self.current_index as u8)).is_none(){
                if self.current_index == 256{
                    return None
                }
                self.current_index += 1
            }
            let entry = Some((self.current_index as u8, *self.weights.get(&(self.current_index as u8)).unwrap()));
            if self.current_index != 256{self.current_index += 1;}

            entry
        }
    }

    /// Non consuming iterator over the contents (`(u8, usize)`) of `ByteWeights`
    pub struct Iter<'a>{
            weights: &'a ByteWeights,
            current_index: usize,
    }

    impl Iterator for Iter<'_>{
            type Item = (u8, usize);
    
            fn next(&mut self) -> Option<Self::Item>{
                if self.current_index == 256{
                    return None
                }
    
                while self.weights.get(&(self.current_index as u8)).is_none(){
                    if self.current_index == 256{
                        return None
                    }
                    self.current_index += 1
                }
                let entry = Some((self.current_index as u8, *self.weights.get(&(self.current_index as u8)).unwrap()));
                if self.current_index != 256{self.current_index += 1;}
    
                entry
            }
    }
}