Zig 0.17.0-dev (Split by item)

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 library itself.

NistLengthEncoding

The NIST SP 800-185 encoded length format.

sha3.NistLengthEncoding
pub const NistLengthEncoding = enum

File

lib/std/crypto/sha3.zig:447

Code

pub const NistLengthEncoding = enum {
    left,
    right,

    /// A length encoded according to NIST SP 800-185.
    pub const Length = struct {
        /// The size of the encoded value, in bytes.
        len: usize = 0,
        /// A buffer to store the encoded length.
        buf: [@sizeOf(usize) + 1]u8 = undefined,

        /// Return the encoded length as a slice.
        pub fn slice(self: *const Length) []const u8 {
            return self.buf[0..self.len];
        }
    };

    /// Encode a length according to NIST SP 800-185.
    pub fn encode(comptime encoding: NistLengthEncoding, len: usize) Length {
        const len_bits = @bitSizeOf(@TypeOf(len)) - @clz(len) + 3;
        const len_bytes = @divCeil(len_bits, 8);

        var res = Length{ .len = len_bytes + 1 };
        if (encoding == .right) {
            res.buf[len_bytes] = @intCast(len_bytes);
        }
        const end = if (encoding == .right) len_bytes - 1 else len_bytes;
        res.buf[end] = @truncate(len << 3);
        var len_ = len >> 5;
        for (1..len_bytes) |i| {
            res.buf[end - i] = @truncate(len_);
            len_ >>= 8;
        }
        if (encoding == .left) {
            res.buf[0] = @intCast(len_bytes);
        }
        return res;
    }
}