-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathPreparedTextReader.cs
More file actions
111 lines (86 loc) · 2.74 KB
/
PreparedTextReader.cs
File metadata and controls
111 lines (86 loc) · 2.74 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
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Npgsql.Internal;
namespace Npgsql;
sealed class PreparedTextReader : TextReader
{
string _str = null!;
NpgsqlReadBuffer.ColumnStream _stream = null!;
int _position;
bool _disposed;
public void Init(string str, NpgsqlReadBuffer.ColumnStream stream)
{
_str = str;
_stream = stream;
_disposed = false;
_position = 0;
}
public bool IsDisposed => _disposed;
public override int Peek()
{
CheckDisposed();
return _position < _str.Length
? _str[_position]
: -1;
}
public override int Read()
{
CheckDisposed();
return _position < _str.Length
? _str[_position++]
: -1;
}
public override int Read(Span<char> buffer)
{
CheckDisposed();
var toRead = Math.Min(buffer.Length, _str.Length - _position);
if (toRead == 0)
return 0;
_str.AsSpan(_position, toRead).CopyTo(buffer);
_position += toRead;
return toRead;
}
public override int Read(char[] buffer, int index, int count)
{
ArgumentNullException.ThrowIfNull(buffer);
ArgumentOutOfRangeException.ThrowIfNegative(index);
ArgumentOutOfRangeException.ThrowIfNegative(count);
if (buffer.Length - index < count)
{
ThrowHelper.ThrowArgumentException("Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.");
}
return Read(buffer.AsSpan(index, count));
}
public override Task<int> ReadAsync(char[] buffer, int index, int count)
=> Task.FromResult(Read(buffer, index, count));
public override ValueTask<int> ReadAsync(Memory<char> buffer, CancellationToken cancellationToken = default) => new(Read(buffer.Span));
public override Task<string?> ReadLineAsync() => Task.FromResult<string?>(ReadLine());
public override string ReadToEnd()
{
CheckDisposed();
if (_position == _str.Length)
return string.Empty;
var str = _str.Substring(_position);
_position = _str.Length;
return str;
}
public override Task<string> ReadToEndAsync() => Task.FromResult(ReadToEnd());
void CheckDisposed()
=> ObjectDisposedException.ThrowIf(_disposed || _stream.IsDisposed, this);
public void Restart()
{
CheckDisposed();
_position = 0;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
_disposed = true;
_stream.Dispose();
}
}
}