DoxigAlpha

readUleb128

Read a single unsigned LEB128 value from the given reader as type T, or error.Overflow if the value cannot fit.

Function parameters

Parameters

#
T:type
reader:anytype

Read a single unsigned LEB128 value from the given reader as type T,

Functions

#
readUleb128
Read a single unsigned LEB128 value from the given reader as type T,
writeUleb128
Write a single unsigned integer as unsigned LEB128 to the given writer.
readIleb128
Read a single signed LEB128 value from the given reader as type T,
writeIleb128
Write a single signed integer as signed LEB128 to the given writer.
writeUnsignedFixed
This is an "advanced" function.
writeUnsignedExtended
Same as `writeUnsignedFixed` but with a runtime-known length.
writeSignedFixed
This is an "advanced" function.

Source

Implementation

#
pub fn readUleb128(comptime T: type, reader: anytype) !T {
    const U = if (@typeInfo(T).int.bits < 8) u8 else T;
    const ShiftT = std.math.Log2Int(U);

    const max_group = (@typeInfo(U).int.bits + 6) / 7;

    var value: U = 0;
    var group: ShiftT = 0;

    while (group < max_group) : (group += 1) {
        const byte = try reader.readByte();

        const ov = @shlWithOverflow(@as(U, byte & 0x7f), group * 7);
        if (ov[1] != 0) return error.Overflow;

        value |= ov[0];
        if (byte & 0x80 == 0) break;
    } else {
        return error.Overflow;
    }

    // only applies in the case that we extended to u8
    if (U != T) {
        if (value > std.math.maxInt(T)) return error.Overflow;
    }

    return @as(T, @truncate(value));
}