Sha256: b73ada97e1f0f9208498c452280f3f18c37ffdfd60d3bf2e894b68075a2f39f3

Contents?: true

Size: 1.11 KB

Versions: 322

Compression:

Stored size: 1.11 KB

Contents

module VariableLengthQuantity

let sevenBitsMask = 0x7fu
let eightBitMask = 0x80u

let toBytesSingle value =
    let unfolder (remainder, first) =
        if remainder > 0u then 
            let maskedBytes = 
                if first then 
                    remainder &&& sevenBitsMask 
                else 
                    remainder &&& sevenBitsMask ||| eightBitMask

            Some (byte maskedBytes, (remainder >>> 7, false))
        else 
            None
        
    if value = 0u then [0uy]
    else List.unfold unfolder (value, true) |> List.rev

let toBytes values = List.collect toBytesSingle values

let fromBytes (bytes: byte list): uint32 list = 
    let folder (acc, values) b = 
        if acc &&& 0xfe000000u > 0u then 
            failwith "Overflow exception"
        else
            let value = (acc <<< 7) ||| (uint32 b &&& 0x7fu)

            if 0x80uy &&& b = 0uy then 
                (0u, value :: values) 
            else 
                (value, values)

    let (acc, values) = List.fold folder (0u, []) bytes

    if acc <> 0u then failwith "Incomplete byte sequence"
    else values |> List.rev

Version data entries

322 entries across 322 versions & 1 rubygems

Version Path
trackler-2.2.1.104 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.103 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.102 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.101 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.100 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.99 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.98 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.97 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.96 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.95 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.94 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.93 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.92 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.91 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.90 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.89 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.88 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.87 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.86 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.85 tracks/fsharp/exercises/variable-length-quantity/Example.fs