StreamUtilities
using Org.BouncyCastle.Crypto.Utilities;
using Org.BouncyCastle.Utilities.IO;
using System;
using System.IO;
namespace Org.BouncyCastle.Bcpg
{
internal static class StreamUtilities
{
[Flags]
internal enum StreamFlags
{
None = 0,
LongLength = 1,
Partial = 2
}
internal static int ReadBodyLen(Stream s, out StreamFlags flags)
{
flags = StreamFlags.None;
int num = s.ReadByte();
if (num < 0)
return -1;
if (num < 192)
return num;
if (num < 224) {
int num2 = RequireByte(s);
return (num - 192 << 8) + num2 + 192;
}
if (num == 255) {
flags |= StreamFlags.LongLength;
return (int)RequireUInt32BE(s);
}
flags |= StreamFlags.Partial;
return 1 << num;
}
internal static int RequireBodyLen(Stream s, out StreamFlags flags)
{
int num = ReadBodyLen(s, out flags);
if (num < 0)
throw new EndOfStreamException();
return num;
}
internal static byte RequireByte(Stream s)
{
int num = s.ReadByte();
if (num < 0)
throw new EndOfStreamException();
return (byte)num;
}
internal static void RequireBytes(Stream s, byte[] buffer)
{
RequireBytes(s, buffer, 0, buffer.Length);
}
internal static void RequireBytes(Stream s, byte[] buffer, int offset, int count)
{
if (Streams.ReadFully(s, buffer, offset, count) < count)
throw new EndOfStreamException();
}
internal static void RequireBytes(Stream s, Span<byte> buffer)
{
if (Streams.ReadFully(s, buffer) != buffer.Length)
throw new EndOfStreamException();
}
internal unsafe static ushort RequireUInt16BE(Stream s)
{
Span<byte> span = new Span<byte>(stackalloc byte[2], 2);
RequireBytes(s, span);
return Pack.BE_To_UInt16(span);
}
internal unsafe static uint RequireUInt32BE(Stream s)
{
Span<byte> span = new Span<byte>(stackalloc byte[4], 4);
RequireBytes(s, span);
return Pack.BE_To_UInt32(span);
}
internal unsafe static ulong RequireUInt64BE(Stream s)
{
Span<byte> span = new Span<byte>(stackalloc byte[8], 8);
RequireBytes(s, span);
return Pack.BE_To_UInt64(span);
}
}
}