-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathCharStream.cs
3923 lines (3709 loc) · 161 KB
/
CharStream.cs
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
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Stephan Tolksdorf 2007-2012
// License: Simplified BSD License. See accompanying documentation.
#if !LOW_TRUST
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Microsoft.FSharp.Core;
using FParsec.Cloning;
namespace FParsec {
/// <summary>An opaque representation of a CharStream index.</summary>
public unsafe struct CharStreamIndexToken {
#if DEBUG
internal readonly CharStream CharStream;
private long Index { get { return GetIndex(CharStream); } }
#endif
internal readonly char* Ptr;
private readonly int BlockPlus1;
/// <summary>Returns -1 if the IndexToken was zero-initialized.</summary>
internal int Block { get { return unchecked(BlockPlus1 - 1); } }
internal CharStreamIndexToken(
#if DEBUG
CharStream charStream,
#endif
char* ptr,
int block)
{
#if DEBUG
CharStream = charStream;
#endif
Ptr = ptr;
BlockPlus1 = unchecked(block + 1);
}
private static void ThrowInvalidIndexToken() {
throw new InvalidOperationException("The CharStreamIndexToken is invalid.");
}
public long GetIndex(CharStream charStreamFromWhichIndexTokenWasRetrieved) {
int block = Block;
if (block < 0) ThrowInvalidIndexToken(); // tests for a zero-initialized IndexToken
#if DEBUG
Debug.Assert(CharStream == charStreamFromWhichIndexTokenWasRetrieved);
#endif
return charStreamFromWhichIndexTokenWasRetrieved.GetIndex(Ptr, block);
}
}
public struct TwoChars : IEquatable<TwoChars> {
private uint Chars;
internal TwoChars(uint chars) {
Chars = chars;
}
public TwoChars(char char0, char char1) {
Chars = ((uint)char1 << 16) | (uint)char0;
}
public char Char0 { get { return unchecked((char)Chars); } }
public char Char1 { get { return (char)(Chars >> 16); } }
public override bool Equals(object obj) { return (obj is TwoChars) && Chars == ((TwoChars) obj).Chars; }
public bool Equals(TwoChars other) { return Chars == other.Chars; }
public override int GetHashCode() { return unchecked((int)Chars); }
public static bool operator==(TwoChars left, TwoChars right) { return left.Chars == right.Chars; }
public static bool operator!=(TwoChars left, TwoChars right) { return left.Chars != right.Chars; }
}
/// <summary>Provides read‐access to a sequence of UTF‐16 chars.</summary>
public unsafe class CharStream : IDisposable {
// In order to facilitate efficient backtracking we divide the stream into overlapping
// blocks with equal number of chars. The blocks are overlapping, so that
// backtracking over short distances at a block boundary doesn't trigger a reread of the
// previous block.
//
// Block 0
//
// -----------------|-------- Block 1
// Overlap
// --------|--------|-------- Block 2
// Overlap
// --------|--------|--------
// (...)
// a '-' symbolizes a char, a '|' a block boundary.
//
//
// In general there's no fixed relationship between the number of input bytes and the
// number of input chars. Worse, the encoding can be stateful, which makes it necessary
// to persist the decoder state over block boundaries. If we later want to
// be able to reread a certain block, we therefore need to keep record of various
// bits of information describing the state of the input stream at the beginning of a block:
private class BlockInfo {
/// <summary>the byte stream index of the first char in the block after the OverhangCharsAtBlockBegin</summary>
public long ByteIndex;
/// <summary>the value of the CharStream's ByteBufferIndex before the block is read</summary>
public int ByteBufferIndex;
/// <summary>the number of bytes in the stream from ByteIndex to the first char after the OverhangCharsAfterOverlap</summary>
public int NumberOfBytesInOverlap;
/// <summary>the last char in the overlap with the previous block (used for integrity checking)</summary>
public char LastCharInOverlap;
/// <summary>chars at the block begin that were already read together with chars of the last block before the overlap</summary>
public string OverhangCharsAtBlockBegin;
/// <summary>chars after the overlap with the previous block that were already read together with the overlap chars</summary>
public string OverhangCharsAfterOverlap;
// Unfortunately the Decoder API has no explicit methods for managing the state,
// which forces us to use the comparatively inefficient serialization API
// (via FParsec.Cloning) for this purpose.
// The absence of explicit state management or at least a cloning method in the
// Decoder interface is almost as puzzling to me as the absence of such methods
// in System.Random.
public CloneImage DecoderImageAtBlockBegin;
public CloneImage DecoderImageAfterOverlap;
public BlockInfo(long byteIndex, int byteBufferIndex,
int nBytesInOverlapCount, char lastCharInOverlap,
string overhangCharsAtBlockBegin, CloneImage decoderImageAtBlockBegin,
string overhangCharsAfterOverlap, CloneImage decoderImageAfterOverlap)
{
ByteIndex = byteIndex;
ByteBufferIndex = byteBufferIndex;
NumberOfBytesInOverlap = nBytesInOverlapCount;
LastCharInOverlap = lastCharInOverlap;
OverhangCharsAtBlockBegin = overhangCharsAtBlockBegin;
OverhangCharsAfterOverlap = overhangCharsAfterOverlap;
DecoderImageAtBlockBegin = decoderImageAtBlockBegin;
DecoderImageAfterOverlap = decoderImageAfterOverlap;
}
}
private const int DefaultBlockSize = 3*(1 << 16); // 3*2^16 = 200k
private const int DefaultByteBufferLength = (1 << 12);
private static int MinimumByteBufferLength = 128; // must be larger than longest detectable preamble (we can only guess here)
private const char EOS = '\uFFFF';
public const char EndOfStreamChar = EOS;
/// <summary>Points to the current char in Buffer,
/// or is null if the end of the stream has been reached.</summary>
internal char* Ptr;
/// <summary>Equals Ptr == null ? null : BufferBegin.</summary>
internal char* PtrBegin;
/// <summary>Equals Ptr == null ? null : BufferEnd.</summary>
internal char* PtrEnd;
/// <summary>Begin of the used part of the char buffer. Is constant. Is null if the CharStream is empty.</summary>
internal char* BufferBegin;
/// <summary>End of the used part of the char buffer. Varies for a multi-block stream. Is null if the CharStream is empty.</summary>
internal char* BufferEnd;
/// <summary>The block currently loaded in the buffer.</summary>
internal int Block;
/// <summary>Any CharStream method or property setter increments this value when it changes the CharStream state.
/// Backtracking to an old state also restores the old value of the StateTag.</summary>
public
#if SMALL_STATETAG
int
#else
long
#endif
StateTag;
internal long IndexOfFirstCharInBlock;
internal long _IndexOfFirstChar;
/// <summary>The index of the first char in the stream.</summary>
public long IndexOfFirstChar { get { return _IndexOfFirstChar; } }
internal long _Line;
/// <summary>The line number for the next char. (The line count starts with 1.)</summary>
public long Line { get { return _Line; } }
public void SetLine_WithoutCheckAndWithoutIncrementingTheStateTag(long line) {
_Line = line;
}
internal long _LineBegin;
/// <summary>The stream index of the first char of the line that also contains the next char.</summary>
public long LineBegin { get { return _LineBegin; } }
public void SetLineBegin_WithoutCheckAndWithoutIncrementingTheStateTag(long lineBegin) {
_LineBegin = lineBegin;
}
/// <summary>The UTF‐16 column number of the next char, i.e. Index ‐ LineBegin + 1.</summary>
public long Column { get { return Index - LineBegin + 1; } }
internal string _Name;
public string Name {
get { return _Name; }
set { _Name = value; ++StateTag; }
}
/// <summary>The Encoding that is used for decoding the underlying byte stream, or
/// System.Text.UnicodeEncoding in case the stream was directly constructed
/// from a string or char buffer.</summary>
public Encoding Encoding { get; private set; }
// If the CharStream is constructed from a binary stream, we use a managed string as the char
// buffer. This allows us to apply regular expressions directly to the input.
// In the case of multi-block CharStreams we thus have to mutate the buffer string through pointers.
// This is safe as long as we use a newly constructed string and we don't pass a reference
// to the internal buffer string to the "outside world". (The one instance where we have to pass
// a reference to the buffer string is regex matching. See the docs for Match(regex) for more info.)
//
// Apart from Match(regex) we access the internal buffer only through a pinned pointer.
// This way we avoid the overhead of redundant bounds checking and can support strings, char arrays
// and unmanaged char buffers through the same interface.
//
// Pinning a string or char array makes life more difficult for the GC. However, as long as
// the buffer is only short-lived or large enough to be allocated on the large object heap,
// there shouldn't be a problem. Furthermore, the buffer strings for CharStreams constructed
// from a binary stream are allocated through the StringBuffer interface and hence always live
// on the large object heap. Thus, the only scenario to really worry about (and which the
// documentation explicitly warns about) is when a large number of small CharStreams
// are constructed directly from strings or char arrays and are used for an extended period of time.
/// <summary>The string holding the char buffer, or null if the buffer is not part of a .NET string.</summary>
internal string BufferString;
/// <summary>A pointer to the beginning of BufferString, or null if BufferString is null.</summary>
internal char* BufferStringPointer;
/// <summary>Holds the GCHandle for CharStreams directly constructed from strings or char arrays.</summary>
private GCHandle BufferHandle;
/// <summary>Holds the StringBuffer for CharStreams constructed from a binary stream.</summary>
private StringBuffer StringBuffer;
#if DEBUG
internal FSharpRef<int> SubstreamCount = new FSharpRef<int>(0);
internal FSharpRef<int> ParentSubstreamCount = null;
#endif
private MultiBlockData BlockData;
internal bool IsSingleBlockStream { get { return BlockData == null; } }
/// <summary>Contains the data and methods needed in case the input byte stream
/// is large enough to span multiple blocks of the CharStream.</summary>
private partial class MultiBlockData {
public CharStream CharStream;
public long IndexOfLastCharPlus1;
/// <summary>The index of the last block of the stream, or Int32.MaxValue if the end of stream has not yet been detected.</summary>
public int LastBlock;
public Stream Stream;
// we keep a separate record of the Stream.Position, so that we don't need to require Stream.CanSeek
public long StreamPosition;
// we use StreamLength to avoid calling Read() again on a non-seekable stream after it returned 0 once (see ticket #23)
public long StreamLength;
public bool LeaveOpen;
public int MaxCharCountForOneByte;
public Decoder Decoder;
public bool DecoderIsSerializable;
public int BlockSize;
public int BlockOverlap;
/// <summary>BufferBegin + BlockSize - minRegexSpace</summary>
public char* RegexSpaceThreshold;
/// <summary>The byte stream index of the first unused byte in the ByteBuffer.</summary>
public long ByteIndex { get { return StreamPosition - (ByteBufferCount - ByteBufferIndex); } }
public List<BlockInfo> Blocks;
public byte[] ByteBuffer;
public int ByteBufferIndex;
public int ByteBufferCount;
}
public long IndexOfLastCharPlus1 { get {
return BlockData != null ? BlockData.IndexOfLastCharPlus1
: IndexOfFirstChar + Buffer.PositiveDistance(BufferBegin, BufferEnd);
} }
public int BlockOverlap { get {
return BlockData == null ? 0 : BlockData.BlockOverlap;
} }
public int MinRegexSpace {
get {
return BlockData == null
? 0
: (int)Buffer.PositiveDistance(BlockData.RegexSpaceThreshold,
BufferBegin + BlockData.BlockSize);
}
set {
if (BlockData != null) {
if (value < 0 || value > BlockData.BlockOverlap) throw new ArgumentOutOfRangeException("value", "The MinRegexSpace value must be non-negative and not greater than the BlockOverlap.");
BlockData.RegexSpaceThreshold = BufferBegin + BlockData.BlockSize - value;
}
}
}
public bool IsBeginOfStream { get { return Ptr == BufferBegin && Block == 0; } }
public bool IsEndOfStream { get { return Ptr == null; } }
public long Index {
#if AGGRESSIVE_INLINING
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
get {
if (Ptr != null) {
Debug.Assert(BufferBegin <= Ptr && Ptr < BufferEnd);
if (sizeof(System.IntPtr) != 8) // the JIT removes the inactive branch
return Buffer.PositiveDistance(PtrBegin, Ptr) + IndexOfFirstCharInBlock;
else
return Buffer.PositiveDistance64(PtrBegin, Ptr) + IndexOfFirstCharInBlock;
}
Debug.Assert(BlockData == null || BlockData.IndexOfLastCharPlus1 != Int64.MaxValue);
return IndexOfLastCharPlus1;
}
}
internal long GetIndex(char* ptr, int block) {
if (ptr != null) {
if (block == Block) {
Debug.Assert(BufferBegin <= ptr && ptr < BufferEnd);
if (sizeof(System.IntPtr) != 8)
return Buffer.PositiveDistance(BufferBegin, ptr) + IndexOfFirstCharInBlock;
else
return Buffer.PositiveDistance64(BufferBegin, ptr) + IndexOfFirstCharInBlock;
} else {
Debug.Assert(BlockData != null && BufferBegin <= ptr && ptr < BufferBegin + BlockData.BlockSize);
int blockSizeMinusOverlap = BlockData.BlockSize - BlockData.BlockOverlap;
long indexOfBlockBegin = IndexOfFirstChar + Math.BigMul(block, blockSizeMinusOverlap);
if (sizeof(System.IntPtr) != 8)
return Buffer.PositiveDistance(BufferBegin, ptr) + indexOfBlockBegin;
else
return Buffer.PositiveDistance64(BufferBegin, ptr) + indexOfBlockBegin;
}
}
Debug.Assert(BlockData == null || BlockData.IndexOfLastCharPlus1 != Int64.MaxValue);
return IndexOfLastCharPlus1;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public Position Position { get {
long index = Index;
return new Position(_Name, index, Line, index - LineBegin + 1);
} }
// we don't have a public constructor that only takes a string to avoid potential confusion with a filepath constructor
internal CharStream(string chars) {
Debug.Assert(chars != null);
BufferString = chars;
BufferHandle = GCHandle.Alloc(chars, GCHandleType.Pinned);
char* bufferBegin = (char*)BufferHandle.AddrOfPinnedObject();
BufferStringPointer = bufferBegin;
CharConstructorContinue(bufferBegin, chars.Length);
}
public CharStream(string chars, int index, int length) : this(chars, index, length, 0) {}
public CharStream(string chars, int index, int length, long streamIndexOffset) {
if (chars == null) throw new ArgumentNullException("chars");
if (index < 0) throw new ArgumentOutOfRangeException("index", "index is negative.");
if (length < 0 || length > chars.Length - index) throw new ArgumentOutOfRangeException("length", "index or length is out of range.");
if (streamIndexOffset < 0 || streamIndexOffset >= (1L << 60)) throw new ArgumentOutOfRangeException("streamIndexOffset", "streamIndexOffset must be non-negative and less than 2^60.");
IndexOfFirstCharInBlock = streamIndexOffset;
_IndexOfFirstChar = streamIndexOffset;
_LineBegin = streamIndexOffset;
BufferString = chars;
BufferHandle = GCHandle.Alloc(chars, GCHandleType.Pinned);
char* pBufferString = (char*)BufferHandle.AddrOfPinnedObject();
BufferStringPointer = pBufferString;
CharConstructorContinue(pBufferString + index, length);
}
public CharStream(char[] chars, int index, int length) : this(chars, index, length, 0) { }
public CharStream(char[] chars, int index, int length, long streamIndexOffset) {
if (chars == null) throw new ArgumentNullException("chars");
if (index < 0) throw new ArgumentOutOfRangeException("index", "index is negative.");
if (length < 0 || length > chars.Length - index) throw new ArgumentOutOfRangeException("length", "index or length is out of range.");
if (streamIndexOffset < 0 || streamIndexOffset >= (1L << 60)) throw new ArgumentOutOfRangeException("streamIndexOffset", "streamIndexOffset must be non-negative and less than 2^60.");
IndexOfFirstCharInBlock = streamIndexOffset;
_IndexOfFirstChar = streamIndexOffset;
_LineBegin = streamIndexOffset;
BufferHandle = GCHandle.Alloc(chars, GCHandleType.Pinned);
char* bufferBegin = (char*)BufferHandle.AddrOfPinnedObject() + index;
if (bufferBegin < unchecked(bufferBegin + length + 1)) { // a pedantic check ...
CharConstructorContinue(bufferBegin, length);
} else {
// ... for a purely theoretic case
BufferHandle.Free();
throw new ArgumentOutOfRangeException("length", "The char array may not be allocated directly below the end of the address space.");
}
}
public CharStream(char* chars, int length) : this(chars, length, 0) {}
public CharStream(char* chars, int length, long streamIndexOffset) {
if (chars == null) throw new ArgumentNullException("chars");
if (length < 0) throw new ArgumentOutOfRangeException("length", "length is negative.");
if (chars >= unchecked(chars + length + 1)) // chars + length + 1 must not overflow (the + 1 is needed for some methods below)
throw new ArgumentOutOfRangeException("length", "length is too large.");
if (streamIndexOffset < 0 || streamIndexOffset >= (1L << 60)) throw new ArgumentOutOfRangeException("streamIndexOffset", "streamIndexOffset must be non-negative and less than 2^60.");
IndexOfFirstCharInBlock = streamIndexOffset;
_IndexOfFirstChar = streamIndexOffset;
_LineBegin = streamIndexOffset;
CharConstructorContinue(chars, length);
}
private void CharConstructorContinue(char* bufferBegin, int length) {
Debug.Assert((bufferBegin != null || length == 0) && length >= 0
&& bufferBegin < unchecked(bufferBegin + length + 1)); // the + 1 is needed for some methods below
if (length != 0) {
BufferBegin = bufferBegin;
BufferEnd = bufferBegin + length;
Ptr = bufferBegin;
PtrBegin = bufferBegin;
PtrEnd = BufferEnd;
}
_Line = 1;
Encoding = Encoding.Unicode;
}
internal CharStream(string chars, char* pChars, char* begin, int length) {
Debug.Assert((chars == null ? pChars == null
: pChars <= begin && length >= 0 && (int)Buffer.PositiveDistance(pChars, begin) <= chars.Length - length)
&& (begin == null ? length == 0
: length >= 0 && begin < unchecked(begin + length + 1)));
BufferString = chars;
BufferStringPointer = pChars;
if (length != 0) {
BufferBegin = begin;
BufferEnd = begin + length;
Ptr = begin;
PtrBegin = begin;
PtrEnd = BufferEnd;
}
_Line = 1;
Encoding = Encoding.Unicode;
}
public CharStream(string path, Encoding encoding)
: this(path, encoding, true,
DefaultBlockSize, DefaultBlockSize/3, DefaultByteBufferLength) { }
public CharStream(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks)
: this(path, encoding, detectEncodingFromByteOrderMarks,
DefaultBlockSize, DefaultBlockSize/3, DefaultByteBufferLength) { }
public CharStream(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks,
int blockSize, int blockOverlap, int byteBufferLength)
{
if (encoding == null) throw new ArgumentNullException("encoding");
var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan);
try {
StreamConstructorContinue(stream, false, encoding, detectEncodingFromByteOrderMarks,
blockSize, blockOverlap, byteBufferLength);
_Name = path;
} catch {
stream.Dispose();
throw;
}
}
public CharStream(Stream stream, Encoding encoding)
: this(stream,
false, encoding, true,
DefaultBlockSize, DefaultBlockSize/3, DefaultByteBufferLength) { }
public CharStream(Stream stream, bool leaveOpen, Encoding encoding)
: this(stream,
leaveOpen, encoding, true,
DefaultBlockSize, DefaultBlockSize/3, DefaultByteBufferLength) { }
public CharStream(Stream stream, bool leaveOpen, Encoding encoding, bool detectEncodingFromByteOrderMarks)
: this(stream,
leaveOpen, encoding, detectEncodingFromByteOrderMarks,
DefaultBlockSize, DefaultBlockSize/3, DefaultByteBufferLength) { }
public CharStream(Stream stream, bool leaveOpen,
Encoding encoding, bool detectEncodingFromByteOrderMarks,
int blockSize, int blockOverlap, int byteBufferLength)
{
if (stream == null) throw new ArgumentNullException("stream");
if (!stream.CanRead) throw new ArgumentException("stream is not readable");
if (encoding == null) throw new ArgumentNullException("encoding");
StreamConstructorContinue(stream, leaveOpen, encoding, detectEncodingFromByteOrderMarks,
blockSize, blockOverlap, byteBufferLength);
}
/// <summary>we modify this flag via reflection in the unit test</summary>
private static bool DoNotRoundUpBlockSizeToSimplifyTesting = false;
private void StreamConstructorContinue(Stream stream, bool leaveOpen,
Encoding encoding, bool detectEncodingFromByteOrderMarks,
int blockSize, int blockOverlap, int byteBufferLength)
{
if (byteBufferLength < MinimumByteBufferLength) byteBufferLength = MinimumByteBufferLength;
int remainingBytesCount = -1;
long streamPosition;
long streamLength;
if (stream.CanSeek) {
streamPosition = stream.Position;
streamLength = stream.Length;
long remainingBytesCount64 = streamLength - streamPosition;
if (remainingBytesCount64 <= Int32.MaxValue) {
remainingBytesCount = (int)remainingBytesCount64;
if (remainingBytesCount < byteBufferLength) byteBufferLength = remainingBytesCount;
}
} else {
streamPosition = 0;
streamLength = Int64.MaxValue;
}
byte[] byteBuffer = new byte[byteBufferLength];
int byteBufferCount = 0;
do {
int n = stream.Read(byteBuffer, byteBufferCount, byteBufferLength - byteBufferCount);
if (n == 0) {
remainingBytesCount = byteBufferCount;
Debug.Assert(!stream.CanSeek || streamPosition + byteBufferCount == streamLength);
streamLength = streamPosition + byteBufferCount;
break;
}
byteBufferCount += n;
} while (byteBufferCount < MinimumByteBufferLength);
streamPosition += byteBufferCount;
int preambleLength = Text.DetectPreamble(byteBuffer, byteBufferCount, ref encoding, detectEncodingFromByteOrderMarks);
remainingBytesCount -= preambleLength;
_Line = 1;
Encoding = encoding;
// we allow such small block sizes only to simplify testing
if (blockSize < 8) blockSize = DefaultBlockSize;
bool allCharsFitIntoOneBlock = false;
if (remainingBytesCount >= 0 && remainingBytesCount/4 <= blockSize) {
if (remainingBytesCount != 0) {
try {
int maxCharCount = Encoding.GetMaxCharCount(remainingBytesCount); // may throw ArgumentOutOfRangeException
if (blockSize >= maxCharCount) {
allCharsFitIntoOneBlock = true;
blockSize = maxCharCount;
}
} catch (ArgumentOutOfRangeException) { }
} else {
allCharsFitIntoOneBlock = true;
blockSize = 0;
}
}
var buffer = StringBuffer.Create(blockSize);
Debug.Assert(buffer.Length >= blockSize && (blockSize > 0 || buffer.StringPointer == null));
StringBuffer = buffer;
BufferString = buffer.String;
BufferStringPointer = buffer.StringPointer;
char* bufferBegin = buffer.StringPointer + buffer.Index;
try {
Decoder decoder = encoding.GetDecoder();
if (allCharsFitIntoOneBlock) {
int bufferCount = preambleLength == byteBufferCount
? 0
: Text.ReadAllRemainingCharsFromStream(bufferBegin, buffer.Length, byteBuffer, preambleLength, byteBufferCount, stream, streamPosition, decoder, streamPosition == streamLength);
if (!leaveOpen) stream.Close();
if (bufferCount != 0) {
BufferBegin = bufferBegin;
Ptr = bufferBegin;
PtrBegin = bufferBegin;
BufferEnd = bufferBegin + bufferCount;
PtrEnd = BufferEnd;
}
Block = 0;
} else {
if (!DoNotRoundUpBlockSizeToSimplifyTesting) blockSize = buffer.Length;
BufferBegin = bufferBegin;
BufferEnd = bufferBegin;
var d = new MultiBlockData();
BlockData = d;
d.CharStream = this;
d.Stream = stream;
d.StreamPosition = streamPosition;
d.StreamLength = streamLength;
d.LeaveOpen = leaveOpen;
d.Decoder = decoder;
d.DecoderIsSerializable = decoder.GetType().IsSerializable;
d.ByteBuffer = byteBuffer;
d.ByteBufferIndex = preambleLength;
d.ByteBufferCount = byteBufferCount;
d.MaxCharCountForOneByte = Math.Max(1, Encoding.GetMaxCharCount(1));
if (d.MaxCharCountForOneByte > 1024) // an arbitrary limit low enough that a char array with this size can be allocated on the stack
throw new ArgumentException("The CharStream class does not support Encodings with GetMaxCharCount(1) > 1024.");
if (blockSize < 3*d.MaxCharCountForOneByte) blockSize = 3*d.MaxCharCountForOneByte;
// MaxCharCountForOneByte == the maximum number of overhang chars
if( Math.Min(blockOverlap, blockSize - 2*blockOverlap) < d.MaxCharCountForOneByte
|| blockOverlap >= blockSize/2) blockOverlap = blockSize/3;
d.BlockSize = blockSize;
d.BlockOverlap = blockOverlap;
d.RegexSpaceThreshold = bufferBegin + (blockSize - 2*blockOverlap/3);
d.IndexOfLastCharPlus1 = Int64.MaxValue;
Block = -2; // special value recognized by ReadBlock
d.LastBlock = Int32.MaxValue;
d.Blocks = new List<BlockInfo>();
// the first block has no overlap with a previous block
d.Blocks.Add(new BlockInfo(preambleLength, preambleLength, 0, EOS, null, null, null, null));
d.ReadBlock(0);
if (d.LastBlock == 0) {
if (!d.LeaveOpen) d.Stream.Close();
BlockData = null;
}
}
} catch {
buffer.Dispose();
throw;
}
}
public void Dispose() {
#if DEBUG
lock (SubstreamCount) {
if (SubstreamCount.Value != 0)
throw new InvalidOperationException("A CharStream must not be disposed before all of its Substreams have been disposed.");
}
if (ParentSubstreamCount != null) {
lock (ParentSubstreamCount) --ParentSubstreamCount.Value;
}
#endif
if (BufferHandle.IsAllocated) BufferHandle.Free();
if (StringBuffer != null) StringBuffer.Dispose();
if (BlockData != null && !BlockData.LeaveOpen) BlockData.Stream.Close();
Ptr = null;
PtrBegin = null;
PtrEnd = null;
BufferBegin = null;
BufferEnd = null;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification="The CharStream is manually disposed.")]
public static T ParseString<T,TUserState>(string chars, int index, int length,
FSharpFunc<CharStream<TUserState>,T> parser,
TUserState userState,
string streamName)
{
if (index < 0) throw new ArgumentOutOfRangeException("index", "index is negative.");
if (length < 0 || length > chars.Length - index) throw new ArgumentOutOfRangeException("length", "length is out of range.");
fixed (char* pChars = chars) {
var stream = new CharStream<TUserState>(chars, pChars, pChars + index, length);
stream.UserState = userState;
stream._Name = streamName;
try {
return parser.Invoke(stream);
} finally {
#if DEBUG
stream.Dispose();
#else
// manually dispose stream
stream.Ptr = null;
stream.PtrBegin = null;
stream.PtrEnd = null;
stream.BufferBegin = null;
stream.BufferEnd = null;
#endif
}
}
}
private partial class MultiBlockData {
/// <summary>Refills the ByteBuffer if no unused byte is remaining.
/// Returns the number of unused bytes in the (refilled) ByteBuffer.</summary>
private int FillByteBuffer() {
int n = ByteBufferCount - ByteBufferIndex;
if (n > 0) return n;
return ClearAndRefillByteBuffer(0);
}
/// <summary>Refills the ByteBuffer starting at the given index. If the underlying byte
/// stream contains enough bytes, the ByteBuffer is filled up to the ByteBuffer.Length.
/// Returns the number of bytes available for consumption in the refilled ByteBuffer.</summary>
private int ClearAndRefillByteBuffer(int byteBufferIndex) {
Debug.Assert(byteBufferIndex >= 0 && byteBufferIndex <= ByteBuffer.Length);
// Stream.Read is not guaranteed to use all the provided output buffer, so we need
// to call it in a loop when we want to rely on the buffer being fully filled
// (unless we reach the end of the stream). Knowing that the buffer always gets
// completely filled allows us to calculate the buffer utilization after skipping
// a certain number of input bytes. For most streams there will be only one loop
// iteration anyway (or two at the end of the stream).
int i = byteBufferIndex;
int m = ByteBuffer.Length - byteBufferIndex;
while (m != 0 && StreamPosition != StreamLength) { // we check the StreamPosition to avoid calling Read after it returned 0 at the end of the stream (see ticket #23)
int c = Stream.Read(ByteBuffer, i, m);
if (c != 0) {
i += c;
m -= c;
StreamPosition += c;
} else {
Debug.Assert(!Stream.CanSeek || StreamPosition == StreamLength);
StreamLength = StreamPosition;
break;
}
}
int n = i - byteBufferIndex;
ByteBufferIndex = byteBufferIndex;
ByteBufferCount = byteBufferIndex + n;
return n;
}
/// <summary>Reads up to the given maximum number of chars into the given buffer.
/// If more than the maximum number of chars have to be read from the stream in order to
/// fill the buffer (due to the way the Decoder API works), the overhang chars are
/// returned through the output parameter.
/// Returns a pointer to one char after the last char read.</summary>
private char* ReadCharsFromStream(char* buffer, int maxCount, out string overhangChars) {
Debug.Assert(maxCount >= 0);
fixed (byte* byteBuffer = ByteBuffer) {
overhangChars = null;
try {
while (maxCount >= MaxCharCountForOneByte) {// if maxCount < MaxCharCountForOneByte, Convert could throw
int nBytesInByteBuffer = FillByteBuffer();
bool flush = nBytesInByteBuffer == 0;
int bytesUsed, charsUsed; bool completed = false;
Decoder.Convert(byteBuffer + ByteBufferIndex, nBytesInByteBuffer,
buffer, maxCount, flush,
out bytesUsed, out charsUsed, out completed);
ByteBufferIndex += bytesUsed; // GetChars consumed bytesUsed bytes from the byte buffer
buffer += charsUsed;
maxCount -= charsUsed;
if (flush && completed) return buffer;
}
if (maxCount == 0) return buffer;
char* cs = stackalloc char[MaxCharCountForOneByte];
for (;;) {
int nBytesInByteBuffer = FillByteBuffer();
bool flush = nBytesInByteBuffer == 0;
int bytesUsed, charsUsed; bool completed;
Decoder.Convert(byteBuffer + ByteBufferIndex, nBytesInByteBuffer,
cs, MaxCharCountForOneByte, flush,
out bytesUsed, out charsUsed, out completed);
ByteBufferIndex += bytesUsed;
if (charsUsed > 0) {
int i = 0;
do {
*buffer = cs[i];
++buffer; ++i;
if (--maxCount == 0) {
if (i < charsUsed) overhangChars = new string(cs, i, charsUsed - i);
return buffer;
}
} while (i < charsUsed);
}
if (flush && completed) return buffer;
}
} catch (DecoderFallbackException e) {
e.Data.Add("Stream.Position", ByteIndex + e.Index);
throw;
}
}
}
/// <summary> Reads a block of chars (which must be different from the current block)
/// into the BufferString. If the current CharStream block is block - 1, this method
/// seeks the CharStream to the first char after the overlap of the two blocks.
/// Otherwise it seeks the CharStream to the first char in the block. It returns the
/// CharStream.Ptr value at the new position (which can be null).</summary>
internal char* ReadBlock(int block) {
int prevBlock = CharStream.Block;
if (block == prevBlock) throw new InvalidOperationException();
if (!DecoderIsSerializable && block > 0) {
if (prevBlock > block)
throw new NotSupportedException("The CharStream does not support seeking backwards over ranges longer than the block overlap because the Encoding's Decoder is not serializable. The decoder has the type: " + Decoder.GetType().FullName);
while (prevBlock + 1 < block) ReadBlock(++prevBlock);
}
BlockInfo bi = Blocks[block]; // will throw if block is out of range
int blockSizeMinusOverlap = BlockSize - BlockOverlap;
long charIndex = Math.BigMul(block, blockSizeMinusOverlap);
char* bufferBegin = CharStream.BufferBegin;
char* begin, buffer;
int nCharsToRead;
// fill [0 ... BlockOverlap-1] if block > 0
if (prevBlock == block - 1) {
Buffer.Copy((byte*)bufferBegin, (byte*)(bufferBegin + blockSizeMinusOverlap),
BlockOverlap*sizeof(char));
Debug.Assert(bufferBegin[BlockOverlap - 1] == bi.LastCharInOverlap);
begin = buffer = bufferBegin + BlockOverlap;
} else if (prevBlock >= 0) {
Stream.Seek(bi.ByteIndex, SeekOrigin.Begin); // will throw if Stream can't seek
// now that there was no exception, we can change the state...
StreamPosition = bi.ByteIndex;
ClearAndRefillByteBuffer(bi.ByteBufferIndex);
if (block != 0)
Decoder = (Decoder)bi.DecoderImageAtBlockBegin.CreateClone();
else
Decoder.Reset();
if (prevBlock == block + 1) {
// move the overlap into [BlockSize - BlockOverlap, BlockSize - 1] before it gets overwritten
Buffer.Copy((byte*)(bufferBegin + blockSizeMinusOverlap), (byte*)bufferBegin,
BlockOverlap*sizeof(char));
}
begin = buffer = bufferBegin;
if (block > 0) {
nCharsToRead = BlockOverlap;
if (bi.OverhangCharsAtBlockBegin != null) {
nCharsToRead -= bi.OverhangCharsAtBlockBegin.Length;
for (int i = 0; i < bi.OverhangCharsAtBlockBegin.Length; ++i)
*(buffer++) = bi.OverhangCharsAtBlockBegin[i];
}
string overhangCharsAfterOverlap;
buffer = ReadCharsFromStream(buffer, nCharsToRead, out overhangCharsAfterOverlap);
if ( buffer != bufferBegin + BlockOverlap
|| ByteIndex != bi.ByteIndex + bi.NumberOfBytesInOverlap
|| *(buffer - 1) != bi.LastCharInOverlap
|| overhangCharsAfterOverlap != bi.OverhangCharsAfterOverlap)
throw new IOException("CharStream: stream integrity error");
}
} else { // ReadBlock was called from the constructor
if (block != 0) throw new InvalidOperationException();
begin = buffer = bufferBegin;
}
// fill [0 ... BlockSize-BlockOverlap-1] if block == 0
// and [BlockOverlap ... BlockSize-BlockOverlap-1] otherwise
if (block == 0) {
nCharsToRead = blockSizeMinusOverlap;
} else {
nCharsToRead = blockSizeMinusOverlap - BlockOverlap;
if (bi.OverhangCharsAfterOverlap != null) {
nCharsToRead -= bi.OverhangCharsAfterOverlap.Length;
for (int i = 0; i < bi.OverhangCharsAfterOverlap.Length; ++i)
*(buffer++) = bi.OverhangCharsAfterOverlap[i];
}
}
string overhangCharsAtNextBlockBegin;
buffer = ReadCharsFromStream(buffer, nCharsToRead, out overhangCharsAtNextBlockBegin);
long byteIndexAtNextBlockBegin = ByteIndex;
int byteBufferIndexAtNextBlockBegin = ByteBufferIndex;
// fill [BlockSize-BlockOverlap ... BlockSize-1]
if (block == Blocks.Count - 1) { // next block hasn't yet been read
Cloner cloner = null;
CloneImage decoderImageAtNextBlockBegin = null;
if (DecoderIsSerializable) {
cloner = Cloner.Create(Decoder.GetType());
decoderImageAtNextBlockBegin = cloner.CaptureImage(Decoder);
}
nCharsToRead = BlockOverlap;
if (overhangCharsAtNextBlockBegin != null) {
nCharsToRead -= overhangCharsAtNextBlockBegin.Length;
for (int i = 0; i < overhangCharsAtNextBlockBegin.Length; ++i)
*(buffer++) = overhangCharsAtNextBlockBegin[i];
}
string overhangCharsAfterOverlapWithNextBlock;
buffer = ReadCharsFromStream(buffer, nCharsToRead, out overhangCharsAfterOverlapWithNextBlock);
if (LastBlock == Int32.MaxValue) { // last block hasn't yet been detected
if (buffer == bufferBegin + BlockSize) {
var decoderImageAfterOverlapWithNextBlock =
!DecoderIsSerializable ? null : cloner.CaptureImage(Decoder);
int nBytesInOverlapWithNextBlock = (int)(ByteIndex - byteIndexAtNextBlockBegin);
Blocks.Add(new BlockInfo(byteIndexAtNextBlockBegin, byteBufferIndexAtNextBlockBegin,
nBytesInOverlapWithNextBlock, *(buffer - 1),
overhangCharsAtNextBlockBegin, decoderImageAtNextBlockBegin,
overhangCharsAfterOverlapWithNextBlock, decoderImageAfterOverlapWithNextBlock));
} else { // we reached the end of the stream
LastBlock = block;
IndexOfLastCharPlus1 = CharStream.IndexOfFirstChar + charIndex + (buffer - bufferBegin);
}
} else if (IndexOfLastCharPlus1 != CharStream.IndexOfFirstChar + charIndex + (buffer - bufferBegin)) {
throw new IOException("CharStream: stream integrity error");
}
} else {
BlockInfo nbi = Blocks[block + 1];
if (buffer != bufferBegin + blockSizeMinusOverlap
|| byteIndexAtNextBlockBegin != nbi.ByteIndex
|| byteBufferIndexAtNextBlockBegin != nbi.ByteBufferIndex
|| overhangCharsAtNextBlockBegin != nbi.OverhangCharsAtBlockBegin)
throw new IOException("CharStream: stream integrity error");
if (prevBlock != block + 1 || (block == 0 && !DecoderIsSerializable)) { // jumping back to block 0 is supported even if the decoder is not serializable
nCharsToRead = BlockOverlap;
if (overhangCharsAtNextBlockBegin != null) {
nCharsToRead -= overhangCharsAtNextBlockBegin.Length;
for (int i = 0; i < overhangCharsAtNextBlockBegin.Length; ++i)
*(buffer++) = overhangCharsAtNextBlockBegin[i];
}
string overhangCharsAfterOverlapWithNextBlock;
buffer = ReadCharsFromStream(buffer, nCharsToRead, out overhangCharsAfterOverlapWithNextBlock);
int nBytesInOverlapWithNextBlock = (int)(ByteIndex - byteIndexAtNextBlockBegin);
if (buffer != bufferBegin + BlockSize
|| nBytesInOverlapWithNextBlock != nbi.NumberOfBytesInOverlap
|| *(buffer - 1) != nbi.LastCharInOverlap
|| overhangCharsAfterOverlapWithNextBlock != nbi.OverhangCharsAfterOverlap)
throw new IOException("CharStream: stream integrity error");
} else {
Debug.Assert(bufferBegin[BlockSize - 1] == nbi.LastCharInOverlap);
buffer += BlockOverlap; // we already copied the chars at the beginning of this function
int off = nbi.NumberOfBytesInOverlap - (ByteBufferCount - ByteBufferIndex);
if (off > 0) {
// we wouldn't have gotten here if the Stream didn't support seeking
Stream.Seek(off, SeekOrigin.Current);
StreamPosition += off;
ClearAndRefillByteBuffer(off%ByteBuffer.Length);
} else {
ByteBufferIndex += nbi.NumberOfBytesInOverlap;
}
Decoder = (Decoder)nbi.DecoderImageAfterOverlap.CreateClone();
}
}
CharStream.Block = block;
//CharStream.CharIndex = charIndex;
CharStream.IndexOfFirstCharInBlock = CharStream.IndexOfFirstChar + charIndex;
CharStream.BufferEnd = buffer;
if (begin != buffer) {
CharStream.Ptr = begin;
CharStream.PtrEnd = buffer;
CharStream.PtrBegin = CharStream.BufferBegin;
return begin;
} else {
CharStream.Ptr = null;
CharStream.PtrEnd = null;
CharStream.PtrBegin = null;
return null;
}
}
} // class MultiBlockData
/// <summary>Returns an iterator pointing to the given index in the stream,
/// or to the end of the stream if the indexed position lies beyond the last char in the stream.</summary>
/// <exception cref="ArgumentOutOfRangeException">The index is negative or less than the BeginIndex.</exception>
/// <exception cref="NotSupportedException">Accessing the char with the given index requires seeking in the underlying byte stream, but the byte stream does not support seeking or the Encoding's Decoder is not serializable.</exception>
/// <exception cref="IOException">An I/O error occured.</exception>
/// <exception cref="ArgumentException">The input stream contains invalid bytes and the encoding was constructed with the throwOnInvalidBytes option.</exception>
/// <exception cref="DecoderFallbackException">The input stream contains invalid bytes for which the decoder fallback threw this exception.</exception>
/// <exception cref="OutOfMemoryException">Can not allocate enough memory for the internal data structure.</exception>
/// <exception cref="ObjectDisposedException">Method is called after the stream was disposed.</exception>
public void Seek(long index) {
++StateTag;
// The following comparison is safe in case of an overflow since
// 0 <= IndexOfFirstCharInBlock < 2^60 + 2^31 * 2^31 and BufferEnd - BufferBegin < 2^31,
// where 2^31 is an upper bound for both the number of blocks and the number of chars in a block.
long off = unchecked(index - IndexOfFirstCharInBlock);
if (0 <= off && off < Buffer.PositiveDistance(BufferBegin, BufferEnd)) {
Ptr = BufferBegin + (uint)off;
PtrBegin = BufferBegin;
PtrEnd = BufferEnd;
return;
}
if (index < IndexOfFirstChar) {
--StateTag;
throw (new ArgumentOutOfRangeException("index", "The index is negative or less than the IndexOfFirstChar."));
}
if (BlockData == null || index >= BlockData.IndexOfLastCharPlus1) {
Ptr = null;
PtrBegin = null;
PtrEnd = null;
return;
}
// we never get here for streams with only one block
index -= IndexOfFirstChar;
int blockSizeMinusOverlap = BlockData.BlockSize - BlockData.BlockOverlap;
long idx_;
long block_ = Math.DivRem(index, blockSizeMinusOverlap, out idx_);
int block = block_ > Int32.MaxValue ? Int32.MaxValue : (int)block_;
int idx = (int)idx_;
Seek(block, idx);
}
private void Seek(int block, int indexInBlock) {
Debug.Assert(block >= 0 && indexInBlock >= 0 && BlockData != null);
if (block > Block) {
if (indexInBlock < BlockData.BlockOverlap) {
--block;
indexInBlock += BlockData.BlockSize - BlockData.BlockOverlap;
}
} else if (block < Block) {
int blockSizeMinusOverlap = BlockData.BlockSize - BlockData.BlockOverlap;
if (indexInBlock >= blockSizeMinusOverlap) {
++block;
indexInBlock -= blockSizeMinusOverlap;