about summary refs log tree commit diff
path: root/tvix/nix-compat/src/wire/bytes
diff options
context:
space:
mode:
authoredef <edef@edef.eu>2024-04-30T08·56+0000
committeredef <edef@edef.eu>2024-04-30T09·16+0000
commitb3305ea6e26bef913cfa1a1d7b5cb0c13392ed4c (patch)
treee37074053e15e9bfcc2fc9791ed4555cdc28f916 /tvix/nix-compat/src/wire/bytes
parent88f49c83513670113bc429abb478412de4ffd1a8 (diff)
refactor(nix-compat/wire/bytes): branchless padding computation r/8041
Change-Id: Ie07c2516a485c78afa6f9a3c8256e9708c4c42c5
Reviewed-on: https://cl.tvl.fyi/c/depot/+/11548
Tested-by: BuildkiteCI
Reviewed-by: flokli <flokli@flokli.de>
Diffstat (limited to 'tvix/nix-compat/src/wire/bytes')
-rw-r--r--tvix/nix-compat/src/wire/bytes/mod.rs15
1 files changed, 8 insertions, 7 deletions
diff --git a/tvix/nix-compat/src/wire/bytes/mod.rs b/tvix/nix-compat/src/wire/bytes/mod.rs
index 436667731815..031d969e287f 100644
--- a/tvix/nix-compat/src/wire/bytes/mod.rs
+++ b/tvix/nix-compat/src/wire/bytes/mod.rs
@@ -119,14 +119,10 @@ pub async fn write_bytes<W: AsyncWriteExt + Unpin, B: AsRef<[u8]>>(
 }
 
 /// Computes the number of bytes we should add to len (a length in
-/// bytes) to be alined on 64 bits (8 bytes).
+/// bytes) to be aligned on 64 bits (8 bytes).
 fn padding_len(len: u64) -> u8 {
-    let modulo = len % 8;
-    if modulo == 0 {
-        0
-    } else {
-        8 - modulo as u8
-    }
+    let aligned = len.wrapping_add(7) & !7;
+    aligned.wrapping_sub(len) as u8
 }
 
 #[cfg(test)]
@@ -229,4 +225,9 @@ mod tests {
             .build();
         assert_ok!(write_bytes(&mut mock, &input).await)
     }
+
+    #[test]
+    fn padding_len_u64_max() {
+        assert_eq!(padding_len(u64::MAX), 1);
+    }
 }