module Language.Lexer.Tlex.Data.Addr (
    addrCodeUnitsLE,
) where

import           Language.Lexer.Tlex.Prelude

import qualified Data.Bits                   as Bits


addrCodeUnitsLE :: Bits.Bits a => Integral a => Int -> a -> [Word8]
addrCodeUnitsLE :: Int -> a -> [Word8]
addrCodeUnitsLE Int
us a
n
    | a
n a -> a -> Bool
forall a. Ord a => a -> a -> Bool
>= a
0    = Int -> [Word8] -> [Word8]
forall a. Int -> [a] -> [a]
take Int
us
        do (a -> Word8) -> [a] -> [Word8]
forall a b. (a -> b) -> [a] -> [b]
map
            do \a
m -> Integer -> Word8
forall a. Num a => Integer -> a
fromInteger do a -> Integer
forall a b. (Integral a, Num b) => a -> b
fromIntegral do a -> a
mod8bit a
m
            do (a -> a) -> a -> [a]
forall a. (a -> a) -> a -> [a]
iterate (a -> Int -> a
forall a. Bits a => a -> Int -> a
`Bits.shiftR` Int
8) a
n
    | a
n a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
-1   = Int -> Word8 -> [Word8]
forall a. Int -> a -> [a]
replicate Int
us Word8
0xFF
    | Bool
otherwise = [Char] -> [Word8]
forall a. HasCallStack => [Char] -> a
error [Char]
"unsupported"
    where
        mod8bit :: a -> a
mod8bit = case a -> Maybe Int
forall a. Bits a => a -> Maybe Int
Bits.bitSizeMaybe a
n of
            Maybe Int
Nothing -> \a
x -> a
x a -> a -> a
forall a. Integral a => a -> a -> a
`mod` a
256
            Just Int
bs
                | Int
bs Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
8   -> \a
x -> a
x
                | Bool
otherwise -> \a
x -> a
x a -> a -> a
forall a. Integral a => a -> a -> a
`mod` a
256