forked from Code-Sharp/uHttpSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLimitedStream.cs
More file actions
95 lines (67 loc) · 2.67 KB
/
Copy pathLimitedStream.cs
File metadata and controls
95 lines (67 loc) · 2.67 KB
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
using System.IO;
namespace uhttpsharp {
internal class LimitedStream : Stream {
private const string _exceptionMessageFormat = "The Stream has exceeded the {0} limit specified.";
private readonly Stream _child;
private long _readLimit;
private long _writeLimit;
public override bool CanRead => _child.CanRead;
public override bool CanSeek => _child.CanSeek;
public override bool CanWrite => _child.CanWrite;
public override long Length => _child.Length;
public override long Position {
get => _child.Position;
set => _child.Position = value;
}
public override int ReadTimeout {
get => _child.ReadTimeout;
set => _child.ReadTimeout = value;
}
public override int WriteTimeout {
get => _child.WriteTimeout;
set => _child.WriteTimeout = value;
}
public LimitedStream(Stream child, long readLimit = -1, long writeLimit = -1) {
_child = child;
_readLimit = readLimit;
_writeLimit = writeLimit;
}
public override void Flush() {
_child.Flush();
}
public override long Seek(long offset, SeekOrigin origin) {
return _child.Seek(offset, origin);
}
public override void SetLength(long value) {
_child.SetLength(value);
}
public override int Read(byte[] buffer, int offset, int count) {
var retVal = _child.Read(buffer, offset, count);
AssertReadLimit(retVal);
return retVal;
}
private void AssertReadLimit(int coefficient) {
if (_readLimit == -1) return;
_readLimit -= coefficient;
if (_readLimit < 0) throw new IOException(string.Format(_exceptionMessageFormat, "read"));
}
private void AssertWriteLimit(int coefficient) {
if (_writeLimit == -1) return;
_writeLimit -= coefficient;
if (_writeLimit < 0) throw new IOException(string.Format(_exceptionMessageFormat, "write"));
}
public override int ReadByte() {
var retVal = _child.ReadByte();
AssertReadLimit(1);
return retVal;
}
public override void Write(byte[] buffer, int offset, int count) {
_child.Write(buffer, offset, count);
AssertWriteLimit(count);
}
public override void WriteByte(byte value) {
_child.WriteByte(value);
AssertWriteLimit(1);
}
}
}