@@ -28,57 +28,80 @@
2828
2929module Streamly.Internal.Data.MutArray.Type
3030 (
31− -- * Type
31+ -- ** Type
3232 -- $arrayNotes
3333 MutArray (..)
34− , MutableByteArray
35− , touch
34+
35+ -- ** Conversion
36+ -- *** Pinned and Unpinned
3637 , pin
3738 , unpin
3839 , isPinned
3940
40− -- * Constructing and Writing
41+ -- ** Casting
42+ , cast
43+ , castUnsafe -- XXX unsafeCast
44+ , asBytes
45+ , unsafePinnedAsPtr
46+ , unsafeAsPtr
47+
4148 -- ** Construction
42− , nil
49+ , empty
50+
51+ -- *** New
52+ -- | New arrays are always empty arrays with some reserve capacity to
53+ -- extend the length without reallocating.
54+ , emptyOf
55+ , newArrayWith -- emptyAlignedWith
56+ , pinnedEmptyOf
57+ , pinnedNewAligned -- XXX not required
58+ -- , new -- uninitialized array of specified length
59+
60+ -- *** Cloning
61+ , clone
62+ , pinnedClone
4363
44− -- *** Uninitialized Arrays
45− , pinnedNew
46− , pinnedNewBytes
47− , pinnedNewAligned
48− , new
49− , newArrayWith
64+ -- *** Slicing
65+ -- | Get a subarray without copying
66+ , getSliceUnsafe -- XXX unsafeGetSlice
67+ , getSlice
68+ , splitAt -- XXX should be able to express using getSlice
69+ , breakOn
5070
51− -- *** From streams
71+ -- *** Stream Folds
5272 , ArrayUnsafe (..)
53− , writeNWithUnsafe
54− , writeNWith
55− , writeNUnsafe
56− , pinnedWriteNUnsafe
57− , writeN
58− , pinnedWriteN
59− , pinnedWriteNAligned
60−
61− , writeWith
62− , write
63− , pinnedWrite
64−
65− , writeRevN
66− -- , writeRev
67−
68− -- ** From containers
73+ , unsafeCreateOfWith
74+ , unsafeCreateOf
75+ , unsafePinnedCreateOf
76+ , pinnedCreateOf
77+ , createOfWith
78+ , createOf
79+ , revCreateOf
80+
81+ , pinnedCreate
82+ , createWith
83+ , create
84+ -- , revCreate
85+
86+ -- *** From containers
6987 , fromListN
7088 , pinnedFromListN
7189 , fromList
7290 , pinnedFromList
7391 , fromListRevN
7492 , fromListRev
75− , fromStreamDN
76− , fromStreamD
93+ , fromStreamN
94+ , fromStream
95+ , fromPureStreamN
7796 , fromPureStream
97+ , fromByteStr#
98+ , fromPtrN
99+ , fromChunksK
100+ , fromChunksRealloced -- fromSmallChunks
78101
79− -- * Random writes
102+ -- ** Random writes
80103 , putIndex
81− , putIndexUnsafe
104+ , putIndexUnsafe -- XXX unsafePutIndex
82105 , putIndices
83106 -- , putFromThenTo
84107 -- , putFrom -- start writing at the given position
@@ -86,78 +109,71 @@ module Streamly.Internal.Data.MutArray.Type
86109 -- , putFromTo
87110 -- , putFromRev
88111 -- , putUptoRev
89− , modifyIndexUnsafe
112+ , modifyIndexUnsafe -- XXX unsafeModifyIndex
90113 , modifyIndex
91114 , modifyIndices
92115 , modify
93116 , swapIndices
94117 , unsafeSwapIndices
95118
96− -- * Growing and Shrinking
97− -- Arrays grow only at the end, though it is possible to grow on both sides
98− -- and therefore have a cons as well as snoc. But that will require two
99− -- bounds in the array representation.
100−
101− -- ** Appending elements
102− , snocWith
103− , snoc
104− , snocLinear
105− , snocMay
106− , snocUnsafe
107−
108− -- ** Appending streams
109− , writeAppendNUnsafe
110− , writeAppendN
111− , writeAppendWith
112− , writeAppend
119+ -- ** Reading
113120
114− -- * Eliminating and Reading
115−
116− -- ** To streams
117− , reader
118− , readerRevWith
119− , readerRev
121+ -- *** Indexing
122+ , getIndex
123+ , getIndexUnsafe -- XXX unsafeGetIndex
124+ -- , getFromThenTo
125+ , getIndexRev -- getRevIndex?
126+ , indexReader
127+ , indexReaderWith
120128
121− -- ** To containers
122− , toStreamDWith
123− , toStreamDRevWith
124− , toStreamKWith
125− , toStreamKRevWith
129+ -- *** To Streams
126130 , read
127131 , readRev
132+ , toStreamWith
133+ , toStreamRevWith
128134 , toStreamK
135+ , toStreamKWith
129136 , toStreamKRev
137+ , toStreamKRevWith
138+
139+ -- *** To Containers
130140 , toList
131141
142+ -- *** Unfolds
132143 -- experimental
133144 , producerWith
134145 , producer
135146
136− -- ** Random reads
137− , getIndex
138− , getIndexUnsafe
139− , getIndices
140− , getIndicesD
141− -- , getFromThenTo
142− , getIndexRev
143−
144− -- * Memory Management
145− , blockSize
146− , arrayChunkBytes
147− , allocBytesToElemCount
148− , realloc
149− , resize
150− , resizeExp
151− , rightSize
147+ , reader
148+ , readerRevWith
149+ , readerRev
152150
153− -- * Size
151+ -- ** Size and Capacity
152+ -- *** Size
154153 , length
155154 , byteLength
155+
156+ -- *** Capacity
156157 -- , capacity
157158 , byteCapacity
158159 , bytesFree
159160
160− -- * In-place Mutation Algorithms
161+ -- *** Capacity Management
162+ , blockSize
163+ , arrayChunkBytes
164+ , allocBytesToElemCount
165+ , realloc -- this is "resize"
166+ , grow
167+ , growExp
168+ , rightSize
169+
170+ -- ** Folding
171+ , foldl'
172+ , foldr
173+ , byteCmp
174+ , byteEq
175+
176+ -- ** In-place Mutation Algorithms
161177 , strip
162178 , reverse
163179 , permute
@@ -167,62 +183,121 @@ module Streamly.Internal.Data.MutArray.Type
167183 , mergeBy
168184 , bubble
169185
170− -- * Casting
171− , cast
172− , castUnsafe
173− , asBytes
174− , asPtrUnsafe
175−
176− -- * Folding
177− , foldl'
178− , foldr
179− , cmp
180−
181− -- * Arrays of arrays
182− -- We can add dimensionality parameter to the array type to get
183− -- multidimensional arrays. Multidimensional arrays would just be a
184− -- convenience wrapper on top of single dimensional arrays.
186+ -- ** Growing and Shrinking
187+ -- | Arrays grow only at the end, though it is possible to grow on both
188+ -- sides and therefore have a cons as well as snoc. But that will require
189+ -- both lower and upper bound in the array representation.
185190
186− -- | Operations dealing with multiple arrays, streams of arrays or
187− -- multidimensional array representations.
188−
189− -- ** Construct from streams
190− , chunksOf
191− , pinnedChunksOf
192− , writeChunks
193−
194− -- ** Eliminate to streams
195− , flattenArrays
196− , flattenArraysRev
197− , fromArrayStreamK
198−
199− -- ** Construct from arrays
200− -- get chunks without copying
201− , getSliceUnsafe
202− , getSlice
203− -- , getSlicesFromLenN
204− , splitAt -- XXX should be able to express using getSlice
205− , breakOn
191+ -- *** Appending elements
192+ , snocWith
193+ , snoc
194+ , snocLinear
195+ , snocMay
196+ , snocUnsafe -- XXX unsafeSnoc
206197
207− -- ** Cloning arrays
208− , clone
209− , pinnedClone
198+ -- *** Appending streams
199+ , unsafeAppendN
200+ , appendN
201+ , appendWith
202+ , append
210203
211− -- ** Appending arrays
204+ -- *** Appending arrays
212205 , spliceCopy
213206 , spliceWith
214207 , splice
215208 , spliceExp
216− , spliceUnsafe
209+ , spliceUnsafe -- XXX unsafeSplice
217210 -- , putSlice
218211 -- , appendSlice
219212 -- , appendSliceFrom
220213
221− -- * Utilities
214+ -- ** Serialization using Unbox
215+ , pokeAppend
216+ , pokeAppendMay
217+ , pokeSkipUnsafe -- unsafePokeSkip
218+
219+ -- ** Deserialization using Unbox
220+ , peekUncons
221+ , peekUnconsUnsafe -- unsafePeekUncons
222+ , peekSkipUnsafe -- unsafePeekSkip
223+
224+ -- Arrays of arrays
225+ -- We can add dimensionality parameter to the array type to get
226+ -- multidimensional arrays. Multidimensional arrays would just be a
227+ -- convenience wrapper on top of single dimensional arrays.
228+
229+ -- ** Streams of Arrays
230+ -- *** Chunk
231+ -- | Group a stream into arrays.
232+ , chunksOf
233+ , pinnedChunksOf
234+ , buildChunks
235+
236+ -- *** Split
237+ -- | Split an array into slices.
238+
239+ -- , getSlicesFromLenN
240+ , splitOn
241+ -- , slicesOf
242+
243+ -- *** Concat
244+ -- | Append the arrays in a stream to form a stream of elements.
245+ , concatWith
246+ , concatRevWith
247+ , concat
248+ , concatRev
249+
250+ -- *** Compact
251+ -- | Append the arrays in a stream to form a stream of larger arrays.
252+ , SpliceState (..)
253+ , pCompactLE
254+ , pPinnedCompactLE
255+ , compactLeAs
256+ , fCompactGE
257+ , fPinnedCompactGE
258+ , lCompactGE
259+ , lPinnedCompactGE
260+ , compactGE
261+ , compactEQ
262+
263+ -- ** Utilities
222264 , roundUpToPower2
223265 , memcpy
224266 , memcmp
225267 , c_memchr
268+
269+ -- * Deprecated
270+ , asPtrUnsafe
271+ , writeChunks
272+ , flattenArrays
273+ , flattenArraysRev
274+ , fromArrayStreamK
275+ , fromStreamDN
276+ , fromStreamD
277+ , cmp
278+ , getIndices
279+ , getIndicesWith
280+ , resize
281+ , resizeExp
282+ , nil
283+ , new
284+ , pinnedNew
285+ , pinnedNewBytes
286+ , writeAppendNUnsafe
287+ , writeAppendN
288+ , writeAppendWith
289+ , writeAppend
290+ , writeNWithUnsafe
291+ , writeNWith
292+ , writeNUnsafe
293+ , pinnedWriteNUnsafe
294+ , writeN
295+ , pinnedWriteN
296+ , pinnedWriteNAligned -- XXX not required
297+ , writeWith
298+ , write
299+ , pinnedWrite
300+ , writeRevN
226301 )
227302where
228303
@@ -233,49 +308,52 @@ where
233308
234309import Control.Monad (when, void)
235310import Control.Monad.IO.Class (MonadIO(..))
311+import Data.Bifunctor (first)
236312import Data.Bits (shiftR, (.|.), (.&.))
237313import Data.Functor.Identity (Identity(..))
238314import Data.Proxy (Proxy(..))
239315import Data.Word (Word8)
240316import Foreign.C.Types (CSize(..), CInt(..))
241317import Foreign.Ptr (plusPtr, minusPtr, nullPtr)
242−import Streamly.Internal.Data.Unbox
243− ( MutableByteArray(..)
244− , Unbox(..)
318+import Streamly.Internal.Data.MutByteArray.Type
319+ ( MutByteArray(..)
245320 , PinnedState(..)
246321 , getMutableByteArray#
247− , touch
248322 , putSliceUnsafe
249323 )
324+import Streamly.Internal.Data.Unbox (Unbox(..))
250325import GHC.Base
251326 ( IO(..)
252327 , Int(..)
253− , byteArrayContents#
254328 , compareByteArrays#
255329 , copyMutableByteArray#
256330 )
257331import GHC.Base (noinline)
258−import GHC.Exts (unsafeCoerce#)
332+import GHC.Exts (unsafeCoerce#, Addr#)
259333import GHC.Ptr (Ptr(..))
260334
261335import Streamly.Internal.Data.Fold.Type (Fold(..))
262336import Streamly.Internal.Data.Producer.Type (Producer (..))
263337import Streamly.Internal.Data.Stream.Type (Stream)
338+import Streamly.Internal.Data.Parser.Type (Parser (..))
264339import Streamly.Internal.Data.StreamK.Type (StreamK)
265340import Streamly.Internal.Data.SVar.Type (adaptState, defState)
341+import Streamly.Internal.Data.Tuple.Strict (Tuple'(..))
266342import Streamly.Internal.Data.Unfold.Type (Unfold(..))
267343import Streamly.Internal.System.IO (arrayPayloadSize, defaultChunkSize)
268344
269345import qualified Streamly.Internal.Data.Fold.Type as FL
346+import qualified Streamly.Internal.Data.MutByteArray.Type as Unboxed
347+import qualified Streamly.Internal.Data.Parser.Type as Parser
348+-- import qualified Streamly.Internal.Data.Fold.Type as Fold
270349import qualified Streamly.Internal.Data.Producer as Producer
271350import qualified Streamly.Internal.Data.Stream.Type as D
272351import qualified Streamly.Internal.Data.Stream.Lift as D
273352import qualified Streamly.Internal.Data.StreamK.Type as K
274−import qualified Streamly.Internal.Data.Unbox as Unboxed
275353import qualified Prelude
276354
277355import Prelude hiding
278− (Foldable(..), read, unlines, splitAt, reverse, truncate)
356+ (Foldable(..), concat, read, unlines, splitAt, reverse, truncate)
279357
280358#include "DocTestDataMutArray.hs"
281359
@@ -283,6 +361,7 @@ import Prelude hiding
283361-- Foreign helpers
284362-------------------------------------------------------------------------------
285363
364+-- NOTE: Have to be "ccall unsafe" so that we can pass unpinned memory to these
286365foreign import ccall unsafe "string.h memcpy" c_memcpy
287366 :: Ptr Word8 -> Ptr Word8 -> CSize -> IO (Ptr Word8)
288367
@@ -292,6 +371,9 @@ foreign import ccall unsafe "string.h memchr" c_memchr
292371foreign import ccall unsafe "string.h memcmp" c_memcmp
293372 :: Ptr Word8 -> Ptr Word8 -> CSize -> IO CInt
294373
374+foreign import ccall unsafe "string.h strlen" c_strlen
375+ :: Ptr Word8 -> IO CSize
376+
295377-- | Given an 'Unboxed' type (unused first arg) and a number of bytes, return
296378-- how many elements of that type will completely fit in those bytes.
297379--
@@ -346,7 +428,7 @@ data MutArray a =
346428 -- The array is a range into arrContents. arrContents may be a superset of
347429 -- the slice represented by the array. All offsets are in bytes.
348430 MutArray
349− { arrContents :: {-# UNPACK #-} !MutableByteArray
431+ { arrContents :: {-# UNPACK #-} !MutByteArray
350432 , arrStart :: {-# UNPACK #-} !Int -- ^ index into arrContents
351433 , arrEnd :: {-# UNPACK #-} !Int -- ^ index into arrContents
352434 -- Represents the first invalid index of
@@ -358,22 +440,25 @@ data MutArray a =
358440-- Pinning & Unpinning
359441-------------------------------------------------------------------------------
360442
361−-- | Copy the 'MutArray' to pinned memory if unpinned, else do nothing. The
362−-- overhead is a copy if the input array is unpinned.
443+-- | Return a copy of the array in pinned memory if unpinned, else return the
444+-- original array.
363445{-# INLINE pin #-}
364446pin :: MutArray a -> IO (MutArray a)
365−pin arr@MutArray{..} = do
366− contents <- Unboxed.pin arrContents
367− return $ arr {arrContents = contents}
447+pin arr@MutArray{..} =
448+ if Unboxed.isPinned arrContents
449+ then pure arr
450+ else pinnedClone arr
368451
369−-- | Copy the 'MutArray' to unpinned memory if pinned, else do nothing. The
370−-- overhead is a copy if the input array is pinned.
452+-- | Return a copy of the array in unpinned memory if pinned, else return the
453+-- original array.
371454{-# INLINE unpin #-}
372455unpin :: MutArray a -> IO (MutArray a)
373−unpin arr@MutArray{..} = do
374− contents <- Unboxed.unpin arrContents
375− return $ arr {arrContents = contents}
456+unpin arr@MutArray{..} =
457+ if Unboxed.isPinned arrContents
458+ then clone arr
459+ else pure arr
376460
461+-- | Return 'True' if the array is allocated in pinned memory.
377462{-# INLINE isPinned #-}
378463isPinned :: MutArray a -> Bool
379464isPinned MutArray{..} = Unboxed.isPinned arrContents
@@ -394,6 +479,8 @@ isPinned MutArray{..} = Unboxed.isPinned arrContents
394479-- we need more than that. See stg_pinnedNewAlignedByteArrayzh and
395480-- allocatePinned in GHC source.
396481
482+-- XXX Rename to emptyAlignedWith, alignSize should be first arg.
483+
397484-- | @newArrayWith allocator alignment count@ allocates a new array of zero
398485-- length and with a capacity to hold @count@ elements, using @allocator
399486-- size alignment@ as the memory allocator function.
@@ -406,7 +493,7 @@ isPinned MutArray{..} = Unboxed.isPinned arrContents
406493-- /Pre-release/
407494{-# INLINE newArrayWith #-}
408495newArrayWith :: forall m a. (MonadIO m, Unbox a)
409− => (Int -> Int -> m MutableByteArray) -> Int -> Int -> m (MutArray a)
496+ => (Int -> Int -> m MutByteArray) -> Int -> Int -> m (MutArray a)
410497newArrayWith alloc alignSize count = do
411498 let size = max (count * SIZE_OF(a)) 0
412499 contents <- alloc size alignSize
@@ -417,12 +504,25 @@ newArrayWith alloc alignSize count = do
417504 , arrBound = size
418505 }
419506
507+-- For arrays "nil" sounds a bit odd. empty is better. The only problem with
508+-- empty is that it is also used by the Alternative type class. But assuming we
509+-- will mostly import the Array module qualified this should be fine.
510+
511+-- | Create an empty array.
512+empty ::
513+#ifdef DEVBUILD
514+ Unbox a =>
515+#endif
516+ MutArray a
517+empty = MutArray Unboxed.empty 0 0 0
518+
519+{-# DEPRECATED nil "Please use empty instead." #-}
420520nil ::
421521#ifdef DEVBUILD
422522 Unbox a =>
423523#endif
424524 MutArray a
425−nil = MutArray Unboxed.nil 0 0 0
525+nil = empty
426526
427527{-# INLINE newBytesAs #-}
428528newBytesAs :: MonadIO m =>
@@ -439,12 +539,13 @@ newBytesAs ps bytes = do
439539 , arrBound = bytes
440540 }
441541
442−-- | Allocates a pinned empty array that can hold 'count' items. The memory of
443−-- the array is uninitialized and the allocation is aligned as per the
444−-- 'Unboxed' instance of the type.
542+-- | Allocates a pinned empty array that with a reserved capacity of bytes.
543+-- The memory of the array is uninitialized and the allocation is aligned as
544+-- per the 'Unboxed' instance of the type.
445545--
446546-- /Pre-release/
447547{-# INLINE pinnedNewBytes #-}
548+{-# DEPRECATED pinnedNewBytes "Please use pinnedEmptyOf with appropriate calculation" #-}
448549pinnedNewBytes :: MonadIO m =>
449550#ifdef DEVBUILD
450551 Unbox a =>
@@ -469,21 +570,31 @@ newAs ps =
469570 (error "new: alignment is not used in unpinned arrays.")
470571
471572-- XXX can unaligned allocation be more efficient when alignment is not needed?
472−--
473−-- | Allocates an empty pinned array that can hold 'count' items. The memory of
474−-- the array is uninitialized and the allocation is aligned as per the 'Unboxed'
475−-- instance of the type.
476−--
573+
574+-- | Allocates a pinned array of zero length but growable to the specified
575+-- capacity without reallocation.
576+{-# INLINE pinnedEmptyOf #-}
577+pinnedEmptyOf :: forall m a. (MonadIO m, Unbox a) => Int -> m (MutArray a)
578+pinnedEmptyOf = newAs Pinned
579+
580+-- XXX Deprecate in major
581+-- {-# DEPRECATED pinnedNew "Please use pinnedEmptyOf instead." #-}
477582{-# INLINE pinnedNew #-}
478583pinnedNew :: forall m a. (MonadIO m, Unbox a) => Int -> m (MutArray a)
479−pinnedNew = newAs Pinned
584+pinnedNew = pinnedEmptyOf
480585
481−-- | Allocates an empty unpinned array that can hold 'count' items. The memory
482−-- of the array is uninitialized.
586+-- | Allocates an unpinned array of zero length but growable to the specified
587+-- capacity without reallocation.
483588--
589+{-# INLINE emptyOf #-}
590+emptyOf :: (MonadIO m, Unbox a) => Int -> m (MutArray a)
591+emptyOf = newAs Unpinned
592+
593+-- XXX Deprecate in major
594+-- {-# DEPRECATED new "Please use emptyOf instead." #-}
484595{-# INLINE new #-}
485596new :: (MonadIO m, Unbox a) => Int -> m (MutArray a)
486−new = newAs Unpinned
597+new = emptyOf
487598
488599-------------------------------------------------------------------------------
489600-- Random writes
@@ -499,7 +610,7 @@ putIndexUnsafe :: forall m a. (MonadIO m, Unbox a)
499610putIndexUnsafe i MutArray{..} x = do
500611 let index = INDEX_OF(arrStart, i, a)
501612 assert (i >= 0 && INDEX_VALID(index, arrEnd, a)) (return ())
502− liftIO $ pokeByteIndex index arrContents x
613+ liftIO $ pokeAt index arrContents x
503614
504615invalidIndex :: String -> Int -> a
505616invalidIndex label i =
@@ -517,7 +628,7 @@ putIndex :: forall m a. (MonadIO m, Unbox a) => Int -> MutArray a -> a -> m ()
517628putIndex i MutArray{..} x = do
518629 let index = INDEX_OF(arrStart,i,a)
519630 if i >= 0 && INDEX_VALID(index,arrEnd,a)
520− then liftIO $ pokeByteIndex index arrContents x
631+ then liftIO $ pokeAt index arrContents x
521632 else invalidIndex "putIndex" i
522633
523634-- | Write an input stream of (index, value) pairs to an array. Throws an
@@ -531,7 +642,7 @@ putIndices arr = FL.foldlM' step (return ())
531642
532643 where
533644
534− step () (i, x) = liftIO (putIndex i arr x)
645+ step () (i, x) = putIndex i arr x
535646
536647-- | Modify a given index of an array using a modifier function.
537648--
@@ -543,9 +654,9 @@ modifyIndexUnsafe :: forall m a b. (MonadIO m, Unbox a) =>
543654modifyIndexUnsafe i MutArray{..} f = liftIO $ do
544655 let index = INDEX_OF(arrStart,i,a)
545656 assert (i >= 0 && INDEX_NEXT(index,a) <= arrEnd) (return ())
546− r <- peekByteIndex index arrContents
657+ r <- peekAt index arrContents
547658 let (x, res) = f r
548− pokeByteIndex index arrContents x
659+ pokeAt index arrContents x
549660 return res
550661
551662-- | Modify a given index of an array using a modifier function.
@@ -557,9 +668,9 @@ modifyIndex i MutArray{..} f = do
557668 let index = INDEX_OF(arrStart,i,a)
558669 if i >= 0 && INDEX_VALID(index,arrEnd,a)
559670 then liftIO $ do
560− r <- peekByteIndex index arrContents
671+ r <- peekAt index arrContents
561672 let (x, res) = f r
562− pokeByteIndex index arrContents x
673+ pokeAt index arrContents x
563674 return res
564675 else invalidIndex "modifyIndex" i
565676
@@ -593,8 +704,8 @@ modify MutArray{..} f = liftIO $
593704
594705 go i =
595706 when (INDEX_VALID(i,arrEnd,a)) $ do
596− r <- peekByteIndex i arrContents
597− pokeByteIndex i arrContents (f r)
707+ r <- peekAt i arrContents
708+ pokeAt i arrContents (f r)
598709 go (INDEX_NEXT(i,a))
599710
600711-- XXX We could specify the number of bytes to swap instead of Proxy. Need
@@ -603,15 +714,15 @@ modify MutArray{..} f = liftIO $
603714swapArrayByteIndices ::
604715 forall a. Unbox a
605716 => Proxy a
606− -> MutableByteArray
717+ -> MutByteArray
607718 -> Int
608719 -> Int
609720 -> IO ()
610721swapArrayByteIndices _ arrContents i1 i2 = do
611− r1 <- peekByteIndex i1 arrContents
612− r2 <- peekByteIndex i2 arrContents
613− pokeByteIndex i1 arrContents (r2 :: a)
614− pokeByteIndex i2 arrContents (r1 :: a)
722+ r1 <- peekAt i1 arrContents
723+ r2 <- peekAt i2 arrContents
724+ pokeAt i1 arrContents (r2 :: a)
725+ pokeAt i2 arrContents (r1 :: a)
615726
616727-- | Swap the elements at two indices without validating the indices.
617728--
@@ -727,26 +838,23 @@ arrayChunkBytes = 1024
727838roundDownTo :: Int -> Int -> Int
728839roundDownTo elemSize size = size - (size `mod` elemSize)
729840
730−-- XXX See if resizing can be implemented by reading the old array as a stream
731−-- and then using writeN to the new array.
732−--
733841-- NOTE: we are passing elemSize explicitly to avoid an Unboxed constraint.
734842-- Since this is not inlined Unboxed consrraint leads to dictionary passing
735843-- which complicates some inspection tests.
736844--
737−{-# NOINLINE reallocExplicit #-}
738−reallocExplicit :: Int -> Int -> MutArray a -> IO (MutArray a)
739−reallocExplicit elemSize newCapacityInBytes MutArray{..} = do
845+{-# NOINLINE reallocExplicitAs #-}
846+reallocExplicitAs :: PinnedState -> Int -> Int -> MutArray a -> IO (MutArray a)
847+reallocExplicitAs ps elemSize newCapacityInBytes MutArray{..} = do
740848 assertM(arrEnd <= arrBound)
741849
742850 -- Allocate new array
743851 let newCapMaxInBytes = roundUpLargeArray newCapacityInBytes
744852 contents <-
745− if Unboxed.isPinned arrContents
746− then Unboxed.pinnedNewBytes newCapMaxInBytes
747− else Unboxed.newBytes newCapMaxInBytes
748− let !(MutableByteArray mbarrFrom#) = arrContents
749− !(MutableByteArray mbarrTo#) = contents
853+ if ps == Pinned
854+ then Unboxed.pinnedNew newCapMaxInBytes
855+ else Unboxed.new newCapMaxInBytes
856+ let !(MutByteArray mbarrFrom#) = arrContents
857+ !(MutByteArray mbarrTo#) = contents
750858
751859 -- Copy old data
752860 let oldStart = arrStart
@@ -767,6 +875,10 @@ reallocExplicit elemSize newCapacityInBytes MutArray{..} = do
767875 , arrBound = newCapInBytes
768876 }
769877
878+-- XXX Should these be called reallocBytes etc?
879+-- XXX We may also need reallocAs to allocate as pinned/unpinned explicitly. In
880+-- fact clone/pinnedClone can be implemented using reallocAs.
881+
770882-- | @realloc newCapacity array@ reallocates the array to the specified
771883-- capacity in bytes.
772884--
@@ -778,7 +890,12 @@ reallocExplicit elemSize newCapacityInBytes MutArray{..} = do
778890-- If the original array is pinned, the newly allocated array is also pinned.
779891{-# INLINABLE realloc #-}
780892realloc :: forall m a. (MonadIO m, Unbox a) => Int -> MutArray a -> m (MutArray a)
781−realloc bytes arr = liftIO $ reallocExplicit (SIZE_OF(a)) bytes arr
893+realloc bytes arr =
894+ let ps =
895+ if isPinned arr
896+ then Pinned
897+ else Unpinned
898+ in liftIO $ reallocExplicitAs ps (SIZE_OF(a)) bytes arr
782899
783900-- | @reallocWith label capSizer minIncrBytes array@. The label is used
784901-- in error messages and the capSizer is used to determine the capacity of the
@@ -801,14 +918,14 @@ reallocWith label capSizer minIncrBytes arr = do
801918 where
802919
803920 badSize newSize =
804− concat
921+ Prelude.concat
805922 [ label
806923 , ": new array size (in bytes) is less than required size "
807924 , show newSize
808925 , ". Please check the sizing function passed."
809926 ]
810927
811−-- | @resize newCapacity array@ changes the total capacity of the array so that
928+-- | @grow newCapacity array@ changes the total capacity of the array so that
812929-- it is enough to hold the specified number of elements. Nothing is done if
813930-- the specified capacity is less than the length of the array.
814931--
@@ -816,34 +933,46 @@ reallocWith label capSizer minIncrBytes arr = do
816933-- the block size (4K).
817934--
818935-- /Pre-release/
819−{-# INLINE resize #-}
820−resize :: forall m a. (MonadIO m, Unbox a) =>
936+{-# INLINE grow #-}
937+grow :: forall m a. (MonadIO m, Unbox a) =>
821938 Int -> MutArray a -> m (MutArray a)
822−resize nElems arr@MutArray{..} = do
939+grow nElems arr@MutArray{..} = do
823940 let req = SIZE_OF(a) * nElems
824− len = arrEnd - arrStart
825− if req < len
941+ cap = arrBound - arrStart
942+ if req < cap
826943 then return arr
827944 else realloc req arr
828945
829−-- | Like 'resize' but if the byte capacity is more than 'largeObjectThreshold'
830−-- then it is rounded up to the closest power of 2.
946+{-# DEPRECATED resize "Please use grow instead." #-}
947+{-# INLINE resize #-}
948+resize :: forall m a. (MonadIO m, Unbox a) =>
949+ Int -> MutArray a -> m (MutArray a)
950+resize = grow
951+
952+-- | Like 'grow' but if the requested byte capacity is more than
953+-- 'largeObjectThreshold' then it is rounded up to the closest power of 2.
831954--
832955-- /Pre-release/
833−{-# INLINE resizeExp #-}
834−resizeExp :: forall m a. (MonadIO m, Unbox a) =>
956+{-# INLINE growExp #-}
957+growExp :: forall m a. (MonadIO m, Unbox a) =>
835958 Int -> MutArray a -> m (MutArray a)
836−resizeExp nElems arr@MutArray{..} = do
959+growExp nElems arr@MutArray{..} = do
837960 let req = roundUpLargeArray (SIZE_OF(a) * nElems)
838961 req1 =
839962 if req > largeObjectThreshold
840963 then roundUpToPower2 req
841964 else req
842− len = arrEnd - arrStart
843− if req1 < len
965+ cap = arrBound - arrStart
966+ if req1 < cap
844967 then return arr
845968 else realloc req1 arr
846969
970+{-# DEPRECATED resizeExp "Please use growExp instead." #-}
971+{-# INLINE resizeExp #-}
972+resizeExp :: forall m a. (MonadIO m, Unbox a) =>
973+ Int -> MutArray a -> m (MutArray a)
974+resizeExp = growExp
975+
847976-- | Resize the allocated memory to drop any reserved free space at the end of
848977-- the array and reallocate it to reduce wastage.
849978--
@@ -888,7 +1017,7 @@ rightSize arr@MutArray{..} = do
8881017snocNewEnd :: (MonadIO m, Unbox a) => Int -> MutArray a -> a -> m (MutArray a)
8891018snocNewEnd newEnd arr@MutArray{..} x = liftIO $ do
8901019 assert (newEnd <= arrBound) (return ())
891− pokeByteIndex arrEnd arrContents x
1020+ pokeAt arrEnd arrContents x
8921021 return $ arr {arrEnd = newEnd}
8931022
8941023-- | Really really unsafe, appends the element into the first array, may
@@ -908,7 +1037,7 @@ snocUnsafe arr@MutArray{..} = snocNewEnd (INDEX_NEXT(arrEnd,a)) arr
9081037{-# INLINE snocMay #-}
9091038snocMay :: forall m a. (MonadIO m, Unbox a) =>
9101039 MutArray a -> a -> m (Maybe (MutArray a))
911−snocMay arr@MutArray{..} x = liftIO $ do
1040+snocMay arr@MutArray{..} x = do
9121041 let newEnd = INDEX_NEXT(arrEnd,a)
9131042 if newEnd <= arrBound
9141043 then Just <$> snocNewEnd newEnd arr x
@@ -922,7 +1051,7 @@ snocWithRealloc :: forall m a. (MonadIO m, Unbox a) =>
9221051 -> a
9231052 -> m (MutArray a)
9241053snocWithRealloc sizer arr x = do
925− arr1 <- liftIO $ reallocWith "snocWith" sizer (SIZE_OF(a)) arr
1054+ arr1 <- reallocWith "snocWith" sizer (SIZE_OF(a)) arr
9261055 snocUnsafe arr1 x
9271056
9281057-- | @snocWith sizer arr elem@ mutates @arr@ to append @elem@. The length of
@@ -944,7 +1073,7 @@ snocWith :: forall m a. (MonadIO m, Unbox a) =>
9441073 -> MutArray a
9451074 -> a
9461075 -> m (MutArray a)
947−snocWith allocSize arr x = liftIO $ do
1076+snocWith allocSize arr x = do
9481077 let newEnd = INDEX_NEXT(arrEnd arr,a)
9491078 if newEnd <= arrBound arr
9501079 then snocNewEnd newEnd arr x
@@ -988,6 +1117,126 @@ snoc = snocWith f
9881117 then oldSize * 2
9891118 else roundUpToPower2 oldSize * 2
9901119
1120+-------------------------------------------------------------------------------
1121+-- Serialization/Deserialization
1122+-------------------------------------------------------------------------------
1123+
1124+{-# INLINE pokeNewEnd #-}
1125+pokeNewEnd :: (MonadIO m, Unbox a) =>
1126+ Int -> MutArray Word8 -> a -> m (MutArray Word8)
1127+pokeNewEnd newEnd arr@MutArray{..} x = liftIO $ do
1128+ assert (newEnd <= arrBound) (return ())
1129+ liftIO $ pokeAt arrEnd arrContents x
1130+ return $ arr {arrEnd = newEnd}
1131+
1132+-- | Really really unsafe, unboxes a Haskell type and appends the resulting
1133+-- bytes to the byte array, may cause silent data corruption or if you are
1134+-- lucky a segfault if the array does not have enough space to append the
1135+-- element.
1136+--
1137+-- /Internal/
1138+{-# INLINE pokeAppendUnsafe #-}
1139+pokeAppendUnsafe :: forall m a. (MonadIO m, Unbox a) =>
1140+ MutArray Word8 -> a -> m (MutArray Word8)
1141+pokeAppendUnsafe arr@MutArray{..} = pokeNewEnd (arrEnd + SIZE_OF(a)) arr
1142+
1143+-- | Skip the specified number of bytes in the array. The data in the skipped
1144+-- region remains uninitialzed.
1145+{-# INLINE pokeSkipUnsafe #-}
1146+pokeSkipUnsafe :: Int -> MutArray Word8 -> MutArray Word8
1147+pokeSkipUnsafe n arr@MutArray{..} = do
1148+ let newEnd = arrEnd + n
1149+ in assert (newEnd <= arrBound) (arr {arrEnd = newEnd})
1150+
1151+-- | Like 'pokeAppend' but does not grow the array when pre-allocated array
1152+-- capacity becomes full.
1153+--
1154+-- /Internal/
1155+{-# INLINE pokeAppendMay #-}
1156+pokeAppendMay :: forall m a. (MonadIO m, Unbox a) =>
1157+ MutArray Word8 -> a -> m (Maybe (MutArray Word8))
1158+pokeAppendMay arr@MutArray{..} x = liftIO $ do
1159+ let newEnd = arrEnd + SIZE_OF(a)
1160+ if newEnd <= arrBound
1161+ then Just <$> pokeNewEnd newEnd arr x
1162+ else return Nothing
1163+
1164+{-# NOINLINE pokeWithRealloc #-}
1165+pokeWithRealloc :: forall m a. (MonadIO m, Unbox a) =>
1166+ (Int -> Int)
1167+ -> MutArray Word8
1168+ -> a
1169+ -> m (MutArray Word8)
1170+pokeWithRealloc sizer arr x = do
1171+ arr1 <- liftIO $ reallocWith "pokeWithRealloc" sizer (SIZE_OF(a)) arr
1172+ pokeAppendUnsafe arr1 x
1173+
1174+{-# INLINE pokeAppendWith #-}
1175+pokeAppendWith :: forall m a. (MonadIO m, Unbox a) =>
1176+ (Int -> Int)
1177+ -> MutArray Word8
1178+ -> a
1179+ -> m (MutArray Word8)
1180+pokeAppendWith allocSize arr x = liftIO $ do
1181+ let newEnd = arrEnd arr + SIZE_OF(a)
1182+ if newEnd <= arrBound arr
1183+ then pokeNewEnd newEnd arr x
1184+ else pokeWithRealloc allocSize arr x
1185+
1186+-- | Unbox a Haskell type and append the resulting bytes to a mutable byte
1187+-- array. The array is grown exponentially when more space is needed.
1188+--
1189+-- Definition:
1190+--
1191+-- >>> pokeAppend arr x = MutArray.castUnsafe <$> MutArray.snoc (MutArray.castUnsafe arr) x
1192+--
1193+{-# INLINE pokeAppend #-}
1194+pokeAppend :: forall m a. (MonadIO m, Unbox a) =>
1195+ MutArray Word8 -> a -> m (MutArray Word8)
1196+pokeAppend = pokeAppendWith f
1197+
1198+ where
1199+
1200+ f oldSize =
1201+ if isPower2 oldSize
1202+ then oldSize * 2
1203+ else roundUpToPower2 oldSize * 2
1204+
1205+-- | Really really unsafe, create a Haskell value from an unboxed byte array,
1206+-- does not check if the array is big enough, may return garbage or if you are
1207+-- lucky may cause a segfault.
1208+--
1209+-- /Internal/
1210+{-# INLINE peekUnconsUnsafe #-}
1211+peekUnconsUnsafe :: forall m a. (MonadIO m, Unbox a) =>
1212+ MutArray Word8 -> m (a, MutArray Word8)
1213+peekUnconsUnsafe MutArray{..} = do
1214+ let start1 = arrStart + SIZE_OF(a)
1215+ assert (start1 <= arrEnd) (return ())
1216+ liftIO $ do
1217+ r <- peekAt arrStart arrContents
1218+ return (r, MutArray arrContents start1 arrEnd arrBound)
1219+
1220+-- | Discard the specified number of bytes in the array.
1221+{-# INLINE peekSkipUnsafe #-}
1222+peekSkipUnsafe :: Int -> MutArray Word8 -> MutArray Word8
1223+peekSkipUnsafe n MutArray{..} =
1224+ let start1 = arrStart + n
1225+ in assert (start1 <= arrEnd) (MutArray arrContents start1 arrEnd arrBound)
1226+
1227+-- | Create a Haskell value from its unboxed representation from the head of a
1228+-- byte array, return the value and the remaining array.
1229+{-# INLINE peekUncons #-}
1230+peekUncons :: forall m a. (MonadIO m, Unbox a) =>
1231+ MutArray Word8 -> m (Maybe a, MutArray Word8)
1232+peekUncons arr@MutArray{..} = do
1233+ let start1 = arrStart + SIZE_OF(a)
1234+ if start1 > arrEnd
1235+ then return (Nothing, arr)
1236+ else liftIO $ do
1237+ r <- peekAt arrStart arrContents
1238+ return (Just r, MutArray arrContents start1 arrEnd arrBound)
1239+
9911240-------------------------------------------------------------------------------
9921241-- Random reads
9931242-------------------------------------------------------------------------------
@@ -1002,7 +1251,7 @@ getIndexUnsafe :: forall m a. (MonadIO m, Unbox a) => Int -> MutArray a -> m a
10021251getIndexUnsafe i MutArray{..} = do
10031252 let index = INDEX_OF(arrStart,i,a)
10041253 assert (i >= 0 && INDEX_VALID(index,arrEnd,a)) (return ())
1005− liftIO $ peekByteIndex index arrContents
1254+ liftIO $ peekAt index arrContents
10061255
10071256-- | /O(1)/ Lookup the element at the given index. Index starts from 0.
10081257--
@@ -1011,7 +1260,7 @@ getIndex :: forall m a. (MonadIO m, Unbox a) => Int -> MutArray a -> m (Maybe a)
10111260getIndex i MutArray{..} = do
10121261 let index = INDEX_OF(arrStart,i,a)
10131262 if i >= 0 && INDEX_VALID(index,arrEnd,a)
1014− then liftIO $ Just <$> peekByteIndex index arrContents
1263+ then liftIO $ Just <$> peekAt index arrContents
10151264 else return Nothing
10161265
10171266-- | /O(1)/ Lookup the element at the given index from the end of the array.
@@ -1024,21 +1273,16 @@ getIndexRev :: forall m a. (MonadIO m, Unbox a) => Int -> MutArray a -> m a
10241273getIndexRev i MutArray{..} = do
10251274 let index = RINDEX_OF(arrEnd,i,a)
10261275 if i >= 0 && index >= arrStart
1027− then liftIO $ peekByteIndex index arrContents
1276+ then liftIO $ peekAt index arrContents
10281277 else invalidIndex "getIndexRev" i
10291278
10301279data GetIndicesState contents start end st =
10311280 GetIndicesState contents start end st
10321281
1033−-- | Given an unfold that generates array indices, read the elements on those
1034−-- indices from the supplied MutArray. An error is thrown if an index is out of
1035−-- bounds.
1036−--
1037−-- /Pre-release/
1038−{-# INLINE getIndicesD #-}
1039−getIndicesD :: (Monad m, Unbox a) =>
1282+{-# INLINE indexReaderWith #-}
1283+indexReaderWith :: (Monad m, Unbox a) =>
10401284 (forall b. IO b -> m b) -> D.Stream m Int -> Unfold m (MutArray a) a
1041−getIndicesD liftio (D.Stream stepi sti) = Unfold step inject
1285+indexReaderWith liftio (D.Stream stepi sti) = Unfold step inject
10421286
10431287 where
10441288
@@ -1057,9 +1301,26 @@ getIndicesD liftio (D.Stream stepi sti) = Unfold step inject
10571301 D.Skip s -> return $ D.Skip (GetIndicesState contents start end s)
10581302 D.Stop -> return D.Stop
10591303
1304+{-# DEPRECATED getIndicesWith "Please use indexReaderWith instead." #-}
1305+{-# INLINE getIndicesWith #-}
1306+getIndicesWith :: (Monad m, Unbox a) =>
1307+ (forall b. IO b -> m b) -> D.Stream m Int -> Unfold m (MutArray a) a
1308+getIndicesWith = indexReaderWith
1309+
1310+-- | Given an unfold that generates array indices, read the elements on those
1311+-- indices from the supplied MutArray. An error is thrown if an index is out of
1312+-- bounds.
1313+--
1314+-- /Pre-release/
1315+{-# INLINE indexReader #-}
1316+indexReader :: (MonadIO m, Unbox a) => Stream m Int -> Unfold m (MutArray a) a
1317+indexReader = indexReaderWith liftIO
1318+
1319+-- XXX DO NOT REMOVE, change the signature to use Stream instead of unfold
1320+{-# DEPRECATED getIndices "Please use indexReader instead." #-}
10601321{-# INLINE getIndices #-}
10611322getIndices :: (MonadIO m, Unbox a) => Stream m Int -> Unfold m (MutArray a) a
1062−getIndices = getIndicesD liftIO
1323+getIndices = indexReader
10631324
10641325-------------------------------------------------------------------------------
10651326-- Subarrays
@@ -1164,7 +1425,7 @@ partitionBy f arr@MutArray{..} = liftIO $ do
11641425
11651426 -- Invariant low < high on entry, and on return as well
11661427 moveHigh low high = do
1167− h <- peekByteIndex high arrContents
1428+ h <- peekAt high arrContents
11681429 if f h
11691430 then
11701431 -- Correctly classified, continue the loop
@@ -1184,7 +1445,7 @@ partitionBy f arr@MutArray{..} = liftIO $ do
11841445 -- low <= high
11851446 -- Both low and high are valid locations within the array
11861447 go low high = do
1187− l <- peekByteIndex low arrContents
1448+ l <- peekAt low arrContents
11881449 if f l
11891450 then
11901451 -- low is wrongly classified
@@ -1195,8 +1456,8 @@ partitionBy f arr@MutArray{..} = liftIO $ do
11951456 case r of
11961457 Nothing -> return low
11971458 Just (high1, h) -> do -- low < high1
1198− pokeByteIndex low arrContents h
1199− pokeByteIndex high1 arrContents l
1459+ pokeAt low arrContents h
1460+ pokeAt high1 arrContents l
12001461 let low1 = INDEX_NEXT(low,a)
12011462 high2 = INDEX_PREV(high1,a)
12021463 if low1 <= high2
@@ -1330,7 +1591,7 @@ chunksOfAs ps n (D.Stream step state) =
13301591 r <- step (adaptState gst) st
13311592 case r of
13321593 D.Yield x s -> do
1333− liftIO $ pokeByteIndex end contents x
1594+ liftIO $ pokeAt end contents x
13341595 let end1 = INDEX_NEXT(end,a)
13351596 return $
13361597 if end1 >= bound
@@ -1349,10 +1610,12 @@ chunksOfAs ps n (D.Stream step state) =
13491610
13501611 step' _ GroupFinish = return D.Stop
13511612
1352−-- | @chunksOf n stream@ groups the input stream into a stream of
1353−-- arrays of size n.
1613+-- | @chunksOf n stream@ groups the elements in the input stream into arrays of
1614+-- @n@ elements each.
1615+--
1616+-- Same as the following but may be more efficient:
13541617--
1355−-- @chunksOf n = StreamD.foldMany (MutArray.writeN n)@
1618+-- >>> chunksOf n = Stream.foldMany (MutArray.createOf n)
13561619--
13571620-- /Pre-release/
13581621{-# INLINE_NORMAL chunksOf #-}
@@ -1361,17 +1624,29 @@ chunksOf :: forall m a. (MonadIO m, Unbox a)
13611624-- XXX the idiomatic implementation leads to large regression in the D.reverse'
13621625-- benchmark. It seems it has difficulty producing optimized code when
13631626-- converting to StreamK. Investigate GHC optimizations.
1364−-- chunksOf n = D.foldMany (writeN n)
1627+-- chunksOf n = D.foldMany (createOf n)
13651628chunksOf = chunksOfAs Unpinned
13661629
13671630-- | Like 'chunksOf' but creates pinned arrays.
13681631{-# INLINE_NORMAL pinnedChunksOf #-}
13691632pinnedChunksOf :: forall m a. (MonadIO m, Unbox a)
13701633 => Int -> D.Stream m a -> D.Stream m (MutArray a)
1371−-- pinnedChunksOf n = D.foldMany (pinnedWriteN n)
1634+-- pinnedChunksOf n = D.foldMany (pinnedCreateOf n)
13721635pinnedChunksOf = chunksOfAs Pinned
13731636
1374−-- XXX This should take a PinnedState
1637+-- | When we are buffering a stream of unknown size into an array we do not
1638+-- know how much space to pre-allocate. So we start with the min size and emit
1639+-- the array then keep on doubling the size every time. Thus we do not need to
1640+-- guess the optimum chunk size.
1641+--
1642+-- We can incorporate this in chunksOfAs if the additional size parameter does
1643+-- not impact perf.
1644+--
1645+{-# INLINE _chunksOfRange #-}
1646+_chunksOfRange :: -- (MonadIO m, Unbox a) =>
1647+ PinnedState -> Int -> Int -> D.Stream m a -> D.Stream m (MutArray a)
1648+_chunksOfRange _ps _low _hi = undefined
1649+
13751650-- XXX buffer to a list instead?
13761651-- | Buffer the stream into arrays in memory.
13771652{-# INLINE arrayStreamKFromStreamDAs #-}
@@ -1389,16 +1664,10 @@ data FlattenState s contents a =
13891664 OuterLoop s
13901665 | InnerLoop s contents !Int !Int
13911666
1392−-- | Use the "reader" unfold instead.
1393−--
1394−-- @flattenArrays = unfoldMany reader@
1395−--
1396−-- We can try this if there are any fusion issues in the unfold.
1397−--
1398−{-# INLINE_NORMAL flattenArrays #-}
1399−flattenArrays :: forall m a. (MonadIO m, Unbox a)
1400− => D.Stream m (MutArray a) -> D.Stream m a
1401−flattenArrays (D.Stream step state) = D.Stream step' (OuterLoop state)
1667+{-# INLINE_NORMAL concatWith #-}
1668+concatWith :: forall m a. (Monad m, Unbox a)
1669+ => (forall b. IO b -> m b) -> D.Stream m (MutArray a) -> D.Stream m a
1670+concatWith liftio (D.Stream step state) = D.Stream step' (OuterLoop state)
14021671
14031672 where
14041673
@@ -1415,19 +1684,30 @@ flattenArrays (D.Stream step state) = D.Stream step' (OuterLoop state)
14151684 return $ D.Skip $ OuterLoop st
14161685
14171686 step' _ (InnerLoop st contents p end) = do
1418− x <- liftIO $ peekByteIndex p contents
1687+ x <- liftio $ peekAt p contents
14191688 return $ D.Yield x (InnerLoop st contents (INDEX_NEXT(p,a)) end)
14201689
1421−-- | Use the "readerRev" unfold instead.
1690+-- | Use the "reader" unfold instead.
14221691--
1423−-- @flattenArrays = unfoldMany readerRev@
1692+-- @concat = unfoldMany reader@
14241693--
14251694-- We can try this if there are any fusion issues in the unfold.
14261695--
1427−{-# INLINE_NORMAL flattenArraysRev #-}
1428−flattenArraysRev :: forall m a. (MonadIO m, Unbox a)
1696+{-# INLINE_NORMAL concat #-}
1697+concat :: forall m a. (MonadIO m, Unbox a)
14291698 => D.Stream m (MutArray a) -> D.Stream m a
1430−flattenArraysRev (D.Stream step state) = D.Stream step' (OuterLoop state)
1699+concat = concatWith liftIO
1700+
1701+{-# DEPRECATED flattenArrays "Please use \"unfoldMany reader\" instead." #-}
1702+{-# INLINE flattenArrays #-}
1703+flattenArrays :: forall m a. (MonadIO m, Unbox a)
1704+ => D.Stream m (MutArray a) -> D.Stream m a
1705+flattenArrays = concat
1706+
1707+{-# INLINE_NORMAL concatRevWith #-}
1708+concatRevWith :: forall m a. (Monad m, Unbox a)
1709+ => (forall b. IO b -> m b) -> D.Stream m (MutArray a) -> D.Stream m a
1710+concatRevWith liftio (D.Stream step state) = D.Stream step' (OuterLoop state)
14311711
14321712 where
14331713
@@ -1445,16 +1725,33 @@ flattenArraysRev (D.Stream step state) = D.Stream step' (OuterLoop state)
14451725 return $ D.Skip $ OuterLoop st
14461726
14471727 step' _ (InnerLoop st contents p start) = do
1448− x <- liftIO $ peekByteIndex p contents
1728+ x <- liftio $ peekAt p contents
14491729 let cur = INDEX_PREV(p,a)
14501730 return $ D.Yield x (InnerLoop st contents cur start)
14511731
1732+-- | Use the "readerRev" unfold instead.
1733+--
1734+-- @concat = unfoldMany readerRev@
1735+--
1736+-- We can try this if there are any fusion issues in the unfold.
1737+--
1738+{-# INLINE_NORMAL concatRev #-}
1739+concatRev :: forall m a. (MonadIO m, Unbox a)
1740+ => D.Stream m (MutArray a) -> D.Stream m a
1741+concatRev = concatRevWith liftIO
1742+
1743+{-# DEPRECATED flattenArraysRev "Please use \"unfoldMany readerRev\" instead." #-}
1744+{-# INLINE flattenArraysRev #-}
1745+flattenArraysRev :: forall m a. (MonadIO m, Unbox a)
1746+ => D.Stream m (MutArray a) -> D.Stream m a
1747+flattenArraysRev = concatRev
1748+
14521749-------------------------------------------------------------------------------
14531750-- Unfolds
14541751-------------------------------------------------------------------------------
14551752
14561753data ArrayUnsafe a = ArrayUnsafe
1457− {-# UNPACK #-} !MutableByteArray -- contents
1754+ {-# UNPACK #-} !MutByteArray -- contents
14581755 {-# UNPACK #-} !Int -- index 1
14591756 {-# UNPACK #-} !Int -- index 2
14601757
@@ -1484,7 +1781,7 @@ producerWith liftio = Producer step (return . toArrayUnsafe) extract
14841781 -- few actions for correctness and execution order sanity. We want
14851782 -- the peek to occur right here and not lazily at some later point
14861783 -- because we want the peek to be ordered with respect to the touch.
1487− !x <- liftio $ peekByteIndex cur contents
1784+ !x <- liftio $ peekAt cur contents
14881785 return $ D.Yield x (ArrayUnsafe contents (INDEX_NEXT(cur,a)) end)
14891786
14901787 extract = return . fromArrayUnsafe
@@ -1515,7 +1812,7 @@ readerRevWith liftio = Unfold step inject
15151812 {-# INLINE_LATE step #-}
15161813 step (ArrayUnsafe _ start p) | p < start = return D.Stop
15171814 step (ArrayUnsafe contents start p) = do
1518− !x <- liftio $ peekByteIndex p contents
1815+ !x <- liftio $ peekAt p contents
15191816 return $ D.Yield x (ArrayUnsafe contents start (INDEX_PREV(p,a)))
15201817
15211818-- | Unfold an array into a stream in reverse order.
@@ -1546,7 +1843,7 @@ toListFB c n MutArray{..} = go arrStart
15461843 -- evaluated/written to before we peek at them.
15471844 -- XXX
15481845 let !x = unsafeInlineIO $ do
1549− r <- peekByteIndex arrContents p
1846+ r <- peekAt arrContents p
15501847 return r
15511848 in c x (go (PTR_NEXT(p,a)))
15521849-}
@@ -1563,21 +1860,21 @@ toList MutArray{..} = liftIO $ go arrStart
15631860
15641861 go p | assert (p <= arrEnd) (p == arrEnd) = return []
15651862 go p = do
1566− x <- peekByteIndex p arrContents
1863+ x <- peekAt p arrContents
15671864 (:) x <$> go (INDEX_NEXT(p,a))
15681865
1569−{-# INLINE_NORMAL toStreamDWith #-}
1570−toStreamDWith ::
1866+{-# INLINE_NORMAL toStreamWith #-}
1867+toStreamWith ::
15711868 forall m a. (Monad m, Unbox a)
15721869 => (forall b. IO b -> m b) -> MutArray a -> D.Stream m a
1573−toStreamDWith liftio MutArray{..} = D.Stream step arrStart
1870+toStreamWith liftio MutArray{..} = D.Stream step arrStart
15741871
15751872 where
15761873
15771874 {-# INLINE_LATE step #-}
15781875 step _ p | assert (p <= arrEnd) (p == arrEnd) = return D.Stop
15791876 step _ p = liftio $ do
1580− r <- peekByteIndex p arrContents
1877+ r <- peekAt p arrContents
15811878 return $ D.Yield r (INDEX_NEXT(p,a))
15821879
15831880-- | Convert a 'MutArray' into a stream.
@@ -1586,7 +1883,7 @@ toStreamDWith liftio MutArray{..} = D.Stream step arrStart
15861883--
15871884{-# INLINE_NORMAL read #-}
15881885read :: forall m a. (MonadIO m, Unbox a) => MutArray a -> D.Stream m a
1589−read = toStreamDWith liftIO
1886+read = toStreamWith liftIO
15901887
15911888{-# INLINE toStreamKWith #-}
15921889toStreamKWith ::
@@ -1598,18 +1895,18 @@ toStreamKWith liftio MutArray{..} = go arrStart
15981895
15991896 go p | assert (p <= arrEnd) (p == arrEnd) = K.nil
16001897 | otherwise =
1601− let elemM = peekByteIndex p arrContents
1898+ let elemM = peekAt p arrContents
16021899 in liftio elemM `K.consM` go (INDEX_NEXT(p,a))
16031900
16041901{-# INLINE toStreamK #-}
16051902toStreamK :: forall m a. (MonadIO m, Unbox a) => MutArray a -> StreamK m a
16061903toStreamK = toStreamKWith liftIO
16071904
1608−{-# INLINE_NORMAL toStreamDRevWith #-}
1609−toStreamDRevWith ::
1905+{-# INLINE_NORMAL toStreamRevWith #-}
1906+toStreamRevWith ::
16101907 forall m a. (Monad m, Unbox a)
16111908 => (forall b. IO b -> m b) -> MutArray a -> D.Stream m a
1612−toStreamDRevWith liftio MutArray{..} =
1909+toStreamRevWith liftio MutArray{..} =
16131910 let p = INDEX_PREV(arrEnd,a)
16141911 in D.Stream step p
16151912
@@ -1618,7 +1915,7 @@ toStreamDRevWith liftio MutArray{..} =
16181915 {-# INLINE_LATE step #-}
16191916 step _ p | p < arrStart = return D.Stop
16201917 step _ p = liftio $ do
1621− r <- peekByteIndex p arrContents
1918+ r <- peekAt p arrContents
16221919 return $ D.Yield r (INDEX_PREV(p,a))
16231920
16241921-- | Convert a 'MutArray' into a stream in reverse order.
@@ -1627,7 +1924,7 @@ toStreamDRevWith liftio MutArray{..} =
16271924--
16281925{-# INLINE_NORMAL readRev #-}
16291926readRev :: forall m a. (MonadIO m, Unbox a) => MutArray a -> D.Stream m a
1630−readRev = toStreamDRevWith liftIO
1927+readRev = toStreamRevWith liftIO
16311928
16321929{-# INLINE toStreamKRevWith #-}
16331930toStreamKRevWith ::
@@ -1641,7 +1938,7 @@ toStreamKRevWith liftio MutArray {..} =
16411938
16421939 go p | p < arrStart = K.nil
16431940 | otherwise =
1644− let elemM = peekByteIndex p arrContents
1941+ let elemM = peekAt p arrContents
16451942 in liftio elemM `K.consM` go (INDEX_PREV(p,a))
16461943
16471944{-# INLINE toStreamKRev #-}
@@ -1676,7 +1973,7 @@ foldr f z arr = D.foldr f z $ read arr
16761973
16771974-- XXX Keep the bound intact to not lose any free space? Perf impact?
16781975
1679−-- | @writeAppendNUnsafe n arr@ appends up to @n@ input items to the supplied
1976+-- | @unsafeAppendN n arr@ appends up to @n@ input items to the supplied
16801977-- array.
16811978--
16821979-- Unsafe: Do not drive the fold beyond @n@ elements, it will lead to memory
@@ -1685,13 +1982,12 @@ foldr f z arr = D.foldr f z $ read arr
16851982-- Any free space left in the array after appending @n@ elements is lost.
16861983--
16871984-- /Internal/
1688−{-# INLINE_NORMAL writeAppendNUnsafe #-}
1689−writeAppendNUnsafe :: forall m a. (MonadIO m, Unbox a) =>
1985+{-# INLINE_NORMAL unsafeAppendN #-}
1986+unsafeAppendN :: forall m a. (MonadIO m, Unbox a) =>
16901987 Int
16911988 -> m (MutArray a)
16921989 -> Fold m a (MutArray a)
1693−writeAppendNUnsafe n action =
1694− fmap fromArrayUnsafe $ FL.foldlM' step initial
1990+unsafeAppendN n action = fmap fromArrayUnsafe $ FL.foldlM' step initial
16951991
16961992 where
16971993
@@ -1704,38 +2000,59 @@ writeAppendNUnsafe n action =
17042000 -- otherwise we lose that space.
17052001 arr1 <-
17062002 if free < needed
1707− then noinline reallocWith "writeAppendNUnsafeWith" (+ needed) needed arr
2003+ then noinline reallocWith "unsafeAppendN" (+ needed) needed arr
17082004 else return arr
17092005 return $ toArrayUnsafe arr1
17102006
17112007 step (ArrayUnsafe contents start end) x = do
1712− liftIO $ pokeByteIndex end contents x
2008+ liftIO $ pokeAt end contents x
17132009 return $ ArrayUnsafe contents start (INDEX_NEXT(end,a))
17142010
2011+{-# DEPRECATED writeAppendNUnsafe "Please use unsafeAppendN instead." #-}
2012+{-# INLINE writeAppendNUnsafe #-}
2013+writeAppendNUnsafe :: forall m a. (MonadIO m, Unbox a) =>
2014+ Int
2015+ -> m (MutArray a)
2016+ -> Fold m a (MutArray a)
2017+writeAppendNUnsafe = unsafeAppendN
2018+
17152019-- | Append @n@ elements to an existing array. Any free space left in the array
17162020-- after appending @n@ elements is lost.
17172021--
1718−-- >>> writeAppendN n initial = Fold.take n (MutArray.writeAppendNUnsafe n initial)
2022+-- >>> appendN n initial = Fold.take n (MutArray.unsafeAppendN n initial)
17192023--
1720−{-# INLINE_NORMAL writeAppendN #-}
2024+{-# INLINE_NORMAL appendN #-}
2025+appendN :: forall m a. (MonadIO m, Unbox a) =>
2026+ Int -> m (MutArray a) -> Fold m a (MutArray a)
2027+appendN n initial = FL.take n (unsafeAppendN n initial)
2028+
2029+-- XXX Deprecate in major
2030+-- {-# DEPRECATED writeAppendN "Please use appendN instead." #-}
2031+{-# INLINE writeAppendN #-}
17212032writeAppendN :: forall m a. (MonadIO m, Unbox a) =>
17222033 Int -> m (MutArray a) -> Fold m a (MutArray a)
1723−writeAppendN n initial = FL.take n (writeAppendNUnsafe n initial)
2034+writeAppendN = appendN
17242035
1725−-- | @writeAppendWith realloc action@ mutates the array generated by @action@ to
2036+-- | @appendWith realloc action@ mutates the array generated by @action@ to
17262037-- append the input stream. If there is no reserved space available in the
17272038-- array it is reallocated to a size in bytes determined by @realloc oldSize@,
17282039-- where @oldSize@ is the current size of the array in bytes.
17292040--
17302041-- Note that the returned array may be a mutated version of original array.
17312042--
1732−-- >>> writeAppendWith sizer = Fold.foldlM' (MutArray.snocWith sizer)
2043+-- >>> appendWith sizer = Fold.foldlM' (MutArray.snocWith sizer)
17332044--
17342045-- /Pre-release/
2046+{-# INLINE appendWith #-}
2047+appendWith :: forall m a. (MonadIO m, Unbox a) =>
2048+ (Int -> Int) -> m (MutArray a) -> Fold m a (MutArray a)
2049+appendWith sizer = FL.foldlM' (snocWith sizer)
2050+
2051+{-# DEPRECATED writeAppendWith "Please use appendWith instead." #-}
17352052{-# INLINE writeAppendWith #-}
17362053writeAppendWith :: forall m a. (MonadIO m, Unbox a) =>
17372054 (Int -> Int) -> m (MutArray a) -> Fold m a (MutArray a)
1738−writeAppendWith sizer = FL.foldlM' (snocWith sizer)
2055+writeAppendWith = appendWith
17392056
17402057-- | @append action@ mutates the array generated by @action@ to append the
17412058-- input stream. If there is no reserved space available in the array it is
@@ -1743,70 +2060,101 @@ writeAppendWith sizer = FL.foldlM' (snocWith sizer)
17432060--
17442061-- Note that the returned array may be a mutated version of original array.
17452062--
1746−-- >>> writeAppend = MutArray.writeAppendWith (* 2)
2063+-- >>> append = MutArray.appendWith (* 2)
17472064--
2065+{-# INLINE append #-}
2066+append :: forall m a. (MonadIO m, Unbox a) =>
2067+ m (MutArray a) -> Fold m a (MutArray a)
2068+append = appendWith (* 2)
2069+
2070+-- XXX Deprecate in major
2071+-- {-# DEPRECATED writeAppend "Please use append instead." #-}
17482072{-# INLINE writeAppend #-}
17492073writeAppend :: forall m a. (MonadIO m, Unbox a) =>
17502074 m (MutArray a) -> Fold m a (MutArray a)
1751−writeAppend = writeAppendWith (* 2)
2075+writeAppend = append
17522076
17532077-- XXX We can carry bound as well in the state to make sure we do not lose the
17542078-- remaining capacity. Need to check perf impact.
17552079--
1756−-- | Like 'writeNUnsafe' but takes a new array allocator @alloc size@ function
1757−-- as argument.
2080+-- | Like 'unsafeCreateOf' but takes a new array allocator @alloc size@
2081+-- function as argument.
17582082--
1759−-- >>> writeNWithUnsafe alloc n = MutArray.writeAppendNUnsafe (alloc n) n
2083+-- >>> unsafeCreateOfWith alloc n = MutArray.unsafeAppendN (alloc n) n
17602084--
17612085-- /Pre-release/
1762−{-# INLINE_NORMAL writeNWithUnsafe #-}
1763−writeNWithUnsafe :: forall m a. (MonadIO m, Unbox a)
2086+{-# INLINE_NORMAL unsafeCreateOfWith #-}
2087+unsafeCreateOfWith :: forall m a. (MonadIO m, Unbox a)
17642088 => (Int -> m (MutArray a)) -> Int -> Fold m a (MutArray a)
1765−writeNWithUnsafe alloc n = fromArrayUnsafe <$> FL.foldlM' step initial
2089+unsafeCreateOfWith alloc n = fromArrayUnsafe <$> FL.foldlM' step initial
17662090
17672091 where
17682092
17692093 initial = toArrayUnsafe <$> alloc (max n 0)
17702094
17712095 step (ArrayUnsafe contents start end) x = do
1772− liftIO $ pokeByteIndex end contents x
2096+ liftIO $ pokeAt end contents x
17732097 return
17742098 $ ArrayUnsafe contents start (INDEX_NEXT(end,a))
17752099
2100+{-# DEPRECATED writeNWithUnsafe "Please use unsafeCreateOfWith instead." #-}
2101+{-# INLINE writeNWithUnsafe #-}
2102+writeNWithUnsafe :: forall m a. (MonadIO m, Unbox a)
2103+ => (Int -> m (MutArray a)) -> Int -> Fold m a (MutArray a)
2104+writeNWithUnsafe = unsafeCreateOfWith
2105+
17762106{-# INLINE_NORMAL writeNUnsafeAs #-}
17772107writeNUnsafeAs :: forall m a. (MonadIO m, Unbox a)
17782108 => PinnedState -> Int -> Fold m a (MutArray a)
1779−writeNUnsafeAs ps = writeNWithUnsafe (newAs ps)
2109+writeNUnsafeAs ps = unsafeCreateOfWith (newAs ps)
17802110
1781−-- | Like 'writeN' but does not check the array bounds when writing. The fold
2111+-- | Like 'createOf' but does not check the array bounds when writing. The fold
17822112-- driver must not call the step function more than 'n' times otherwise it will
17832113-- corrupt the memory and crash. This function exists mainly because any
17842114-- conditional in the step function blocks fusion causing 10x performance
17852115-- slowdown.
17862116--
1787−-- >>> writeNUnsafe = MutArray.writeNWithUnsafe MutArray.new
2117+-- >>> unsafeCreateOf = MutArray.unsafeCreateOfWith MutArray.emptyOf
17882118--
1789−{-# INLINE_NORMAL writeNUnsafe #-}
2119+{-# INLINE_NORMAL unsafeCreateOf #-}
2120+unsafeCreateOf :: forall m a. (MonadIO m, Unbox a)
2121+ => Int -> Fold m a (MutArray a)
2122+unsafeCreateOf = writeNUnsafeAs Unpinned
2123+
2124+{-# DEPRECATED writeNUnsafe "Please use unsafeCreateOf instead." #-}
2125+{-# INLINE writeNUnsafe #-}
17902126writeNUnsafe :: forall m a. (MonadIO m, Unbox a)
17912127 => Int -> Fold m a (MutArray a)
1792−writeNUnsafe = writeNUnsafeAs Unpinned
2128+writeNUnsafe = unsafeCreateOf
17932129
1794−-- | Like 'writeNUnsafe' but creates a pinned array.
1795−{-# INLINE_NORMAL pinnedWriteNUnsafe #-}
2130+-- | Like 'unsafeCreateOf' but creates a pinned array.
2131+{-# INLINE_NORMAL unsafePinnedCreateOf #-}
2132+unsafePinnedCreateOf :: forall m a. (MonadIO m, Unbox a)
2133+ => Int -> Fold m a (MutArray a)
2134+unsafePinnedCreateOf = writeNUnsafeAs Pinned
2135+
2136+{-# DEPRECATED pinnedWriteNUnsafe "Please use unsafePinnedCreateOf instead." #-}
2137+{-# INLINE pinnedWriteNUnsafe #-}
17962138pinnedWriteNUnsafe :: forall m a. (MonadIO m, Unbox a)
17972139 => Int -> Fold m a (MutArray a)
1798−pinnedWriteNUnsafe = writeNUnsafeAs Pinned
2140+pinnedWriteNUnsafe = unsafePinnedCreateOf
17992141
1800−-- | @writeNWith alloc n@ folds a maximum of @n@ elements into an array
2142+-- | @createOfWith alloc n@ folds a maximum of @n@ elements into an array
18012143-- allocated using the @alloc@ function.
18022144--
1803−-- >>> writeNWith alloc n = Fold.take n (MutArray.writeNWithUnsafe alloc n)
1804−-- >>> writeNWith alloc n = MutArray.writeAppendN (alloc n) n
2145+-- >>> createOfWith alloc n = Fold.take n (MutArray.unsafeCreateOfWith alloc n)
2146+-- >>> createOfWith alloc n = MutArray.appendN (alloc n) n
18052147--
1806−{-# INLINE_NORMAL writeNWith #-}
2148+{-# INLINE_NORMAL createOfWith #-}
2149+createOfWith :: forall m a. (MonadIO m, Unbox a)
2150+ => (Int -> m (MutArray a)) -> Int -> Fold m a (MutArray a)
2151+createOfWith alloc n = FL.take n (unsafeCreateOfWith alloc n)
2152+
2153+-- {-# DEPRECATED writeNWith "Please use createOfWith instead." #-}
2154+{-# INLINE writeNWith #-}
18072155writeNWith :: forall m a. (MonadIO m, Unbox a)
18082156 => (Int -> m (MutArray a)) -> Int -> Fold m a (MutArray a)
1809−writeNWith alloc n = FL.take n (writeNWithUnsafe alloc n)
2157+writeNWith = createOfWith
18102158
18112159{-# INLINE_NORMAL writeNAs #-}
18122160writeNAs ::
@@ -1814,28 +2162,42 @@ writeNAs ::
18142162 => PinnedState
18152163 -> Int
18162164 -> Fold m a (MutArray a)
1817−writeNAs ps = writeNWith (newAs ps)
2165+writeNAs ps = createOfWith (newAs ps)
18182166
1819−-- | @writeN n@ folds a maximum of @n@ elements from the input stream to an
2167+-- | @createOf n@ folds a maximum of @n@ elements from the input stream to an
18202168-- 'MutArray'.
18212169--
1822−-- >>> writeN = MutArray.writeNWith MutArray.new
1823−-- >>> writeN n = Fold.take n (MutArray.writeNUnsafe n)
1824−-- >>> writeN n = MutArray.writeAppendN n (MutArray.new n)
2170+-- >>> createOf = MutArray.createOfWith MutArray.new
2171+-- >>> createOf n = Fold.take n (MutArray.unsafeCreateOf n)
2172+-- >>> createOf n = MutArray.appendN n (MutArray.emptyOf n)
18252173--
1826−{-# INLINE_NORMAL writeN #-}
2174+{-# INLINE_NORMAL createOf #-}
2175+createOf :: forall m a. (MonadIO m, Unbox a) => Int -> Fold m a (MutArray a)
2176+createOf = writeNAs Unpinned
2177+
2178+-- XXX Deprecate in major
2179+-- {-# DEPRECATED writeN "Please use createOf instead." #-}
2180+{-# INLINE writeN #-}
18272181writeN :: forall m a. (MonadIO m, Unbox a) => Int -> Fold m a (MutArray a)
1828−writeN = writeNAs Unpinned
2182+writeN = createOf
2183+
2184+-- | Like 'createOf' but creates a pinned array.
2185+{-# INLINE_NORMAL pinnedCreateOf #-}
2186+pinnedCreateOf ::
2187+ forall m a. (MonadIO m, Unbox a)
2188+ => Int
2189+ -> Fold m a (MutArray a)
2190+pinnedCreateOf = writeNAs Pinned
18292191
1830−-- | Like 'writeN' but creates a pinned array.
1831−{-# INLINE_NORMAL pinnedWriteN #-}
2192+{-# DEPRECATED pinnedWriteN "Please use pinnedCreateOf instead." #-}
2193+{-# INLINE pinnedWriteN #-}
18322194pinnedWriteN ::
18332195 forall m a. (MonadIO m, Unbox a)
18342196 => Int
18352197 -> Fold m a (MutArray a)
1836−pinnedWriteN = writeNAs Pinned
2198+pinnedWriteN = pinnedCreateOf
18372199
1838−-- | Like writeNWithUnsafe but writes the array in reverse order.
2200+-- | Like unsafeCreateOfWith but writes the array in reverse order.
18392201--
18402202-- /Internal/
18412203{-# INLINE_NORMAL writeRevNWithUnsafe #-}
@@ -1852,11 +2214,11 @@ writeRevNWithUnsafe alloc n = fromArrayUnsafe <$> FL.foldlM' step initial
18522214
18532215 step (ArrayUnsafe contents start end) x = do
18542216 let ptr = INDEX_PREV(start,a)
1855− liftIO $ pokeByteIndex ptr contents x
2217+ liftIO $ pokeAt ptr contents x
18562218 return
18572219 $ ArrayUnsafe contents ptr end
18582220
1859−-- | Like writeNWith but writes the array in reverse order.
2221+-- | Like createOfWith but writes the array in reverse order.
18602222--
18612223-- /Internal/
18622224{-# INLINE_NORMAL writeRevNWith #-}
@@ -1864,31 +2226,36 @@ writeRevNWith :: forall m a. (MonadIO m, Unbox a)
18642226 => (Int -> m (MutArray a)) -> Int -> Fold m a (MutArray a)
18652227writeRevNWith alloc n = FL.take n (writeRevNWithUnsafe alloc n)
18662228
1867−-- | Like writeN but writes the array in reverse order.
2229+-- | Like 'createOf' but writes the array in reverse order.
18682230--
18692231-- /Pre-release/
1870−{-# INLINE_NORMAL writeRevN #-}
2232+{-# INLINE_NORMAL revCreateOf #-}
2233+revCreateOf :: forall m a. (MonadIO m, Unbox a) => Int -> Fold m a (MutArray a)
2234+revCreateOf = writeRevNWith new
2235+
2236+{-# DEPRECATED writeRevN "Please use revCreateOf instead." #-}
2237+{-# INLINE writeRevN #-}
18712238writeRevN :: forall m a. (MonadIO m, Unbox a) => Int -> Fold m a (MutArray a)
1872−writeRevN = writeRevNWith new
2239+writeRevN = revCreateOf
18732240
18742241-- | @pinnedWriteNAligned align n@ folds a maximum of @n@ elements from the
18752242-- input stream to a 'MutArray' aligned to the given size.
18762243--
1877−-- >>> pinnedWriteNAligned align = MutArray.writeNWith (MutArray.pinnedNewAligned align)
1878−-- >>> pinnedWriteNAligned align n = MutArray.writeAppendN n (MutArray.pinnedNewAligned align n)
2244+-- >>> pinnedWriteNAligned align = MutArray.createOfWith (MutArray.pinnedNewAligned align)
2245+-- >>> pinnedWriteNAligned align n = MutArray.appendN n (MutArray.pinnedNewAligned align n)
18792246--
18802247-- /Pre-release/
18812248--
18822249{-# INLINE_NORMAL pinnedWriteNAligned #-}
18832250pinnedWriteNAligned :: forall m a. (MonadIO m, Unbox a)
18842251 => Int -> Int -> Fold m a (MutArray a)
1885−pinnedWriteNAligned align = writeNWith (pinnedNewAligned align)
2252+pinnedWriteNAligned align = createOfWith (pinnedNewAligned align)
18862253
18872254-- XXX Buffer to a list instead?
1888−--
2255+
18892256-- | Buffer a stream into a stream of arrays.
18902257--
1891−-- >>> writeChunks n = Fold.many (MutArray.writeN n) Fold.toStreamK
2258+-- >>> buildChunks n = Fold.many (MutArray.createOf n) Fold.toStreamK
18922259--
18932260-- Breaking an array into an array stream can be useful to consume a large
18942261-- array sequentially such that memory of the array is released incrementatlly.
@@ -1897,37 +2264,43 @@ pinnedWriteNAligned align = writeNWith (pinnedNewAligned align)
18972264--
18982265-- /Unimplemented/
18992266--
1900−{-# INLINE_NORMAL writeChunks #-}
2267+{-# INLINE_NORMAL buildChunks #-}
2268+buildChunks :: (MonadIO m, Unbox a) =>
2269+ Int -> Fold m a (StreamK n (MutArray a))
2270+buildChunks n = FL.many (createOf n) FL.toStreamK
2271+
2272+{-# DEPRECATED writeChunks "Please use buildChunks instead." #-}
2273+{-# INLINE writeChunks #-}
19012274writeChunks :: (MonadIO m, Unbox a) =>
19022275 Int -> Fold m a (StreamK n (MutArray a))
1903−writeChunks n = FL.many (writeN n) FL.toStreamK
2276+writeChunks = buildChunks
19042277
19052278{-# INLINE_NORMAL writeWithAs #-}
19062279writeWithAs :: forall m a. (MonadIO m, Unbox a)
19072280 => PinnedState -> Int -> Fold m a (MutArray a)
1908−-- writeWithAs ps n = FL.rmapM rightSize $ writeAppendWith (* 2) (newAs ps n)
2281+-- writeWithAs ps n = FL.rmapM rightSize $ appendWith (* 2) (newAs ps n)
19092282writeWithAs ps elemCount =
19102283 FL.rmapM extract $ FL.foldlM' step initial
19112284
19122285 where
19132286
19142287 initial = do
1915− when (elemCount < 0) $ error "writeWith: elemCount is negative"
1916− liftIO $ newAs ps elemCount
2288+ when (elemCount < 0) $ error "createWith: elemCount is negative"
2289+ newAs ps elemCount
19172290
19182291 step arr@(MutArray _ start end bound) x
19192292 | INDEX_NEXT(end,a) > bound = do
19202293 let oldSize = end - start
19212294 newSize = max (oldSize * 2) 1
1922− arr1 <- liftIO $ reallocExplicit (SIZE_OF(a)) newSize arr
2295+ arr1 <- liftIO $ reallocExplicitAs ps (SIZE_OF(a)) newSize arr
19232296 snocUnsafe arr1 x
19242297 step arr x = snocUnsafe arr x
19252298
19262299 extract = liftIO . rightSize
19272300
1928−-- XXX Compare writeWith with fromStreamD which uses an array of streams
1929−-- implementation. We can write this using writeChunks above if that is faster.
1930−-- If writeWith is faster then we should use that to implement
2301+-- XXX Compare createWith with fromStreamD which uses an array of streams
2302+-- implementation. We can write this using buildChunks above if that is faster.
2303+-- If createWith is faster then we should use that to implement
19312304-- fromStreamD.
19322305--
19332306-- XXX The realloc based implementation needs to make one extra copy if we use
@@ -1942,39 +2315,56 @@ writeWithAs ps elemCount =
19422315-- XXX check if GHC's memory allocator is efficient enough. We can try the C
19432316-- malloc to compare against.
19442317
1945−-- | @writeWith minCount@ folds the whole input to a single array. The array
2318+-- | @createWith minCount@ folds the whole input to a single array. The array
19462319-- starts at a size big enough to hold minCount elements, the size is doubled
19472320-- every time the array needs to be grown.
19482321--
19492322-- /Caution! Do not use this on infinite streams./
19502323--
1951−-- >>> f n = MutArray.writeAppendWith (* 2) (MutArray.new n)
1952−-- >>> writeWith n = Fold.rmapM MutArray.rightSize (f n)
1953−-- >>> writeWith n = Fold.rmapM MutArray.fromArrayStreamK (MutArray.writeChunks n)
2324+-- >>> f n = MutArray.appendWith (* 2) (MutArray.emptyOf n)
2325+-- >>> createWith n = Fold.rmapM MutArray.rightSize (f n)
2326+-- >>> createWith n = Fold.rmapM MutArray.fromChunksK (MutArray.buildChunks n)
19542327--
19552328-- /Pre-release/
1956−{-# INLINE_NORMAL writeWith #-}
2329+{-# INLINE_NORMAL createWith #-}
2330+createWith :: forall m a. (MonadIO m, Unbox a)
2331+ => Int -> Fold m a (MutArray a)
2332+-- createWith n = FL.rmapM rightSize $ appendWith (* 2) (emptyOf n)
2333+createWith = writeWithAs Unpinned
2334+
2335+{-# DEPRECATED writeWith "Please use createWith instead." #-}
2336+{-# INLINE writeWith #-}
19572337writeWith :: forall m a. (MonadIO m, Unbox a)
19582338 => Int -> Fold m a (MutArray a)
1959−-- writeWith n = FL.rmapM rightSize $ writeAppendWith (* 2) (new n)
1960−writeWith = writeWithAs Unpinned
2339+writeWith = createWith
19612340
19622341-- | Fold the whole input to a single array.
19632342--
1964−-- Same as 'writeWith' using an initial array size of 'arrayChunkBytes' bytes
2343+-- Same as 'createWith' using an initial array size of 'arrayChunkBytes' bytes
19652344-- rounded up to the element size.
19662345--
19672346-- /Caution! Do not use this on infinite streams./
19682347--
2348+{-# INLINE create #-}
2349+create :: forall m a. (MonadIO m, Unbox a) => Fold m a (MutArray a)
2350+create = createWith (allocBytesToElemCount (undefined :: a) arrayChunkBytes)
2351+
2352+-- XXX Deprecate in major
2353+-- {-# DEPRECATED write "Please use create instead." #-}
19692354{-# INLINE write #-}
19702355write :: forall m a. (MonadIO m, Unbox a) => Fold m a (MutArray a)
1971−write = writeWith (allocBytesToElemCount (undefined :: a) arrayChunkBytes)
2356+write = create
2357+
2358+-- | Like 'create' but creates a pinned array.
2359+{-# INLINE pinnedCreate #-}
2360+pinnedCreate :: forall m a. (MonadIO m, Unbox a) => Fold m a (MutArray a)
2361+pinnedCreate =
2362+ writeWithAs Pinned (allocBytesToElemCount (undefined :: a) arrayChunkBytes)
19722363
1973−-- | Like 'write' but creates a pinned array.
2364+{-# DEPRECATED pinnedWrite "Please use pinnedCreate instead." #-}
19742365{-# INLINE pinnedWrite #-}
19752366pinnedWrite :: forall m a. (MonadIO m, Unbox a) => Fold m a (MutArray a)
1976−pinnedWrite =
1977− writeWithAs Pinned (allocBytesToElemCount (undefined :: a) arrayChunkBytes)
2367+pinnedWrite = pinnedCreate
19782368
19792369-------------------------------------------------------------------------------
19802370-- construct from streams, known size
@@ -1984,25 +2374,31 @@ pinnedWrite =
19842374fromStreamDNAs :: forall m a. (MonadIO m, Unbox a)
19852375 => PinnedState -> Int -> D.Stream m a -> m (MutArray a)
19862376fromStreamDNAs ps limit str = do
1987− (arr :: MutArray a) <- liftIO $ newAs ps limit
2377+ (arr :: MutArray a) <- newAs ps limit
19882378 end <- D.foldlM' (fwrite (arrContents arr)) (return $ arrEnd arr) $ D.take limit str
19892379 return $ arr {arrEnd = end}
19902380
19912381 where
19922382
19932383 fwrite arrContents ptr x = do
1994− liftIO $ pokeByteIndex ptr arrContents x
2384+ liftIO $ pokeAt ptr arrContents x
19952385 return $ INDEX_NEXT(ptr,a)
19962386
1997−-- | Use the 'writeN' fold instead.
2387+-- | Use the 'createOf' fold instead.
19982388--
1999−-- >>> fromStreamDN n = Stream.fold (MutArray.writeN n)
2389+-- >>> fromStreamN n = Stream.fold (MutArray.createOf n)
20002390--
2001−{-# INLINE_NORMAL fromStreamDN #-}
2391+{-# INLINE_NORMAL fromStreamN #-}
2392+fromStreamN :: forall m a. (MonadIO m, Unbox a)
2393+ => Int -> D.Stream m a -> m (MutArray a)
2394+-- fromStreamDN n = D.fold (createOf n)
2395+fromStreamN = fromStreamDNAs Unpinned
2396+
2397+{-# DEPRECATED fromStreamDN "Please use fromStreamN instead." #-}
2398+{-# INLINE fromStreamDN #-}
20022399fromStreamDN :: forall m a. (MonadIO m, Unbox a)
20032400 => Int -> D.Stream m a -> m (MutArray a)
2004−-- fromStreamDN n = D.fold (writeN n)
2005−fromStreamDN = fromStreamDNAs Unpinned
2401+fromStreamDN = fromStreamN
20062402
20072403-- | Create a 'MutArray' from the first N elements of a list. The array is
20082404-- allocated to size N, if the list terminates before N elements then the
@@ -2022,16 +2418,70 @@ pinnedFromListN n xs = fromStreamDNAs Pinned n $ D.fromList xs
20222418-- /Pre-release/
20232419{-# INLINE fromListRevN #-}
20242420fromListRevN :: (MonadIO m, Unbox a) => Int -> [a] -> m (MutArray a)
2025−fromListRevN n xs = D.fold (writeRevN n) $ D.fromList xs
2421+fromListRevN n xs = D.fold (revCreateOf n) $ D.fromList xs
2422+
2423+-- | Convert a pure stream in Identity monad to a mutable array.
2424+{-# INLINABLE fromPureStreamN #-}
2425+fromPureStreamN :: (MonadIO m, Unbox a) =>
2426+ Int -> Stream Identity a -> m (MutArray a)
2427+fromPureStreamN n xs =
2428+ D.fold (createOf n) $ D.morphInner (return . runIdentity) xs
20262429
20272430-- | Convert a pure stream in Identity monad to a mutable array.
20282431{-# INLINABLE fromPureStream #-}
20292432fromPureStream :: (MonadIO m, Unbox a) => Stream Identity a -> m (MutArray a)
20302433fromPureStream xs =
2031− liftIO $ D.fold write $ D.morphInner (return . runIdentity) xs
2434+ D.fold create $ D.morphInner (return . runIdentity) xs
2435+
2436+{-# INLINABLE fromPtrN #-}
2437+fromPtrN :: MonadIO m => Int -> Ptr Word8 -> m (MutArray Word8)
2438+fromPtrN len addr = do
2439+ -- memcpy is better than stream copy when the size is known.
2440+ -- XXX We can implement a stream copy in a similar way by streaming Word64
2441+ -- first and then remaining Word8.
2442+ arr <- new len
2443+ _ <- unsafeAsPtr arr
2444+ (\ptr -> liftIO $ c_memcpy ptr addr (fromIntegral len))
2445+ return (arr {arrEnd = len})
2446+
2447+{-# INLINABLE fromByteStr# #-}
2448+fromByteStr# :: MonadIO m => Addr# -> m (MutArray Word8)
2449+fromByteStr# addr = do
2450+ -- It is better to count the size first and allocate exact space.
2451+ -- Also, memcpy is better than stream copy when the size is known.
2452+ -- C strlen compares 4 bytes at a time, so is better than the stream
2453+ -- version. https://github.com/bminor/glibc/blob/master/string/strlen.c
2454+ -- XXX We can possibly use a stream of Word64 to do the same.
2455+ -- fromByteStr# addr = fromPureStream (D.fromByteStr# addr)
2456+ len <- liftIO $ c_strlen (Ptr addr)
2457+ let lenInt = fromIntegral len
2458+ arr <- new lenInt
2459+ _ <- unsafeAsPtr arr (\ptr -> liftIO $ c_memcpy ptr (Ptr addr) len)
2460+ return (arr {arrEnd = lenInt})
20322461
20332462-------------------------------------------------------------------------------
2034−-- convert stream to a single array
2463+-- convert a stream of arrays to a single array by reallocating and copying
2464+-------------------------------------------------------------------------------
2465+
2466+-- XXX Both of these implementations of splicing seem to perform equally well.
2467+-- We need to perform benchmarks over a range of sizes though.
2468+
2469+-- | Also see 'fromChunksK'.
2470+{-# INLINE fromChunksRealloced #-}
2471+fromChunksRealloced :: forall m a. (MonadIO m, Unbox a)
2472+ => Stream m (MutArray a) -> m (MutArray a)
2473+fromChunksRealloced s = do
2474+ res <- D.uncons s
2475+ case res of
2476+ Just (a, strm) -> do
2477+ arr <- D.foldlM' spliceExp (pure a) strm
2478+ -- Reallocation is exponential so there may be 50% empty space in
2479+ -- worst case. One more reallocation to reclaim the space.
2480+ rightSize arr
2481+ Nothing -> pure nil
2482+
2483+-------------------------------------------------------------------------------
2484+-- convert a stream of arrays to a single array by buffering arrays first
20352485-------------------------------------------------------------------------------
20362486
20372487{-# INLINE arrayStreamKLength #-}
@@ -2041,34 +2491,72 @@ arrayStreamKLength as = K.foldl' (+) 0 (K.map length as)
20412491-- | Convert an array stream to an array. Note that this requires peak memory
20422492-- that is double the size of the array stream.
20432493--
2494+{-# INLINE fromChunkskAs #-}
2495+fromChunkskAs :: (Unbox a, MonadIO m) =>
2496+ PinnedState -> StreamK m (MutArray a) -> m (MutArray a)
2497+fromChunkskAs ps as = do
2498+ len <- arrayStreamKLength as
2499+ arr <- newAs ps len
2500+ -- XXX is StreamK fold faster or StreamD fold?
2501+ K.foldlM' spliceUnsafe (pure arr) as
2502+ -- fromStreamDN len $ D.unfoldMany reader $ D.fromStreamK as
2503+
2504+-- XXX Need to compare this with fromChunks and fromChunkList and keep the
2505+-- fastest or simplest one if all are equally fast.
2506+
2507+-- | Convert an array stream to an array. Note that this requires peak memory
2508+-- that is double the size of the array stream.
2509+--
2510+-- Also see 'fromChunksRealloced'.
2511+--
2512+{-# INLINE fromChunksK #-}
2513+fromChunksK :: (Unbox a, MonadIO m) =>
2514+ StreamK m (MutArray a) -> m (MutArray a)
2515+fromChunksK = fromChunkskAs Unpinned
2516+
2517+{-# DEPRECATED fromArrayStreamK "Please use fromChunksK instead." #-}
20442518{-# INLINE fromArrayStreamK #-}
20452519fromArrayStreamK :: (Unbox a, MonadIO m) =>
20462520 StreamK m (MutArray a) -> m (MutArray a)
2047−fromArrayStreamK as = do
2048− len <- arrayStreamKLength as
2049− fromStreamDN len $ D.unfoldMany reader $ D.fromStreamK as
2521+fromArrayStreamK = fromChunksK
20502522
20512523{-# INLINE fromStreamDAs #-}
20522524fromStreamDAs ::
20532525 (MonadIO m, Unbox a) => PinnedState -> D.Stream m a -> m (MutArray a)
2054−fromStreamDAs ps m = arrayStreamKFromStreamDAs ps m >>= fromArrayStreamK
2526+fromStreamDAs ps m =
2527+ arrayStreamKFromStreamDAs Unpinned m >>= fromChunkskAs ps
20552528
2529+-- | Create an 'Array' from a stream. This is useful when we want to create a
2530+-- single array from a stream of unknown size. 'createOf' is at least twice
2531+-- as efficient when the size is already known.
2532+--
2533+-- Note that if the input stream is too large memory allocation for the array
2534+-- may fail. When the stream size is not known, `chunksOf` followed by
2535+-- processing of indvidual arrays in the resulting stream should be preferred.
2536+--
2537+-- /Pre-release/
2538+{-# INLINE fromStream #-}
2539+fromStream :: (MonadIO m, Unbox a) => Stream m a -> m (MutArray a)
2540+fromStream = fromStreamDAs Unpinned
2541+
2542+-- fromStream (Stream m) = P.fold create m
20562543-- CAUTION: a very large number (millions) of arrays can degrade performance
20572544-- due to GC overhead because we need to buffer the arrays before we flatten
20582545-- all the arrays.
20592546--
2060−-- XXX Compare if this is faster or "fold write".
2547+-- XXX Compare if this is faster or "fold create".
20612548--
20622549-- | We could take the approach of doubling the memory allocation on each
20632550-- overflow. This would result in more or less the same amount of copying as in
20642551-- the chunking approach. However, if we have to shrink in the end then it may
20652552-- result in an extra copy of the entire data.
20662553--
2067−-- >>> fromStreamD = StreamD.fold MutArray.write
2554+-- >>> fromStreamD = StreamD.fold MutArray.create
20682555--
20692556{-# INLINE fromStreamD #-}
2557+{-# DEPRECATED fromStreamD "Please use fromStream instead." #-}
20702558fromStreamD :: (MonadIO m, Unbox a) => D.Stream m a -> m (MutArray a)
2071−fromStreamD = fromStreamDAs Unpinned
2559+fromStreamD = fromStream
20722560
20732561-- | Create a 'MutArray' from a list. The list must be of finite size.
20742562--
@@ -2093,22 +2581,44 @@ fromListRev xs = fromListRevN (Prelude.length xs) xs
20932581-- Cloning
20942582-------------------------------------------------------------------------------
20952583
2584+-- Arrays are aligned on 64-bit boundaries. The fastest way to copy an array is
2585+-- to unsafeCast it to Word64, read it, write it to Word64 array and unsafeCast
2586+-- it again. We can use SIMD read/write as well.
2587+
20962588{-# INLINE cloneAs #-}
2097−cloneAs :: MonadIO m => PinnedState -> MutArray a -> m (MutArray a)
2589+cloneAs ::
2590+ ( MonadIO m
2591+#ifdef DEVBUILD
2592+ , Unbox a
2593+#endif
2594+ )
2595+ => PinnedState -> MutArray a -> m (MutArray a)
20982596cloneAs ps src =
2099− liftIO $ do
2597+ do
21002598 let startSrc = arrStart src
21012599 srcLen = arrEnd src - startSrc
2102− newArrContents <- Unboxed.newBytesAs ps srcLen
2103− putSliceUnsafe (arrContents src) startSrc newArrContents 0 srcLen
2600+ newArrContents <-
2601+ Unboxed.cloneSliceUnsafeAs ps startSrc srcLen (arrContents src)
21042602 return $ MutArray newArrContents 0 srcLen srcLen
21052603
21062604{-# INLINE clone #-}
2107−clone :: MonadIO m => MutArray a -> m (MutArray a)
2605+clone ::
2606+ ( MonadIO m
2607+#ifdef DEVBUILD
2608+ , Unbox a
2609+#endif
2610+ )
2611+ => MutArray a -> m (MutArray a)
21082612clone = cloneAs Unpinned
21092613
21102614{-# INLINE pinnedClone #-}
2111−pinnedClone :: MonadIO m => MutArray a -> m (MutArray a)
2615+pinnedClone ::
2616+ ( MonadIO m
2617+#ifdef DEVBUILD
2618+ , Unbox a
2619+#endif
2620+ )
2621+ => MutArray a -> m (MutArray a)
21122622pinnedClone = cloneAs Pinned
21132623
21142624-------------------------------------------------------------------------------
@@ -2123,17 +2633,16 @@ spliceCopy :: forall m a. MonadIO m =>
21232633 Unbox a =>
21242634#endif
21252635 MutArray a -> MutArray a -> m (MutArray a)
2126−spliceCopy arr1 arr2 = liftIO $ do
2636+spliceCopy arr1 arr2 = do
21272637 let start1 = arrStart arr1
21282638 start2 = arrStart arr2
21292639 len1 = arrEnd arr1 - start1
21302640 len2 = arrEnd arr2 - start2
2131− let newLen = len1 + len2
2641+ let len = len1 + len2
21322642 newArrContents <-
21332643 if Unboxed.isPinned (arrContents arr1)
2134− then Unboxed.pinnedNewBytes newLen
2135− else Unboxed.newBytes newLen
2136− let len = len1 + len2
2644+ then liftIO $ Unboxed.pinnedNew len
2645+ else liftIO $ Unboxed.new len
21372646 putSliceUnsafe (arrContents arr1) start1 newArrContents 0 len1
21382647 putSliceUnsafe (arrContents arr2) start2 newArrContents len1 len2
21392648 return $ MutArray newArrContents 0 len len
@@ -2145,7 +2654,7 @@ spliceCopy arr1 arr2 = liftIO $ do
21452654spliceUnsafe :: MonadIO m =>
21462655 MutArray a -> MutArray a -> m (MutArray a)
21472656spliceUnsafe dst src =
2148− liftIO $ do
2657+ do
21492658 let startSrc = arrStart src
21502659 srcLen = arrEnd src - startSrc
21512660 endDst = arrEnd dst
@@ -2167,7 +2676,7 @@ spliceWith :: forall m a. (MonadIO m, Unbox a) =>
21672676 (Int -> Int -> Int) -> MutArray a -> MutArray a -> m (MutArray a)
21682677spliceWith sizer dst@(MutArray _ start end bound) src = do
21692678{-
2170− let f = writeAppendWith (`sizer` byteLength src) (return dst)
2679+ let f = appendWith (`sizer` byteLength src) (return dst)
21712680 in D.fold f (toStreamD src)
21722681-}
21732682 assert (end <= bound) (return ())
@@ -2183,7 +2692,7 @@ spliceWith sizer dst@(MutArray _ start end bound) src = do
21832692 $ "splice: newSize is less than the total size "
21842693 ++ "of arrays being appended. Please check the "
21852694 ++ "sizer function passed."
2186− liftIO $ realloc newSizeInBytes dst
2695+ realloc newSizeInBytes dst
21872696 else return dst
21882697 spliceUnsafe dst1 src
21892698
@@ -2220,14 +2729,24 @@ spliceExp = spliceWith (\l1 l2 -> max (l1 * 2) (l1 + l2))
22202729-- Splitting
22212730-------------------------------------------------------------------------------
22222731
2732+-- | Generate a stream of array slices using a predicate. The array element
2733+-- matching the predicate is dropped.
2734+--
2735+-- /Pre-release/
2736+{-# INLINE splitOn #-}
2737+splitOn :: (MonadIO m, Unbox a) =>
2738+ (a -> Bool) -> MutArray a -> Stream m (MutArray a)
2739+splitOn predicate arr =
2740+ fmap (\(i, len) -> getSliceUnsafe i len arr)
2741+ $ D.indexOnSuffix predicate (read arr)
2742+
22232743-- | Drops the separator byte
22242744{-# INLINE breakOn #-}
22252745breakOn :: MonadIO m
22262746 => Word8 -> MutArray Word8 -> m (MutArray Word8, Maybe (MutArray Word8))
2227−breakOn sep arr@MutArray{..} = asPtrUnsafe arr $ \p -> liftIO $ do
2228− -- XXX Instead of using asPtrUnsafe (pinning memory) we can pass unlifted
2229− -- Addr# to memchr and it should be safe (from ghc 8.4).
2747+breakOn sep arr@MutArray{..} = unsafeAsPtr arr $ \p -> liftIO $ do
22302748 -- XXX We do not need memchr here, we can use a Haskell equivalent.
2749+ -- Need efficient stream based primitives that work on Word64.
22312750 loc <- c_memchr p sep (fromIntegral $ byteLength arr)
22322751 let sepIndex = loc `minusPtr` p
22332752 return $
@@ -2248,32 +2767,41 @@ breakOn sep arr@MutArray{..} = asPtrUnsafe arr $ \p -> liftIO $ do
22482767 }
22492768 )
22502769
2770+-- | Like 'splitAt' but does not check whether the index is valid.
2771+--
2772+{-# INLINE unsafeSplitAt #-}
2773+unsafeSplitAt :: forall a. Unbox a =>
2774+ Int -> MutArray a -> (MutArray a, MutArray a)
2775+unsafeSplitAt i MutArray{..} =
2776+ let off = i * SIZE_OF(a)
2777+ p = arrStart + off
2778+ in ( MutArray
2779+ { arrContents = arrContents
2780+ , arrStart = arrStart
2781+ , arrEnd = p
2782+ , arrBound = p
2783+ }
2784+ , MutArray
2785+ { arrContents = arrContents
2786+ , arrStart = p
2787+ , arrEnd = arrEnd
2788+ , arrBound = arrBound
2789+ }
2790+ )
2791+
22512792-- | Create two slices of an array without copying the original array. The
22522793-- specified index @i@ is the first index of the second slice.
22532794--
2795+{-# INLINE splitAt #-}
22542796splitAt :: forall a. Unbox a => Int -> MutArray a -> (MutArray a, MutArray a)
2255−splitAt i arr@MutArray{..} =
2797+splitAt i arr =
22562798 let maxIndex = length arr - 1
22572799 in if i < 0
22582800 then error "sliceAt: negative array index"
22592801 else if i > maxIndex
22602802 then error $ "sliceAt: specified array index " ++ show i
22612803 ++ " is beyond the maximum index " ++ show maxIndex
2262− else let off = i * SIZE_OF(a)
2263− p = arrStart + off
2264− in ( MutArray
2265− { arrContents = arrContents
2266− , arrStart = arrStart
2267− , arrEnd = p
2268− , arrBound = p
2269− }
2270− , MutArray
2271− { arrContents = arrContents
2272− , arrStart = p
2273− , arrEnd = arrEnd
2274− , arrBound = arrBound
2275− }
2276− )
2804+ else unsafeSplitAt i arr
22772805
22782806-------------------------------------------------------------------------------
22792807-- Casting
@@ -2323,13 +2851,16 @@ cast arr =
23232851-- guarantees that unsafe calls will be performed in the calling thread. Making
23242852-- it safe to pass heap-allocated objects to unsafe functions.
23252853
2326−-- Unsafe because of direct pointer operations. The user must ensure that they
2327−-- are writing within the legal bounds of the array. Should we just name it
2328−-- asPtr, the unsafety is implicit for any pointer operations. And we are safe
2329−-- from Haskell perspective because we will be pinning the memory.
2854+-- XXX Should we just name it asPtr, the unsafety is implicit for any pointer
2855+-- operations. And we are safe from Haskell perspective because we will be
2856+-- pinning the memory.
2857+--
2858+-- XXX we cannot pass the length of the ptr here as in some cases it may not be
2859+-- available e.g. a null terminated C string. However, we can create another
2860+-- flavor of the API e.g. asPtrN.
23302861
2331−-- | Use an @MutArray a@ as @Ptr a@. This is useful when we want to pass an array
2332−-- as a pointer to some operating system call or to a "safe" FFI call.
2862+-- | Use a @MutArray a@ as @Ptr a@. This is useful when we want to pass an
2863+-- array as a pointer to some operating system call or to a "safe" FFI call.
23332864--
23342865-- If the array is not pinned it is copied to pinned memory before passing it
23352866-- to the monadic action.
@@ -2339,56 +2870,382 @@ cast arr =
23392870-- opportunistically before this operation occurs, to avoid the cost of a copy
23402871-- if possible.
23412872--
2342−-- /Unsafe/
2873+-- /Unsafe/ because of direct pointer operations. The user must ensure that
2874+-- they are writing within the legal bounds of the array.
23432875--
23442876-- /Pre-release/
23452877--
2878+{-# INLINE unsafePinnedAsPtr #-}
2879+unsafePinnedAsPtr :: MonadIO m => MutArray a -> (Ptr a -> m b) -> m b
2880+unsafePinnedAsPtr arr f =
2881+ Unboxed.unsafePinnedAsPtr
2882+ (arrContents arr) (\ptr -> f (ptr `plusPtr` arrStart arr))
2883+
2884+{-# DEPRECATED asPtrUnsafe "Please use unsafePinnedAsPtr instead." #-}
2885+{-# INLINE asPtrUnsafe #-}
23462886asPtrUnsafe :: MonadIO m => MutArray a -> (Ptr a -> m b) -> m b
2347−asPtrUnsafe arr f = do
2348− contents <- liftIO $ Unboxed.pin $ arrContents arr
2349− let !ptr = Ptr (byteArrayContents#
2350− (unsafeCoerce# (getMutableByteArray# contents)))
2887+asPtrUnsafe = unsafePinnedAsPtr
23512888
2352− r <- f (ptr `plusPtr` arrStart arr)
2353− liftIO $ touch contents
2354− return r
2889+{-# INLINE unsafeAsPtr #-}
2890+unsafeAsPtr :: MonadIO m => MutArray a -> (Ptr a -> m b) -> m b
2891+unsafeAsPtr arr f =
2892+ Unboxed.unsafeAsPtr
2893+ (arrContents arr) (\ptr -> f (ptr `plusPtr` arrStart arr))
23552894
23562895-------------------------------------------------------------------------------
23572896-- Equality
23582897-------------------------------------------------------------------------------
23592898
2360−-- | Compare the length of the arrays. If the length is equal, compare the
2361−-- lexicographical ordering of two underlying byte arrays otherwise return the
2362−-- result of length comparison.
2899+-- | Byte compare two arrays. Compare the length of the arrays. If the length
2900+-- is equal, compare the lexicographical ordering of two underlying byte arrays
2901+-- otherwise return the result of length comparison.
2902+--
2903+-- /Unsafe/: Note that the 'Unbox' instance of sum types with constructors of
2904+-- different sizes may leave some memory uninitialized which can make byte
2905+-- comparison unreliable.
23632906--
23642907-- /Pre-release/
2908+{-# INLINE byteCmp #-}
2909+byteCmp :: MonadIO m => MutArray a -> MutArray a -> m Ordering
2910+byteCmp arr1 arr2 = do
2911+ let marr1 = getMutableByteArray# (arrContents arr1)
2912+ marr2 = getMutableByteArray# (arrContents arr2)
2913+ !(I# st1#) = arrStart arr1
2914+ !(I# st2#) = arrStart arr2
2915+ !(I# len#) = byteLength arr1
2916+ case compare (byteLength arr1) (byteLength arr2) of
2917+ EQ -> do
2918+ r <- liftIO $ IO $ \s# ->
2919+ let res =
2920+ I#
2921+ (compareByteArrays#
2922+ (unsafeCoerce# marr1)
2923+ st1#
2924+ (unsafeCoerce# marr2)
2925+ st2#
2926+ len#)
2927+ in (# s#, res #)
2928+ return $ compare r 0
2929+ x -> return x
2930+
23652931{-# INLINE cmp #-}
2932+{-# DEPRECATED cmp "Please use byteCmp instead." #-}
23662933cmp :: MonadIO m => MutArray a -> MutArray a -> m Ordering
2367−cmp arr1 arr2 =
2368− liftIO
2369− $ do
2370− let marr1 = getMutableByteArray# (arrContents arr1)
2371− marr2 = getMutableByteArray# (arrContents arr2)
2372− !(I# st1#) = arrStart arr1
2373− !(I# st2#) = arrStart arr2
2374− !(I# len#) = byteLength arr1
2375− case compare (byteLength arr1) (byteLength arr2) of
2376− EQ -> do
2377− r <- liftIO $ IO $ \s# ->
2378− let res =
2379− I#
2380− (compareByteArrays#
2381− (unsafeCoerce# marr1)
2382− st1#
2383− (unsafeCoerce# marr2)
2384− st2#
2385− len#)
2386− in (# s#, res #)
2387− return $ compare r 0
2388− x -> return x
2934+cmp = byteCmp
2935+
2936+-- | Byte equality of two arrays.
2937+--
2938+-- >>> byteEq arr1 arr2 = (==) EQ $ MArray.byteCmp arr1 arr2
2939+--
2940+-- /Unsafe/: See 'byteCmp'.
2941+{-# INLINE byteEq #-}
2942+byteEq :: MonadIO m => MutArray a -> MutArray a -> m Bool
2943+byteEq arr1 arr2 = fmap (EQ ==) $ byteCmp arr1 arr2
2944+
2945+-------------------------------------------------------------------------------
2946+-- Compact
2947+-------------------------------------------------------------------------------
2948+
2949+-- Note: LE versions avoid an extra copy compared to GE. LE parser trades
2950+-- backtracking one array in lieu of avoiding a copy. However, LE and GE both
2951+-- can leave some memory unused. They can split the last array to fit it
2952+-- exactly in the space.
2953+
2954+{-# INLINE_NORMAL pCompactLeAs #-}
2955+pCompactLeAs ::
2956+ forall m a. (MonadIO m, Unbox a)
2957+ => PinnedState -> Int -> Parser (MutArray a) m (MutArray a)
2958+pCompactLeAs ps maxElems = Parser step initial extract
2959+
2960+ where
2961+
2962+ maxBytes = maxElems * SIZE_OF(a)
2963+
2964+ functionName = "Streamly.Internal.Data.MutArray.pCompactLE"
2965+
2966+ initial =
2967+ return
2968+ $ if maxElems <= 0
2969+ then error
2970+ $ functionName
2971+ ++ ": the size of arrays ["
2972+ ++ show maxElems ++ "] must be a natural number"
2973+ else Parser.IPartial Nothing
2974+
2975+ step Nothing arr =
2976+ return
2977+ $ let len = byteLength arr
2978+ in if len >= maxBytes
2979+ then Parser.Done 0 arr
2980+ else Parser.Partial 0 (Just arr)
2981+ -- XXX Split the last array to use the space more compactly.
2982+ step (Just buf) arr =
2983+ let len = byteLength buf + byteLength arr
2984+ in if len > maxBytes
2985+ then return $ Parser.Done 1 buf
2986+ else do
2987+ buf1 <-
2988+ if byteCapacity buf < maxBytes
2989+ then liftIO $ reallocExplicitAs
2990+ ps (SIZE_OF(a)) maxBytes buf
2991+ else return buf
2992+ buf2 <- spliceUnsafe buf1 arr
2993+ return $ Parser.Partial 0 (Just buf2)
2994+
2995+ extract Nothing = return $ Parser.Done 0 nil
2996+ extract (Just buf) = return $ Parser.Done 0 buf
2997+
2998+-- | Parser @pCompactLE maxElems@ coalesces adjacent arrays in the input stream
2999+-- only if the combined size would be less than or equal to @maxElems@
3000+-- elements. Note that it won't split an array if the original array is already
3001+-- larger than maxElems.
3002+--
3003+-- @maxElems@ must be greater than 0.
3004+--
3005+-- Generates unpinned arrays irrespective of the pinning status of input
3006+-- arrays.
3007+--
3008+-- /Internal/
3009+{-# INLINE pCompactLE #-}
3010+pCompactLE ::
3011+ forall m a. (MonadIO m, Unbox a)
3012+ => Int -> Parser (MutArray a) m (MutArray a)
3013+pCompactLE = pCompactLeAs Unpinned
3014+
3015+-- | Pinned version of 'pCompactLE'.
3016+{-# INLINE pPinnedCompactLE #-}
3017+pPinnedCompactLE ::
3018+ forall m a. (MonadIO m, Unbox a)
3019+ => Int -> Parser (MutArray a) m (MutArray a)
3020+pPinnedCompactLE = pCompactLeAs Pinned
3021+
3022+data SpliceState s arr
3023+ = SpliceInitial s
3024+ | SpliceBuffering s arr
3025+ | SpliceYielding arr (SpliceState s arr)
3026+ | SpliceFinish
3027+
3028+-- This mutates the first array (if it has space) to append values from the
3029+-- second one. This would work for immutable arrays as well because an
3030+-- immutable array never has additional space so a new array is allocated
3031+-- instead of mutating it.
3032+
3033+{-# INLINE_NORMAL compactLeAs #-}
3034+compactLeAs :: forall m a. (MonadIO m, Unbox a)
3035+ => PinnedState -> Int -> D.Stream m (MutArray a) -> D.Stream m (MutArray a)
3036+compactLeAs ps maxElems (D.Stream step state) =
3037+ D.Stream step' (SpliceInitial state)
3038+
3039+ where
3040+
3041+ maxBytes = maxElems * SIZE_OF(a)
3042+
3043+ functionName = "Streamly.Internal.Data.MutArray.rCompactLE"
3044+
3045+ {-# INLINE_LATE step' #-}
3046+ step' gst (SpliceInitial st) = do
3047+ when (maxElems <= 0) $
3048+ -- XXX we can pass the module string from the higher level API
3049+ error $ functionName ++ ": the size of arrays [" ++ show maxElems
3050+ ++ "] must be a natural number"
3051+ r <- step gst st
3052+ case r of
3053+ D.Yield arr s -> return $
3054+ let len = byteLength arr
3055+ in if len >= maxBytes
3056+ then D.Skip (SpliceYielding arr (SpliceInitial s))
3057+ else D.Skip (SpliceBuffering s arr)
3058+ D.Skip s -> return $ D.Skip (SpliceInitial s)
3059+ D.Stop -> return D.Stop
3060+
3061+ -- XXX Split the last array to use the space more compactly.
3062+ step' gst (SpliceBuffering st buf) = do
3063+ r <- step gst st
3064+ case r of
3065+ D.Yield arr s -> do
3066+ let len = byteLength buf + byteLength arr
3067+ if len > maxBytes
3068+ then return $
3069+ D.Skip (SpliceYielding buf (SpliceBuffering s arr))
3070+ else do
3071+ buf1 <- if byteCapacity buf < maxBytes
3072+ then liftIO $ reallocExplicitAs
3073+ ps (SIZE_OF(a)) maxBytes buf
3074+ else return buf
3075+ buf2 <- spliceUnsafe buf1 arr
3076+ return $ D.Skip (SpliceBuffering s buf2)
3077+ D.Skip s -> return $ D.Skip (SpliceBuffering s buf)
3078+ D.Stop -> return $ D.Skip (SpliceYielding buf SpliceFinish)
3079+
3080+ step' _ SpliceFinish = return D.Stop
3081+
3082+ step' _ (SpliceYielding arr next) = return $ D.Yield arr next
3083+
3084+
3085+{-# INLINE_NORMAL fCompactGeAs #-}
3086+fCompactGeAs ::
3087+ forall m a. (MonadIO m, Unbox a)
3088+ => PinnedState -> Int -> FL.Fold m (MutArray a) (MutArray a)
3089+fCompactGeAs ps minElems = Fold step initial extract extract
3090+
3091+ where
3092+
3093+ minBytes = minElems * SIZE_OF(a)
3094+
3095+ functionName = "Streamly.Internal.Data.MutArray.fCompactGE"
3096+
3097+ initial =
3098+ return
3099+ $ if minElems < 0
3100+ then error
3101+ $ functionName
3102+ ++ ": the size of arrays ["
3103+ ++ show minElems ++ "] must be a natural number"
3104+ else FL.Partial Nothing
3105+
3106+ step Nothing arr =
3107+ return
3108+ $ let len = byteLength arr
3109+ in if len >= minBytes
3110+ then FL.Done arr
3111+ else FL.Partial (Just arr)
3112+ -- XXX Buffer arrays as a list to avoid copy and reallocations
3113+ step (Just buf) arr = do
3114+ let len = byteLength buf + byteLength arr
3115+ buf1 <-
3116+ if byteCapacity buf < len
3117+ then liftIO $ reallocExplicitAs
3118+ ps (SIZE_OF(a)) (max minBytes len) buf
3119+ else return buf
3120+ buf2 <- spliceUnsafe buf1 arr
3121+ if len >= minBytes
3122+ then return $ FL.Done buf2
3123+ else return $ FL.Partial (Just buf2)
3124+
3125+ extract Nothing = return nil
3126+ extract (Just buf) = return buf
3127+
3128+-- | Fold @fCompactGE minElems@ coalesces adjacent arrays in the input stream
3129+-- until the size becomes greater than or equal to @minElems@.
3130+--
3131+-- Generates unpinned arrays irrespective of the pinning status of input
3132+-- arrays.
3133+{-# INLINE fCompactGE #-}
3134+fCompactGE ::
3135+ forall m a. (MonadIO m, Unbox a)
3136+ => Int -> FL.Fold m (MutArray a) (MutArray a)
3137+fCompactGE = fCompactGeAs Unpinned
3138+
3139+-- | Pinned version of 'fCompactGE'.
3140+{-# INLINE fPinnedCompactGE #-}
3141+fPinnedCompactGE ::
3142+ forall m a. (MonadIO m, Unbox a)
3143+ => Int -> FL.Fold m (MutArray a) (MutArray a)
3144+fPinnedCompactGE = fCompactGeAs Pinned
3145+
3146+{-# INLINE_NORMAL lCompactGeAs #-}
3147+lCompactGeAs :: forall m a. (MonadIO m, Unbox a)
3148+ => PinnedState -> Int -> Fold m (MutArray a) () -> Fold m (MutArray a) ()
3149+-- The fold version turns out to be a little bit slower.
3150+-- lCompactGeAs ps n = FL.many (fCompactGeAs ps n)
3151+lCompactGeAs ps minElems (Fold step1 initial1 _ final1) =
3152+ Fold step initial extract final
3153+
3154+ where
3155+
3156+ minBytes = minElems * SIZE_OF(a)
3157+
3158+ functionName = "Streamly.Internal.Data.MutArray.lCompactGE"
3159+
3160+ initial = do
3161+ when (minElems <= 0) $
3162+ -- XXX we can pass the module string from the higher level API
3163+ error $ functionName ++ ": the size of arrays ["
3164+ ++ show minElems ++ "] must be a natural number"
3165+
3166+ r <- initial1
3167+ return $ first (Tuple' Nothing) r
3168+
3169+ {-# INLINE runInner #-}
3170+ runInner len acc buf =
3171+ if len >= minBytes
3172+ then do
3173+ r <- step1 acc buf
3174+ case r of
3175+ FL.Done _ -> return $ FL.Done ()
3176+ FL.Partial s -> do
3177+ _ <- final1 s
3178+ res <- initial1
3179+ return $ first (Tuple' Nothing) res
3180+ else return $ FL.Partial $ Tuple' (Just buf) acc
3181+
3182+ step (Tuple' Nothing r1) arr =
3183+ runInner (byteLength arr) r1 arr
3184+
3185+ -- XXX Buffer arrays as a list to avoid copy and reallocations
3186+ step (Tuple' (Just buf) r1) arr = do
3187+ let len = byteLength buf + byteLength arr
3188+ buf1 <- if byteCapacity buf < len
3189+ then liftIO $ reallocExplicitAs
3190+ ps (SIZE_OF(a)) (max minBytes len) buf
3191+ else return buf
3192+ buf2 <- spliceUnsafe buf1 arr
3193+ runInner len r1 buf2
3194+
3195+ -- XXX Several folds do extract >=> final, therefore, we need to make final
3196+ -- return "m b" rather than using extract post it if we want extract to be
3197+ -- partial.
3198+ --
3199+ -- extract forces the pending buffer to be sent to the fold which is not
3200+ -- what we want.
3201+ extract _ = error "lCompactGE: not designed for scanning"
3202+
3203+ final (Tuple' Nothing r1) = final1 r1
3204+ final (Tuple' (Just buf) r1) = do
3205+ r <- step1 r1 buf
3206+ case r of
3207+ FL.Partial rr -> final1 rr
3208+ FL.Done _ -> return ()
3209+
3210+-- | Like 'compactGE' but for transforming folds instead of stream.
3211+--
3212+-- >>> lCompactGE n = Fold.many (MutArray.fCompactGE n)
3213+--
3214+-- Generates unpinned arrays irrespective of the pinning status of input
3215+-- arrays.
3216+{-# INLINE lCompactGE #-}
3217+lCompactGE :: forall m a. (MonadIO m, Unbox a)
3218+ => Int -> Fold m (MutArray a) () -> Fold m (MutArray a) ()
3219+lCompactGE = lCompactGeAs Unpinned
3220+
3221+-- | Pinned version of 'lCompactGE'.
3222+{-# INLINE lPinnedCompactGE #-}
3223+lPinnedCompactGE :: forall m a. (MonadIO m, Unbox a)
3224+ => Int -> Fold m (MutArray a) () -> Fold m (MutArray a) ()
3225+lPinnedCompactGE = lCompactGeAs Pinned
3226+
3227+-- | @compactGE n stream@ coalesces adjacent arrays in the @stream@ until
3228+-- the size becomes greater than or equal to @n@.
3229+--
3230+-- >>> compactGE n = Stream.foldMany (MutArray.fCompactGE n)
3231+--
3232+{-# INLINE compactGE #-}
3233+compactGE ::
3234+ (MonadIO m, Unbox a)
3235+ => Int -> Stream m (MutArray a) -> Stream m (MutArray a)
3236+compactGE n = D.foldMany (fCompactGE n)
3237+
3238+-- | 'compactEQ n' coalesces adajacent arrays in the input stream to
3239+-- arrays of exact size @n@.
3240+--
3241+-- /Unimplemented/
3242+{-# INLINE compactEQ #-}
3243+compactEQ :: -- (MonadIO m, Unbox a) =>
3244+ Int -> Stream m (MutArray a) -> Stream m (MutArray a)
3245+compactEQ _n = undefined -- D.parseManyD (pCompactEQ n)
23893246
23903247-------------------------------------------------------------------------------
2391−-- NFData
3248+-- In-place mutation algorithms
23923249-------------------------------------------------------------------------------
23933250
23943251-- | Strip elements which match with predicate from both ends.
@@ -2417,7 +3274,7 @@ strip eq arr@MutArray{..} = liftIO $ do
24173274 getStart cur = do
24183275 if cur < arrEnd
24193276 then do
2420− r <- peekByteIndex cur arrContents
3277+ r <- peekAt cur arrContents
24213278 if eq r
24223279 then getStart (INDEX_NEXT(cur,a))
24233280 else return cur
@@ -2427,7 +3284,7 @@ strip eq arr@MutArray{..} = liftIO $ do
24273284 if cur > low
24283285 then do
24293286 let prev = INDEX_PREV(cur,a)
2430− r <- peekByteIndex prev arrContents
3287+ r <- peekAt prev arrContents
24313288 if eq r
24323289 then getLast prev low
24333290 else return cur