BufToStream(ReadOnlySpan <byte> buf, ref int offset) { int len = LenSerial.Decode(buf, ref offset); if (len < 0) { // Stream was null. return(null); } if (len == 0) { return(new MemoryStream()); } // Need extra check... (buf.Length - offset) should be greater or equal to decoded len. byte[] arr = new byte[len]; Span <byte> s = new Span <byte>(arr); buf.Slice(offset, len).CopyTo(s); MemoryStream ms = new MemoryStream(arr); offset += len; return(ms); }
/// <summary> /// /// </summary> public static void Test_BufLen() { using MemoryStream ms = new(); int offset = 0; int n; LenSerial.EncodeNull(ms); Debug.Assert(ms.ToArray()[0] == (byte)EncodedLen.NULL); ms.SetLength(0); LenSerial.Encode(10, ms); offset = 0; Debug.Assert(LenSerial.Decode(ms.ToArray(), ref offset) == 10); ms.SetLength(0); n = LenSerial.Encode(2345, ms); Debug.Assert(n == 3 && ms.ToArray().Length == 3); offset = 0; Debug.Assert(LenSerial.Decode(ms.ToArray(), ref offset) == 2345); ms.SetLength(0); LenSerial.Encode(123123123, ms); offset = 0; Debug.Assert(LenSerial.Decode(ms.ToArray(), ref offset) == 123123123); }
BufToString(ReadOnlySpan <byte> buf, ref int offset) { int decodedLen; try { decodedLen = LenSerial.Decode(buf, ref offset); } catch (ArgumentOutOfRangeException) { throw new BufSeriaLenException("Length can't be converted to uint."); } catch (IndexOutOfRangeException) { throw new BufSeriaLenException("Length can't be decoded."); } if (decodedLen > buf.Length) { throw new BufSeriaLenException("String's length is overflowing the buffer."); } if (decodedLen == 0) { return(""); } if (decodedLen < 0) { return(null); } string ret = Encoding.UTF8.GetString(buf.ToArray(), offset, decodedLen); offset += decodedLen; return(ret); }
BufToBytes(ReadOnlySpan <byte> buf, ref int offset) { int idx = offset; int len = LenSerial.Decode(buf, ref offset); if (len < 0) { return(null); } if (len == 0) { return(new byte[0]); } byte[] arr = new byte[len]; Span <byte> s = new Span <byte>(arr); buf.Slice(offset, len).CopyTo(s); offset += len; return(arr); }