| | 1 | | using System; |
| | 2 | |
|
| | 3 | | namespace KernelCommunication |
| | 4 | | { |
| | 5 | | public class ByteArrayReader : IBinaryReader |
| | 6 | | { |
| | 7 | | private readonly byte[] bytes; |
| | 8 | | private int currentOffset; |
| | 9 | |
|
| 15 | 10 | | public ByteArrayReader(byte[] bytes) |
| | 11 | | { |
| 15 | 12 | | this.bytes = bytes; |
| 15 | 13 | | currentOffset = 0; |
| 15 | 14 | | } |
| | 15 | |
|
| 0 | 16 | | int IBinaryReader.offset => currentOffset; |
| | 17 | |
|
| 24 | 18 | | bool IBinaryReader.CanRead() => currentOffset < bytes.Length; |
| | 19 | |
|
| | 20 | | unsafe int IBinaryReader.ReadInt32() |
| | 21 | | { |
| 79 | 22 | | int ofs = currentOffset; |
| 79 | 23 | | currentOffset += 4; |
| | 24 | |
|
| 79 | 25 | | if (bytes == null) |
| 0 | 26 | | throw new NullReferenceException("bytes array == null"); |
| 79 | 27 | | if ((long)(uint)ofs >= (long)bytes.Length) |
| 0 | 28 | | throw new IndexOutOfRangeException("offset is bigger than bytes array lenght"); |
| 79 | 29 | | if (ofs > bytes.Length - 4) |
| 0 | 30 | | throw new IndexOutOfRangeException("bytes.Length is not large enough to contain a valid Int32"); |
| | 31 | |
|
| 79 | 32 | | fixed (byte* numPtr = &bytes[ofs]) |
| | 33 | | { |
| 79 | 34 | | return ByteUtils.PointerToInt32(numPtr); |
| | 35 | | } |
| | 36 | | } |
| | 37 | |
|
| | 38 | | unsafe long IBinaryReader.ReadInt64() |
| | 39 | | { |
| 15 | 40 | | int ofs = currentOffset; |
| 15 | 41 | | currentOffset += 8; |
| | 42 | |
|
| 15 | 43 | | if (bytes == null) |
| 0 | 44 | | throw new NullReferenceException("bytes array == null"); |
| 15 | 45 | | if ((long)(uint)ofs >= (long)bytes.Length) |
| 0 | 46 | | throw new IndexOutOfRangeException("offset is bigger than bytes array lenght"); |
| 15 | 47 | | if (ofs > bytes.Length - 8) |
| 0 | 48 | | throw new IndexOutOfRangeException("bytes.Length is not large enough to contain a valid Int64"); |
| | 49 | |
|
| 15 | 50 | | fixed (byte* numPtr = &bytes[ofs]) |
| | 51 | | { |
| 15 | 52 | | return ByteUtils.PointerToInt64(numPtr); |
| | 53 | | } |
| | 54 | | } |
| | 55 | |
|
| | 56 | | byte[] IBinaryReader.ReadBytes(int length) |
| | 57 | | { |
| 11 | 58 | | int ofs = currentOffset; |
| 11 | 59 | | currentOffset += length; |
| 11 | 60 | | byte[] data = new byte[length]; |
| 11 | 61 | | Buffer.BlockCopy(bytes, ofs, data, 0, length); |
| 11 | 62 | | return data; |
| | 63 | | } |
| | 64 | |
|
| | 65 | | void IBinaryReader.Skip(int bytesCount) |
| | 66 | | { |
| 4 | 67 | | currentOffset += bytesCount; |
| 4 | 68 | | } |
| | 69 | | } |
| | 70 | | } |