Guest User

Untitled

a guest
Jun 24th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. fn main() {
  2. assert!(is_valid_ipv6_mask(0));
  3. assert!(is_valid_ipv6_mask(
  4. 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff
  5. ));
  6. assert!(is_valid_ipv6_mask(
  7. 0xffff_0000_0000_0000_0000_0000_0000_0000
  8. ));
  9. assert!(is_valid_ipv6_mask(
  10. 0xff80_0000_0000_0000_0000_0000_0000_0000
  11. ));
  12. assert!(!is_valid_ipv6_mask(
  13. 0xff01_0000_0000_0000_0000_0000_0000_0000
  14. ));
  15. assert!(!is_valid_ipv6_mask(
  16. 0xffff_0000_ffff_ffff_ffff_ffff_ffff_ffff
  17. ));
  18. }
  19.  
  20. /// Check whether the given integer represents a valid IPv6 mask.
  21. /// A valid IP mask is an integer which left-most bits are 1s, and right-most bits are 0s.
  22. fn is_valid_ipv6_mask(value: u128) -> bool {
  23. // flag to check if we're currently processing 1s or 0s
  24. let mut count_ones = true;
  25.  
  26. // check each byte starting from the left.
  27. for byte_index in (0..=15).rev() {
  28. let x = (value >> (byte_index * 8)) & 0xff;
  29. match x {
  30. // We're processing 1s and this byte is 0b1111_1111
  31. 0xff if count_ones => continue,
  32. // We're processing 0s and this byte is 0b0000_0000
  33. 0x00 if !count_ones => continue,
  34. // We're processing 1s and this byte is 0b0000_0000.
  35. // That means all the remaining bytes should be 0 for this integer
  36. // to be a valid mask
  37. 0x00 if count_ones => {
  38. count_ones = false;
  39. continue;
  40. }
  41. // We're processsing 1s and this byte has at least a 1, so we have
  42. // to check bit by bit that the left-most bits are 1s and the
  43. // right-most bits are 0s
  44. byte if byte > 0 && count_ones => {
  45. let mut bit_index = 7;
  46. while (byte >> bit_index) & 1 == 1 {
  47. // This does not overflow, because we now this byte has at
  48. // least a 0 somewhere
  49. bit_index -= 1
  50. }
  51. // At this point, all the bits should be 0s
  52. count_ones = false;
  53. for i in 0..bit_index {
  54. if (byte >> i) & 1 == 1 {
  55. return false;
  56. }
  57. }
  58. }
  59. // Any other case is an error
  60. _ => return false,
  61. }
  62. }
  63. true
  64. }
Add Comment
Please, Sign In to add comment