Example #1
0
        private static Message <RentedArray> Deserialize(DeserializationContext context)
        {
            var sequence = context.PayloadAsReadOnlySequence();
            var length   = context.PayloadLength;
            var source   = sequence.Slice(0, length);

            var rentedArray = RentedArray.Rent(length);

            source.CopyTo(rentedArray.Array.AsSpan(0, length));

            return(new Message <RentedArray>(rentedArray));
        }
Example #2
0
        public static async IAsyncEnumerable <RentedArray> ToAsyncEnumerableRented(
            this Stream stream,
            [EnumeratorCancellation] CancellationToken token,
            Action <long> onProgress = default,
            int?maxBufferSize        = default)
        {
            var chunkSize = CalculateChunkSize(maxBufferSize, stream);

            await using (stream)
                using (var chunk = RentedArray.Rent(chunkSize))
                {
                    var progress    = 0L;
                    var chunkOffset = 0;
                    int readLength;
                    while ((readLength = await stream.ReadAsync(chunk.Array, chunkOffset, chunkSize - chunkOffset, token)) > 0)
                    {
                        chunkOffset += readLength;
                        if (chunkOffset == chunkSize)
                        {
                            chunkOffset = 0;
                            yield return(chunk);

                            progress += chunkSize;
                            onProgress?.Invoke(progress);
                        }
                    }

                    if (chunkOffset > 0)
                    {
                        chunk.Resize(chunkOffset);
                        yield return(chunk);

                        progress += chunkOffset;
                        onProgress?.Invoke(progress);
                    }
                }
        }