@@ -40,22 +40,22 @@ module Streamly.Internal.Data.MutArray.Type
4040
4141 -- ** Casting
4242 , cast
43− , castUnsafe -- XXX unsafeCast
43+ , castUnsafe
4444 , asBytes
45− , unsafePinnedAsPtr
46− , unsafeAsPtr
45+ , asPtrUnsafe
46+ , asUnpinnedPtrUnsafe
4747
4848 -- ** Construction
49− , empty
49+ , nil
5050
5151 -- *** New
5252 -- | New arrays are always empty arrays with some reserve capacity to
5353 -- extend the length without reallocating.
54− , emptyOf
55− , newArrayWith -- emptyAlignedWith
56− , pinnedEmptyOf
57− , pinnedNewAligned -- XXX not required
58− -- , new -- uninitialized array of specified length
54+ , new
55+ , newArrayWith
56+ , pinnedNew
57+ , pinnedNewBytes
58+ , pinnedNewAligned
5959
6060 -- *** Cloning
6161 , clone
@@ -63,25 +63,27 @@ module Streamly.Internal.Data.MutArray.Type
6363
6464 -- *** Slicing
6565 -- | Get a subarray without copying
66− , getSliceUnsafe -- XXX unsafeGetSlice
66+ , getSliceUnsafe
6767 , getSlice
6868 , splitAt -- XXX should be able to express using getSlice
6969 , breakOn
7070
7171 -- *** Stream Folds
7272 , ArrayUnsafe (..)
73− , unsafeCreateOfWith
74− , unsafeCreateOf
75− , unsafePinnedCreateOf
76− , pinnedCreateOf
77− , createOfWith
78− , createOf
79− , revCreateOf
80−
81− , pinnedCreate
82− , createWith
83− , create
84− -- , revCreate
73+ , writeNWithUnsafe
74+ , writeNWith
75+ , writeNUnsafe
76+ , pinnedWriteNUnsafe
77+ , writeN
78+ , pinnedWriteN
79+ , pinnedWriteNAligned
80+
81+ , writeWith
82+ , write
83+ , pinnedWrite
84+
85+ , writeRevN
86+ -- , writeRev
8587
8688 -- *** From containers
8789 , fromListN
@@ -97,11 +99,11 @@ module Streamly.Internal.Data.MutArray.Type
9799 , fromByteStr#
98100 , fromPtrN
99101 , fromChunksK
100− , fromChunksRealloced -- fromSmallChunks
102+ , fromChunksRealloced
101103
102104 -- ** Random writes
103105 , putIndex
104− , putIndexUnsafe -- XXX unsafePutIndex
106+ , putIndexUnsafe
105107 , putIndices
106108 -- , putFromThenTo
107109 -- , putFrom -- start writing at the given position
@@ -109,7 +111,7 @@ module Streamly.Internal.Data.MutArray.Type
109111 -- , putFromTo
110112 -- , putFromRev
111113 -- , putUptoRev
112− , modifyIndexUnsafe -- XXX unsafeModifyIndex
114+ , modifyIndexUnsafe
113115 , modifyIndex
114116 , modifyIndices
115117 , modify
@@ -120,9 +122,9 @@ module Streamly.Internal.Data.MutArray.Type
120122
121123 -- *** Indexing
122124 , getIndex
123− , getIndexUnsafe -- XXX unsafeGetIndex
125+ , getIndexUnsafe
124126 -- , getFromThenTo
125− , getIndexRev -- getRevIndex?
127+ , getIndexRev
126128 , indexReader
127129 , indexReaderWith
128130
@@ -162,9 +164,9 @@ module Streamly.Internal.Data.MutArray.Type
162164 , blockSize
163165 , arrayChunkBytes
164166 , allocBytesToElemCount
165− , realloc -- this is "resize"
166− , grow
167− , growExp
167+ , realloc
168+ , resize
169+ , resizeExp
168170 , rightSize
169171
170172 -- ** Folding
@@ -193,34 +195,24 @@ module Streamly.Internal.Data.MutArray.Type
193195 , snoc
194196 , snocLinear
195197 , snocMay
196− , snocUnsafe -- XXX unsafeSnoc
198+ , snocUnsafe
197199
198200 -- *** Appending streams
199− , unsafeAppendN
200− , appendN
201− , appendWith
202− , append
201+ , writeAppendNUnsafe
202+ , writeAppendN
203+ , writeAppendWith
204+ , writeAppend
203205
204206 -- *** Appending arrays
205207 , spliceCopy
206208 , spliceWith
207209 , splice
208210 , spliceExp
209− , spliceUnsafe -- XXX unsafeSplice
211+ , spliceUnsafe
210212 -- , putSlice
211213 -- , appendSlice
212214 -- , appendSliceFrom
213215
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−
224216 -- Arrays of arrays
225217 -- We can add dimensionality parameter to the array type to get
226218 -- multidimensional arrays. Multidimensional arrays would just be a
@@ -242,8 +234,6 @@ module Streamly.Internal.Data.MutArray.Type
242234
243235 -- *** Concat
244236 -- | Append the arrays in a stream to form a stream of elements.
245− , concatWith
246− , concatRevWith
247237 , concat
248238 , concatRev
249239
@@ -251,12 +241,9 @@ module Streamly.Internal.Data.MutArray.Type
251241 -- | Append the arrays in a stream to form a stream of larger arrays.
252242 , SpliceState (..)
253243 , pCompactLE
254− , pPinnedCompactLE
255− , compactLeAs
244+ , rCompactLE
256245 , fCompactGE
257− , fPinnedCompactGE
258246 , lCompactGE
259− , lPinnedCompactGE
260247 , compactGE
261248 , compactEQ
262249
@@ -267,7 +254,6 @@ module Streamly.Internal.Data.MutArray.Type
267254 , c_memchr
268255
269256 -- * Deprecated
270− , asPtrUnsafe
271257 , writeChunks
272258 , flattenArrays
273259 , flattenArraysRev
@@ -277,27 +263,6 @@ module Streamly.Internal.Data.MutArray.Type
277263 , cmp
278264 , getIndices
279265 , 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
301266 )
302267where
303268
@@ -479,8 +444,6 @@ isPinned MutArray{..} = Unboxed.isPinned arrContents
479444-- we need more than that. See stg_pinnedNewAlignedByteArrayzh and
480445-- allocatePinned in GHC source.
481446
482−-- XXX Rename to emptyAlignedWith, alignSize should be first arg.
483−
484447-- | @newArrayWith allocator alignment count@ allocates a new array of zero
485448-- length and with a capacity to hold @count@ elements, using @allocator
486449-- size alignment@ as the memory allocator function.
@@ -504,25 +467,12 @@ newArrayWith alloc alignSize count = do
504467 , arrBound = size
505468 }
506469
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." #-}
520470nil ::
521471#ifdef DEVBUILD
522472 Unbox a =>
523473#endif
524474 MutArray a
525−nil = empty
475+nil = MutArray Unboxed.nil 0 0 0
526476
527477{-# INLINE newBytesAs #-}
528478newBytesAs :: MonadIO m =>
@@ -539,13 +489,12 @@ newBytesAs ps bytes = do
539489 , arrBound = bytes
540490 }
541491
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.
492+-- | Allocates a pinned empty array that can hold 'count' items. The memory of
493+-- the array is uninitialized and the allocation is aligned as per the
494+-- 'Unboxed' instance of the type.
545495--
546496-- /Pre-release/
547497{-# INLINE pinnedNewBytes #-}
548−{-# DEPRECATED pinnedNewBytes "Please use pinnedEmptyOf with appropriate calculation" #-}
549498pinnedNewBytes :: MonadIO m =>
550499#ifdef DEVBUILD
551500 Unbox a =>
@@ -570,31 +519,21 @@ newAs ps =
570519 (error "new: alignment is not used in unpinned arrays.")
571520
572521-- XXX can unaligned allocation be more efficient when alignment is not needed?
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." #-}
522+--
523+-- | Allocates an empty pinned array that can hold 'count' items. The memory of
524+-- the array is uninitialized and the allocation is aligned as per the 'Unboxed'
525+-- instance of the type.
526+--
582527{-# INLINE pinnedNew #-}
583528pinnedNew :: forall m a. (MonadIO m, Unbox a) => Int -> m (MutArray a)
584−pinnedNew = pinnedEmptyOf
529+pinnedNew = newAs Pinned
585530
586−-- | Allocates an unpinned array of zero length but growable to the specified
587−-- capacity without reallocation.
531+-- | Allocates an empty unpinned array that can hold 'count' items. The memory
532+-- of the array is uninitialized.
588533--
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." #-}
595534{-# INLINE new #-}
596535new :: (MonadIO m, Unbox a) => Int -> m (MutArray a)
597−new = emptyOf
536+new = newAs Unpinned
598537
599538-------------------------------------------------------------------------------
600539-- Random writes
@@ -842,15 +781,15 @@ roundDownTo elemSize size = size - (size `mod` elemSize)
842781-- Since this is not inlined Unboxed consrraint leads to dictionary passing
843782-- which complicates some inspection tests.
844783--
845−{-# NOINLINE reallocExplicitAs #-}
846−reallocExplicitAs :: PinnedState -> Int -> Int -> MutArray a -> IO (MutArray a)
847−reallocExplicitAs ps elemSize newCapacityInBytes MutArray{..} = do
784+{-# NOINLINE reallocExplicit #-}
785+reallocExplicit :: Int -> Int -> MutArray a -> IO (MutArray a)
786+reallocExplicit elemSize newCapacityInBytes MutArray{..} = do
848787 assertM(arrEnd <= arrBound)
849788
850789 -- Allocate new array
851790 let newCapMaxInBytes = roundUpLargeArray newCapacityInBytes
852791 contents <-
853− if ps == Pinned
792+ if Unboxed.isPinned arrContents
854793 then Unboxed.pinnedNew newCapMaxInBytes
855794 else Unboxed.new newCapMaxInBytes
856795 let !(MutByteArray mbarrFrom#) = arrContents
@@ -890,12 +829,7 @@ reallocExplicitAs ps elemSize newCapacityInBytes MutArray{..} = do
890829-- If the original array is pinned, the newly allocated array is also pinned.
891830{-# INLINABLE realloc #-}
892831realloc :: forall m a. (MonadIO m, Unbox a) => Int -> MutArray a -> m (MutArray a)
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
832+realloc bytes arr = liftIO $ reallocExplicit (SIZE_OF(a)) bytes arr
899833
900834-- | @reallocWith label capSizer minIncrBytes array@. The label is used
901835-- in error messages and the capSizer is used to determine the capacity of the
@@ -925,7 +859,9 @@ reallocWith label capSizer minIncrBytes arr = do
925859 , ". Please check the sizing function passed."
926860 ]
927861
928−-- | @grow newCapacity array@ changes the total capacity of the array so that
862+-- XXX should be called expand/extend because it never shortens the array.
863+
864+-- | @resize newCapacity array@ changes the total capacity of the array so that
929865-- it is enough to hold the specified number of elements. Nothing is done if
930866-- the specified capacity is less than the length of the array.
931867--
@@ -933,46 +869,36 @@ reallocWith label capSizer minIncrBytes arr = do
933869-- the block size (4K).
934870--
935871-- /Pre-release/
936−{-# INLINE grow #-}
937−grow :: forall m a. (MonadIO m, Unbox a) =>
872+{-# INLINE resize #-}
873+resize :: forall m a. (MonadIO m, Unbox a) =>
938874 Int -> MutArray a -> m (MutArray a)
939−grow nElems arr@MutArray{..} = do
875+resize nElems arr@MutArray{..} = do
940876 let req = SIZE_OF(a) * nElems
941− cap = arrBound - arrStart
942− if req < cap
877+ -- XXX Should use arrBound
878+ len = arrEnd - arrStart
879+ if req < len
943880 then return arr
944881 else realloc req arr
945882
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
883+-- | Like 'resize' but if the requested byte capacity is more than
953884-- 'largeObjectThreshold' then it is rounded up to the closest power of 2.
954885--
955886-- /Pre-release/
956−{-# INLINE growExp #-}
957−growExp :: forall m a. (MonadIO m, Unbox a) =>
887+{-# INLINE resizeExp #-}
888+resizeExp :: forall m a. (MonadIO m, Unbox a) =>
958889 Int -> MutArray a -> m (MutArray a)
959−growExp nElems arr@MutArray{..} = do
890+resizeExp nElems arr@MutArray{..} = do
960891 let req = roundUpLargeArray (SIZE_OF(a) * nElems)
961892 req1 =
962893 if req > largeObjectThreshold
963894 then roundUpToPower2 req
964895 else req
965− cap = arrBound - arrStart
966− if req1 < cap
896+ -- XXX Should use arrBound
897+ len = arrEnd - arrStart
898+ if req1 < len
967899 then return arr
968900 else realloc req1 arr
969901
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−
976902-- | Resize the allocated memory to drop any reserved free space at the end of
977903-- the array and reallocate it to reduce wastage.
978904--
@@ -1117,126 +1043,6 @@ snoc = snocWith f
11171043 then oldSize * 2
11181044 else roundUpToPower2 oldSize * 2
11191045
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−
12401046-------------------------------------------------------------------------------
12411047-- Random reads
12421048-------------------------------------------------------------------------------
@@ -1302,7 +1108,6 @@ indexReaderWith liftio (D.Stream stepi sti) = Unfold step inject
13021108 D.Stop -> return D.Stop
13031109
13041110{-# DEPRECATED getIndicesWith "Please use indexReaderWith instead." #-}
1305−{-# INLINE getIndicesWith #-}
13061111getIndicesWith :: (Monad m, Unbox a) =>
13071112 (forall b. IO b -> m b) -> D.Stream m Int -> Unfold m (MutArray a) a
13081113getIndicesWith = indexReaderWith
@@ -1318,7 +1123,6 @@ indexReader = indexReaderWith liftIO
13181123
13191124-- XXX DO NOT REMOVE, change the signature to use Stream instead of unfold
13201125{-# DEPRECATED getIndices "Please use indexReader instead." #-}
1321−{-# INLINE getIndices #-}
13221126getIndices :: (MonadIO m, Unbox a) => Stream m Int -> Unfold m (MutArray a) a
13231127getIndices = indexReader
13241128
@@ -1615,7 +1419,7 @@ chunksOfAs ps n (D.Stream step state) =
16151419--
16161420-- Same as the following but may be more efficient:
16171421--
1618−-- >>> chunksOf n = Stream.foldMany (MutArray.createOf n)
1422+-- >>> chunksOf n = Stream.foldMany (MutArray.writeN n)
16191423--
16201424-- /Pre-release/
16211425{-# INLINE_NORMAL chunksOf #-}
@@ -1624,14 +1428,14 @@ chunksOf :: forall m a. (MonadIO m, Unbox a)
16241428-- XXX the idiomatic implementation leads to large regression in the D.reverse'
16251429-- benchmark. It seems it has difficulty producing optimized code when
16261430-- converting to StreamK. Investigate GHC optimizations.
1627−-- chunksOf n = D.foldMany (createOf n)
1431+-- chunksOf n = D.foldMany (writeN n)
16281432chunksOf = chunksOfAs Unpinned
16291433
16301434-- | Like 'chunksOf' but creates pinned arrays.
16311435{-# INLINE_NORMAL pinnedChunksOf #-}
16321436pinnedChunksOf :: forall m a. (MonadIO m, Unbox a)
16331437 => Int -> D.Stream m a -> D.Stream m (MutArray a)
1634−-- pinnedChunksOf n = D.foldMany (pinnedCreateOf n)
1438+-- pinnedChunksOf n = D.foldMany (pinnedWriteN n)
16351439pinnedChunksOf = chunksOfAs Pinned
16361440
16371441-- | When we are buffering a stream of unknown size into an array we do not
@@ -1664,10 +1468,16 @@ data FlattenState s contents a =
16641468 OuterLoop s
16651469 | InnerLoop s contents !Int !Int
16661470
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)
1471+-- | Use the "reader" unfold instead.
1472+--
1473+-- @concat = unfoldMany reader@
1474+--
1475+-- We can try this if there are any fusion issues in the unfold.
1476+--
1477+{-# INLINE_NORMAL concat #-}
1478+concat :: forall m a. (MonadIO m, Unbox a)
1479+ => D.Stream m (MutArray a) -> D.Stream m a
1480+concat (D.Stream step state) = D.Stream step' (OuterLoop state)
16711481
16721482 where
16731483
@@ -1684,30 +1494,24 @@ concatWith liftio (D.Stream step state) = D.Stream step' (OuterLoop state)
16841494 return $ D.Skip $ OuterLoop st
16851495
16861496 step' _ (InnerLoop st contents p end) = do
1687− x <- liftio $ peekAt p contents
1497+ x <- liftIO $ peekAt p contents
16881498 return $ D.Yield x (InnerLoop st contents (INDEX_NEXT(p,a)) end)
16891499
1690−-- | Use the "reader" unfold instead.
1691−--
1692−-- @concat = unfoldMany reader@
1693−--
1694−-- We can try this if there are any fusion issues in the unfold.
1695−--
1696−{-# INLINE_NORMAL concat #-}
1697−concat :: forall m a. (MonadIO m, Unbox a)
1698− => D.Stream m (MutArray a) -> D.Stream m a
1699−concat = concatWith liftIO
1700−
17011500{-# DEPRECATED flattenArrays "Please use \"unfoldMany reader\" instead." #-}
1702−{-# INLINE flattenArrays #-}
17031501flattenArrays :: forall m a. (MonadIO m, Unbox a)
17041502 => D.Stream m (MutArray a) -> D.Stream m a
17051503flattenArrays = concat
17061504
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)
1505+-- | Use the "readerRev" unfold instead.
1506+--
1507+-- @concat = unfoldMany readerRev@
1508+--
1509+-- We can try this if there are any fusion issues in the unfold.
1510+--
1511+{-# INLINE_NORMAL concatRev #-}
1512+concatRev :: forall m a. (MonadIO m, Unbox a)
1513+ => D.Stream m (MutArray a) -> D.Stream m a
1514+concatRev (D.Stream step state) = D.Stream step' (OuterLoop state)
17111515
17121516 where
17131517
@@ -1725,23 +1529,11 @@ concatRevWith liftio (D.Stream step state) = D.Stream step' (OuterLoop state)
17251529 return $ D.Skip $ OuterLoop st
17261530
17271531 step' _ (InnerLoop st contents p start) = do
1728− x <- liftio $ peekAt p contents
1532+ x <- liftIO $ peekAt p contents
17291533 let cur = INDEX_PREV(p,a)
17301534 return $ D.Yield x (InnerLoop st contents cur start)
17311535
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−
17431536{-# DEPRECATED flattenArraysRev "Please use \"unfoldMany readerRev\" instead." #-}
1744−{-# INLINE flattenArraysRev #-}
17451537flattenArraysRev :: forall m a. (MonadIO m, Unbox a)
17461538 => D.Stream m (MutArray a) -> D.Stream m a
17471539flattenArraysRev = concatRev
@@ -1973,7 +1765,7 @@ foldr f z arr = D.foldr f z $ read arr
19731765
19741766-- XXX Keep the bound intact to not lose any free space? Perf impact?
19751767
1976−-- | @unsafeAppendN n arr@ appends up to @n@ input items to the supplied
1768+-- | @writeAppendNUnsafe n arr@ appends up to @n@ input items to the supplied
19771769-- array.
19781770--
19791771-- Unsafe: Do not drive the fold beyond @n@ elements, it will lead to memory
@@ -1982,12 +1774,13 @@ foldr f z arr = D.foldr f z $ read arr
19821774-- Any free space left in the array after appending @n@ elements is lost.
19831775--
19841776-- /Internal/
1985−{-# INLINE_NORMAL unsafeAppendN #-}
1986−unsafeAppendN :: forall m a. (MonadIO m, Unbox a) =>
1777+{-# INLINE_NORMAL writeAppendNUnsafe #-}
1778+writeAppendNUnsafe :: forall m a. (MonadIO m, Unbox a) =>
19871779 Int
19881780 -> m (MutArray a)
19891781 -> Fold m a (MutArray a)
1990−unsafeAppendN n action = fmap fromArrayUnsafe $ FL.foldlM' step initial
1782+writeAppendNUnsafe n action =
1783+ fmap fromArrayUnsafe $ FL.foldlM' step initial
19911784
19921785 where
19931786
@@ -2000,7 +1793,7 @@ unsafeAppendN n action = fmap fromArrayUnsafe $ FL.foldlM' step initial
20001793 -- otherwise we lose that space.
20011794 arr1 <-
20021795 if free < needed
2003− then noinline reallocWith "unsafeAppendN" (+ needed) needed arr
1796+ then noinline reallocWith "writeAppendNUnsafeWith" (+ needed) needed arr
20041797 else return arr
20051798 return $ toArrayUnsafe arr1
20061799
@@ -2008,51 +1801,30 @@ unsafeAppendN n action = fmap fromArrayUnsafe $ FL.foldlM' step initial
20081801 liftIO $ pokeAt end contents x
20091802 return $ ArrayUnsafe contents start (INDEX_NEXT(end,a))
20101803
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−
20191804-- | Append @n@ elements to an existing array. Any free space left in the array
20201805-- after appending @n@ elements is lost.
20211806--
2022−-- >>> appendN n initial = Fold.take n (MutArray.unsafeAppendN n initial)
1807+-- >>> writeAppendN n initial = Fold.take n (MutArray.writeAppendNUnsafe n initial)
20231808--
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 #-}
1809+{-# INLINE_NORMAL writeAppendN #-}
20321810writeAppendN :: forall m a. (MonadIO m, Unbox a) =>
20331811 Int -> m (MutArray a) -> Fold m a (MutArray a)
2034−writeAppendN = appendN
1812+writeAppendN n initial = FL.take n (writeAppendNUnsafe n initial)
20351813
2036−-- | @appendWith realloc action@ mutates the array generated by @action@ to
1814+-- | @writeAppendWith realloc action@ mutates the array generated by @action@ to
20371815-- append the input stream. If there is no reserved space available in the
20381816-- array it is reallocated to a size in bytes determined by @realloc oldSize@,
20391817-- where @oldSize@ is the current size of the array in bytes.
20401818--
20411819-- Note that the returned array may be a mutated version of original array.
20421820--
2043−-- >>> appendWith sizer = Fold.foldlM' (MutArray.snocWith sizer)
1821+-- >>> writeAppendWith sizer = Fold.foldlM' (MutArray.snocWith sizer)
20441822--
20451823-- /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." #-}
20521824{-# INLINE writeAppendWith #-}
20531825writeAppendWith :: forall m a. (MonadIO m, Unbox a) =>
20541826 (Int -> Int) -> m (MutArray a) -> Fold m a (MutArray a)
2055−writeAppendWith = appendWith
1827+writeAppendWith sizer = FL.foldlM' (snocWith sizer)
20561828
20571829-- | @append action@ mutates the array generated by @action@ to append the
20581830-- input stream. If there is no reserved space available in the array it is
@@ -2060,33 +1832,26 @@ writeAppendWith = appendWith
20601832--
20611833-- Note that the returned array may be a mutated version of original array.
20621834--
2063−-- >>> append = MutArray.appendWith (* 2)
1835+-- >>> writeAppend = MutArray.writeAppendWith (* 2)
20641836--
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." #-}
20721837{-# INLINE writeAppend #-}
20731838writeAppend :: forall m a. (MonadIO m, Unbox a) =>
20741839 m (MutArray a) -> Fold m a (MutArray a)
2075−writeAppend = append
1840+writeAppend = writeAppendWith (* 2)
20761841
20771842-- XXX We can carry bound as well in the state to make sure we do not lose the
20781843-- remaining capacity. Need to check perf impact.
20791844--
2080−-- | Like 'unsafeCreateOf' but takes a new array allocator @alloc size@
2081−-- function as argument.
1845+-- | Like 'writeNUnsafe' but takes a new array allocator @alloc size@ function
1846+-- as argument.
20821847--
2083−-- >>> unsafeCreateOfWith alloc n = MutArray.unsafeAppendN (alloc n) n
1848+-- >>> writeNWithUnsafe alloc n = MutArray.writeAppendNUnsafe (alloc n) n
20841849--
20851850-- /Pre-release/
2086−{-# INLINE_NORMAL unsafeCreateOfWith #-}
2087−unsafeCreateOfWith :: forall m a. (MonadIO m, Unbox a)
1851+{-# INLINE_NORMAL writeNWithUnsafe #-}
1852+writeNWithUnsafe :: forall m a. (MonadIO m, Unbox a)
20881853 => (Int -> m (MutArray a)) -> Int -> Fold m a (MutArray a)
2089−unsafeCreateOfWith alloc n = fromArrayUnsafe <$> FL.foldlM' step initial
1854+writeNWithUnsafe alloc n = fromArrayUnsafe <$> FL.foldlM' step initial
20901855
20911856 where
20921857
@@ -2097,64 +1862,40 @@ unsafeCreateOfWith alloc n = fromArrayUnsafe <$> FL.foldlM' step initial
20971862 return
20981863 $ ArrayUnsafe contents start (INDEX_NEXT(end,a))
20991864
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−
21061865{-# INLINE_NORMAL writeNUnsafeAs #-}
21071866writeNUnsafeAs :: forall m a. (MonadIO m, Unbox a)
21081867 => PinnedState -> Int -> Fold m a (MutArray a)
2109−writeNUnsafeAs ps = unsafeCreateOfWith (newAs ps)
1868+writeNUnsafeAs ps = writeNWithUnsafe (newAs ps)
21101869
2111−-- | Like 'createOf' but does not check the array bounds when writing. The fold
1870+-- | Like 'writeN' but does not check the array bounds when writing. The fold
21121871-- driver must not call the step function more than 'n' times otherwise it will
21131872-- corrupt the memory and crash. This function exists mainly because any
21141873-- conditional in the step function blocks fusion causing 10x performance
21151874-- slowdown.
21161875--
2117−-- >>> unsafeCreateOf = MutArray.unsafeCreateOfWith MutArray.emptyOf
1876+-- >>> writeNUnsafe = MutArray.writeNWithUnsafe MutArray.new
21181877--
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 #-}
1878+{-# INLINE_NORMAL writeNUnsafe #-}
21261879writeNUnsafe :: forall m a. (MonadIO m, Unbox a)
21271880 => Int -> Fold m a (MutArray a)
2128−writeNUnsafe = unsafeCreateOf
2129−
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
1881+writeNUnsafe = writeNUnsafeAs Unpinned
21351882
2136−{-# DEPRECATED pinnedWriteNUnsafe "Please use unsafePinnedCreateOf instead." #-}
2137−{-# INLINE pinnedWriteNUnsafe #-}
1883+-- | Like 'writeNUnsafe' but creates a pinned array.
1884+{-# INLINE_NORMAL pinnedWriteNUnsafe #-}
21381885pinnedWriteNUnsafe :: forall m a. (MonadIO m, Unbox a)
21391886 => Int -> Fold m a (MutArray a)
2140−pinnedWriteNUnsafe = unsafePinnedCreateOf
1887+pinnedWriteNUnsafe = writeNUnsafeAs Pinned
21411888
2142−-- | @createOfWith alloc n@ folds a maximum of @n@ elements into an array
1889+-- | @writeNWith alloc n@ folds a maximum of @n@ elements into an array
21431890-- allocated using the @alloc@ function.
21441891--
2145−-- >>> createOfWith alloc n = Fold.take n (MutArray.unsafeCreateOfWith alloc n)
2146−-- >>> createOfWith alloc n = MutArray.appendN (alloc n) n
1892+-- >>> writeNWith alloc n = Fold.take n (MutArray.writeNWithUnsafe alloc n)
1893+-- >>> writeNWith alloc n = MutArray.writeAppendN (alloc n) n
21471894--
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 #-}
1895+{-# INLINE_NORMAL writeNWith #-}
21551896writeNWith :: forall m a. (MonadIO m, Unbox a)
21561897 => (Int -> m (MutArray a)) -> Int -> Fold m a (MutArray a)
2157−writeNWith = createOfWith
1898+writeNWith alloc n = FL.take n (writeNWithUnsafe alloc n)
21581899
21591900{-# INLINE_NORMAL writeNAs #-}
21601901writeNAs ::
@@ -2162,42 +1903,28 @@ writeNAs ::
21621903 => PinnedState
21631904 -> Int
21641905 -> Fold m a (MutArray a)
2165−writeNAs ps = createOfWith (newAs ps)
1906+writeNAs ps = writeNWith (newAs ps)
21661907
2167−-- | @createOf n@ folds a maximum of @n@ elements from the input stream to an
1908+-- | @writeN n@ folds a maximum of @n@ elements from the input stream to an
21681909-- 'MutArray'.
21691910--
2170−-- >>> createOf = MutArray.createOfWith MutArray.new
2171−-- >>> createOf n = Fold.take n (MutArray.unsafeCreateOf n)
2172−-- >>> createOf n = MutArray.appendN n (MutArray.emptyOf n)
1911+-- >>> writeN = MutArray.writeNWith MutArray.new
1912+-- >>> writeN n = Fold.take n (MutArray.writeNUnsafe n)
1913+-- >>> writeN n = MutArray.writeAppendN n (MutArray.new n)
21731914--
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 #-}
1915+{-# INLINE_NORMAL writeN #-}
21811916writeN :: forall m a. (MonadIO m, Unbox a) => Int -> Fold m a (MutArray a)
2182−writeN = createOf
1917+writeN = writeNAs Unpinned
21831918
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
2191−
2192−{-# DEPRECATED pinnedWriteN "Please use pinnedCreateOf instead." #-}
2193−{-# INLINE pinnedWriteN #-}
1919+-- | Like 'writeN' but creates a pinned array.
1920+{-# INLINE_NORMAL pinnedWriteN #-}
21941921pinnedWriteN ::
21951922 forall m a. (MonadIO m, Unbox a)
21961923 => Int
21971924 -> Fold m a (MutArray a)
2198−pinnedWriteN = pinnedCreateOf
1925+pinnedWriteN = writeNAs Pinned
21991926
2200−-- | Like unsafeCreateOfWith but writes the array in reverse order.
1927+-- | Like writeNWithUnsafe but writes the array in reverse order.
22011928--
22021929-- /Internal/
22031930{-# INLINE_NORMAL writeRevNWithUnsafe #-}
@@ -2218,7 +1945,7 @@ writeRevNWithUnsafe alloc n = fromArrayUnsafe <$> FL.foldlM' step initial
22181945 return
22191946 $ ArrayUnsafe contents ptr end
22201947
2221−-- | Like createOfWith but writes the array in reverse order.
1948+-- | Like writeNWith but writes the array in reverse order.
22221949--
22231950-- /Internal/
22241951{-# INLINE_NORMAL writeRevNWith #-}
@@ -2226,36 +1953,31 @@ writeRevNWith :: forall m a. (MonadIO m, Unbox a)
22261953 => (Int -> m (MutArray a)) -> Int -> Fold m a (MutArray a)
22271954writeRevNWith alloc n = FL.take n (writeRevNWithUnsafe alloc n)
22281955
2229−-- | Like 'createOf' but writes the array in reverse order.
1956+-- | Like writeN but writes the array in reverse order.
22301957--
22311958-- /Pre-release/
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 #-}
1959+{-# INLINE_NORMAL writeRevN #-}
22381960writeRevN :: forall m a. (MonadIO m, Unbox a) => Int -> Fold m a (MutArray a)
2239−writeRevN = revCreateOf
1961+writeRevN = writeRevNWith new
22401962
22411963-- | @pinnedWriteNAligned align n@ folds a maximum of @n@ elements from the
22421964-- input stream to a 'MutArray' aligned to the given size.
22431965--
2244−-- >>> pinnedWriteNAligned align = MutArray.createOfWith (MutArray.pinnedNewAligned align)
2245−-- >>> pinnedWriteNAligned align n = MutArray.appendN n (MutArray.pinnedNewAligned align n)
1966+-- >>> pinnedWriteNAligned align = MutArray.writeNWith (MutArray.pinnedNewAligned align)
1967+-- >>> pinnedWriteNAligned align n = MutArray.writeAppendN n (MutArray.pinnedNewAligned align n)
22461968--
22471969-- /Pre-release/
22481970--
22491971{-# INLINE_NORMAL pinnedWriteNAligned #-}
22501972pinnedWriteNAligned :: forall m a. (MonadIO m, Unbox a)
22511973 => Int -> Int -> Fold m a (MutArray a)
2252−pinnedWriteNAligned align = createOfWith (pinnedNewAligned align)
1974+pinnedWriteNAligned align = writeNWith (pinnedNewAligned align)
22531975
22541976-- XXX Buffer to a list instead?
22551977
22561978-- | Buffer a stream into a stream of arrays.
22571979--
2258−-- >>> buildChunks n = Fold.many (MutArray.createOf n) Fold.toStreamK
1980+-- >>> buildChunks n = Fold.many (MutArray.writeN n) Fold.toStreamK
22591981--
22601982-- Breaking an array into an array stream can be useful to consume a large
22611983-- array sequentially such that memory of the array is released incrementatlly.
@@ -2267,10 +1989,9 @@ pinnedWriteNAligned align = createOfWith (pinnedNewAligned align)
22671989{-# INLINE_NORMAL buildChunks #-}
22681990buildChunks :: (MonadIO m, Unbox a) =>
22691991 Int -> Fold m a (StreamK n (MutArray a))
2270−buildChunks n = FL.many (createOf n) FL.toStreamK
1992+buildChunks n = FL.many (writeN n) FL.toStreamK
22711993
22721994{-# DEPRECATED writeChunks "Please use buildChunks instead." #-}
2273−{-# INLINE writeChunks #-}
22741995writeChunks :: (MonadIO m, Unbox a) =>
22751996 Int -> Fold m a (StreamK n (MutArray a))
22761997writeChunks = buildChunks
@@ -2278,29 +1999,29 @@ writeChunks = buildChunks
22781999{-# INLINE_NORMAL writeWithAs #-}
22792000writeWithAs :: forall m a. (MonadIO m, Unbox a)
22802001 => PinnedState -> Int -> Fold m a (MutArray a)
2281−-- writeWithAs ps n = FL.rmapM rightSize $ appendWith (* 2) (newAs ps n)
2002+-- writeWithAs ps n = FL.rmapM rightSize $ writeAppendWith (* 2) (newAs ps n)
22822003writeWithAs ps elemCount =
22832004 FL.rmapM extract $ FL.foldlM' step initial
22842005
22852006 where
22862007
22872008 initial = do
2288− when (elemCount < 0) $ error "createWith: elemCount is negative"
2009+ when (elemCount < 0) $ error "writeWith: elemCount is negative"
22892010 newAs ps elemCount
22902011
22912012 step arr@(MutArray _ start end bound) x
22922013 | INDEX_NEXT(end,a) > bound = do
22932014 let oldSize = end - start
22942015 newSize = max (oldSize * 2) 1
2295− arr1 <- liftIO $ reallocExplicitAs ps (SIZE_OF(a)) newSize arr
2016+ arr1 <- liftIO $ reallocExplicit (SIZE_OF(a)) newSize arr
22962017 snocUnsafe arr1 x
22972018 step arr x = snocUnsafe arr x
22982019
22992020 extract = liftIO . rightSize
23002021
2301−-- XXX Compare createWith with fromStreamD which uses an array of streams
2022+-- XXX Compare writeWith with fromStreamD which uses an array of streams
23022023-- implementation. We can write this using buildChunks above if that is faster.
2303−-- If createWith is faster then we should use that to implement
2024+-- If writeWith is faster then we should use that to implement
23042025-- fromStreamD.
23052026--
23062027-- XXX The realloc based implementation needs to make one extra copy if we use
@@ -2315,56 +2036,39 @@ writeWithAs ps elemCount =
23152036-- XXX check if GHC's memory allocator is efficient enough. We can try the C
23162037-- malloc to compare against.
23172038
2318−-- | @createWith minCount@ folds the whole input to a single array. The array
2039+-- | @writeWith minCount@ folds the whole input to a single array. The array
23192040-- starts at a size big enough to hold minCount elements, the size is doubled
23202041-- every time the array needs to be grown.
23212042--
23222043-- /Caution! Do not use this on infinite streams./
23232044--
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)
2045+-- >>> f n = MutArray.writeAppendWith (* 2) (MutArray.new n)
2046+-- >>> writeWith n = Fold.rmapM MutArray.rightSize (f n)
2047+-- >>> writeWith n = Fold.rmapM MutArray.fromChunksK (MutArray.buildChunks n)
23272048--
23282049-- /Pre-release/
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 #-}
2050+{-# INLINE_NORMAL writeWith #-}
23372051writeWith :: forall m a. (MonadIO m, Unbox a)
23382052 => Int -> Fold m a (MutArray a)
2339−writeWith = createWith
2053+-- writeWith n = FL.rmapM rightSize $ writeAppendWith (* 2) (new n)
2054+writeWith = writeWithAs Unpinned
23402055
23412056-- | Fold the whole input to a single array.
23422057--
2343−-- Same as 'createWith' using an initial array size of 'arrayChunkBytes' bytes
2058+-- Same as 'writeWith' using an initial array size of 'arrayChunkBytes' bytes
23442059-- rounded up to the element size.
23452060--
23462061-- /Caution! Do not use this on infinite streams./
23472062--
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." #-}
23542063{-# INLINE write #-}
23552064write :: forall m a. (MonadIO m, Unbox a) => Fold m a (MutArray a)
2356−write = create
2065+write = writeWith (allocBytesToElemCount (undefined :: a) arrayChunkBytes)
23572066
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)
2363−
2364−{-# DEPRECATED pinnedWrite "Please use pinnedCreate instead." #-}
2067+-- | Like 'write' but creates a pinned array.
23652068{-# INLINE pinnedWrite #-}
23662069pinnedWrite :: forall m a. (MonadIO m, Unbox a) => Fold m a (MutArray a)
2367−pinnedWrite = pinnedCreate
2070+pinnedWrite =
2071+ writeWithAs Pinned (allocBytesToElemCount (undefined :: a) arrayChunkBytes)
23682072
23692073-------------------------------------------------------------------------------
23702074-- construct from streams, known size
@@ -2384,18 +2088,17 @@ fromStreamDNAs ps limit str = do
23842088 liftIO $ pokeAt ptr arrContents x
23852089 return $ INDEX_NEXT(ptr,a)
23862090
2387−-- | Use the 'createOf' fold instead.
2091+-- | Use the 'writeN' fold instead.
23882092--
2389−-- >>> fromStreamN n = Stream.fold (MutArray.createOf n)
2093+-- >>> fromStreamN n = Stream.fold (MutArray.writeN n)
23902094--
23912095{-# INLINE_NORMAL fromStreamN #-}
23922096fromStreamN :: forall m a. (MonadIO m, Unbox a)
23932097 => Int -> D.Stream m a -> m (MutArray a)
2394−-- fromStreamDN n = D.fold (createOf n)
2098+-- fromStreamDN n = D.fold (writeN n)
23952099fromStreamN = fromStreamDNAs Unpinned
23962100
23972101{-# DEPRECATED fromStreamDN "Please use fromStreamN instead." #-}
2398−{-# INLINE fromStreamDN #-}
23992102fromStreamDN :: forall m a. (MonadIO m, Unbox a)
24002103 => Int -> D.Stream m a -> m (MutArray a)
24012104fromStreamDN = fromStreamN
@@ -2418,20 +2121,20 @@ pinnedFromListN n xs = fromStreamDNAs Pinned n $ D.fromList xs
24182121-- /Pre-release/
24192122{-# INLINE fromListRevN #-}
24202123fromListRevN :: (MonadIO m, Unbox a) => Int -> [a] -> m (MutArray a)
2421−fromListRevN n xs = D.fold (revCreateOf n) $ D.fromList xs
2124+fromListRevN n xs = D.fold (writeRevN n) $ D.fromList xs
24222125
24232126-- | Convert a pure stream in Identity monad to a mutable array.
24242127{-# INLINABLE fromPureStreamN #-}
24252128fromPureStreamN :: (MonadIO m, Unbox a) =>
24262129 Int -> Stream Identity a -> m (MutArray a)
24272130fromPureStreamN n xs =
2428− D.fold (createOf n) $ D.morphInner (return . runIdentity) xs
2131+ D.fold (writeN n) $ D.morphInner (return . runIdentity) xs
24292132
24302133-- | Convert a pure stream in Identity monad to a mutable array.
24312134{-# INLINABLE fromPureStream #-}
24322135fromPureStream :: (MonadIO m, Unbox a) => Stream Identity a -> m (MutArray a)
24332136fromPureStream xs =
2434− D.fold create $ D.morphInner (return . runIdentity) xs
2137+ D.fold write $ D.morphInner (return . runIdentity) xs
24352138
24362139{-# INLINABLE fromPtrN #-}
24372140fromPtrN :: MonadIO m => Int -> Ptr Word8 -> m (MutArray Word8)
@@ -2440,7 +2143,7 @@ fromPtrN len addr = do
24402143 -- XXX We can implement a stream copy in a similar way by streaming Word64
24412144 -- first and then remaining Word8.
24422145 arr <- new len
2443− _ <- unsafeAsPtr arr
2146+ _ <- asUnpinnedPtrUnsafe arr
24442147 (\ptr -> liftIO $ c_memcpy ptr addr (fromIntegral len))
24452148 return (arr {arrEnd = len})
24462149
@@ -2456,7 +2159,7 @@ fromByteStr# addr = do
24562159 len <- liftIO $ c_strlen (Ptr addr)
24572160 let lenInt = fromIntegral len
24582161 arr <- new lenInt
2459− _ <- unsafeAsPtr arr (\ptr -> liftIO $ c_memcpy ptr (Ptr addr) len)
2162+ _ <- asUnpinnedPtrUnsafe arr (\ptr -> liftIO $ c_memcpy ptr (Ptr addr) len)
24602163 return (arr {arrEnd = lenInt})
24612164
24622165-------------------------------------------------------------------------------
@@ -2515,7 +2218,6 @@ fromChunksK :: (Unbox a, MonadIO m) =>
25152218fromChunksK = fromChunkskAs Unpinned
25162219
25172220{-# DEPRECATED fromArrayStreamK "Please use fromChunksK instead." #-}
2518−{-# INLINE fromArrayStreamK #-}
25192221fromArrayStreamK :: (Unbox a, MonadIO m) =>
25202222 StreamK m (MutArray a) -> m (MutArray a)
25212223fromArrayStreamK = fromChunksK
@@ -2527,7 +2229,7 @@ fromStreamDAs ps m =
25272229 arrayStreamKFromStreamDAs Unpinned m >>= fromChunkskAs ps
25282230
25292231-- | 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
2232+-- single array from a stream of unknown size. 'writeN' is at least twice
25312233-- as efficient when the size is already known.
25322234--
25332235-- Note that if the input stream is too large memory allocation for the array
@@ -2539,19 +2241,19 @@ fromStreamDAs ps m =
25392241fromStream :: (MonadIO m, Unbox a) => Stream m a -> m (MutArray a)
25402242fromStream = fromStreamDAs Unpinned
25412243
2542−-- fromStream (Stream m) = P.fold create m
2244+-- fromStream (Stream m) = P.fold write m
25432245-- CAUTION: a very large number (millions) of arrays can degrade performance
25442246-- due to GC overhead because we need to buffer the arrays before we flatten
25452247-- all the arrays.
25462248--
2547−-- XXX Compare if this is faster or "fold create".
2249+-- XXX Compare if this is faster or "fold write".
25482250--
25492251-- | We could take the approach of doubling the memory allocation on each
25502252-- overflow. This would result in more or less the same amount of copying as in
25512253-- the chunking approach. However, if we have to shrink in the end then it may
25522254-- result in an extra copy of the entire data.
25532255--
2554−-- >>> fromStreamD = StreamD.fold MutArray.create
2256+-- >>> fromStreamD = StreamD.fold MutArray.write
25552257--
25562258{-# INLINE fromStreamD #-}
25572259{-# DEPRECATED fromStreamD "Please use fromStream instead." #-}
@@ -2581,10 +2283,6 @@ fromListRev xs = fromListRevN (Prelude.length xs) xs
25812283-- Cloning
25822284-------------------------------------------------------------------------------
25832285
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−
25882286{-# INLINE cloneAs #-}
25892287cloneAs ::
25902288 ( MonadIO m
@@ -2676,7 +2374,7 @@ spliceWith :: forall m a. (MonadIO m, Unbox a) =>
26762374 (Int -> Int -> Int) -> MutArray a -> MutArray a -> m (MutArray a)
26772375spliceWith sizer dst@(MutArray _ start end bound) src = do
26782376{-
2679− let f = appendWith (`sizer` byteLength src) (return dst)
2377+ let f = writeAppendWith (`sizer` byteLength src) (return dst)
26802378 in D.fold f (toStreamD src)
26812379-}
26822380 assert (end <= bound) (return ())
@@ -2744,7 +2442,7 @@ splitOn predicate arr =
27442442{-# INLINE breakOn #-}
27452443breakOn :: MonadIO m
27462444 => Word8 -> MutArray Word8 -> m (MutArray Word8, Maybe (MutArray Word8))
2747−breakOn sep arr@MutArray{..} = unsafeAsPtr arr $ \p -> liftIO $ do
2445+breakOn sep arr@MutArray{..} = asUnpinnedPtrUnsafe arr $ \p -> liftIO $ do
27482446 -- XXX We do not need memchr here, we can use a Haskell equivalent.
27492447 -- Need efficient stream based primitives that work on Word64.
27502448 loc <- c_memchr p sep (fromIntegral $ byteLength arr)
@@ -2767,41 +2465,33 @@ breakOn sep arr@MutArray{..} = unsafeAsPtr arr $ \p -> liftIO $ do
27672465 }
27682466 )
27692467
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−
27922468-- | Create two slices of an array without copying the original array. The
27932469-- specified index @i@ is the first index of the second slice.
27942470--
27952471{-# INLINE splitAt #-}
27962472splitAt :: forall a. Unbox a => Int -> MutArray a -> (MutArray a, MutArray a)
2797−splitAt i arr =
2473+splitAt i arr@MutArray{..} =
27982474 let maxIndex = length arr - 1
27992475 in if i < 0
28002476 then error "sliceAt: negative array index"
28012477 else if i > maxIndex
28022478 then error $ "sliceAt: specified array index " ++ show i
28032479 ++ " is beyond the maximum index " ++ show maxIndex
2804− else unsafeSplitAt i arr
2480+ else let off = i * SIZE_OF(a)
2481+ p = arrStart + off
2482+ in ( MutArray
2483+ { arrContents = arrContents
2484+ , arrStart = arrStart
2485+ , arrEnd = p
2486+ , arrBound = p
2487+ }
2488+ , MutArray
2489+ { arrContents = arrContents
2490+ , arrStart = p
2491+ , arrEnd = arrEnd
2492+ , arrBound = arrBound
2493+ }
2494+ )
28052495
28062496-------------------------------------------------------------------------------
28072497-- Casting
@@ -2851,13 +2541,9 @@ cast arr =
28512541-- guarantees that unsafe calls will be performed in the calling thread. Making
28522542-- it safe to pass heap-allocated objects to unsafe functions.
28532543
2854−-- XXX Should we just name it asPtr, the unsafety is implicit for any pointer
2544+-- Should we just name it asPtr, the unsafety is implicit for any pointer
28552545-- operations. And we are safe from Haskell perspective because we will be
28562546-- 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.
28612547
28622548-- | Use a @MutArray a@ as @Ptr a@. This is useful when we want to pass an
28632549-- array as a pointer to some operating system call or to a "safe" FFI call.
@@ -2875,21 +2561,16 @@ cast arr =
28752561--
28762562-- /Pre-release/
28772563--
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." #-}
28852564{-# INLINE asPtrUnsafe #-}
28862565asPtrUnsafe :: MonadIO m => MutArray a -> (Ptr a -> m b) -> m b
2887−asPtrUnsafe = unsafePinnedAsPtr
2566+asPtrUnsafe arr f =
2567+ Unboxed.asPtrUnsafe
2568+ (arrContents arr) (\ptr -> f (ptr `plusPtr` arrStart arr))
28882569
2889−{-# INLINE unsafeAsPtr #-}
2890−unsafeAsPtr :: MonadIO m => MutArray a -> (Ptr a -> m b) -> m b
2891−unsafeAsPtr arr f =
2892− Unboxed.unsafeAsPtr
2570+{-# INLINE asUnpinnedPtrUnsafe #-}
2571+asUnpinnedPtrUnsafe :: MonadIO m => MutArray a -> (Ptr a -> m b) -> m b
2572+asUnpinnedPtrUnsafe arr f =
2573+ Unboxed.asUnpinnedPtrUnsafe
28932574 (arrContents arr) (\ptr -> f (ptr `plusPtr` arrStart arr))
28942575
28952576-------------------------------------------------------------------------------
@@ -2946,48 +2627,46 @@ byteEq arr1 arr2 = fmap (EQ ==) $ byteCmp arr1 arr2
29462627-- Compact
29472628-------------------------------------------------------------------------------
29482629
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 ::
2630+-- | Parser @pCompactLE n@ coalesces adjacent arrays in the input stream
2631+-- only if the combined size would be less than or equal to n.
2632+--
2633+-- /Internal/
2634+{-# INLINE_NORMAL pCompactLE #-}
2635+pCompactLE ::
29562636 forall m a. (MonadIO m, Unbox a)
2957− => PinnedState -> Int -> Parser (MutArray a) m (MutArray a)
2958−pCompactLeAs ps maxElems = Parser step initial extract
2637+ => Int -> Parser (MutArray a) m (MutArray a)
2638+pCompactLE n = Parser step initial extract
29592639
29602640 where
29612641
2962− maxBytes = maxElems * SIZE_OF(a)
2642+ nBytes = n * SIZE_OF(a)
29632643
29642644 functionName = "Streamly.Internal.Data.MutArray.pCompactLE"
29652645
29662646 initial =
29672647 return
2968− $ if maxElems <= 0
2648+ $ if n <= 0
29692649 then error
29702650 $ functionName
29712651 ++ ": the size of arrays ["
2972− ++ show maxElems ++ "] must be a natural number"
2652+ ++ show n ++ "] must be a natural number"
29732653 else Parser.IPartial Nothing
29742654
29752655 step Nothing arr =
29762656 return
29772657 $ let len = byteLength arr
2978− in if len >= maxBytes
2658+ in if len >= nBytes
29792659 then Parser.Done 0 arr
29802660 else Parser.Partial 0 (Just arr)
2981− -- XXX Split the last array to use the space more compactly.
29822661 step (Just buf) arr =
29832662 let len = byteLength buf + byteLength arr
2984− in if len > maxBytes
2663+ in if len > nBytes
29852664 then return $ Parser.Done 1 buf
29862665 else do
2666+ -- XXX check this in the Nothing case
29872667 buf1 <-
2988− if byteCapacity buf < maxBytes
2989− then liftIO $ reallocExplicitAs
2990− ps (SIZE_OF(a)) maxBytes buf
2668+ if byteCapacity buf < nBytes
2669+ then liftIO $ realloc nBytes buf
29912670 else return buf
29922671 buf2 <- spliceUnsafe buf1 arr
29932672 return $ Parser.Partial 0 (Just buf2)
@@ -2995,30 +2674,6 @@ pCompactLeAs ps maxElems = Parser step initial extract
29952674 extract Nothing = return $ Parser.Done 0 nil
29962675 extract (Just buf) = return $ Parser.Done 0 buf
29972676
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−
30222677data SpliceState s arr
30232678 = SpliceInitial s
30242679 | SpliceBuffering s arr
@@ -3030,47 +2685,48 @@ data SpliceState s arr
30302685-- immutable array never has additional space so a new array is allocated
30312686-- instead of mutating it.
30322687
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) =
2688+-- | Scan @rCompactLE n@ coalesces adjacent arrays in the input stream
2689+-- only if the combined size would be less than or equal to n.
2690+--
2691+-- /Internal/
2692+{-# INLINE_NORMAL rCompactLE #-}
2693+rCompactLE :: (MonadIO m, Unbox a)
2694+ => Int -> D.Stream m (MutArray a) -> D.Stream m (MutArray a)
2695+rCompactLE n (D.Stream step state) =
30372696 D.Stream step' (SpliceInitial state)
30382697
30392698 where
30402699
3041− maxBytes = maxElems * SIZE_OF(a)
3042−
30432700 functionName = "Streamly.Internal.Data.MutArray.rCompactLE"
30442701
30452702 {-# INLINE_LATE step' #-}
30462703 step' gst (SpliceInitial st) = do
3047− when (maxElems <= 0) $
2704+ when (n <= 0) $
30482705 -- XXX we can pass the module string from the higher level API
3049− error $ functionName ++ ": the size of arrays [" ++ show maxElems
2706+ error $ functionName ++ ": the size of arrays [" ++ show n
30502707 ++ "] must be a natural number"
30512708 r <- step gst st
30522709 case r of
30532710 D.Yield arr s -> return $
30542711 let len = byteLength arr
3055− in if len >= maxBytes
2712+ in if len >= n
30562713 then D.Skip (SpliceYielding arr (SpliceInitial s))
30572714 else D.Skip (SpliceBuffering s arr)
30582715 D.Skip s -> return $ D.Skip (SpliceInitial s)
30592716 D.Stop -> return D.Stop
30602717
3061− -- XXX Split the last array to use the space more compactly.
30622718 step' gst (SpliceBuffering st buf) = do
30632719 r <- step gst st
30642720 case r of
30652721 D.Yield arr s -> do
30662722 let len = byteLength buf + byteLength arr
3067− if len > maxBytes
2723+ if len > n
30682724 then return $
30692725 D.Skip (SpliceYielding buf (SpliceBuffering s arr))
30702726 else do
3071− buf1 <- if byteCapacity buf < maxBytes
3072− then liftIO $ reallocExplicitAs
3073− ps (SIZE_OF(a)) maxBytes buf
2727+ -- XXX check this in the SpliceInitial case
2728+ buf1 <- if byteCapacity buf < n
2729+ then liftIO $ realloc n buf
30742730 else return buf
30752731 buf2 <- spliceUnsafe buf1 arr
30762732 return $ D.Skip (SpliceBuffering s buf2)
@@ -3081,119 +2737,108 @@ compactLeAs ps maxElems (D.Stream step state) =
30812737
30822738 step' _ (SpliceYielding arr next) = return $ D.Yield arr next
30832739
3084−
3085−{-# INLINE_NORMAL fCompactGeAs #-}
3086−fCompactGeAs ::
2740+-- | Fold @fCompactGE n@ coalesces adjacent arrays in the input stream
2741+-- until the size becomes greater than or equal to n.
2742+--
2743+{-# INLINE_NORMAL fCompactGE #-}
2744+fCompactGE ::
30872745 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
2746+ => Int -> FL.Fold m (MutArray a) (MutArray a)
2747+fCompactGE n = Fold step initial extract extract
30902748
30912749 where
30922750
3093− minBytes = minElems * SIZE_OF(a)
2751+ nBytes = n * SIZE_OF(a)
30942752
30952753 functionName = "Streamly.Internal.Data.MutArray.fCompactGE"
30962754
30972755 initial =
30982756 return
3099− $ if minElems < 0
2757+ $ if n < 0
31002758 then error
31012759 $ functionName
31022760 ++ ": the size of arrays ["
3103− ++ show minElems ++ "] must be a natural number"
2761+ ++ show n ++ "] must be a natural number"
31042762 else FL.Partial Nothing
31052763
31062764 step Nothing arr =
31072765 return
31082766 $ let len = byteLength arr
3109− in if len >= minBytes
2767+ in if len >= nBytes
31102768 then FL.Done arr
31112769 else FL.Partial (Just arr)
3112− -- XXX Buffer arrays as a list to avoid copy and reallocations
31132770 step (Just buf) arr = do
31142771 let len = byteLength buf + byteLength arr
31152772 buf1 <-
31162773 if byteCapacity buf < len
3117− then liftIO $ reallocExplicitAs
3118− ps (SIZE_OF(a)) (max minBytes len) buf
2774+ then liftIO $ realloc (max len nBytes) buf
31192775 else return buf
31202776 buf2 <- spliceUnsafe buf1 arr
3121− if len >= minBytes
2777+ if len >= n
31222778 then return $ FL.Done buf2
31232779 else return $ FL.Partial (Just buf2)
31242780
31252781 extract Nothing = return nil
31262782 extract (Just buf) = return buf
31272783
3128−-- | Fold @fCompactGE minElems@ coalesces adjacent arrays in the input stream
3129−-- until the size becomes greater than or equal to @minElems@.
2784+-- | Like 'compactGE' but for transforming folds instead of stream.
31302785--
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) =
2786+-- >>> lCompactGE n = Fold.many (MutArray.fCompactGE n)
2787+--
2788+{-# INLINE_NORMAL lCompactGE #-}
2789+lCompactGE :: (MonadIO m, Unbox a)
2790+ => Int -> Fold m (MutArray a) () -> Fold m (MutArray a) ()
2791+-- lCompactGE n = Fold.many (fCompactGE n)
2792+lCompactGE n (Fold step1 initial1 _ final1) =
31522793 Fold step initial extract final
31532794
31542795 where
31552796
3156− minBytes = minElems * SIZE_OF(a)
3157−
31582797 functionName = "Streamly.Internal.Data.MutArray.lCompactGE"
31592798
31602799 initial = do
3161− when (minElems <= 0) $
2800+ when (n <= 0) $
31622801 -- XXX we can pass the module string from the higher level API
31632802 error $ functionName ++ ": the size of arrays ["
3164− ++ show minElems ++ "] must be a natural number"
2803+ ++ show n ++ "] must be a natural number"
31652804
31662805 r <- initial1
31672806 return $ first (Tuple' Nothing) r
31682807
3169− {-# INLINE runInner #-}
3170− runInner len acc buf =
3171− if len >= minBytes
2808+ step (Tuple' Nothing r1) arr =
2809+ let len = byteLength arr
2810+ in if len >= n
2811+ then do
2812+ r <- step1 r1 arr
2813+ case r of
2814+ FL.Done _ -> return $ FL.Done ()
2815+ FL.Partial s -> do
2816+ _ <- final1 s
2817+ res <- initial1
2818+ return $ first (Tuple' Nothing) res
2819+ else return $ FL.Partial $ Tuple' (Just arr) r1
2820+
2821+ step (Tuple' (Just buf) r1) arr = do
2822+ let len = byteLength buf + byteLength arr
2823+ buf1 <- if byteCapacity buf < len
2824+ then liftIO $ realloc (max n len) buf
2825+ else return buf
2826+ buf2 <- spliceUnsafe buf1 arr
2827+
2828+ -- XXX this is common in both the equations of step
2829+ if len >= n
31722830 then do
3173− r <- step1 acc buf
2831+ r <- step1 r1 buf2
31742832 case r of
31752833 FL.Done _ -> return $ FL.Done ()
31762834 FL.Partial s -> do
31772835 _ <- final1 s
31782836 res <- initial1
31792837 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
2838+ else return $ FL.Partial $ Tuple' (Just buf2) r1
31942839
31952840 -- 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
2841+ -- return "m b" rather than using extract post it if we want extract to be
31972842 -- partial.
31982843 --
31992844 -- extract forces the pending buffer to be sent to the fold which is not
@@ -3207,23 +2852,6 @@ lCompactGeAs ps minElems (Fold step1 initial1 _ final1) =
32072852 FL.Partial rr -> final1 rr
32082853 FL.Done _ -> return ()
32092854
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−
32272855-- | @compactGE n stream@ coalesces adjacent arrays in the @stream@ until
32282856-- the size becomes greater than or equal to @n@.
32292857--