-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathPgReader.cs
More file actions
832 lines (679 loc) · 28.1 KB
/
PgReader.cs
File metadata and controls
832 lines (679 loc) · 28.1 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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
using System;
using System.Buffers;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Npgsql.Internal;
[Experimental(NpgsqlDiagnostics.ConvertersExperimental)]
public class PgReader
{
const int DbNullSentinel = -1;
const int UninitializedSentinel = -1;
// We don't want to add a ton of memory pressure for large strings.
internal const int MaxPreparedTextReaderSize = 1024 * 64;
readonly NpgsqlReadBuffer _buffer;
bool _resumable;
byte[]? _pooledArray;
NpgsqlReadBuffer.ColumnStream? _userActiveStream;
PreparedTextReader? _preparedTextReader;
long _fieldStartPos;
Size _fieldBufferRequirement;
DataFormat _fieldFormat;
int _fieldSize;
// This position is relative to _fieldStartPos, which is why it can be an int.
int _currentStartPos;
Size _currentBufferRequirement;
int _currentSize;
// GetChars Internal state
TextReader? _charsReadReader;
int _charsRead;
// GetChars User state
int? _charsReadOffset;
ArraySegment<char>? _charsReadBuffer;
bool _requiresCleanup;
// The field reading process of doing init/commit and startread/endread pairs is very perf sensitive.
// So this is used in Commit as a fast-path alternative to FieldRemaining to detect if the field was consumed succesfully.
bool _fieldConsumed;
internal PgReader(NpgsqlReadBuffer buffer)
{
_buffer = buffer;
_fieldStartPos = UninitializedSentinel;
_currentSize = UninitializedSentinel;
}
internal bool Initialized => _fieldStartPos is not UninitializedSentinel;
int FieldOffset => (int)(_buffer.CumulativeReadPosition - _fieldStartPos);
int FieldSize => _fieldSize;
int FieldRemaining => FieldSize - FieldOffset;
internal bool FieldIsDbNull => FieldSize is DbNullSentinel;
internal bool FieldAtStart => FieldOffset is 0;
internal bool IsFieldPastOffset(int offset) => FieldOffset > offset;
// TODO refactor out
internal long GetFieldStartPos(NpgsqlNestedDataReader nestedDataReader) => _fieldStartPos;
// TODO refactor out
internal int GetFieldOffset(NpgsqlNestedDataReader nestedDataReader) => FieldOffset;
internal bool NestedInitialized => _currentSize is not UninitializedSentinel;
int CurrentSize => NestedInitialized ? _currentSize : _fieldSize;
public ValueMetadata Current => new() { Size = CurrentSize, Format = _fieldFormat, BufferRequirement = CurrentBufferRequirement };
public int CurrentRemaining => NestedInitialized ? _currentSize - CurrentOffset : FieldRemaining;
internal Size CurrentBufferRequirement => NestedInitialized ? _currentBufferRequirement : _fieldBufferRequirement;
int CurrentOffset => FieldOffset - _currentStartPos;
internal bool Resumable => _resumable;
public bool IsResumed => Resumable && CurrentOffset > 0;
ArrayPool<byte> ArrayPool => ArrayPool<byte>.Shared;
// Here for testing purposes
internal void BreakConnection() => throw _buffer.Connector.Break(new Exception("Broken"));
internal void Revert(int size, int startPos, Size bufferRequirement)
{
if (startPos > FieldOffset)
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(startPos), "Can't revert forwardly");
_currentStartPos = startPos;
_currentBufferRequirement = bufferRequirement;
_currentSize = size;
}
void CheckBounds(int count)
{
if (NpgsqlReadBuffer.BufferBoundsChecks)
Core(count);
[MethodImpl(MethodImplOptions.NoInlining)]
void Core(int count)
{
if (count > CurrentRemaining)
ThrowHelper.ThrowIndexOutOfRangeException("Attempt to read past the end of the current field size.");
}
}
public byte ReadByte()
{
CheckBounds(sizeof(byte));
var result = _buffer.ReadByte();
return result;
}
public short ReadInt16()
{
CheckBounds(sizeof(short));
var result = _buffer.ReadInt16();
return result;
}
public int ReadInt32()
{
CheckBounds(sizeof(int));
var result = _buffer.ReadInt32();
return result;
}
public long ReadInt64()
{
CheckBounds(sizeof(long));
var result = _buffer.ReadInt64();
return result;
}
public ushort ReadUInt16()
{
CheckBounds(sizeof(ushort));
var result = _buffer.ReadUInt16();
return result;
}
public uint ReadUInt32()
{
CheckBounds(sizeof(uint));
var result = _buffer.ReadUInt32();
return result;
}
public ulong ReadUInt64()
{
CheckBounds(sizeof(ulong));
var result = _buffer.ReadUInt64();
return result;
}
public float ReadFloat()
{
CheckBounds(sizeof(float));
var result = _buffer.ReadSingle();
return result;
}
public double ReadDouble()
{
CheckBounds(sizeof(double));
var result = _buffer.ReadDouble();
return result;
}
public void Read(Span<byte> destination)
{
CheckBounds(destination.Length);
_buffer.ReadBytes(destination);
}
public async ValueTask<string> ReadNullTerminatedStringAsync(Encoding encoding, CancellationToken cancellationToken = default)
{
var result = await _buffer.ReadNullTerminatedString(encoding, async: true, cancellationToken).ConfigureAwait(false);
// Can only check after the fact.
CheckBounds(0);
return result;
}
public string ReadNullTerminatedString(Encoding encoding)
{
var result = _buffer.ReadNullTerminatedString(encoding, async: false, CancellationToken.None).GetAwaiter().GetResult();
CheckBounds(0);
return result;
}
public Stream GetStream(int? length = null) => GetColumnStream(false, length);
internal Stream GetStream(bool canSeek, int? length = null) => GetColumnStream(canSeek, length);
NpgsqlReadBuffer.ColumnStream GetColumnStream(bool canSeek = false, int? length = null)
{
if (length > CurrentRemaining)
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(length), "Length is larger than the current remaining value size");
_requiresCleanup = true;
// This will cause any previously handed out StreamReaders etc to throw, as intended.
if (_userActiveStream is not null)
DisposeUserActiveStream(async: false).GetAwaiter().GetResult();
length ??= CurrentRemaining;
CheckBounds(length.GetValueOrDefault());
return _userActiveStream = _buffer.CreateStream(length.GetValueOrDefault(), canSeek && length <= _buffer.ReadBytesLeft, consumeOnDispose: false);
}
public TextReader GetTextReader(Encoding encoding)
=> GetTextReader(async: false, encoding, CancellationToken.None).GetAwaiter().GetResult();
public ValueTask<TextReader> GetTextReaderAsync(Encoding encoding, CancellationToken cancellationToken)
=> GetTextReader(async: true, encoding, cancellationToken);
async ValueTask<TextReader> GetTextReader(bool async, Encoding encoding, CancellationToken cancellationToken)
{
_requiresCleanup = true;
if (CurrentRemaining > _buffer.ReadBytesLeft || CurrentRemaining > MaxPreparedTextReaderSize)
return new StreamReader(GetColumnStream(), encoding, detectEncodingFromByteOrderMarks: false);
if (_preparedTextReader is { IsDisposed: false })
{
_preparedTextReader.Dispose();
_preparedTextReader = null;
}
_preparedTextReader ??= new PreparedTextReader();
_preparedTextReader.Init(
encoding.GetString(async
? await ReadBytesAsync(CurrentRemaining, cancellationToken).ConfigureAwait(false)
: ReadBytes(CurrentRemaining)), GetColumnStream(canSeek: false, 0));
return _preparedTextReader;
}
public ValueTask ReadBytesAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
var count = buffer.Length;
CheckBounds(count);
var offset = _buffer.ReadPosition;
var remaining = _buffer.FilledBytes - offset;
if (remaining >= count)
{
_buffer.Buffer.AsSpan(offset, count).CopyTo(buffer.Span);
_buffer.ReadPosition += count;
return new();
}
return Slow(count, buffer, cancellationToken);
async ValueTask Slow(int count, Memory<byte> buffer, CancellationToken cancellationToken)
{
var stream = _buffer.CreateStream(count, canSeek: false);
await using var _ = stream.ConfigureAwait(false);
await stream.ReadExactlyAsync(buffer, cancellationToken).ConfigureAwait(false);
}
}
public void ReadBytes(Span<byte> buffer)
{
var count = buffer.Length;
CheckBounds(count);
var offset = _buffer.ReadPosition;
var remaining = _buffer.FilledBytes - offset;
if (remaining >= count)
{
_buffer.Buffer.AsSpan(offset, count).CopyTo(buffer);
_buffer.ReadPosition += count;
return;
}
Slow(count, buffer);
void Slow(int count, Span<byte> buffer)
{
using var stream = _buffer.CreateStream(count, canSeek: false);
stream.ReadExactly(buffer);
}
}
public bool TryReadBytes(int count, out ReadOnlySpan<byte> bytes)
{
CheckBounds(count);
var offset = _buffer.ReadPosition;
var remaining = _buffer.FilledBytes - offset;
if (remaining >= count)
{
bytes = new ReadOnlySpan<byte>(_buffer.Buffer, offset, count);
_buffer.ReadPosition += count;
return true;
}
bytes = default;
return false;
}
public bool TryReadBytes(int count, out ReadOnlyMemory<byte> bytes)
{
CheckBounds(count);
var offset = _buffer.ReadPosition;
var remaining = _buffer.FilledBytes - offset;
if (remaining >= count)
{
bytes = new ReadOnlyMemory<byte>(_buffer.Buffer, offset, count);
_buffer.ReadPosition += count;
return true;
}
bytes = default;
return false;
}
/// ReadBytes without memory management, the next read invalidates the underlying buffer(s), only use this for intermediate transformations.
public ReadOnlySequence<byte> ReadBytes(int count)
{
CheckBounds(count);
var offset = _buffer.ReadPosition;
var remaining = _buffer.FilledBytes - offset;
if (remaining >= count)
{
var result = new ReadOnlySequence<byte>(_buffer.Buffer, offset, count);
_buffer.ReadPosition += count;
return result;
}
var array = RentArray(count);
ReadBytes(array.AsSpan(0, count));
return new(array, 0, count);
}
/// ReadBytesAsync without memory management, the next read invalidates the underlying buffer(s), only use this for intermediate transformations.
public async ValueTask<ReadOnlySequence<byte>> ReadBytesAsync(int count, CancellationToken cancellationToken = default)
{
CheckBounds(count);
var offset = _buffer.ReadPosition;
var remaining = _buffer.FilledBytes - offset;
if (remaining >= count)
{
var result = new ReadOnlySequence<byte>(_buffer.Buffer, offset, count);
_buffer.ReadPosition += count;
return result;
}
var array = RentArray(count);
await ReadBytesAsync(array.AsMemory(0, count), cancellationToken).ConfigureAwait(false);
return new(array, 0, count);
}
public void Rewind(int count)
{
if (CurrentOffset < count)
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(count), "Attempt to rewind past the current field start.");
if (_buffer.ReadPosition < count)
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(count), "Attempt to rewind past the buffer start, some of this data is no longer part of the underlying buffer.");
// Shut down any streaming going on on the column
if (StreamActive)
DisposeUserActiveStream(async: false).GetAwaiter().GetResult();
RewindCore(count);
}
void RewindCore(int count)
{
Debug.Assert(CurrentOffset >= count);
Debug.Assert(_buffer.ReadPosition >= count);
_buffer.ReadPosition -= count;
}
/// <summary>
///
/// </summary>
/// <param name="async"></param>
/// <returns>The stream length, if any</returns>
async ValueTask DisposeUserActiveStream(bool async)
{
if (async)
await (_userActiveStream?.DisposeAsync() ?? new()).ConfigureAwait(false);
else
_userActiveStream?.Dispose();
_userActiveStream = null;
}
internal int CharsRead => _charsRead;
internal bool CharsReadActive => _charsReadOffset is not null;
internal void GetCharsReadInfo(Encoding encoding, out int charsRead, out TextReader reader, out int charsOffset, out ArraySegment<char>? buffer)
{
if (!CharsReadActive)
ThrowHelper.ThrowInvalidOperationException("No active chars read");
charsRead = _charsRead;
reader = _charsReadReader ??= GetTextReader(encoding);
charsOffset = _charsReadOffset ?? 0;
buffer = _charsReadBuffer;
}
internal void RestartCharsRead()
{
if (!CharsReadActive)
ThrowHelper.ThrowInvalidOperationException("No active chars read");
switch (_charsReadReader)
{
case PreparedTextReader reader:
reader.Restart();
break;
case StreamReader reader:
reader.BaseStream.Seek(0, SeekOrigin.Begin);
reader.DiscardBufferedData();
break;
}
_charsRead = 0;
}
internal void AdvanceCharsRead(int charsRead) => _charsRead += charsRead;
internal void StartCharsRead(int dataOffset, ArraySegment<char>? buffer)
{
if (!Resumable)
ThrowHelper.ThrowInvalidOperationException("Reader was not initialized as resumable");
_charsReadOffset = dataOffset;
_charsReadBuffer = buffer;
}
internal void EndCharsRead()
{
if (!Resumable)
ThrowHelper.ThrowInvalidOperationException("Wasn't initialized as resumed");
if (!CharsReadActive)
ThrowHelper.ThrowInvalidOperationException("No active chars read");
_charsReadOffset = null;
_charsReadBuffer = null;
}
internal void Init(int fieldSize, DataFormat fieldFormat, bool resumable = false)
{
if (Initialized)
ThrowHelper.ThrowInvalidOperationException("Already initialized");
_fieldStartPos = _buffer.CumulativeReadPosition;
_fieldConsumed = false;
_fieldSize = fieldSize;
_fieldFormat = fieldFormat;
_resumable = resumable;
}
internal void StartRead(Size bufferRequirement)
{
Debug.Assert(FieldSize >= 0);
_fieldBufferRequirement = bufferRequirement;
var byteCount = BufferRequirements.GetMinimumBufferByteCount(bufferRequirement, FieldSize);
if (ShouldBuffer(byteCount))
BufferNoInlined(byteCount);
[MethodImpl(MethodImplOptions.NoInlining)]
void BufferNoInlined(int byteCount)
=> Buffer(byteCount);
}
internal ValueTask StartReadAsync(Size bufferRequirement, CancellationToken cancellationToken)
{
Debug.Assert(FieldSize >= 0);
_fieldBufferRequirement = bufferRequirement;
var byteCount = BufferRequirements.GetMinimumBufferByteCount(bufferRequirement, FieldSize);
return ShouldBuffer(byteCount) ? BufferAsync(byteCount, cancellationToken) : new();
}
internal void EndRead()
{
if (_resumable || StreamActive)
return;
// If it was upper bound we should consume.
if (_fieldBufferRequirement is { Kind: SizeKind.UpperBound })
{
Consume(FieldRemaining);
return;
}
if (FieldOffset != FieldSize)
ThrowNotConsumedExactly();
_fieldConsumed = true;
}
internal ValueTask EndReadAsync()
{
if (_resumable || StreamActive)
return new();
// If it was upper bound we should consume.
if (_fieldBufferRequirement is { Kind: SizeKind.UpperBound })
return ConsumeAsync(FieldRemaining);
if (FieldOffset != FieldSize)
ThrowNotConsumedExactly();
_fieldConsumed = true;
return new();
}
internal async ValueTask<NestedReadScope> BeginNestedRead(bool async, int size, Size bufferRequirement, CancellationToken cancellationToken = default)
{
if (size > CurrentRemaining)
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(size), "Cannot begin a read for a larger size than the current remaining size.");
if (size < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(size), "Cannot be negative");
var previousSize = CurrentSize;
var previousStartPos = _currentStartPos;
var previousBufferRequirement = CurrentBufferRequirement;
_currentSize = size;
_currentBufferRequirement = bufferRequirement;
_currentStartPos = FieldOffset;
var byteCount = BufferRequirements.GetMinimumBufferByteCount(bufferRequirement, size);
if (ShouldBuffer(byteCount))
await Buffer(async, byteCount, cancellationToken).ConfigureAwait(false);
return new NestedReadScope(async, this, previousSize, previousStartPos, previousBufferRequirement);
}
public NestedReadScope BeginNestedRead(int size, Size bufferRequirement)
=> BeginNestedRead(async: false, size, bufferRequirement, CancellationToken.None).GetAwaiter().GetResult();
public ValueTask<NestedReadScope> BeginNestedReadAsync(int size, Size bufferRequirement, CancellationToken cancellationToken = default)
=> BeginNestedRead(async: true, size, bufferRequirement, cancellationToken);
/// Seek origin is the start of Current, e.g. Seek(0) rewinds to the start.
internal void Seek(int offset)
{
var currentOffset = CurrentOffset;
if (currentOffset > offset)
Rewind(currentOffset - offset);
else if (currentOffset < offset)
Consume(offset - currentOffset);
}
public void Consume(int? count = null)
{
if (count <= 0 || FieldSize < 0 || FieldRemaining == 0)
return;
var currentRemaining = CurrentRemaining;
var remaining = count ?? currentRemaining;
if (count > currentRemaining)
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(count), "Attempt to read past the end of the current field size.");
if (StreamActive)
DisposeUserActiveStream(async: false).GetAwaiter().GetResult();
var origOffset = FieldOffset;
// A breaking exception unwind from a nested scope should not try to consume its remaining data.
if (!_buffer.Connector.IsBroken)
_buffer.Skip(remaining, allowIO: true);
Debug.Assert(FieldRemaining == FieldSize - origOffset - remaining);
}
public async ValueTask ConsumeAsync(int? count = null, CancellationToken cancellationToken = default)
{
if (count <= 0 || FieldSize < 0 || FieldRemaining == 0)
return;
var currentRemaining = CurrentRemaining;
var remaining = count ?? currentRemaining;
if (count > currentRemaining)
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(count), "Attempt to read past the end of the current field size.");
if (StreamActive)
await DisposeUserActiveStream(async: true).ConfigureAwait(false);
var origOffset = FieldOffset;
// A breaking exception unwind from a nested scope should not try to consume its remaining data.
if (!_buffer.Connector.IsBroken)
await _buffer.Skip(async:true, remaining).ConfigureAwait(false);
Debug.Assert(FieldRemaining == FieldSize - origOffset - remaining);
}
[MemberNotNullWhen(true, nameof(_userActiveStream))]
bool StreamActive => _userActiveStream is { IsDisposed: false };
internal void ThrowIfStreamActive()
{
if (StreamActive)
ThrowHelper.ThrowInvalidOperationException("A stream is already open for this reader");
}
[MethodImpl(MethodImplOptions.NoInlining)]
void Cleanup()
{
if (StreamActive)
DisposeUserActiveStream(async: false).GetAwaiter().GetResult();
if (_pooledArray is not null)
{
ArrayPool.Return(_pooledArray);
_pooledArray = null;
}
if (_charsReadReader is not null)
{
_charsReadReader.Dispose();
_charsReadReader = null;
_charsRead = default;
}
_requiresCleanup = false;
}
void ResetCurrent()
{
_currentStartPos = 0;
_currentBufferRequirement = default;
_currentSize = UninitializedSentinel;
}
internal int Restart(bool resumable)
{
if (!Initialized)
ThrowHelper.ThrowInvalidOperationException("Cannot restart a non-initialized reader.");
// We resume if the reader was initialized as resumable and we're not explicitly restarting as non-resumable.
// When the field size is DbNullSentinel (i.e. -1) we're always restarting as resumable, to allow rereading null values endlessly.
var fieldSize = FieldSize;
if ((Resumable && resumable) || fieldSize is DbNullSentinel)
{
_resumable = true;
return fieldSize;
}
// From this point on we're not resuming, we're resetting any remaining state and rewinding our position.
// Shut down any streaming and pooling going on on the column.
if (_requiresCleanup)
Cleanup();
if (NestedInitialized)
ResetCurrent();
_fieldConsumed = false;
_resumable = resumable;
RewindCore(FieldOffset);
Debug.Assert(Initialized);
return fieldSize;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void Commit()
{
if (!Initialized)
return;
// Shut down any streaming and pooling going on on the column.
if (_requiresCleanup)
Cleanup();
if (NestedInitialized)
ResetCurrent();
// We make sure to fuly consume any FieldRemaining in the event of an exception or a nested scope not being disposed.
Debug.Assert(!NestedInitialized);
if (!_fieldConsumed && FieldRemaining > 0)
Consume();
_fieldStartPos = UninitializedSentinel;
Debug.Assert(!Initialized);
// These will always be re-initialized by Init()
// _fieldSize = default;
// _fieldFormat = default;
// _resumable = default;
// _fieldConsumed = default;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ValueTask CommitAsync()
{
if (!Initialized)
return new();
// Shut down any streaming and pooling going on on the column.
if (_requiresCleanup)
Cleanup();
if (NestedInitialized)
ResetCurrent();
// We make sure to fuly consume any FieldRemaining in the event of an exception or a nested scope not being disposed.
Debug.Assert(!NestedInitialized);
if (!_fieldConsumed && FieldRemaining > 0)
return CommitAsync();
_fieldStartPos = UninitializedSentinel;
Debug.Assert(!Initialized);
// These will always be re-initialized by Init()
// _fieldSize = default;
// _fieldFormat = default;
// _resumable = default;
// _fieldConsumed = default;
return new();
async ValueTask CommitAsync()
{
await ConsumeAsync().ConfigureAwait(false);
_fieldStartPos = UninitializedSentinel;
Debug.Assert(!Initialized);
// These will always be re-initialized by Init()
// _fieldSize = default;
// _fieldFormat = default;
// _resumable = default;
// _fieldConsumed = default;
}
}
byte[] RentArray(int count)
{
_requiresCleanup = true;
var pooledArray = _pooledArray;
if (pooledArray is not null)
{
if (pooledArray.Length >= count)
return pooledArray;
ArrayPool.Return(pooledArray);
}
var array = _pooledArray = ArrayPool.Rent(count);
return array;
}
// We check FieldAtStart to speed up simple value reads, as field level buffering was handled by reader.StartRead() already.
internal bool ShouldBufferCurrent()
=> !FieldAtStart && ShouldBuffer(BufferRequirements.GetMinimumBufferByteCount(CurrentBufferRequirement, CurrentRemaining));
public bool ShouldBuffer(int byteCount)
{
return _buffer.ReadBytesLeft < byteCount && ShouldBufferSlow(byteCount);
[MethodImpl(MethodImplOptions.NoInlining)]
bool ShouldBufferSlow(int byteCount)
{
if (byteCount > _buffer.Size)
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(byteCount),
"Buffer requirement is larger than the buffer size, this can never succeed by buffering data but requires a larger buffer size instead.");
if (byteCount > CurrentRemaining)
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(byteCount),
"Buffer requirement is larger than the remaining length of the value, make sure the value is always at least this size or use an upper bound requirement instead.");
return true;
}
}
public void Buffer(int byteCount) => _buffer.Ensure(byteCount);
public ValueTask BufferAsync(int byteCount, CancellationToken cancellationToken) => _buffer.EnsureAsync(byteCount);
internal ValueTask Buffer(bool async, int byteCount, CancellationToken cancellationToken)
{
if (async)
return BufferAsync(byteCount, cancellationToken);
Buffer(byteCount);
return new();
}
void ThrowNotConsumedExactly() =>
throw _buffer.Connector.Break(
new InvalidOperationException(
FieldOffset < FieldSize
? $"The read on this field has not consumed all of its bytes (pos: {FieldOffset}, len: {FieldSize})"
: $"The read on this field has consumed all of its bytes and read into the subsequent bytes (pos: {FieldOffset}, len: {FieldSize})"));
}
public readonly struct NestedReadScope : IDisposable, IAsyncDisposable
{
readonly PgReader _reader;
readonly int _previousSize;
readonly int _previousStartPos;
readonly Size _previousBufferRequirement;
readonly bool _async;
internal NestedReadScope(bool async, PgReader reader, int previousSize, int previousStartPos, Size previousBufferRequirement)
{
_async = async;
_reader = reader;
_previousSize = previousSize;
_previousStartPos = previousStartPos;
_previousBufferRequirement = previousBufferRequirement;
}
public void Dispose()
{
if (_async)
ThrowHelper.ThrowInvalidOperationException("Cannot synchronously dispose async scopes, call DisposeAsync instead.");
DisposeAsync().GetAwaiter().GetResult();
}
public ValueTask DisposeAsync()
{
if (_reader.CurrentRemaining > 0)
{
if (_async)
return AsyncCore(_reader, _previousSize, _previousStartPos, _previousBufferRequirement);
_reader.Consume();
}
_reader.Revert(_previousSize, _previousStartPos, _previousBufferRequirement);
return new();
static async ValueTask AsyncCore(PgReader reader, int previousSize, int previousStartPos, Size previousBufferRequirement)
{
await reader.ConsumeAsync().ConfigureAwait(false);
reader.Revert(previousSize, previousStartPos, previousBufferRequirement);
}
}
}