-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathTupleEnumerator.cs
More file actions
93 lines (78 loc) · 2.84 KB
/
TupleEnumerator.cs
File metadata and controls
93 lines (78 loc) · 2.84 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
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Npgsql.BackendMessages;
using Npgsql.Internal;
namespace Npgsql.Replication.PgOutput;
sealed class TupleEnumerator : IAsyncEnumerator<ReplicationValue>
{
readonly ReplicationTuple _tupleEnumerable;
readonly NpgsqlReadBuffer _readBuffer;
readonly ReplicationValue _value;
ushort _numColumns;
int _pos;
RowDescriptionMessage _rowDescription = null!;
CancellationToken _cancellationToken;
internal TupleEnumerator(ReplicationTuple tupleEnumerable, NpgsqlConnector connector)
{
_tupleEnumerable = tupleEnumerable;
_readBuffer = connector.ReadBuffer;
_value = new(connector);
}
internal void Reset(ushort numColumns, RowDescriptionMessage rowDescription, CancellationToken cancellationToken)
{
_pos = -1;
_numColumns = numColumns;
_rowDescription = rowDescription;
_cancellationToken = cancellationToken;
}
public ValueTask<bool> MoveNextAsync()
{
if (_tupleEnumerable.State != RowState.Reading)
throw new ObjectDisposedException(null);
return MoveNextCore();
async ValueTask<bool> MoveNextCore()
{
// Consume the previous column
if (_pos != -1)
await _value.Consume(_cancellationToken).ConfigureAwait(false);
if (_pos + 1 == _numColumns)
return false;
_pos++;
// Read the next column
await _readBuffer.Ensure(1, async: true).ConfigureAwait(false);
var kind = (TupleDataKind)_readBuffer.ReadByte();
int len;
switch (kind)
{
case TupleDataKind.Null:
case TupleDataKind.UnchangedToastedValue:
len = 0;
break;
case TupleDataKind.TextValue:
case TupleDataKind.BinaryValue:
await _readBuffer.Ensure(4, async: true).ConfigureAwait(false);
len = _readBuffer.ReadInt32();
break;
default:
throw new ArgumentOutOfRangeException();
}
_value.Reset(kind, len, _rowDescription[_pos]);
return true;
}
}
public ReplicationValue Current => _tupleEnumerable.State switch
{
RowState.NotRead => throw new ObjectDisposedException(null),
RowState.Reading => _value,
RowState.Consumed => throw new ObjectDisposedException(null),
_ => throw new ArgumentOutOfRangeException()
};
public async ValueTask DisposeAsync()
{
if (_tupleEnumerable.State == RowState.Reading)
while (await MoveNextAsync().ConfigureAwait(false)) { /* Do nothing, just iterate the enumerator */ }
_tupleEnumerable.State = RowState.Consumed;
}
}