Repository navigation
Expand file tree
/
Copy pathRisMemoryStream.cs
More file actions
109 lines (95 loc) · 2.48 KB
/
Copy pathRisMemoryStream.cs
File metadata and controls
109 lines (95 loc) · 2.48 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
namespace RisSerialization;
public class RisMemoryStream
{
private byte[] _data;
private int _position;
public RisMemoryStream()
{
_data = Array.Empty<byte>();
_position = 0;
}
public RisMemoryStream(byte[] value)
{
_data = value;
_position = 0;
}
public byte[] ToArray()
{
return _data.ToArray();
}
public int Seek(int offset, SeekFrom seekFrom)
{
switch (seekFrom)
{
case SeekFrom.Begin:
_position = offset;
break;
case SeekFrom.Current:
_position += offset;
break;
case SeekFrom.End:
_position = _data.Length + offset;
break;
default:
throw new ArgumentOutOfRangeException(nameof(seekFrom), seekFrom, null);
}
// clamp the position, in case it falls out of range
if (_position < 0)
{
_position = 0;
}
if (_position > _data.Length)
{
_position = _data.Length;
}
return _position;
}
public byte[] Read(int count)
{
// clamp count, such that only the remaining bytes are read
var bytesLeftToRead = _data.Length - _position;
if (count > bytesLeftToRead)
{
count = bytesLeftToRead;
}
// read the bytes, by copying them to a new array
var bytes = new byte[count];
Array.Copy(
_data,
_position,
bytes,
0,
count
);
// advance the cursor
_position += count;
return bytes;
}
public void Write(byte[] value)
{
// ensure the capacity is big enough
var requiredCapacity = _position + value.Length;
if (_data.Length < requiredCapacity)
{
// capacity is not big enough
// create an array that is big enough and copy the old into the new one
var newDataArray = new byte[requiredCapacity];
Array.Copy(
_data,
newDataArray,
_data.Length
);
_data = newDataArray;
}
// write by copying the values into the array
Array.Copy(
value,
0,
_data,
_position,
value.Length
);
// advance the cursor
_position += value.Length;
}
}