SpanWriter.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using System.Runtime.InteropServices;
  4. namespace Ryujinx.Common.Memory
  5. {
  6. public ref struct SpanWriter
  7. {
  8. private Span<byte> _output;
  9. public int Length => _output.Length;
  10. public SpanWriter(Span<byte> output)
  11. {
  12. _output = output;
  13. }
  14. public void Write<T>(T value) where T : unmanaged
  15. {
  16. MemoryMarshal.Cast<byte, T>(_output)[0] = value;
  17. _output = _output.Slice(Unsafe.SizeOf<T>());
  18. }
  19. public void Write(ReadOnlySpan<byte> data)
  20. {
  21. data.CopyTo(_output.Slice(0, data.Length));
  22. _output = _output.Slice(data.Length);
  23. }
  24. public void WriteAt<T>(int offset, T value) where T : unmanaged
  25. {
  26. MemoryMarshal.Cast<byte, T>(_output.Slice(offset))[0] = value;
  27. }
  28. public void WriteAt(int offset, ReadOnlySpan<byte> data)
  29. {
  30. data.CopyTo(_output.Slice(offset, data.Length));
  31. }
  32. public void Skip(int size)
  33. {
  34. _output = _output.Slice(size);
  35. }
  36. }
  37. }