urbit-hob

Haskell utilities for phonemic base wrangling.
git clone git://git.jtobin.io/urbit-hob.git
Log | Files | Refs | README | LICENSE

Extended.hs (622B)


      1 
      2 module Data.Serialize.Extended (
      3     roll
      4   , unroll
      5   ) where
      6 
      7 import Data.Bits
      8 import qualified Data.ByteString as BS
      9 import Data.List (unfoldr)
     10 import Numeric.Natural (Natural)
     11 
     12 -- | Simple little-endian ByteString encoding for Naturals.
     13 unroll :: Natural -> BS.ByteString
     14 unroll nat = case nat of
     15     0 -> BS.singleton 0
     16     _ -> BS.pack (unfoldr step nat)
     17   where
     18     step 0 = Nothing
     19     step i = Just (fromIntegral i, i `shiftR` 8)
     20 
     21 -- | Simple little-endian ByteString decoding for Naturals.
     22 roll :: BS.ByteString -> Natural
     23 roll = foldr unstep 0 . BS.unpack where
     24   unstep b a = a `shiftL` 8 .|. fromIntegral b
     25