1{-# LANGUAGE GeneralizedNewtypeDeriving #-}
2module Basement.MutableBuilder
3    ( Builder(..)
4    , BuildingState(..)
5    ) where
6
7import           Basement.Compat.Base
8import           Basement.Compat.MonadTrans
9import           Basement.Types.OffsetSize
10import           Basement.Monad
11
12newtype Builder collection mutCollection step state err a = Builder
13    { runBuilder :: State (Offset step, BuildingState collection mutCollection step (PrimState state), Maybe err) state a }
14    deriving (Functor, Applicative, Monad)
15
16-- | The in-progress state of a building operation.
17--
18-- The previous buffers are in reverse order, and
19-- this contains the current buffer and the state of
20-- progress packing the elements inside.
21data BuildingState collection mutCollection step state = BuildingState
22    { prevChunks     :: [collection]
23    , prevChunksSize :: !(CountOf step)
24    , curChunk       :: mutCollection state
25    , chunkSize      :: !(CountOf step)
26    }
27
28instance Monad state => MonadFailure (Builder collection mutCollection step state err) where
29    type Failure (Builder collection mutCollection step state err) = err
30    mFail builderError = Builder $ State $ \(offset, bs, _)  ->
31        return ((), (offset, bs, Just builderError))
32