HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

Modulestreamly-core-0.2.2Haskell2010

Streamly.Internal.Data.MutArray

  • 4 types
  • 179 values

MutArray.Type module

169 declarations
valueappend :: (MonadIO m, Unbox a) => m (MutArray a) -> Fold m a (MutArray a)
#

append action mutates the array generated by action to append the input stream. If there is no reserved space available in the array it is reallocated to double the size.

Note that the returned array may be a mutated version of original array.

Example1 expression
append = MutArray.appendWith (* 2)
valuefromStreamD :: (MonadIO m, Unbox a) => Stream m a -> m (MutArray a)
#

Deprecated. Please use fromStream instead.

We could take the approach of doubling the memory allocation on each overflow. This would result in more or less the same amount of copying as in the chunking approach. However, if we have to shrink in the end then it may result in an extra copy of the entire data.

Example1 expression
fromStreamD = StreamD.fold MutArray.create
valueconcat :: (MonadIO m, Unbox a) => Stream m (MutArray a) -> Stream m a
#

Use the "reader" unfold instead.

concat = unfoldMany reader

We can try this if there are any fusion issues in the unfold.

valuegetIndexUnsafe :: (MonadIO m, Unbox a) => Int -> MutArray a -> m a
#

Return the element at the specified index without checking the bounds.

Unsafe because it does not check the bounds of the array.

valuecastUnsafe :: MutArray a -> MutArray b
#

Cast an array having elements of type a into an array having elements of type b. The array size must be a multiple of the size of type b otherwise accessing the last element of the array may result into a crash or a random value.

Pre-release

datadata MutArray a
#

An unboxed mutable array. An array is created with a given length and capacity. Length is the number of valid elements in the array. Capacity is the maximum number of elements that the array can be expanded to without having to reallocate the memory.

The elements in the array can be mutated in-place without changing the reference (constructor). However, the length of the array cannot be mutated in-place. A new array reference is generated when the length changes. When the length is increased (upto the maximum reserved capacity of the array), the array is not reallocated and the new reference uses the same underlying memory as the old one.

Several routines in this module allow the programmer to control the capacity of the array. The programmer can control the trade-off between memory usage and performance impact due to reallocations when growing or shrinking the array.

Constructors

valuelength :: Unbox a => MutArray a -> Int
#

O(1) Get the length of the array i.e. the number of elements in the array.

Note that byteLength is less expensive than this operation, as length involves a costly division operation.

valuesplitAt :: Unbox a => Int -> MutArray a -> (MutArray a, MutArray a)
#

Create two slices of an array without copying the original array. The specified index i is the first index of the second slice.

valuenil :: MutArray a
#

Deprecated. Please use empty instead.

valueemptyOf :: (MonadIO m, Unbox a) => Int -> m (MutArray a)
#

Allocates an unpinned array of zero length but growable to the specified capacity without reallocation.

valueunsafeCreateOf :: (MonadIO m, Unbox a) => Int -> Fold m a (MutArray a)
#

Like createOf but does not check the array bounds when writing. The fold driver must not call the step function more than n times otherwise it will corrupt the memory and crash. This function exists mainly because any conditional in the step function blocks fusion causing 10x performance slowdown.

Example1 expression
unsafeCreateOf = MutArray.unsafeCreateOfWith MutArray.emptyOf
valuecreateOf :: (MonadIO m, Unbox a) => Int -> Fold m a (MutArray a)
#

createOf n folds a maximum of n elements from the input stream to an MutArray.

Example3 expressions
createOf = MutArray.createOfWith MutArray.newcreateOf n = Fold.take n (MutArray.unsafeCreateOf n)createOf n = MutArray.appendN n (MutArray.emptyOf n)
valuecreateWith :: (MonadIO m, Unbox a) => Int -> Fold m a (MutArray a)
#

createWith minCount folds the whole input to a single array. The array starts at a size big enough to hold minCount elements, the size is doubled every time the array needs to be grown.

Caution! Do not use this on infinite streams.

Example3 expressions
f n = MutArray.appendWith (* 2) (MutArray.emptyOf n)createWith n = Fold.rmapM MutArray.rightSize (f n)createWith n = Fold.rmapM MutArray.fromChunksK (MutArray.buildChunks n)

Pre-release

valuefromStream :: (MonadIO m, Unbox a) => Stream m a -> m (MutArray a)
#

Create an Array from a stream. This is useful when we want to create a single array from a stream of unknown size. createOf is at least twice as efficient when the size is already known.

Note that if the input stream is too large memory allocation for the array may fail. When the stream size is not known, chunksOf followed by processing of indvidual arrays in the resulting stream should be preferred.

Pre-release

valuefromListN :: (MonadIO m, Unbox a) => Int -> [a] -> m (MutArray a)
#

Create a MutArray from the first N elements of a list. The array is allocated to size N, if the list terminates before N elements then the array may hold less than N elements.

valueputIndex :: (MonadIO m, Unbox a) => Int -> MutArray a -> a -> m ()
#

O(1) Write the given element at the given index in the array. Performs in-place mutation of the array.

Example3 expressions
putIndex ix arr val = MutArray.modifyIndex ix arr (const (val, ()))f = MutArray.putIndicesputIndex ix arr val = Stream.fold (f arr) (Stream.fromPure (ix, val))
valueputIndexUnsafe :: (MonadIO m, Unbox a) => Int -> MutArray a -> a -> m ()
#

Write the given element to the given index of the array. Does not check if the index is out of bounds of the array.

Pre-release

valueputIndices :: (MonadIO m, Unbox a) => MutArray a -> Fold m (Int, a) ()
#

Write an input stream of (index, value) pairs to an array. Throws an error if any index is out of bounds.

Pre-release

valuemodifyIndexUnsafe
  1. :: (MonadIO m, Unbox a)
  2. => Int
  3. -> MutArray a
  4. -> a -> (a, b)
  5. -> m b
#

Modify a given index of an array using a modifier function.

Unsafe because it does not check the bounds of the array.

Pre-release

valuerealloc :: (MonadIO m, Unbox a) => Int -> MutArray a -> m (MutArray a)
#

realloc newCapacity array reallocates the array to the specified capacity in bytes.

If the new size is less than the original array the array gets truncated. If the new size is not a multiple of array element size then it is rounded down to multiples of array size. If the new size is more than largeObjectThreshold then it is rounded up to the block size (4K).

If the original array is pinned, the newly allocated array is also pinned.

valuesnocWith
  1. :: (MonadIO m, Unbox a)
  2. => Int -> Int
  3. -> MutArray a
  4. -> a
  5. -> m (MutArray a)
#

snocWith sizer arr elem mutates arr to append elem. The length of the array increases by 1.

If there is no reserved space available in arr it is reallocated to a size in bytes determined by the sizer oldSizeBytes function, where oldSizeBytes is the original size of the array in bytes.

If the new array size is more than largeObjectThreshold we automatically round it up to blockSize.

Note that the returned array may be a mutated version of the original array.

Pre-release

valuesnoc :: (MonadIO m, Unbox a) => MutArray a -> a -> m (MutArray a)
#

The array is mutated to append an additional element to it. If there is no reserved space available in the array then it is reallocated to double the original size.

This is useful to reduce allocations when appending unknown number of elements.

Note that the returned array may be a mutated version of the original array.

Example1 expression
snoc = MutArray.snocWith (* 2)

Performs O(n * log n) copies to grow, but is liberal with memory allocation.

valuesnocUnsafe :: (MonadIO m, Unbox a) => MutArray a -> a -> m (MutArray a)
#

Really really unsafe, appends the element into the first array, may cause silent data corruption or if you are lucky a segfault if the first array does not have enough space to append the element.

Internal

valuechunksOf
  1. :: (MonadIO m, Unbox a)
  2. => Int
  3. -> Stream m a
  4. -> Stream m (MutArray a)
#

chunksOf n stream groups the elements in the input stream into arrays of n elements each.

Same as the following but may be more efficient:

Example1 expression
chunksOf n = Stream.foldMany (MutArray.createOf n)

Pre-release

valuegetSlice
  1. :: Unbox a
  2. => Int

    from index

  3. -> Int

    length of the slice

  4. -> MutArray a
  5. -> MutArray a
#

O(1) Slice an array in constant time. Throws an error if the slice extends out of the array bounds.

Pre-release

valuemergeBy :: Int -> (MutArray a -> MutArray a -> m ()) -> MutArray a -> m ()
#

mergeBy level merge array performs a pairwise bottom up fold recursively merging the pairs using the supplied merge function. Level indicates the level in the tree where the fold would stop.

This performs a random shuffle if the merge function is random. If we stop at level 0 and repeatedly apply the function then we can do a bubble sort.

Unimplemented

valuereverse :: (MonadIO m, Unbox a) => MutArray a -> m ()
#

You may not need to reverse an array because you can consume it in reverse using readerRev. To reverse large arrays you can read in reverse and write to another array. However, in-place reverse can be useful to take adavantage of cache locality and when you do not want to allocate additional memory.

valuegetIndexRev :: (MonadIO m, Unbox a) => Int -> MutArray a -> m a
#

O(1) Lookup the element at the given index from the end of the array. Index starts from 0.

Slightly faster than computing the forward index and using getIndex.

valueindexReader
  1. :: (MonadIO m, Unbox a)
  2. => Stream m Int
  3. -> Unfold m (MutArray a) a
#

Given an unfold that generates array indices, read the elements on those indices from the supplied MutArray. An error is thrown if an index is out of bounds.

Pre-release

valuecast :: Unbox b => MutArray a -> Maybe (MutArray b)
#

Cast an array having elements of type a into an array having elements of type b. The length of the array should be a multiple of the size of the target element otherwise Nothing is returned.

valuecompactGE
  1. :: (MonadIO m, Unbox a)
  2. => Int
  3. -> Stream m (MutArray a)
  4. -> Stream m (MutArray a)
#

compactGE n stream coalesces adjacent arrays in the stream until the size becomes greater than or equal to n.

Example1 expression
compactGE n = Stream.foldMany (MutArray.fCompactGE n)
valuebyteCapacity :: MutArray a -> Int
#

Get the total capacity of an array. An array may have space reserved beyond the current used length of the array.

Pre-release

valuebytesFree :: MutArray a -> Int
#

The remaining capacity in the array for appending more elements without reallocation.

Pre-release

valuepin :: MutArray a -> IO (MutArray a)
#

Return a copy of the array in pinned memory if unpinned, else return the original array.

valueunpin :: MutArray a -> IO (MutArray a)
#

Return a copy of the array in unpinned memory if pinned, else return the original array.

valueappendN
  1. :: (MonadIO m, Unbox a)
  2. => Int
  3. -> m (MutArray a)
  4. -> Fold m a (MutArray a)
#

Append n elements to an existing array. Any free space left in the array after appending n elements is lost.

Example1 expression
appendN n initial = Fold.take n (MutArray.unsafeAppendN n initial)
valuemodify :: (MonadIO m, Unbox a) => MutArray a -> (a -> a) -> m ()
#

Modify each element of an array using the supplied modifier function.

This is an in-place equivalent of an immutable map operation.

Pre-release

valueunsafePinnedAsPtr :: MonadIO m => MutArray a -> (Ptr a -> m b) -> m b
#

Use a MutArray a as Ptr a. This is useful when we want to pass an array as a pointer to some operating system call or to a "safe" FFI call.

If the array is not pinned it is copied to pinned memory before passing it to the monadic action.

Performance Notes: Forces a copy if the array is not pinned. It is advised that the programmer keeps this in mind and creates a pinned array opportunistically before this operation occurs, to avoid the cost of a copy if possible.

Unsafe because of direct pointer operations. The user must ensure that they are writing within the legal bounds of the array.

Pre-release

valuenewArrayWith
  1. :: (MonadIO m, Unbox a)
  2. => Int -> Int -> m MutByteArray
  3. -> Int
  4. -> Int
  5. -> m (MutArray a)
#

newArrayWith allocator alignment count allocates a new array of zero length and with a capacity to hold count elements, using allocator size alignment as the memory allocator function.

Alignment must be greater than or equal to machine word size and a power of 2.

Alignment is ignored if the allocator allocates unpinned memory.

Pre-release

valuecreateOfWith
  1. :: (MonadIO m, Unbox a)
  2. => Int -> m (MutArray a)
  3. -> Int
  4. -> Fold m a (MutArray a)
#

createOfWith alloc n folds a maximum of n elements into an array allocated using the alloc function.

Example2 expressions
createOfWith alloc n = Fold.take n (MutArray.unsafeCreateOfWith alloc n)createOfWith alloc n = MutArray.appendN (alloc n) n
valueunsafeSwapIndices
  1. :: (MonadIO m, Unbox a)
  2. => Int
  3. -> Int
  4. -> MutArray a
  5. -> m ()
#

Swap the elements at two indices without validating the indices.

Unsafe: This could result in memory corruption if indices are not valid.

Pre-release

valueblockSize :: Int
#

The page or block size used by the GHC allocator. Allocator allocates at least a block and then allocates smaller allocations from within a block.

valuearrayChunkBytes :: Int
#

The default chunk size by which the array creation routines increase the size of the array when the array is grown linearly.

valueallocBytesToElemCount :: Unbox a => a -> Int -> Int
#

Given an Unboxed type (unused first arg) and real allocation size (including overhead), return how many elements of that type will completely fit in it, returns at least 1.

valuegrow :: (MonadIO m, Unbox a) => Int -> MutArray a -> m (MutArray a)
#

grow newCapacity array changes the total capacity of the array so that it is enough to hold the specified number of elements. Nothing is done if the specified capacity is less than the length of the array.

If the capacity is more than largeObjectThreshold then it is rounded up to the block size (4K).

Pre-release

valuegrowExp :: (MonadIO m, Unbox a) => Int -> MutArray a -> m (MutArray a)
#

Like grow but if the requested byte capacity is more than largeObjectThreshold then it is rounded up to the closest power of 2.

Pre-release

valuerightSize :: (MonadIO m, Unbox a) => MutArray a -> m (MutArray a)
#

Resize the allocated memory to drop any reserved free space at the end of the array and reallocate it to reduce wastage.

Up to 25% wastage is allowed to avoid reallocations. If the capacity is more than largeObjectThreshold then free space up to the blockSize is retained.

Pre-release

valuebyteCmp :: MonadIO m => MutArray a -> MutArray a -> m Ordering
#

Byte compare two arrays. Compare the length of the arrays. If the length is equal, compare the lexicographical ordering of two underlying byte arrays otherwise return the result of length comparison.

Unsafe: Note that the Unbox instance of sum types with constructors of different sizes may leave some memory uninitialized which can make byte comparison unreliable.

Pre-release

valuepermute :: MutArray a -> m Bool
#

Generate the next permutation of the sequence, returns False if this is the last permutation.

Unimplemented

valueshuffleBy :: (a -> a -> m Bool) -> MutArray a -> MutArray a -> m ()
#

Shuffle corresponding elements from two arrays using a shuffle function. If the shuffle function returns False then do nothing otherwise swap the elements. This can be used in a bottom up fold to shuffle or reorder the elements.

Unimplemented

valuedivideBy
  1. :: Int
  2. -> MutArray a -> m (MutArray a, MutArray a)
  3. -> MutArray a
  4. -> m ()
#

divideBy level partition array performs a top down hierarchical recursive partitioning fold of items in the container using the given function as the partition function. Level indicates the level in the tree where the fold would stop.

This performs a quick sort if the partition function is 'partitionBy (< pivot)'.

Unimplemented

valuebubble :: (MonadIO m, Unbox a) => (a -> a -> Ordering) -> MutArray a -> m ()
#

Given an array sorted in ascending order except the last element being out of order, use bubble sort to place the last element at the right place such that the array remains sorted in ascending order.

Pre-release

valuesnocLinear :: (MonadIO m, Unbox a) => MutArray a -> a -> m (MutArray a)
#

The array is mutated to append an additional element to it. If there is no reserved space available in the array then it is reallocated to grow it by arrayChunkBytes rounded up to blockSize when the size becomes more than largeObjectThreshold.

Note that the returned array may be a mutated version of the original array.

Performs O(n^2) copies to grow but is thrifty on memory.

Pre-release

valueunsafeAppendN
  1. :: (MonadIO m, Unbox a)
  2. => Int
  3. -> m (MutArray a)
  4. -> Fold m a (MutArray a)
#

unsafeAppendN n arr appends up to n input items to the supplied array.

Unsafe: Do not drive the fold beyond n elements, it will lead to memory corruption or segfault.

Any free space left in the array after appending n elements is lost.

Internal

valueappendWith
  1. :: (MonadIO m, Unbox a)
  2. => Int -> Int
  3. -> m (MutArray a)
  4. -> Fold m a (MutArray a)
#

appendWith realloc action mutates the array generated by action to append the input stream. If there is no reserved space available in the array it is reallocated to a size in bytes determined by realloc oldSize, where oldSize is the current size of the array in bytes.

Note that the returned array may be a mutated version of original array.

Example1 expression
appendWith sizer = Fold.foldlM' (MutArray.snocWith sizer)

Pre-release

valuespliceWith
  1. :: (MonadIO m, Unbox a)
  2. => Int -> Int -> Int
  3. -> MutArray a
  4. -> MutArray a
  5. -> m (MutArray a)
#

spliceWith sizer dst src mutates dst to append src. If there is no reserved space available in dst it is reallocated to a size determined by the sizer dstBytes srcBytes function, where dstBytes is the size of the first array and srcBytes is the size of the second array, in bytes.

Note that the returned array may be a mutated version of first array.

Pre-release

valuesplice :: (MonadIO m, Unbox a) => MutArray a -> MutArray a -> m (MutArray a)
#

The first array is mutated to append the second array. If there is no reserved space available in the first array a new allocation of exact required size is done.

Note that the returned array may be a mutated version of first array.

Example1 expression
splice = MutArray.spliceWith (+)

If the original array is pinned the spliced array is also pinned.

Pre-release

valuespliceExp
  1. :: (MonadIO m, Unbox a)
  2. => MutArray a
  3. -> MutArray a
  4. -> m (MutArray a)
#

Like append but the growth of the array is exponential. Whenever a new allocation is required the previous array size is at least doubled.

This is useful to reduce allocations when folding many arrays together.

Note that the returned array may be a mutated version of first array.

Example1 expression
spliceExp = MutArray.spliceWith (\l1 l2 -> max (l1 * 2) (l1 + l2))

Pre-release

valuespliceUnsafe :: MonadIO m => MutArray a -> MutArray a -> m (MutArray a)
#

Really really unsafe, appends the second array into the first array. If the first array does not have enough space it may cause silent data corruption or if you are lucky a segfault.

valuepokeAppend
  1. :: (MonadIO m, Unbox a)
  2. => MutArray Word8
  3. -> a
  4. -> m (MutArray Word8)
#

Unbox a Haskell type and append the resulting bytes to a mutable byte array. The array is grown exponentially when more space is needed.

Definition:

Example1 expression
pokeAppend arr x = MutArray.castUnsafe <$> MutArray.snoc (MutArray.castUnsafe arr) x
valuepeekUnconsUnsafe
  1. :: (MonadIO m, Unbox a)
  2. => MutArray Word8
  3. -> m (a, MutArray Word8)
#

Really really unsafe, create a Haskell value from an unboxed byte array, does not check if the array is big enough, may return garbage or if you are lucky may cause a segfault.

Internal

valuebuildChunks
  1. :: (MonadIO m, Unbox a)
  2. => Int
  3. -> Fold m a (StreamK n (MutArray a))
#

Buffer a stream into a stream of arrays.

Example1 expression
buildChunks n = Fold.many (MutArray.createOf n) Fold.toStreamK

Breaking an array into an array stream can be useful to consume a large array sequentially such that memory of the array is released incrementatlly.

See also: arrayStreamKFromStreamD.

Unimplemented

valuepCompactLE
  1. :: (MonadIO m, Unbox a)
  2. => Int
  3. -> Parser (MutArray a) m (MutArray a)
#

Parser pCompactLE maxElems coalesces adjacent arrays in the input stream only if the combined size would be less than or equal to maxElems elements. Note that it won't split an array if the original array is already larger than maxElems.

maxElems must be greater than 0.

Generates unpinned arrays irrespective of the pinning status of input arrays.

Internal

valuefCompactGE
  1. :: (MonadIO m, Unbox a)
  2. => Int
  3. -> Fold m (MutArray a) (MutArray a)
#

Fold fCompactGE minElems coalesces adjacent arrays in the input stream until the size becomes greater than or equal to minElems.

Generates unpinned arrays irrespective of the pinning status of input arrays.

valuelCompactGE
  1. :: (MonadIO m, Unbox a)
  2. => Int
  3. -> Fold m (MutArray a) ()
  4. -> Fold m (MutArray a) ()
#

Like compactGE but for transforming folds instead of stream.

Example1 expression
lCompactGE n = Fold.many (MutArray.fCompactGE n)

Generates unpinned arrays irrespective of the pinning status of input arrays.

valuepinnedNewBytes :: MonadIO m => Int -> m (MutArray a)
#

Deprecated. Please use pinnedEmptyOf with appropriate calculation

Allocates a pinned empty array that with a reserved capacity of bytes. The memory of the array is uninitialized and the allocation is aligned as per the Unboxed instance of the type.

Pre-release

valuepinnedWriteNAligned
  1. :: (MonadIO m, Unbox a)
  2. => Int
  3. -> Int
  4. -> Fold m a (MutArray a)
#

pinnedWriteNAligned align n folds a maximum of n elements from the input stream to a MutArray aligned to the given size.

Example2 expressions
pinnedWriteNAligned align = MutArray.createOfWith (MutArray.pinnedNewAligned align)pinnedWriteNAligned align n = MutArray.appendN n (MutArray.pinnedNewAligned align n)

Pre-release

MutArray module

6 declarations
valuesliceIndexerFromLen
  1. :: (Monad m, Unbox a)
  2. => Int

    from index

  3. -> Int

    length of the slice

  4. -> Unfold m (MutArray a) (Int, Int)
#

Generate a stream of array slice descriptors ((index, len)) of specified length from an array, starting from the supplied array index. The last slice may be shorter than the requested length depending on the array length.

Pre-release

valueslicerFromLen
  1. :: (Monad m, Unbox a)
  2. => Int

    from index

  3. -> Int

    length of the slice

  4. -> Unfold m (MutArray a) (MutArray a)
#

Generate a stream of slices of specified length from an array, starting from the supplied array index. The last slice may be shorter than the requested length depending on the array length.

Pre-release

valuecompactLE
  1. :: (MonadIO m, Unbox a)
  2. => Int
  3. -> Stream m (MutArray a)
  4. -> Stream m (MutArray a)
#

compactLE maxElems coalesces adjacent arrays in the input stream only if the combined size would be less than or equal to maxElems elements. Note that it won't split an array if the original array is already larger than maxElems.

maxElems must be greater than 0.

Generates unpinned arrays irrespective of the pinning status of input arrays.

Unboxed IORef

6 declarations
valuepollIntIORef :: (MonadIO m, Unbox a) => IORef a -> Stream m a
#

Generate a stream by continuously reading the IORef.

This operation reads the IORef without any synchronization. It can be assumed to be atomic because the IORef (MutableByteArray) is always aligned to Int boundaries, we are assuming that compiler uses single instructions to access the memory. It may read stale values though until caches are synchronised in a multiprocessor architecture.

Pre-release

Deprecated

2 declarations