summary refs log tree commit diff
path: root/crypto/src/util/io/PushbackStream.cs
blob: 95469425963a3e3dff5bee564f2bcf0fd1c14d01 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.IO;

using Org.BouncyCastle.Asn1.Utilities;

namespace Org.BouncyCastle.Utilities.IO
{
	public class PushbackStream
		: FilterStream
	{
		private int buf = -1;

		public PushbackStream(
			Stream s)
			: base(s)
		{
		}

		public override int ReadByte()
		{
			if (buf != -1)
			{
				int tmp = buf;
				buf = -1;
				return tmp;
			}

			return base.ReadByte();
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			if (buf != -1 && count > 0)
			{
				// TODO Can this case be made more efficient?
				buffer[offset] = (byte) buf;
				buf = -1;
				return 1;
			}

			return base.Read(buffer, offset, count);
		}

		public virtual void Unread(int b)
		{
			if (buf != -1)
				throw new InvalidOperationException("Can only push back one byte");

			buf = b & 0xFF;
		}
	}
}