From d496f23fd897bd816927fe2089eaf5578e28f805 Mon Sep 17 00:00:00 2001 From: Andrew Martin Date: Fri, 3 Jan 2020 06:42:32 -0500 Subject: [PATCH] Add word8PaddedLowerHex --- CHANGELOG.md | 1 + src/Data/ByteArray/Builder/Bounded.hs | 7 +++++++ test/Main.hs | 7 +++++++ 3 files changed, 15 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 31ecc0b..ba5bb20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ * Add `runOnto` * Add `Data.Bytes.Chunks.length` * Add `wordPaddedDec2` and `wordPaddedDec9`. +* Add `word8PaddedLowerHex`. ## 0.3.1.0 -- 2019-11-20 diff --git a/src/Data/ByteArray/Builder/Bounded.hs b/src/Data/ByteArray/Builder/Bounded.hs index dfd4231..c014036 100644 --- a/src/Data/ByteArray/Builder/Bounded.hs +++ b/src/Data/ByteArray/Builder/Bounded.hs @@ -47,6 +47,7 @@ module Data.ByteArray.Builder.Bounded , word16LowerHex , word16UpperHex -- ** 8-bit + , word8PaddedLowerHex , word8PaddedUpperHex , word8LowerHex , ascii @@ -383,6 +384,12 @@ word8LowerHex (W8# w) = word8LowerHex# w word8PaddedUpperHex :: Word8 -> Builder 2 word8PaddedUpperHex (W8# w) = word8PaddedUpperHex# w +-- | Requires exactly 2 bytes. Encodes a 8-bit unsigned integer as +-- hexadecimal, zero-padding the encoding to 2 digits. This uses +-- lowercase for the alphabetical digits. +word8PaddedLowerHex :: Word8 -> Builder 2 +word8PaddedLowerHex (W8# w) = word8PaddedLowerHex# w + -- TODO: Is it actually worth unrolling this loop. I suspect that it -- might not be. Benchmark this. word64PaddedUpperHex# :: Word# -> Builder 16 diff --git a/test/Main.hs b/test/Main.hs index 42c0979..f39cec3 100644 --- a/test/Main.hs +++ b/test/Main.hs @@ -64,6 +64,10 @@ tests = testGroup "Tests" runConcat 1 (word64PaddedUpperHex w) === pack (showWord64PaddedUpperHex w) + , TQC.testProperty "word16PaddedLowerHex" $ \w -> + runConcat 1 (word16PaddedLowerHex w) + === + pack (showWord16PaddedLowerHex w) , TQC.testProperty "wordPaddedDec2" $ TQC.forAll (TQC.choose (0,99)) $ \w -> Bounded.run Nat.two (Bounded.wordPaddedDec2 w) === @@ -278,6 +282,9 @@ packUtf8 = Exts.fromList . ByteString.unpack . TE.encodeUtf8 . T.pack showWord64PaddedUpperHex :: Word64 -> String showWord64PaddedUpperHex = printf "%016X" +showWord16PaddedLowerHex :: Word16 -> String +showWord16PaddedLowerHex = printf "%04x" + runConcat :: Int -> Builder -> ByteArray runConcat n = Chunks.concat . run n