aboutsummaryrefslogtreecommitdiff
path: root/src/Spv.Generator/LiteralString.cs
blob: ed20d0e8f5e78445e58212bb067b0426d785e236 (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
using System;
using System.IO;
using System.Text;

namespace Spv.Generator
{
    public class LiteralString : IOperand, IEquatable<LiteralString>
    {
        public OperandType Type => OperandType.String;

        private readonly string _value;

        public LiteralString(string value)
        {
            _value = value;
        }

        public ushort WordCount => (ushort)(_value.Length / 4 + 1);

        public void WriteOperand(BinaryWriter writer)
        {
            writer.Write(_value.AsSpan());

            // String must be padded to the word size (which is 4 bytes).
            int paddingSize = 4 - (Encoding.ASCII.GetByteCount(_value) % 4);

            Span<byte> padding = stackalloc byte[paddingSize];

            writer.Write(padding);
        }

        public override bool Equals(object obj)
        {
            return obj is LiteralString literalString && Equals(literalString);
        }

        public bool Equals(LiteralString cmpObj)
        {
            return Type == cmpObj.Type && _value.Equals(cmpObj._value);
        }

        public override int GetHashCode()
        {
            return DeterministicHashCode.Combine(Type, DeterministicHashCode.GetHashCode(_value));
        }

        public bool Equals(IOperand obj)
        {
            return obj is LiteralString literalString && Equals(literalString);
        }

        public override string ToString() => _value;
    }
}