aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Horizon/Sdk/Sm/ServiceName.cs
blob: b44106d63b8ce9293eee4ca38b76b8365c24952b (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Ryujinx.Horizon.Sdk.Sm
{
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public readonly struct ServiceName
    {
        public static ServiceName Invalid { get; } = new(0);

        public bool IsValid => Packed != 0;

        public const int Length = sizeof(ulong);

        public ulong Packed { get; }

        public byte this[int index]
        {
            get
            {
                if ((uint)index >= sizeof(ulong))
                {
                    throw new IndexOutOfRangeException();
                }

                return (byte)(Packed >> (index * 8));
            }
        }

        private ServiceName(ulong packed)
        {
            Packed = packed;
        }

        public static ServiceName Encode(string name)
        {
            ulong packed = 0;

            for (int index = 0; index < sizeof(ulong); index++)
            {
                if (index < name.Length)
                {
                    packed |= (ulong)(byte)name[index] << (index * 8);
                }
                else
                {
                    break;
                }
            }

            return new ServiceName(packed);
        }

        public override bool Equals(object obj)
        {
            return obj is ServiceName serviceName && serviceName.Equals(this);
        }

        public bool Equals(ServiceName other)
        {
            return other.Packed == Packed;
        }

        public override int GetHashCode()
        {
            return Packed.GetHashCode();
        }

        public static bool operator ==(ServiceName lhs, ServiceName rhs)
        {
            return lhs.Equals(rhs);
        }

        public static bool operator !=(ServiceName lhs, ServiceName rhs)
        {
            return !lhs.Equals(rhs);
        }

        public override string ToString()
        {
            StringBuilder nameBuilder = new();

            for (int index = 0; index < sizeof(ulong); index++)
            {
                byte character = (byte)(Packed >> (index * 8));

                if (character == 0)
                {
                    break;
                }

                nameBuilder.Append((char)character);
            }

            return nameBuilder.ToString();
        }
    }
}