forked from apache/lucenenet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPackedInts.cs
More file actions
1508 lines (1365 loc) · 67.4 KB
/
Copy pathPackedInts.cs
File metadata and controls
1508 lines (1365 loc) · 67.4 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.Numerics;
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
namespace Lucene.Net.Util.Packed
{
/*
* 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 CodecUtil = Lucene.Net.Codecs.CodecUtil;
using DataInput = Lucene.Net.Store.DataInput;
using DataOutput = Lucene.Net.Store.DataOutput;
using IndexInput = Lucene.Net.Store.IndexInput;
using NumericDocValues = Lucene.Net.Index.NumericDocValues;
/// <summary>
/// Simplistic compression for array of unsigned long values.
/// Each value is >= 0 and <= a specified maximum value. The
/// values are stored as packed ints, with each value
/// consuming a fixed number of bits.
/// <para/>
/// NOTE: This was PackedInts in Lucene.
/// <para/>
/// @lucene.internal
/// </summary>
public static class PackedInt32s // LUCENENET specific: CA1052 Static holder types should be Static or NotInheritable
{
/// <summary>
/// At most 700% memory overhead, always select a direct implementation.
/// </summary>
public const float FASTEST = 7f;
/// <summary>
/// At most 50% memory overhead, always select a reasonably fast implementation.
/// </summary>
public const float FAST = 0.5f;
/// <summary>
/// At most 20% memory overhead.
/// </summary>
public const float DEFAULT = 0.2f;
/// <summary>
/// No memory overhead at all, but the returned implementation may be slow.
/// </summary>
public const float COMPACT = 0f;
/// <summary>
/// Default amount of memory to use for bulk operations.
/// </summary>
public const int DEFAULT_BUFFER_SIZE = 1024; // 1K
public const string CODEC_NAME = "PackedInts";
public static readonly int VERSION_START = 0; // PackedInts were long-aligned
public static readonly int VERSION_BYTE_ALIGNED = 1;
public static readonly int VERSION_CURRENT = VERSION_BYTE_ALIGNED;
/// <summary>
/// Check the validity of a version number.
/// </summary>
public static void CheckVersion(int version)
{
if (version < VERSION_START)
{
throw new ArgumentOutOfRangeException(nameof(version), "Version is too old, should be at least " + VERSION_START + " (got " + version + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
else if (version > VERSION_CURRENT)
{
throw new ArgumentOutOfRangeException(nameof(version), "Version is too new, should be at most " + VERSION_CURRENT + " (got " + version + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
}
private sealed class PackedFormat : Format
{
public PackedFormat()
: base(0)
{
}
/// <summary>
/// Computes how many <see cref="byte"/> blocks are needed to store <paramref name="valueCount"/>
/// values of size <paramref name="bitsPerValue"/>.
/// </summary>
public override long ByteCount(int packedIntsVersion, int valueCount, int bitsPerValue)
{
if (packedIntsVersion < VERSION_BYTE_ALIGNED)
{
return 8L * (long)Math.Ceiling((double)valueCount * bitsPerValue / 64);
}
return (long)Math.Ceiling((double)valueCount * bitsPerValue / 8);
}
}
private sealed class PackedSingleBlockFormat : Format
{
public PackedSingleBlockFormat()
: base(1)
{
}
/// <summary>
/// Computes how many <see cref="long"/> blocks are needed to store <paramref name="valueCount"/>
/// values of size <paramref name="bitsPerValue"/>.
/// <para/>
/// NOTE: This was longCount() in Lucene.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int Int64Count(int packedIntsVersion, int valueCount, int bitsPerValue)
{
int valuesPerBlock = 64 / bitsPerValue;
return (int)Math.Ceiling((double)valueCount / valuesPerBlock);
}
/// <summary>
/// Tests whether the provided number of bits per value is supported by the
/// format.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool IsSupported(int bitsPerValue)
{
return Packed64SingleBlock.IsSupported(bitsPerValue);
}
/// <summary>
/// Returns the overhead per value, in bits.
/// </summary>
public override float OverheadPerValue(int bitsPerValue)
{
if (Debugging.AssertsEnabled) Debugging.Assert(IsSupported(bitsPerValue));
int valuesPerBlock = 64 / bitsPerValue;
int overhead = 64 % bitsPerValue;
return (float)overhead / valuesPerBlock;
}
}
/// <summary>
/// A format to write packed <see cref="int"/>s.
/// <para/>
/// @lucene.internal
/// </summary>
public class Format
{
/// <summary>
/// Compact format, all bits are written contiguously.
/// </summary>
public static readonly Format PACKED = new PackedFormat();
/// <summary>
/// A format that may insert padding bits to improve encoding and decoding
/// speed. Since this format doesn't support all possible bits per value, you
/// should never use it directly, but rather use
/// <see cref="PackedInt32s.FastestFormatAndBits(int, int, float)"/> to find the
/// format that best suits your needs.
/// </summary>
public static readonly Format PACKED_SINGLE_BLOCK = new PackedSingleBlockFormat();
private static readonly Format[] values = new Format[] { PACKED, PACKED_SINGLE_BLOCK };
public static IEnumerable<Format> Values => values;
/// <summary>
/// Get a format according to its ID.
/// </summary>
public static Format ById(int id)
{
foreach (Format format in Values)
{
if (format.Id == id)
{
return format;
}
}
throw new ArgumentException("Unknown format id: " + id);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Format(int id)
{
this.Id = id;
}
/// <summary>
/// Returns the ID of the format.
/// </summary>
public int Id { get; private set; }
/// <summary>
/// Computes how many <see cref="byte"/> blocks are needed to store <paramref name="valueCount"/>
/// values of size <paramref name="bitsPerValue"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual long ByteCount(int packedIntsVersion, int valueCount, int bitsPerValue)
{
if (Debugging.AssertsEnabled) Debugging.Assert(bitsPerValue >= 0 && bitsPerValue <= 64, "{0}", bitsPerValue);
// assume long-aligned
return 8L * Int64Count(packedIntsVersion, valueCount, bitsPerValue);
}
/// <summary>
/// Computes how many <see cref="long"/> blocks are needed to store <paramref name="valueCount"/>
/// values of size <paramref name="bitsPerValue"/>.
/// <para/>
/// NOTE: This was longCount() in Lucene.
/// </summary>
public virtual int Int64Count(int packedIntsVersion, int valueCount, int bitsPerValue)
{
if (Debugging.AssertsEnabled) Debugging.Assert(bitsPerValue >= 0 && bitsPerValue <= 64, "{0}", bitsPerValue);
long byteCount = ByteCount(packedIntsVersion, valueCount, bitsPerValue);
if (Debugging.AssertsEnabled) Debugging.Assert(byteCount < 8L * int.MaxValue);
if ((byteCount % 8) == 0)
return (int)(byteCount / 8);
else
return (int)(byteCount / 8 + 1);
}
/// <summary>
/// Tests whether the provided number of bits per value is supported by the
/// format.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual bool IsSupported(int bitsPerValue)
{
return bitsPerValue >= 1 && bitsPerValue <= 64;
}
/// <summary>
/// Returns the overhead per value, in bits.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual float OverheadPerValue(int bitsPerValue)
{
if (Debugging.AssertsEnabled) Debugging.Assert(IsSupported(bitsPerValue));
return 0f;
}
/// <summary>
/// Returns the overhead ratio (<c>overhead per value / bits per value</c>).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual float OverheadRatio(int bitsPerValue)
{
if (Debugging.AssertsEnabled) Debugging.Assert(IsSupported(bitsPerValue));
return OverheadPerValue(bitsPerValue) / bitsPerValue;
}
}
/// <summary>
/// Simple class that holds a format and a number of bits per value.
/// </summary>
public class FormatAndBits
{
public Format Format { get; private set; }
public int BitsPerValue { get; private set; }
public FormatAndBits(Format format, int bitsPerValue)
{
this.Format = format;
this.BitsPerValue = bitsPerValue;
}
public override string ToString()
{
return "FormatAndBits(format=" + Format + " bitsPerValue=" + BitsPerValue + ")";
}
}
/// <summary>
/// Try to find the <see cref="Format"/> and number of bits per value that would
/// restore from disk the fastest reader whose overhead is less than
/// <paramref name="acceptableOverheadRatio"/>.
/// <para/>
/// The <paramref name="acceptableOverheadRatio"/> parameter makes sense for
/// random-access <see cref="Reader"/>s. In case you only plan to perform
/// sequential access on this stream later on, you should probably use
/// <see cref="PackedInt32s.COMPACT"/>.
/// <para/>
/// If you don't know how many values you are going to write, use
/// <c><paramref name="valueCount"/> = -1</c>.
/// </summary>
public static FormatAndBits FastestFormatAndBits(int valueCount, int bitsPerValue, float acceptableOverheadRatio)
{
if (valueCount == -1)
{
valueCount = int.MaxValue;
}
acceptableOverheadRatio = Math.Max(COMPACT, acceptableOverheadRatio);
acceptableOverheadRatio = Math.Min(FASTEST, acceptableOverheadRatio);
float acceptableOverheadPerValue = acceptableOverheadRatio * bitsPerValue; // in bits
int maxBitsPerValue = bitsPerValue + (int)acceptableOverheadPerValue;
int actualBitsPerValue = -1;
Format format = Format.PACKED;
if (bitsPerValue <= 8 && maxBitsPerValue >= 8)
{
actualBitsPerValue = 8;
}
else if (bitsPerValue <= 16 && maxBitsPerValue >= 16)
{
actualBitsPerValue = 16;
}
else if (bitsPerValue <= 32 && maxBitsPerValue >= 32)
{
actualBitsPerValue = 32;
}
else if (bitsPerValue <= 64 && maxBitsPerValue >= 64)
{
actualBitsPerValue = 64;
}
else if (valueCount <= Packed8ThreeBlocks.MAX_SIZE && bitsPerValue <= 24 && maxBitsPerValue >= 24)
{
actualBitsPerValue = 24;
}
else if (valueCount <= Packed16ThreeBlocks.MAX_SIZE && bitsPerValue <= 48 && maxBitsPerValue >= 48)
{
actualBitsPerValue = 48;
}
else
{
for (int bpv = bitsPerValue; bpv <= maxBitsPerValue; ++bpv)
{
if (Format.PACKED_SINGLE_BLOCK.IsSupported(bpv))
{
float overhead = Format.PACKED_SINGLE_BLOCK.OverheadPerValue(bpv);
float acceptableOverhead = acceptableOverheadPerValue + bitsPerValue - bpv;
// LUCENENET specific - compare bits rather than using equality operators to prevent these comparisons from failing in x86 in .NET Framework with optimizations enabled
if (NumericUtils.SingleToSortableInt32(overhead) <= NumericUtils.SingleToSortableInt32(acceptableOverhead))
{
actualBitsPerValue = bpv;
format = Format.PACKED_SINGLE_BLOCK;
break;
}
}
}
if (actualBitsPerValue < 0)
{
actualBitsPerValue = bitsPerValue;
}
}
return new FormatAndBits(format, actualBitsPerValue);
}
/// <summary>
/// A decoder for packed integers.
/// </summary>
public interface IDecoder
{
/// <summary>
/// The minimum number of <see cref="long"/> blocks to encode in a single iteration, when
/// using long encoding.
/// <para/>
/// NOTE: This was longBlockCount() in Lucene.
/// </summary>
int Int64BlockCount { get; }
/// <summary>
/// The number of values that can be stored in <see cref="Int64BlockCount"/> <see cref="long"/>
/// blocks.
/// <para/>
/// NOTE: This was longValueCount() in Lucene.
/// </summary>
int Int64ValueCount { get; }
/// <summary>
/// The minimum number of <see cref="byte"/> blocks to encode in a single iteration, when
/// using byte encoding.
/// </summary>
int ByteBlockCount { get; }
/// <summary>
/// The number of values that can be stored in <see cref="ByteBlockCount"/> <see cref="byte"/>
/// blocks.
/// </summary>
int ByteValueCount { get; }
/// <summary>
/// Read <c>iterations * BlockCount</c> blocks from <paramref name="blocks"/>,
/// decode them and write <c>iterations * ValueCount</c> values into
/// <paramref name="values"/>.
/// </summary>
/// <param name="blocks"> The long blocks that hold packed integer values. </param>
/// <param name="blocksOffset"> The offset where to start reading blocks. </param>
/// <param name="values"> The values buffer. </param>
/// <param name="valuesOffset"> The offset where to start writing values. </param>
/// <param name="iterations"> Controls how much data to decode. </param>
void Decode(long[] blocks, int blocksOffset, long[] values, int valuesOffset, int iterations);
/// <summary>
/// Read <c>8 * iterations * BlockCount</c> blocks from <paramref name="blocks"/>,
/// decode them and write <c>iterations * ValueCount</c> values into
/// <paramref name="values"/>.
/// </summary>
/// <param name="blocks"> The long blocks that hold packed integer values. </param>
/// <param name="blocksOffset"> The offset where to start reading blocks. </param>
/// <param name="values"> The values buffer. </param>
/// <param name="valuesOffset"> The offset where to start writing values. </param>
/// <param name="iterations"> Controls how much data to decode. </param>
void Decode(byte[] blocks, int blocksOffset, long[] values, int valuesOffset, int iterations);
/// <summary>
/// Read <c>iterations * BlockCount</c> blocks from <paramref name="blocks"/>,
/// decode them and write <c>iterations * ValueCount</c> values into
/// <paramref name="values"/>.
/// </summary>
/// <param name="blocks"> The long blocks that hold packed integer values. </param>
/// <param name="blocksOffset"> The offset where to start reading blocks. </param>
/// <param name="values"> The values buffer. </param>
/// <param name="valuesOffset"> The offset where to start writing values. </param>
/// <param name="iterations"> Controls how much data to decode. </param>
void Decode(long[] blocks, int blocksOffset, int[] values, int valuesOffset, int iterations);
/// <summary>
/// Read <c>8 * iterations * BlockCount</c> blocks from <paramref name="blocks"/>,
/// decode them and write <c>iterations * ValueCount</c> values into
/// <paramref name="values"/>.
/// </summary>
/// <param name="blocks"> The long blocks that hold packed integer values. </param>
/// <param name="blocksOffset"> The offset where to start reading blocks. </param>
/// <param name="values"> The values buffer. </param>
/// <param name="valuesOffset"> The offset where to start writing values. </param>
/// <param name="iterations"> Controls how much data to decode. </param>
void Decode(byte[] blocks, int blocksOffset, int[] values, int valuesOffset, int iterations);
}
/// <summary>
/// An encoder for packed integers.
/// </summary>
public interface IEncoder
{
/// <summary>
/// The minimum number of long blocks to encode in a single iteration, when
/// using long encoding.
/// <para/>
/// NOTE: This was longBlockCount() in Lucene
/// </summary>
int Int64BlockCount { get; }
/// <summary>
/// The number of values that can be stored in <see cref="Int64BlockCount"/> long
/// blocks.
/// <para/>
/// NOTE: This was longValueCount() in Lucene
/// </summary>
int Int64ValueCount { get; }
/// <summary>
/// The minimum number of byte blocks to encode in a single iteration, when
/// using byte encoding.
/// </summary>
int ByteBlockCount { get; }
/// <summary>
/// The number of values that can be stored in <see cref="ByteBlockCount"/> byte
/// blocks.
/// </summary>
int ByteValueCount { get; }
/// <summary>
/// Read <c>iterations * ValueCount</c> values from <paramref name="values"/>,
/// encode them and write <c>iterations * BlockCount</c> blocks into
/// <paramref name="blocks"/>.
/// </summary>
/// <param name="blocks"> The long blocks that hold packed integer values. </param>
/// <param name="blocksOffset"> The offset where to start writing blocks. </param>
/// <param name="values"> The values buffer. </param>
/// <param name="valuesOffset"> The offset where to start reading values. </param>
/// <param name="iterations"> Controls how much data to encode. </param>
void Encode(long[] values, int valuesOffset, long[] blocks, int blocksOffset, int iterations);
/// <summary>
/// Read <c>iterations * ValueCount</c> values from <paramref name="values"/>,
/// encode them and write <c>8 * iterations * BlockCount</c> blocks into
/// <paramref name="blocks"/>.
/// </summary>
/// <param name="blocks"> The long blocks that hold packed integer values. </param>
/// <param name="blocksOffset"> The offset where to start writing blocks. </param>
/// <param name="values"> The values buffer. </param>
/// <param name="valuesOffset"> The offset where to start reading values. </param>
/// <param name="iterations"> Controls how much data to encode. </param>
void Encode(long[] values, int valuesOffset, byte[] blocks, int blocksOffset, int iterations);
/// <summary>
/// Read <c>iterations * ValueCount</c> values from <paramref name="values"/>,
/// encode them and write <c>iterations * BlockCount</c> blocks into
/// <paramref name="blocks"/>.
/// </summary>
/// <param name="blocks"> The long blocks that hold packed integer values. </param>
/// <param name="blocksOffset"> The offset where to start writing blocks. </param>
/// <param name="values"> The values buffer. </param>
/// <param name="valuesOffset"> The offset where to start reading values. </param>
/// <param name="iterations"> Controls how much data to encode. </param>
void Encode(int[] values, int valuesOffset, long[] blocks, int blocksOffset, int iterations);
/// <summary>
/// Read <c>iterations * ValueCount</c> values from <paramref name="values"/>,
/// encode them and write <c>8 * iterations * BlockCount</c> blocks into
/// <paramref name="blocks"/>.
/// </summary>
/// <param name="blocks"> The long blocks that hold packed integer values. </param>
/// <param name="blocksOffset"> The offset where to start writing blocks. </param>
/// <param name="values"> The values buffer. </param>
/// <param name="valuesOffset"> The offset where to start reading values. </param>
/// <param name="iterations"> Controls how much data to encode. </param>
void Encode(int[] values, int valuesOffset, byte[] blocks, int blocksOffset, int iterations);
}
/// <summary>
/// A read-only random access array of positive integers.
/// <para/>
/// @lucene.internal
/// </summary>
public abstract class Reader : NumericDocValues
{
/// <summary>
/// Bulk get: read at least one and at most <paramref name="len"/> longs starting
/// from <paramref name="index"/> into <c>arr[off:off+len]</c> and return
/// the actual number of values that have been read.
/// </summary>
public virtual int Get(int index, long[] arr, int off, int len)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(len > 0, "len must be > 0 (got {0})", len);
Debugging.Assert(index >= 0 && index < Count);
Debugging.Assert(off + len <= arr.Length);
}
int gets = Math.Min(Count - index, len);
for (int i = index, o = off, end = index + gets; i < end; ++i, ++o)
{
arr[o] = Get(i);
}
return gets;
}
/// <returns> The number of bits used to store any given value.
/// Note: this does not imply that memory usage is
/// <c>bitsPerValue * #values</c> as implementations are free to
/// use non-space-optimal packing of bits. </returns>
public abstract int BitsPerValue { get; }
/// <summary>
/// The number of values.
/// <para/>
/// NOTE: This was size() in Lucene.
/// </summary>
public abstract int Count { get; }
/// <summary>
/// Return the in-memory size in bytes.
/// </summary>
public abstract long RamBytesUsed();
/// <summary>
/// Expert: if the bit-width of this reader matches one of
/// .NET's native types, returns the underlying array
/// (ie, byte[], short[], int[], long[]); else, returns
/// <c>null</c>. Note that when accessing the array you must
/// upgrade the type (bitwise AND with all ones), to
/// interpret the full value as unsigned. Ie,
/// bytes[idx]&0xFF, shorts[idx]&0xFFFF, etc.
/// </summary>
public virtual object GetArray()
{
if (Debugging.AssertsEnabled) Debugging.Assert(!HasArray);
return null;
}
/// <summary>
/// Returns <c>true</c> if this implementation is backed by a
/// native .NET array.
/// </summary>
/// <seealso cref="GetArray"/>
public virtual bool HasArray => false;
}
/// <summary>
/// Run-once iterator interface, to decode previously saved <see cref="PackedInt32s"/>.
/// </summary>
public interface IReaderIterator
{
/// <summary>
/// Returns next value. </summary>
long Next();
/// <summary>
/// Returns at least 1 and at most <paramref name="count"/> next values,
/// the returned ref MUST NOT be modified.
/// </summary>
Int64sRef Next(int count);
/// <summary>
/// Returns number of bits per value. </summary>
int BitsPerValue { get; }
/// <summary>
/// Returns number of values.
/// <para/>
/// NOTE: This was size() in Lucene.
/// </summary>
int Count { get; }
/// <summary>
/// Returns the current position. </summary>
int Ord { get; }
}
// LUCENENET NOTE: Was ReaderIteratorImpl in Lucene
internal abstract class ReaderIterator : IReaderIterator
{
protected readonly DataInput m_in;
protected readonly int m_bitsPerValue;
protected readonly int m_valueCount;
protected ReaderIterator(int valueCount, int bitsPerValue, DataInput @in)
{
this.m_in = @in;
this.m_bitsPerValue = bitsPerValue;
this.m_valueCount = valueCount;
}
public virtual long Next()
{
Int64sRef nextValues = Next(1);
if (Debugging.AssertsEnabled) Debugging.Assert(nextValues.Length > 0);
long result = nextValues.Int64s[nextValues.Offset];
++nextValues.Offset;
--nextValues.Length;
return result;
}
public abstract Int64sRef Next(int count);
public virtual int BitsPerValue => m_bitsPerValue;
public virtual int Count => m_valueCount;
public abstract int Ord { get; }
}
/// <summary>
/// A packed integer array that can be modified.
/// <para/>
/// @lucene.internal
/// </summary>
public abstract class Mutable : Reader
{
/// <summary>
/// Set the value at the given index in the array. </summary>
/// <param name="index"> Where the value should be positioned. </param>
/// <param name="value"> A value conforming to the constraints set by the array. </param>
public abstract void Set(int index, long value);
/// <summary>
/// Bulk set: set at least one and at most <paramref name="len"/> longs starting
/// at <paramref name="off"/> in <paramref name="arr"/> into this mutable, starting at
/// <paramref name="index"/>. Returns the actual number of values that have been
/// set.
/// </summary>
public virtual int Set(int index, long[] arr, int off, int len)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(len > 0, "len must be > 0 (got {0})", len);
Debugging.Assert(index >= 0 && index < Count);
}
len = Math.Min(len, Count - index);
if (Debugging.AssertsEnabled) Debugging.Assert(off + len <= arr.Length);
for (int i = index, o = off, end = index + len; i < end; ++i, ++o)
{
Set(i, arr[o]);
}
return len;
}
/// <summary>
/// Fill the mutable from <paramref name="fromIndex"/> (inclusive) to
/// <paramref name="toIndex"/> (exclusive) with <paramref name="val"/>.
/// </summary>
public virtual void Fill(int fromIndex, int toIndex, long val)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(val <= MaxValue(BitsPerValue));
Debugging.Assert(fromIndex <= toIndex);
}
for (int i = fromIndex; i < toIndex; ++i)
{
Set(i, val);
}
}
/// <summary>
/// Sets all values to 0.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual void Clear()
{
Fill(0, Count, 0);
}
/// <summary>
/// Save this mutable into <paramref name="out"/>. Instantiating a reader from
/// the generated data will return a reader with the same number of bits
/// per value.
/// </summary>
public virtual void Save(DataOutput @out)
{
Writer writer = GetWriterNoHeader(@out, Format, Count, BitsPerValue, DEFAULT_BUFFER_SIZE);
writer.WriteHeader();
for (int i = 0; i < Count; ++i)
{
writer.Add(Get(i));
}
writer.Finish();
}
/// <summary>
/// The underlying format. </summary>
internal virtual Format Format => Format.PACKED;
}
/// <summary>
/// A simple base for <see cref="Reader"/>s that keeps track of valueCount and bitsPerValue.
/// <para/>
/// @lucene.internal
/// </summary>
internal abstract class ReaderImpl : Reader
{
protected readonly int m_bitsPerValue;
protected readonly int m_valueCount;
protected ReaderImpl(int valueCount, int bitsPerValue)
{
this.m_bitsPerValue = bitsPerValue;
if (Debugging.AssertsEnabled) Debugging.Assert(bitsPerValue > 0 && bitsPerValue <= 64, "bitsPerValue={0}", bitsPerValue);
this.m_valueCount = valueCount;
}
public override abstract long Get(int index);
public override sealed int BitsPerValue => m_bitsPerValue;
public override sealed int Count => m_valueCount;
}
public abstract class MutableImpl : Mutable
{
protected readonly int m_valueCount;
protected readonly int m_bitsPerValue;
protected MutableImpl(int valueCount, int bitsPerValue)
{
this.m_valueCount = valueCount;
if (Debugging.AssertsEnabled) Debugging.Assert(bitsPerValue > 0 && bitsPerValue <= 64, "bitsPerValue={0}", bitsPerValue);
this.m_bitsPerValue = bitsPerValue;
}
public override sealed int BitsPerValue => m_bitsPerValue;
public override sealed int Count => m_valueCount;
}
/// <summary>
/// A <see cref="Reader"/> which has all its values equal to 0 (bitsPerValue = 0). </summary>
public sealed class NullReader : Reader
{
private readonly int valueCount;
/// <summary>
/// Sole constructor. </summary>
public NullReader(int valueCount)
{
this.valueCount = valueCount;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override long Get(int index)
{
return 0;
}
public override int Get(int index, long[] arr, int off, int len)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(len > 0, "len must be > 0 (got {0})", len);
Debugging.Assert(index >= 0 && index < valueCount);
}
len = Math.Min(len, valueCount - index);
Arrays.Fill(arr, off, off + len, 0);
return len;
}
public override int BitsPerValue => 0;
public override int Count => valueCount;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override long RamBytesUsed()
{
return RamUsageEstimator.AlignObjectSize(RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + RamUsageEstimator.NUM_BYTES_INT32);
}
}
/// <summary>
/// A write-once Writer.
/// <para/>
/// @lucene.internal
/// </summary>
public abstract class Writer
{
protected readonly DataOutput m_out;
protected readonly int m_valueCount;
protected readonly int m_bitsPerValue;
protected Writer(DataOutput @out, int valueCount, int bitsPerValue)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(bitsPerValue <= 64);
Debugging.Assert(valueCount >= 0 || valueCount == -1);
}
this.m_out = @out;
this.m_valueCount = valueCount;
this.m_bitsPerValue = bitsPerValue;
}
internal virtual void WriteHeader()
{
if (Debugging.AssertsEnabled) Debugging.Assert(m_valueCount != -1);
CodecUtil.WriteHeader(m_out, CODEC_NAME, VERSION_CURRENT);
m_out.WriteVInt32(m_bitsPerValue);
m_out.WriteVInt32(m_valueCount);
m_out.WriteVInt32(Format.Id);
}
/// <summary>
/// The format used to serialize values. </summary>
protected internal abstract PackedInt32s.Format Format { get; }
/// <summary>
/// Add a value to the stream. </summary>
public abstract void Add(long v);
/// <summary>
/// The number of bits per value. </summary>
public int BitsPerValue => m_bitsPerValue;
/// <summary>
/// Perform end-of-stream operations. </summary>
public abstract void Finish();
/// <summary>
/// Returns the current ord in the stream (number of values that have been
/// written so far minus one).
/// </summary>
public abstract int Ord { get; }
}
/// <summary>
/// Get a <see cref="IDecoder"/>.
/// </summary>
/// <param name="format"> The format used to store packed <see cref="int"/>s. </param>
/// <param name="version"> The compatibility version. </param>
/// <param name="bitsPerValue"> The number of bits per value. </param>
/// <returns> A decoder. </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IDecoder GetDecoder(Format format, int version, int bitsPerValue)
{
CheckVersion(version);
return BulkOperation.Of(format, bitsPerValue);
}
/// <summary>
/// Get an <see cref="IEncoder"/>.
/// </summary>
/// <param name="format"> The format used to store packed <see cref="int"/>s. </param>
/// <param name="version"> The compatibility version. </param>
/// <param name="bitsPerValue"> The number of bits per value. </param>
/// <returns> An encoder. </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IEncoder GetEncoder(Format format, int version, int bitsPerValue)
{
CheckVersion(version);
return BulkOperation.Of(format, bitsPerValue);
}
/// <summary>
/// Expert: Restore a <see cref="Reader"/> from a stream without reading metadata at
/// the beginning of the stream. This method is useful to restore data from
/// streams which have been created using
/// <see cref="PackedInt32s.GetWriterNoHeader(DataOutput, Format, int, int, int)"/>.
/// <para/>
/// @lucene.internal
/// </summary>
/// <param name="in"> The stream to read data from, positioned at the beginning of the packed values. </param>
/// <param name="format"> The format used to serialize. </param>
/// <param name="version"> The version used to serialize the data. </param>
/// <param name="valueCount"> How many values the stream holds. </param>
/// <param name="bitsPerValue"> The number of bits per value. </param>
/// <returns> A <see cref="Reader"/>. </returns>
/// <exception cref="IOException"> If there is a low-level I/O error. </exception>
/// <seealso cref="PackedInt32s.GetWriterNoHeader(DataOutput, Format, int, int, int)"/>
public static Reader GetReaderNoHeader(DataInput @in, Format format, int version, int valueCount, int bitsPerValue)
{
CheckVersion(version);
if (format == PackedInt32s.Format.PACKED_SINGLE_BLOCK)
{
return Packed64SingleBlock.Create(@in, valueCount, bitsPerValue);
}
else if (format == PackedInt32s.Format.PACKED)
{
switch (bitsPerValue)
{
case 8:
return new Direct8(version, @in, valueCount);
case 16:
return new Direct16(version, @in, valueCount);
case 32:
return new Direct32(version, @in, valueCount);
case 64:
return new Direct64(/*version,*/ @in, valueCount); // LUCENENET specific - removed unused parameter
case 24:
if (valueCount <= Packed8ThreeBlocks.MAX_SIZE)
{
return new Packed8ThreeBlocks(version, @in, valueCount);
}
break;
case 48:
if (valueCount <= Packed16ThreeBlocks.MAX_SIZE)
{
return new Packed16ThreeBlocks(version, @in, valueCount);
}
break;
}
return new Packed64(version, @in, valueCount, bitsPerValue);
}
else
{
throw AssertionError.Create("Unknown Writer format: " + format);
}
}
/// <summary>
/// Expert: Restore a <see cref="Reader"/> from a stream without reading metadata at
/// the beginning of the stream. this method is useful to restore data when
/// metadata has been previously read using <see cref="ReadHeader(DataInput)"/>.
/// <para/>
/// @lucene.internal
/// </summary>
/// <param name="in"> The stream to read data from, positioned at the beginning of the packed values. </param>
/// <param name="header"> Metadata result from <see cref="ReadHeader(DataInput)"/>. </param>
/// <returns> A <see cref="Reader"/>. </returns>
/// <exception cref="IOException"> If there is a low-level I/O error. </exception>
/// <seealso cref="ReadHeader(DataInput)"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Reader GetReaderNoHeader(DataInput @in, Header header)
{
return GetReaderNoHeader(@in, header.format, header.version, header.valueCount, header.bitsPerValue);
}
/// <summary>
/// Restore a <see cref="Reader"/> from a stream.
/// <para/>
/// @lucene.internal
/// </summary>
/// <param name="in"> The stream to read data from. </param>
/// <returns> A <see cref="Reader"/>. </returns>
/// <exception cref="IOException"> If there is a low-level I/O error </exception>
public static Reader GetReader(DataInput @in)
{