Skip to content

Commit

Permalink
Add newEmptyBuffer
Browse files Browse the repository at this point in the history
Some situations may require a fresh empty buffer. For example, if one
want to define a function that append padded hexadecimal numbers, the
use of a mere `justifyRight` requires the input `Buffer` to be empty.

We introduce `newEmptyBuffer` to solve this issue. It has the caveat to
require an existing `Buffer`, because we need to to know if the array is
pinned or not.

Working example for padded hexadecimal numbers:

    -- | Convenient function to append padded hex
    infixl 6 |>&&
    (|>&&) ∷ (Integral a, FiniteBits a) ⇒ Buffer ⊸ (Word, a) → Buffer
    b |>&& (w, n) = case newEmptyBuffer b of
    (# b', empty #) → (b' |># "0x"#) >< justifyRight w '0' (empty |>& n)

    -- Example
    runBuffer \b → (b |># "Foo "#) |>&& (4, 0xf ∷ Word) |># "; "# |>&& (4, 0xabc ∷ Word)
    -- "Foo 0x000f; 0x0abc"
  • Loading branch information
wismill committed Sep 10, 2023
1 parent fcb019d commit b2d3c84
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Data/Text/Builder/Linear/Core.hs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ module Data.Text.Builder.Linear.Core (
lengthOfBuffer,
dropBuffer,
takeBuffer,
newEmptyBuffer,

-- * Text concatenation
appendBounded,
Expand Down Expand Up @@ -112,6 +113,16 @@ memptyPinned = runST $ do
arr A.unsafeFreeze marr
pure $ Text arr 0 0

-- | Create an empty 'Buffer'.
--
-- The first 'Buffer' is the input and the second is a new empty 'Buffer'.
--
-- Note: a previous buffer is necessary in order to create an empty buffer with
-- the same characteristics.
newEmptyBuffer Buffer (# Buffer, Buffer #)
newEmptyBuffer (Buffer t@(Text arr _ _)) =
(# Buffer t, Buffer (if isPinned arr then memptyPinned else mempty) #)

-- | Duplicate builder. Feel free to process results in parallel threads.
-- Similar to
-- [@Dupable@](https://hackage.haskell.org/package/linear-base/docs/Prelude-Linear.html#t:Dupable)
Expand Down

0 comments on commit b2d3c84

Please sign in to comment.