Function parseIntSizeSuffix [src]
Parses a number like '2G', '2Gi', or '2GiB'.
Prototype
pub fn parseIntSizeSuffix(buf: []const u8, digit_base: u8) ParseIntError!usize
Parameters
buf: []const u8
digit_base: u8
Possible Errors
The input was empty or contained an invalid character
The result cannot fit in the type specified
Example
test parseIntSizeSuffix {
try std.testing.expectEqual(2, try parseIntSizeSuffix("2", 10));
try std.testing.expectEqual(2, try parseIntSizeSuffix("2B", 10));
try std.testing.expectEqual(2000, try parseIntSizeSuffix("2kB", 10));
try std.testing.expectEqual(2000, try parseIntSizeSuffix("2k", 10));
try std.testing.expectEqual(2048, try parseIntSizeSuffix("2KiB", 10));
try std.testing.expectEqual(2048, try parseIntSizeSuffix("2Ki", 10));
try std.testing.expectEqual(10240, try parseIntSizeSuffix("aKiB", 16));
try std.testing.expectError(error.InvalidCharacter, parseIntSizeSuffix("", 10));
try std.testing.expectError(error.InvalidCharacter, parseIntSizeSuffix("2iB", 10));
}
Source
pub fn parseIntSizeSuffix(buf: []const u8, digit_base: u8) ParseIntError!usize {
var without_B = buf;
if (mem.endsWith(u8, buf, "B")) without_B.len -= 1;
var without_i = without_B;
var magnitude_base: usize = 1000;
if (mem.endsWith(u8, without_B, "i")) {
without_i.len -= 1;
magnitude_base = 1024;
}
if (without_i.len == 0) return error.InvalidCharacter;
const orders_of_magnitude: usize = switch (without_i[without_i.len - 1]) {
'k', 'K' => 1,
'M' => 2,
'G' => 3,
'T' => 4,
'P' => 5,
'E' => 6,
'Z' => 7,
'Y' => 8,
'R' => 9,
'Q' => 10,
else => 0,
};
var without_suffix = without_i;
if (orders_of_magnitude > 0) {
without_suffix.len -= 1;
} else if (without_i.len != without_B.len) {
return error.InvalidCharacter;
}
const multiplier = math.powi(usize, magnitude_base, orders_of_magnitude) catch |err| switch (err) {
error.Underflow => unreachable,
error.Overflow => return error.Overflow,
};
const number = try std.fmt.parseInt(usize, without_suffix, digit_base);
return math.mul(usize, number, multiplier);
}