authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-07-22 10:58:45-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-07-22 10:58:45-04:00
log99153ac0aa390f01091308073b39947c45851ae6
tree9886098ba123710078bcaa07e2136705469deaea
parentd53fae3551f6215b99f065e837f1f4439ba850fd

add std.math.big.Int.fitsInTwosComp

so that we can pass runtime-known values

1 files changed, 8 insertions(+), 4 deletions(-)

std/math/big/int.zig+8-4
...@@ -150,16 +150,20 @@ pub const Int = struct {...@@ -150,16 +150,20 @@ pub const Int = struct {
150 return bits;150 return bits;
151 }151 }
152152
153 pub fn fits(self: Int, comptime T: type) bool {153 pub fn fitsInTwosComp(self: Int, is_signed: bool, bit_count: usize) bool {
154 if (self.eqZero()) {154 if (self.eqZero()) {
155 return true;155 return true;
156 }156 }
157 if (!T.is_signed and !self.positive) {157 if (!is_signed and !self.positive) {
158 return false;158 return false;
159 }159 }
160160
161 const req_bits = self.bitCountTwosComp() + @boolToInt(self.positive and T.is_signed);161 const req_bits = self.bitCountTwosComp() + @boolToInt(self.positive and is_signed);
162 return T.bit_count >= req_bits;162 return bit_count >= req_bits;
163 }
164
165 pub fn fits(self: Int, comptime T: type) bool {
166 return self.fitsInTwosComp(T.is_signed, T.bit_count);
163 }167 }
164168
165 // Returns the approximate size of the integer in the given base. Negative values accomodate for169 // Returns the approximate size of the integer in the given base. Negative values accomodate for