Skip to content
0.2.0-dev Download ZIP
104 lines ·2.2 KB Raw
1namespace EvilEngine.Conversion;
2
3public sealed class ConversionOutput : MemoryStream
4{
5 private byte[]? _adopted;
6
7 public override long Length => _adopted?.Length ?? base.Length;
8
9 public override long Position
10 {
11 get => _adopted?.Length ?? base.Position;
12 set
13 {
14 Spill();
15 base.Position = value;
16 }
17 }
18
19 public ReadOnlyMemory<byte> Data
20 {
21 get
22 {
23 if (_adopted is { } adopted)
24 return adopted;
25 return TryGetBuffer(out var buffer) && buffer.Offset == 0 && buffer.Count == buffer.Array!.Length
26 ? buffer.Array
27 : ToArray();
28 }
29 }
30
31 public void Adopt(byte[] bytes)
32 {
33 if (_adopted is null && base.Length == 0)
34 _adopted = bytes;
35 else
36 Write(bytes);
37 }
38
39 public override void Write(byte[] buffer, int offset, int count)
40 {
41 Spill();
42 base.Write(buffer, offset, count);
43 }
44
45 public override void Write(ReadOnlySpan<byte> buffer)
46 {
47 Spill();
48 base.Write(buffer);
49 }
50
51 public override void WriteByte(byte value)
52 {
53 Spill();
54 base.WriteByte(value);
55 }
56
57 public override long Seek(long offset, SeekOrigin loc)
58 {
59 Spill();
60 return base.Seek(offset, loc);
61 }
62
63 public override void SetLength(long value)
64 {
65 Spill();
66 base.SetLength(value);
67 }
68
69 public override int Read(byte[] buffer, int offset, int count)
70 {
71 Spill();
72 return base.Read(buffer, offset, count);
73 }
74
75 public override int Read(Span<byte> buffer)
76 {
77 Spill();
78 return base.Read(buffer);
79 }
80
81 public override byte[] ToArray()
82 {
83 return _adopted is { } adopted ? adopted.ToArray() : base.ToArray();
84 }
85
86 private void Spill()
87 {
88 if (_adopted is not { } adopted)
89 return;
90 _adopted = null;
91 base.Write(adopted);
92 }
93}
94
95public static class ConversionOutputs
96{
97 public static void Adopt(this Stream output, byte[] bytes)
98 {
99 if (output is ConversionOutput adopting)
100 adopting.Adopt(bytes);
101 else
102 output.Write(bytes);
103 }
104}