-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathOutputStream.cs
123 lines (110 loc) · 3.15 KB
/
OutputStream.cs
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using SpinHttpWorld.wit.imports.wasi.io.v0_2_1;
namespace Spin.Http;
public class OutputStream : Stream
{
IStreams.OutputStream stream;
public OutputStream(IStreams.OutputStream stream)
{
this.stream = stream;
}
public override bool CanRead => false;
public override bool CanWrite => true;
public override bool CanSeek => false;
public override long Length => throw new NotImplementedException();
public override long Position
{
get => throw new NotImplementedException();
set => throw new NotImplementedException();
}
public new void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing)
{
stream.Dispose();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void Flush()
{
// ignore
}
public override void SetLength(long length)
{
throw new NotImplementedException();
}
public override int Read(byte[] buffer, int offset, int length)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int length)
{
throw new NotImplementedException();
}
public override async Task WriteAsync(
byte[] bytes,
int offset,
int length,
CancellationToken cancellationToken
)
{
var limit = offset + length;
var flushing = false;
while (true)
{
var count = (int)stream.CheckWrite();
if (count == 0)
{
await WasiEventLoop.Register(stream.Subscribe(), cancellationToken);
}
else if (offset == limit)
{
if (flushing)
{
return;
}
else
{
stream.Flush();
flushing = true;
}
}
else
{
var min = Math.Min(count, limit - offset);
if (offset == 0 && min == bytes.Length)
{
stream.Write(bytes);
}
else
{
// TODO: is there a more efficient option than copying here?
// Do we need to change the binding generator to accept
// e.g. `Span`s?
var copy = new byte[min];
Array.Copy(bytes, offset, copy, 0, min);
stream.Write(copy);
}
offset += min;
}
}
}
public override ValueTask WriteAsync(
ReadOnlyMemory<byte> buffer,
CancellationToken cancellationToken = default
)
{
// TODO: avoid copy when possible and use ArrayPool when not
var copy = new byte[buffer.Length];
buffer.Span.CopyTo(copy);
return new ValueTask(WriteAsync(copy, 0, buffer.Length, cancellationToken));
}
}