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
use rand::{rngs::OsRng, Rng};
use std::sync::{Arc, Mutex};

/// A Factory for nonce blobs.
#[derive(Clone)]
pub struct NonceFactory {
    inner: Arc<Mutex<Box<dyn Iterator<Item = Vec<u8>> + Send>>>,
}

impl NonceFactory {
    pub fn from_iterator(iter: Box<dyn Iterator<Item = Vec<u8>> + Send>) -> Self {
        Self {
            inner: Arc::new(Mutex::new(iter)),
        }
    }

    pub fn random() -> NonceFactory {
        Self::from_iterator(Box::new(RandomBlobIter {}))
    }

    pub fn empty() -> NonceFactory {
        Self::from_iterator(Box::new(EmptyBlobIter {}))
    }

    pub fn incrementing() -> NonceFactory {
        Self::from_iterator(Box::new(IncrementingIter { next: 0 }))
    }

    pub fn generate(&self) -> Option<Vec<u8>> {
        self.inner.lock().unwrap().next()
    }
}

struct RandomBlobIter {}

impl Iterator for RandomBlobIter {
    type Item = Vec<u8>;

    fn next(&mut self) -> Option<Self::Item> {
        Some(OsRng.gen::<[u8; 16]>().to_vec())
    }
}

struct EmptyBlobIter {}

impl Iterator for EmptyBlobIter {
    type Item = Vec<u8>;

    fn next(&mut self) -> Option<Self::Item> {
        None
    }
}

struct IncrementingIter {
    next: u64,
}

impl Iterator for IncrementingIter {
    type Item = Vec<u8>;

    fn next(&mut self) -> Option<Self::Item> {
        let blob = self.next.to_le_bytes().to_vec();
        self.next += 1;
        Some(blob)
    }
}