Copyright | (c) Andreas Klebinger 2020 |
---|---|

License | BSD3 |

Maintainer | Andreas Klebinger |

Portability | GHC >= 7.10 This module provides a generic interface over the encoding and decoding algorithm. It can be instantiated to a wide variate of types. Instantiations based on bytestring and lists are provided in the "Codec.LEB128.List" and "Codec.LEB128.Internal.BS" modules. Size checks for inputs or output types are not performed by default. However they can be included in the put/get functions if desired. |

Safe Haskell | None |

Language | Haskell2010 |

## Synopsis

- encodeLEB128 :: forall a m. (Monoid m, LEB128 a) => (Word8 -> m) -> a -> m
- encodeSLEB128 :: forall a m. (Monoid m, SLEB128 a) => (Word8 -> m) -> a -> m
- decodeLEB128 :: forall a m. (Monad m, LEB128 a) => m Word8 -> m a
- decodeSLEB128 :: forall a m. (Monad m, SLEB128 a) => m Word8 -> m a

# Generic encoding functions

encodeLEB128 :: forall a m. (Monoid m, LEB128 a) => (Word8 -> m) -> a -> m Source #

LEB128-encode a unsigned value into a sequence of bytes.

For example to encode a integer into a list of words you might use.

encodeLEB128 pure :: Integer -> [Word8]

To do the same using a serialization library like bytestrings builder:

encodeLEB128 (B.word8)

For performance reasons it can be important to make sure `encodeLEB128`

is sufficiently specialized. One way to achieve this is to force inlining
using the `inline`

function from GHC.Magic (defined in the ghc-prim package).
For an efficient example generic over the value type this gives us for lists:

toULEB128 :: (Integral a, Bits a) => a -> [Word8] toULEB128 = (inline G.encodeLEB128) pure

Results are undefined for negative numbers.

encodeSLEB128 :: forall a m. (Monoid m, SLEB128 a) => (Word8 -> m) -> a -> m Source #

SLEB128-encodes an singed value into a sequence of bytes.

Works the same as `encodeLEB128`

but supports negative values.

# Generic decoding functions

decodeLEB128 :: forall a m. (Monad m, LEB128 a) => m Word8 -> m a Source #

LEB128-decodes a unsigned value given a monadic way to request bytes.

For example a implementation over a state monad might look like:

execState . decodeLEB128 getByte

This pattern is used by the bytestring based decoder in this package. See there for a complete example.