@@ -40,22 +40,22 @@ module Streamly.Internal.Data.MutArray.Type
4040
4141 -- ** Casting
4242 , cast
43− , castUnsafe
43+ , castUnsafe -- XXX unsafeCast
4444 , asBytes
45− , asPtrUnsafe
46− , asUnpinnedPtrUnsafe
45+ , unsafePinnedAsPtr
46+ , unsafeAsPtr
4747
4848 -- ** Construction
49− , nil
49+ , empty
5050
5151 -- *** New
5252 -- | New arrays are always empty arrays with some reserve capacity to
5353 -- extend the length without reallocating.
54− , new
55− , newArrayWith
56− , pinnedNew
57− , pinnedNewBytes
58− , pinnedNewAligned
54+ , emptyOf
55+ , newArrayWith -- emptyAlignedWith
56+ , pinnedEmptyOf
57+ , pinnedNewAligned -- XXX not required
58+ -- , new -- uninitialized array of specified length
5959
6060 -- *** Cloning
6161 , clone
@@ -63,27 +63,25 @@ module Streamly.Internal.Data.MutArray.Type
6363
6464 -- *** Slicing
6565 -- | Get a subarray without copying
66− , getSliceUnsafe
66+ , getSliceUnsafe -- XXX unsafeGetSlice
6767 , getSlice
6868 , splitAt -- XXX should be able to express using getSlice
6969 , breakOn
7070
7171 -- *** Stream Folds
7272 , ArrayUnsafe (..)
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
73+ , unsafeCreateOfWith
74+ , unsafeCreateOf
75+ , unsafePinnedCreateOf
76+ , pinnedCreateOf
77+ , createOfWith
78+ , createOf
79+ , revCreateOf
80+
81+ , pinnedCreate
82+ , createWith
83+ , create
84+ -- , revCreate
8785
8886 -- *** From containers
8987 , fromListN
@@ -99,11 +97,11 @@ module Streamly.Internal.Data.MutArray.Type
9997 , fromByteStr#
10098 , fromPtrN
10199 , fromChunksK
102− , fromChunksRealloced
100+ , fromChunksRealloced -- fromSmallChunks
103101
104102 -- ** Random writes
105103 , putIndex
106− , putIndexUnsafe
104+ , putIndexUnsafe -- XXX unsafePutIndex
107105 , putIndices
108106 -- , putFromThenTo
109107 -- , putFrom -- start writing at the given position
@@ -111,7 +109,7 @@ module Streamly.Internal.Data.MutArray.Type
111109 -- , putFromTo
112110 -- , putFromRev
113111 -- , putUptoRev
114− , modifyIndexUnsafe
112+ , modifyIndexUnsafe -- XXX unsafeModifyIndex
115113 , modifyIndex
116114 , modifyIndices
117115 , modify
@@ -122,9 +120,9 @@ module Streamly.Internal.Data.MutArray.Type
122120
123121 -- *** Indexing
124122 , getIndex
125− , getIndexUnsafe
123+ , getIndexUnsafe -- XXX unsafeGetIndex
126124 -- , getFromThenTo
127− , getIndexRev
125+ , getIndexRev -- getRevIndex?
128126 , indexReader
129127 , indexReaderWith
130128
@@ -195,24 +193,34 @@ module Streamly.Internal.Data.MutArray.Type
195193 , snoc
196194 , snocLinear
197195 , snocMay
198− , snocUnsafe
196+ , snocUnsafe -- XXX unsafeSnoc
199197
200198 -- *** Appending streams
201− , writeAppendNUnsafe
202− , writeAppendN
203− , writeAppendWith
204− , writeAppend
199+ , unsafeAppendN
200+ , appendN
201+ , appendWith
202+ , append
205203
206204 -- *** Appending arrays
207205 , spliceCopy
208206 , spliceWith
209207 , splice
210208 , spliceExp
211− , spliceUnsafe
209+ , spliceUnsafe -- XXX unsafeSplice
212210 -- , putSlice
213211 -- , appendSlice
214212 -- , appendSliceFrom
215213
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+
216224 -- Arrays of arrays
217225 -- We can add dimensionality parameter to the array type to get
218226 -- multidimensional arrays. Multidimensional arrays would just be a
@@ -234,6 +242,8 @@ module Streamly.Internal.Data.MutArray.Type
234242
235243 -- *** Concat
236244 -- | Append the arrays in a stream to form a stream of elements.
245+ , concatWith
246+ , concatRevWith
237247 , concat
238248 , concatRev
239249
@@ -241,9 +251,12 @@ module Streamly.Internal.Data.MutArray.Type
241251 -- | Append the arrays in a stream to form a stream of larger arrays.
242252 , SpliceState (..)
243253 , pCompactLE
244− , rCompactLE
254+ , pPinnedCompactLE
255+ , compactLeAs
245256 , fCompactGE
257+ , fPinnedCompactGE
246258 , lCompactGE
259+ , lPinnedCompactGE
247260 , compactGE
248261 , compactEQ
249262
@@ -254,6 +267,7 @@ module Streamly.Internal.Data.MutArray.Type
254267 , c_memchr
255268
256269 -- * Deprecated
270+ , asPtrUnsafe
257271 , writeChunks
258272 , flattenArrays
259273 , flattenArraysRev
@@ -265,6 +279,25 @@ module Streamly.Internal.Data.MutArray.Type
265279 , getIndicesWith
266280 , resize
267281 , 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
268301 )
269302where
270303
@@ -446,6 +479,8 @@ isPinned MutArray{..} = Unboxed.isPinned arrContents
446479-- we need more than that. See stg_pinnedNewAlignedByteArrayzh and
447480-- allocatePinned in GHC source.
448481
482+-- XXX Rename to emptyAlignedWith, alignSize should be first arg.
483+
449484-- | @newArrayWith allocator alignment count@ allocates a new array of zero
450485-- length and with a capacity to hold @count@ elements, using @allocator
451486-- size alignment@ as the memory allocator function.
@@ -469,12 +504,25 @@ newArrayWith alloc alignSize count = do
469504 , arrBound = size
470505 }
471506
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." #-}
472520nil ::
473521#ifdef DEVBUILD
474522 Unbox a =>
475523#endif
476524 MutArray a
477−nil = MutArray Unboxed.nil 0 0 0
525+nil = empty
478526
479527{-# INLINE newBytesAs #-}
480528newBytesAs :: MonadIO m =>
@@ -491,12 +539,13 @@ newBytesAs ps bytes = do
491539 , arrBound = bytes
492540 }
493541
494−-- | Allocates a pinned empty array that can hold 'count' items. The memory of
495−-- the array is uninitialized and the allocation is aligned as per the
496−-- '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.
497545--
498546-- /Pre-release/
499547{-# INLINE pinnedNewBytes #-}
548+{-# DEPRECATED pinnedNewBytes "Please use pinnedEmptyOf with appropriate calculation" #-}
500549pinnedNewBytes :: MonadIO m =>
501550#ifdef DEVBUILD
502551 Unbox a =>
@@ -521,21 +570,31 @@ newAs ps =
521570 (error "new: alignment is not used in unpinned arrays.")
522571
523572-- XXX can unaligned allocation be more efficient when alignment is not needed?
524−--
525−-- | Allocates an empty pinned array that can hold 'count' items. The memory of
526−-- the array is uninitialized and the allocation is aligned as per the 'Unboxed'
527−-- instance of the type.
528−--
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." #-}
529582{-# INLINE pinnedNew #-}
530583pinnedNew :: forall m a. (MonadIO m, Unbox a) => Int -> m (MutArray a)
531−pinnedNew = newAs Pinned
584+pinnedNew = pinnedEmptyOf
532585
533−-- | Allocates an empty unpinned array that can hold 'count' items. The memory
534−-- of the array is uninitialized.
586+-- | Allocates an unpinned array of zero length but growable to the specified
587+-- capacity without reallocation.
535588--
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." #-}
536595{-# INLINE new #-}
537596new :: (MonadIO m, Unbox a) => Int -> m (MutArray a)
538−new = newAs Unpinned
597+new = emptyOf
539598
540599-------------------------------------------------------------------------------
541600-- Random writes
@@ -783,15 +842,15 @@ roundDownTo elemSize size = size - (size `mod` elemSize)
783842-- Since this is not inlined Unboxed consrraint leads to dictionary passing
784843-- which complicates some inspection tests.
785844--
786−{-# NOINLINE reallocExplicit #-}
787−reallocExplicit :: Int -> Int -> MutArray a -> IO (MutArray a)
788−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
789848 assertM(arrEnd <= arrBound)
790849
791850 -- Allocate new array
792851 let newCapMaxInBytes = roundUpLargeArray newCapacityInBytes
793852 contents <-
794− if Unboxed.isPinned arrContents
853+ if ps == Pinned
795854 then Unboxed.pinnedNew newCapMaxInBytes
796855 else Unboxed.new newCapMaxInBytes
797856 let !(MutByteArray mbarrFrom#) = arrContents
@@ -831,7 +890,12 @@ reallocExplicit elemSize newCapacityInBytes MutArray{..} = do
831890-- If the original array is pinned, the newly allocated array is also pinned.
832891{-# INLINABLE realloc #-}
833892realloc :: forall m a. (MonadIO m, Unbox a) => Int -> MutArray a -> m (MutArray a)
834−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
835899
836900-- | @reallocWith label capSizer minIncrBytes array@. The label is used
837901-- in error messages and the capSizer is used to determine the capacity of the
@@ -880,6 +944,7 @@ grow nElems arr@MutArray{..} = do
880944 else realloc req arr
881945
882946{-# DEPRECATED resize "Please use grow instead." #-}
947+{-# INLINE resize #-}
883948resize :: forall m a. (MonadIO m, Unbox a) =>
884949 Int -> MutArray a -> m (MutArray a)
885950resize = grow
@@ -903,6 +968,7 @@ growExp nElems arr@MutArray{..} = do
903968 else realloc req1 arr
904969
905970{-# DEPRECATED resizeExp "Please use growExp instead." #-}
971+{-# INLINE resizeExp #-}
906972resizeExp :: forall m a. (MonadIO m, Unbox a) =>
907973 Int -> MutArray a -> m (MutArray a)
908974resizeExp = growExp
@@ -1051,6 +1117,126 @@ snoc = snocWith f
10511117 then oldSize * 2
10521118 else roundUpToPower2 oldSize * 2
10531119
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+
10541240-------------------------------------------------------------------------------
10551241-- Random reads
10561242-------------------------------------------------------------------------------
@@ -1116,6 +1302,7 @@ indexReaderWith liftio (D.Stream stepi sti) = Unfold step inject
11161302 D.Stop -> return D.Stop
11171303
11181304{-# DEPRECATED getIndicesWith "Please use indexReaderWith instead." #-}
1305+{-# INLINE getIndicesWith #-}
11191306getIndicesWith :: (Monad m, Unbox a) =>
11201307 (forall b. IO b -> m b) -> D.Stream m Int -> Unfold m (MutArray a) a
11211308getIndicesWith = indexReaderWith
@@ -1131,6 +1318,7 @@ indexReader = indexReaderWith liftIO
11311318
11321319-- XXX DO NOT REMOVE, change the signature to use Stream instead of unfold
11331320{-# DEPRECATED getIndices "Please use indexReader instead." #-}
1321+{-# INLINE getIndices #-}
11341322getIndices :: (MonadIO m, Unbox a) => Stream m Int -> Unfold m (MutArray a) a
11351323getIndices = indexReader
11361324
@@ -1427,7 +1615,7 @@ chunksOfAs ps n (D.Stream step state) =
14271615--
14281616-- Same as the following but may be more efficient:
14291617--
1430−-- >>> chunksOf n = Stream.foldMany (MutArray.writeN n)
1618+-- >>> chunksOf n = Stream.foldMany (MutArray.createOf n)
14311619--
14321620-- /Pre-release/
14331621{-# INLINE_NORMAL chunksOf #-}
@@ -1436,14 +1624,14 @@ chunksOf :: forall m a. (MonadIO m, Unbox a)
14361624-- XXX the idiomatic implementation leads to large regression in the D.reverse'
14371625-- benchmark. It seems it has difficulty producing optimized code when
14381626-- converting to StreamK. Investigate GHC optimizations.
1439−-- chunksOf n = D.foldMany (writeN n)
1627+-- chunksOf n = D.foldMany (createOf n)
14401628chunksOf = chunksOfAs Unpinned
14411629
14421630-- | Like 'chunksOf' but creates pinned arrays.
14431631{-# INLINE_NORMAL pinnedChunksOf #-}
14441632pinnedChunksOf :: forall m a. (MonadIO m, Unbox a)
14451633 => Int -> D.Stream m a -> D.Stream m (MutArray a)
1446−-- pinnedChunksOf n = D.foldMany (pinnedWriteN n)
1634+-- pinnedChunksOf n = D.foldMany (pinnedCreateOf n)
14471635pinnedChunksOf = chunksOfAs Pinned
14481636
14491637-- | When we are buffering a stream of unknown size into an array we do not
@@ -1476,16 +1664,10 @@ data FlattenState s contents a =
14761664 OuterLoop s
14771665 | InnerLoop s contents !Int !Int
14781666
1479−-- | Use the "reader" unfold instead.
1480−--
1481−-- @concat = unfoldMany reader@
1482−--
1483−-- We can try this if there are any fusion issues in the unfold.
1484−--
1485−{-# INLINE_NORMAL concat #-}
1486−concat :: forall m a. (MonadIO m, Unbox a)
1487− => D.Stream m (MutArray a) -> D.Stream m a
1488−concat (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)
14891671
14901672 where
14911673
@@ -1502,24 +1684,30 @@ concat (D.Stream step state) = D.Stream step' (OuterLoop state)
15021684 return $ D.Skip $ OuterLoop st
15031685
15041686 step' _ (InnerLoop st contents p end) = do
1505− x <- liftIO $ peekAt p contents
1687+ x <- liftio $ peekAt p contents
15061688 return $ D.Yield x (InnerLoop st contents (INDEX_NEXT(p,a)) end)
15071689
1508−{-# DEPRECATED flattenArrays "Please use \"unfoldMany reader\" instead." #-}
1509−flattenArrays :: forall m a. (MonadIO m, Unbox a)
1510− => D.Stream m (MutArray a) -> D.Stream m a
1511−flattenArrays = concat
1512−
1513−-- | Use the "readerRev" unfold instead.
1690+-- | Use the "reader" unfold instead.
15141691--
1515−-- @concat = unfoldMany readerRev@
1692+-- @concat = unfoldMany reader@
15161693--
15171694-- We can try this if there are any fusion issues in the unfold.
15181695--
1519−{-# INLINE_NORMAL concatRev #-}
1520−concatRev :: forall m a. (MonadIO m, Unbox a)
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+
1701+{-# DEPRECATED flattenArrays "Please use \"unfoldMany reader\" instead." #-}
1702+{-# INLINE flattenArrays #-}
1703+flattenArrays :: forall m a. (MonadIO m, Unbox a)
15211704 => D.Stream m (MutArray a) -> D.Stream m a
1522−concatRev (D.Stream step state) = D.Stream step' (OuterLoop state)
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)
15231711
15241712 where
15251713
@@ -1537,11 +1725,23 @@ concatRev (D.Stream step state) = D.Stream step' (OuterLoop state)
15371725 return $ D.Skip $ OuterLoop st
15381726
15391727 step' _ (InnerLoop st contents p start) = do
1540− x <- liftIO $ peekAt p contents
1728+ x <- liftio $ peekAt p contents
15411729 let cur = INDEX_PREV(p,a)
15421730 return $ D.Yield x (InnerLoop st contents cur start)
15431731
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+
15441743{-# DEPRECATED flattenArraysRev "Please use \"unfoldMany readerRev\" instead." #-}
1744+{-# INLINE flattenArraysRev #-}
15451745flattenArraysRev :: forall m a. (MonadIO m, Unbox a)
15461746 => D.Stream m (MutArray a) -> D.Stream m a
15471747flattenArraysRev = concatRev
@@ -1773,7 +1973,7 @@ foldr f z arr = D.foldr f z $ read arr
17731973
17741974-- XXX Keep the bound intact to not lose any free space? Perf impact?
17751975
1776−-- | @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
17771977-- array.
17781978--
17791979-- Unsafe: Do not drive the fold beyond @n@ elements, it will lead to memory
@@ -1782,13 +1982,12 @@ foldr f z arr = D.foldr f z $ read arr
17821982-- Any free space left in the array after appending @n@ elements is lost.
17831983--
17841984-- /Internal/
1785−{-# INLINE_NORMAL writeAppendNUnsafe #-}
1786−writeAppendNUnsafe :: forall m a. (MonadIO m, Unbox a) =>
1985+{-# INLINE_NORMAL unsafeAppendN #-}
1986+unsafeAppendN :: forall m a. (MonadIO m, Unbox a) =>
17871987 Int
17881988 -> m (MutArray a)
17891989 -> Fold m a (MutArray a)
1790−writeAppendNUnsafe n action =
1791− fmap fromArrayUnsafe $ FL.foldlM' step initial
1990+unsafeAppendN n action = fmap fromArrayUnsafe $ FL.foldlM' step initial
17921991
17931992 where
17941993
@@ -1801,7 +2000,7 @@ writeAppendNUnsafe n action =
18012000 -- otherwise we lose that space.
18022001 arr1 <-
18032002 if free < needed
1804− then noinline reallocWith "writeAppendNUnsafeWith" (+ needed) needed arr
2003+ then noinline reallocWith "unsafeAppendN" (+ needed) needed arr
18052004 else return arr
18062005 return $ toArrayUnsafe arr1
18072006
@@ -1809,30 +2008,51 @@ writeAppendNUnsafe n action =
18092008 liftIO $ pokeAt end contents x
18102009 return $ ArrayUnsafe contents start (INDEX_NEXT(end,a))
18112010
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+
18122019-- | Append @n@ elements to an existing array. Any free space left in the array
18132020-- after appending @n@ elements is lost.
18142021--
1815−-- >>> writeAppendN n initial = Fold.take n (MutArray.writeAppendNUnsafe n initial)
2022+-- >>> appendN n initial = Fold.take n (MutArray.unsafeAppendN n initial)
18162023--
1817−{-# 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 #-}
18182032writeAppendN :: forall m a. (MonadIO m, Unbox a) =>
18192033 Int -> m (MutArray a) -> Fold m a (MutArray a)
1820−writeAppendN n initial = FL.take n (writeAppendNUnsafe n initial)
2034+writeAppendN = appendN
18212035
1822−-- | @writeAppendWith realloc action@ mutates the array generated by @action@ to
2036+-- | @appendWith realloc action@ mutates the array generated by @action@ to
18232037-- append the input stream. If there is no reserved space available in the
18242038-- array it is reallocated to a size in bytes determined by @realloc oldSize@,
18252039-- where @oldSize@ is the current size of the array in bytes.
18262040--
18272041-- Note that the returned array may be a mutated version of original array.
18282042--
1829−-- >>> writeAppendWith sizer = Fold.foldlM' (MutArray.snocWith sizer)
2043+-- >>> appendWith sizer = Fold.foldlM' (MutArray.snocWith sizer)
18302044--
18312045-- /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." #-}
18322052{-# INLINE writeAppendWith #-}
18332053writeAppendWith :: forall m a. (MonadIO m, Unbox a) =>
18342054 (Int -> Int) -> m (MutArray a) -> Fold m a (MutArray a)
1835−writeAppendWith sizer = FL.foldlM' (snocWith sizer)
2055+writeAppendWith = appendWith
18362056
18372057-- | @append action@ mutates the array generated by @action@ to append the
18382058-- input stream. If there is no reserved space available in the array it is
@@ -1840,26 +2060,33 @@ writeAppendWith sizer = FL.foldlM' (snocWith sizer)
18402060--
18412061-- Note that the returned array may be a mutated version of original array.
18422062--
1843−-- >>> writeAppend = MutArray.writeAppendWith (* 2)
2063+-- >>> append = MutArray.appendWith (* 2)
18442064--
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." #-}
18452072{-# INLINE writeAppend #-}
18462073writeAppend :: forall m a. (MonadIO m, Unbox a) =>
18472074 m (MutArray a) -> Fold m a (MutArray a)
1848−writeAppend = writeAppendWith (* 2)
2075+writeAppend = append
18492076
18502077-- XXX We can carry bound as well in the state to make sure we do not lose the
18512078-- remaining capacity. Need to check perf impact.
18522079--
1853−-- | Like 'writeNUnsafe' but takes a new array allocator @alloc size@ function
1854−-- as argument.
2080+-- | Like 'unsafeCreateOf' but takes a new array allocator @alloc size@
2081+-- function as argument.
18552082--
1856−-- >>> writeNWithUnsafe alloc n = MutArray.writeAppendNUnsafe (alloc n) n
2083+-- >>> unsafeCreateOfWith alloc n = MutArray.unsafeAppendN (alloc n) n
18572084--
18582085-- /Pre-release/
1859−{-# INLINE_NORMAL writeNWithUnsafe #-}
1860−writeNWithUnsafe :: forall m a. (MonadIO m, Unbox a)
2086+{-# INLINE_NORMAL unsafeCreateOfWith #-}
2087+unsafeCreateOfWith :: forall m a. (MonadIO m, Unbox a)
18612088 => (Int -> m (MutArray a)) -> Int -> Fold m a (MutArray a)
1862−writeNWithUnsafe alloc n = fromArrayUnsafe <$> FL.foldlM' step initial
2089+unsafeCreateOfWith alloc n = fromArrayUnsafe <$> FL.foldlM' step initial
18632090
18642091 where
18652092
@@ -1870,40 +2097,64 @@ writeNWithUnsafe alloc n = fromArrayUnsafe <$> FL.foldlM' step initial
18702097 return
18712098 $ ArrayUnsafe contents start (INDEX_NEXT(end,a))
18722099
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+
18732106{-# INLINE_NORMAL writeNUnsafeAs #-}
18742107writeNUnsafeAs :: forall m a. (MonadIO m, Unbox a)
18752108 => PinnedState -> Int -> Fold m a (MutArray a)
1876−writeNUnsafeAs ps = writeNWithUnsafe (newAs ps)
2109+writeNUnsafeAs ps = unsafeCreateOfWith (newAs ps)
18772110
1878−-- | 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
18792112-- driver must not call the step function more than 'n' times otherwise it will
18802113-- corrupt the memory and crash. This function exists mainly because any
18812114-- conditional in the step function blocks fusion causing 10x performance
18822115-- slowdown.
18832116--
1884−-- >>> writeNUnsafe = MutArray.writeNWithUnsafe MutArray.new
2117+-- >>> unsafeCreateOf = MutArray.unsafeCreateOfWith MutArray.emptyOf
18852118--
1886−{-# 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 #-}
18872126writeNUnsafe :: forall m a. (MonadIO m, Unbox a)
18882127 => Int -> Fold m a (MutArray a)
1889−writeNUnsafe = writeNUnsafeAs Unpinned
2128+writeNUnsafe = unsafeCreateOf
18902129
1891−-- | Like 'writeNUnsafe' but creates a pinned array.
1892−{-# 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 #-}
18932138pinnedWriteNUnsafe :: forall m a. (MonadIO m, Unbox a)
18942139 => Int -> Fold m a (MutArray a)
1895−pinnedWriteNUnsafe = writeNUnsafeAs Pinned
2140+pinnedWriteNUnsafe = unsafePinnedCreateOf
18962141
1897−-- | @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
18982143-- allocated using the @alloc@ function.
18992144--
1900−-- >>> writeNWith alloc n = Fold.take n (MutArray.writeNWithUnsafe alloc n)
1901−-- >>> 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
19022147--
1903−{-# 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 #-}
19042155writeNWith :: forall m a. (MonadIO m, Unbox a)
19052156 => (Int -> m (MutArray a)) -> Int -> Fold m a (MutArray a)
1906−writeNWith alloc n = FL.take n (writeNWithUnsafe alloc n)
2157+writeNWith = createOfWith
19072158
19082159{-# INLINE_NORMAL writeNAs #-}
19092160writeNAs ::
@@ -1911,28 +2162,42 @@ writeNAs ::
19112162 => PinnedState
19122163 -> Int
19132164 -> Fold m a (MutArray a)
1914−writeNAs ps = writeNWith (newAs ps)
2165+writeNAs ps = createOfWith (newAs ps)
19152166
1916−-- | @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
19172168-- 'MutArray'.
19182169--
1919−-- >>> writeN = MutArray.writeNWith MutArray.new
1920−-- >>> writeN n = Fold.take n (MutArray.writeNUnsafe n)
1921−-- >>> 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)
19222173--
1923−{-# 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 #-}
19242181writeN :: forall m a. (MonadIO m, Unbox a) => Int -> Fold m a (MutArray a)
1925−writeN = writeNAs Unpinned
2182+writeN = createOf
19262183
1927−-- | Like 'writeN' but creates a pinned array.
1928−{-# INLINE_NORMAL pinnedWriteN #-}
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 #-}
19292194pinnedWriteN ::
19302195 forall m a. (MonadIO m, Unbox a)
19312196 => Int
19322197 -> Fold m a (MutArray a)
1933−pinnedWriteN = writeNAs Pinned
2198+pinnedWriteN = pinnedCreateOf
19342199
1935−-- | Like writeNWithUnsafe but writes the array in reverse order.
2200+-- | Like unsafeCreateOfWith but writes the array in reverse order.
19362201--
19372202-- /Internal/
19382203{-# INLINE_NORMAL writeRevNWithUnsafe #-}
@@ -1953,7 +2218,7 @@ writeRevNWithUnsafe alloc n = fromArrayUnsafe <$> FL.foldlM' step initial
19532218 return
19542219 $ ArrayUnsafe contents ptr end
19552220
1956−-- | Like writeNWith but writes the array in reverse order.
2221+-- | Like createOfWith but writes the array in reverse order.
19572222--
19582223-- /Internal/
19592224{-# INLINE_NORMAL writeRevNWith #-}
@@ -1961,31 +2226,36 @@ writeRevNWith :: forall m a. (MonadIO m, Unbox a)
19612226 => (Int -> m (MutArray a)) -> Int -> Fold m a (MutArray a)
19622227writeRevNWith alloc n = FL.take n (writeRevNWithUnsafe alloc n)
19632228
1964−-- | Like writeN but writes the array in reverse order.
2229+-- | Like 'createOf' but writes the array in reverse order.
19652230--
19662231-- /Pre-release/
1967−{-# 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 #-}
19682238writeRevN :: forall m a. (MonadIO m, Unbox a) => Int -> Fold m a (MutArray a)
1969−writeRevN = writeRevNWith new
2239+writeRevN = revCreateOf
19702240
19712241-- | @pinnedWriteNAligned align n@ folds a maximum of @n@ elements from the
19722242-- input stream to a 'MutArray' aligned to the given size.
19732243--
1974−-- >>> pinnedWriteNAligned align = MutArray.writeNWith (MutArray.pinnedNewAligned align)
1975−-- >>> 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)
19762246--
19772247-- /Pre-release/
19782248--
19792249{-# INLINE_NORMAL pinnedWriteNAligned #-}
19802250pinnedWriteNAligned :: forall m a. (MonadIO m, Unbox a)
19812251 => Int -> Int -> Fold m a (MutArray a)
1982−pinnedWriteNAligned align = writeNWith (pinnedNewAligned align)
2252+pinnedWriteNAligned align = createOfWith (pinnedNewAligned align)
19832253
19842254-- XXX Buffer to a list instead?
19852255
19862256-- | Buffer a stream into a stream of arrays.
19872257--
1988−-- >>> buildChunks n = Fold.many (MutArray.writeN n) Fold.toStreamK
2258+-- >>> buildChunks n = Fold.many (MutArray.createOf n) Fold.toStreamK
19892259--
19902260-- Breaking an array into an array stream can be useful to consume a large
19912261-- array sequentially such that memory of the array is released incrementatlly.
@@ -1997,9 +2267,10 @@ pinnedWriteNAligned align = writeNWith (pinnedNewAligned align)
19972267{-# INLINE_NORMAL buildChunks #-}
19982268buildChunks :: (MonadIO m, Unbox a) =>
19992269 Int -> Fold m a (StreamK n (MutArray a))
2000−buildChunks n = FL.many (writeN n) FL.toStreamK
2270+buildChunks n = FL.many (createOf n) FL.toStreamK
20012271
20022272{-# DEPRECATED writeChunks "Please use buildChunks instead." #-}
2273+{-# INLINE writeChunks #-}
20032274writeChunks :: (MonadIO m, Unbox a) =>
20042275 Int -> Fold m a (StreamK n (MutArray a))
20052276writeChunks = buildChunks
@@ -2007,29 +2278,29 @@ writeChunks = buildChunks
20072278{-# INLINE_NORMAL writeWithAs #-}
20082279writeWithAs :: forall m a. (MonadIO m, Unbox a)
20092280 => PinnedState -> Int -> Fold m a (MutArray a)
2010−-- writeWithAs ps n = FL.rmapM rightSize $ writeAppendWith (* 2) (newAs ps n)
2281+-- writeWithAs ps n = FL.rmapM rightSize $ appendWith (* 2) (newAs ps n)
20112282writeWithAs ps elemCount =
20122283 FL.rmapM extract $ FL.foldlM' step initial
20132284
20142285 where
20152286
20162287 initial = do
2017− when (elemCount < 0) $ error "writeWith: elemCount is negative"
2288+ when (elemCount < 0) $ error "createWith: elemCount is negative"
20182289 newAs ps elemCount
20192290
20202291 step arr@(MutArray _ start end bound) x
20212292 | INDEX_NEXT(end,a) > bound = do
20222293 let oldSize = end - start
20232294 newSize = max (oldSize * 2) 1
2024− arr1 <- liftIO $ reallocExplicit (SIZE_OF(a)) newSize arr
2295+ arr1 <- liftIO $ reallocExplicitAs ps (SIZE_OF(a)) newSize arr
20252296 snocUnsafe arr1 x
20262297 step arr x = snocUnsafe arr x
20272298
20282299 extract = liftIO . rightSize
20292300
2030−-- XXX Compare writeWith with fromStreamD which uses an array of streams
2301+-- XXX Compare createWith with fromStreamD which uses an array of streams
20312302-- implementation. We can write this using buildChunks above if that is faster.
2032−-- If writeWith is faster then we should use that to implement
2303+-- If createWith is faster then we should use that to implement
20332304-- fromStreamD.
20342305--
20352306-- XXX The realloc based implementation needs to make one extra copy if we use
@@ -2044,39 +2315,56 @@ writeWithAs ps elemCount =
20442315-- XXX check if GHC's memory allocator is efficient enough. We can try the C
20452316-- malloc to compare against.
20462317
2047−-- | @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
20482319-- starts at a size big enough to hold minCount elements, the size is doubled
20492320-- every time the array needs to be grown.
20502321--
20512322-- /Caution! Do not use this on infinite streams./
20522323--
2053−-- >>> f n = MutArray.writeAppendWith (* 2) (MutArray.new n)
2054−-- >>> writeWith n = Fold.rmapM MutArray.rightSize (f n)
2055−-- >>> writeWith n = Fold.rmapM MutArray.fromChunksK (MutArray.buildChunks 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)
20562327--
20572328-- /Pre-release/
2058−{-# 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 #-}
20592337writeWith :: forall m a. (MonadIO m, Unbox a)
20602338 => Int -> Fold m a (MutArray a)
2061−-- writeWith n = FL.rmapM rightSize $ writeAppendWith (* 2) (new n)
2062−writeWith = writeWithAs Unpinned
2339+writeWith = createWith
20632340
20642341-- | Fold the whole input to a single array.
20652342--
2066−-- Same as 'writeWith' using an initial array size of 'arrayChunkBytes' bytes
2343+-- Same as 'createWith' using an initial array size of 'arrayChunkBytes' bytes
20672344-- rounded up to the element size.
20682345--
20692346-- /Caution! Do not use this on infinite streams./
20702347--
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." #-}
20712354{-# INLINE write #-}
20722355write :: forall m a. (MonadIO m, Unbox a) => Fold m a (MutArray a)
2073−write = writeWith (allocBytesToElemCount (undefined :: a) arrayChunkBytes)
2356+write = create
20742357
2075−-- | Like 'write' but creates a pinned array.
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." #-}
20762365{-# INLINE pinnedWrite #-}
20772366pinnedWrite :: forall m a. (MonadIO m, Unbox a) => Fold m a (MutArray a)
2078−pinnedWrite =
2079− writeWithAs Pinned (allocBytesToElemCount (undefined :: a) arrayChunkBytes)
2367+pinnedWrite = pinnedCreate
20802368
20812369-------------------------------------------------------------------------------
20822370-- construct from streams, known size
@@ -2096,17 +2384,18 @@ fromStreamDNAs ps limit str = do
20962384 liftIO $ pokeAt ptr arrContents x
20972385 return $ INDEX_NEXT(ptr,a)
20982386
2099−-- | Use the 'writeN' fold instead.
2387+-- | Use the 'createOf' fold instead.
21002388--
2101−-- >>> fromStreamN n = Stream.fold (MutArray.writeN n)
2389+-- >>> fromStreamN n = Stream.fold (MutArray.createOf n)
21022390--
21032391{-# INLINE_NORMAL fromStreamN #-}
21042392fromStreamN :: forall m a. (MonadIO m, Unbox a)
21052393 => Int -> D.Stream m a -> m (MutArray a)
2106−-- fromStreamDN n = D.fold (writeN n)
2394+-- fromStreamDN n = D.fold (createOf n)
21072395fromStreamN = fromStreamDNAs Unpinned
21082396
21092397{-# DEPRECATED fromStreamDN "Please use fromStreamN instead." #-}
2398+{-# INLINE fromStreamDN #-}
21102399fromStreamDN :: forall m a. (MonadIO m, Unbox a)
21112400 => Int -> D.Stream m a -> m (MutArray a)
21122401fromStreamDN = fromStreamN
@@ -2129,20 +2418,20 @@ pinnedFromListN n xs = fromStreamDNAs Pinned n $ D.fromList xs
21292418-- /Pre-release/
21302419{-# INLINE fromListRevN #-}
21312420fromListRevN :: (MonadIO m, Unbox a) => Int -> [a] -> m (MutArray a)
2132−fromListRevN n xs = D.fold (writeRevN n) $ D.fromList xs
2421+fromListRevN n xs = D.fold (revCreateOf n) $ D.fromList xs
21332422
21342423-- | Convert a pure stream in Identity monad to a mutable array.
21352424{-# INLINABLE fromPureStreamN #-}
21362425fromPureStreamN :: (MonadIO m, Unbox a) =>
21372426 Int -> Stream Identity a -> m (MutArray a)
21382427fromPureStreamN n xs =
2139− D.fold (writeN n) $ D.morphInner (return . runIdentity) xs
2428+ D.fold (createOf n) $ D.morphInner (return . runIdentity) xs
21402429
21412430-- | Convert a pure stream in Identity monad to a mutable array.
21422431{-# INLINABLE fromPureStream #-}
21432432fromPureStream :: (MonadIO m, Unbox a) => Stream Identity a -> m (MutArray a)
21442433fromPureStream xs =
2145− D.fold write $ D.morphInner (return . runIdentity) xs
2434+ D.fold create $ D.morphInner (return . runIdentity) xs
21462435
21472436{-# INLINABLE fromPtrN #-}
21482437fromPtrN :: MonadIO m => Int -> Ptr Word8 -> m (MutArray Word8)
@@ -2151,7 +2440,7 @@ fromPtrN len addr = do
21512440 -- XXX We can implement a stream copy in a similar way by streaming Word64
21522441 -- first and then remaining Word8.
21532442 arr <- new len
2154− _ <- asUnpinnedPtrUnsafe arr
2443+ _ <- unsafeAsPtr arr
21552444 (\ptr -> liftIO $ c_memcpy ptr addr (fromIntegral len))
21562445 return (arr {arrEnd = len})
21572446
@@ -2167,7 +2456,7 @@ fromByteStr# addr = do
21672456 len <- liftIO $ c_strlen (Ptr addr)
21682457 let lenInt = fromIntegral len
21692458 arr <- new lenInt
2170− _ <- asUnpinnedPtrUnsafe arr (\ptr -> liftIO $ c_memcpy ptr (Ptr addr) len)
2459+ _ <- unsafeAsPtr arr (\ptr -> liftIO $ c_memcpy ptr (Ptr addr) len)
21712460 return (arr {arrEnd = lenInt})
21722461
21732462-------------------------------------------------------------------------------
@@ -2226,6 +2515,7 @@ fromChunksK :: (Unbox a, MonadIO m) =>
22262515fromChunksK = fromChunkskAs Unpinned
22272516
22282517{-# DEPRECATED fromArrayStreamK "Please use fromChunksK instead." #-}
2518+{-# INLINE fromArrayStreamK #-}
22292519fromArrayStreamK :: (Unbox a, MonadIO m) =>
22302520 StreamK m (MutArray a) -> m (MutArray a)
22312521fromArrayStreamK = fromChunksK
@@ -2237,7 +2527,7 @@ fromStreamDAs ps m =
22372527 arrayStreamKFromStreamDAs Unpinned m >>= fromChunkskAs ps
22382528
22392529-- | Create an 'Array' from a stream. This is useful when we want to create a
2240−-- single array from a stream of unknown size. 'writeN' is at least twice
2530+-- single array from a stream of unknown size. 'createOf' is at least twice
22412531-- as efficient when the size is already known.
22422532--
22432533-- Note that if the input stream is too large memory allocation for the array
@@ -2249,19 +2539,19 @@ fromStreamDAs ps m =
22492539fromStream :: (MonadIO m, Unbox a) => Stream m a -> m (MutArray a)
22502540fromStream = fromStreamDAs Unpinned
22512541
2252−-- fromStream (Stream m) = P.fold write m
2542+-- fromStream (Stream m) = P.fold create m
22532543-- CAUTION: a very large number (millions) of arrays can degrade performance
22542544-- due to GC overhead because we need to buffer the arrays before we flatten
22552545-- all the arrays.
22562546--
2257−-- XXX Compare if this is faster or "fold write".
2547+-- XXX Compare if this is faster or "fold create".
22582548--
22592549-- | We could take the approach of doubling the memory allocation on each
22602550-- overflow. This would result in more or less the same amount of copying as in
22612551-- the chunking approach. However, if we have to shrink in the end then it may
22622552-- result in an extra copy of the entire data.
22632553--
2264−-- >>> fromStreamD = StreamD.fold MutArray.write
2554+-- >>> fromStreamD = StreamD.fold MutArray.create
22652555--
22662556{-# INLINE fromStreamD #-}
22672557{-# DEPRECATED fromStreamD "Please use fromStream instead." #-}
@@ -2291,6 +2581,10 @@ fromListRev xs = fromListRevN (Prelude.length xs) xs
22912581-- Cloning
22922582-------------------------------------------------------------------------------
22932583
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+
22942588{-# INLINE cloneAs #-}
22952589cloneAs ::
22962590 ( MonadIO m
@@ -2382,7 +2676,7 @@ spliceWith :: forall m a. (MonadIO m, Unbox a) =>
23822676 (Int -> Int -> Int) -> MutArray a -> MutArray a -> m (MutArray a)
23832677spliceWith sizer dst@(MutArray _ start end bound) src = do
23842678{-
2385− let f = writeAppendWith (`sizer` byteLength src) (return dst)
2679+ let f = appendWith (`sizer` byteLength src) (return dst)
23862680 in D.fold f (toStreamD src)
23872681-}
23882682 assert (end <= bound) (return ())
@@ -2450,7 +2744,7 @@ splitOn predicate arr =
24502744{-# INLINE breakOn #-}
24512745breakOn :: MonadIO m
24522746 => Word8 -> MutArray Word8 -> m (MutArray Word8, Maybe (MutArray Word8))
2453−breakOn sep arr@MutArray{..} = asUnpinnedPtrUnsafe arr $ \p -> liftIO $ do
2747+breakOn sep arr@MutArray{..} = unsafeAsPtr arr $ \p -> liftIO $ do
24542748 -- XXX We do not need memchr here, we can use a Haskell equivalent.
24552749 -- Need efficient stream based primitives that work on Word64.
24562750 loc <- c_memchr p sep (fromIntegral $ byteLength arr)
@@ -2473,33 +2767,41 @@ breakOn sep arr@MutArray{..} = asUnpinnedPtrUnsafe arr $ \p -> liftIO $ do
24732767 }
24742768 )
24752769
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+
24762792-- | Create two slices of an array without copying the original array. The
24772793-- specified index @i@ is the first index of the second slice.
24782794--
24792795{-# INLINE splitAt #-}
24802796splitAt :: forall a. Unbox a => Int -> MutArray a -> (MutArray a, MutArray a)
2481−splitAt i arr@MutArray{..} =
2797+splitAt i arr =
24822798 let maxIndex = length arr - 1
24832799 in if i < 0
24842800 then error "sliceAt: negative array index"
24852801 else if i > maxIndex
24862802 then error $ "sliceAt: specified array index " ++ show i
24872803 ++ " is beyond the maximum index " ++ show maxIndex
2488− else let off = i * SIZE_OF(a)
2489− p = arrStart + off
2490− in ( MutArray
2491− { arrContents = arrContents
2492− , arrStart = arrStart
2493− , arrEnd = p
2494− , arrBound = p
2495− }
2496− , MutArray
2497− { arrContents = arrContents
2498− , arrStart = p
2499− , arrEnd = arrEnd
2500− , arrBound = arrBound
2501− }
2502− )
2804+ else unsafeSplitAt i arr
25032805
25042806-------------------------------------------------------------------------------
25052807-- Casting
@@ -2549,9 +2851,13 @@ cast arr =
25492851-- guarantees that unsafe calls will be performed in the calling thread. Making
25502852-- it safe to pass heap-allocated objects to unsafe functions.
25512853
2552−-- Should we just name it asPtr, the unsafety is implicit for any pointer
2854+-- XXX Should we just name it asPtr, the unsafety is implicit for any pointer
25532855-- operations. And we are safe from Haskell perspective because we will be
25542856-- 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.
25552861
25562862-- | Use a @MutArray a@ as @Ptr a@. This is useful when we want to pass an
25572863-- array as a pointer to some operating system call or to a "safe" FFI call.
@@ -2569,16 +2875,21 @@ cast arr =
25692875--
25702876-- /Pre-release/
25712877--
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." #-}
25722885{-# INLINE asPtrUnsafe #-}
25732886asPtrUnsafe :: MonadIO m => MutArray a -> (Ptr a -> m b) -> m b
2574−asPtrUnsafe arr f =
2575− Unboxed.asPtrUnsafe
2576− (arrContents arr) (\ptr -> f (ptr `plusPtr` arrStart arr))
2887+asPtrUnsafe = unsafePinnedAsPtr
25772888
2578−{-# INLINE asUnpinnedPtrUnsafe #-}
2579−asUnpinnedPtrUnsafe :: MonadIO m => MutArray a -> (Ptr a -> m b) -> m b
2580−asUnpinnedPtrUnsafe arr f =
2581− Unboxed.asUnpinnedPtrUnsafe
2889+{-# INLINE unsafeAsPtr #-}
2890+unsafeAsPtr :: MonadIO m => MutArray a -> (Ptr a -> m b) -> m b
2891+unsafeAsPtr arr f =
2892+ Unboxed.unsafeAsPtr
25822893 (arrContents arr) (\ptr -> f (ptr `plusPtr` arrStart arr))
25832894
25842895-------------------------------------------------------------------------------
@@ -2635,46 +2946,48 @@ byteEq arr1 arr2 = fmap (EQ ==) $ byteCmp arr1 arr2
26352946-- Compact
26362947-------------------------------------------------------------------------------
26372948
2638−-- | Parser @pCompactLE n@ coalesces adjacent arrays in the input stream
2639−-- only if the combined size would be less than or equal to n.
2640−--
2641−-- /Internal/
2642−{-# INLINE_NORMAL pCompactLE #-}
2643−pCompactLE ::
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 ::
26442956 forall m a. (MonadIO m, Unbox a)
2645− => Int -> Parser (MutArray a) m (MutArray a)
2646−pCompactLE n = Parser step initial extract
2957+ => PinnedState -> Int -> Parser (MutArray a) m (MutArray a)
2958+pCompactLeAs ps maxElems = Parser step initial extract
26472959
26482960 where
26492961
2650− nBytes = n * SIZE_OF(a)
2962+ maxBytes = maxElems * SIZE_OF(a)
26512963
26522964 functionName = "Streamly.Internal.Data.MutArray.pCompactLE"
26532965
26542966 initial =
26552967 return
2656− $ if n <= 0
2968+ $ if maxElems <= 0
26572969 then error
26582970 $ functionName
26592971 ++ ": the size of arrays ["
2660− ++ show n ++ "] must be a natural number"
2972+ ++ show maxElems ++ "] must be a natural number"
26612973 else Parser.IPartial Nothing
26622974
26632975 step Nothing arr =
26642976 return
26652977 $ let len = byteLength arr
2666− in if len >= nBytes
2978+ in if len >= maxBytes
26672979 then Parser.Done 0 arr
26682980 else Parser.Partial 0 (Just arr)
2981+ -- XXX Split the last array to use the space more compactly.
26692982 step (Just buf) arr =
26702983 let len = byteLength buf + byteLength arr
2671− in if len > nBytes
2984+ in if len > maxBytes
26722985 then return $ Parser.Done 1 buf
26732986 else do
2674− -- XXX check this in the Nothing case
26752987 buf1 <-
2676− if byteCapacity buf < nBytes
2677− then liftIO $ realloc nBytes buf
2988+ if byteCapacity buf < maxBytes
2989+ then liftIO $ reallocExplicitAs
2990+ ps (SIZE_OF(a)) maxBytes buf
26782991 else return buf
26792992 buf2 <- spliceUnsafe buf1 arr
26802993 return $ Parser.Partial 0 (Just buf2)
@@ -2682,6 +2995,30 @@ pCompactLE n = Parser step initial extract
26822995 extract Nothing = return $ Parser.Done 0 nil
26832996 extract (Just buf) = return $ Parser.Done 0 buf
26842997
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+
26853022data SpliceState s arr
26863023 = SpliceInitial s
26873024 | SpliceBuffering s arr
@@ -2693,48 +3030,47 @@ data SpliceState s arr
26933030-- immutable array never has additional space so a new array is allocated
26943031-- instead of mutating it.
26953032
2696−-- | Scan @rCompactLE n@ coalesces adjacent arrays in the input stream
2697−-- only if the combined size would be less than or equal to n.
2698−--
2699−-- /Internal/
2700−{-# INLINE_NORMAL rCompactLE #-}
2701−rCompactLE :: (MonadIO m, Unbox a)
2702− => Int -> D.Stream m (MutArray a) -> D.Stream m (MutArray a)
2703−rCompactLE n (D.Stream step state) =
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) =
27043037 D.Stream step' (SpliceInitial state)
27053038
27063039 where
27073040
3041+ maxBytes = maxElems * SIZE_OF(a)
3042+
27083043 functionName = "Streamly.Internal.Data.MutArray.rCompactLE"
27093044
27103045 {-# INLINE_LATE step' #-}
27113046 step' gst (SpliceInitial st) = do
2712− when (n <= 0) $
3047+ when (maxElems <= 0) $
27133048 -- XXX we can pass the module string from the higher level API
2714− error $ functionName ++ ": the size of arrays [" ++ show n
3049+ error $ functionName ++ ": the size of arrays [" ++ show maxElems
27153050 ++ "] must be a natural number"
27163051 r <- step gst st
27173052 case r of
27183053 D.Yield arr s -> return $
27193054 let len = byteLength arr
2720− in if len >= n
3055+ in if len >= maxBytes
27213056 then D.Skip (SpliceYielding arr (SpliceInitial s))
27223057 else D.Skip (SpliceBuffering s arr)
27233058 D.Skip s -> return $ D.Skip (SpliceInitial s)
27243059 D.Stop -> return D.Stop
27253060
3061+ -- XXX Split the last array to use the space more compactly.
27263062 step' gst (SpliceBuffering st buf) = do
27273063 r <- step gst st
27283064 case r of
27293065 D.Yield arr s -> do
27303066 let len = byteLength buf + byteLength arr
2731− if len > n
3067+ if len > maxBytes
27323068 then return $
27333069 D.Skip (SpliceYielding buf (SpliceBuffering s arr))
27343070 else do
2735− -- XXX check this in the SpliceInitial case
2736− buf1 <- if byteCapacity buf < n
2737− then liftIO $ realloc n buf
3071+ buf1 <- if byteCapacity buf < maxBytes
3072+ then liftIO $ reallocExplicitAs
3073+ ps (SIZE_OF(a)) maxBytes buf
27383074 else return buf
27393075 buf2 <- spliceUnsafe buf1 arr
27403076 return $ D.Skip (SpliceBuffering s buf2)
@@ -2745,108 +3081,119 @@ rCompactLE n (D.Stream step state) =
27453081
27463082 step' _ (SpliceYielding arr next) = return $ D.Yield arr next
27473083
2748−-- | Fold @fCompactGE n@ coalesces adjacent arrays in the input stream
2749−-- until the size becomes greater than or equal to n.
2750−--
2751−{-# INLINE_NORMAL fCompactGE #-}
2752−fCompactGE ::
3084+
3085+{-# INLINE_NORMAL fCompactGeAs #-}
3086+fCompactGeAs ::
27533087 forall m a. (MonadIO m, Unbox a)
2754− => Int -> FL.Fold m (MutArray a) (MutArray a)
2755−fCompactGE n = Fold step initial extract extract
3088+ => PinnedState -> Int -> FL.Fold m (MutArray a) (MutArray a)
3089+fCompactGeAs ps minElems = Fold step initial extract extract
27563090
27573091 where
27583092
2759− nBytes = n * SIZE_OF(a)
3093+ minBytes = minElems * SIZE_OF(a)
27603094
27613095 functionName = "Streamly.Internal.Data.MutArray.fCompactGE"
27623096
27633097 initial =
27643098 return
2765− $ if n < 0
3099+ $ if minElems < 0
27663100 then error
27673101 $ functionName
27683102 ++ ": the size of arrays ["
2769− ++ show n ++ "] must be a natural number"
3103+ ++ show minElems ++ "] must be a natural number"
27703104 else FL.Partial Nothing
27713105
27723106 step Nothing arr =
27733107 return
27743108 $ let len = byteLength arr
2775− in if len >= nBytes
3109+ in if len >= minBytes
27763110 then FL.Done arr
27773111 else FL.Partial (Just arr)
3112+ -- XXX Buffer arrays as a list to avoid copy and reallocations
27783113 step (Just buf) arr = do
27793114 let len = byteLength buf + byteLength arr
27803115 buf1 <-
27813116 if byteCapacity buf < len
2782− then liftIO $ realloc (max len nBytes) buf
3117+ then liftIO $ reallocExplicitAs
3118+ ps (SIZE_OF(a)) (max minBytes len) buf
27833119 else return buf
27843120 buf2 <- spliceUnsafe buf1 arr
2785− if len >= n
3121+ if len >= minBytes
27863122 then return $ FL.Done buf2
27873123 else return $ FL.Partial (Just buf2)
27883124
27893125 extract Nothing = return nil
27903126 extract (Just buf) = return buf
27913127
2792−-- | Like 'compactGE' but for transforming folds instead of stream.
3128+-- | Fold @fCompactGE minElems@ coalesces adjacent arrays in the input stream
3129+-- until the size becomes greater than or equal to @minElems@.
27933130--
2794−-- >>> lCompactGE n = Fold.many (MutArray.fCompactGE n)
2795−--
2796−{-# INLINE_NORMAL lCompactGE #-}
2797−lCompactGE :: (MonadIO m, Unbox a)
2798− => Int -> Fold m (MutArray a) () -> Fold m (MutArray a) ()
2799−-- lCompactGE n = Fold.many (fCompactGE n)
2800−lCompactGE n (Fold step1 initial1 _ final1) =
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) =
28013152 Fold step initial extract final
28023153
28033154 where
28043155
3156+ minBytes = minElems * SIZE_OF(a)
3157+
28053158 functionName = "Streamly.Internal.Data.MutArray.lCompactGE"
28063159
28073160 initial = do
2808− when (n <= 0) $
3161+ when (minElems <= 0) $
28093162 -- XXX we can pass the module string from the higher level API
28103163 error $ functionName ++ ": the size of arrays ["
2811− ++ show n ++ "] must be a natural number"
3164+ ++ show minElems ++ "] must be a natural number"
28123165
28133166 r <- initial1
28143167 return $ first (Tuple' Nothing) r
28153168
2816− step (Tuple' Nothing r1) arr =
2817− let len = byteLength arr
2818− in if len >= n
2819− then do
2820− r <- step1 r1 arr
2821− case r of
2822− FL.Done _ -> return $ FL.Done ()
2823− FL.Partial s -> do
2824− _ <- final1 s
2825− res <- initial1
2826− return $ first (Tuple' Nothing) res
2827− else return $ FL.Partial $ Tuple' (Just arr) r1
2828−
2829− step (Tuple' (Just buf) r1) arr = do
2830− let len = byteLength buf + byteLength arr
2831− buf1 <- if byteCapacity buf < len
2832− then liftIO $ realloc (max n len) buf
2833− else return buf
2834− buf2 <- spliceUnsafe buf1 arr
2835−
2836− -- XXX this is common in both the equations of step
2837− if len >= n
3169+ {-# INLINE runInner #-}
3170+ runInner len acc buf =
3171+ if len >= minBytes
28383172 then do
2839− r <- step1 r1 buf2
3173+ r <- step1 acc buf
28403174 case r of
28413175 FL.Done _ -> return $ FL.Done ()
28423176 FL.Partial s -> do
28433177 _ <- final1 s
28443178 res <- initial1
28453179 return $ first (Tuple' Nothing) res
2846− else return $ FL.Partial $ Tuple' (Just buf2) r1
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
28473194
28483195 -- XXX Several folds do extract >=> final, therefore, we need to make final
2849− -- return "m b" rather than using extract post it if we want extract to be
3196+ -- return "m b" rather than using extract post it if we want extract to be
28503197 -- partial.
28513198 --
28523199 -- extract forces the pending buffer to be sent to the fold which is not
@@ -2860,6 +3207,23 @@ lCompactGE n (Fold step1 initial1 _ final1) =
28603207 FL.Partial rr -> final1 rr
28613208 FL.Done _ -> return ()
28623209
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+
28633227-- | @compactGE n stream@ coalesces adjacent arrays in the @stream@ until
28643228-- the size becomes greater than or equal to @n@.
28653229--