aboutsummaryrefslogtreecommitdiff
path: root/Ryujinx.Graphics/Vic/StructUnpacker.cs
blob: 6b6b9795c73366ae874c76e0e7d2d3f1626508d5 (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
using Ryujinx.Graphics.Memory;
using System;

namespace Ryujinx.Graphics.Vic
{
    class StructUnpacker
    {
        private NvGpuVmm _vmm;

        private long _position;

        private ulong _buffer;
        private int   _buffPos;

        public StructUnpacker(NvGpuVmm vmm, long position)
        {
            _vmm      = vmm;
            _position = position;

            _buffPos = 64;
        }

        public int Read(int bits)
        {
            if ((uint)bits > 32)
            {
                throw new ArgumentOutOfRangeException(nameof(bits));
            }

            int value = 0;

            while (bits > 0)
            {
                RefillBufferIfNeeded();

                int readBits = bits;

                int maxReadBits = 64 - _buffPos;

                if (readBits > maxReadBits)
                {
                    readBits = maxReadBits;
                }

                value <<= readBits;

                value |= (int)(_buffer >> _buffPos) & (int)(0xffffffff >> (32 - readBits));

                _buffPos += readBits;

                bits -= readBits;
            }

            return value;
        }

        private void RefillBufferIfNeeded()
        {
            if (_buffPos >= 64)
            {
                _buffer = _vmm.ReadUInt64(_position);

                _position += 8;

                _buffPos = 0;
            }
        }
    }
}