Skip to content

Commit 3bb144c

Browse files
committed
Merge pull request #117 from cassiersg/fix-round-power-of-two
Use wrapping operations for bit-level functions
2 parents b74cdb7 + 35c9960 commit 3bb144c

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

src/utils.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -119,26 +119,26 @@ pub fn format_visibility(vis: Visibility) -> &'static str {
119119
// Based on the trick layed out at
120120
// http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
121121
pub fn round_up_to_power_of_two(mut x: usize) -> usize {
122-
x -= 1;
122+
x = x.wrapping_sub(1);
123123
x |= x >> 1;
124124
x |= x >> 2;
125125
x |= x >> 4;
126126
x |= x >> 8;
127127
x |= x >> 16;
128128
x |= x >> 32;
129-
x + 1
129+
x.wrapping_add(1)
130130
}
131131

132132
#[inline]
133133
#[cfg(target_pointer_width="32")]
134134
pub fn round_up_to_power_of_two(mut x: usize) -> usize {
135-
x -= 1;
135+
x = x.wrapping_sub(1);
136136
x |= x >> 1;
137137
x |= x >> 2;
138138
x |= x >> 4;
139139
x |= x >> 8;
140140
x |= x >> 16;
141-
x + 1
141+
x.wrapping_add(1)
142142
}
143143

144144
// Macro for deriving implementations of Decodable for enums
@@ -161,6 +161,7 @@ macro_rules! impl_enum_decodable {
161161

162162
#[test]
163163
fn power_rounding() {
164+
assert_eq!(0, round_up_to_power_of_two(0));
164165
assert_eq!(1, round_up_to_power_of_two(1));
165166
assert_eq!(64, round_up_to_power_of_two(33));
166167
assert_eq!(256, round_up_to_power_of_two(256));

0 commit comments

Comments
 (0)