Move to as_chunks.
authorSunil Nimmagadda <sunil@nimmagadda.net>
Thu, 01 Feb 2024 16:51:45 +0530
changeset 25 72c4d898c478
parent 24 b45e6310310e
child 26 4ad31d279c35
Move to as_chunks. Fuzz testing needs a nightly, so let's move to nightly everywhere.
src/lib.rs
src/vrrpv2.rs
--- a/src/lib.rs	Wed Jan 31 14:39:06 2024 +0530
+++ b/src/lib.rs	Thu Feb 01 16:51:45 2024 +0530
@@ -1,1 +1,2 @@
+#![feature(slice_as_chunks)]
 pub mod vrrpv2;
--- a/src/vrrpv2.rs	Wed Jan 31 14:39:06 2024 +0530
+++ b/src/vrrpv2.rs	Thu Feb 01 16:51:45 2024 +0530
@@ -163,16 +163,13 @@
     Ok(vrrpv2)
 }
 
-/// TODO: as_chunks is nicer but not stabilised yet.
 fn checksum(bytes: &[u8]) -> u16 {
-    let mut sum: u32 = 0;
-    for chunk in bytes.chunks(2) {
-        // Left over byte if any
-        if chunk.len() == 1 {
-            sum += u32::from(chunk[0]);
-        } else {
-            sum += u32::from(u16::from_be_bytes(chunk.try_into().unwrap()));
-        }
+    let (chunks, remainder) = bytes.as_chunks::<2>();
+    let mut sum = chunks
+        .iter()
+        .fold(0, |acc, x| acc + u32::from(u16::from_be_bytes(*x)));
+    if !remainder.is_empty() {
+        sum += u32::from(remainder[0]);
     }
     while (sum >> 16) > 0 {
         sum = (sum & 0xffff) + (sum >> 16);