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.24 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.23 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.22 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.21 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.20 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.19 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.18 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.17 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.16 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.15 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.14 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.13 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.12 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.11 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.10 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.9 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.8 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.7 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.6 tracks/fsharp/exercises/variable-length-quantity/Example.fs
trackler-2.2.1.5 tracks/fsharp/exercises/variable-length-quantity/Example.fs