summary refs log tree commit diff
path: root/crypto/src/asn1/ConstructedOctetStream.cs
blob: 1773b22ccf832cf4f54e07ddfec7e39fa9d30408 (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using System.IO;

using Org.BouncyCastle.Utilities.IO;

namespace Org.BouncyCastle.Asn1
{
	internal class ConstructedOctetStream
		: BaseInputStream
	{
		private readonly Asn1StreamParser _parser;

		private bool _first = true;
		private Stream _currentStream;

		internal ConstructedOctetStream(
			Asn1StreamParser parser)
		{
			_parser = parser;
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			if (_currentStream == null)
			{
				if (!_first)
					return 0;

				Asn1OctetStringParser s = (Asn1OctetStringParser)_parser.ReadObject();

				if (s == null)
					return 0;

				_first = false;
				_currentStream = s.GetOctetStream();
			}

			int totalRead = 0;

			for (;;)
			{
				int numRead = _currentStream.Read(buffer, offset + totalRead, count - totalRead);

				if (numRead > 0)
				{
					totalRead += numRead;

					if (totalRead == count)
						return totalRead;
				}
				else
				{
					Asn1OctetStringParser aos = (Asn1OctetStringParser)_parser.ReadObject();

					if (aos == null)
					{
						_currentStream = null;
						return totalRead;
					}

					_currentStream = aos.GetOctetStream();
				}
			}
		}

		public override int ReadByte()
		{
			if (_currentStream == null)
			{
				if (!_first)
					return 0;

				Asn1OctetStringParser s = (Asn1OctetStringParser)_parser.ReadObject();

				if (s == null)
					return 0;

				_first = false;
				_currentStream = s.GetOctetStream();
			}

			for (;;)
			{
				int b = _currentStream.ReadByte();

				if (b >= 0)
				{
					return b;
				}

				Asn1OctetStringParser aos = (Asn1OctetStringParser)_parser.ReadObject();

				if (aos == null)
				{
					_currentStream = null;
					return -1;
				}

				_currentStream = aos.GetOctetStream();
			}
		}
	}
}