forked from bonesoul/uhttpsharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLimitedStream.cs
More file actions
122 lines (106 loc) · 3.05 KB
/
LimitedStream.cs
File metadata and controls
122 lines (106 loc) · 3.05 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
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
using System.IO;
namespace uhttpsharp
{
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 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);
}
public override bool CanRead
{
get { return _child.CanRead; }
}
public override bool CanSeek
{
get { return _child.CanSeek; }
}
public override bool CanWrite
{
get { return _child.CanWrite; }
}
public override long Length
{
get { return _child.Length; }
}
public override long Position
{
get { return _child.Position; }
set { _child.Position = value; }
}
public override int ReadTimeout
{
get { return _child.ReadTimeout; }
set { _child.ReadTimeout = value; }
}
public override int WriteTimeout
{
get { return _child.WriteTimeout; }
set { _child.WriteTimeout = value; }
}
}
}