Skip to content

Commit 52785d2

Browse files
Andrew ScullAndrewScull
authored andcommitted
refactor: improve 128-bit integer serialization
Calculate the leading zero bytes with straight line integer operations instead of a looping search. This generates fewer instructions with no branching. Signed-off-by: Andrew Scull <[email protected]>
1 parent 1ee7d49 commit 52785d2

File tree

1 file changed

+4
-14
lines changed

1 file changed

+4
-14
lines changed

ciborium/src/ser/mod.rs

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -87,13 +87,8 @@ where
8787
_ => {}
8888
}
8989

90-
let bytes = raw.to_be_bytes();
91-
92-
// Skip leading zeros.
93-
let mut slice = &bytes[..];
94-
while !slice.is_empty() && slice[0] == 0 {
95-
slice = &slice[1..];
96-
}
90+
let first_non_zero_byte = raw.leading_zeros() as usize / 8;
91+
let slice = &raw.to_be_bytes()[first_non_zero_byte..];
9792

9893
self.0.push(Header::Tag(tag))?;
9994
self.0.push(Header::Bytes(Some(slice.len())))?;
@@ -126,13 +121,8 @@ where
126121
return self.serialize_u64(x);
127122
}
128123

129-
let bytes = v.to_be_bytes();
130-
131-
// Skip leading zeros.
132-
let mut slice = &bytes[..];
133-
while !slice.is_empty() && slice[0] == 0 {
134-
slice = &slice[1..];
135-
}
124+
let first_non_zero_byte = v.leading_zeros() as usize / 8;
125+
let slice = &v.to_be_bytes()[first_non_zero_byte..];
136126

137127
self.0.push(Header::Tag(tag::BIGPOS))?;
138128
self.0.push(Header::Bytes(Some(slice.len())))?;

0 commit comments

Comments
 (0)