Skip to content

Commit b00aa12

Browse files
author
Palmer Cox
committed
Crypto: Add tests for add_bytes_to_bits functions.
1 parent 6386f88 commit b00aa12

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/libextra/crypto/cryptoutil.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,7 @@ mod test {
351351
use std::rand::RngUtil;
352352
use std::vec;
353353

354+
use cryptoutil::{add_bytes_to_bits, add_bytes_to_bits_tuple};
354355
use digest::Digest;
355356

356357
/// Feed 1,000,000 'a's into the digest with varying input sizes and check that the result is
@@ -375,4 +376,50 @@ mod test {
375376

376377
assert!(expected == result_str);
377378
}
379+
380+
// A normal addition - no overflow occurs
381+
#[test]
382+
fn test_add_bytes_to_bits_ok() {
383+
assert!(add_bytes_to_bits::<u64>(100, 10) == 180);
384+
}
385+
386+
// A simple failure case - adding 1 to the max value
387+
#[test]
388+
#[should_fail]
389+
fn test_add_bytes_to_bits_overflow() {
390+
add_bytes_to_bits::<u64>(Bounded::max_value(), 1);
391+
}
392+
393+
// A normal addition - no overflow occurs (fast path)
394+
#[test]
395+
fn test_add_bytes_to_bits_tuple_ok() {
396+
assert!(add_bytes_to_bits_tuple::<u64>((5, 100), 10) == (5, 180));
397+
}
398+
399+
// The low order value overflows into the high order value
400+
#[test]
401+
fn test_add_bytes_to_bits_tuple_ok2() {
402+
assert!(add_bytes_to_bits_tuple::<u64>((5, Bounded::max_value()), 1) == (6, 7));
403+
}
404+
405+
// The value to add is too large to be converted into bits without overflowing its type
406+
#[test]
407+
fn test_add_bytes_to_bits_tuple_ok3() {
408+
assert!(add_bytes_to_bits_tuple::<u64>((5, 0), 0x4000000000000001) == (7, 8));
409+
}
410+
411+
// A simple failure case - adding 1 to the max value
412+
#[test]
413+
#[should_fail]
414+
fn test_add_bytes_to_bits_tuple_overflow() {
415+
add_bytes_to_bits_tuple::<u64>((Bounded::max_value(), Bounded::max_value()), 1);
416+
}
417+
418+
// The value to add is too large to convert to bytes without overflowing its type, but the high
419+
// order value from this conversion overflows when added to the existing high order value
420+
#[test]
421+
#[should_fail]
422+
fn test_add_bytes_to_bits_tuple_overflow2() {
423+
add_bytes_to_bits_tuple::<u64>((Bounded::max_value::<u64>() - 1, 0), 0x8000000000000000);
424+
}
378425
}

0 commit comments

Comments
 (0)