#![doc(hidden)]
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;
#[cfg(not(feature = "std"))]
use crate::prelude::*;
#[cfg(feature = "std")]
use std::error::Error;
use crate::{digest, error};
pub use crate::hex::{
decode as from_hex, decode_dirty as from_dirty_hex, encode as to_hex,
encode_upper as to_hex_upper,
};
#[allow(clippy::extra_unused_type_parameters)]
pub fn compile_time_assert_clone<T: Clone>() {}
#[allow(clippy::extra_unused_type_parameters)]
pub fn compile_time_assert_copy<T: Copy>() {}
#[allow(clippy::extra_unused_type_parameters)]
pub fn compile_time_assert_eq<T: Eq>() {}
#[allow(clippy::extra_unused_type_parameters)]
pub fn compile_time_assert_send<T: Send>() {}
#[allow(clippy::extra_unused_type_parameters)]
pub fn compile_time_assert_sync<T: Sync>() {}
#[cfg(feature = "std")]
#[allow(clippy::extra_unused_type_parameters)]
pub fn compile_time_assert_std_error_error<T: Error>() {}
#[derive(Debug)]
#[allow(clippy::module_name_repetitions)]
pub struct TestCase {
attributes: Vec<(String, String, bool)>,
}
impl TestCase {
pub fn consume_digest_alg(&mut self, key: &str) -> Option<&'static digest::Algorithm> {
let name = self.consume_string(key);
match name.as_ref() {
"SHA1" => Some(&digest::SHA1_FOR_LEGACY_USE_ONLY),
"SHA224" => Some(&digest::SHA224),
"SHA256" => Some(&digest::SHA256),
"SHA384" => Some(&digest::SHA384),
"SHA512" => Some(&digest::SHA512),
"SHA512_256" => Some(&digest::SHA512_256),
"SHA3_256" => Some(&digest::SHA3_256),
"SHA3_384" => Some(&digest::SHA3_384),
"SHA3_512" => Some(&digest::SHA3_512),
_ => unreachable!("Unsupported digest algorithm: {}", name),
}
}
pub fn consume_bytes(&mut self, key: &str) -> Vec<u8> {
self.consume_optional_bytes(key)
.unwrap_or_else(|| panic!("No attribute named \"{key}\""))
}
pub fn consume_optional_bytes(&mut self, key: &str) -> Option<Vec<u8>> {
let s = self.consume_optional_string(key)?;
let result = if s.starts_with('\"') {
let s = s.as_bytes();
let mut bytes = Vec::with_capacity(s.len());
let mut s = s.iter().skip(1);
loop {
let b = match s.next() {
Some(b'\\') => {
match s.next() {
Some(b'0') => 0u8,
Some(b't') => b'\t',
Some(b'n') => b'\n',
_ => {
panic!("Invalid hex escape sequence in string.");
}
}
}
Some(b'"') => {
assert!(
s.next().is_none(),
"characters after the closing quote of a quoted string."
);
break;
}
Some(b) => *b,
None => panic!("Missing terminating '\"' in string literal."),
};
bytes.push(b);
}
bytes
} else {
match from_hex(&s) {
Ok(s) => s,
Err(err_str) => {
panic!("{err_str} in {s}");
}
}
};
Some(result)
}
pub fn consume_usize(&mut self, key: &str) -> usize {
let s = self.consume_string(key);
s.parse::<usize>().unwrap()
}
pub fn consume_bool(&mut self, key: &str) -> bool {
let value_str = self
.consume_optional_string(key)
.unwrap_or_else(|| panic!("No attribute named \"{key}\""))
.to_ascii_lowercase();
value_str.starts_with('t') || value_str.starts_with('y')
}
pub fn consume_string(&mut self, key: &str) -> String {
self.consume_optional_string(key)
.unwrap_or_else(|| panic!("No attribute named \"{key}\""))
}
pub fn consume_optional_string(&mut self, key: &str) -> Option<String> {
for (name, value, consumed) in &mut self.attributes {
if key == name {
assert!(!(*consumed), "Attribute {key} was already consumed");
*consumed = true;
return Some(value.clone());
}
}
None
}
}
#[macro_export]
#[allow(clippy::module_name_repetitions)]
macro_rules! test_file {
($file_name: expr) => {
$crate::test::File {
file_name: $file_name,
contents: include_str!($file_name),
}
};
}
#[derive(Clone, Copy)]
pub struct File<'a> {
pub file_name: &'a str,
pub contents: &'a str,
}
#[allow(clippy::needless_pass_by_value)]
pub fn run<F>(test_file: File, mut f: F)
where
F: FnMut(&str, &mut TestCase) -> Result<(), error::Unspecified>,
{
let lines = &mut test_file.contents.lines();
let mut current_section = String::new();
let mut failed = false;
while let Some(mut test_case) = parse_test_case(&mut current_section, lines) {
let result = match f(¤t_section, &mut test_case) {
Ok(()) => {
if test_case
.attributes
.iter()
.any(|&(_, _, consumed)| !consumed)
{
failed = true;
Err("Test didn't consume all attributes.")
} else {
Ok(())
}
}
Err(error::Unspecified) => Err("Test returned Err(error::Unspecified)."),
};
if result.is_err() {
failed = true;
}
#[cfg(feature = "test_logging")]
{
if let Err(msg) = result {
println!("{}: {}", test_file.file_name, msg);
for (name, value, consumed) in test_case.attributes {
let consumed_str = if consumed { "" } else { " (unconsumed)" };
println!("{}{} = {}", name, consumed_str, value);
}
};
}
}
assert!(!failed, "Test failed.");
}
fn parse_test_case(
current_section: &mut String,
lines: &mut dyn Iterator<Item = &str>,
) -> Option<TestCase> {
let mut attributes = Vec::new();
let mut is_first_line = true;
loop {
let line = lines.next();
#[cfg(feature = "test_logging")]
{
if let Some(text) = &line {
println!("Line: {}", text);
}
}
match line {
None if is_first_line => {
return None;
}
None => {
return Some(TestCase { attributes });
}
Some("") => {
if !is_first_line {
return Some(TestCase { attributes });
}
}
Some(line) if line.starts_with('#') => (),
Some(line) if line.starts_with('[') => {
assert!(is_first_line);
assert!(line.ends_with(']'));
current_section.truncate(0);
current_section.push_str(line);
let _: Option<char> = current_section.pop();
let _: char = current_section.remove(0);
}
Some(line) => {
is_first_line = false;
let parts: Vec<&str> = line.splitn(2, " = ").collect();
assert_eq!(parts.len(), 2, "Syntax error: Expected Key = Value.");
let key = parts[0].trim();
let value = parts[1].trim();
assert_ne!(value.len(), 0);
attributes.push((String::from(key), String::from(value), false));
}
}
}
}
pub mod rand {
use crate::error;
#[derive(Debug)]
pub struct FixedByteRandom {
pub byte: u8,
}
impl crate::rand::sealed::SecureRandom for FixedByteRandom {
fn fill_impl(&self, dest: &mut [u8]) -> Result<(), error::Unspecified> {
dest.fill(self.byte);
Ok(())
}
}
#[derive(Debug)]
pub struct FixedSliceRandom<'a> {
pub bytes: &'a [u8],
}
impl crate::rand::sealed::SecureRandom for FixedSliceRandom<'_> {
#[inline]
fn fill_impl(&self, dest: &mut [u8]) -> Result<(), error::Unspecified> {
dest.copy_from_slice(self.bytes);
Ok(())
}
}
#[derive(Debug)]
pub struct FixedSliceSequenceRandom<'a> {
pub bytes: &'a [&'a [u8]],
pub current: core::cell::UnsafeCell<usize>,
}
impl crate::rand::sealed::SecureRandom for FixedSliceSequenceRandom<'_> {
fn fill_impl(&self, dest: &mut [u8]) -> Result<(), error::Unspecified> {
let current = unsafe { *self.current.get() };
let bytes = self.bytes[current];
dest.copy_from_slice(bytes);
unsafe { *self.current.get() += 1 };
Ok(())
}
}
impl Drop for FixedSliceSequenceRandom<'_> {
fn drop(&mut self) {
assert_eq!(unsafe { *self.current.get() }, self.bytes.len());
}
}
}
#[cfg(test)]
mod tests {
use crate::rand::sealed::SecureRandom;
use crate::test::rand::{FixedByteRandom, FixedSliceRandom, FixedSliceSequenceRandom};
use crate::test::{from_dirty_hex, to_hex_upper};
use crate::{error, test};
use core::cell::UnsafeCell;
#[test]
fn fixed_byte_random() {
let fbr = FixedByteRandom { byte: 42 };
let mut bs = [0u8; 42];
fbr.fill_impl(&mut bs).expect("filled");
assert_eq!([42u8; 42], bs);
}
#[test]
fn fixed_slice_random() {
let fbr = FixedSliceRandom { bytes: &[42u8; 42] };
let mut bs = [0u8; 42];
fbr.fill_impl(&mut bs).expect("fill");
}
#[test]
#[should_panic(
expected = "source slice length (42) does not match destination slice length (0)"
)]
fn fixed_slice_random_length_mismatch() {
let fbr = FixedSliceRandom { bytes: &[42u8; 42] };
let _: Result<(), error::Unspecified> = fbr.fill_impl(&mut []);
}
#[test]
fn fixed_slice_sequence_random() {
let fbr = FixedSliceSequenceRandom {
bytes: &[&[7u8; 7], &[42u8; 42]],
current: UnsafeCell::new(0),
};
let mut bs_one = [0u8; 7];
fbr.fill_impl(&mut bs_one).expect("fill");
assert_eq!([7u8; 7], bs_one);
let mut bs_two = [42u8; 42];
fbr.fill_impl(&mut bs_two).expect("filled");
assert_eq!([42u8; 42], bs_two);
}
#[test]
#[should_panic(expected = "index out of bounds: the len is 0 but the index is 0")]
fn fixed_slice_sequence_random_no_remaining() {
let fbr = FixedSliceSequenceRandom {
bytes: &[],
current: UnsafeCell::new(0),
};
let mut bs_one = [0u8; 7];
let _: Result<(), error::Unspecified> = fbr.fill_impl(&mut bs_one);
}
#[test]
fn one_ok() {
test::run(test_file!("test/test_1_tests.txt"), |_, test_case| {
test_case.consume_string("Key");
Ok(())
});
}
#[test]
#[should_panic(expected = "Test failed.")]
fn one_err() {
test::run(test_file!("test/test_1_tests.txt"), |_, test_case| {
test_case.consume_string("Key");
Err(error::Unspecified)
});
}
#[test]
#[should_panic(expected = "Oh noes!")]
fn one_panics() {
test::run(test_file!("test/test_1_tests.txt"), |_, test_case| {
test_case.consume_string("Key");
panic!("Oh noes!");
});
}
#[test]
#[should_panic(expected = "Test failed.")]
fn first_err() {
err_one(0);
}
#[test]
#[should_panic(expected = "Test failed.")]
fn middle_err() {
err_one(1);
}
#[test]
#[should_panic(expected = "Test failed.")]
fn last_err() {
err_one(2);
}
fn err_one(test_to_fail: usize) {
let mut n = 0;
test::run(test_file!("test/test_3_tests.txt"), |_, test_case| {
test_case.consume_string("Key");
let result = if n == test_to_fail {
Err(error::Unspecified)
} else {
Ok(())
};
n += 1;
result
});
}
#[test]
#[should_panic(expected = "Oh Noes!")]
fn first_panic() {
panic_one(0);
}
#[test]
#[should_panic(expected = "Oh Noes!")]
fn middle_panic() {
panic_one(1);
}
#[test]
#[should_panic(expected = "Oh Noes!")]
fn last_panic() {
panic_one(2);
}
fn panic_one(test_to_fail: usize) {
let mut n = 0;
test::run(test_file!("test/test_3_tests.txt"), |_, test_case| {
test_case.consume_string("Key");
assert_ne!(n, test_to_fail, "Oh Noes!");
n += 1;
Ok(())
});
}
#[test]
#[should_panic(expected = "Syntax error: Expected Key = Value.")]
fn syntax_error() {
test::run(test_file!("test/test_1_syntax_error_tests.txt"), |_, _| {
Ok(())
});
}
#[test]
fn test_to_hex_upper() {
let hex = "abcdef0123";
let bytes = from_dirty_hex(hex);
assert_eq!(hex.to_ascii_uppercase(), to_hex_upper(bytes));
}
}