Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / third_party / betocore / crypto_provider_rustcrypto / src / testing.rs

testing.rs48 lines · 1.6 KiBRaw
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.
19pub(crate) struct MockCryptoRng<'a, I: Iterator<Item = &'a u8>> {
20 pub(crate) values: I,
21}
22
23impl<'a, I: Iterator<Item = &'a u8>> rand::CryptoRng for MockCryptoRng<'a, I> {}
24
25impl<'a, I: Iterator<Item = &'a u8>> rand::RngCore for MockCryptoRng<'a, I> {
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
32 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
38 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
44 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {
45 self.fill_bytes(dest);
46 Ok(())
47 }
48}