InstructionOperands.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. namespace Spv.Generator
  6. {
  7. public struct InstructionOperands
  8. {
  9. private const int InternalCount = 5;
  10. public int Count;
  11. public Operand Operand1;
  12. public Operand Operand2;
  13. public Operand Operand3;
  14. public Operand Operand4;
  15. public Operand Operand5;
  16. public Operand[] Overflow;
  17. public Span<Operand> AsSpan()
  18. {
  19. if (Count > InternalCount)
  20. {
  21. return MemoryMarshal.CreateSpan(ref this.Overflow[0], Count);
  22. }
  23. else
  24. {
  25. return MemoryMarshal.CreateSpan(ref this.Operand1, Count);
  26. }
  27. }
  28. public void Add(Operand operand)
  29. {
  30. if (Count < InternalCount)
  31. {
  32. MemoryMarshal.CreateSpan(ref this.Operand1, Count + 1)[Count] = operand;
  33. Count++;
  34. }
  35. else
  36. {
  37. if (Overflow == null)
  38. {
  39. Overflow = new Operand[InternalCount * 2];
  40. MemoryMarshal.CreateSpan(ref this.Operand1, InternalCount).CopyTo(Overflow.AsSpan());
  41. }
  42. else if (Count == Overflow.Length)
  43. {
  44. Array.Resize(ref Overflow, Overflow.Length * 2);
  45. }
  46. Overflow[Count++] = operand;
  47. }
  48. }
  49. private IEnumerable<Operand> AllOperands => new[] { Operand1, Operand2, Operand3, Operand4, Operand5 }
  50. .Concat(Overflow ?? Array.Empty<Operand>())
  51. .Take(Count);
  52. public override string ToString()
  53. {
  54. return $"({string.Join(", ", AllOperands)})";
  55. }
  56. public string ToString(string[] labels)
  57. {
  58. var labeledParams = AllOperands.Zip(labels, (op, label) => $"{label}: {op}");
  59. var unlabeledParams = AllOperands.Skip(labels.Length).Select(op => op.ToString());
  60. var paramsToPrint = labeledParams.Concat(unlabeledParams);
  61. return $"({string.Join(", ", paramsToPrint)})";
  62. }
  63. }
  64. }