2 * Novacoin classes library
3 * Copyright (C) 2015 Alex D. (balthazar.ad@gmail.com)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Affero General Public License for more details.
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 using System.Collections.Generic;
21 using System.Diagnostics.Contracts;
27 public class ByteQueueException : Exception
29 public ByteQueueException()
33 public ByteQueueException(string message)
38 public ByteQueueException(string message, Exception inner)
39 : base(message, inner)
47 /// TODO: rewrite using MemoryStream
49 public class ByteQueue : IDisposable
51 private bool disposed = false;
53 private MemoryStream _Stream;
54 private BinaryReader _Reader;
56 public ByteQueue(ref byte[] buffer, int Start)
58 _Stream = new MemoryStream(buffer);
59 _Stream.Seek(Start, SeekOrigin.Begin);
60 _Reader = new BinaryReader(_Stream);
63 public ByteQueue(ref byte[] buffer)
65 _Stream = new MemoryStream(buffer);
66 _Reader = new BinaryReader(_Stream);
69 public ByteQueue(ref List<byte> List, int Start)
71 _Stream = new MemoryStream(List.ToArray());
72 _Stream.Seek(Start, SeekOrigin.Begin);
73 _Reader = new BinaryReader(_Stream);
76 public ByteQueue(ref List<byte> List)
78 _Stream = new MemoryStream(List.ToArray());
79 _Reader = new BinaryReader(_Stream);
90 GC.SuppressFinalize(this);
93 protected virtual void Dispose(bool disposing)
109 if (_Stream.Position == _Stream.Length)
111 throw new ByteQueueException("No elements left.");
114 return _Reader.ReadByte();
117 public bool TryGet(ref byte Element)
119 if (_Stream.Position == _Stream.Length)
124 Element = _Reader.ReadByte();
129 public byte[] Get(int nCount)
131 Contract.Requires<ArgumentException>(Count - Index >= nCount, "nCount is greater than amount of elements.");
133 return _Reader.ReadBytes(nCount);
136 public bool TryGet(int nCount, ref byte[] Elements)
138 Elements = _Reader.ReadBytes(nCount);
139 return (Elements.Length == nCount);
143 /// Current index value
147 get { return (int)_Stream.Position; }
152 get { return (int)_Stream.Length; }
155 public ulong GetVarInt()
159 byte prefix = _Reader.ReadByte();
164 return _Reader.ReadUInt16();
166 return _Reader.ReadUInt32();
168 return _Reader.ReadUInt64();
173 catch (EndOfStreamException e)
175 throw new ByteQueueException("No elements left.", e);