-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlarge_division.go
1048 lines (934 loc) · 37.7 KB
/
large_division.go
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
package goip
import (
"bytes"
"fmt"
"math/big"
"strings"
"unsafe"
"github.com/pchchv/goip/address_error"
)
var _ divisionValues = &largeDivValues{}
// BigDivInt is an unsigned integer type for unlimited size division values.
type BigDivInt = big.Int
type addressLargeDivInternal struct {
addressDivisionBase
defaultRadix *BigDivInt
}
func (div *addressLargeDivInternal) getDefaultRadix() int {
rad := div.defaultRadix
if rad == nil {
return 16 // use same default as other divisions when zero div
}
return int(rad.Int64())
}
func (div *addressLargeDivInternal) toLargeAddressDivision() *IPAddressLargeDivision {
return (*IPAddressLargeDivision)(unsafe.Pointer(div))
}
// getDefaultTextualRadix returns the default radix for textual representations of divisions.
func (div *addressLargeDivInternal) getDefaultTextualRadix() int {
if div.divisionValues == nil || div.defaultRadix == nil {
return 16 // use same default as other divisions when zero div
}
return int(div.defaultRadix.Int64())
}
func (div *addressLargeDivInternal) getLargeDivValues() *largeDivValues {
vals := div.divisionValues
if vals == nil {
return nil
}
return vals.(*largeDivValues)
}
// getBigDefaultTextualRadix returns the default radix for textual representations of divisions.
func (div *addressLargeDivInternal) getBigDefaultTextualRadix() *big.Int {
if div.divisionValues == nil || div.defaultRadix == nil {
return bigSixteen() // use same default as other divisions when zero div
}
return div.defaultRadix
}
// toString produces a string that is useful when a division string is provided with no context.
// It uses a string prefix for octal or hex ("0" or "0x"), and does not use the wildcard '*', because division size is variable, so '*' is ambiguous.
// GetWildcardString() is more appropriate in context with other segments or divisions. It does not use a string prefix and uses '*' for full-range segments.
// GetString() is more appropriate in context with prefix lengths, it uses zeros instead of wildcards for prefix block ranges.
func (div *addressLargeDivInternal) toString() string { // this can be moved to addressDivisionBase when we have ContainsPrefixBlock and similar methods implemented for big.Int in the base
return toString(div.toLargeAddressDivision())
}
// Format implements [fmt.Formatter] interface. It accepts the formats
// - 'v' for the default address and section format (either the normalized or canonical string),
// - 's' (string) for the same,
// - 'b' (binary), 'o' (octal with 0 prefix), 'O' (octal with 0o prefix),
// - 'd' (decimal), 'x' (lowercase hexadecimal), and
// - 'X' (uppercase hexadecimal).
//
// Also supported are some of fmt's format flags for integral types.
// Sign control is not supported since addresses and sections are never negative.
// '#' for an alternate format is supported, which adds a leading zero for octal, and for hexadecimal it adds
// a leading "0x" or "0X" for "%#x" and "%#X" respectively.
// Also supported is specification of minimum digits precision, output field width,
// space or zero padding, and '-' for left or right justification.
func (div addressLargeDivInternal) Format(state fmt.State, verb rune) {
switch verb {
case 's', 'v':
_, _ = state.Write([]byte(div.toString()))
return
}
// we try to filter through the flags provided to the DivInt values, as if the fmt string were applied to the int(s) directly
formatStr := flagsFromState(state, verb)
if div.isMultiple() {
formatStr = fmt.Sprintf("%s%c%s", formatStr, RangeSeparator, formatStr)
_, _ = state.Write([]byte(fmt.Sprintf(formatStr, div.getValue(), div.getUpperValue())))
} else {
_, _ = state.Write([]byte(fmt.Sprintf(formatStr, div.getValue())))
}
}
// IPAddressLargeDivision represents an arbitrary bit size division in an address or address division grouping.
// It can contain a single value or a range of consecutive values and has an assigned bit length.
// Like all address components, it is immutable.
type IPAddressLargeDivision struct {
addressLargeDivInternal
}
// IsMultiple returns true if the given division represents a consecutive range of values or a single value.
func (div *IPAddressLargeDivision) IsMultiple() bool {
return div != nil && div.isMultiple()
}
// IsPrefixed returns whether the given division has a prefix length associated with it.
// If so, the prefix length is given by GetDivisionPrefixLen()
func (div *IPAddressLargeDivision) IsPrefixed() bool {
return div.GetDivisionPrefixLen() != nil
}
// GetDivisionPrefixLen returns the network prefix for the division.
// For an address like "1.2.0.0/16", the network prefix is 16.
// When it comes to each address subdivision or segment, the subdivision prefix is the prefix obtained by applying an address or partition prefix.
// For example, consider the address "1.2.0.0/20."
// The first segment has no prefix because the address prefix 20 is beyond the 8 bits in the first segment, it is not even applied to the segment.
// The second segment has no prefix because the address prefix extends beyond bits 9 through 16,
// which are in the second segment, it also does not apply to this segment.
// The third segment is prefixed with 4 because address prefix 20 corresponds to the first 4 bits in the third segment,
// which means that the first 4 bits are part of the network portion of the address or segment.
// The last segment is prefixed with 0 because no bits are part of the network portion of the address or segment.
// The following division prefixes apply throughout the address: nil ... nil (1 to the bit length of the segment) 0 ... 0.
// If the division has no prefix, nil is returned.
func (div *IPAddressLargeDivision) GetDivisionPrefixLen() PrefixLen {
return div.getDivisionPrefixLength()
}
// GetPrefixLen returns the network prefix for the unit.
// For an address like "1.2.0.0/16", the network prefix is 16.
// When it comes to each address subdivision or segment, the prefix for the subdivision is the prefix obtained when the address or partition prefix is applied.
// For example, consider the address "1.2.0.0/20".
// The first segment has no prefix because the address prefix 20 is beyond the 8 bits in the first segment, it is not even applied to the segment.
// The second segment has no prefix because the address prefix extends beyond bits 9 through 16,
// which are in the second segment, it also does not apply to this segment.
// The third segment is prefixed with 4 because address prefix 20 corresponds to the first 4 bits in the third segment,
// which means that the first 4 bits are part of the network portion of the address or segment.
// The last segment is prefixed with 0 because no bits are part of the network portion of the address or segment.
// The following division prefixes apply throughout the address: nil ... nil (1 to the bit length of the segment) 0 ... 0.
// If the segment has no prefix, nil is returned.
func (div *IPAddressLargeDivision) GetPrefixLen() PrefixLen {
return div.getDivisionPrefixLength()
}
func (div *IPAddressLargeDivision) isNil() bool {
return div == nil
}
// IsSinglePrefix returns true if the division value range spans
// just a single prefix value for the given prefix length.
func (div *IPAddressLargeDivision) IsSinglePrefix(divisionPrefixLen BitCount) bool {
lower, upper := div.getValue(), div.getUpperValue()
bitCount := div.GetBitCount()
divisionPrefixLen = checkBitCount(divisionPrefixLen, bitCount)
shift := uint(bitCount - divisionPrefixLen)
var one, two big.Int
return one.Rsh(lower, shift).Cmp(two.Rsh(upper, shift)) == 0
}
func (div *IPAddressLargeDivision) getBigRadix(radix int) *big.Int {
defaultRadix := div.getDefaultTextualRadix()
if defaultRadix == radix {
return div.getBigDefaultTextualRadix()
}
return big.NewInt(int64(radix))
}
func (div *IPAddressLargeDivision) getRangeDigitCount(radix int) int {
if !div.IsMultiple() {
return 0
}
var quotient, upperQuotient, remainder big.Int
count := 1
bigRadix := big.NewInt(int64(radix))
bigUpperDigit := big.NewInt(int64(radix - 1))
val, upperVal := div.getValue(), div.getUpperValue()
for {
quotient.QuoRem(val, bigRadix, &remainder)
if bigIsZero(&remainder) {
upperQuotient.QuoRem(upperVal, bigRadix, &remainder)
if remainder.CmpAbs(bigUpperDigit) == 0 {
val, upperVal = "ient, &upperQuotient
if val.CmpAbs(upperVal) == 0 {
return count
} else {
count++
continue
}
}
}
return 0
}
}
// IsPrefixBlock returns whether the division has a prefix length and
// the division range includes the block of values for that prefix length.
// If the prefix length matches the bit count, this returns true.
func (div *IPAddressLargeDivision) IsPrefixBlock() bool {
return div.getLargeDivValues().isPrefixBlock
}
// IsSinglePrefixBlock returns whether the division range matches
// the block of values for its prefix length
func (div *IPAddressLargeDivision) IsSinglePrefixBlock() bool {
return *div.getLargeDivValues().cache.isSinglePrefBlock
}
// GetValue returns the lowest value in the address division range as a big integer.
func (div *IPAddressLargeDivision) GetValue() *BigDivInt {
return new(big.Int).Set(div.addressLargeDivInternal.GetValue())
}
// GetUpperValue returns the highest value in the address division range as a big integer.
func (div *IPAddressLargeDivision) GetUpperValue() *BigDivInt {
return new(big.Int).Set(div.addressLargeDivInternal.GetUpperValue())
}
// GetCount returns the count of possible distinct values for this division.
// If not representing multiple values, the count is 1.
//
// For example, a division with the value range of 3-7 has count 5.
//
// Use IsMultiple if you simply want to know if the count is greater than 1.
func (div *IPAddressLargeDivision) GetCount() *big.Int {
if div == nil {
return bigZero()
}
return div.getCount()
}
// ContainsPrefixBlock returns whether the division range includes
// the block of values for the given prefix length.
func (div *IPAddressLargeDivision) ContainsPrefixBlock(prefixLen BitCount) bool {
bitCount := div.GetBitCount()
if prefixLen <= 0 {
return div.IsFullRange()
} else if prefixLen >= bitCount {
return true
}
lower, upper := div.getValue(), div.getUpperValue()
return testBigRange(lower, upper, upper, bitCount, prefixLen)
}
// ContainsSinglePrefixBlock returns whether the division range matches exactly
// the block of values for the given prefix length and
// has just a single prefix for that prefix length.
func (div *IPAddressLargeDivision) ContainsSinglePrefixBlock(prefixLen BitCount) bool {
bitCount := div.GetBitCount()
prefixLen = checkBitCount(prefixLen, bitCount)
if prefixLen == 0 {
return div.IsFullRange()
}
lower, upper := div.getValue(), div.getUpperValue()
return testBigRange(lower, lower, upper, bitCount, prefixLen)
}
// GetMinPrefixLenForBlock returns the smallest prefix length such that this division includes the block of all values for that prefix length.
//
// If the entire range can be described in this way, this method returns, the same value as GetPrefixLenForSingleBlock.
//
// This block can have a single prefix or multiple possible prefix values for the returned prefix length.
// To avoid the case of multiple prefix values, use GetPrefixLenForSingleBlock.
//
// If this division represents a single value, a bit count is returned.
func (div *IPAddressLargeDivision) GetMinPrefixLenForBlock() BitCount {
result := div.GetBitCount()
if div.IsMultiple() {
lower, upper := div.getValue(), div.getUpperValue()
lowerZeros := lower.TrailingZeroBits()
if lowerZeros != 0 {
var upperNot big.Int
upperOnes := upperNot.Not(upper).TrailingZeroBits()
if upperOnes != 0 {
prefixedBitCount := BitCount(umin(lowerZeros, upperOnes))
result -= prefixedBitCount
}
}
}
return result
}
// GetPrefixLenForSingleBlock returns a prefix length for which there is only one prefix in a given division,
// and the range of values in that division is the same as the block of all values for that prefix.
//
// If the range of division values can be described in this way,
// this method returns, the same value as GetMinPrefixLenForBlock.
//
// If no such prefix length exists, returns nil.
//
// If this division is a single value, this returns the bit count of the segment.
func (div *IPAddressLargeDivision) GetPrefixLenForSingleBlock() PrefixLen {
prefLen := div.GetMinPrefixLenForBlock()
bitCount := div.GetBitCount()
if prefLen == bitCount {
if !div.IsMultiple() {
result := PrefixBitCount(prefLen)
return &result
}
} else {
lower, upper := div.getValue(), div.getUpperValue()
shift := uint(bitCount - prefLen)
var one, two big.Int
if one.Rsh(lower, shift).Cmp(two.Rsh(upper, shift)) == 0 {
result := PrefixBitCount(prefLen)
return &result
}
}
return nil
}
func (div *IPAddressLargeDivision) getMaxDigitCount() int {
var maxValue *BigDivInt
rad := div.getDefaultTextualRadix()
bc := div.GetBitCount()
vals := div.getLargeDivValues()
if vals == nil {
maxValue = bigZeroConst()
} else {
maxValue = vals.maxValue
}
return getBigMaxDigitCount(rad, bc, maxValue)
}
func (div *IPAddressLargeDivision) getDefaultLowerString() string {
val := div.GetValue()
rad := div.getBigDefaultTextualRadix()
mdg := div.getMaxDigitCount()
return toDefaultBigString(val, rad, false, 0, mdg)
}
func (div *IPAddressLargeDivision) getStringAsLower() string {
stringer := div.getDefaultLowerString
if div.divisionValues != nil {
if cache := div.getCache(); cache != nil {
return cacheStr(&cache.cachedString, stringer)
}
}
return stringer()
}
func (div *IPAddressLargeDivision) isExtendedDigits() bool {
return isExtendedDigits(div.getDefaultTextualRadix())
}
func (div *IPAddressLargeDivision) getDefaultRangeSeparatorString() string {
if div.isExtendedDigits() {
return ExtendedDigitsRangeSeparatorStr
}
return RangeSeparatorStr
}
func (div *IPAddressLargeDivision) getDefaultMaskedRangeString() string {
maxDigitCount := div.getMaxDigitCount()
radix := div.getBigDefaultTextualRadix()
return toDefaultBigString(div.getValue(), radix, false, 0, maxDigitCount) +
div.getDefaultRangeSeparatorString() +
toDefaultBigString(div.getLargeDivValues().upperValueMasked, radix, false, 0, maxDigitCount)
}
func (div *IPAddressLargeDivision) getDefaultRangeString() string {
maxDigitCount := div.getMaxDigitCount()
radix := div.getBigDefaultTextualRadix()
return toDefaultBigString(div.getValue(), radix, false, 0, maxDigitCount) +
div.getDefaultRangeSeparatorString() +
toDefaultBigString(div.getUpperValue(), radix, false, 0, maxDigitCount)
}
// GetString produces a normalized string to represent the segment.
// If the segment is an IP segment string with a CIDR network prefix block for its prefix length,
// the string contains only the lower value of the block range.
// Otherwise, an explicit range will be printed.
// If the segment is not an IP segment,
// the string will be similar to the string output by the GetWildcardString function.
//
// The returned string is useful in the context of creating strings for address sections or full addresses,
// in which case the radix and bit length can be deduced from the context.
// The String method produces strings, which are more appropriate when there is no context.
func (div *IPAddressLargeDivision) GetString() string {
stringer := func() string {
if div.IsSinglePrefixBlock() || !div.isMultiple() { //covers the case of single addresses, when there is no prefix or the prefix is the bit count
return div.getDefaultLowerString()
} else {
if div.IsPrefixBlock() {
return div.getDefaultMaskedRangeString()
}
return div.getDefaultRangeString()
}
}
if div.divisionValues != nil {
if cache := div.getCache(); cache != nil {
return cacheStr(&cache.cachedString, stringer)
}
}
return stringer()
}
// GetWildcardString produces a normalized string to represent the segment,
// favouring wildcards and range characters regardless of any network prefix length.
// The explicit range of a range-valued segment will be printed.
//
// The string returned is useful in the context of creating strings for address sections or full addresses,
// in which case the radix and the bit-length can be deduced from the context.
// The String method produces strings more appropriate when no context is provided.
func (div *IPAddressLargeDivision) GetWildcardString() string {
stringer := func() string {
if !div.IsPrefixed() || !div.isMultiple() {
return div.GetString()
}
return div.getDefaultRangeString()
}
if div.divisionValues != nil {
if cache := div.getCache(); cache != nil {
return cacheStr(&cache.cachedWildcardString, stringer)
}
}
return stringer()
}
func (div *IPAddressLargeDivision) getLowerStringLength(radix int) int {
return getBigDigitCount(div.getValue(), div.getBigRadix(radix))
}
func (div *IPAddressLargeDivision) getUpperStringLength(radix int) int {
return getBigDigitCount(div.getUpperValue(), div.getBigRadix(radix))
}
func (div *IPAddressLargeDivision) toDefaultString(val *BigDivInt, radix int, uppercase bool, choppedDigits int) string {
return toDefaultBigString(val, div.getBigRadix(radix), uppercase, choppedDigits, getBigMaxDigitCount(radix, div.GetBitCount(), div.getLargeDivValues().maxValue))
}
func (div *IPAddressLargeDivision) getLowerString(radix int, uppercase bool, appendable *strings.Builder) {
appendable.WriteString(div.toDefaultString(div.getValue(), radix, uppercase, 0))
}
func (div *IPAddressLargeDivision) getLowerStringChopped(radix int, choppedDigits int, uppercase bool, appendable *strings.Builder) {
appendable.WriteString(div.toDefaultString(div.getValue(), radix, uppercase, choppedDigits))
}
func (div *IPAddressLargeDivision) getUpperString(radix int, uppercase bool, appendable *strings.Builder) {
appendable.WriteString(div.toDefaultString(div.getUpperValue(), radix, uppercase, 0))
}
func (div *IPAddressLargeDivision) getUpperStringMasked(radix int, uppercase bool, appendable *strings.Builder) {
appendable.WriteString(div.toDefaultString(div.getLargeDivValues().upperValueMasked, radix, uppercase, 0))
}
func (div *IPAddressLargeDivision) getSplitLowerString(radix int, choppedDigits int, uppercase bool, splitDigitSeparator byte, reverseSplitDigits bool, stringPrefix string, appendable *strings.Builder) {
var builder strings.Builder
div.getLowerStringChopped(radix, choppedDigits, uppercase, &builder)
str := builder.String()
length := len(str)
prefLen := len(stringPrefix)
for i := 0; i < length; i++ {
if i > 0 {
appendable.WriteByte(splitDigitSeparator)
}
if prefLen > 0 {
appendable.WriteString(stringPrefix)
}
if reverseSplitDigits {
appendable.WriteByte(str[length-i-1])
} else {
appendable.WriteByte(str[i])
}
}
}
func (div *IPAddressLargeDivision) getSplitRangeString(rangeSeparator string, wildcard string, radix int, uppercase bool, splitDigitSeparator byte, reverseSplitDigits bool, stringPrefix string, appendable *strings.Builder) address_error.IncompatibleAddressError {
var lowerBuilder, upperBuilder strings.Builder
div.getLowerString(radix, uppercase, &lowerBuilder)
div.getUpperString(radix, uppercase, &upperBuilder)
diff := upperBuilder.Len() - lowerBuilder.Len()
if diff > 0 {
lowerStr := lowerBuilder.String()
lowerBuilder.Reset()
for ; diff > 0; diff-- {
lowerBuilder.WriteByte('0')
}
lowerBuilder.WriteString(lowerStr)
}
previousWasFull, nextMustBeFull := true, false
dig := getDigits(uppercase, radix)
zeroDigit := dig[0]
highestDigit := dig[radix-1]
lowerStr := lowerBuilder.String()
upperStr := upperBuilder.String()
length := len(lowerStr)
prefLen := len(stringPrefix)
for i := 0; i < length; i++ {
var index int
if reverseSplitDigits {
index = length - i - 1
} else {
index = 1
}
lower := lowerStr[index]
upper := upperStr[index]
if i > 0 {
appendable.WriteByte(splitDigitSeparator)
}
if lower == upper {
if nextMustBeFull {
return &incompatibleAddressError{addressError{key: "ipaddress.error.splitMismatch"}}
}
if prefLen > 0 {
appendable.WriteString(stringPrefix)
}
appendable.WriteByte(lower)
} else {
isFullRange := (lower == zeroDigit) && (upper == highestDigit)
if isFullRange {
appendable.WriteString(wildcard)
} else {
if nextMustBeFull {
return &incompatibleAddressError{addressError{key: "ipaddress.error.splitMismatch"}}
}
if prefLen > 0 {
appendable.WriteString(stringPrefix)
}
appendable.WriteByte(lower)
appendable.WriteString(rangeSeparator)
appendable.WriteByte(upper)
}
if reverseSplitDigits {
if !previousWasFull {
return &incompatibleAddressError{addressError{key: "ipaddress.error.splitMismatch"}}
}
previousWasFull = isFullRange
} else {
nextMustBeFull = true
}
}
}
return nil
}
func (div *IPAddressLargeDivision) getSplitRangeStringLength(rangeSeparator string, wildcard string, leadingZeroCount int, radix int, uppercase bool, splitDigitSeparator byte, reverseSplitDigits bool, stringPrefix string) int {
var lowerBuilder, upperBuilder strings.Builder
_, _, _ = rangeSeparator, splitDigitSeparator, reverseSplitDigits
digitsLength := -1
stringPrefixLength := len(stringPrefix)
div.getLowerString(radix, uppercase, &lowerBuilder)
div.getUpperString(radix, uppercase, &upperBuilder)
dig := getDigits(uppercase, radix)
zeroDigit := dig[0]
highestDigit := dig[radix-1]
remainingAfterLoop := leadingZeroCount
lowerStr := lowerBuilder.String()
upperStr := upperBuilder.String()
upperLength := len(upperStr)
lowerLength := len(lowerStr)
for i := 1; i < upperLength; i++ {
var lower byte
if i <= lowerLength {
lower = lowerStr[lowerLength-i]
}
upperIndex := upperLength - i
upper := upperStr[upperIndex]
isFullRange := (lower == zeroDigit) && (upper == highestDigit)
if isFullRange {
digitsLength += len(wildcard) + 1
} else if lower != upper {
digitsLength += (stringPrefixLength << 1) + 4 // 1 for each digit, 1 for range separator, 1 for split digit separator
} else {
// this and any remaining must be singles
remainingAfterLoop += upperIndex + 1
break
}
}
if remainingAfterLoop > 0 {
digitsLength += remainingAfterLoop * (stringPrefixLength + 2) // one for each splitDigitSeparator, 1 for each digit
}
return digitsLength
}
func (div *IPAddressLargeDivision) getDigitCount(val *BigDivInt, radix int) int {
vals := div.divisionValues
if vals == nil {
return 1
}
var bigRadix *big.Int
if div.getDefaultTextualRadix() == radix {
bigRadix = div.getBigDefaultTextualRadix()
} else {
bigRadix = big.NewInt(int64(radix))
}
return getBigDigitCount(val, bigRadix)
}
func (div *IPAddressLargeDivision) getMaxDigitCountRadix(radix int) int {
var maxValue *BigDivInt
bc := div.GetBitCount()
vals := div.getLargeDivValues()
if vals == nil {
maxValue = bigZeroConst()
} else {
maxValue = vals.maxValue
}
return getBigMaxDigitCount(radix, bc, maxValue)
}
func (div *IPAddressLargeDivision) adjustLeadingZeroCount(leadingZeroCount int, value *BigDivInt, radix int) int {
if leadingZeroCount < 0 {
width := div.getDigitCount(value, radix)
return max(0, div.getMaxDigitCountRadix(radix)-width)
}
return leadingZeroCount
}
func (div *IPAddressLargeDivision) adjustLowerLeadingZeroCount(leadingZeroCount int, radix int) int {
return div.adjustLeadingZeroCount(leadingZeroCount, div.getValue(), radix)
}
func (div *IPAddressLargeDivision) adjustUpperLeadingZeroCount(leadingZeroCount int, radix int) int {
return div.adjustLeadingZeroCount(leadingZeroCount, div.getUpperValue(), radix)
}
// String produces a string that is useful when a division string is provided with no context.
// It uses a string prefix for octal or hex ("0" or "0x"), and does not use the wildcard '*',
// because division size is variable, so '*' is ambiguous.
// GetWildcardString is more appropriate in context with other segments or divisions.
// It does not use a string prefix and uses '*' for full-range segments.
// GetString is more appropriate in context with prefix lengths,
// it uses zeros instead of wildcards for prefix block ranges.
func (div *IPAddressLargeDivision) String() string {
if div == nil {
return nilString()
}
return div.toString()
}
// Compare returns a negative integer, zero,
// or a positive integer if the given address division is less than,
// equal, or greater than the given item.
// Any address item is comparable to any other address element.
// CountComparator is used to compare all address items.
func (div *IPAddressLargeDivision) Compare(item AddressItem) int {
return CountComparator.Compare(div, item)
}
// CompareSize compares the counts of two items, the number of individual values within.
//
// Instead of calculating the count using GetCount,
// there can be more efficient ways of determining that one represents more individual values than another.
//
// CompareSize returns a positive integer if the given division has a larger count than the given item,
// zero if they are the same, or a negative integer if the other has a larger count.
func (div *IPAddressLargeDivision) CompareSize(other AddressItem) int {
if div == nil {
if isNilItem(other) {
return 0
}
// we have size 0, other has size >= 1
return -1
}
return compareCount(div, other)
}
type largeDivValues struct {
bitCount BitCount
value *BigDivInt
upperValue *BigDivInt // always points to value when single-valued
maxValue *BigDivInt
upperValueMasked *BigDivInt
isPrefixBlock bool // note that isSinglePrefBlock is in the divCache
isMult bool
prefLen PrefixLen
cache divCache
}
func (div *largeDivValues) getBitCount() BitCount {
return div.bitCount
}
func (div *largeDivValues) getByteCount() int {
return (int(div.getBitCount()) + 7) >> 3
}
func (div *largeDivValues) getDivisionPrefixLength() PrefixLen {
return div.prefLen
}
// For internal use.
// Returns a cached value, so it cannot be changed or returned to external callers.
// The only place to clone is the GetValue() and GetUpperValue() methods, which return elsewhere
func (div *largeDivValues) getValue() *BigDivInt {
return div.value
}
// For internal use.
// Returns a cached value, so it cannot be changed or returned to external callers.
// The only place to clone is the GetValue() and GetUpperValue() methods, which return elsewhere
func (div *largeDivValues) getUpperValue() *BigDivInt {
return div.upperValue
}
func (div *largeDivValues) includesMax() bool {
return div.upperValue.Cmp(div.maxValue) == 0
}
func (div *largeDivValues) isMultiple() bool {
return div.isMult
}
func (div *largeDivValues) calcBytesInternal() (bytes, upperBytes []byte) {
return div.value.Bytes(), div.upperValue.Bytes()
}
func (div *largeDivValues) bytesInternal(upper bool) (bytes []byte) {
if upper {
return div.upperValue.Bytes()
}
return div.value.Bytes()
}
func (div *largeDivValues) getCache() *divCache {
return &div.cache
}
func (div *largeDivValues) getDivisionValue() DivInt {
return DivInt(div.value.Uint64())
}
func (div *largeDivValues) getUpperDivisionValue() DivInt {
return DivInt(div.upperValue.Uint64())
}
func (div *largeDivValues) getSegmentValue() SegInt {
return SegInt(div.value.Uint64())
}
func (div *largeDivValues) getUpperSegmentValue() SegInt {
return SegInt(div.upperValue.Uint64())
}
func (div *largeDivValues) getAddrType() addrType {
return zeroType
}
func (div *largeDivValues) includesZero() bool {
return bigIsZero(div.value)
}
func (div *largeDivValues) getCount() *big.Int {
var res big.Int
return res.Sub(div.upperValue, div.value).Add(&res, bigOneConst())
}
func (div *largeDivValues) derivePrefixed(prefLen PrefixLen) divisionValues {
return newLargeDivValuesUnchecked(div.value, div.upperValue, div.maxValue, div.isMult, prefLen, div.bitCount)
}
func (div *largeDivValues) deriveNewMultiSeg(val, upperVal SegInt, prefLen PrefixLen) divisionValues {
return newLargeDivValuesDivIntUnchecked(DivInt(val), DivInt(upperVal), prefLen, div.bitCount)
}
func (div *largeDivValues) deriveNew(val, upperVal DivInt, prefLen PrefixLen) divisionValues {
return newLargeDivValuesDivIntUnchecked(val, upperVal, prefLen, div.bitCount)
}
func (div *largeDivValues) deriveNewSeg(val SegInt, prefLen PrefixLen) divisionValues {
return newLargeDivValuesDivIntUnchecked(DivInt(val), DivInt(val), prefLen, div.bitCount)
}
func newLargeDivValuesUnchecked(value, upperValue, maxValue *BigDivInt, isMult bool, prefLen PrefixLen, bitCount BitCount) *largeDivValues {
var isSinglePrefBlock bool
result := &largeDivValues{
prefLen: prefLen,
bitCount: bitCount,
value: value,
upperValue: upperValue,
maxValue: maxValue,
isMult: isMult,
}
result.isPrefixBlock, isSinglePrefBlock, result.upperValueMasked =
setCachedPrefixValues(result.value, result.upperValue, result.maxValue, prefLen, bitCount)
if isSinglePrefBlock {
result.cache.isSinglePrefBlock = &trueVal
} else {
result.cache.isSinglePrefBlock = &falseVal
}
return result
}
func newLargeDivValuesDivIntUnchecked(value, upperValue DivInt, prefLen PrefixLen, bitCount BitCount) *largeDivValues {
result := &largeDivValues{
prefLen: prefLen,
bitCount: bitCount,
}
val := new(big.Int).SetUint64(uint64(value))
if value == upperValue {
result.value, result.upperValue = val, val
} else {
result.isMult = true
result.value, result.upperValue = val, new(big.Int).SetUint64(uint64(upperValue))
}
var isSinglePrefBlock bool
result.maxValue = setMax(result.upperValue, bitCount)
result.isPrefixBlock, isSinglePrefBlock, result.upperValueMasked =
setCachedPrefixValues(result.value, result.upperValue, result.maxValue, prefLen, bitCount)
if isSinglePrefBlock {
result.cache.isSinglePrefBlock = &trueVal
} else {
result.cache.isSinglePrefBlock = &falseVal
}
return result
}
func setCachedPrefixValues(value, upperValue, maxValue *BigDivInt, prefLen PrefixLen, bitCount BitCount) (isPrefixBlock, isSinglePrefBlock bool, upperValueMasked *BigDivInt) {
if prefLen != nil {
if prefLen.Len() == bitCount {
isPrefixBlock = true
isSinglePrefBlock = value == upperValue
upperValueMasked = upperValue
} else if prefLen.Len() == 0 {
valIsZero := bigIsZero(value)
isFullRange := valIsZero && upperValue == maxValue
isPrefixBlock = isFullRange
isSinglePrefBlock = isFullRange
if valIsZero {
upperValueMasked = value
} else {
upperValueMasked = bigZeroConst()
}
} else {
prefixLen := prefLen.Len()
isPrefixBlock = testBigRange(value, upperValue, upperValue, bitCount, prefixLen)
isSinglePrefBlock = testBigRange(value, value, upperValue, bitCount, prefixLen)
upperValueMasked = setUpperValueMasked(value, upperValue, prefLen, bitCount)
}
} else {
upperValueMasked = upperValue
}
return
}
func setUpperValueMasked(value, upperValue *BigDivInt, prefLen PrefixLen, bitCount BitCount) *BigDivInt {
var networkMask big.Int
networkMask.Lsh(bigMinusOneConst(), uint(bitCount-prefLen.Len())).And(upperValue, &networkMask)
if networkMask.Cmp(upperValue) == 0 {
return upperValue
} else if networkMask.Cmp(value) == 0 {
return value
}
return &networkMask
}
func testBigRangeMasks(lowerValue, upperValue, finalUpperValue, networkMask, hostMask *BigDivInt) bool {
var one, two big.Int
return lowerValue.CmpAbs(one.And(lowerValue, networkMask)) == 0 &&
finalUpperValue.CmpAbs(two.Or(upperValue, hostMask)) == 0
}
func testBigRange(lowerValue, upperValue, finalUpperValue *BigDivInt, bitCount, divisionPrefixLen BitCount) bool {
var networkMask, hostMask big.Int
networkMask.Lsh(bigMinusOneConst(), uint(bitCount-divisionPrefixLen))
hostMask.Not(&networkMask)
return testBigRangeMasks(lowerValue, upperValue, finalUpperValue, &networkMask, &hostMask)
}
func setMax(assignedUpper *BigDivInt, bitCount BitCount) (max *BigDivInt) {
var maxVal big.Int
max = maxVal.Lsh(bigOneConst(), uint(bitCount)).Sub(&maxVal, bigOneConst())
if max.CmpAbs(assignedUpper) == 0 {
max = assignedUpper
}
return
}
func setVal(valueBytes []byte, bitCount BitCount) (assignedValue *BigDivInt, assignedBitCount BitCount, maxVal *BigDivInt) {
if bitCount < 0 {
bitCount = 0
}
assignedBitCount = bitCount
maxLen := (bitCount + 7) >> 3
if len(valueBytes) >= maxLen {
valueBytes = valueBytes[:maxLen]
}
assignedValue = new(big.Int).SetBytes(valueBytes)
maxVal = setMax(assignedValue, bitCount)
return
}
func setVals(valueBytes []byte, upperBytes []byte, bitCount BitCount) (assignedValue, assignedUpper *BigDivInt, assignedBitCount BitCount, maxVal *BigDivInt) {
if bitCount < 0 {
bitCount = 0
}
assignedBitCount = bitCount
maxLen := (bitCount + 7) >> 3
if len(valueBytes) >= maxLen || len(upperBytes) >= maxLen {
extraBits := bitCount & 7
mask := byte(0xff)
if extraBits > 0 {
mask = ^(mask << uint(8-extraBits))
}
if len(valueBytes) >= maxLen {
valueBytes = valueBytes[len(valueBytes)-maxLen:]
b := valueBytes[0]
if b&mask != b {
valueBytes = cloneBytes(valueBytes)
valueBytes[0] &= mask
}
}
if len(upperBytes) >= maxLen {
upperBytes = upperBytes[len(upperBytes)-maxLen:]
b := upperBytes[0]
if b&mask != b {
upperBytes = cloneBytes(upperBytes)
upperBytes[0] &= mask
}
}
}
assignedValue = new(big.Int).SetBytes(valueBytes)
if upperBytes == nil || bytes.Compare(valueBytes, upperBytes) == 0 {
assignedUpper = assignedValue
} else {
assignedUpper = new(big.Int).SetBytes(upperBytes)
cmp := assignedValue.CmpAbs(assignedUpper)
if cmp == 0 {
assignedUpper = assignedValue
} else if cmp > 0 {
// flip them
assignedValue, assignedUpper = assignedUpper, assignedValue
}
}
maxVal = setMax(assignedUpper, bitCount)
return
}
func createLargeAddressDiv(vals divisionValues, defaultRadix int) *IPAddressLargeDivision {
res := &IPAddressLargeDivision{
addressLargeDivInternal{
addressDivisionBase: addressDivisionBase{vals},
},
}
if defaultRadix >= 2 {
res.defaultRadix = new(big.Int).SetInt64(int64(defaultRadix))
}
return res
}
func newLargeDivValue(value []byte, bitCount BitCount) *largeDivValues {
result := &largeDivValues{cache: divCache{}}
result.value, bitCount, result.maxValue = setVal(value, bitCount)
result.bitCount = bitCount
result.upperValue = result.value
result.upperValueMasked = result.upperValue
result.cache.isSinglePrefBlock = &falseVal
return result
}
func newLargeDivValues(value, upperValue []byte, bitCount BitCount) *largeDivValues {
result := &largeDivValues{cache: divCache{}}
result.value, result.upperValue, bitCount, result.maxValue = setVals(value, upperValue, bitCount)
result.bitCount = bitCount
result.isMult = result.value != result.upperValue
result.upperValueMasked = result.upperValue
result.cache.isSinglePrefBlock = &falseVal
return result
}
// NewIPAddressLargeDivision creates a division of the given arbitrary bit-length, assigning it the given value.
// If the value's bit length exceeds the given bit length, it is truncated.
func NewIPAddressLargeDivision(val []byte, bitCount BitCount, defaultRadix int) *IPAddressLargeDivision {
return createLargeAddressDiv(newLargeDivValue(val, bitCount), defaultRadix)
}
// NewIPAddressLargeRangeDivision creates a division of the given arbitrary bit-length, assigning it the given value range.
// If a value's bit length exceeds the given bit length, it is truncated.
func NewIPAddressLargeRangeDivision(val, upperVal []byte, bitCount BitCount, defaultRadix int) *IPAddressLargeDivision {
return createLargeAddressDiv(newLargeDivValues(val, upperVal, bitCount), defaultRadix)
}
func newLargeDivPrefixedValue(value []byte, prefLen PrefixLen, bitCount BitCount) *largeDivValues {
result := &largeDivValues{cache: divCache{}}
result.value, bitCount, result.maxValue = setVal(value, bitCount)
result.bitCount = bitCount
result.upperValue = result.value
prefLen = checkPrefLen(prefLen, bitCount)
result.prefLen = prefLen
if prefLen != nil {
if result.isPrefixBlock = prefLen.Len() == bitCount; result.isPrefixBlock {
result.cache.isSinglePrefBlock = &trueVal