StreamUtils.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace SharpGLTF.Schema2.LoadAndSave
  8. {
  9. /// <summary>
  10. /// Utility stream used to simulate streams that don't support <see cref="CanSeek"/> nor <see cref="Length"/>
  11. /// </summary>
  12. internal class ReadOnlyTestStream : System.IO.Stream
  13. {
  14. public ReadOnlyTestStream(Byte[] data)
  15. {
  16. _Data = data;
  17. }
  18. private readonly Byte[] _Data;
  19. private int _Position;
  20. public override bool CanRead => true;
  21. public override bool CanSeek => false;
  22. public override bool CanWrite => false;
  23. public override long Length => throw new NotSupportedException();
  24. public override long Position
  25. {
  26. get => _Position;
  27. set => throw new NotSupportedException();
  28. }
  29. public override void Flush() { }
  30. public override int Read(byte[] buffer, int offset, int count)
  31. {
  32. if (_Position >= _Data.Length) return 0;
  33. if (count > 1) count /= 2; // simulate partial reads
  34. var bytesLeft = _Data.Length - _Position;
  35. count = Math.Min(count, bytesLeft);
  36. var dst = buffer.AsSpan().Slice(offset, count);
  37. var src = _Data.AsSpan().Slice(_Position, count);
  38. src.CopyTo(dst);
  39. _Position += count;
  40. return count;
  41. }
  42. public override long Seek(long offset, SeekOrigin origin)
  43. {
  44. throw new NotSupportedException();
  45. }
  46. public override void SetLength(long value)
  47. {
  48. throw new NotSupportedException();
  49. }
  50. public override void Write(byte[] buffer, int offset, int count)
  51. {
  52. throw new NotSupportedException();
  53. }
  54. }
  55. }