Skip to content

Commit

Permalink
presented_id_matches_reference_id: clarify, test, correct
Browse files Browse the repository at this point in the history
This would panic with zero-length inputs.  Clarify the allowed
input lengths, and make the loop correct by construction anyway.
  • Loading branch information
ctz committed Dec 30, 2022
1 parent 197e19c commit 7573333
Showing 1 changed file with 67 additions and 7 deletions.
74 changes: 67 additions & 7 deletions src/name/ip_address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,21 +241,22 @@ pub(super) fn presented_id_matches_reference_id(
presented_id: untrusted::Input,
reference_id: untrusted::Input,
) -> Result<bool, Error> {
if presented_id.len() != reference_id.len() {
return Ok(false);
}
match (presented_id.len(), reference_id.len()) {
(4, 4) => (),
(16, 16) => (),
_ => {
return Ok(false);
}
};

let mut presented_ip_address = untrusted::Reader::new(presented_id);
let mut reference_ip_address = untrusted::Reader::new(reference_id);
loop {
while !presented_ip_address.at_end() {
let presented_ip_address_byte = presented_ip_address.read_byte().unwrap();
let reference_ip_address_byte = reference_ip_address.read_byte().unwrap();
if presented_ip_address_byte != reference_ip_address_byte {
return Ok(false);
}
if presented_ip_address.at_end() {
break;
}
}

Ok(true)
Expand Down Expand Up @@ -976,6 +977,65 @@ mod tests {
Ok(false),
);
}

#[test]
fn test_presented_id_matches_reference_id() {
assert_eq!(
presented_id_matches_reference_id(
untrusted::Input::from(&[]),
untrusted::Input::from(&[])
),
Ok(false),
);

assert_eq!(
presented_id_matches_reference_id(
untrusted::Input::from(&[0x01]),
untrusted::Input::from(&[])
),
Ok(false),
);

assert_eq!(
presented_id_matches_reference_id(
untrusted::Input::from(&[]),
untrusted::Input::from(&[0x01])
),
Ok(false),
);

assert_eq!(
presented_id_matches_reference_id(
untrusted::Input::from(&[1, 2, 3, 4]),
untrusted::Input::from(&[1, 2, 3, 4])
),
Ok(true),
);

assert_eq!(
presented_id_matches_reference_id(
untrusted::Input::from(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]),
untrusted::Input::from(&[1, 2, 3, 4])
),
Ok(false),
);

assert_eq!(
presented_id_matches_reference_id(
untrusted::Input::from(&[1, 2, 3, 4]),
untrusted::Input::from(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
),
Ok(false),
);

assert_eq!(
presented_id_matches_reference_id(
untrusted::Input::from(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]),
untrusted::Input::from(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
),
Ok(true),
);
}
}

#[cfg(all(test, feature = "alloc"))]
Expand Down

0 comments on commit 7573333

Please sign in to comment.