forked from apache/lucenenet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFST.cs
More file actions
2422 lines (2147 loc) · 91.6 KB
/
Copy pathFST.cs
File metadata and controls
2422 lines (2147 loc) · 91.6 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
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
using J2N.Collections;
using Lucene.Net.Diagnostics;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Util.Fst
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using ByteArrayDataOutput = Lucene.Net.Store.ByteArrayDataOutput;
using CodecUtil = Lucene.Net.Codecs.CodecUtil;
using DataInput = Lucene.Net.Store.DataInput;
using DataOutput = Lucene.Net.Store.DataOutput;
using GrowableWriter = Lucene.Net.Util.Packed.GrowableWriter;
using InputStreamDataInput = Lucene.Net.Store.InputStreamDataInput;
using OutputStreamDataOutput = Lucene.Net.Store.OutputStreamDataOutput;
using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s;
using RAMOutputStream = Lucene.Net.Store.RAMOutputStream;
// TODO: break this into WritableFST and ReadOnlyFST.. then
// we can have subclasses of ReadOnlyFST to handle the
// different byte[] level encodings (packed or
// not)... and things like nodeCount, arcCount are read only
// TODO: if FST is pure prefix trie we can do a more compact
// job, ie, once we are at a 'suffix only', just store the
// completion labels as a string not as a series of arcs.
// NOTE: while the FST is able to represent a non-final
// dead-end state (NON_FINAL_END_NODE=0), the layers above
// (FSTEnum, Util) have problems with this!!
/// <summary>
/// Represents an finite state machine (FST), using a
/// compact <see cref="T:byte[]"/> format.
/// <para/> The format is similar to what's used by Morfologik
/// (http://sourceforge.net/projects/morfologik).
///
/// <para/> See the <a href="https://lucene.apache.org/core/4_8_0/core/org/apache/lucene/util/fst/package-summary.html">
/// FST package documentation</a> for some simple examples.
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class FST<T>
where T : class // LUCENENET specific - added class constraint, since we compare reference equality
{
/*/// <summary>
/// Specifies allowed range of each int input label for
/// this FST.
/// </summary>
public enum INPUT_TYPE
{
BYTE1,
BYTE2,
BYTE4
}*/
private readonly FST.INPUT_TYPE inputType;
/*internal static readonly int BIT_FINAL_ARC = 1 << 0;
internal static readonly int BIT_LAST_ARC = 1 << 1;
internal static readonly int BIT_TARGET_NEXT = 1 << 2;
// TODO: we can free up a bit if we can nuke this:
internal static readonly int BIT_STOP_NODE = 1 << 3;
internal static readonly int BIT_ARC_HAS_OUTPUT = 1 << 4;
internal static readonly int BIT_ARC_HAS_FINAL_OUTPUT = 1 << 5;
// Arcs are stored as fixed-size (per entry) array, so
// that we can find an arc using binary search. We do
// this when number of arcs is > NUM_ARCS_ARRAY:
// If set, the target node is delta coded vs current
// position:
private static readonly int BIT_TARGET_DELTA = 1 << 6;
// We use this as a marker (because this one flag is
// illegal by itself ...):
private static readonly sbyte ARCS_AS_FIXED_ARRAY = (sbyte)BIT_ARC_HAS_FINAL_OUTPUT;
/// <seealso cref= #shouldExpand(UnCompiledNode) </seealso>
internal const int FIXED_ARRAY_SHALLOW_DISTANCE = 3; // 0 => only root node.
/// <seealso cref= #shouldExpand(UnCompiledNode) </seealso>
internal const int FIXED_ARRAY_NUM_ARCS_SHALLOW = 5;
/// <seealso cref= #shouldExpand(UnCompiledNode) </seealso>
internal const int FIXED_ARRAY_NUM_ARCS_DEEP = 10;*/
private int[] bytesPerArc = Array.Empty<int>();
/*// Increment version to change it
private const string FILE_FORMAT_NAME = "FST";
private const int VERSION_START = 0;
/// <summary>
/// Changed numBytesPerArc for array'd case from byte to int. </summary>
private const int VERSION_INT_NUM_BYTES_PER_ARC = 1;
/// <summary>
/// Write BYTE2 labels as 2-byte short, not vInt. </summary>
private const int VERSION_SHORT_BYTE2_LABELS = 2;
/// <summary>
/// Added optional packed format. </summary>
private const int VERSION_PACKED = 3;
/// <summary>
/// Changed from int to vInt for encoding arc targets.
/// Also changed maxBytesPerArc from int to vInt in the array case.
/// </summary>
private const int VERSION_VINT_TARGET = 4;
private const int VERSION_CURRENT = VERSION_VINT_TARGET;
// Never serialized; just used to represent the virtual
// final node w/ no arcs:
private const long FINAL_END_NODE = -1;
// Never serialized; just used to represent the virtual
// non-final node w/ no arcs:
private const long NON_FINAL_END_NODE = 0;*/
// if non-null, this FST accepts the empty string and
// produces this output
internal T emptyOutput;
internal readonly BytesStore bytes;
private long startNode = -1;
public Outputs<T> Outputs { get; private set; }
// Used for the BIT_TARGET_NEXT optimization (whereby
// instead of storing the address of the target node for
// a given arc, we mark a single bit noting that the next
// node in the byte[] is the target node):
private long lastFrozenNode;
private readonly T NO_OUTPUT;
// LUCENENET NOTE: changed accessibility of the following 3 fields
// because we already have public properties that can read them.
// This class is sealed, so it is unclear what the benefit of setting
// them from outside is (if any).
internal long nodeCount;
private long arcCount;
private long arcWithOutputCount;
private readonly bool packed;
private PackedInt32s.Reader nodeRefToAddress;
///// <summary>
///// If arc has this label then that arc is final/accepted </summary>
//public static readonly int END_LABEL = -1;
private readonly bool allowArrayArcs;
private FST.Arc<T>[] cachedRootArcs;
private FST.Arc<T>[] assertingCachedRootArcs; // only set wit assert
// LUCENENET NOTE: Arc<T> moved into FST class
internal static bool Flag(int flags, int bit)
{
return (flags & bit) != 0;
}
private GrowableWriter nodeAddress;
// TODO: we could be smarter here, and prune periodically
// as we go; high in-count nodes will "usually" become
// clear early on:
private GrowableWriter inCounts;
private readonly int version;
// make a new empty FST, for building; Builder invokes
// this ctor
internal FST(FST.INPUT_TYPE inputType, Outputs<T> outputs, bool willPackFST, float acceptableOverheadRatio, bool allowArrayArcs, int bytesPageBits)
{
this.inputType = inputType;
this.Outputs = outputs;
this.allowArrayArcs = allowArrayArcs;
version = FST.VERSION_CURRENT;
bytes = new BytesStore(bytesPageBits);
// pad: ensure no node gets address 0 which is reserved to mean
// the stop state w/ no arcs
bytes.WriteByte(0);
NO_OUTPUT = outputs.NoOutput;
if (willPackFST)
{
nodeAddress = new GrowableWriter(15, 8, acceptableOverheadRatio);
inCounts = new GrowableWriter(1, 8, acceptableOverheadRatio);
}
else
{
nodeAddress = null;
inCounts = null;
}
emptyOutput = default;
packed = false;
nodeRefToAddress = null;
}
/// <summary>
/// Load a previously saved FST. </summary>
public FST(DataInput @in, Outputs<T> outputs)
: this(@in, outputs, FST.DEFAULT_MAX_BLOCK_BITS)
{
}
/// <summary>
/// Load a previously saved FST; <paramref name="maxBlockBits"/> allows you to
/// control the size of the <see cref="T:byte[]"/> pages used to hold the FST bytes.
/// </summary>
public FST(DataInput @in, Outputs<T> outputs, int maxBlockBits)
{
this.Outputs = outputs;
if (maxBlockBits < 1 || maxBlockBits > 30)
{
throw new ArgumentOutOfRangeException(nameof(maxBlockBits), "maxBlockBits should be 1 .. 30; got " + maxBlockBits); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
// NOTE: only reads most recent format; we don't have
// back-compat promise for FSTs (they are experimental):
version = CodecUtil.CheckHeader(@in, FST.FILE_FORMAT_NAME, FST.VERSION_PACKED, FST.VERSION_VINT32_TARGET);
packed = @in.ReadByte() == 1;
if (@in.ReadByte() == 1)
{
// accepts empty string
// 1 KB blocks:
BytesStore emptyBytes = new BytesStore(10);
int numBytes = @in.ReadVInt32();
emptyBytes.CopyBytes(@in, numBytes);
// De-serialize empty-string output:
FST.BytesReader reader;
if (packed)
{
reader = emptyBytes.GetForwardReader();
}
else
{
reader = emptyBytes.GetReverseReader();
// NoOutputs uses 0 bytes when writing its output,
// so we have to check here else BytesStore gets
// angry:
if (numBytes > 0)
{
reader.Position = numBytes - 1;
}
}
emptyOutput = outputs.ReadFinalOutput(reader);
}
else
{
emptyOutput = default;
}
var t = @in.ReadByte();
inputType = t switch
{
0 => FST.INPUT_TYPE.BYTE1,
1 => FST.INPUT_TYPE.BYTE2,
2 => FST.INPUT_TYPE.BYTE4,
_ => throw IllegalStateException.Create("invalid input type " + t),
};
if (packed)
{
nodeRefToAddress = PackedInt32s.GetReader(@in);
}
else
{
nodeRefToAddress = null;
}
startNode = @in.ReadVInt64();
nodeCount = @in.ReadVInt64();
arcCount = @in.ReadVInt64();
arcWithOutputCount = @in.ReadVInt64();
long numBytes_ = @in.ReadVInt64();
bytes = new BytesStore(@in, numBytes_, 1 << maxBlockBits);
NO_OUTPUT = outputs.NoOutput;
CacheRootArcs();
// NOTE: bogus because this is only used during
// building; we need to break out mutable FST from
// immutable
allowArrayArcs = false;
/*
if (bytes.length == 665) {
Writer w = new OutputStreamWriter(new FileOutputStream("out.dot"), StandardCharsets.UTF_8);
Util.toDot(this, w, false, false);
w.Dispose();
System.out.println("Wrote FST to out.dot");
}
*/
}
public FST.INPUT_TYPE InputType => inputType;
/// <summary>
/// Returns bytes used to represent the FST </summary>
public long GetSizeInBytes()
{
long size = bytes.Position;
if (packed)
{
size += nodeRefToAddress.RamBytesUsed();
}
else if (nodeAddress != null)
{
size += nodeAddress.RamBytesUsed();
size += inCounts.RamBytesUsed();
}
return size;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void Finish(long newStartNode)
{
if (startNode != -1)
{
throw IllegalStateException.Create("already finished");
}
if (newStartNode == FST.FINAL_END_NODE && !EqualityComparer<T>.Default.Equals(emptyOutput, default))
{
newStartNode = 0;
}
startNode = newStartNode;
bytes.Finish();
CacheRootArcs();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private long GetNodeAddress(long node)
{
if (nodeAddress != null)
{
// Deref
return nodeAddress.Get((int)node);
}
else
{
// Straight
return node;
}
}
// Caches first 128 labels
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CacheRootArcs()
{
cachedRootArcs = (FST.Arc<T>[])new FST.Arc<T>[0x80];
ReadRootArcs(cachedRootArcs);
if (Debugging.AssertsEnabled)
{
Debugging.Assert(SetAssertingRootArcs(cachedRootArcs));
Debugging.Assert(AssertRootArcs());
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadRootArcs(FST.Arc<T>[] arcs)
{
FST.Arc<T> arc = new FST.Arc<T>();
GetFirstArc(arc);
FST.BytesReader @in = GetBytesReader();
if (TargetHasArcs(arc))
{
ReadFirstRealTargetArc(arc.Target, arc, @in);
while (true)
{
if (Debugging.AssertsEnabled) Debugging.Assert(arc.Label != FST.END_LABEL);
if (arc.Label < cachedRootArcs.Length)
{
arcs[arc.Label] = (new FST.Arc<T>()).CopyFrom(arc);
}
else
{
break;
}
if (arc.IsLast)
{
break;
}
ReadNextRealArc(arc, @in);
}
}
}
private bool SetAssertingRootArcs(FST.Arc<T>[] arcs) // Only called from assert
{
assertingCachedRootArcs = (FST.Arc<T>[])new FST.Arc<T>[arcs.Length];
ReadRootArcs(assertingCachedRootArcs);
return true;
}
private bool AssertRootArcs()
{
Debugging.Assert(cachedRootArcs != null);
Debugging.Assert(assertingCachedRootArcs != null);
for (int i = 0; i < cachedRootArcs.Length; i++)
{
FST.Arc<T> root = cachedRootArcs[i];
FST.Arc<T> asserting = assertingCachedRootArcs[i];
if (root != null)
{
Debugging.Assert(root.ArcIdx == asserting.ArcIdx);
Debugging.Assert(root.BytesPerArc == asserting.BytesPerArc);
Debugging.Assert(root.Flags == asserting.Flags);
Debugging.Assert(root.Label == asserting.Label);
Debugging.Assert(root.NextArc == asserting.NextArc);
// LUCENENET NOTE: In .NET, IEnumerable will not equal another identical IEnumerable
// because it checks for reference equality, not that the list contents
// are the same. StructuralEqualityComparer.Default.Equals() will make that check.
Debugging.Assert(typeof(T).IsValueType
? JCG.EqualityComparer<T>.Default.Equals(root.NextFinalOutput, asserting.NextFinalOutput)
: StructuralEqualityComparer.Default.Equals(root.NextFinalOutput, asserting.NextFinalOutput));
Debugging.Assert(root.Node == asserting.Node);
Debugging.Assert(root.NumArcs == asserting.NumArcs);
Debugging.Assert(typeof(T).IsValueType
? JCG.EqualityComparer<T>.Default.Equals(root.Output, asserting.Output)
: StructuralEqualityComparer.Default.Equals(root.Output, asserting.Output));
Debugging.Assert(root.PosArcsStart == asserting.PosArcsStart);
Debugging.Assert(root.Target == asserting.Target);
}
else
{
Debugging.Assert(root is null && asserting is null);
}
}
return true;
}
public T EmptyOutput
{
get => emptyOutput;
set
{
if (emptyOutput != null)
{
emptyOutput = Outputs.Merge(emptyOutput, value);
}
else
{
emptyOutput = value;
}
}
}
public void Save(DataOutput @out)
{
if (startNode == -1)
{
throw IllegalStateException.Create("call finish first");
}
if (nodeAddress != null)
{
throw IllegalStateException.Create("cannot save an FST pre-packed FST; it must first be packed");
}
if (packed && nodeRefToAddress is not PackedInt32s.Mutable)
{
throw IllegalStateException.Create("cannot save a FST which has been loaded from disk ");
}
CodecUtil.WriteHeader(@out, FST.FILE_FORMAT_NAME, FST.VERSION_CURRENT);
if (packed)
{
@out.WriteByte(1);
}
else
{
@out.WriteByte(0);
}
// TODO: really we should encode this as an arc, arriving
// to the root node, instead of special casing here:
if (!EqualityComparer<T>.Default.Equals(emptyOutput, default))
{
// Accepts empty string
@out.WriteByte(1);
// Serialize empty-string output:
using var ros = new RAMOutputStream();
Outputs.WriteFinalOutput(emptyOutput, ros);
var emptyOutputBytes = new byte[(int)ros.Position]; // LUCENENET specific: Renamed from getFilePointer() to match FileStream
ros.WriteTo(emptyOutputBytes, 0);
if (!packed)
{
// reverse
int stopAt = emptyOutputBytes.Length / 2;
int upto = 0;
while (upto < stopAt)
{
var b = emptyOutputBytes[upto];
emptyOutputBytes[upto] = emptyOutputBytes[emptyOutputBytes.Length - upto - 1];
emptyOutputBytes[emptyOutputBytes.Length - upto - 1] = b;
upto++;
}
}
@out.WriteVInt32(emptyOutputBytes.Length);
@out.WriteBytes(emptyOutputBytes, 0, emptyOutputBytes.Length);
}
else
{
@out.WriteByte(0);
}
sbyte t;
if (inputType == FST.INPUT_TYPE.BYTE1)
{
t = 0;
}
else if (inputType == FST.INPUT_TYPE.BYTE2)
{
t = 1;
}
else
{
t = 2;
}
@out.WriteByte((byte)t);
if (packed)
{
((PackedInt32s.Mutable)nodeRefToAddress).Save(@out);
}
@out.WriteVInt64(startNode);
@out.WriteVInt64(nodeCount);
@out.WriteVInt64(arcCount);
@out.WriteVInt64(arcWithOutputCount);
long numBytes = bytes.Position;
@out.WriteVInt64(numBytes);
bytes.WriteTo(@out);
}
/// <summary>
/// Writes an automaton to a file.
/// </summary>
/// <param name="fileName">The file name. The path is not normalized by this method.</param>
/// <remarks>
/// LUCENENET: This overload takes a string file name to avoid allocating a <see cref="FileInfo"/> object.
/// </remarks>
public void Save(string fileName)
{
bool success = false;
var bs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
try
{
Save(new OutputStreamDataOutput(bs));
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(bs);
}
else
{
IOUtils.DisposeWhileHandlingException(bs);
}
}
}
/// <summary>
/// Writes an automaton to a file.
/// </summary>
/// <seealso cref="Save(string)"/>
public void Save(FileInfo file)
=> Save(file.FullName);
// LUCENENET NOTE: static Read<T>() was moved into the FST class
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteLabel(DataOutput @out, int v)
{
if (Debugging.AssertsEnabled) Debugging.Assert(v >= 0, "v={0}", v);
if (inputType == FST.INPUT_TYPE.BYTE1)
{
if (Debugging.AssertsEnabled) Debugging.Assert(v <= 255, "v={0}", v);
@out.WriteByte((byte)v);
}
else if (inputType == FST.INPUT_TYPE.BYTE2)
{
if (Debugging.AssertsEnabled) Debugging.Assert(v <= 65535, "v={0}", v);
@out.WriteInt16((short)v);
}
else
{
@out.WriteVInt32(v);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal int ReadLabel(DataInput @in)
{
int v;
if (inputType == FST.INPUT_TYPE.BYTE1)
{
// Unsigned byte:
v = @in.ReadByte() & 0xFF;
}
else if (inputType == FST.INPUT_TYPE.BYTE2)
{
// Unsigned short:
v = @in.ReadInt16() & 0xFFFF;
}
else
{
v = @in.ReadVInt32();
}
return v;
}
/// <summary>
/// returns <c>true</c> if the node at this address has any
/// outgoing arcs
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TargetHasArcs(FST.Arc<T> arc)
{
return arc.Target > 0;
}
// serializes new node by appending its bytes to the end
// of the current byte[]
internal long AddNode(Builder.UnCompiledNode<T> nodeIn)
{
//System.out.println("FST.addNode pos=" + bytes.getPosition() + " numArcs=" + nodeIn.numArcs);
if (nodeIn.NumArcs == 0)
{
if (nodeIn.IsFinal)
{
return FST.FINAL_END_NODE;
}
else
{
return FST.NON_FINAL_END_NODE;
}
}
long startAddress = bytes.Position;
//System.out.println(" startAddr=" + startAddress);
bool doFixedArray = ShouldExpand(nodeIn);
if (doFixedArray)
{
//System.out.println(" fixedArray");
if (bytesPerArc.Length < nodeIn.NumArcs)
{
bytesPerArc = new int[ArrayUtil.Oversize(nodeIn.NumArcs, 1)];
}
}
arcCount += nodeIn.NumArcs;
int lastArc = nodeIn.NumArcs - 1;
long lastArcStart = bytes.Position;
int maxBytesPerArc = 0;
for (int arcIdx = 0; arcIdx < nodeIn.NumArcs; arcIdx++)
{
Builder.Arc<T> arc = nodeIn.Arcs[arcIdx];
var target = (Builder.CompiledNode)arc.Target;
int flags = 0;
//System.out.println(" arc " + arcIdx + " label=" + arc.Label + " -> target=" + target.Node);
if (arcIdx == lastArc)
{
flags += FST.BIT_LAST_ARC;
}
if (lastFrozenNode == target.Node && !doFixedArray)
{
// TODO: for better perf (but more RAM used) we
// could avoid this except when arc is "near" the
// last arc:
flags += FST.BIT_TARGET_NEXT;
}
if (arc.IsFinal)
{
flags += FST.BIT_FINAL_ARC;
if (arc.NextFinalOutput != NO_OUTPUT)
{
flags += FST.BIT_ARC_HAS_FINAL_OUTPUT;
}
}
else if (Debugging.AssertsEnabled)
{
Debugging.Assert(arc.NextFinalOutput == NO_OUTPUT);
}
bool targetHasArcs = target.Node > 0;
if (!targetHasArcs)
{
flags += FST.BIT_STOP_NODE;
}
else if (inCounts != null)
{
inCounts.Set((int)target.Node, inCounts.Get((int)target.Node) + 1);
}
if (arc.Output != NO_OUTPUT)
{
flags += FST.BIT_ARC_HAS_OUTPUT;
}
bytes.WriteByte((byte)flags);
WriteLabel(bytes, arc.Label);
// System.out.println(" write arc: label=" + (char) arc.Label + " flags=" + flags + " target=" + target.Node + " pos=" + bytes.getPosition() + " output=" + outputs.outputToString(arc.Output));
if (arc.Output != NO_OUTPUT)
{
Outputs.Write(arc.Output, bytes);
//System.out.println(" write output");
arcWithOutputCount++;
}
if (arc.NextFinalOutput != NO_OUTPUT)
{
//System.out.println(" write final output");
Outputs.WriteFinalOutput(arc.NextFinalOutput, bytes);
}
if (targetHasArcs && (flags & FST.BIT_TARGET_NEXT) == 0)
{
if (Debugging.AssertsEnabled) Debugging.Assert(target.Node > 0);
//System.out.println(" write target");
bytes.WriteVInt64(target.Node);
}
// just write the arcs "like normal" on first pass,
// but record how many bytes each one took, and max
// byte size:
if (doFixedArray)
{
bytesPerArc[arcIdx] = (int)(bytes.Position - lastArcStart);
lastArcStart = bytes.Position;
maxBytesPerArc = Math.Max(maxBytesPerArc, bytesPerArc[arcIdx]);
//System.out.println(" bytes=" + bytesPerArc[arcIdx]);
}
}
// TODO: try to avoid wasteful cases: disable doFixedArray in that case
/*
*
* LUCENE-4682: what is a fair heuristic here?
* It could involve some of these:
* 1. how "busy" the node is: nodeIn.inputCount relative to frontier[0].inputCount?
* 2. how much binSearch saves over scan: nodeIn.numArcs
* 3. waste: numBytes vs numBytesExpanded
*
* the one below just looks at #3
if (doFixedArray) {
// rough heuristic: make this 1.25 "waste factor" a parameter to the phd ctor????
int numBytes = lastArcStart - startAddress;
int numBytesExpanded = maxBytesPerArc * nodeIn.numArcs;
if (numBytesExpanded > numBytes*1.25) {
doFixedArray = false;
}
}
*/
if (doFixedArray)
{
const int MAX_HEADER_SIZE = 11; // header(byte) + numArcs(vint) + numBytes(vint)
if (Debugging.AssertsEnabled) Debugging.Assert(maxBytesPerArc > 0);
// 2nd pass just "expands" all arcs to take up a fixed
// byte size
//System.out.println("write int @pos=" + (fixedArrayStart-4) + " numArcs=" + nodeIn.numArcs);
// create the header
// TODO: clean this up: or just rewind+reuse and deal with it
byte[] header = new byte[MAX_HEADER_SIZE];
var bad = new ByteArrayDataOutput(header);
// write a "false" first arc:
bad.WriteByte((byte)FST.ARCS_AS_FIXED_ARRAY);
bad.WriteVInt32(nodeIn.NumArcs);
bad.WriteVInt32(maxBytesPerArc);
int headerLen = bad.Position;
long fixedArrayStart = startAddress + headerLen;
// expand the arcs in place, backwards
long srcPos = bytes.Position;
long destPos = fixedArrayStart + nodeIn.NumArcs * maxBytesPerArc;
if (Debugging.AssertsEnabled) Debugging.Assert(destPos >= srcPos);
if (destPos > srcPos)
{
bytes.SkipBytes((int)(destPos - srcPos));
for (int arcIdx = nodeIn.NumArcs - 1; arcIdx >= 0; arcIdx--)
{
destPos -= maxBytesPerArc;
srcPos -= bytesPerArc[arcIdx];
//System.out.println(" repack arcIdx=" + arcIdx + " srcPos=" + srcPos + " destPos=" + destPos);
if (srcPos != destPos)
{
//System.out.println(" copy len=" + bytesPerArc[arcIdx]);
if (Debugging.AssertsEnabled) Debugging.Assert(destPos > srcPos, "destPos={0} srcPos={1} arcIdx={2} maxBytesPerArc={3} bytesPerArc[arcIdx]={4} nodeIn.numArcs={5}", destPos, srcPos, arcIdx, maxBytesPerArc, bytesPerArc[arcIdx], nodeIn.NumArcs);
bytes.CopyBytes(srcPos, destPos, bytesPerArc[arcIdx]);
}
}
}
// now write the header
bytes.WriteBytes(startAddress, header, 0, headerLen);
}
long thisNodeAddress = bytes.Position - 1;
bytes.Reverse(startAddress, thisNodeAddress);
// PackedInts uses int as the index, so we cannot handle
// > 2.1B nodes when packing:
if (nodeAddress != null && nodeCount == int.MaxValue)
{
throw IllegalStateException.Create("cannot create a packed FST with more than 2.1 billion nodes");
}
nodeCount++;
long node;
if (nodeAddress != null)
{
// Nodes are addressed by 1+ord:
if ((int)nodeCount == nodeAddress.Count)
{
nodeAddress = nodeAddress.Resize(ArrayUtil.Oversize(nodeAddress.Count + 1, nodeAddress.BitsPerValue));
inCounts = inCounts.Resize(ArrayUtil.Oversize(inCounts.Count + 1, inCounts.BitsPerValue));
}
nodeAddress.Set((int)nodeCount, thisNodeAddress);
// System.out.println(" write nodeAddress[" + nodeCount + "] = " + endAddress);
node = nodeCount;
}
else
{
node = thisNodeAddress;
}
lastFrozenNode = node;
//System.out.println(" ret node=" + node + " address=" + thisNodeAddress + " nodeAddress=" + nodeAddress);
return node;
}
/// <summary>
/// Fills virtual 'start' arc, ie, an empty incoming arc to
/// the FST's start node
/// </summary>
public FST.Arc<T> GetFirstArc(FST.Arc<T> arc)
{
if (null != emptyOutput) // LUCENENET: intentionally putting null on the left to avoid custom equality overrides
{
arc.Flags = FST.BIT_FINAL_ARC | FST.BIT_LAST_ARC;
arc.NextFinalOutput = emptyOutput;
if (emptyOutput != NO_OUTPUT)
{
arc.Flags |= FST.BIT_ARC_HAS_FINAL_OUTPUT;
}
}
else
{
arc.Flags = FST.BIT_LAST_ARC;
arc.NextFinalOutput = NO_OUTPUT;
}
arc.Output = NO_OUTPUT;
// If there are no nodes, ie, the FST only accepts the
// empty string, then startNode is 0
arc.Target = startNode;
return arc;
}
/// <summary>
/// Follows the <paramref name="follow"/> arc and reads the last
/// arc of its target; this changes the provided
/// <paramref name="arc"/> (2nd arg) in-place and returns it.
/// </summary>
/// <returns> Returns the second argument
/// (<paramref name="arc"/>). </returns>
public FST.Arc<T> ReadLastTargetArc(FST.Arc<T> follow, FST.Arc<T> arc, FST.BytesReader @in)
{
//System.out.println("readLast");
if (!TargetHasArcs(follow))
{
//System.out.println(" end node");
if (Debugging.AssertsEnabled) Debugging.Assert(follow.IsFinal);
arc.Label = FST.END_LABEL;
arc.Target = FST.FINAL_END_NODE;
arc.Output = follow.NextFinalOutput;
arc.Flags = (sbyte)FST.BIT_LAST_ARC;
return arc;
}
else
{
@in.Position = GetNodeAddress(follow.Target);
arc.Node = follow.Target;
var b = (sbyte)@in.ReadByte();
if (b == FST.ARCS_AS_FIXED_ARRAY)
{
// array: jump straight to end
arc.NumArcs = @in.ReadVInt32();
if (packed || version >= FST.VERSION_VINT32_TARGET)
{
arc.BytesPerArc = @in.ReadVInt32();
}
else
{
arc.BytesPerArc = @in.ReadInt32();
}
//System.out.println(" array numArcs=" + arc.numArcs + " bpa=" + arc.bytesPerArc);
arc.PosArcsStart = @in.Position;
arc.ArcIdx = arc.NumArcs - 2;
}
else
{
arc.Flags = b;
// non-array: linear scan
arc.BytesPerArc = 0;
//System.out.println(" scan");
while (!arc.IsLast)
{
// skip this arc:
ReadLabel(@in);
if (arc.Flag(FST.BIT_ARC_HAS_OUTPUT))
{
Outputs.Read(@in);
}
if (arc.Flag(FST.BIT_ARC_HAS_FINAL_OUTPUT))
{
Outputs.ReadFinalOutput(@in);
}
if (arc.Flag(FST.BIT_STOP_NODE))
{
// LUCENENET: intentionally empty to match Lucene
}
else if (arc.Flag(FST.BIT_TARGET_NEXT))
{
// LUCENENET: intentionally empty to match Lucene
}
else if (packed)
{
@in.ReadVInt64();
}
else
{
ReadUnpackedNodeTarget(@in);
}
arc.Flags = (sbyte)@in.ReadByte();
}
// Undo the byte flags we read:
@in.SkipBytes(-1);
arc.NextArc = @in.Position;
}
ReadNextRealArc(arc, @in);
if (Debugging.AssertsEnabled) Debugging.Assert(arc.IsLast);
return arc;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private long ReadUnpackedNodeTarget(FST.BytesReader @in)
{
long target;
if (version < FST.VERSION_VINT32_TARGET)
{
target = @in.ReadInt32();
}
else