-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsection.go
2850 lines (2598 loc) · 104 KB
/
section.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"
"strconv"
"unsafe"
"github.com/pchchv/goip/address_error"
"github.com/pchchv/goip/address_string"
)
var (
hexPrefixedUppercaseParams = new(address_string.StringOptionsBuilder).SetRadix(16).SetHasSeparator(false).SetExpandedSegments(true).SetAddressLabel(HexPrefix).SetUppercase(true).ToOptions()
octal0oPrefixedParams = new(address_string.StringOptionsBuilder).SetRadix(8).SetHasSeparator(false).SetExpandedSegments(true).SetAddressLabel(otherOctalPrefix).ToOptions()
binaryPrefixedParams = new(address_string.StringOptionsBuilder).SetRadix(2).SetHasSeparator(false).SetExpandedSegments(true).SetAddressLabel(BinaryPrefix).ToOptions()
octalPrefixedParams = new(address_string.StringOptionsBuilder).SetRadix(8).SetHasSeparator(false).SetExpandedSegments(true).SetAddressLabel(OctalPrefix).ToOptions()
hexUppercaseParams = new(address_string.StringOptionsBuilder).SetRadix(16).SetHasSeparator(false).SetExpandedSegments(true).SetUppercase(true).ToOptions()
hexPrefixedParams = new(address_string.StringOptionsBuilder).SetRadix(16).SetHasSeparator(false).SetExpandedSegments(true).SetAddressLabel(HexPrefix).ToOptions()
decimalParams = new(address_string.StringOptionsBuilder).SetRadix(10).SetHasSeparator(false).SetExpandedSegments(true).ToOptions()
binaryParams = new(address_string.StringOptionsBuilder).SetRadix(2).SetHasSeparator(false).SetExpandedSegments(true).ToOptions()
octalParams = new(address_string.StringOptionsBuilder).SetRadix(8).SetHasSeparator(false).SetExpandedSegments(true).ToOptions()
hexParams = new(address_string.StringOptionsBuilder).SetRadix(16).SetHasSeparator(false).SetExpandedSegments(true).ToOptions()
zeroSection = createSection(zeroDivs, nil, zeroType)
otherHexPrefix = "0X"
otherOctalPrefix = "0o"
)
type addressSectionInternal struct {
addressDivisionGroupingInternal
}
// GetSegmentCount returns the segment count.
func (section *addressSectionInternal) GetSegmentCount() int {
return section.GetDivisionCount()
}
// GetSegment returns the segment at the given index.
// The first segment is at index 0.
// GetSegment will panic given a negative index or an index matching or larger than the segment count.
func (section *addressSectionInternal) GetSegment(index int) *AddressSegment {
return section.getDivision(index).ToSegmentBase()
}
// Bytes returns the lowest individual address section in this address section as a byte slice.
func (section *addressSectionInternal) Bytes() []byte {
return section.addressDivisionGroupingInternal.Bytes()
}
// GetBitsPerSegment returns the number of bits comprising each segment in this section.
// Segments in the same address section are equal length.
func (section *addressSectionInternal) GetBitsPerSegment() BitCount {
addrType := section.getAddrType()
if addrType.isIPv4() {
return IPv4BitsPerSegment
} else if addrType.isIPv6() {
return IPv6BitsPerSegment
} else if addrType.isMAC() {
return MACBitsPerSegment
}
if section.GetDivisionCount() == 0 {
return 0
}
return section.getDivision(0).GetBitCount()
}
// GetBytesPerSegment returns the number of bytes comprising each segment in this section.
// Segments in the same address section are equal length.
func (section *addressSectionInternal) GetBytesPerSegment() int {
addrType := section.getAddrType()
if addrType.isIPv4() {
return IPv4BytesPerSegment
} else if addrType.isIPv6() {
return IPv6BytesPerSegment
} else if addrType.isMAC() {
return MACBytesPerSegment
}
if section.GetDivisionCount() == 0 {
return 0
}
return section.getDivision(0).GetByteCount()
}
func (section *addressSectionInternal) toAddressSection() *AddressSection {
return (*AddressSection)(unsafe.Pointer(section))
}
func (section *addressSectionInternal) toIPAddressSection() *IPAddressSection {
return section.toAddressSection().ToIP()
}
func (section *addressSectionInternal) toIPv4AddressSection() *IPv4AddressSection {
return section.toAddressSection().ToIPv4()
}
func (section *addressSectionInternal) toIPv6AddressSection() *IPv6AddressSection {
return section.toAddressSection().ToIPv6()
}
func (section *addressSectionInternal) toMACAddressSection() *MACAddressSection {
return section.toAddressSection().ToMAC()
}
func (section *addressSectionInternal) toPrefixBlock() *AddressSection {
prefixLength := section.getPrefixLen()
if prefixLength == nil {
return section.toAddressSection()
}
return section.toPrefixBlockLen(prefixLength.bitCount())
}
func (section *addressSectionInternal) toPrefixBlockLen(prefLen BitCount) *AddressSection {
prefLen = checkSubnet(section, prefLen)
segCount := section.GetSegmentCount()
if segCount == 0 {
return section.toAddressSection()
}
segmentByteCount := section.GetBytesPerSegment()
segmentBitCount := section.GetBitsPerSegment()
existingPrefixLength := section.getPrefixLen()
prefixMatches := existingPrefixLength != nil && existingPrefixLength.bitCount() == prefLen
if prefixMatches {
prefixedSegmentIndex := getHostSegmentIndex(prefLen, segmentByteCount, segmentBitCount)
if prefixedSegmentIndex >= segCount {
return section.toAddressSection()
}
segPrefLength := getPrefixedSegmentPrefixLength(segmentBitCount, prefLen, prefixedSegmentIndex).bitCount()
seg := section.GetSegment(prefixedSegmentIndex)
if seg.containsPrefixBlock(segPrefLength) {
i := prefixedSegmentIndex + 1
for ; i < segCount; i++ {
seg = section.GetSegment(i)
if !seg.IsFullRange() {
break
}
}
if i == segCount {
return section.toAddressSection()
}
}
}
prefixedSegmentIndex := 0
newSegs := createSegmentArray(segCount)
if prefLen > 0 {
prefixedSegmentIndex = getNetworkSegmentIndex(prefLen, segmentByteCount, segmentBitCount)
section.copySubDivisions(0, prefixedSegmentIndex, newSegs)
}
for i := prefixedSegmentIndex; i < segCount; i++ {
segPrefLength := getPrefixedSegmentPrefixLength(segmentBitCount, prefLen, i)
oldSeg := section.getDivision(i)
newSegs[i] = oldSeg.toPrefixedNetworkDivision(segPrefLength)
}
return createSectionMultiple(newSegs, cacheBitCount(prefLen), section.getAddrType(), section.isMultiple() || prefLen < section.GetBitCount())
}
func (section *addressSectionInternal) initImplicitPrefLen(bitsPerSegment BitCount) {
segCount := section.GetSegmentCount()
if segCount != 0 {
for i := segCount - 1; i >= 0; i-- {
segment := section.GetSegment(i)
minPref := segment.GetMinPrefixLenForBlock()
if minPref > 0 {
if minPref != bitsPerSegment || i != segCount-1 {
section.prefixLength = getNetworkPrefixLen(bitsPerSegment, minPref, i)
}
return
}
}
section.prefixLength = cacheBitCount(0)
}
}
func (section *addressSectionInternal) initMultAndImplicitPrefLen(bitsPerSegment BitCount) {
segCount := section.GetSegmentCount()
if segCount != 0 {
isMultiple := false
isBlock := true
for i := segCount - 1; i >= 0; i-- {
segment := section.GetSegment(i)
if isBlock {
minPref := segment.GetMinPrefixLenForBlock()
if minPref > 0 {
if minPref != bitsPerSegment || i != segCount-1 {
section.prefixLength = getNetworkPrefixLen(bitsPerSegment, minPref, i)
}
isBlock = false
if isMultiple { // nothing left to do
return
}
}
}
if !isMultiple && segment.isMultiple() {
isMultiple = true
section.isMult = true
if !isBlock { // nothing left to do
return
}
}
}
if isBlock {
section.prefixLength = cacheBitCount(0)
}
}
}
func (section *addressSectionInternal) createLowestHighestSections() (lower, upper *AddressSection) {
var highSegs []*AddressDivision
segmentCount := section.GetSegmentCount()
lowSegs := createSegmentArray(segmentCount)
if section.isMultiple() {
highSegs = createSegmentArray(segmentCount)
}
for i := 0; i < segmentCount; i++ {
seg := section.GetSegment(i)
lowSegs[i] = seg.GetLower().ToDiv()
if highSegs != nil {
highSegs[i] = seg.GetUpper().ToDiv()
}
}
lower = deriveAddressSection(section.toAddressSection(), lowSegs)
if highSegs == nil {
upper = lower
} else {
upper = deriveAddressSection(section.toAddressSection(), highSegs)
}
return
}
func (section *addressSectionInternal) getLowestHighestSections() (lower, upper *AddressSection) {
if !section.isMultiple() {
lower = section.toAddressSection()
upper = lower
return
}
cache := section.cache
if cache == nil {
return section.createLowestHighestSections()
}
cached := (*groupingCache)(atomicLoadPointer((*unsafe.Pointer)(unsafe.Pointer(&cache.sectionCache))))
if cached == nil {
cached = &groupingCache{}
cached.lower, cached.upper = section.createLowestHighestSections()
dataLoc := (*unsafe.Pointer)(unsafe.Pointer(&cache.sectionCache))
atomicStorePointer(dataLoc, unsafe.Pointer(cached))
}
lower = cached.lower
upper = cached.upper
return
}
func (section *addressSectionInternal) getLower() *AddressSection {
lower, _ := section.getLowestHighestSections()
return lower
}
func (section *addressSectionInternal) getUpper() *AddressSection {
_, upper := section.getLowestHighestSections()
return upper
}
// GetMaxSegmentValue returns the maximum possible segment value for this type of address.
//
// Note this is not the maximum of the range of segment values in this specific address,
// this is the maximum value of any segment for this address type and version, determined by the number of bits per segment.
func (section *addressSectionInternal) GetMaxSegmentValue() SegInt {
addrType := section.getAddrType()
if addrType.isIPv4() {
return IPv4MaxValuePerSegment
} else if addrType.isIPv6() {
return IPv6MaxValuePerSegment
} else if addrType.isMAC() {
return MACMaxValuePerSegment
}
divLen := section.GetDivisionCount()
if divLen == 0 {
return 0
}
return section.GetSegment(0).GetMaxValue()
}
func (section *addressSectionInternal) toBlock(segmentIndex int, lower, upper SegInt) *AddressSection {
segCount := section.GetSegmentCount()
i := segmentIndex
if i < 0 {
i = 0
}
maxSegVal := section.GetMaxSegmentValue()
for ; i < segCount; i++ {
seg := section.GetSegment(segmentIndex)
var lowerVal, upperVal SegInt
if i == segmentIndex {
lowerVal, upperVal = lower, upper
} else {
upperVal = maxSegVal
}
if !segsSame(nil, seg.getDivisionPrefixLength(), lowerVal, seg.GetSegmentValue(), upperVal, seg.GetUpperSegmentValue()) {
newSegs := createSegmentArray(segCount)
section.copySubDivisions(0, i, newSegs)
newSeg := createAddressDivision(seg.deriveNewMultiSeg(lowerVal, upperVal, nil))
newSegs[i] = newSeg
var allSeg *AddressDivision
if j := i + 1; j < segCount {
if i == segmentIndex {
allSeg = createAddressDivision(seg.deriveNewMultiSeg(0, maxSegVal, nil))
} else {
allSeg = newSeg
}
newSegs[j] = allSeg
for j++; j < segCount; j++ {
newSegs[j] = allSeg
}
}
return createSectionMultiple(newSegs, nil, section.getAddrType(),
segmentIndex < segCount-1 || lower != upper)
}
}
return section.toAddressSection()
}
func (section *addressSectionInternal) getAdjustedPrefix(adjustment BitCount) BitCount {
var result BitCount
prefix := section.getPrefixLen()
bitCount := section.GetBitCount()
if prefix == nil {
if adjustment > 0 { // start from 0
if adjustment > bitCount {
result = bitCount
} else {
result = adjustment
}
} else { // start from end
if -adjustment < bitCount {
result = bitCount + adjustment
}
}
} else {
result = prefix.bitCount() + adjustment
if result > bitCount {
result = bitCount
} else if result < 0 {
result = 0
}
}
return result
}
// getSubnetSegments called by methods to adjust/remove/set prefix length, masking methods, zero host and zero network methods
func (section *addressSectionInternal) getSubnetSegments(startIndex int, networkPrefixLength PrefixLen, verifyMask bool, segProducer func(int) *AddressDivision, segmentMaskProducer func(int) SegInt) (res *AddressSection, err address_error.IncompatibleAddressError) {
networkPrefixLength = checkPrefLen(networkPrefixLength, section.GetBitCount())
bitsPerSegment := section.GetBitsPerSegment()
count := section.GetSegmentCount()
for i := startIndex; i < count; i++ {
segmentPrefixLength := getSegmentPrefixLength(bitsPerSegment, networkPrefixLength, i)
seg := segProducer(i)
// note that the mask can represent a range (for example a CIDR mask),
// but we use the lowest value (maskSegment.value) in the range when masking (ie we discard the range)
maskValue := segmentMaskProducer(i)
origValue, origUpperValue := seg.getSegmentValue(), seg.getUpperSegmentValue()
value, upperValue := origValue, origUpperValue
if verifyMask {
mask64 := uint64(maskValue)
val64 := uint64(value)
upperVal64 := uint64(upperValue)
masker := MaskRange(val64, upperVal64, mask64, seg.GetMaxValue())
if !masker.IsSequential() {
err = &incompatibleAddressError{addressError{key: "ipaddress.error.maskMismatch"}}
return
}
value = SegInt(masker.GetMaskedLower(val64, mask64))
upperValue = SegInt(masker.GetMaskedUpper(upperVal64, mask64))
} else {
value &= maskValue
upperValue &= maskValue
}
if !segsSame(segmentPrefixLength, seg.getDivisionPrefixLength(), value, origValue, upperValue, origUpperValue) {
newSegments := createSegmentArray(count)
section.copySubDivisions(0, i, newSegments)
newSegments[i] = createAddressDivision(seg.deriveNewMultiSeg(value, upperValue, segmentPrefixLength))
for i++; i < count; i++ {
segmentPrefixLength = getSegmentPrefixLength(bitsPerSegment, networkPrefixLength, i)
seg = segProducer(i)
maskValue = segmentMaskProducer(i)
origValue, origUpperValue = seg.getSegmentValue(), seg.getUpperSegmentValue()
value, upperValue = origValue, origUpperValue
if verifyMask {
mask64 := uint64(maskValue)
val64 := uint64(value)
upperVal64 := uint64(upperValue)
masker := MaskRange(val64, upperVal64, mask64, seg.GetMaxValue())
if !masker.IsSequential() {
err = &incompatibleAddressError{addressError{key: "ipaddress.error.maskMismatch"}}
return
}
value = SegInt(masker.GetMaskedLower(val64, mask64))
upperValue = SegInt(masker.GetMaskedUpper(upperVal64, mask64))
} else {
value &= maskValue
upperValue &= maskValue
}
if !segsSame(segmentPrefixLength, seg.getDivisionPrefixLength(), value, origValue, upperValue, origUpperValue) {
newSegments[i] = createAddressDivision(seg.deriveNewMultiSeg(value, upperValue, segmentPrefixLength))
} else {
newSegments[i] = seg
}
}
res = deriveAddressSectionPrefLen(section.toAddressSection(), newSegments, networkPrefixLength)
return
}
}
res = section.toAddressSection()
return
}
func (section *addressSectionInternal) setPrefixLength(networkPrefixLength BitCount, withZeros bool) (res *AddressSection, err address_error.IncompatibleAddressError) {
existingPrefixLength := section.getPrefixLen()
if existingPrefixLength != nil && networkPrefixLength == existingPrefixLength.bitCount() {
res = section.toAddressSection()
return
}
var startIndex int
var appliedPrefixLen PrefixLen // purposely nil when there are no segments
var segmentMaskProducer func(int) SegInt
verifyMask := false
segmentCount := section.GetSegmentCount()
if segmentCount != 0 {
maxVal := section.GetMaxSegmentValue()
appliedPrefixLen = cacheBitCount(networkPrefixLength)
var minPrefIndex, maxPrefIndex int
var minPrefLen, maxPrefLen BitCount
bitsPerSegment := section.GetBitsPerSegment()
bytesPerSegment := section.GetBytesPerSegment()
prefIndex := getNetworkSegmentIndex(networkPrefixLength, bytesPerSegment, bitsPerSegment)
if existingPrefixLength != nil {
verifyMask = true
existingPrefLen := existingPrefixLength.bitCount()
existingPrefIndex := getNetworkSegmentIndex(existingPrefLen, bytesPerSegment, bitsPerSegment) // can be -1 if existingPrefLen is 0
if prefIndex > existingPrefIndex {
maxPrefIndex = prefIndex
minPrefIndex = existingPrefIndex
} else {
maxPrefIndex = existingPrefIndex
minPrefIndex = prefIndex
}
if withZeros {
if networkPrefixLength < existingPrefLen {
minPrefLen = networkPrefixLength
maxPrefLen = existingPrefLen
} else {
minPrefLen = existingPrefLen
maxPrefLen = networkPrefixLength
}
startIndex = minPrefIndex
segmentMaskProducer = func(i int) SegInt {
if i >= minPrefIndex {
if i <= maxPrefIndex {
minSegPrefLen := getPrefixedSegmentPrefixLength(bitsPerSegment, minPrefLen, i).bitCount()
minMask := maxVal << uint(bitsPerSegment-minSegPrefLen)
maxSegPrefLen := getPrefixedSegmentPrefixLength(bitsPerSegment, maxPrefLen, i)
if maxSegPrefLen != nil {
maxMask := maxVal << uint(bitsPerSegment-maxSegPrefLen.bitCount())
return minMask | ^maxMask
}
return minMask
}
}
return maxVal
}
} else {
startIndex = minPrefIndex
}
} else {
startIndex = prefIndex
}
if segmentMaskProducer == nil {
segmentMaskProducer = func(i int) SegInt {
return maxVal
}
}
}
if startIndex < 0 {
startIndex = 0
}
return section.getSubnetSegments(
startIndex,
appliedPrefixLen,
verifyMask,
func(i int) *AddressDivision {
return section.getDivision(i)
},
segmentMaskProducer,
)
}
func (section *addressSectionInternal) setPrefixLen(prefixLen BitCount) *AddressSection {
// no zeroing
res, _ := section.setPrefixLength(prefixLen, false)
return res
}
func (section *addressSectionInternal) adjustPrefixLength(adjustment BitCount, withZeros bool) (*AddressSection, address_error.IncompatibleAddressError) {
if adjustment == 0 && section.isPrefixed() {
return section.toAddressSection(), nil
}
prefix := section.getAdjustedPrefix(adjustment)
return section.setPrefixLength(prefix, withZeros)
}
func (section *addressSectionInternal) adjustPrefixLen(adjustment BitCount) *AddressSection {
// no zeroing
res, _ := section.adjustPrefixLength(adjustment, false)
return res
}
func (section *addressSectionInternal) adjustPrefixLenZeroed(adjustment BitCount) (*AddressSection, address_error.IncompatibleAddressError) {
return section.adjustPrefixLength(adjustment, true)
}
func (section *addressSectionInternal) matchesTypeAndCount(other *AddressSection) (matches bool, count int) {
count = section.GetDivisionCount()
if count != other.GetDivisionCount() {
return
} else if section.getAddrType() != other.getAddrType() {
return
}
matches = true
return
}
func (section *addressSectionInternal) sameCountTypeEquals(other *AddressSection) bool {
count := section.GetSegmentCount()
for i := count - 1; i >= 0; i-- {
if !section.GetSegment(i).sameTypeEquals(other.GetSegment(i)) {
return false
}
}
return true
}
func (section *addressSectionInternal) equal(otherT AddressSectionType) bool {
if otherT == nil {
return false
}
other := otherT.ToSectionBase()
if other == nil {
return false
}
matchesStructure, _ := section.matchesTypeAndCount(other)
return matchesStructure && section.sameCountTypeEquals(other)
}
func (section *addressSectionInternal) sameCountTypeContains(other *AddressSection) bool {
count := section.GetSegmentCount()
for i := count - 1; i >= 0; i-- {
if !section.GetSegment(i).sameTypeContains(other.GetSegment(i)) {
return false
}
}
return true
}
// ForEachSegment visits each segment in order from most-significant to least, the most significant with index 0,
// calling the given function for each, terminating early if the function returns true.
// Returns the number of visited segments.
func (section *addressSectionInternal) ForEachSegment(consumer func(segmentIndex int, segment *AddressSegment) (stop bool)) int {
divArray := section.getDivArray()
if divArray != nil {
for i, div := range divArray {
if consumer(i, div.ToSegmentBase()) {
return i + 1
}
}
}
return len(divArray)
}
// GetBitCount returns the number of bits in each value comprising this address item.
func (section *addressSectionInternal) GetBitCount() BitCount {
divLen := section.GetDivisionCount()
if divLen == 0 {
return 0
}
return getSegmentsBitCount(section.getDivision(0).GetBitCount(), section.GetSegmentCount())
}
// GetByteCount returns the number of bytes required for each value comprising this address item.
func (section *addressSectionInternal) GetByteCount() int {
return int((section.GetBitCount() + 7) >> 3)
}
// IsOneBit returns true if the bit in the lower value of this section at the given index is 1,
// where index 0 refers to the most significant bit.
// IsOneBit will panic if bitIndex is less than zero, or if it is larger than the bit count of this item.
func (section *addressSectionInternal) IsOneBit(prefixBitIndex BitCount) bool {
bitsPerSegment := section.GetBitsPerSegment()
bytesPerSegment := section.GetBytesPerSegment()
segment := section.GetSegment(getHostSegmentIndex(prefixBitIndex, bytesPerSegment, bitsPerSegment))
segmentBitIndex := prefixBitIndex % bitsPerSegment
return segment.IsOneBit(segmentBitIndex)
}
// Gets the subsection from the series starting from the given index and ending just before the give endIndex.
// The first segment is at index 0.
func (section *addressSectionInternal) getSubSection(index, endIndex int) *AddressSection {
if index < 0 {
index = 0
}
thisSegmentCount := section.GetSegmentCount()
if endIndex > thisSegmentCount {
endIndex = thisSegmentCount
}
segmentCount := endIndex - index
if segmentCount <= 0 {
if thisSegmentCount == 0 {
return section.toAddressSection()
}
// we do not want an inconsistency where mac zero length can have prefix len zero while ip sections cannot
return zeroSection
}
if index == 0 && endIndex == thisSegmentCount {
return section.toAddressSection()
}
segs := section.getSubDivisions(index, endIndex)
newPrefLen := section.getPrefixLen()
if newPrefLen != nil {
newPrefLen = getAdjustedPrefixLength(section.GetBitsPerSegment(), newPrefLen.bitCount(), index, endIndex)
}
addrType := section.getAddrType()
if !section.isMultiple() {
return createSection(segs, newPrefLen, addrType)
}
return deriveAddressSectionPrefLen(section.toAddressSection(), segs, newPrefLen)
}
// TestBit returns true if the bit in the lower value of this section at the given index is 1, where index 0 refers to the least significant bit.
// In other words, it computes (bits & (1 << n)) != 0), using the lower value of this section.
// TestBit will panic if n < 0, or if it matches or exceeds the bit count of this item.
func (section *addressSectionInternal) TestBit(n BitCount) bool {
return section.IsOneBit(section.GetBitCount() - (n + 1))
}
func (section *addressSectionInternal) withoutPrefixLen() *AddressSection {
if !section.isPrefixed() {
return section.toAddressSection()
}
if sect := section.toIPAddressSection(); sect != nil {
return sect.withoutPrefixLen().ToSectionBase()
}
return createSectionMultiple(section.getDivisionsInternal(), nil, section.getAddrType(), section.isMultiple())
}
func (section *addressSectionInternal) toAboveOrBelow(above bool) *AddressSection {
prefLen := section.GetPrefixLen()
if prefLen == nil {
return section.toAddressSection()
}
prefBits := prefLen.Len()
segmentCount := section.GetSegmentCount()
if prefBits == section.GetBitCount() || segmentCount == 0 {
return section.withoutPrefixLen()
}
segmentByteCount := section.GetBytesPerSegment()
segmentBitCount := section.GetBitsPerSegment()
newSegs := createSegmentArray(segmentCount)
if prefBits > 0 {
networkSegmentIndex := getNetworkSegmentIndex(prefBits, segmentByteCount, segmentBitCount)
section.copySubDivisions(0, networkSegmentIndex, newSegs)
}
hostSegmentIndex := getHostSegmentIndex(prefBits, segmentByteCount, segmentBitCount)
if hostSegmentIndex < segmentCount {
var newVal SegInt
oldSeg := section.getDivision(hostSegmentIndex)
oldVal := oldSeg.getUpperSegmentValue()
segPrefBits := getPrefixedSegmentPrefixLength(segmentBitCount, prefBits, hostSegmentIndex).bitCount()
allOnes := ^SegInt(0)
if above {
hostBits := uint(segmentBitCount - segPrefBits)
networkMask := allOnes << (hostBits - 1)
hostMask := ^(allOnes << hostBits)
newVal = (oldVal | hostMask) & networkMask
} else {
hostBits := uint(segmentBitCount - segPrefBits)
networkMask := allOnes << hostBits
hostMask := ^(allOnes<<hostBits - 1)
newVal = (oldVal & networkMask) | hostMask
}
newSegs[hostSegmentIndex] = createAddressDivision(oldSeg.deriveNewSeg(newVal, nil))
if j := hostSegmentIndex + 1; j < segmentCount {
var endSeg *AddressDivision
if above {
endSeg = createAddressDivision(oldSeg.deriveNewSeg(0, nil))
} else {
maxSegVal := section.GetMaxSegmentValue()
endSeg = createAddressDivision(oldSeg.deriveNewSeg(maxSegVal, nil))
}
newSegs[j] = endSeg
for j++; j < segmentCount; j++ {
newSegs[j] = endSeg
}
}
}
return deriveAddressSectionPrefLen(section.toAddressSection(), newSegs, nil)
}
// toMaxLower returns the address created by converting this address to
// an address with a 0 as the first bit following the prefix,
// followed by all ones to the end, and with the prefix length then removed
// Returns the same address if it has no prefix length.
func (section *addressSectionInternal) toMaxLower() *AddressSection {
return section.toAboveOrBelow(false)
}
// toMinUpper returns the address created by converting this address to
// an address with a 1 as the first bit following the prefix,
// followed by all zeros to the end, and with the prefix length then removed
// Returns the same address if it has no prefix length
func (section *addressSectionInternal) toMinUpper() *AddressSection {
return section.toAboveOrBelow(true)
}
func (section *addressSectionInternal) reverseSegments(segProducer func(int) (*AddressSegment, address_error.IncompatibleAddressError)) (res *AddressSection, err address_error.IncompatibleAddressError) {
count := section.GetSegmentCount()
if count == 0 { // case count == 1 we cannot exit early, we need to apply segProducer to each segment
return section.withoutPrefixLen(), nil
}
i := 0
halfCount := count >> 1
isSame := !section.isPrefixed() // when reversing, the prefix must go
newSegs := createSegmentArray(count)
for j := count - 1; i < halfCount; i, j = i+1, j-1 {
var newj, newi *AddressSegment
if newj, err = segProducer(i); err != nil {
return
}
if newi, err = segProducer(j); err != nil {
return
}
origi := section.GetSegment(i)
origj := section.GetSegment(j)
newSegs[j] = newj.ToDiv()
newSegs[i] = newi.ToDiv()
if isSame &&
!(segValsSame(newi.getSegmentValue(), origi.getSegmentValue(), newi.getUpperSegmentValue(), origi.getUpperSegmentValue()) &&
segValsSame(newj.getSegmentValue(), origj.getSegmentValue(), newj.getUpperSegmentValue(), origj.getUpperSegmentValue())) {
isSame = false
}
}
if (count & 1) == 1 { //the count is odd, handle the middle one
seg := section.getDivision(i)
newSegs[i] = seg // gets segment i without prefix length
}
if isSame {
res = section.toAddressSection()
return
}
res = deriveAddressSectionPrefLen(section.toAddressSection(), newSegs, nil)
return
}
// callers to replace have ensures the component sections have consistent prefix lengths for the replacement
func (section *addressSectionInternal) replace(index, endIndex int, replacement *AddressSection, replacementStartIndex, replacementEndIndex int, prefixLen PrefixLen) *AddressSection {
otherSegmentCount := replacementEndIndex - replacementStartIndex
segmentCount := section.GetSegmentCount()
totalSegmentCount := segmentCount + otherSegmentCount - (endIndex - index)
segs := createSegmentArray(totalSegmentCount)
sect := section.toAddressSection()
sect.copySubDivisions(0, index, segs)
if index < totalSegmentCount {
replacement.copySubDivisions(replacementStartIndex, replacementEndIndex, segs[index:])
if index+otherSegmentCount < totalSegmentCount {
sect.copySubDivisions(endIndex, segmentCount, segs[index+otherSegmentCount:])
}
}
addrType := sect.getAddrType()
if addrType.isZeroSegments() { // zero-length section
addrType = replacement.getAddrType()
}
return createInitializedSection(segs, prefixLen, addrType)
}
func (section *addressSectionInternal) setPrefixLenZeroed(prefixLen BitCount) (*AddressSection, address_error.IncompatibleAddressError) {
return section.setPrefixLength(prefixLen, true)
}
// replaceLen replaces segments starting from startIndex and ending before endIndex with the segments starting at replacementStartIndex and
// ending before replacementEndIndex from the replacement section.
func (section *addressSectionInternal) replaceLen(startIndex, endIndex int, replacement *AddressSection, replacementStartIndex, replacementEndIndex int, segmentToBitsShift uint) *AddressSection {
segmentCount := section.GetSegmentCount()
startIndex, endIndex, replacementStartIndex, replacementEndIndex =
adjustIndices(startIndex, endIndex, segmentCount, replacementStartIndex, replacementEndIndex, replacement.GetSegmentCount())
replacedCount := endIndex - startIndex
replacementCount := replacementEndIndex - replacementStartIndex
// unlike ipvx, sections of zero length with 0 prefix are still considered to be applying their prefix during replacement,
// because you can have zero length prefixes when there are no bits in the section
prefixLength := section.getPrefixLen()
if replacementCount == 0 && replacedCount == 0 {
if prefixLength != nil {
prefLen := prefixLength.bitCount()
if prefLen <= BitCount(startIndex<<segmentToBitsShift) {
return section.toAddressSection()
} else {
replacementPrefisLength := replacement.getPrefixLen()
if replacementPrefisLength == nil {
return section.toAddressSection()
} else if replacementPrefisLength.bitCount() > BitCount(replacementStartIndex<<segmentToBitsShift) {
return section.toAddressSection()
}
}
} else {
replacementPrefisLength := replacement.getPrefixLen()
if replacementPrefisLength == nil {
return section.toAddressSection()
} else if replacementPrefisLength.bitCount() > BitCount(replacementStartIndex<<segmentToBitsShift) {
return section.toAddressSection()
}
}
} else if segmentCount == replacedCount {
if prefixLength == nil || prefixLength.bitCount() > 0 {
return replacement
} else {
replacementPrefisLength := replacement.getPrefixLen()
if replacementPrefisLength != nil && replacementPrefisLength.bitCount() == 0 { // prefix length is 0
return replacement
}
}
}
var newPrefixLength PrefixLen
startBits := BitCount(startIndex << segmentToBitsShift)
if prefixLength != nil && prefixLength.bitCount() <= startBits {
newPrefixLength = prefixLength
} else {
replacementPrefLen := replacement.getPrefixLen()
if replacementPrefLen != nil && replacementPrefLen.bitCount() <= BitCount(replacementEndIndex<<segmentToBitsShift) {
var replacementPrefixLen BitCount
replacementStartBits := BitCount(replacementStartIndex << segmentToBitsShift)
if replacementPrefLen.bitCount() > replacementStartBits {
replacementPrefixLen = replacementPrefLen.bitCount() - replacementStartBits
}
newPrefixLength = cacheBitCount(startBits + replacementPrefixLen)
} else if prefixLength != nil {
replacementBits := BitCount(replacementCount << segmentToBitsShift)
var endPrefixBits BitCount
endIndexBits := BitCount(endIndex << segmentToBitsShift)
if prefixLength.bitCount() > endIndexBits {
endPrefixBits = prefixLength.bitCount() - endIndexBits
}
newPrefixLength = cacheBitCount(startBits + replacementBits + endPrefixBits)
} else {
newPrefixLength = nil
}
}
return section.replace(startIndex, endIndex, replacement, replacementStartIndex, replacementEndIndex, newPrefixLength)
}
// Constructs an equivalent address section with the smallest CIDR prefix possible (largest network),
// such that the range of values are a set of subnet blocks for that prefix.
func (section *addressSectionInternal) assignMinPrefixForBlock() *AddressSection {
return section.setPrefixLen(section.GetMinPrefixLenForBlock())
}
func (section *addressSectionInternal) contains(other AddressSectionType) bool {
if other == nil {
return true
}
otherSection := other.ToSectionBase()
if section.toAddressSection() == otherSection || otherSection == nil {
return true
}
// check if they are comparable first
matches, count := section.matchesTypeAndCount(otherSection)
if !matches {
return false
} else {
for i := count - 1; i >= 0; i-- {
if !section.GetSegment(i).sameTypeContains(otherSection.GetSegment(i)) {
return false
}
}
}
return true
}
func (section *addressSectionInternal) getStringCache() *stringCache {
if section.hasNoDivisions() {
return &zeroStringCache
}
cache := section.cache
if cache == nil {
return nil
}
return &cache.stringCache
}
func (section addressSectionInternal) writeStrFmt(state fmt.State, verb rune, str string, zone Zone) {
var leftPaddingCount, rightPaddingCount int
if precision, hasPrecision := state.Precision(); hasPrecision && len(str) > precision {
str = str[:precision]
}
if verb == 'q' {
if state.Flag('#') && (zone == NoZone || strconv.CanBackquote(string(zone))) {
str = "`" + str + "`"
} else if zone == NoZone {
str = `"` + str + `"`
} else {
str = strconv.Quote(str) // zones should not have special characters, but you cannot be sure
}
}
if width, hasWidth := state.Width(); hasWidth && len(str) < width { // padding required
paddingCount := width - len(str)
if state.Flag('-') {
// right padding with spaces (takes precedence over '0' flag)
rightPaddingCount = paddingCount
} else {
// left padding with spaces
leftPaddingCount = paddingCount
}
}
// left padding/str/right padding
writeBytes(state, ' ', leftPaddingCount)
_, _ = state.Write([]byte(str))
writeBytes(state, ' ', rightPaddingCount)
}
func (section addressSectionInternal) writeNumberFmt(state fmt.State, verb rune, str string, zone Zone) {
var prefix string
if verb == 'O' {
prefix = otherOctalPrefix // "0o"
} else if state.Flag('#') {
switch verb {
case 'x':
prefix = HexPrefix
case 'X':
prefix = otherHexPrefix
case 'b':
prefix = BinaryPrefix
case 'o':
prefix = OctalPrefix
}
}
var separator byte
var address_String, secondStr string
isMulti := section.isMultiple()
if isMulti {
separatorIndex := len(str) >> 1
address_String = str[:separatorIndex]
separator = str[separatorIndex]
secondStr = str[separatorIndex+1:]
} else {
address_String = str
}
precision, hasPrecision := state.Precision()
width, hasWidth := state.Width()
usePrecision := hasPrecision
if section.hasNoDivisions() {
usePrecision = false