From 5c2dd94acfc1682135e9f09378d6112b5644e5d0 Mon Sep 17 00:00:00 2001 From: Andrew Martin Date: Mon, 1 Jun 2020 11:28:35 -0400 Subject: [PATCH] Add replicate --- CHANGELOG.md | 4 ++++ bytebuild.cabal | 2 +- src/Data/Bytes/Builder.hs | 15 +++++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b644ae3..664b1ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ Note: Prior to version 0.3.4.0, this library was named `small-bytearray-builder` is now just a compatibility shim to ease the migration process. +## 0.3.6.0 -- 2020-??-?? + +* Add `replicate`. + ## 0.3.5.0 -- 2020-05-01 * Add `wordLEB128` and `word64LEB128`. diff --git a/bytebuild.cabal b/bytebuild.cabal index f01dd95..2fe2674 100644 --- a/bytebuild.cabal +++ b/bytebuild.cabal @@ -1,6 +1,6 @@ cabal-version: 2.2 name: bytebuild -version: 0.3.5.0 +version: 0.3.6.0 synopsis: Serialize to a small byte arrays description: This is similar to the builder facilities provided by diff --git a/src/Data/Bytes/Builder.hs b/src/Data/Bytes/Builder.hs index 63229f1..892f1c9 100644 --- a/src/Data/Bytes/Builder.hs +++ b/src/Data/Bytes/Builder.hs @@ -118,10 +118,14 @@ module Data.Bytes.Builder -- * Encode Floating-Point Types -- ** Human-Readable , doubleDec + -- * Replication + , replicate -- * Control , flush ) where +import Prelude hiding (replicate) + import Control.Exception (SomeException,toException) import Control.Monad.ST (ST,runST) import Control.Monad.IO.Class (MonadIO,liftIO) @@ -1130,6 +1134,17 @@ backwardsWordLoop arr off0 x0 = go off0 x0 where go (off + 1) y else pure off +-- | Replicate a byte the given number of times. +replicate :: + Int -- ^ Number of times to replicate the byte + -> Word8 -- ^ Byte to replicate + -> Builder +replicate !len !w = fromEffect len + (\marr off -> do + PM.setByteArray marr off len w + pure (off + len) + ) + -- Based on C code from https://stackoverflow.com/a/5558614 -- For numbers less than 1073741829, this gives a correct answer. approxDiv10 :: Word -> Word