Zig 0.17.0-dev (Split by item)

Shortcut keys
?
Show these tips
S
Focus search field
Esc
Clear focus & close tips
U
Jump to source code
↑
Move up in search results
↓
Move down in search results
↵
Go to active search result
This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig standard library. Public Function

writeLeb128

Public Function
std.Io.Writer.writeLeb128
pub fn writeLeb128(w: *Writer, value: anytype) Error!void

Write a single integer as LEB128 to the given writer.

Params

Errors

WriteFailed

See the Writer implementation for detailed diagnostics.

File

Io/Writer.zig:1981
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
pub fn writeLeb128(w: *Writer, value: anytype) Error!void {
    const T = @TypeOf(value);
    const info = switch (@typeInfo(T)) {
        .int => |info| info,
        else => @compileError(@typeName(T) ++ " not supported"),
    };

    const BoundInt = @Int(info.signedness, 7);
    if (info.bits <= 7 or (value >= std.math.minInt(BoundInt) and value <= std.math.maxInt(BoundInt))) {
        const Bits = @Int(info.signedness, 8);
        const byte = switch (info.signedness) {
            .signed => @as(Bits, @intCast(value)) & 0x7F,
            .unsigned => @as(Bits, @intCast(value)),
        };
        try w.writeByte(@bitCast(byte));
        return;
    }

    const Byte = packed struct { bits: u7, more: bool };
    const Int = std.math.ByteAlignedInt(T);

    const max_bytes = @divFloor(info.bits - 1, 7) + 1;

    const sign_value = value >> (info.bits - 1);
    var val: Int = value;
    for (0..max_bytes) |_| {
        const more = switch (info.signedness) {
            .signed => val >> 6 != sign_value,
            .unsigned => val > std.math.maxInt(u7),
        };

        try w.writeByte(@bitCast(@as(Byte, .{
            .bits = @intCast(val & 0x7F),
            .more = more,
        })));

        if (!more) return;

        val >>= 7;
    } else unreachable;
}