forked from managedcode/Storage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringStream.cs
More file actions
70 lines (56 loc) · 1.68 KB
/
StringStream.cs
File metadata and controls
70 lines (56 loc) · 1.68 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
using System;
using System.IO;
namespace ManagedCode.Storage.Core;
public class StringStream : Stream
{
private readonly string _string;
public StringStream(string s)
{
_string = s ?? throw new ArgumentNullException(nameof(s));
}
public override bool CanRead => true;
public override bool CanSeek => true;
public override bool CanWrite => false;
public override long Length => _string.Length * 2;
public override long Position { get; set; }
private byte this[int i] => (i & 1) == 0 ? (byte)(_string[i / 2] & 0xFF) : (byte)(_string[i / 2] >> 8);
public override long Seek(long offset, SeekOrigin origin)
{
Position = origin switch
{
SeekOrigin.Begin => offset,
SeekOrigin.Current => Position + offset,
SeekOrigin.End => Length - offset,
_ => throw new ArgumentOutOfRangeException(nameof(origin), origin, null)
};
return Position;
}
public override int Read(byte[] buffer, int offset, int count)
{
var length = Math.Min(count, Length - Position);
for (var i = 0; i < length; i++)
{
buffer[offset++] = this[(int)Position++];
}
return (int)length;
}
public override int ReadByte()
{
return Position >= Length ? -1 : this[(int)Position++];
}
public override void Flush()
{
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override string ToString()
{
return _string;
}
}