示例#1
0
        /// Create and populate a segment with random data
        public static DataSegment CreateRandom(Random random, int maxLength)
        {
            int size  = random.Next(0, maxLength);
            var chunk = new DataSegment(size);

            foreach (ref byte b in chunk.AsSpan())
            {
                b = s_bytePool[random.Next(255)];
            }

            return(chunk);
        }
示例#2
0
        public DataSegment Deserialize(ReadOnlySequence <byte> buffer)
        {
            // length
            SequencePosition?pos = buffer.PositionOf((byte)',');

            if (pos == null)
            {
                throw new DataMismatchException("should contain comma-separated values");
            }

            ReadOnlySequence <byte> lengthBytes = buffer.Slice(0, pos.Value);
            int numSize = s_encoding.GetChars(lengthBytes.ToArray(), _charBuffer);
            int length  = int.Parse(_charBuffer.AsSpan().Slice(0, numSize));

            buffer = buffer.Slice(buffer.GetPosition(1, pos.Value));

            // checksum
            pos = buffer.PositionOf((byte)',');
            if (pos == null)
            {
                throw new DataMismatchException("should contain comma-separated values");
            }

            ReadOnlySequence <byte> checksumBytes = buffer.Slice(0, pos.Value);

            numSize = s_encoding.GetChars(checksumBytes.ToArray(), _charBuffer);
            ulong checksum = ulong.Parse(_charBuffer.AsSpan().Slice(0, numSize));

            buffer = buffer.Slice(buffer.GetPosition(1, pos.Value));

            // payload
            if (length != (int)buffer.Length)
            {
                throw new DataMismatchException("declared length does not match payload length");
            }

            var chunk = new DataSegment((int)buffer.Length);

            buffer.CopyTo(chunk.AsSpan());

            if (checksum != chunk.Checksum)
            {
                chunk.Return();
                throw new DataMismatchException("declared checksum doesn't match payload checksum");
            }

            return(chunk);
        }