Strict left fold of an array.
Modulestreamly-core-0.2.2Haskell2010
Streamly.Internal.Data.MutArray
- 4 types
- 179 values
- Packagestreamly-core-0.2.2
- Exports183
- LanguageHaskell2010
- LicenceBSD-3-Clause
- SourceType.hs
MutArray.Type module
169 declarationsappend 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.
append = MutArray.appendWith (* 2)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.
fromStreamD = StreamD.fold MutArray.createUse the "reader" unfold instead.
concat = unfoldMany readerWe can try this if there are any fusion issues in the unfold.
Return the element at the specified index without checking the bounds.
Unsafe because it does not check the bounds of the array.
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
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
MutArrayarrContents :: !MutByteArrayarrStart :: !Intindex into arrContents
arrEnd :: !Intindex into arrContents Represents the first invalid index of the array.
arrBound :: !Intfirst invalid index of arrContents.
Right fold of an array.
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.
Convert a MutArray into a stream.
read = Stream.unfold MutArray.readerCreate two slices of an array without copying the original array. The
specified index i is the first index of the second slice.
Deprecated. Please use empty instead.
Allocates an unpinned array of zero length but growable to the specified capacity without reallocation.
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.
unsafeCreateOf = MutArray.unsafeCreateOfWith MutArray.emptyOfcreateOf n folds a maximum of n elements from the input stream to an
MutArray.
createOf = MutArray.createOfWith MutArray.newcreateOf n = Fold.take n (MutArray.unsafeCreateOf n)createOf n = MutArray.appendN n (MutArray.emptyOf n)
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.
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
Fold the whole input to a single array.
Same as createWith using an initial array size of arrayChunkBytes bytes rounded up to the element size.
Caution! Do not use this on infinite streams.
Use the createOf fold instead.
fromStreamN n = Stream.fold (MutArray.createOf n)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
Convert a pure stream in Identity monad to a mutable array.
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.
Create a MutArray from a list. The list must be of finite size.
O(1) Write the given element at the given index in the array. Performs in-place mutation of the array.
putIndex ix arr val = MutArray.modifyIndex ix arr (const (val, ()))f = MutArray.putIndicesputIndex ix arr val = Stream.fold (f arr) (Stream.fromPure (ix, val))
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
Write an input stream of (index, value) pairs to an array. Throws an error if any index is out of bounds.
Pre-release
Modify a given index of an array using a modifier function.
Unsafe because it does not check the bounds of the array.
Pre-release
Modify a given index of an array using a modifier function.
Pre-release
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.
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
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.
snoc = MutArray.snocWith (* 2)Performs O(n * log n) copies to grow, but is liberal with memory allocation.
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
Unfold an array into a stream.
Resumable unfold of an array.
Convert a MutArray into a stream in reverse order.
readRev = Stream.unfold MutArray.readerRevConvert a MutArray into a list.
O(1) Lookup the element at the given index. Index starts from 0.
Strip elements which match with predicate from both ends.
Pre-release
Deprecated. Please use byteCmp instead.
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:
chunksOf n = Stream.foldMany (MutArray.createOf n)Pre-release
O(1) Slice an array in constant time.
Unsafe: The bounds of the slice are not checked.
Unsafe
Pre-release
O(1) Slice an array in constant time. Throws an error if the slice extends out of the array bounds.
Pre-release
Deprecated. Please use unsafeCreateOf instead.
Deprecated. Please use createWith instead.
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
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.
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.
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
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.
Cast an MutArray a into an MutArray Word8.
Generate a stream of array slices using a predicate. The array element matching the predicate is dropped.
Pre-release
Deprecated. Please use indexReader instead.
Like chunksOf but creates pinned arrays.
Deprecated. Please use buildChunks instead.
Constructors
SpliceInitial sSpliceBuffering s arrSpliceYielding arr (SpliceState s arr)SpliceFinish
'compactEQ n' coalesces adajacent arrays in the input stream to
arrays of exact size n.
Unimplemented
compactGE n stream coalesces adjacent arrays in the stream until
the size becomes greater than or equal to n.
compactGE n = Stream.foldMany (MutArray.fCompactGE n)Deprecated. Please use "unfoldMany reader" instead.
Deprecated. Please use "unfoldMany readerRev" instead.
Deprecated. Please use fromChunksK instead.
Use the "readerRev" unfold instead.
concat = unfoldMany readerRevWe can try this if there are any fusion issues in the unfold.
O(1) Get the byte length of the array.
Deprecated. Please use appendWith instead.
Get the total capacity of an array. An array may have space reserved beyond the current used length of the array.
Pre-release
The remaining capacity in the array for appending more elements without reallocation.
Pre-release
Return True if the array is allocated in pinned memory.
Return a copy of the array in pinned memory if unpinned, else return the original array.
Return a copy of the array in unpinned memory if pinned, else return the original array.
Unfold an array into a stream in reverse order.
Allocates a pinned array of zero length but growable to the specified capacity without reallocation.
Append n elements to an existing array. Any free space left in the array
after appending n elements is lost.
appendN n initial = Fold.take n (MutArray.unsafeAppendN n initial)Modify each element of an array using the supplied modifier function.
This is an in-place equivalent of an immutable map operation.
Pre-release
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
Create an empty array.
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
Like newArrayWith but using an allocator is a pinned memory allocator and
the alignment is dictated by the Unboxed instance of the type.
Internal
Drops the separator byte
Constructors
Like unsafeCreateOf but takes a new array allocator alloc size
function as argument.
unsafeCreateOfWith alloc n = MutArray.unsafeAppendN (alloc n) nPre-release
Like unsafeCreateOf but creates a pinned array.
Like createOf but creates a pinned array.
createOfWith alloc n folds a maximum of n elements into an array
allocated using the alloc function.
createOfWith alloc n = Fold.take n (MutArray.unsafeCreateOfWith alloc n)createOfWith alloc n = MutArray.appendN (alloc n) n
Like createOf but writes the array in reverse order.
Pre-release
Like create but creates a pinned array.
Like fromListN but creates a pinned array.
Like fromList but creates a pinned array.
Like fromListN but writes the array in reverse order.
Pre-release
Like fromList but writes the contents of the list in reverse order.
Convert a pure stream in Identity monad to a mutable array.
Convert an array stream to an array. Note that this requires peak memory that is double the size of the array stream.
Also see fromChunksRealloced.
Also see fromChunksK.
Modify the array indices generated by the supplied stream.
Pre-release
Swap the elements at two indices.
Pre-release
Swap the elements at two indices without validating the indices.
Unsafe: This could result in memory corruption if indices are not valid.
Pre-release
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.
The default chunk size by which the array creation routines increase the size of the array when the array is grown linearly.
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.
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
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
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
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
Byte equality of two arrays.
byteEq arr1 arr2 = (==) EQ $ MArray.byteCmp arr1 arr2Unsafe: See byteCmp.
Generate the next permutation of the sequence, returns False if this is the last permutation.
Unimplemented
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
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
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
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
Like snoc but does not reallocate when pre-allocated array capacity becomes full.
Internal
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
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.
appendWith sizer = Fold.foldlM' (MutArray.snocWith sizer)Pre-release
Copy two arrays into a newly allocated array. If the first array is pinned the spliced array is also pinned.
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
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.
splice = MutArray.spliceWith (+)If the original array is pinned the spliced array is also pinned.
Pre-release
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.
spliceExp = MutArray.spliceWith (\l1 l2 -> max (l1 * 2) (l1 + l2))Pre-release
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.
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:
pokeAppend arr x = MutArray.castUnsafe <$> MutArray.snoc (MutArray.castUnsafe arr) xLike pokeAppend but does not grow the array when pre-allocated array capacity becomes full.
Internal
Skip the specified number of bytes in the array. The data in the skipped region remains uninitialzed.
Create a Haskell value from its unboxed representation from the head of a byte array, return the value and the remaining array.
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
Discard the specified number of bytes in the array.
Buffer a stream into a stream of arrays.
buildChunks n = Fold.many (MutArray.createOf n) Fold.toStreamKBreaking 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
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
Pinned version of pCompactLE.
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.
Pinned version of fCompactGE.
Like compactGE but for transforming folds instead of stream.
lCompactGE n = Fold.many (MutArray.fCompactGE n)Generates unpinned arrays irrespective of the pinning status of input arrays.
Pinned version of lCompactGE.
Deprecated. Please use unsafePinnedAsPtr instead.
Deprecated. Please use fromStreamN instead.
Deprecated. Please use indexReaderWith instead.
Deprecated. Please use grow instead.
Deprecated. Please use growExp instead.
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
Deprecated. Please use unsafeAppendN instead.
Deprecated. Please use unsafeCreateOfWith instead.
Deprecated. Please use unsafePinnedCreateOf instead.
Deprecated. Please use pinnedCreateOf instead.
pinnedWriteNAligned align n folds a maximum of n elements from the
input stream to a MutArray aligned to the given size.
pinnedWriteNAligned align = MutArray.createOfWith (MutArray.pinnedNewAligned align)pinnedWriteNAligned align n = MutArray.appendN n (MutArray.pinnedNewAligned align n)
Pre-release
Deprecated. Please use pinnedCreate instead.
Deprecated. Please use revCreateOf instead.
MutArray module
6 declarationssliceIndexerFromLen 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
slicerFromLen 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
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.
Pinned version of compactLE.
Split a stream of arrays on a given separator byte, dropping the separator and coalescing all the arrays between two separators into a single array.
Like compactOnByte considers the separator in suffix position instead of infix position.
Unboxed IORef
6 declarationsCreate a new IORef.
Pre-release
Read a value from an IORef.
Pre-release
Write a value to an IORef.
Pre-release
Modify the value of an IORef using a function with strict application.
Pre-release
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 declarationsgenSlicesFromLen Deprecated. Please use sliceIndexerFromLen instead.
getSlicesFromLen Deprecated. Please use slicerFromLen instead.