• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #![allow(clippy::expect_used)]
2 // Copyright 2023 Google LLC
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //     http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 #[cfg(test)]
17 /// A mock implementation of a CryptoRng that returns the given bytes in `values` in
18 /// sequence.
19 pub(crate) struct MockCryptoRng<'a, I: Iterator<Item = &'a u8>> {
20     pub(crate) values: I,
21 }
22 
23 impl<'a, I: Iterator<Item = &'a u8>> rand::CryptoRng for MockCryptoRng<'a, I> {}
24 
25 impl<'a, I: Iterator<Item = &'a u8>> rand::RngCore for MockCryptoRng<'a, I> {
fill_bytes(&mut self, dest: &mut [u8])26     fn fill_bytes(&mut self, dest: &mut [u8]) {
27         for i in dest {
28             *i = *self.values.next().expect("Expecting more data in MockCryptoRng input");
29         }
30     }
31 
next_u32(&mut self) -> u3232     fn next_u32(&mut self) -> u32 {
33         let mut bytes = [0; 4];
34         self.fill_bytes(&mut bytes);
35         u32::from_le_bytes(bytes)
36     }
37 
next_u64(&mut self) -> u6438     fn next_u64(&mut self) -> u64 {
39         let mut bytes = [0; 8];
40         self.fill_bytes(&mut bytes);
41         u64::from_le_bytes(bytes)
42     }
43 
try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error>44     fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {
45         self.fill_bytes(dest);
46         Ok(())
47     }
48 }
49