File: Digits.hs

package info (click to toggle)
haskell-text-builder-dev 0.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 104 kB
  • sloc: haskell: 587; makefile: 3
file content (40 lines) | stat: -rw-r--r-- 1,130 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
module TextBuilderDev.Domains.Digits where

import qualified Data.ByteString as ByteString
import qualified Data.List.Split as Split
import TextBuilder
import TextBuilderDev.Prelude hiding (intercalate)

-- | Decimal digit.
{-# INLINE decimalDigit #-}
decimalDigit :: (Integral a) => a -> TextBuilder
decimalDigit (fromIntegral -> n) =
  unicodeCodepoint (n + 48)

-- | Hexadecimal digit.
{-# INLINE hexadecimalDigit #-}
hexadecimalDigit :: (Integral a) => a -> TextBuilder
hexadecimalDigit (fromIntegral -> n) =
  if n <= 9
    then unicodeCodepoint (n + 48)
    else unicodeCodepoint (n + 87)

{-# INLINE signed #-}
signed :: (Ord a, Num a) => (a -> TextBuilder) -> a -> TextBuilder
signed onUnsigned i =
  if i >= 0
    then onUnsigned i
    else unicodeCodepoint 45 <> onUnsigned (negate i)

-- | Hexadecimal readable representation of binary data.
--
-- >>> byteStringHexEncoding "Hello"
-- "4865 6c6c 6f"
{-# INLINE byteStringHexEncoding #-}
byteStringHexEncoding :: ByteString -> TextBuilder
byteStringHexEncoding =
  intercalate " "
    . fmap mconcat
    . Split.chunksOf 2
    . fmap hexadecimal
    . ByteString.unpack