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,
Eof = 4
}
internal static uint ReadBodyLen(Stream s, out StreamFlags flags)
{
flags = StreamFlags.None;
int num = s.ReadByte();
if (num < 0) {
flags = StreamFlags.Eof;
return 0;
}
if (num < 192)
return (uint)num;
if (num < 224) {
int num2 = RequireByte(s);
return (uint)((num - 192 << 8) + num2 + 192);
}
if (num == 255) {
flags |= StreamFlags.LongLength;
return RequireUInt32BE(s);
}
flags |= StreamFlags.Partial;
return (uint)(1 << num);
}
internal static uint RequireBodyLen(Stream s, out StreamFlags streamFlags)
{
uint result = ReadBodyLen(s, out streamFlags);
if (streamFlags.HasFlag(StreamFlags.Eof))
throw new EndOfStreamException();
return result;
}
internal static byte RequireByte(Stream s)
{
int num = s.ReadByte();
if (num < 0)
throw new EndOfStreamException();
return (byte)num;
}
internal static byte[] RequireBytes(Stream s, int count)
{
byte[] array = new byte[count];
RequireBytes(s, array);
return array;
}
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 ushort RequireUInt16BE(Stream s)
{
byte[] array = new byte[2];
RequireBytes(s, array);
return Pack.BE_To_UInt16(array);
}
internal static uint RequireUInt32BE(Stream s)
{
byte[] array = new byte[4];
RequireBytes(s, array);
return Pack.BE_To_UInt32(array);
}
internal static ulong RequireUInt64BE(Stream s)
{
byte[] array = new byte[8];
RequireBytes(s, array);
return Pack.BE_To_UInt64(array);
}
internal static void WriteNewPacketLength(Stream s, long bodyLen, bool longLength = false)
{
if (longLength || bodyLen > 8383) {
s.WriteByte(byte.MaxValue);
s.WriteByte((byte)(bodyLen >> 24));
s.WriteByte((byte)(bodyLen >> 16));
s.WriteByte((byte)(bodyLen >> 8));
s.WriteByte((byte)bodyLen);
} else if (bodyLen < 192) {
s.WriteByte((byte)bodyLen);
} else {
bodyLen -= 192;
s.WriteByte((byte)(((bodyLen >> 8) & 255) + 192));
s.WriteByte((byte)bodyLen);
}
}
internal static void WriteUInt16BE(Stream s, ushort n)
{
s.WriteByte((byte)(n >> 8));
s.WriteByte((byte)n);
}
internal static void WriteUInt32BE(Stream s, uint n)
{
byte[] array = new byte[4];
Pack.UInt32_To_BE(n, array, 0);
s.Write(array, 0, array.Length);
}
internal static void WriteUInt64BE(Stream s, ulong n)
{
byte[] array = new byte[8];
Pack.UInt64_To_BE(n, array, 0);
s.Write(array, 0, array.Length);
}
}
}