-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathip_section.go
2531 lines (2291 loc) · 104 KB
/
ip_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 (
"math/big"
"unsafe"
"github.com/pchchv/goip/address_error"
"github.com/pchchv/goip/address_string"
)
var (
rangeWildcard = new(address_string.WildcardsBuilder).ToWildcards()
allWildcards = new(address_string.WildcardOptionsBuilder).SetWildcardOptions(address_string.WildcardsAll).ToOptions()
wildcardsRangeOnlyNetworkOnly = new(address_string.WildcardOptionsBuilder).SetWildcards(rangeWildcard).ToOptions()
allSQLWildcards = new(address_string.WildcardOptionsBuilder).SetWildcardOptions(address_string.WildcardsAll).SetWildcards(
new(address_string.WildcardsBuilder).SetWildcard(SegmentSqlWildcardStr).SetSingleWildcard(SegmentSqlSingleWildcardStr).ToWildcards()).ToOptions()
)
type ipAddressSectionInternal struct {
addressSectionInternal
}
func (section *ipAddressSectionInternal) getNetworkPrefixLen() PrefixLen {
return section.prefixLength
}
// GetNetworkPrefixLen returns the prefix length or nil if there is no prefix length.
// This is equivalent to GetPrefixLen.
//
// A prefix length indicates the number of bits in the initial part of the address item that make up the prefix.
//
// A prefix is a part of an address item that is not specific to a given address,
// but is common to a group of such items, such as the subnet of a CIDR prefix block.
func (section *ipAddressSectionInternal) GetNetworkPrefixLen() PrefixLen {
return section.getNetworkPrefixLen().copy()
}
// GetBlockMaskPrefixLen returns the prefix length if this address section is equivalent to the mask for a CIDR prefix block.
// Otherwise, it returns nil.
// A CIDR network mask is an address section with all ones in the network section and then all zeros in the host section.
// A CIDR host mask is an address section with all zeros in the network section and then all ones in the host section.
// The prefix length is the bit-length of the network section.
//
// Also, keep in mind that the prefix length returned by this method is not equivalent to the prefix length of this instance,
// indicating the network and host section of this address section.
// The prefix length returned here indicates the whether the value of this address can be used as a mask for the network and host
// section of any other address. Therefore the two values can be different values, or one can be nil while the other is not.
//
// This method applies only to the lower value of the range if this section represents multiple values.
func (section *ipAddressSectionInternal) GetBlockMaskPrefixLen(network bool) PrefixLen {
cache := section.cache
if cache == nil {
return nil // no prefix
}
cachedMaskLens := (*maskLenSetting)(atomicLoadPointer((*unsafe.Pointer)(unsafe.Pointer(&cache.cachedMaskLens))))
if cachedMaskLens == nil {
networkMaskLen, hostMaskLen := section.checkForPrefixMask()
cachedMaskLens = &maskLenSetting{networkMaskLen, hostMaskLen}
dataLoc := (*unsafe.Pointer)(unsafe.Pointer(&cache.cachedMaskLens))
atomicStorePointer(dataLoc, unsafe.Pointer(cachedMaskLens))
}
if network {
return cachedMaskLens.networkMaskLen
}
return cachedMaskLens.hostMaskLen
}
func (section *ipAddressSectionInternal) checkForPrefixMask() (networkMaskLen, hostMaskLen PrefixLen) {
count := section.GetSegmentCount()
if count == 0 {
return
}
firstSeg := section.GetSegment(0)
checkingNetworkFront, checkingHostFront := true, true
var checkingNetworkBack, checkingHostBack bool
var prefixedSeg int
prefixedSegPrefixLen := BitCount(0)
maxVal := firstSeg.GetMaxValue()
for i := 0; i < count; i++ {
seg := section.GetSegment(i)
val := seg.GetSegmentValue()
if val == 0 {
if checkingNetworkFront {
prefixedSeg = i
checkingNetworkFront, checkingNetworkBack = false, true
} else if !checkingHostFront && !checkingNetworkBack {
return
}
checkingHostBack = false
} else if val == maxVal {
if checkingHostFront {
prefixedSeg = i
checkingHostFront, checkingHostBack = false, true
} else if !checkingHostBack && !checkingNetworkFront {
return
}
checkingNetworkBack = false
} else {
segNetworkMaskLen, segHostMaskLen := seg.checkForPrefixMask()
if segNetworkMaskLen != nil {
if checkingNetworkFront {
prefixedSegPrefixLen = segNetworkMaskLen.bitCount()
checkingNetworkBack = true
checkingHostBack = false
prefixedSeg = i
} else {
return
}
} else if segHostMaskLen != nil {
if checkingHostFront {
prefixedSegPrefixLen = segHostMaskLen.bitCount()
checkingHostBack = true
checkingNetworkBack = false
prefixedSeg = i
} else {
return
}
} else {
return
}
checkingNetworkFront, checkingHostFront = false, false
}
}
if checkingNetworkFront {
// all ones
networkMaskLen = cacheBitCount(section.GetBitCount())
hostMaskLen = cacheBitCount(0)
} else if checkingHostFront {
// all zeros
hostMaskLen = cacheBitCount(section.GetBitCount())
networkMaskLen = cacheBitCount(0)
} else if checkingNetworkBack {
// ending in zeros, network mask
networkMaskLen = getNetworkPrefixLen(firstSeg.GetBitCount(), prefixedSegPrefixLen, prefixedSeg)
} else if checkingHostBack {
// ending in ones, host mask
hostMaskLen = getNetworkPrefixLen(firstSeg.GetBitCount(), prefixedSegPrefixLen, prefixedSeg)
}
return
}
// GetBitsPerSegment returns the number of bits comprising each segment in this section. Segments in the same address section are equal length.
func (section *ipAddressSectionInternal) GetBitsPerSegment() BitCount {
return section.addressSectionInternal.GetBitsPerSegment()
}
// GetBytesPerSegment returns the number of bytes comprising each segment in this section. Segments in the same address section are equal length.
func (section *ipAddressSectionInternal) GetBytesPerSegment() int {
return section.addressSectionInternal.GetBytesPerSegment()
}
// 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 *ipAddressSectionInternal) GetSegment(index int) *IPAddressSegment {
return section.getDivision(index).ToIP()
}
// 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 *ipAddressSectionInternal) ForEachSegment(consumer func(segmentIndex int, segment *IPAddressSegment) (stop bool)) int {
divArray := section.getDivArray()
if divArray != nil {
for i, div := range divArray {
if consumer(i, div.ToIP()) {
return i + 1
}
}
}
return len(divArray)
}
// GetIPVersion returns the IP version of this IP address section.
func (section *ipAddressSectionInternal) GetIPVersion() IPVersion {
addrType := section.getAddrType()
if addrType.isIPv4() {
return IPv4
} else if addrType.isIPv6() {
return IPv6
}
return IndeterminateIPVersion
}
// IncludesZeroHostLen returns whether the address section contains an individual section with a host of zero, a section for which all bits past the given prefix length are zero.
func (section *ipAddressSectionInternal) IncludesZeroHostLen(networkPrefixLength BitCount) bool {
networkPrefixLength = checkSubnet(section, networkPrefixLength)
bitsPerSegment := section.GetBitsPerSegment()
bytesPerSegment := section.GetBytesPerSegment()
prefixedSegmentIndex := getHostSegmentIndex(networkPrefixLength, bytesPerSegment, bitsPerSegment)
divCount := section.GetSegmentCount()
for i := prefixedSegmentIndex; i < divCount; i++ {
div := section.GetSegment(i)
segmentPrefixLength := getPrefixedSegmentPrefixLength(bitsPerSegment, networkPrefixLength, i)
mask := div.GetSegmentHostMask(segmentPrefixLength.bitCount())
if (mask & div.GetSegmentValue()) != 0 {
return false
}
for i++; i < divCount; i++ {
div = section.GetSegment(i)
if !div.includesZero() {
return false
}
}
}
return true
}
// IncludesMaxHost returns whether the address section contains an individual address section with a host of all one-bits.
// If the address section has no prefix length it returns false.
// If the prefix length matches the bit count, then it returns true.
//
// Otherwise, it checks whether it contains an individual address section for which all bits past the prefix are one.
func (section *ipAddressSectionInternal) IncludesMaxHost() bool {
networkPrefixLength := section.getPrefixLen()
return networkPrefixLength != nil && section.IncludesMaxHostLen(networkPrefixLength.bitCount())
}
// IncludesMaxHostLen returns whether the address section contains an individual address section with a host of all one-bits,
// an address section for which all bits past the given prefix length are all ones.
func (section *ipAddressSectionInternal) IncludesMaxHostLen(networkPrefixLength BitCount) bool {
networkPrefixLength = checkSubnet(section, networkPrefixLength)
bitsPerSegment := section.GetBitsPerSegment()
bytesPerSegment := section.GetBytesPerSegment()
prefixedSegmentIndex := getHostSegmentIndex(networkPrefixLength, bytesPerSegment, bitsPerSegment)
divCount := section.GetSegmentCount()
for i := prefixedSegmentIndex; i < divCount; i++ {
div := section.GetSegment(i)
segmentPrefixLength := getPrefixedSegmentPrefixLength(bitsPerSegment, networkPrefixLength, i)
if segmentPrefixLength != nil {
mask := div.GetSegmentHostMask(segmentPrefixLength.bitCount())
if (mask & div.getUpperSegmentValue()) != mask {
return false
}
for i++; i < divCount; i++ {
div = section.GetSegment(i)
if !div.includesMax() {
return false
}
}
}
}
return true
}
// IsSingleNetwork returns whether the network section of the address,
// the prefix, consists of a single value.
//
// If it has no prefix length, it returns true if not multiple,
// if it contains only a single individual address section.
func (section *ipAddressSectionInternal) IsSingleNetwork() bool {
networkPrefixLength := section.getNetworkPrefixLen()
if networkPrefixLength == nil {
return !section.isMultiple()
}
prefLen := networkPrefixLength.bitCount()
if prefLen >= section.GetBitCount() {
return !section.isMultiple()
}
bitsPerSegment := section.GetBitsPerSegment()
prefixedSegmentIndex := getNetworkSegmentIndex(prefLen, section.GetBytesPerSegment(), bitsPerSegment)
if prefixedSegmentIndex < 0 {
return true
}
for i := 0; i < prefixedSegmentIndex; i++ {
if section.getDivision(i).isMultiple() {
return false
}
}
div := section.GetSegment(prefixedSegmentIndex)
divPrefLen := getPrefixedSegmentPrefixLength(bitsPerSegment, prefLen, prefixedSegmentIndex)
shift := bitsPerSegment - divPrefLen.bitCount()
return (div.GetSegmentValue() >> uint(shift)) == (div.GetUpperSegmentValue() >> uint(shift))
}
// IsMaxHost returns whether this section has a prefix length and if so,
// whether the host is all all one-bits, the max value, for all individual sections in this address section.
//
// If the host section is zero length (there are zero host bits), IsMaxHost returns true.
func (section *ipAddressSectionInternal) IsMaxHost() bool {
if !section.isPrefixed() {
return false
}
return section.IsMaxHostLen(section.getNetworkPrefixLen().bitCount())
}
// IsMaxHostLen returns whether the host host is all one-bits,
// the max value, for all individual sections in this address section,
// for the given prefix length, the host being the bits following the prefix.
//
// If the host section is zero length (there are zero host bits), IsMaxHostLen returns true.
func (section *ipAddressSectionInternal) IsMaxHostLen(prefLen BitCount) bool {
divCount := section.GetSegmentCount()
if divCount == 0 {
return true
} else if prefLen < 0 {
prefLen = 0
}
bytesPerSegment := section.GetBytesPerSegment()
bitsPerSegment := section.GetBitsPerSegment()
// Note: 1.2.3.4/32 has a max host
prefixedSegmentIndex := getHostSegmentIndex(prefLen, bytesPerSegment, bitsPerSegment)
if prefixedSegmentIndex < divCount {
segmentPrefixLength := getPrefixedSegmentPrefixLength(bitsPerSegment, prefLen, prefixedSegmentIndex)
i := prefixedSegmentIndex
div := section.GetSegment(i)
mask := div.GetSegmentHostMask(segmentPrefixLength.bitCount())
if div.isMultiple() || (mask&div.getSegmentValue()) != mask {
return false
}
i++
for ; i < divCount; i++ {
div = section.GetSegment(i)
if !div.IsMax() {
return false
}
}
}
return true
}
// IsZeroHost returns whether this section has a prefix length and if so,
// whether the host section is always zero for all individual sections in this address section.
//
// If the host section is zero length (there are zero host bits), IsZeroHost returns true.
func (section *ipAddressSectionInternal) IsZeroHost() bool {
if !section.isPrefixed() {
return false
}
return section.IsZeroHostLen(section.getNetworkPrefixLen().bitCount())
}
// IsZeroHostLen returns whether the host section is always zero for all individual sections in this address section,
// for the given prefix length.
//
// If the host section is zero length (there are zero host bits), IsZeroHostLen returns true.
func (section *ipAddressSectionInternal) IsZeroHostLen(prefLen BitCount) bool {
segmentCount := section.GetSegmentCount()
if segmentCount == 0 {
return true
} else if prefLen < 0 {
prefLen = 0
}
bitsPerSegment := section.GetBitsPerSegment()
// Note: 1.2.3.4/32 has a zero host
prefixedSegmentIndex := getHostSegmentIndex(prefLen, section.GetBytesPerSegment(), bitsPerSegment)
if prefixedSegmentIndex < segmentCount {
segmentPrefixLength := getPrefixedSegmentPrefixLength(bitsPerSegment, prefLen, prefixedSegmentIndex)
i := prefixedSegmentIndex
div := section.GetSegment(i)
if div.isMultiple() || (div.GetSegmentHostMask(segmentPrefixLength.bitCount())&div.getSegmentValue()) != 0 {
return false
}
for i++; i < segmentCount; i++ {
div := section.GetSegment(i)
if !div.IsZero() {
return false
}
}
}
return true
}
func (section *ipAddressSectionInternal) adjustPrefixLength(adjustment BitCount, withZeros bool) (*IPAddressSection, address_error.IncompatibleAddressError) {
if adjustment == 0 && section.isPrefixed() {
return section.toIPAddressSection(), nil
}
prefix := section.getAdjustedPrefix(adjustment)
sec, err := section.setPrefixLength(prefix, withZeros)
return sec.ToIP(), err
}
func (section *ipAddressSectionInternal) adjustPrefixLen(adjustment BitCount) *IPAddressSection {
res, _ := section.adjustPrefixLength(adjustment, false)
return res
}
func (section *ipAddressSectionInternal) adjustPrefixLenZeroed(adjustment BitCount) (*IPAddressSection, address_error.IncompatibleAddressError) {
return section.adjustPrefixLength(adjustment, true)
}
func (section *ipAddressSectionInternal) checkSectionCount(other *IPAddressSection) address_error.SizeMismatchError {
if other.GetSegmentCount() < section.GetSegmentCount() {
return &sizeMismatchError{incompatibleAddressError{addressError{key: "ipaddress.error.sizeMismatch"}}}
}
return nil
}
func (section *ipAddressSectionInternal) matchesWithMask(other *IPAddressSection, mask *IPAddressSection) bool {
if err := section.checkSectionCount(other); err != nil {
return false
} else if err := section.checkSectionCount(mask); err != nil {
return false
}
divCount := section.GetSegmentCount()
for i := 0; i < divCount; i++ {
seg := section.GetSegment(i)
maskSegment := mask.GetSegment(i)
otherSegment := other.GetSegment(i)
if !seg.MatchesValsWithMask(
otherSegment.getSegmentValue(),
otherSegment.getUpperSegmentValue(),
maskSegment.getSegmentValue()) {
return false
}
}
return true
}
func (section *ipAddressSectionInternal) createDiffSection(seg *IPAddressSegment, lower SegInt, upper SegInt, diffIndex int, intersectingValues []*AddressDivision) *IPAddressSection {
segCount := section.GetSegmentCount()
segments := createSegmentArray(segCount)
for j := 0; j < diffIndex; j++ {
segments[j] = intersectingValues[j]
}
diff := createAddressDivision(seg.deriveNewMultiSeg(lower, upper, nil))
segments[diffIndex] = diff
for j := diffIndex + 1; j < segCount; j++ {
segments[j] = section.getDivision(j)
}
return deriveIPAddressSection(section.toIPAddressSection(), segments)
}
func (section *ipAddressSectionInternal) toIPAddressSection() *IPAddressSection {
return (*IPAddressSection)(unsafe.Pointer(section))
}
func (section *ipAddressSectionInternal) getNetworkSectionLen(networkPrefixLength BitCount) *IPAddressSection {
segmentCount := section.GetSegmentCount()
if segmentCount == 0 {
return section.toIPAddressSection()
}
var newSegments []*AddressDivision
bitsPerSegment := section.GetBitsPerSegment()
networkPrefixLength = checkBitCount(networkPrefixLength, section.GetBitCount())
prefixedSegmentIndex := getNetworkSegmentIndex(networkPrefixLength, section.GetBytesPerSegment(), bitsPerSegment)
if prefixedSegmentIndex >= 0 {
segPrefLength := getPrefixedSegmentPrefixLength(bitsPerSegment, networkPrefixLength, prefixedSegmentIndex) // prefixedSegmentIndex of -1 already handled
lastSeg := section.GetSegment(prefixedSegmentIndex)
prefBits := segPrefLength.bitCount()
mask := ^SegInt(0) << uint(bitsPerSegment-prefBits)
lower, upper := lastSeg.getSegmentValue()&mask, lastSeg.getUpperSegmentValue()|^mask
networkSegmentCount := prefixedSegmentIndex + 1
if networkSegmentCount == segmentCount && segsSame(segPrefLength, lastSeg.GetSegmentPrefixLen(), lower, lastSeg.getSegmentValue(), upper, lastSeg.getUpperSegmentValue()) {
// the segment count and prefixed segment matches
return section.toIPAddressSection()
}
newSegments = createSegmentArray(networkSegmentCount)
section.copySubDivisions(0, prefixedSegmentIndex, newSegments)
newSegments[prefixedSegmentIndex] = createAddressDivision(lastSeg.deriveNewMultiSeg(lower, upper, segPrefLength))
} else {
newSegments = createSegmentArray(0)
}
return deriveIPAddressSectionPrefLen(section.toIPAddressSection(), newSegments, cacheBitCount(networkPrefixLength))
}
func (section *ipAddressSectionInternal) getHostSectionLen(networkPrefixLength BitCount) *IPAddressSection {
segmentCount := section.GetSegmentCount()
if segmentCount == 0 {
return section.toIPAddressSection()
}
var prefLen PrefixLen
var newSegments []*AddressDivision
bitsPerSegment := section.GetBitsPerSegment()
bytesPerSegment := section.GetBytesPerSegment()
networkPrefixLength = checkBitCount(networkPrefixLength, section.GetBitCount())
prefixedSegmentIndex := getHostSegmentIndex(networkPrefixLength, bytesPerSegment, bitsPerSegment)
if prefixedSegmentIndex < segmentCount {
firstSeg := section.GetSegment(prefixedSegmentIndex)
segPrefLength := getPrefixedSegmentPrefixLength(bitsPerSegment, networkPrefixLength, prefixedSegmentIndex)
prefLen = segPrefLength
prefBits := segPrefLength.bitCount()
// mask the boundary segment
mask := ^(^SegInt(0) << uint(bitsPerSegment-prefBits))
divLower := uint64(firstSeg.getDivisionValue())
divUpper := uint64(firstSeg.getUpperDivisionValue())
divMask := uint64(mask)
maxVal := uint64(^SegInt(0))
masker := MaskRange(divLower, divUpper, divMask, maxVal)
lower, upper := masker.GetMaskedLower(divLower, divMask), masker.GetMaskedUpper(divUpper, divMask)
segLower, segUpper := SegInt(lower), SegInt(upper)
if prefixedSegmentIndex == 0 && segsSame(segPrefLength, firstSeg.GetSegmentPrefixLen(), segLower, firstSeg.getSegmentValue(), segUpper, firstSeg.getUpperSegmentValue()) {
// the segment count and prefixed segment matches
return section.toIPAddressSection()
}
hostSegmentCount := segmentCount - prefixedSegmentIndex
newSegments = createSegmentArray(hostSegmentCount)
newSegments[0] = createAddressDivision(firstSeg.deriveNewMultiSeg(segLower, segUpper, segPrefLength))
// the remaining segments each must have zero-segment prefix length
var zeroPrefixIndex int
if section.isPrefixed() {
zeroPrefixIndex = getNetworkSegmentIndex(section.GetPrefixLen().bitCount(), bytesPerSegment, bitsPerSegment) + 1
} else {
zeroPrefixIndex = segmentCount
}
zeroPrefixIndex -= prefixedSegmentIndex
zeroPrefixIndex = max(zeroPrefixIndex, 1)
for i := 1; i < zeroPrefixIndex; i++ {
seg := section.GetSegment(prefixedSegmentIndex + i)
newSegments[i] = createAddressDivision(seg.derivePrefixed(cacheBitCount(0)))
}
// the rest already have zero-segment prefix length, just copy them
section.copySubDivisions(prefixedSegmentIndex+zeroPrefixIndex, prefixedSegmentIndex+hostSegmentCount, newSegments[zeroPrefixIndex:])
} else {
prefLen = cacheBitCount(0)
newSegments = createSegmentArray(0)
}
return deriveIPAddressSectionPrefLen(section.toIPAddressSection(), newSegments, prefLen)
}
// getSubnetSegments called by methods to adjust/remove/set prefix length,
// masking methods, zero host and zero network methods
func (section *ipAddressSectionInternal) getSubnetSegments(
startIndex int,
networkPrefixLength PrefixLen,
verifyMask bool,
segProducer func(int) *AddressDivision,
segmentMaskProducer func(int) SegInt,
) (*IPAddressSection, address_error.IncompatibleAddressError) {
newSect, err := section.addressSectionInternal.getSubnetSegments(startIndex, networkPrefixLength, verifyMask, segProducer, segmentMaskProducer)
return newSect.ToIP(), err
}
func (section *ipAddressSectionInternal) getNetwork() IPAddressNetwork {
if addrType := section.getAddrType(); addrType.isIPv4() {
return ipv4Network
} else if addrType.isIPv6() {
return ipv6Network
}
return nil
}
// Wrap wraps this IP address section, returning a WrappedIPAddressSection,
// an implementation of ExtendedIPSegmentSeries that can be used to write code that works with both IP addresses and IP address sections.
// Wrap can be called with a nil receiver, wrapping a nil address section.
func (section *ipAddressSectionInternal) Wrap() WrappedIPAddressSection {
return wrapIPSection(section.toIPAddressSection())
}
// WrapSection wraps this IP address section, returning a WrappedAddressSection,
// an implementation of ExtendedSegmentSeries that can be used to write code that works with both addresses and address sections.
// WrapSection can be called with a nil receiver, wrapping a nil address section.
func (section *ipAddressSectionInternal) WrapSection() WrappedAddressSection {
return wrapSection(section.toAddressSection())
}
// GetBitCount returns the number of bits in each value comprising this address item.
func (section *ipAddressSectionInternal) GetBitCount() BitCount {
return section.addressSectionInternal.GetBitCount()
}
// GetByteCount returns the number of bytes required for each value comprising this address item.
func (section *ipAddressSectionInternal) GetByteCount() int {
return section.addressSectionInternal.GetByteCount()
}
// IsZero returns whether this section matches exactly the value of zero.
func (section *ipAddressSectionInternal) IsZero() bool {
return section.addressSectionInternal.IsZero()
}
// IncludesZero returns whether this section includes the value of zero within its range.
func (section *ipAddressSectionInternal) IncludesZero() bool {
return section.addressSectionInternal.IncludesZero()
}
// IsMax returns whether this section matches exactly the maximum possible value,
// the value whose bits are all ones.
func (section *ipAddressSectionInternal) IsMax() bool {
return section.addressSectionInternal.IsMax()
}
// IncludesMax returns whether this section includes the max value,
// the value whose bits are all ones, within its range.
func (section *ipAddressSectionInternal) IncludesMax() bool {
return section.addressSectionInternal.IncludesMax()
}
// IsFullRange returns whether this address item represents all possible values attainable by an address item of this type.
//
// This is true if and only if both IncludesZero and IncludesMax return true.
func (section *ipAddressSectionInternal) IsFullRange() bool {
return section.addressSectionInternal.IsFullRange()
}
// GetSequentialBlockIndex gets the minimal segment index for which all following segments are full-range blocks.
//
// The segment at this index is not a full-range block itself, unless all segments are full-range.
// The segment at this index and all following segments form a sequential range.
// For the full address section to be sequential, the preceding segments must be single-valued.
func (section *ipAddressSectionInternal) GetSequentialBlockIndex() int {
return section.addressSectionInternal.GetSequentialBlockIndex()
}
// GetSequentialBlockCount provides the count of elements from the sequential block iterator, the minimal number of sequential address sections that comprise this address section.
func (section *ipAddressSectionInternal) GetSequentialBlockCount() *big.Int {
return section.addressSectionInternal.GetSequentialBlockCount()
}
// ContainsPrefixBlock returns whether the values of this item contains the block of values for the given prefix length.
//
// Unlike ContainsSinglePrefixBlock, whether there are multiple prefix values in this item for the given prefix length makes no difference.
//
// Use GetMinPrefixLenForBlock to determine the smallest prefix length for which this method returns true.
func (section *ipAddressSectionInternal) ContainsPrefixBlock(prefixLen BitCount) bool {
return section.addressSectionInternal.ContainsPrefixBlock(prefixLen)
}
// IsPrefixBlock returns whether the given series of address segments has
// a prefix length and whether it includes the block associated with its prefix length.
// If the prefix length matches the bit count, true is returned.
//
// This method differs from the ContainsPrefixBlock method in that it returns false if
// the series has no prefix length or the prefix length differs from
// the prefix length for which the ContainsPrefixBlock returns true.
func (section *ipAddressSectionInternal) IsPrefixBlock() bool {
return section.addressSectionInternal.IsPrefixBlock()
}
// GetMinPrefixLenForBlock returns the smallest prefix length such that this section includes a 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.
//
// For the returned prefix length, there can be either a single prefix or multiple possible prefix values in this block.
// To avoid the case of multiple prefix values, use the GetPrefixLenForSingleBlock.
//
// If this section represents a single value, a bit count is returned.
func (section *ipAddressSectionInternal) GetMinPrefixLenForBlock() BitCount {
return section.addressSectionInternal.GetMinPrefixLenForBlock()
}
// GetValue returns the lowest individual address section in this address section as an integer value.
func (section *ipAddressSectionInternal) GetValue() *big.Int {
return section.addressSectionInternal.GetValue()
}
// GetUpperValue returns the highest individual address section in this address section as an integer value.
func (section *ipAddressSectionInternal) GetUpperValue() *big.Int {
return section.addressSectionInternal.GetUpperValue()
}
// Bytes returns the lowest individual address section in this address section as a byte slice.
func (section *ipAddressSectionInternal) Bytes() []byte {
return section.addressSectionInternal.Bytes()
}
// UpperBytes returns the highest individual address section in this address section as a byte slice.
func (section *ipAddressSectionInternal) UpperBytes() []byte {
return section.addressSectionInternal.UpperBytes()
}
// CopyBytes copies the value of the lowest individual address section in the section into a byte slice.
//
// If the value can fit in the given slice, it 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 (section *ipAddressSectionInternal) CopyBytes(bytes []byte) []byte {
return section.addressSectionInternal.CopyBytes(bytes)
}
// CopyUpperBytes copies the value of the highest individual address in the section into a byte slice.
//
// If the value can fit into the given slice, it 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 (section *ipAddressSectionInternal) CopyUpperBytes(bytes []byte) []byte {
return section.addressSectionInternal.CopyUpperBytes(bytes)
}
// IsSequential returns whether the section represents a range of values that are sequential.
//
// Generally, this means that any segment covering a range of
// values must be followed by segment that are full range, covering all values.
func (section *ipAddressSectionInternal) IsSequential() bool {
return section.addressSectionInternal.IsSequential()
}
// GetSegmentCount returns the segment/division count.
func (section *ipAddressSectionInternal) GetSegmentCount() int {
return section.addressSectionInternal.GetSegmentCount()
}
// 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 *ipAddressSectionInternal) GetMaxSegmentValue() SegInt {
return section.addressSectionInternal.GetMaxSegmentValue()
}
// IncludesZeroHost returns whether the address section contains an individual address section with a host of zero.
// If the address section has no prefix length it returns false.
// If the prefix length matches the bit count, then it returns true.
//
// Otherwise, it checks whether it contains an individual address section for which all bits past the prefix are zero.
func (section *ipAddressSectionInternal) IncludesZeroHost() bool {
networkPrefixLength := section.getPrefixLen()
return networkPrefixLength != nil && section.IncludesZeroHostLen(networkPrefixLength.bitCount())
}
// boundariesOnly: whether it is important to us that masking works for all values in the range.
// For example, 1.2.3.2-4/31 cannot be a null host,
// because when applied to bounds we get 1.2.3.2-4/31, and that includes 1.2.3.3/31,
// which does not have a null host. So in this case, we usually get a boundaries_error.IncompatibleAddressError.
// BoundariesOnly as true avoids an exception if we are really only interested in getting the boundaries of the null host,
// and we are not interested in the other values in between.
func (section *ipAddressSectionInternal) createZeroHost(prefLen BitCount, boundariesOnly bool) (*IPAddressSection, address_error.IncompatibleAddressError) {
mask := section.addrType.getIPNetwork().GetNetworkMask(prefLen)
return section.getSubnetSegments(
getNetworkSegmentIndex(prefLen, section.GetBytesPerSegment(), section.GetBitsPerSegment()),
cacheBitCount(prefLen),
!boundariesOnly, //verifyMask
section.getDivision,
func(i int) SegInt { return mask.GetSegment(i).GetSegmentValue() })
}
func (section *ipAddressSectionInternal) createZeroNetwork() *IPAddressSection {
prefixLength := section.getNetworkPrefixLen()
mask := section.addrType.getIPNetwork().GetHostMask(prefixLength.bitCount())
res, _ := section.getSubnetSegments(
0,
prefixLength,
false,
section.getDivision,
func(i int) SegInt { return mask.GetSegment(i).GetSegmentValue() })
return res
}
func (section *ipAddressSectionInternal) withoutPrefixLen() *IPAddressSection {
if !section.isPrefixed() {
return section.toIPAddressSection()
}
if section.hasNoDivisions() {
return createIPSection(section.getDivisionsInternal(), nil, section.getAddrType())
}
var startIndex int
maxVal := section.GetMaxSegmentValue()
existingPrefixLength := section.getPrefixLen().bitCount()
if existingPrefixLength > 0 {
bitsPerSegment := section.GetBitsPerSegment()
bytesPerSegment := section.GetBytesPerSegment()
startIndex = getNetworkSegmentIndex(existingPrefixLength, bytesPerSegment, bitsPerSegment)
}
res, _ := section.getSubnetSegments(
startIndex,
nil,
false,
func(i int) *AddressDivision {
return section.getDivision(i)
},
func(i int) SegInt {
return maxVal
},
)
return res
}
func (section *ipAddressSectionInternal) mask(msk *IPAddressSection, retainPrefix bool) (*IPAddressSection, address_error.IncompatibleAddressError) {
if err := section.checkSectionCount(msk); err != nil {
return nil, err
}
var prefLen PrefixLen
if retainPrefix {
prefLen = section.getPrefixLen()
}
return section.getSubnetSegments(
0,
prefLen,
true,
section.getDivision,
func(i int) SegInt { return msk.GetSegment(i).GetSegmentValue() })
}
func (section *ipAddressSectionInternal) getNetworkSection() *IPAddressSection {
var prefLen BitCount
if section.isPrefixed() {
prefLen = section.getPrefixLen().bitCount()
} else {
prefLen = section.GetBitCount()
}
return section.getNetworkSectionLen(prefLen)
}
func (section *ipAddressSectionInternal) getHostSection() *IPAddressSection {
var prefLen BitCount
if section.isPrefixed() {
prefLen = section.getPrefixLen().bitCount()
}
return section.getHostSectionLen(prefLen)
}
func (section *ipAddressSectionInternal) getOredSegments(networkPrefixLength PrefixLen, verifyMask bool, segProducer func(int) *AddressDivision, segmentMaskProducer func(int) SegInt) (res *IPAddressSection, err address_error.IncompatibleAddressError) {
networkPrefixLength = checkPrefLen(networkPrefixLength, section.GetBitCount())
bitsPerSegment := section.GetBitsPerSegment()
count := section.GetSegmentCount()
for i := 0; 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 := bitwiseOrRange(val64, upperVal64, mask64, seg.GetMaxValue())
if !masker.IsSequential() {
err = &incompatibleAddressError{addressError{key: "ipaddress.error.maskMismatch"}}
return
}
value = SegInt(masker.GetOredLower(val64, mask64))
upperValue = SegInt(masker.GetOredUpper(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)
value = seg.getSegmentValue()
upperValue = seg.getUpperSegmentValue()
if verifyMask {
mask64 := uint64(maskValue)
val64 := uint64(value)
upperVal64 := uint64(upperValue)
masker := bitwiseOrRange(val64, upperVal64, mask64, seg.GetMaxValue())
if !masker.IsSequential() {
err = &incompatibleAddressError{addressError{key: "ipaddress.error.maskMismatch"}}
return
}
value = SegInt(masker.GetOredLower(val64, mask64))
upperValue = SegInt(masker.GetOredUpper(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 = deriveIPAddressSectionPrefLen(section.toIPAddressSection(), newSegments, networkPrefixLength)
return
}
}
res = section.toIPAddressSection()
return
}
func (section *ipAddressSectionInternal) createMaxHost() (*IPAddressSection, address_error.IncompatibleAddressError) {
prefixLength := section.getNetworkPrefixLen() // we know it is prefixed here so no panic on the derefence
mask := section.addrType.getIPNetwork().GetHostMask(prefixLength.bitCount())
return section.getOredSegments(
prefixLength,
true,
section.getDivision,
func(i int) SegInt { return mask.GetSegment(i).GetSegmentValue() })
}
// error can be address_error.IncompatibleAddressError or address_error.SizeMismatchError
func (section *ipAddressSectionInternal) bitwiseOr(msk *IPAddressSection, retainPrefix bool) (*IPAddressSection, address_error.IncompatibleAddressError) {
if err := section.checkSectionCount(msk); err != nil {
return nil, err
}
var prefLen PrefixLen
if retainPrefix {
prefLen = section.getPrefixLen()
}
return section.getOredSegments(
prefLen,
true,
section.getDivision,
func(i int) SegInt { return msk.GetSegment(i).GetSegmentValue() })
}
func (section *ipAddressSectionInternal) insert(index int, other *IPAddressSection, segmentToBitsShift uint) *IPAddressSection {
return section.replaceLen(index, index, other, 0, other.GetSegmentCount(), segmentToBitsShift)
}
// 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 *ipAddressSectionInternal) replaceLen(startIndex, endIndex int, replacement *IPAddressSection, replacementStartIndex, replacementEndIndex int, segmentToBitsShift uint) *IPAddressSection {
segmentCount := section.GetSegmentCount()
startIndex, endIndex, replacementStartIndex, replacementEndIndex =
adjustIndices(startIndex, endIndex, segmentCount, replacementStartIndex, replacementEndIndex, replacement.GetSegmentCount())
replacedCount := endIndex - startIndex
replacementCount := replacementEndIndex - replacementStartIndex
thizz := section.toAddressSection()
if replacementCount == 0 && replacedCount == 0 { //keep in mind for ipvx, empty sections cannot have prefix lengths
return section.toIPAddressSection()
} else if segmentCount == replacedCount { //keep in mind for ipvx, empty sections cannot have prefix lengths
return replacement
}
var newPrefixLen PrefixLen
prefixLength := section.getPrefixLen()
startBits := BitCount(startIndex << segmentToBitsShift)
if prefixLength != nil && prefixLength.bitCount() <= startBits {
newPrefixLen = prefixLength
replacement = replacement.SetPrefixLen(0)
} else {
replacementEndBits := BitCount(replacementEndIndex << segmentToBitsShift)
replacementPrefLen := replacement.getPrefixLen()
endIndexBits := BitCount(endIndex << segmentToBitsShift)
if replacementPrefLen != nil && replacementPrefLen.bitCount() <= replacementEndBits {
var replacementPrefixLen BitCount
replacementStartBits := BitCount(replacementStartIndex << segmentToBitsShift)
replacementPrefLenIsZero := replacementPrefLen.bitCount() <= replacementStartBits
if !replacementPrefLenIsZero {
replacementPrefixLen = replacementPrefLen.bitCount() - replacementStartBits
}
newPrefixLen = cacheBitCount(startBits + replacementPrefixLen)
if endIndex < segmentCount && (prefixLength == nil || prefixLength.bitCount() > endIndexBits) {
if replacedCount > 0 || replacementPrefLenIsZero {
thizz = section.setPrefixLen(endIndexBits)
} else {
// this covers the case of a:5:6:7:8 is getting b:c:d/47 at index 1 to 1
// We need "a" to have no prefix, and "5" to get prefix len 0
// But setting "5" to have prefix len 0 gives "a" the prefix len 16
// This is not a problem if any segments are getting replaced or the replacement segments have prefix length 0
//
// we move the non-replaced host segments from the end of this to the end of the replacement segments
// and we also remove the prefix length from this
additionalSegs := segmentCount - endIndex
thizz = section.getSubSection(0, startIndex)
replacement = replacement.insert(
replacementEndIndex, section.getSubSection(endIndex, segmentCount).ToIP(), segmentToBitsShift)
replacementEndIndex += additionalSegs
}
}
} else if prefixLength != nil {
replacementBits := BitCount(replacementCount << segmentToBitsShift)
var endPrefixBits BitCount
if prefixLength.bitCount() > endIndexBits {
endPrefixBits = prefixLength.bitCount() - endIndexBits
}
newPrefixLen = cacheBitCount(startBits + replacementBits + endPrefixBits)
} // else newPrefixLen is nil
}
return thizz.replace(startIndex, endIndex, replacement.ToSectionBase(),
replacementStartIndex, replacementEndIndex, newPrefixLen).ToIP()
}
// 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 *ipAddressSectionInternal) TestBit(n BitCount) bool {
return section.addressSectionInternal.TestBit(n)
}
// 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 *ipAddressSectionInternal) IsOneBit(prefixBitIndex BitCount) bool {
return section.addressSectionInternal.IsOneBit(prefixBitIndex)
}
func (section *ipAddressSectionInternal) getNetworkMask(network IPAddressNetwork) *IPAddressSection {
var prefLen BitCount
if section.isPrefixed() {
prefLen = section.getNetworkPrefixLen().bitCount()
} else {
prefLen = section.GetBitCount()
}
return network.GetNetworkMask(prefLen).GetSubSection(0, section.GetSegmentCount())
}
func (section *ipAddressSectionInternal) getHostMask(network IPAddressNetwork) *IPAddressSection {
var prefLen BitCount
if section.isPrefixed() {
prefLen = section.getNetworkPrefixLen().bitCount()
}
return network.GetHostMask(prefLen).GetSubSection(0, section.GetSegmentCount())
}