Skip to content

Feature Request: LEB128 integers #26

Description

@willtemperley

It would be great if there was a way to parse LEB128 integers. These are very common in formats like Parquet (which I'm building a parser for), and Protobuf.

extension UInt64 {
    
    public init(parsing input: inout ParserSpan) throws {
        
        var value: UInt64 = 0
        var shift: UInt64 = 0
        
        while true {
            guard shift <= 63 else { // 63 is the max shift for a UInt64
                // The varint is too long to fit in a UInt64.
                throw BinaryParsing.error("Varint too long to fit in UInt64")
            }
            
            let byte = try UInt8(parsingLittleEndian: &input, byteCount: 1)
            
            value |= UInt64(byte & 0x7f) << shift
            
            if (byte & 0x80) == 0 {
                self = value
                return
            }
            
            shift += 7
        }
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions