aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Horizon/Sdk/Ngc/Detail/BinaryReader.cs
blob: 17bfcabbea16b1ee6b97e76ca07d7d00e7004541 (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
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Ryujinx.Horizon.Sdk.Ngc.Detail
{
    ref struct BinaryReader
    {
        private readonly ReadOnlySpan<byte> _data;
        private int _offset;

        public BinaryReader(ReadOnlySpan<byte> data)
        {
            _data = data;
        }

        public bool Read<T>(out T value) where T : unmanaged
        {
            int byteLength = Unsafe.SizeOf<T>();

            if ((uint)(_offset + byteLength) <= (uint)_data.Length)
            {
                value = MemoryMarshal.Cast<byte, T>(_data[_offset..])[0];
                _offset += byteLength;

                return true;
            }

            value = default;

            return false;
        }

        public int AllocateAndReadArray<T>(ref T[] array, int length, int maxLengthExclusive) where T : unmanaged
        {
            return AllocateAndReadArray(ref array, Math.Min(length, maxLengthExclusive));
        }

        public int AllocateAndReadArray<T>(ref T[] array, int length) where T : unmanaged
        {
            array = new T[length];

            return ReadArray(array);
        }

        public int ReadArray<T>(T[] array) where T : unmanaged
        {
            if (array != null)
            {
                int byteLength = array.Length * Unsafe.SizeOf<T>();
                byteLength = Math.Min(byteLength, _data.Length - _offset);

                MemoryMarshal.Cast<byte, T>(_data.Slice(_offset, byteLength)).CopyTo(array);

                _offset += byteLength;

                return byteLength / Unsafe.SizeOf<T>();
            }

            return 0;
        }
    }
}