-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdivision.go
1237 lines (1066 loc) · 47 KB
/
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 (
"fmt"
"math/big"
"math/bits"
"strings"
"unsafe"
"github.com/pchchv/goip/address_error"
"github.com/pchchv/goip/address_string"
)
const DivIntSize = 64
var (
// Wildcards are different, here we only use the range, since the div size is not implicit.
octalParamsDiv = new(address_string.IPStringOptionsBuilder).SetRadix(8).SetSegmentStrPrefix(OctalPrefix).SetWildcards(rangeWildcard).ToOptions()
hexParamsDiv = new(address_string.IPStringOptionsBuilder).SetRadix(16).SetSegmentStrPrefix(HexPrefix).SetWildcards(rangeWildcard).ToOptions()
decimalParamsDiv = new(address_string.IPStringOptionsBuilder).SetRadix(10).SetWildcards(rangeWildcard).ToOptions()
_ divisionValues = &divIntValues{}
)
// DivInt is an integer type for holding generic division values,
// which can be larger than segment values.
type DivInt = uint64
type divIntVals interface {
getDivisionValue() DivInt // gets the lower value for a division.
getUpperDivisionValue() DivInt // gets the upper value for a division.
}
type divderiver interface {
// deriveNew produces a new division with the same bit count as the old,
// but with the new values and prefix length
deriveNew(val, upperVal DivInt, prefLen PrefixLen) divisionValues
// derivePrefixed produces a new division with the same bit count and values as the old,
// but with the new prefix length
derivePrefixed(prefLen PrefixLen) divisionValues
}
type addressDivisionInternal struct {
addressDivisionBase
}
func (div *addressDivisionInternal) isPrefixed() bool {
return div.getDivisionPrefixLength() != nil
}
func (div *addressDivisionInternal) getDivisionValue() DivInt {
vals := div.divisionValues
if vals == nil {
return 0
}
return vals.getDivisionValue()
}
func (div *addressDivisionInternal) getUpperDivisionValue() DivInt {
vals := div.divisionValues
if vals == nil {
return 0
}
return vals.getUpperDivisionValue()
}
func (div *addressDivisionInternal) matches(value DivInt) bool {
return !div.isMultiple() && value == div.getDivisionValue()
}
func (div *addressDivisionInternal) matchesWithMask(value, mask DivInt) bool {
if div.isMultiple() {
// make sure that any of the bits that can change from value to upperValue are masked out (zeroed) by the mask
// in other words, when masking, it is necessary that all values represented by this segment to become just a single value
diffBits := div.getDivisionValue() ^ div.getUpperDivisionValue()
leadingZeros := bits.LeadingZeros64(diffBits)
// bits that can be changed are all bits following the first leadingZero bits, all subsequent bits must be zeroed by the mask
fullMask := ^DivInt(0) >> uint(leadingZeros)
if (fullMask & mask) != 0 {
return false
} // else know that the mask zeros out all bits that can change from value to upperValue, so now just compare with either one
}
return value == (div.getDivisionValue() & mask)
}
func (div *addressDivisionInternal) matchesIPSegment() bool {
return div.divisionValues == nil || div.getAddrType().isIP()
}
func (div *addressDivisionInternal) matchesIPv4Segment() bool {
// init() methods ensure that even segments with zero IPv4 (IPv4Segment{}) have an IPv4 address type
return div.divisionValues != nil && div.getAddrType().isIPv4()
}
func (div *addressDivisionInternal) matchesIPv6Segment() bool {
// init() methods ensure that even zero IPv6 segments (IPv6Segment{}) are of IPv6 address type
return div.divisionValues != nil && div.getAddrType().isIPv6()
}
func (div *addressDivisionInternal) matchesMACSegment() bool {
// init() methods ensure that even zero MAC segments (MACSegment{}) are of the addr MAC type
return div.divisionValues != nil && div.getAddrType().isMAC()
}
// getDefaultRangeSeparatorString is a wildcard string that will be used when producing default strings with getString() or getWildcardString().
// Since no parameters are provided for the string, default settings are used, but they must match the address.
// For example, generally '-' is used as a range separator, but in some cases this character is used to segment separator.
// Note that this only applies to the 'default' settings, there are additional string methods that allow to specify these delimiter characters.
// These methods must be aware of the default settings, to know when they can defer to the defaults and when they cannot.
func (div *addressDivisionInternal) getDefaultRangeSeparatorString() string {
return "-"
}
func (div *addressDivisionInternal) toAddressDivision() *AddressDivision {
return (*AddressDivision)(unsafe.Pointer(div))
}
// GetBitCount returns the number of bits in each value comprising this address item.
func (div *addressDivisionInternal) GetBitCount() BitCount {
return div.addressDivisionBase.GetBitCount()
}
// isPrefixBlockVals returns whether the division range includes the block of values for its prefix length.
func (div *addressDivisionInternal) isPrefixBlockVals(divisionValue, upperValue DivInt, divisionPrefixLen BitCount) bool {
return isPrefixBlockVals(divisionValue, upperValue, divisionPrefixLen, div.GetBitCount())
}
// ContainsPrefixBlock returns whether the division range includes the block of values for the given prefix length.
func (div *addressDivisionInternal) ContainsPrefixBlock(prefixLen BitCount) bool {
return div.isPrefixBlockVals(div.getDivisionValue(), div.getUpperDivisionValue(), prefixLen)
}
func (div *addressDivisionInternal) toNetworkDivision(divPrefixLength PrefixLen, withPrefixLength bool) *AddressDivision {
vals := div.divisionValues
if vals == nil {
return div.toAddressDivision()
}
var newLower, newUpper DivInt
lower := div.getDivisionValue()
upper := div.getUpperDivisionValue()
hasPrefLen := divPrefixLength != nil
if hasPrefLen {
prefBits := divPrefixLength.bitCount()
bitCount := div.GetBitCount()
prefBits = checkBitCount(prefBits, bitCount)
mask := ^DivInt(0) << uint(bitCount-prefBits)
newLower = lower & mask
newUpper = upper | ^mask
if !withPrefixLength {
divPrefixLength = nil
}
if divsSame(divPrefixLength, div.getDivisionPrefixLength(), newLower, lower, newUpper, upper) {
return div.toAddressDivision()
}
} else {
divPrefixLength = nil
if div.getDivisionPrefixLength() == nil {
return div.toAddressDivision()
}
}
newVals := div.deriveNew(newLower, newUpper, divPrefixLength)
return createAddressDivision(newVals)
}
func (div *addressDivisionInternal) toPrefixedNetworkDivision(divPrefixLength PrefixLen) *AddressDivision {
return div.toNetworkDivision(divPrefixLength, true)
}
// containsPrefixBlock returns whether the division range includes a value block for a given prefix length.
func (div *addressDivisionInternal) containsPrefixBlock(divisionPrefixLen BitCount) bool {
return div.isPrefixBlockVals(div.getDivisionValue(), div.getUpperDivisionValue(), divisionPrefixLen)
}
// isPrefixBlock returns whether the division range includes a value block for the prefix length of the division,
// or false if the division has no prefix length.
func (div *addressDivisionInternal) isPrefixBlock() bool {
prefLen := div.getDivisionPrefixLength()
return prefLen != nil && div.containsPrefixBlock(prefLen.bitCount())
}
func (div *addressDivisionInternal) toHostDivision(divPrefixLength PrefixLen, withPrefixLength bool) *AddressDivision {
vals := div.divisionValues
if vals == nil {
return div.toAddressDivision()
}
var mask SegInt
lower := div.getDivisionValue()
upper := div.getUpperDivisionValue()
hasPrefLen := divPrefixLength != nil
if hasPrefLen {
prefBits := divPrefixLength.bitCount()
bitCount := div.GetBitCount()
prefBits = checkBitCount(prefBits, bitCount)
mask = ^(^SegInt(0) << uint(bitCount-prefBits))
}
divMask := uint64(mask)
maxVal := uint64(^SegInt(0))
masker := MaskRange(lower, upper, divMask, maxVal)
newLower, newUpper := masker.GetMaskedLower(lower, divMask), masker.GetMaskedUpper(upper, divMask)
if !withPrefixLength {
divPrefixLength = nil
}
if divsSame(divPrefixLength, div.getDivisionPrefixLength(), newLower, lower, newUpper, upper) {
return div.toAddressDivision()
}
newVals := div.deriveNew(newLower, newUpper, divPrefixLength)
return createAddressDivision(newVals)
}
func (div *addressDivisionInternal) toPrefixedHostDivision(divPrefixLength PrefixLen) *AddressDivision {
return div.toHostDivision(divPrefixLength, true)
}
// getDefaultTextualRadix returns the default radix for textual representations of addresses (10 for IPv4, 16 for IPv6, MAC and other).
func (div *addressDivisionInternal) getDefaultTextualRadix() int {
addrType := div.getAddrType()
if addrType.isIPv4() {
return IPv4DefaultTextualRadix
}
return 16
}
func (div *addressDivisionInternal) getMaxValue() DivInt {
return ^(^DivInt(0) << uint(div.GetBitCount()))
}
func (div *addressDivisionInternal) getMaxDigitCountRadix(radix int) int {
return getMaxDigitCount(radix, div.GetBitCount(), div.getMaxValue())
}
// getMaxDigitCount returns the number of digits for the maximum possible value of the division when using the default radix
func (div *addressDivisionInternal) getMaxDigitCount() int {
return div.getMaxDigitCountRadix(div.getDefaultTextualRadix())
}
// isSinglePrefix returns whether the given range from divisionValue to upperValue is equivalent to the segmentValue range with the divisionPrefixLen prefix.
func (div *addressDivisionInternal) isSinglePrefix(divisionValue, upperValue DivInt, divisionPrefixLen BitCount) bool {
bitCount := div.GetBitCount()
divisionPrefixLen = checkBitCount(divisionPrefixLen, bitCount)
shift := uint(bitCount - divisionPrefixLen)
return (divisionValue >> shift) == (upperValue >> shift)
}
// IsSinglePrefix returns true if the division value range covers only single prefix value for a given prefix length.
func (div *addressDivisionInternal) IsSinglePrefix(divisionPrefixLength BitCount) bool {
return div.isSinglePrefix(div.getDivisionValue(), div.getUpperDivisionValue(), divisionPrefixLength)
}
func (div *addressDivisionInternal) adjustLeadingZeroCount(leadingZeroCount int, value DivInt, radix int) int {
if leadingZeroCount < 0 {
width := getDigitCount(value, radix)
num := div.getMaxDigitCountRadix(radix) - width
if num < 0 {
return 0
}
return num
}
return leadingZeroCount
}
// If leadingZeroCount is -1, returns the number of leading zeros for the maximum width, based on the width of the value.
func (div *addressDivisionInternal) adjustLowerLeadingZeroCount(leadingZeroCount int, radix int) int {
return div.adjustLeadingZeroCount(leadingZeroCount, div.getDivisionValue(), radix)
}
// If leadingZeroCount is -1, returns the number of leading zeros for the maximum width, based on the width of the value.
func (div *addressDivisionInternal) adjustUpperLeadingZeroCount(leadingZeroCount int, radix int) int {
return div.adjustLeadingZeroCount(leadingZeroCount, div.getUpperDivisionValue(), radix)
}
// isSinglePrefixBlock returns whether the given range from divisionValue to upperValue is equivalent to the segmentValue range with the divisionPrefixLen prefix.
func (div *addressDivisionInternal) isSinglePrefixBlock(divisionValue, upperValue DivInt, divisionPrefixLen BitCount) bool {
if divisionPrefixLen == 0 {
return divisionValue == 0 && upperValue == div.getMaxValue()
}
bitCount := div.GetBitCount()
ones := ^DivInt(0)
divisionBitMask := ^(ones << uint(bitCount))
divisionPrefixMask := ones << uint(bitCount-divisionPrefixLen)
divisionHostMask := ^divisionPrefixMask
return testRange(divisionValue, divisionValue, upperValue, divisionPrefixMask&divisionBitMask, divisionHostMask)
}
// matchesWithMask returns whether masking with a given mask results in a valid contiguous range for the given segment,
// and if so, whether the result matches the range from lowerValue to upperValue.
func (div *addressDivisionInternal) matchesValsWithMask(lowerValue, upperValue, mask DivInt) bool {
if lowerValue == upperValue {
return div.matchesWithMask(lowerValue, mask)
}
if !div.isMultiple() {
// the values to match, lowerValue and upperValue, do not match, so you cannot match these two values with the same value from this segment
return false
}
thisValue := div.getDivisionValue()
thisUpperValue := div.getUpperDivisionValue()
masker := MaskRange(thisValue, thisUpperValue, mask, div.getMaxValue())
if !masker.IsSequential() {
return false
}
return lowerValue == masker.GetMaskedLower(thisValue, mask) && upperValue == masker.GetMaskedUpper(thisUpperValue, mask)
}
func (div *addressDivisionInternal) toPrefixedDivision(divPrefixLength PrefixLen) *AddressDivision {
hasPrefLen := divPrefixLength != nil
bitCount := div.GetBitCount()
if hasPrefLen {
prefBits := divPrefixLength.bitCount()
prefBits = checkBitCount(prefBits, bitCount)
if div.isPrefixed() && prefBits == div.getDivisionPrefixLength().bitCount() {
return div.toAddressDivision()
}
} else {
return div.toAddressDivision()
}
lower := div.getDivisionValue()
upper := div.getUpperDivisionValue()
newVals := div.deriveNew(lower, upper, divPrefixLength)
return createAddressDivision(newVals)
}
func (div *addressDivisionInternal) getCount() *big.Int {
if !div.isMultiple() {
return bigOne()
}
if div.IsFullRange() {
res := bigZero()
return res.SetUint64(0xffffffffffffffff).Add(res, bigOneConst())
}
return bigZero().SetUint64((div.getUpperDivisionValue() - div.getDivisionValue()) + 1)
}
// GetPrefixCountLen returns the number of distinct prefixes in the division value range for a given prefix length.
func (div *addressDivisionInternal) GetPrefixCountLen(divisionPrefixLength BitCount) *big.Int {
if div.IsFullRange() {
return bigZero().Add(bigOneConst(), bigZero().SetUint64(div.getMaxValue()))
}
bitCount := div.GetBitCount()
divisionPrefixLength = checkBitCount(divisionPrefixLength, bitCount)
shiftAdjustment := bitCount - divisionPrefixLength
count := ((div.getUpperDivisionValue() >> uint(shiftAdjustment)) - (div.getDivisionValue() >> uint(shiftAdjustment))) + 1
return bigZero().SetUint64(count)
}
func (div *addressDivisionInternal) matchesSegment() bool {
return div.GetBitCount() <= SegIntSize
}
// A simple string using just the lower value and the default radix.
func (div *addressDivisionInternal) getDefaultLowerString() string {
return toDefaultString(div.getDivisionValue(), div.getDefaultTextualRadix())
}
func (div *addressDivisionInternal) getStringFromStringer(stringer func() string) string {
if div.divisionValues != nil {
if cache := div.getCache(); cache != nil {
return cacheStr(&cache.cachedString, stringer)
}
}
return stringer()
}
// A simple string using just the lower and upper values and the default radix, separated by the default range character.
func (div *addressDivisionInternal) getDefaultRangeString() string {
return div.getDefaultRangeStringVals(div.getDivisionValue(), div.getUpperDivisionValue(), div.getDefaultTextualRadix())
}
func (div *addressDivisionInternal) getDivString() string {
if !div.isMultiple() {
return div.getStringFromStringer(div.getDefaultLowerString)
} else {
return div.getStringFromStringer(div.getDefaultRangeString)
}
}
func (div *addressDivisionInternal) getWildcardString() string {
if seg := div.toAddressDivision().ToIP(); seg != nil {
return seg.GetWildcardString()
}
return div.getDivString() // same string as GetString() when not an IP segment
}
func (div *addressDivisionInternal) getLowerString(radix int, uppercase bool, appendable *strings.Builder) {
toUnsignedStringCased(div.getDivisionValue(), radix, 0, uppercase, appendable)
}
func (div *addressDivisionInternal) getLowerStringLength(radix int) int {
return toUnsignedStringLength(div.getDivisionValue(), radix)
}
func (div *addressDivisionInternal) getLowerStringChopped(radix int, choppedDigits int, uppercase bool, appendable *strings.Builder) {
toUnsignedStringCased(div.getDivisionValue(), radix, choppedDigits, uppercase, appendable)
}
// 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 this way, then this method returns the same value as GetPrefixLenForSingleBlock.
//
// There may be a single prefix, or multiple possible prefix values in this item for the returned prefix length.
// Use GetPrefixLenForSingleBlock to avoid the case of multiple prefix values.
//
// If this division represents a single value, this returns the bit count.
func (div *addressDivisionInternal) GetMinPrefixLenForBlock() BitCount {
return getMinPrefixLenForBlock(div.getDivisionValue(), div.getUpperDivisionValue(), div.GetBitCount())
}
func (div *addressDivisionInternal) getUpperString(radix int, uppercase bool, appendable *strings.Builder) {
toUnsignedStringCased(div.getUpperDivisionValue(), radix, 0, uppercase, appendable)
}
func (div *addressDivisionInternal) getUpperStringLength(radix int) int {
return toUnsignedStringLength(div.getUpperDivisionValue(), radix)
}
func (div *addressDivisionInternal) toAddressSegment() *AddressSegment {
if div.matchesSegment() {
return (*AddressSegment)(unsafe.Pointer(div))
}
return nil
}
func (div *addressDivisionInternal) getStringAsLower() string {
if seg := div.toAddressDivision().ToIP(); seg != nil {
return seg.getStringAsLower()
}
return div.getStringFromStringer(div.getDefaultLowerString)
}
func (div *addressDivisionInternal) getUpperStringMasked(radix int, uppercase bool, appendable *strings.Builder) {
if seg := div.toAddressDivision().ToIP(); seg != nil {
seg.getUpperStringMasked(radix, uppercase, appendable)
} else if div.isPrefixed() {
upperValue := div.getUpperDivisionValue()
mask := ^DivInt(0) << uint(div.GetBitCount()-div.getDivisionPrefixLength().bitCount())
upperValue &= mask
toUnsignedStringCased(upperValue, radix, 0, uppercase, appendable)
} else {
div.getUpperString(radix, uppercase, appendable)
}
}
func (div *addressDivisionInternal) getSplitLowerString(radix int, choppedDigits int, uppercase bool,
splitDigitSeparator byte, reverseSplitDigits bool, stringPrefix string, appendable *strings.Builder) {
toSplitUnsignedString(div.getDivisionValue(), radix, choppedDigits, uppercase, splitDigitSeparator, reverseSplitDigits, stringPrefix, appendable)
}
func (div *addressDivisionInternal) getSplitRangeString(rangeSeparator string, wildcard string, radix int, uppercase bool,
splitDigitSeparator byte, reverseSplitDigits bool, stringPrefix string, appendable *strings.Builder) address_error.IncompatibleAddressError {
return toUnsignedSplitRangeString(
div.getDivisionValue(),
div.getUpperDivisionValue(),
rangeSeparator,
wildcard,
radix,
uppercase,
splitDigitSeparator,
reverseSplitDigits,
stringPrefix,
appendable)
}
func (div *addressDivisionInternal) getSplitRangeStringLength(rangeSeparator string, wildcard string, leadingZeroCount int, radix int, uppercase bool,
splitDigitSeparator byte, reverseSplitDigits bool, stringPrefix string) int {
return toUnsignedSplitRangeStringLength(
div.getDivisionValue(),
div.getUpperDivisionValue(),
rangeSeparator,
wildcard,
leadingZeroCount,
radix,
uppercase,
splitDigitSeparator,
reverseSplitDigits,
stringPrefix)
}
func (div *addressDivisionInternal) getDigitCount(radix int) int {
// optimization - just get the string, which is cached, which speeds up further calls to this or getString()
if !div.isMultiple() && radix == div.getDefaultTextualRadix() {
return len(div.getWildcardString())
}
return getDigitCount(div.getUpperDivisionValue(), radix)
}
// getDefaultSegmentWildcardString() is the wildcard string to be used when producing
// the default strings with getString() or getWildcardString()
//
// Since no parameters for the string are provided,
// default settings are used, but they must be consistent with the address.
//
// For instance, generally the '*' is used as a wildcard to denote all possible values for a given segment,
// but in some cases that character is used for a segment separator.
//
// Note that this only applies to "default" settings,
// there are additional string methods that allow you to specify these separator characters.
// Those methods must be aware of the defaults as well,
// to know when they can defer to the defaults and when they cannot.
func (div *addressDivisionInternal) getDefaultSegmentWildcardString() string {
if seg := div.toAddressDivision().ToSegmentBase(); seg != nil {
return seg.getDefaultSegmentWildcardString()
}
return "" // for divisions, the width is variable and max values can change, so using wildcards make no sense
}
// GetByteCount returns the number of bytes required for each value comprising this address item,
// rounding up if the bit count is not a multiple of 8.
func (div *addressDivisionInternal) GetByteCount() int {
return div.addressDivisionBase.GetByteCount()
}
// GetValue returns the lowest value in the address division range as a big integer.
func (div *addressDivisionInternal) GetValue() *BigDivInt {
return div.addressDivisionBase.GetValue()
}
// GetUpperValue returns the highest value in the address division range as a big integer.
func (div *addressDivisionInternal) GetUpperValue() *BigDivInt {
return div.addressDivisionBase.GetUpperValue()
}
// Bytes returns the lowest value in the address division range as a byte slice.
func (div *addressDivisionInternal) Bytes() []byte {
return div.addressDivisionBase.Bytes()
}
// UpperBytes returns the highest value in the address division range as a byte slice.
func (div *addressDivisionInternal) UpperBytes() []byte {
return div.addressDivisionBase.UpperBytes()
}
// CopyBytes copies the lowest value in the address division range into a byte slice.
//
// If the value can fit in the given slice,
// the value is copied into that slice and a length-adjusted sub-slice is returned.
// Otherwise, a new slice is created and returned with the value.
func (div *addressDivisionInternal) CopyBytes(bytes []byte) []byte {
return div.addressDivisionBase.CopyBytes(bytes)
}
// CopyUpperBytes copies the highest value in the address division range into a byte slice.
//
// If the value can fit in the given slice,
// the value is copied into that slice and a length-adjusted sub-slice is returned.
// Otherwise, a new slice is created and returned with the value.
func (div *addressDivisionInternal) CopyUpperBytes(bytes []byte) []byte {
return div.addressDivisionBase.CopyUpperBytes(bytes)
}
// IsZero returns whether this division matches exactly the value of zero.
func (div *addressDivisionInternal) IsZero() bool {
return div.addressDivisionBase.IsZero()
}
// IncludesZero returns whether this item includes the value of zero within its range.
func (div *addressDivisionInternal) IncludesZero() bool {
return div.addressDivisionBase.IncludesZero()
}
// IsMax returns whether this division matches exactly the maximum possible value, the value whose bits are all ones.
func (div *addressDivisionInternal) IsMax() bool {
return div.addressDivisionBase.IsMax()
}
// IncludesMax returns whether this division includes the max value, the value whose bits are all ones, within its range.
func (div *addressDivisionInternal) IncludesMax() bool {
return div.addressDivisionBase.IncludesMax()
}
// IsFullRange returns whether the division range includes all possible values for its bit length.
//
// This is true if and only if both IncludesZero and IncludesMax return true.
func (div *addressDivisionInternal) IsFullRange() bool {
return div.addressDivisionBase.IsFullRange()
}
// GetPrefixLenForSingleBlock returns a prefix length for which there is only one prefix in this division,
// and the range of values in this division matches the block of all values for that prefix.
//
// If the range of division values can be described this way, then this method returns the same value as GetMinPrefixLenForBlock.
//
// If no such prefix length exists, returns nil.
//
// If this division represents a single value, this returns the bit count of the segment.
func (div *addressDivisionInternal) GetPrefixLenForSingleBlock() PrefixLen {
return getPrefixLenForSingleBlock(div.getDivisionValue(), div.getUpperDivisionValue(), div.GetBitCount())
}
// 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 *addressDivisionInternal) ContainsSinglePrefixBlock(prefixLen BitCount) bool {
prefixLen = checkDiv(div.toAddressDivision(), prefixLen)
return div.isSinglePrefixBlock(div.getDivisionValue(), div.getUpperDivisionValue(), prefixLen)
}
// 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 *addressDivisionInternal) 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.toAddressDivision())
}
// 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 addressDivisionInternal) 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.getDivisionValue(), div.getUpperDivisionValue())))
} else {
_, _ = state.Write([]byte(fmt.Sprintf(formatStr, div.getDivisionValue())))
}
}
// String produces a string that is useful when a division string is provided with no context.
// If the division was originally constructed as an address segment,
// uses the default radix for that segment, which is decimal for IPv4 and hexadecimal for IPv6, MAC or other.
// 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 *addressDivisionInternal) String() string {
return div.toString()
}
func (div *addressDivisionInternal) compareSize(other AddressItem) int {
return compareCount(div.toAddressDivision(), other)
}
func (div *addressDivisionInternal) toStringOpts(opts address_string.StringOptions) string {
return toStringOpts(opts, div.toAddressDivision())
}
func (div *addressDivisionInternal) getRangeDigitCount(radix int) int {
if !div.isMultiple() {
return 0
}
if radix == 16 {
prefix := div.GetMinPrefixLenForBlock()
bitCount := div.GetBitCount()
if prefix < bitCount && div.ContainsSinglePrefixBlock(prefix) {
bitsPerCharacter := BitCount(4)
if prefix%bitsPerCharacter == 0 {
return int((bitCount - prefix) / bitsPerCharacter)
}
}
return 0
}
value := div.getDivisionValue()
upperValue := div.getUpperDivisionValue()
maxValue := div.getMaxValue()
factorRadix := DivInt(radix)
factor := factorRadix
numDigits := 1
for {
lowerRemainder := value % factor
if lowerRemainder == 0 {
// Consider in ipv4 the segment 24_
// what does this mean? It means 240 to 249 (not 240 to 245)
// Consider 25_. It means 250-255.
// so the last digit ranges between 0-5 or 0-9 depending on whether the front matches the max possible front of 25.
// If the front matches, the back ranges from 0 to the highest value of 255.
// if the front does not match, the back must range across all values for the radix (0-9)
var max DivInt
if maxValue/factor == upperValue/factor {
max = maxValue % factor
} else {
max = factor - 1
}
upperRemainder := upperValue % factor
if upperRemainder == max {
// whatever range there is must be accounted entirely by range digits, otherwise the range digits is 0
// so here we check if that is the case
if upperValue-upperRemainder == value {
return numDigits
} else {
numDigits++
factor *= factorRadix
continue
}
}
}
return 0
}
}
func (div *addressDivisionInternal) getDefaultRangeStringVals(val1, val2 uint64, radix int) string {
return getDefaultRangeStringVals(div, val1, val2, radix)
}
func (div *addressDivisionInternal) buildDefaultRangeString(radix int) string {
return buildDefaultRangeString(div, radix)
}
func (div *addressDivisionInternal) getString() string {
if seg := div.toAddressDivision().ToIP(); seg != nil {
return seg.GetString()
}
return div.getDivString()
}
// divIntValues are used by AddressDivision.
type divIntValues struct {
bitCount BitCount
value DivInt
upperValue DivInt
prefLen PrefixLen
cache divCache
}
func (div *divIntValues) getBitCount() BitCount {
return div.bitCount
}
func (div *divIntValues) getByteCount() int {
return (int(div.getBitCount()) + 7) >> 3
}
func (div *divIntValues) getDivisionPrefixLength() PrefixLen {
return div.prefLen
}
func (div *divIntValues) getValue() *BigDivInt {
return big.NewInt(int64(div.value))
}
func (div *divIntValues) getUpperValue() *BigDivInt {
return big.NewInt(int64(div.upperValue))
}
func (div *divIntValues) includesZero() bool {
return div.value == 0
}
func (div *divIntValues) includesMax() bool {
return div.upperValue == ^((^DivInt(0)) << uint(div.getBitCount()))
}
func (div *divIntValues) isMultiple() bool {
return div.value != div.upperValue
}
func (div *divIntValues) getCount() *big.Int {
res := new(big.Int)
return res.SetUint64(uint64(div.upperValue-div.value)).Add(res, bigOneConst())
}
func (div *divIntValues) getCache() *divCache {
return &div.cache
}
func (div *divIntValues) getAddrType() addrType {
return zeroType
}
func (div *divIntValues) getDivisionValue() DivInt {
return div.value
}
func (div *divIntValues) getUpperDivisionValue() DivInt {
return div.upperValue
}
func (div *divIntValues) getSegmentValue() SegInt {
return SegInt(div.value)
}
func (div *divIntValues) getUpperSegmentValue() SegInt {
return SegInt(div.upperValue)
}
func (div *divIntValues) deriveNew(val, upperVal DivInt, prefLen PrefixLen) divisionValues {
return newDivValuesUnchecked(val, upperVal, prefLen, div.bitCount)
}
func (div *divIntValues) derivePrefixed(prefLen PrefixLen) divisionValues {
return newDivValuesUnchecked(div.value, div.upperValue, prefLen, div.bitCount)
}
func (div *divIntValues) deriveNewMultiSeg(val, upperVal SegInt, prefLen PrefixLen) divisionValues {
return newDivValuesUnchecked(DivInt(val), DivInt(upperVal), prefLen, div.bitCount)
}
func (div *divIntValues) deriveNewSeg(val SegInt, prefLen PrefixLen) divisionValues {
value := DivInt(val)
return newDivValuesUnchecked(value, value, prefLen, div.bitCount)
}
func (div *divIntValues) calcBytesInternal() (bytes, upperBytes []byte) {
return calcBytesInternal(div.getByteCount(), div.getDivisionValue(), div.getUpperDivisionValue())
}
func (div *divIntValues) bytesInternal(upper bool) []byte {
if upper {
return calcSingleBytes(div.getByteCount(), div.getUpperDivisionValue())
}
return calcSingleBytes(div.getByteCount(), div.getDivisionValue())
}
// AddressDivision represents an arbitrary division in an address or grouping of address divisions.
// It can contain a single value or a range of sequential values and has an assigned bit length.
// Like all address components, it is immutable.
// Divisions that have been converted from IPv4, IPv6, or MAC segments can be converted back to segments of the same type and version.
// Divisions that have not been converted from IPv4, IPv6 or MAC cannot be converted to segments.
type AddressDivision struct {
addressDivisionInternal
}
// GetDivisionValue returns the lower division value in the range.
func (div *AddressDivision) GetDivisionValue() DivInt {
return div.getDivisionValue()
}
// GetUpperDivisionValue returns the upper division value in the range.
func (div *AddressDivision) GetUpperDivisionValue() DivInt {
return div.getUpperDivisionValue()
}
// IsMultiple returns whether the given division represents a sequential range of values rather than a single value.
func (div *AddressDivision) IsMultiple() bool {
return div != nil && div.isMultiple()
}
// GetCount returns a count of possible distinct values for this division.
// If no multiple values are represented, the counter is 1.
// For instance, a division with a value range of 3-7 has a count 5.
// Use IsMultiple if you just want to know if the counter is greater than 1.
func (div *AddressDivision) GetCount() *big.Int {
if div == nil {
return bigZero()
}
return div.getCount()
}
// Matches returns true if the division range matches the given single value.
func (div *AddressDivision) Matches(value DivInt) bool {
return div.matches(value)
}
// MatchesWithMask applies a mask to a this division and then compares the result to the given value,
// returning true if the range of the resulting division matches that single value.
func (div *AddressDivision) MatchesWithMask(value, mask DivInt) bool {
return div.matchesWithMask(value, mask)
}
// IsIP returns true if this division occurred as an IPv4 or IPv6 segment, or an implicitly zero-valued IP segment.
// If so, use ToIP to convert back to IP-specific type.
func (div *AddressDivision) IsIP() bool {
return div != nil && div.matchesIPSegment()
}
// IsIPv4 returns true if this division originated as an IPv4 segment.
// If so, use ToIPv4 to convert back to IPv4-specific type.
func (div *AddressDivision) IsIPv4() bool {
return div != nil && div.matchesIPv4Segment()
}
// IsIPv6 returns true if this division occurred as an IPv6 segment.
// If so, use ToIPv6 to convert back to IPv6-specific type.
func (div *AddressDivision) IsIPv6() bool {
return div != nil && div.matchesIPv6Segment()
}
// IsMAC returns true if this division originated as a MAC segment.
// If so, use ToMAC to convert back to the MAC-specific type.
func (div *AddressDivision) IsMAC() bool {
return div != nil && div.matchesMACSegment()
}
// IsSegmentBase returns true if this division originated as an address segment,
// and this can be converted back with ToSegmentBase.
func (div *AddressDivision) IsSegmentBase() bool {
return div != nil && div.matchesSegment()
}
// ToDiv is an identity method.
// ToDiv can be called with a nil receiver, which allows this method to be
// used in a chain with methods that can return a nil pointer.
func (div *AddressDivision) ToDiv() *AddressDivision {
return div
}
// ToSegmentBase converts to an AddressSegment if this division originated as a segment.
// If not, ToSegmentBase returns nil.
//
// ToSegmentBase can be called with a nil receiver,
// enabling you to chain this method with methods that might return a nil pointer.
func (div *AddressDivision) ToSegmentBase() *AddressSegment {
if div.IsSegmentBase() {
return (*AddressSegment)(unsafe.Pointer(div))
}
return nil
}
// ToIPv4 converts to an IPv4AddressSegment if this division originated as an IPv4 segment.
// If not, ToIPv4 returns nil.
//
// ToIPv4 can be called with a nil receiver, enabling you to chain this method with methods that might return a nil pointer.
func (div *AddressDivision) ToIPv4() *IPv4AddressSegment {
if div.IsIPv4() {
return (*IPv4AddressSegment)(unsafe.Pointer(div))
}
return nil
}
// ToIPv6 converts to an IPv6AddressSegment if this division originated as an IPv6 segment.
// If not, ToIPv6 returns nil.
//
// ToIPv6 can be called with a nil receiver, enabling you to chain this method with methods that might return a nil pointer.
func (div *AddressDivision) ToIPv6() *IPv6AddressSegment {
if div.IsIPv6() {
return (*IPv6AddressSegment)(unsafe.Pointer(div))
}
return nil
}
// ToIP converts to an IPAddressSegment if this division originated as an IPv4 or IPv6 segment, or an implicitly zero-valued IP segment.
// If not, ToIP returns nil.
//
// ToIP can be called with a nil receiver, enabling you to chain this method with methods that might return a nil pointer.
func (div *AddressDivision) ToIP() *IPAddressSegment {
if div.IsIP() {
return (*IPAddressSegment)(unsafe.Pointer(div))
}
return nil
}
// 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 *AddressDivision) GetWildcardString() string {
if div == nil {
return nilString()
}
return div.getWildcardString()
}
// CompareSize compares the counts of two items, the number of individual values within.
//
// Rather than calculating counts with GetCount, there can be more efficient ways of determining whether one represents more individual values than another.
//
// CompareSize returns a positive integer if this division has a larger count than the one given, zero if they are the same, or a negative integer if the other has a larger count.
func (div *AddressDivision) CompareSize(other AddressItem) int {
if div == nil {
if isNilItem(other) {
return 0
}
// we have size 0, other has size >= 1
return -1
}
return div.compareSize(other)
}
// GetMaxValue gets the maximum possible value for this type of division, determined by the number of bits.
//
// For the highest range value of this particular segment, use GetUpperDivisionValue.
func (div *AddressDivision) GetMaxValue() DivInt {
return div.getMaxValue()
}
// ToMAC converts to a MACAddressSegment if this division originated as a MAC segment.
// If not, ToMAC returns nil.
//
// ToMAC can be called with a nil receiver,
// enabling you to chain this method with methods that might return a nil pointer.
func (div *AddressDivision) ToMAC() *MACAddressSegment {