-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddress.go
2122 lines (1906 loc) · 80.2 KB
/
address.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"
"reflect"
"unsafe"
"github.com/pchchv/goip/address_error"
"github.com/pchchv/goip/address_string"
"github.com/pchchv/goip/tree"
)
const (
HexPrefix = "0x"
OctalPrefix = "0"
BinaryPrefix = "0b"
RangeSeparator = '-'
RangeSeparatorStr = "-"
AlternativeRangeSeparator = '\u00bb'
AlternativeRangeSeparatorStr = "\u00bb" // '»'
ExtendedDigitsRangeSeparatorStr = AlternativeRangeSeparatorStr
SegmentWildcard = '*'
SegmentWildcardStr = "*"
SegmentSqlWildcard = '%'
SegmentSqlWildcardStr = "%"
SegmentSqlSingleWildcard = '_'
SegmentSqlSingleWildcardStr = "_"
)
var (
segmentWildcardStr = SegmentWildcardStr
zeroAddr = createAddress(zeroSection, NoZone)
)
func createAddress(section *AddressSection, zone Zone) *Address {
res := &Address{
addressInternal{
section: section,
zone: zone,
cache: &addressCache{},
},
}
return res
}
// SegmentValueProvider provides values for segments.
// Values that fall outside the segment value type range will be truncated using standard golang integer type conversions.
type SegmentValueProvider func(segmentIndex int) SegInt
// AddressValueProvider provides values for addresses.
type AddressValueProvider interface {
GetSegmentCount() int
GetValues() SegmentValueProvider
GetUpperValues() SegmentValueProvider
}
// identifierStr is a string representation of an address or host name.
type identifierStr struct {
idStr HostIdentifierString // MACAddressString or IPAddressString or HostName
}
type addrsCache struct {
lower *Address
upper *Address
}
type addressCache struct {
addrsCache *addrsCache
stringCache *stringCache // only used by IPv6 when there is a zone
identifierStr *identifierStr
trieKeyCache *tree.TrieKeyData
}
type addressInternal struct {
section *AddressSection
zone Zone
cache *addressCache
}
// GetBitCount returns the number of bits that make up a given address,
// or each address in the range if a subnet.
func (addr *addressInternal) GetBitCount() BitCount {
section := addr.section
if section == nil {
return 0
}
return section.GetBitCount()
}
// GetByteCount returns the number of bytes required for a given address,
// or each address in the range if a subnet.
func (addr *addressInternal) GetByteCount() int {
section := addr.section
if section == nil {
return 0
}
return section.GetByteCount()
}
// GetPrefixCount returns the number of prefixes in a given address or subnet.
// The prefix length is given by GetPrefixLen.
// If the prefix length is not nil, a count of the range of values in the prefix is returned.
// If the prefix length is nil, the same value is returned as in GetCount.
func (addr *addressInternal) GetPrefixCount() *big.Int {
section := addr.section
if section == nil {
return bigOne()
}
return section.GetPrefixCount()
}
// GetPrefixCountLen returns the number of prefixes in the given address or subnet for the given prefix length.
// If it is not a subnet with multiple addresses or a subnet with a single prefix of the given prefix length, 1 is returned.
func (addr *addressInternal) GetPrefixCountLen(prefixLen BitCount) *big.Int {
section := addr.section
if section == nil {
return bigOne()
}
return section.GetPrefixCountLen(prefixLen)
}
// GetBlockCount returns the count of distinct values in the given number of initial (more significant) segments.
func (addr *addressInternal) GetBlockCount(segments int) *big.Int {
section := addr.section
if section == nil {
return bigOne()
}
return section.GetBlockCount(segments)
}
// GetPrefixLen returns the prefix length or nil if there is no prefix length.
//
// A prefix length indicates the number of bits in the initial part (high significant bits) of the address that make up the prefix.
//
// A prefix is a part of the address that is not specific to that address but common amongst a group of addresses, such as a CIDR prefix block subnet.
//
// For IP addresses, the prefix is explicitly specified when the address is created.
// For example, "1.2.0.0/16" has a prefix length of 16, and "1.2.*.*" has no prefix length,
// although both represent the same set of addresses and are considered the same.
// Prefixes may be considered variable for a given IP address and may depend on routing.
//
// The GetMinPrefixLenForBlock and GetPrefixLenForSingleBlock methods help you obtain or determine the length of a prefix length if one does not already exist.
// The ToPrefixBlockLen method allows you to create a subnet consisting of a block of addresses for any given prefix length.
//
// For MAC addresses, the prefix is initially derived from a range, so "1:2:3:*:*:*" has a prefix length of 24.
// MAC addresses derived from an address with a prefix length can retain the prefix length regardless of their own range of values.
func (addr *addressInternal) GetPrefixLen() PrefixLen {
return addr.getPrefixLen().copy()
}
// IsSequential returns whether the given address or subnet represents a range of addresses that are sequential.
//
// Generally, for a subnet this means that any segment that spans a range of values must be followed by segments that are full range and span all values.
//
// Individual addresses are sequential and CIDR prefix blocks are sequential.
// The "1.2.3-4.5" subnet is not sequential because the two addresses it represents, "1.2.3.5" and "1.2.4.5", are not ("1.2.3.6" is in between but not part of the subnet).
//
// Given any subnet of IP addresses, you can use the SequentialBlockIterator to convert any subnet into a set of sequential subnets.
func (addr *addressInternal) IsSequential() bool {
section := addr.section
if section == nil {
return true
}
return section.IsSequential()
}
func (addr *addressInternal) getCount() *big.Int {
section := addr.section
if section == nil {
return bigOne()
}
return section.GetCount()
}
func (addr *addressInternal) getPrefixLen() PrefixLen {
if addr.section == nil {
return nil
}
return addr.section.getPrefixLen()
}
// isMultiple returns true if this address represents more than single individual address, whether it is a subnet of multiple addresses.
func (addr *addressInternal) isMultiple() bool {
return addr.section != nil && addr.section.isMultiple()
}
// isPrefixed returns whether the given address has an associated prefix length.
func (addr *addressInternal) isPrefixed() bool {
return addr.section != nil && addr.section.IsPrefixed()
}
// Be careful when calling this, because for IPv6Address{} and IPv4Address{} it gives the wrong answer without the init method called first.
// An alternative is to call GetIPVersion, or to be sure you have called the init method.
func (addr *addressInternal) getAddrType() addrType {
if addr.section == nil {
return zeroType
}
return addr.section.addrType
}
// isIPv4 returns whether this matches an IPv4 address.
// we allow nil receivers to allow this to be called following a failed conversion like ToIP()
func (addr *addressInternal) isIPv4() bool {
return addr.section != nil && addr.section.matchesIPv4AddressType()
}
// isIPv6 returns whether this matches an IPv6 address.
// we allow nil receivers to allow this to be called following a failed conversion like ToIP()
func (addr *addressInternal) isIPv6() bool {
return addr.section != nil && addr.section.matchesIPv6AddressType()
}
// isMAC returns whether this matches an MAC address.
func (addr *addressInternal) isMAC() bool {
return addr.section != nil && addr.section.matchesMACAddressType()
}
func (addr *addressInternal) toAddress() *Address {
return (*Address)(unsafe.Pointer(addr))
}
func (addr *addressInternal) checkIdentity(section *AddressSection) *Address {
if section == nil {
return nil
} else if section == addr.section {
return addr.toAddress()
}
return createAddress(section, addr.zone)
}
func (addr *addressInternal) toPrefixBlock() *Address {
return addr.checkIdentity(addr.section.toPrefixBlock())
}
func (addr *addressInternal) toPrefixBlockLen(prefLen BitCount) *Address {
return addr.checkIdentity(addr.section.toPrefixBlockLen(prefLen))
}
func (addr *addressInternal) getDivision(index int) *AddressDivision {
return addr.section.getDivision(index)
}
func (addr *addressInternal) getDivisionCount() int {
if addr.section == nil {
return 0
}
return addr.section.GetDivisionCount()
}
func (addr *addressInternal) getSegment(index int) *AddressSegment {
return addr.section.GetSegment(index)
}
// GetBitsPerSegment returns the number of bits comprising each segment in this address or subnet.
// Segments in the same address are equal length.
func (addr *addressInternal) GetBitsPerSegment() BitCount {
section := addr.section
if section == nil {
return 0
}
return section.GetBitsPerSegment()
}
func (addr *addressInternal) createLowestHighestAddrs() (lower, upper *Address) {
lower = addr.checkIdentity(addr.section.GetLower())
upper = addr.checkIdentity(addr.section.GetUpper())
return
}
func (addr *addressInternal) getLowestHighestAddrs() (lower, upper *Address) {
if !addr.isMultiple() {
lower = addr.toAddress()
upper = lower
return
}
cache := addr.cache
if cache == nil {
return addr.createLowestHighestAddrs()
}
cached := (*addrsCache)(atomicLoadPointer((*unsafe.Pointer)(unsafe.Pointer(&cache.addrsCache))))
if cached == nil {
cached = &addrsCache{}
cached.lower, cached.upper = addr.createLowestHighestAddrs()
dataLoc := (*unsafe.Pointer)(unsafe.Pointer(&cache.addrsCache))
atomicStorePointer(dataLoc, unsafe.Pointer(cached))
}
lower, upper = cached.lower, cached.upper
return
}
func (addr *addressInternal) getLower() *Address {
lower, _ := addr.getLowestHighestAddrs()
return lower
}
func (addr *addressInternal) getUpper() *Address {
_, upper := addr.getLowestHighestAddrs()
return upper
}
func (addr *addressInternal) toBlock(segmentIndex int, lower, upper SegInt) *Address {
return addr.checkIdentity(addr.section.toBlock(segmentIndex, lower, upper))
}
func (addr *addressInternal) adjustPrefixLen(prefixLen BitCount) *Address {
return addr.checkIdentity(addr.section.adjustPrefixLen(prefixLen))
}
func (addr *addressInternal) adjustPrefixLenZeroed(prefixLen BitCount) (res *Address, err address_error.IncompatibleAddressError) {
section, err := addr.section.adjustPrefixLenZeroed(prefixLen)
if err == nil {
res = addr.checkIdentity(section)
}
return
}
// isIP returns whether this matches an IP address.
// It must be IPv4, IPv6, or the zero IPAddress which has no segments
// we allow nil receivers to allow this to be called following a failed conversion like ToIP()
func (addr *addressInternal) isIP() bool {
return addr.section == nil /* zero addr */ || addr.section.matchesIPAddressType()
}
func (addr *addressInternal) getBytes() []byte {
return addr.section.getBytes()
}
func (addr *addressInternal) getUpperBytes() []byte {
return addr.section.getUpperBytes()
}
// GetBytesPerSegment returns the number of bytes comprising each segment in this address or subnet.
// Segments in the same address are equal length.
func (addr *addressInternal) GetBytesPerSegment() int {
section := addr.section
if section == nil {
return 0
}
return section.GetBytesPerSegment()
}
func (addr *addressInternal) getMaxSegmentValue() SegInt {
return addr.section.GetMaxSegmentValue()
}
func (addr *addressInternal) setPrefixLen(prefixLen BitCount) *Address {
return addr.checkIdentity(addr.section.setPrefixLen(prefixLen))
}
func (addr *addressInternal) isSameZone(other *Address) bool {
return addr.zone == other.ToAddressBase().zone
}
func (addr *addressInternal) hasZone() bool {
return addr.zone != NoZone
}
func (addr *addressInternal) getStringCache() *stringCache {
cache := addr.cache
if cache == nil {
return nil
}
return addr.cache.stringCache
}
func (addr *addressInternal) getTrailingBitCount(ones bool) BitCount {
return addr.section.GetTrailingBitCount(ones)
}
func (addr *addressInternal) getLeadingBitCount(ones bool) BitCount {
return addr.section.GetLeadingBitCount(ones)
}
// testBit returns true if the bit in the lower value of this address 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 address.
// TestBit will panic if n < 0, or if it matches or exceeds the bit count of this item.
func (addr *addressInternal) testBit(n BitCount) bool {
return addr.section.TestBit(n)
}
// isOneBit returns true if the bit in the lower value of this address 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 larger than the bit count of this item.
func (addr *addressInternal) isOneBit(bitIndex BitCount) bool {
return addr.section.IsOneBit(bitIndex)
}
// IsPrefixBlock returns whether the address has a prefix length and
// the address range includes the block of values for that prefix length.
// If the prefix length matches the bit count, this returns true.
//
// To create a prefix block from any address, use ToPrefixBlock.
//
// This is different from ContainsPrefixBlock in that this method returns
// false if the series has no prefix length, or a prefix length that differs from
// a prefix length for which ContainsPrefixBlock returns true.
func (addr *addressInternal) IsPrefixBlock() bool {
prefLen := addr.getPrefixLen()
return prefLen != nil && addr.section.ContainsPrefixBlock(prefLen.bitCount())
}
// ContainsPrefixBlock returns whether the range of this address or subnet contains the
// block of addresses 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 (addr *addressInternal) ContainsPrefixBlock(prefixLen BitCount) bool {
return addr.section == nil || addr.section.ContainsPrefixBlock(prefixLen)
}
// GetMinPrefixLenForBlock returns the smallest prefix length such that this includes the block of addresses 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 represents just a single address, returns the bit length of this address.
func (addr *addressInternal) GetMinPrefixLenForBlock() BitCount {
section := addr.section
if section == nil {
return 0
}
return section.GetMinPrefixLenForBlock()
}
func (addr *addressInternal) toMaxLower() *Address {
section := addr.section
if section == nil {
return addr.toAddress()
}
return addr.checkIdentity(addr.section.toMaxLower())
}
func (addr *addressInternal) toMinUpper() *Address {
section := addr.section
if section == nil {
return addr.toAddress()
}
return addr.checkIdentity(addr.section.toMinUpper())
}
// IsZero returns whether this address matches exactly the value of zero.
func (addr *addressInternal) IsZero() bool {
section := addr.section
if section == nil {
return true
}
return section.IsZero()
}
// IncludesZero returns whether this address includes the zero address within its range.
func (addr *addressInternal) IncludesZero() bool {
section := addr.section
if section == nil {
return true
}
return section.IncludesZero()
}
// IsFullRange returns whether this address covers the entire address space of this address version or type.
//
// This is true if and only if both IncludesZero and IncludesMax return true.
func (addr *addressInternal) IsFullRange() bool {
section := addr.section
if section == nil {
// when no bits, the only value 0 is the max value too
return true
}
return section.IsFullRange()
}
func (addr *addressInternal) getDivisionsInternal() []*AddressDivision {
return addr.section.getDivisionsInternal()
}
// reverseSegments returns a new address with the segments reversed.
func (addr *addressInternal) reverseSegments() *Address {
return addr.checkIdentity(addr.section.ReverseSegments())
}
// equalsSameVersion returns whether two addresses,
// already known to be the same version and address type, are equal
func (addr *addressInternal) equalsSameVersion(other AddressType) bool {
otherAddr := other.ToAddressBase()
if addr.toAddress() == otherAddr {
return true
} else if otherAddr == nil {
return false
}
otherSection := otherAddr.GetSection()
return addr.section.sameCountTypeEquals(otherSection) &&
// if it it is IPv6 and has a zone, then it does not equal addresses from other zones
addr.isSameZone(otherAddr)
}
// withoutPrefixLen returns the same address but with no associated prefix length.
func (addr *addressInternal) withoutPrefixLen() *Address {
return addr.checkIdentity(addr.section.withoutPrefixLen())
}
func (addr *addressInternal) setPrefixLenZeroed(prefixLen BitCount) (res *Address, err address_error.IncompatibleAddressError) {
section, err := addr.section.setPrefixLenZeroed(prefixLen)
if err == nil {
res = addr.checkIdentity(section)
}
return
}
// assignMinPrefixForBlock 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 (addr *addressInternal) assignMinPrefixForBlock() *Address {
return addr.setPrefixLen(addr.GetMinPrefixLenForBlock())
}
// equivalent to section.sectionIterator
func (addr *addressInternal) addrIterator(excludeFunc func([]*AddressDivision) bool) Iterator[*Address] {
var iterator Iterator[[]*AddressDivision]
useOriginal := !addr.isMultiple()
original := addr.toAddress()
if useOriginal {
if excludeFunc != nil && excludeFunc(addr.getDivisionsInternal()) {
original = nil // the single-valued iterator starts out empty
}
} else {
address := addr.toAddress()
iterator = allSegmentsIterator(
addr.getDivisionCount(),
nil,
func(index int) Iterator[*AddressSegment] { return address.getSegment(index).iterator() },
excludeFunc)
}
return addrIterator(useOriginal, original, original.getPrefixLen(), false, iterator)
}
func (addr *addressInternal) blockIterator(segmentCount int) Iterator[*Address] {
if segmentCount < 0 {
segmentCount = 0
}
allSegsCount := addr.getDivisionCount()
if segmentCount >= allSegsCount {
return addr.addrIterator(nil)
}
var iterator Iterator[[]*AddressDivision]
address := addr.toAddress()
useOriginal := !addr.section.isMultipleTo(segmentCount)
if !useOriginal {
var hostSegIteratorProducer func(index int) Iterator[*AddressSegment]
hostSegIteratorProducer = func(index int) Iterator[*AddressSegment] {
return address.getSegment(index).identityIterator()
}
segIteratorProducer := func(index int) Iterator[*AddressSegment] {
return address.getSegment(index).iterator()
}
iterator = segmentsIterator(
allSegsCount,
nil, //when no prefix we defer to other iterator, when there is one we use the whole original section in the encompassing iterator and not just the original segments
segIteratorProducer,
nil,
segmentCount-1,
segmentCount,
hostSegIteratorProducer)
}
return addrIterator(useOriginal, address, address.getPrefixLen(), addr.section.isMultipleFrom(segmentCount), iterator)
}
func (addr *addressInternal) getSequentialBlockIndex() int {
if addr.section == nil {
return 0
}
return addr.section.GetSequentialBlockIndex()
}
func (addr *addressInternal) getSequentialBlockCount() *big.Int {
if addr.section == nil {
return bigOne()
}
return addr.section.GetSequentialBlockCount()
}
func (addr *addressInternal) getSegmentStrings() []string {
return addr.section.getSegmentStrings()
}
// sequentialBlockIterator iterates through the minimal number of maximum-sized blocks comprising this subnet
// a block is sequential if given any two addresses in the block, any intervening address between the two is also in the block
func (addr *addressInternal) sequentialBlockIterator() Iterator[*Address] {
return addr.blockIterator(addr.getSequentialBlockIndex())
}
func (addr *addressInternal) reverseBytes() (*Address, address_error.IncompatibleAddressError) {
sect, err := addr.section.ReverseBytes()
if err != nil {
return nil, err
}
return addr.checkIdentity(sect), nil
}
func (addr *addressInternal) reverseBits(perByte bool) (*Address, address_error.IncompatibleAddressError) {
sect, err := addr.section.ReverseBits(perByte)
if err != nil {
return nil, err
}
return addr.checkIdentity(sect), nil
}
// GetPrefixLenForSingleBlock returns a prefix length for which the range of
// this address subnet matches exactly the block of addresses for that prefix.
//
// If the range can be described this way, then this method returns
// the same value as GetMinPrefixLenForBlock.
//
// If no such prefix exists, returns nil.
//
// If this segment grouping represents a single value,
// returns the bit length of this address.
//
// IP address examples:
// - 1.2.3.4 returns 32
// - 1.2.3.4/16 returns 32
// - 1.2.*.* returns 16
// - 1.2.*.0/24 returns 16
// - 1.2.0.0/16 returns 16
// - 1.2.*.4 returns nil
// - 1.2.252-255.* returns 22
func (addr *addressInternal) GetPrefixLenForSingleBlock() PrefixLen {
section := addr.section
if section == nil {
return cacheBitCount(0)
}
return section.GetPrefixLenForSingleBlock()
}
func (addr *addressInternal) assignPrefixForSingleBlock() *Address {
newPrefix := addr.GetPrefixLenForSingleBlock()
if newPrefix == nil {
return nil
}
return addr.checkIdentity(addr.section.setPrefixLen(newPrefix.bitCount()))
}
// toSingleBlockOrAddress converts to a single prefix block or address.
// If the given address is a single prefix block, it is returned.
// If it can be converted to a single prefix block by assigning a prefix length,
// the converted block is returned.
// If it is a single address, any prefix length is removed and the address is returned.
// Otherwise, nil is returned.
func (addr *addressInternal) toSinglePrefixBlockOrAddr() *Address {
if !addr.isMultiple() {
if !addr.isPrefixed() {
return addr.toAddress()
}
return addr.withoutPrefixLen()
} else {
series := addr.assignPrefixForSingleBlock()
if series != nil {
return series
}
}
return nil
}
func (addr *addressInternal) constructTrieCache() *tree.TrieKeyData {
var cache *tree.TrieKeyData
sect := addr.section
prefLen := sect.getPrefixLen()
if sectionIPv4 := sect.ToIPv4(); sectionIPv4 != nil {
cache = &tree.TrieKeyData{
Is32Bits: true,
PrefLen: tree.PrefixLen(prefLen),
Uint32Val: sectionIPv4.Uint32Value(),
}
if prefLen != nil {
bits := prefLen.bitCount()
cache.NextBitMask32Val = uint32(0x80000000) >> bits
cache.Mask32Val = ipv4NetworkMasks[bits]
}
} else if sectionIPv6 := sect.ToIPv6(); sectionIPv6 != nil {
cache = &tree.TrieKeyData{
Is128Bits: true,
PrefLen: tree.PrefixLen(prefLen),
}
cache.Uint64HighVal, cache.Uint64LowVal = sectionIPv6.Uint64Values()
if prefLen != nil {
bits := prefLen.bitCount()
mask := ipv6NetworkMasks[bits]
cache.Mask64HighVal, cache.Mask64LowVal = mask[0], mask[1]
if bits > 63 {
cache.NextBitMask64Val = uint64(0x8000000000000000) >> (bits - 64)
} else {
cache.NextBitMask64Val = uint64(0x8000000000000000) >> bits
}
}
} else {
cache = &tree.TrieKeyData{}
}
return cache
}
func (addr *addressInternal) assignTrieCache() {
cache := addr.cache
if cache != nil && cache.trieKeyCache != nil {
cache.trieKeyCache = addr.constructTrieCache()
}
}
func (addr *addressInternal) getTrieCache() *tree.TrieKeyData {
cache := addr.cache
if cache != nil {
cached := (*tree.TrieKeyData)(atomicLoadPointer((*unsafe.Pointer)(unsafe.Pointer(&cache.trieKeyCache))))
if cached == nil {
cached = addr.constructTrieCache()
dataLoc := (*unsafe.Pointer)(unsafe.Pointer(&cache.trieKeyCache))
atomicStorePointer(dataLoc, unsafe.Pointer(cached))
}
return cached
}
return &tree.TrieKeyData{}
}
func (addr *addressInternal) trieCompare(other *Address) int {
if addr.toAddress() == other {
return 0
}
segmentCount := addr.getDivisionCount()
bitsPerSegment := addr.GetBitsPerSegment()
o1Pref := addr.GetPrefixLen()
o2Pref := other.GetPrefixLen()
bitsMatchedSoFar := 0
i := 0
for {
segment1 := addr.getSegment(i)
segment2 := other.getSegment(i)
pref1 := getSegmentPrefLen(addr.toAddress(), o1Pref, bitsPerSegment, bitsMatchedSoFar, segment1)
pref2 := getSegmentPrefLen(other, o2Pref, bitsPerSegment, bitsMatchedSoFar, segment2)
if pref1 != nil {
segmentPref1 := pref1.Len()
segmentPref2 := pref2.Len()
if pref2 != nil && segmentPref2 <= segmentPref1 {
matchingBits := getMatchingBits(segment1, segment2, segmentPref2, bitsPerSegment)
if matchingBits >= segmentPref2 {
if segmentPref2 == segmentPref1 {
// same prefix block
return 0
}
// segmentPref2 is shorter prefix, prefix bits match, so depends on bit at index segmentPref2
if segment1.IsOneBit(segmentPref2) {
return 1
}
return -1
}
return compareSegInt(segment1.GetSegmentValue(), segment2.GetSegmentValue())
} else {
matchingBits := getMatchingBits(segment1, segment2, segmentPref1, bitsPerSegment)
if matchingBits >= segmentPref1 {
if segmentPref1 < bitsPerSegment {
if segment2.IsOneBit(segmentPref1) {
return -1
}
return 1
} else {
i++
if i == segmentCount {
return 1 // o1 with prefix length matching bit count is the bigger
} // else must check the next segment
}
} else {
return compareSegInt(segment1.GetSegmentValue(), segment2.GetSegmentValue())
}
}
} else if pref2 != nil {
segmentPref2 := pref2.Len()
matchingBits := getMatchingBits(segment1, segment2, segmentPref2, bitsPerSegment)
if matchingBits >= segmentPref2 {
if segmentPref2 < bitsPerSegment {
if segment1.IsOneBit(segmentPref2) {
return 1
}
return -1
} else {
i++
if i == segmentCount {
return -1 // o2 with prefix length matching bit count is the bigger
} // else must check the next segment
}
} else {
return compareSegInt(segment1.GetSegmentValue(), segment2.GetSegmentValue())
}
} else {
matchingBits := getMatchingBits(segment1, segment2, bitsPerSegment, bitsPerSegment)
if matchingBits < bitsPerSegment { // no match - the current subnet/address is not here
return compareSegInt(segment1.GetSegmentValue(), segment2.GetSegmentValue())
} else {
i++
if i == segmentCount {
// same address
return 0
} // else must check the next segment
}
}
bitsMatchedSoFar += bitsPerSegment
}
}
func (addr *addressInternal) contains(other AddressType) bool {
if other == nil {
return true
}
otherAddr := other.ToAddressBase()
if addr.toAddress() == otherAddr || otherAddr == nil {
return true
}
otherSection := otherAddr.GetSection()
if addr.section == nil {
return otherSection.GetSegmentCount() == 0
}
return addr.section.Contains(otherSection) &&
// if it is IPv6 and has a zone, then it does not contain addresses from other zones
addr.isSameZone(otherAddr)
}
func (addr *addressInternal) equals(other AddressType) bool {
if other == nil {
return false
}
otherAddr := other.ToAddressBase()
if addr.toAddress() == otherAddr {
return true
} else if otherAddr == nil {
return false
}
otherSection := otherAddr.GetSection()
if addr.section == nil {
return otherSection.GetSegmentCount() == 0
}
return addr.section.Equal(otherSection) &&
// if it it is IPv6 and has a zone, then it does not equal addresses from other zones
addr.isSameZone(otherAddr)
}
// IsSinglePrefixBlock returns whether the address range matches the block
// of values for a single prefix identified by the prefix length of this address.
// This is similar to IsPrefixBlock except that it returns false when the subnet has multiple prefixes.
//
// What distinguishes this method from ContainsSinglePrefixBlock is that this method returns
// false if the series does not have a prefix length assigned to it,
// or a prefix length that differs from the prefix length for which ContainsSinglePrefixBlock returns true.
//
// It is similar to IsPrefixBlock but returns false when there are multiple prefixes.
//
// For instance, "1.*.*.* /16" returns false from this method and returns true from IsPrefixBlock.
func (addr *addressInternal) IsSinglePrefixBlock() bool {
prefLen := addr.getPrefixLen()
return prefLen != nil && addr.section.IsSinglePrefixBlock()
}
// ContainsSinglePrefixBlock returns whether this address contains a single prefix block for the given prefix length.
//
// This means there is only one prefix value for the given prefix length,
// and it also contains the full prefix block for that prefix, all addresses with that prefix.
//
// Use GetPrefixLenForSingleBlock to determine whether there is a prefix length for which this method returns true.
func (addr *addressInternal) ContainsSinglePrefixBlock(prefixLen BitCount) bool {
return addr.section == nil || addr.section.ContainsSinglePrefixBlock(prefixLen)
}
// In callers, we always need to ensure init is called,
// otherwise a nil section will be zero-size instead of having size one.
func (addr *addressInternal) compareSize(other AddressItem) int {
return addr.section.compareSize(other)
}
func (addr *addressInternal) increment(increment int64) *Address {
return addr.checkIdentity(addr.section.increment(increment))
}
func (addr *addressInternal) incrementBoundary(increment int64) *Address {
return addr.checkIdentity(addr.section.incrementBoundary(increment))
}
func (addr *addressInternal) prefixIterator(isBlockIterator bool) Iterator[*Address] {
prefLen := addr.getPrefixLen()
if prefLen == nil {
return addr.addrIterator(nil)
}
var useOriginal bool
if isBlockIterator {
useOriginal = addr.IsSinglePrefixBlock()
} else {
useOriginal = bigIsOne(addr.GetPrefixCount())
}
prefLength := prefLen.bitCount()
bitsPerSeg := addr.GetBitsPerSegment()
bytesPerSeg := addr.GetBytesPerSegment()
networkSegIndex := getNetworkSegmentIndex(prefLength, bytesPerSeg, bitsPerSeg)
hostSegIndex := getHostSegmentIndex(prefLength, bytesPerSeg, bitsPerSeg)
segCount := addr.getDivisionCount()
var iterator Iterator[[]*AddressDivision]
address := addr.toAddress()
if !useOriginal {
var hostSegIteratorProducer func(index int) Iterator[*AddressSegment]
if isBlockIterator {
hostSegIteratorProducer = func(index int) Iterator[*AddressSegment] {
seg := address.getSegment(index)
if seg.isPrefixed() { // IP address segments know their own prefix, MAC segments do not
return seg.prefixBlockIterator()
}
segPref := getPrefixedSegmentPrefixLength(bitsPerSeg, prefLength, index)
return seg.prefixedBlockIterator(segPref.bitCount())
}
} else {
hostSegIteratorProducer = func(index int) Iterator[*AddressSegment] {
seg := address.getSegment(index)
if seg.isPrefixed() { // IP address segments know their own prefix, MACS segments do not
return seg.prefixIterator()
}
segPref := getPrefixedSegmentPrefixLength(bitsPerSeg, prefLength, index)
return seg.prefixedIterator(segPref.bitCount())
}
}
iterator = segmentsIterator(
segCount,
nil, //when no prefix we defer to other iterator, when there is one we use the whole original section in the encompassing iterator and not just the original segments
func(index int) Iterator[*AddressSegment] { return address.getSegment(index).iterator() },
nil,
networkSegIndex,
hostSegIndex,
hostSegIteratorProducer)
}
if isBlockIterator {
return addrIterator(useOriginal, address, address.getPrefixLen(), prefLength < addr.GetBitCount(), iterator)
}
return prefixAddrIterator(useOriginal, address, address.getPrefixLen(), iterator)
}
func (addr *addressInternal) toOctalString(with0Prefix bool) (string, address_error.IncompatibleAddressError) {
if addr.hasZone() {
cache := addr.getStringCache()
if cache == nil {
return addr.section.toOctalStringZoned(with0Prefix, addr.zone)
}
var cacheField **string
if with0Prefix {
cacheField = &cache.octalStringPrefixed
} else {
cacheField = &cache.octalString
}
return cacheStrErr(cacheField,
func() (string, address_error.IncompatibleAddressError) {
return addr.section.toOctalStringZoned(with0Prefix, addr.zone)
})
}
return addr.section.ToOctalString(with0Prefix)
}
func (addr *addressInternal) toBinaryString(with0bPrefix bool) (string, address_error.IncompatibleAddressError) {
if addr.hasZone() {
cache := addr.getStringCache()
if cache == nil {
return addr.section.toBinaryStringZoned(with0bPrefix, addr.zone)
}
var cacheField **string
if with0bPrefix {
cacheField = &cache.binaryStringPrefixed
} else {
cacheField = &cache.binaryString
}
return cacheStrErr(cacheField,
func() (string, address_error.IncompatibleAddressError) {
return addr.section.toBinaryStringZoned(with0bPrefix, addr.zone)
})
}
return addr.section.ToBinaryString(with0bPrefix)
}
func (addr *addressInternal) toHexString(with0xPrefix bool) (string, address_error.IncompatibleAddressError) {
if addr.hasZone() {
cache := addr.getStringCache()
if cache == nil {
return addr.section.toHexStringZoned(with0xPrefix, addr.zone)
}
var cacheField **string
if with0xPrefix {
cacheField = &cache.hexStringPrefixed
} else {