aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Common/Utilities/SpanHelpers.cs
blob: 4765eab3a2355c87759a474e118f39c41946c2bf (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
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Ryujinx.Common.Utilities
{
    public static class SpanHelpers
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Span<T> CreateSpan<T>(scoped ref T reference, int length)
        {
            return MemoryMarshal.CreateSpan(ref reference, length);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Span<T> AsSpan<T>(scoped ref T reference) where T : unmanaged
        {
            return CreateSpan(ref reference, 1);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Span<TSpan> AsSpan<TStruct, TSpan>(scoped ref TStruct reference)
            where TStruct : unmanaged where TSpan : unmanaged
        {
            return CreateSpan(ref Unsafe.As<TStruct, TSpan>(ref reference),
                Unsafe.SizeOf<TStruct>() / Unsafe.SizeOf<TSpan>());
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Span<byte> AsByteSpan<T>(scoped ref T reference) where T : unmanaged
        {
            return CreateSpan(ref Unsafe.As<T, byte>(ref reference), Unsafe.SizeOf<T>());
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static ReadOnlySpan<T> CreateReadOnlySpan<T>(scoped ref T reference, int length)
        {
            return MemoryMarshal.CreateReadOnlySpan(ref reference, length);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static ReadOnlySpan<T> AsReadOnlySpan<T>(scoped ref T reference) where T : unmanaged
        {
            return CreateReadOnlySpan(ref reference, 1);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static ReadOnlySpan<TSpan> AsReadOnlySpan<TStruct, TSpan>(scoped ref TStruct reference)
            where TStruct : unmanaged where TSpan : unmanaged
        {
            return CreateReadOnlySpan(ref Unsafe.As<TStruct, TSpan>(ref reference),
                Unsafe.SizeOf<TStruct>() / Unsafe.SizeOf<TSpan>());
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static ReadOnlySpan<byte> AsReadOnlyByteSpan<T>(scoped ref T reference) where T : unmanaged
        {
            return CreateReadOnlySpan(ref Unsafe.As<T, byte>(ref reference), Unsafe.SizeOf<T>());
        }
    }
}