Ejemplo n.º 1
0
        public static ValueTask <object?> DeserializeAsync(
            Type objectType,
            Stream stream,
            CborOptions?options     = null,
            CancellationToken token = default)
        {
            if (stream is MemoryStream ms && ms.TryGetBuffer(out ArraySegment <byte> buffer))
            {
                ReadOnlySpan <byte> span = new ReadOnlySpan <byte>(buffer.Array, buffer.Offset, buffer.Count);
                return(new ValueTask <object?>(Cbor.Deserialize(objectType, span, options)));
            }

            ValueTask <IMemoryOwner <byte> > task = stream.ReadAsync(256, token);

            if (task.IsCompletedSuccessfully)
            {
                return(new ValueTask <object?>(Deserialize(task.Result)));
            }

            return(FinishDeserializeAsync(task));

            object?Deserialize(IMemoryOwner <byte> memoryOwner)
            {
                using (memoryOwner)
                {
                    return(Cbor.Deserialize(objectType, memoryOwner.Memory.Span, options));
                }
            }

            async ValueTask <object?> FinishDeserializeAsync(ValueTask <IMemoryOwner <byte> > localTask)
            {
                return(Deserialize(await localTask.ConfigureAwait(false)));
            }
        }
Ejemplo n.º 2
0
        public static ValueTask <object?> DeserializeAsync(
            Type objectType,
            PipeReader reader,
            CborOptions?options     = null,
            CancellationToken token = default)
        {
            ValueTask <ReadOnlySequence <byte> > task = reader.FullReadAsync(token);

            if (task.IsCompletedSuccessfully)
            {
                ReadOnlySequence <byte> sequence = task.Result;
                object?result = Cbor.Deserialize(objectType, sequence.GetSpan(), options);
                reader.AdvanceTo(sequence.End);
                return(new ValueTask <object?>(result));
            }

            return(FinishDeserializeAsync(task));

            async ValueTask <object?> FinishDeserializeAsync(ValueTask <ReadOnlySequence <byte> > localTask)
            {
                ReadOnlySequence <byte> sequence = await localTask.ConfigureAwait(false);

                object?result = Cbor.Deserialize(objectType, sequence.GetSpan(), options);

                reader.AdvanceTo(sequence.End);
                return(result);
            }
        }