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