-
Notifications
You must be signed in to change notification settings - Fork 0
/
grouping.go
1259 lines (1123 loc) · 46.7 KB
/
grouping.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"
"unsafe"
"github.com/pchchv/goip/address_error"
)
var emptyBytes = make([]byte, 0, 0)
type addressDivisionGroupingInternal struct {
addressDivisionGroupingBase
}
// The adaptive zero grouping, produced by zero sections like IPv4AddressSection{} or AddressDivisionGrouping{},
// can represent a zero-length section of any address type,
// It is not considered equal to constructions of specific zero length sections of groupings like
// NewIPv4Section(nil) which can only represent a zero-length section of a single address type.
func (grouping *addressDivisionGroupingInternal) matchesZeroGrouping() bool {
addrType := grouping.getAddrType()
return addrType.isZeroSegments() && grouping.hasNoDivisions()
}
func (grouping *addressDivisionGroupingInternal) matchesIPSectionType() bool {
// because there are no init() conversions for IPv6 or IPV4 sections, an implicitly zero-valued IPv4, IPv6 or IP section has addr type nil
return grouping.getAddrType().isIP() || grouping.matchesZeroGrouping()
}
func (grouping *addressDivisionGroupingInternal) matchesIPAddressType() bool {
return grouping.matchesIPSectionType() // no need to check segment count because addresses cannot be constructed with incorrect segment count (note the zero IPAddress has zero-segments)
}
func (grouping *addressDivisionGroupingInternal) matchesAddrSectionType() bool {
addrType := grouping.getAddrType()
// because there are no init() conversions for IPv6/IPV4/MAC sections,
// an implicitly zero-valued IPv6/IPV4/MAC or zero IP section has addr type nil
return addrType.isIP() || addrType.isMAC() || grouping.matchesZeroGrouping()
}
func (grouping *addressDivisionGroupingInternal) isAddressSection() bool {
return grouping != nil && grouping.matchesAddrSectionType()
}
func (grouping *addressDivisionGroupingInternal) matchesIPv6SectionType() bool {
// because there are no init() conversions for IPv6 sections,
// an implicitly zero-valued IPV6 section has addr type nil
return grouping.getAddrType().isIPv6() || grouping.matchesZeroGrouping()
}
func (grouping *addressDivisionGroupingInternal) matchesIPv6v4MixedGroupingType() bool {
// because there are no init() conversions for IPv6v4MixedGrouping groupings,
// an implicitly zero-valued IPv6v4MixedGrouping has addr type nil
return grouping.getAddrType().isIPv6v4Mixed() || grouping.matchesZeroGrouping()
}
func (grouping *addressDivisionGroupingInternal) matchesIPv4SectionType() bool {
// because there are no init() conversions for IPV4 sections,
// an implicitly zero-valued IPV4 section has addr type nil
return grouping.getAddrType().isIPv4() || grouping.matchesZeroGrouping()
}
func (grouping *addressDivisionGroupingInternal) matchesMACSectionType() bool {
// because there are no init() conversions for MAC sections,
// an implicitly zero-valued MAC section has addr type nil
return grouping.getAddrType().isMAC() || grouping.matchesZeroGrouping()
}
func (grouping *addressDivisionGroupingInternal) getDivArray() standardDivArray {
if divsArray := grouping.divisions; divsArray != nil {
return divsArray.(standardDivArray)
}
return nil
}
// getDivision returns the division or panics if the index is negative or too large
func (grouping *addressDivisionGroupingInternal) getDivision(index int) *AddressDivision {
return grouping.getDivArray()[index]
}
func (grouping *addressDivisionGroupingInternal) toAddressDivisionGrouping() *AddressDivisionGrouping {
return (*AddressDivisionGrouping)(unsafe.Pointer(grouping))
}
func (grouping *addressDivisionGroupingInternal) getCachedCount() *big.Int {
if !grouping.isMultiple() {
return bigOne()
} else {
g := grouping.toAddressDivisionGrouping()
if sect := g.ToIPv4(); sect != nil {
return sect.getCachedCount()
} else if sect := g.ToIPv6(); sect != nil {
return sect.getCachedCount()
} else if sect := g.ToMAC(); sect != nil {
return sect.getCachedCount()
}
}
return grouping.addressDivisionGroupingBase.getCachedCount()
}
// GetBitCount returns the number of bits in each value comprising this address item.
func (grouping *addressDivisionGroupingInternal) GetBitCount() BitCount {
return grouping.addressDivisionGroupingBase.GetBitCount()
}
// GetByteCount returns the number of bytes required for each value comprising this address item,
// rounding up if the bit count is not a multiple of 8.
func (grouping *addressDivisionGroupingInternal) GetByteCount() int {
return grouping.addressDivisionGroupingBase.GetByteCount()
}
func (grouping *addressDivisionGroupingInternal) calcBytes() (bytes, upperBytes []byte) {
addrType := grouping.getAddrType()
divisionCount := grouping.GetDivisionCount()
isMultiple := grouping.isMultiple()
if addrType.isIPv4() || addrType.isMAC() {
bytes = make([]byte, divisionCount)
if isMultiple {
upperBytes = make([]byte, divisionCount)
} else {
upperBytes = bytes
}
for i := 0; i < divisionCount; i++ {
seg := grouping.getDivision(i).ToSegmentBase()
bytes[i] = byte(seg.GetSegmentValue())
if isMultiple {
upperBytes[i] = byte(seg.GetUpperSegmentValue())
}
}
} else if addrType.isIPv6() {
byteCount := divisionCount << 1
bytes = make([]byte, byteCount)
if isMultiple {
upperBytes = make([]byte, byteCount)
} else {
upperBytes = bytes
}
for i := 0; i < divisionCount; i++ {
var upperVal SegInt
byteIndex := i << 1
seg := grouping.getDivision(i).ToSegmentBase()
val := seg.GetSegmentValue()
bytes[byteIndex] = byte(val >> 8)
if isMultiple {
upperVal = seg.GetUpperSegmentValue()
upperBytes[byteIndex] = byte(upperVal >> 8)
}
nextByteIndex := byteIndex + 1
bytes[nextByteIndex] = byte(val)
if isMultiple {
upperBytes[nextByteIndex] = byte(upperVal)
}
}
} else {
byteCount := grouping.GetByteCount()
bytes = make([]byte, byteCount)
if isMultiple {
upperBytes = make([]byte, byteCount)
} else {
upperBytes = bytes
}
for k, byteIndex, bitIndex := divisionCount-1, byteCount-1, BitCount(8); k >= 0; k-- {
div := grouping.getDivision(k)
val := div.GetDivisionValue()
var upperVal DivInt
if isMultiple {
upperVal = div.GetUpperDivisionValue()
}
divBits := div.GetBitCount()
for divBits > 0 {
rbi := 8 - bitIndex
bytes[byteIndex] |= byte(val << uint(rbi))
val >>= uint(bitIndex)
if isMultiple {
upperBytes[byteIndex] |= byte(upperVal << uint(rbi))
upperVal >>= uint(bitIndex)
}
if divBits < bitIndex {
bitIndex -= divBits
break
} else {
divBits -= bitIndex
bitIndex = 8
byteIndex--
}
}
}
}
return
}
func (grouping *addressDivisionGroupingInternal) getBytes() (bytes []byte) {
bytes, _ = grouping.getCachedBytes(grouping.calcBytes)
return
}
func (grouping *addressDivisionGroupingInternal) getUpperBytes() (bytes []byte) {
_, bytes = grouping.getCachedBytes(grouping.calcBytes)
return
}
// Bytes returns the lowest individual division grouping in this grouping as a byte slice.
func (grouping *addressDivisionGroupingInternal) Bytes() []byte {
if grouping.hasNoDivisions() {
return emptyBytes
}
return cloneBytes(grouping.getBytes())
}
// UpperBytes returns the highest individual division grouping in this grouping as a byte slice.
func (grouping *addressDivisionGroupingInternal) UpperBytes() []byte {
if grouping.hasNoDivisions() {
return emptyBytes
}
return cloneBytes(grouping.getUpperBytes())
}
func (grouping *addressDivisionGroupingInternal) matchesIPv6AddressType() bool {
return grouping.getAddrType().isIPv6() // no need to check segment count because addresses cannot be constructed with incorrect segment count
}
func (grouping *addressDivisionGroupingInternal) matchesIPv4AddressType() bool {
return grouping.getAddrType().isIPv4() // no need to check segment count because addresses cannot be constructed with incorrect segment count
}
func (grouping *addressDivisionGroupingInternal) matchesMACAddressType() bool {
return grouping.getAddrType().isMAC()
}
// copySubDivisions copies the existing segments from the given start index until but not including the segment at the given end index,
// into the given slice, as much as can be fit into the slice, returning the number of segments copied.
func (grouping *addressDivisionGroupingInternal) copySubDivisions(start, end int, divs []*AddressDivision) (count int) {
if divArray := grouping.getDivArray(); divArray != nil {
start, end, targetIndex := adjust1To1Indices(start, end, grouping.GetDivisionCount(), len(divs))
return divArray.copySubDivisions(start, end, divs[targetIndex:])
}
return
}
func (grouping *addressDivisionGroupingInternal) getDivisionCount() int {
if divArray := grouping.getDivArray(); divArray != nil {
return divArray.getDivisionCount()
}
return 0
}
func (grouping *addressDivisionGroupingInternal) initMultiple() {
divCount := grouping.getDivisionCount()
for i := divCount - 1; i >= 0; i-- {
div := grouping.getDivision(i)
if div.isMultiple() {
grouping.isMult = true
return
}
}
return
}
func (grouping *addressDivisionGroupingInternal) getSubDivisions(start, end int) []*AddressDivision {
divArray := grouping.getDivArray()
if divArray != nil {
return divArray.getSubDivisions(start, end)
} else if start != 0 || end != 0 {
panic("invalid subslice")
}
return make([]*AddressDivision, 0)
}
// getDivisionsInternal returns the divisions slice, only to be used internally
func (grouping *addressDivisionGroupingInternal) getDivisionsInternal() []*AddressDivision {
return grouping.getDivArray()
}
func (grouping *addressDivisionGroupingInternal) forEachSubDivision(start, end int, target func(index int, div *AddressDivision), targetLen int) (count int) {
divArray := grouping.getDivArray()
if divArray != nil {
if targetEnd := start + targetLen; end > targetEnd {
end = targetEnd
}
divArray = divArray[start:end]
for i, div := range divArray {
target(i, div)
}
}
return len(divArray)
}
func (grouping *addressDivisionGroupingInternal) toAddressSection() *AddressSection {
return grouping.toAddressDivisionGrouping().ToSectionBase()
}
func (grouping *addressDivisionGroupingInternal) getSegmentStrings() []string {
if grouping.hasNoDivisions() {
return []string{}
}
result := make([]string, grouping.GetDivisionCount())
for i := range result {
result[i] = grouping.getDivision(i).GetWildcardString()
}
return result
}
func (grouping addressDivisionGroupingInternal) defaultFormat(state fmt.State, verb rune) {
s := flagsFromState(state, verb)
_, _ = state.Write([]byte(fmt.Sprintf(s, grouping.initDivs().getDivArray())))
}
func (grouping *addressDivisionGroupingInternal) initDivs() *addressDivisionGroupingInternal {
if grouping.divisions == nil {
return &zeroSection.addressDivisionGroupingInternal
}
return grouping
}
// ContainsPrefixBlock returns whether the values of this item contains a block of values for the given prefix length.
//
// Unlike ContainsSinglePrefixBlock, whether this item contains multiple prefix values for a given prefix length is irrelevant.
//
// Use GetMinPrefixLenForBlock to determine the smallest prefix length for which this method returns true.
func (grouping *addressDivisionGroupingInternal) ContainsPrefixBlock(prefixLen BitCount) bool {
if section := grouping.toAddressSection(); section != nil {
return section.ContainsPrefixBlock(prefixLen)
}
var prevBitCount BitCount
prefixLen = checkSubnet(grouping, prefixLen)
divisionCount := grouping.GetDivisionCount()
for i := 0; i < divisionCount; i++ {
division := grouping.getDivision(i)
bitCount := division.GetBitCount()
totalBitCount := bitCount + prevBitCount
if prefixLen < totalBitCount {
divPrefixLen := prefixLen - prevBitCount
if !division.containsPrefixBlock(divPrefixLen) {
return false
}
for i++; i < divisionCount; i++ {
division = grouping.getDivision(i)
if !division.IsFullRange() {
return false
}
}
return true
}
prevBitCount = totalBitCount
}
return true
}
// IsPrefixBlock returns whether the given address division series 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 is different from
// the prefix length for which the ContainsPrefixBlock method returns true.
// Note that for any given prefix length, you can perform a comparison with GetMinPrefixLenForBlock.
func (grouping *addressDivisionGroupingInternal) IsPrefixBlock() bool {
prefLen := grouping.getPrefixLen()
return prefLen != nil && grouping.ContainsPrefixBlock(prefLen.bitCount())
}
// GetValue returns the lowest individual address division grouping in this address division grouping as an integer value.
func (grouping *addressDivisionGroupingInternal) GetValue() *big.Int {
if grouping.hasNoDivisions() {
return bigZero()
}
return bigZero().SetBytes(grouping.getBytes())
}
// GetUpperValue returns the highest individual address division grouping in this address division grouping as an integer value.
func (grouping *addressDivisionGroupingInternal) GetUpperValue() *big.Int {
if grouping.hasNoDivisions() {
return bigZero()
}
return bigZero().SetBytes(grouping.getUpperBytes())
}
// CopyBytes copies the value of the lowest division grouping in the range 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 with the value is created and returned.
//
// To determine the required length of the byte array, it is possible to use the GetByteCount.
func (grouping *addressDivisionGroupingInternal) CopyBytes(bytes []byte) []byte {
if grouping.hasNoDivisions() {
if bytes != nil {
return bytes[:0]
}
return emptyBytes
}
return getBytesCopy(bytes, grouping.getBytes())
}
// CopyUpperBytes copies the grouping value with the highest division in the range into the 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 with the value is created and returned.
//
// To determine the required length of the byte array, it is possible to use the GetByteCount.
func (grouping *addressDivisionGroupingInternal) CopyUpperBytes(bytes []byte) []byte {
if grouping.hasNoDivisions() {
if bytes != nil {
return bytes[:0]
}
return emptyBytes
}
return getBytesCopy(bytes, grouping.getUpperBytes())
}
// GetGenericDivision returns the division at the given index as a DivisionType implementation.
func (grouping *addressDivisionGroupingInternal) GetGenericDivision(index int) DivisionType {
return grouping.addressDivisionGroupingBase.GetGenericDivision(index)
}
// GetDivisionCount returns the number of divisions in this grouping.
func (grouping *addressDivisionGroupingInternal) GetDivisionCount() int {
return grouping.addressDivisionGroupingBase.GetDivisionCount()
}
// IsZero returns whether this grouping matches exactly the value of zero.
func (grouping *addressDivisionGroupingInternal) IsZero() bool {
return grouping.addressDivisionGroupingBase.IsZero()
}
// IncludesZero returns whether this grouping includes the value of zero within its range.
func (grouping *addressDivisionGroupingInternal) IncludesZero() bool {
return grouping.addressDivisionGroupingBase.IncludesZero()
}
// IncludesMax returns whether this grouping includes the max value,
// the value whose bits are all ones, within its range.
func (grouping *addressDivisionGroupingInternal) IncludesMax() bool {
return grouping.addressDivisionGroupingBase.IncludesMax()
}
// IsMax returns whether this grouping matches exactly the maximum possible value, the value whose bits are all ones.
func (grouping *addressDivisionGroupingInternal) IsMax() bool {
return grouping.addressDivisionGroupingBase.IsMax()
}
// 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 (grouping *addressDivisionGroupingInternal) IsFullRange() bool {
return grouping.addressDivisionGroupingBase.IsFullRange()
}
// GetSequentialBlockIndex gets the minimal division index for which all following divisions are full-range blocks.
//
// The division at this index is not a full-range block unless all divisions are full-range.
// The division at this index and all following divisions form a sequential range.
// For the full grouping to be sequential, the preceding divisions must be single-valued.
func (grouping *addressDivisionGroupingInternal) GetSequentialBlockIndex() int {
return grouping.addressDivisionGroupingBase.GetSequentialBlockIndex()
}
// GetSequentialBlockCount provides the count of elements from the sequential block iterator, the minimal number of sequential address division groupings that comprise this address division grouping.
func (grouping *addressDivisionGroupingInternal) GetSequentialBlockCount() *big.Int {
return grouping.addressDivisionGroupingBase.GetSequentialBlockCount()
}
// GetBlockCount returns the count of distinct values in the given number of initial (more significant) divisions.
func (grouping *addressDivisionGroupingInternal) GetBlockCount(divisionCount int) *big.Int {
return grouping.addressDivisionGroupingBase.GetBlockCount(divisionCount)
}
// GetPrefixCount returns the number of distinct prefix values in this item.
//
// The prefix length is given by GetPrefixLen.
//
// If this has a non-nil prefix length, returns the number of distinct prefix values.
//
// If this has a nil prefix length, returns the same value as GetCount.
func (grouping *addressDivisionGroupingInternal) GetPrefixCount() *big.Int {
if section := grouping.toAddressSection(); section != nil {
return section.GetPrefixCount()
}
return grouping.addressDivisionGroupingBase.GetPrefixCount()
}
// GetPrefixCountLen returns the number of distinct prefix values in this item for the given prefix length.
func (grouping *addressDivisionGroupingInternal) GetPrefixCountLen(prefixLen BitCount) *big.Int {
if section := grouping.toAddressSection(); section != nil {
return section.GetPrefixCountLen(prefixLen)
}
return grouping.addressDivisionGroupingBase.GetPrefixCountLen(prefixLen)
}
// GetMinPrefixLenForBlock returns the smallest prefix length such that the given grouping includes a block of all values for that prefix length.
//
// If the entire range can be described 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 grouping represents a single value, a bit count is returned.
func (grouping *addressDivisionGroupingInternal) GetMinPrefixLenForBlock() BitCount {
calc := func() BitCount {
count := grouping.GetDivisionCount()
totalPrefix := grouping.GetBitCount()
for i := count - 1; i >= 0; i-- {
div := grouping.getDivision(i)
segBitCount := div.getBitCount()
segPrefix := div.GetMinPrefixLenForBlock()
if segPrefix == segBitCount {
break
} else {
totalPrefix -= segBitCount
if segPrefix != 0 {
totalPrefix += segPrefix
break
}
}
}
return totalPrefix
}
return cacheMinPrefix(grouping.cache, calc)
}
func (grouping *addressDivisionGroupingInternal) createNewPrefixedDivisions(bitsPerDigit BitCount, networkPrefixLength PrefixLen) ([]*AddressDivision, address_error.IncompatibleAddressError) {
bitCount := grouping.GetBitCount()
var bitDivs []BitCount
// here we divide into divisions, each with an exact number of digits.
// Each digit takes 3 bits.
// So the division bit-sizes are a multiple of 3 until the last one.
largestBitCount := BitCount(64) // uint64, size of DivInt
largestBitCount -= largestBitCount % bitsPerDigit // round off to a multiple of 3 bits
for {
if bitCount <= largestBitCount {
mod := bitCount % bitsPerDigit
secondLast := bitCount - mod
if secondLast > 0 {
bitDivs = append(bitDivs, secondLast)
}
if mod > 0 {
bitDivs = append(bitDivs, mod)
}
break
} else {
bitCount -= largestBitCount
bitDivs = append(bitDivs, largestBitCount)
}
}
// at this point bitDivs has our division sizes
divCount := len(bitDivs)
divs := make([]*AddressDivision, divCount)
if divCount > 0 {
currentSegmentIndex := 0
seg := grouping.getDivision(currentSegmentIndex)
segLowerVal := seg.GetDivisionValue()
segUpperVal := seg.GetUpperDivisionValue()
segBits := seg.GetBitCount()
bitsSoFar := BitCount(0)
// 2 to the x is all ones shift left x, then not, then add 1
// so, for x == 1, 1111111 -> 1111110 -> 0000001 -> 0000010
// radix := ^(^(0) << uint(bitsPerDigit)) + 1
// fill up our new divisions, one by one
for i := divCount - 1; i >= 0; i-- {
var divLowerValue, divUpperValue uint64
divBitSize := bitDivs[i]
originalDivBitSize := divBitSize
for {
if segBits >= divBitSize { // this segment fills the remainder of this division
diff := uint(segBits - divBitSize)
segBits = BitCount(diff)
segL := segLowerVal >> diff
segU := segUpperVal >> diff
// if the division upper bits are multiple, then the lower bits inserted must be full range
if divLowerValue != divUpperValue {
if segL != 0 || segU != ^(^uint64(0)<<uint(divBitSize)) {
return nil, &incompatibleAddressError{addressError: addressError{key: "ipaddress.error.invalid.joined.ranges"}}
}
}
divLowerValue |= segL
divUpperValue |= segU
shift := ^(^uint64(0) << diff)
segLowerVal &= shift
segUpperVal &= shift
// if a segment's bits are split into two divisions, and the bits going into the first division are multi-valued,
// then the bits going into the second division must be full range
if segL != segU {
if segLowerVal != 0 || segUpperVal != ^(^uint64(0)<<uint(segBits)) {
return nil, &incompatibleAddressError{addressError: addressError{key: "ipaddress.error.invalid.joined.ranges"}}
}
}
var segPrefixBits PrefixLen
if networkPrefixLength != nil {
segPrefixBits = getDivisionPrefixLength(originalDivBitSize, networkPrefixLength.bitCount()-bitsSoFar)
}
div := newRangePrefixDivision(divLowerValue, divUpperValue, segPrefixBits, originalDivBitSize)
divs[divCount-i-1] = div
if segBits == 0 && i > 0 {
//get next seg
currentSegmentIndex++
seg = grouping.getDivision(currentSegmentIndex)
segLowerVal = seg.getDivisionValue()
segUpperVal = seg.getUpperDivisionValue()
segBits = seg.getBitCount()
}
break
} else {
// if the division upper bits are multiple, then the lower bits inserted must be full range
if divLowerValue != divUpperValue {
if segLowerVal != 0 || segUpperVal != ^(^uint64(0)<<uint(segBits)) {
return nil, &incompatibleAddressError{addressError: addressError{key: "ipaddress.error.invalid.joined.ranges"}}
}
}
diff := uint(divBitSize - segBits)
divLowerValue |= segLowerVal << diff
divUpperValue |= segUpperVal << diff
divBitSize = BitCount(diff)
// get next seg
currentSegmentIndex++
seg = grouping.getDivision(currentSegmentIndex)
segLowerVal = seg.getDivisionValue()
segUpperVal = seg.getUpperDivisionValue()
segBits = seg.getBitCount()
}
}
bitsSoFar += originalDivBitSize
}
}
return divs, nil
}
func (grouping *addressDivisionGroupingInternal) createNewDivisions(bitsPerDigit BitCount) ([]*AddressDivision, address_error.IncompatibleAddressError) {
return grouping.createNewPrefixedDivisions(bitsPerDigit, nil)
}
func (grouping *addressDivisionGroupingInternal) getCount() *big.Int {
if !grouping.isMultiple() {
return bigOne()
} else {
g := grouping.toAddressDivisionGrouping()
if sect := g.ToIPv4(); sect != nil {
return sect.GetCount()
} else if sect := g.ToIPv6(); sect != nil {
return sect.GetCount()
} else if sect := g.ToMAC(); sect != nil {
return sect.GetCount()
}
}
return grouping.addressDivisionGroupingBase.getCount()
}
// Format implements the [fmt.Formatter] interface. It accepts the formats
// - 'v' for the default address and section format (either the normalized or canonical string),
// - 's' (string) for the same,
// - 'b' (binary), 'o' (octal with 0 prefix), 'O' (octal with 0o prefix),
// - 'd' (decimal), 'x' (lowercase hexadecimal), and
// - 'X' (uppercase hexadecimal).
//
// Also supported are some of fmt's format flags for integral types.
// Sign control is not supported since addresses and sections are never negative.
// '#' for an alternate format is supported, which adds a leading zero for octal,
// and for hexadecimal it adds
// a leading "0x" or "0X" for "%#x" and "%#X" respectively.
// Also supported is specification of minimum digits precision, output field width,
// space or zero padding, and '-' for left or right justification.
func (grouping addressDivisionGroupingInternal) Format(state fmt.State, verb rune) {
if sect := grouping.toAddressSection(); sect != nil {
sect.Format(state, verb)
return
} else if mixed := grouping.toAddressDivisionGrouping().ToMixedIPv6v4(); mixed != nil {
mixed.Format(state, verb)
return
}
// divisions are printed like slices of *AddressDivision (which are Stringers)
// with division separated by spaces and enclosed in square brackets,
// sections are printed like addresses with segments separated by segment separators
grouping.defaultFormat(state, verb)
}
// GetPrefixLenForSingleBlock returns a prefix length for which the range of this division grouping matches the block of addresses for that prefix.
//
// If no such prefix exists, GetPrefixLenForSingleBlock returns nil.
//
// If this division grouping represents a single value, returns the bit length.
func (grouping *addressDivisionGroupingInternal) GetPrefixLenForSingleBlock() PrefixLen {
calc := func() *PrefixLen {
count := grouping.GetDivisionCount()
var totalPrefix BitCount
for i := 0; i < count; i++ {
div := grouping.getDivision(i)
divPrefix := div.GetPrefixLenForSingleBlock()
if divPrefix == nil {
return cacheNilPrefix()
}
divPrefLen := divPrefix.bitCount()
totalPrefix += divPrefLen
if divPrefLen < div.GetBitCount() {
//remaining segments must be full range or we return nil
for i++; i < count; i++ {
laterDiv := grouping.getDivision(i)
if !laterDiv.IsFullRange() {
return cacheNilPrefix()
}
}
}
}
return cachePrefix(totalPrefix)
}
return cachePrefLenSingleBlock(grouping.cache, grouping.getPrefixLen(), calc)
}
// ContainsSinglePrefixBlock returns whether the values of this grouping contains a single prefix block for the given prefix length.
//
// This means there is only one prefix of the given length in this item,
// and this item contains the prefix block for that given prefix.
//
// Use GetPrefixLenForSingleBlock to determine whether there is a prefix length for which this method returns true.
func (grouping *addressDivisionGroupingInternal) ContainsSinglePrefixBlock(prefixLen BitCount) bool {
prefixLen = checkSubnet(grouping, prefixLen)
divisionCount := grouping.GetDivisionCount()
var prevBitCount BitCount
for i := 0; i < divisionCount; i++ {
division := grouping.getDivision(i)
bitCount := division.getBitCount()
totalBitCount := bitCount + prevBitCount
if prefixLen >= totalBitCount {
if division.isMultiple() {
return false
}
} else {
divPrefixLen := prefixLen - prevBitCount
if !division.ContainsSinglePrefixBlock(divPrefixLen) {
return false
}
for i++; i < divisionCount; i++ {
division = grouping.getDivision(i)
if !division.IsFullRange() {
return false
}
}
return true
}
prevBitCount = totalBitCount
}
return true
}
// IsSinglePrefixBlock returns whether the range of values matches a single subnet block for the prefix length.
//
// What distinguishes this method with 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.
// Note for any given prefix length you can compare with GetPrefixLenForSingleBlock.
func (grouping *addressDivisionGroupingInternal) IsSinglePrefixBlock() bool {
calc := func() bool {
prefLen := grouping.getPrefixLen()
return prefLen != nil && grouping.ContainsSinglePrefixBlock(prefLen.bitCount())
}
return cacheIsSinglePrefixBlock(grouping.cache, grouping.getPrefixLen(), calc)
}
func (grouping *addressDivisionGroupingInternal) compareSize(other AddressItem) int { // the getCount() is optimized which is why we do not defer to the method in addressDivisionGroupingBase
return compareCount(grouping.toAddressDivisionGrouping(), other)
}
func (grouping *addressDivisionGroupingInternal) getDivisionStrings() []string {
if grouping.hasNoDivisions() {
return []string{}
}
result := make([]string, grouping.GetDivisionCount())
for i := range result {
result[i] = grouping.getDivision(i).String()
}
return result
}
func (grouping *addressDivisionGroupingInternal) toString() string {
if sect := grouping.toAddressSection(); sect != nil {
return sect.ToNormalizedString()
}
return fmt.Sprint(grouping.initDivs().getDivArray())
}
// copyDivisions copies the existing segments from the given start index until but not including the segment at the given end index,
// into the given slice, as much as can be fit into the slice, returning the number of segments copied.
func (grouping *addressDivisionGroupingInternal) copyDivisions(divs []*AddressDivision) (count int) {
if divArray := grouping.getDivArray(); divArray != nil {
return divArray.copyDivisions(divs)
}
return
}
// AddressDivisionGrouping objects consist of a series of AddressDivision objects,
// each containing a consistent range of values.
//
// AddressDivisionGrouping objects are immutable.
// This also makes them concurrency-safe.
//
// AddressDivision objects use uint64 to represent their values,
// so this places a limit on the size of the divisions in AddressDivisionGrouping.
//
// AddressDivisionGrouping objects are similar to address sections and addresses,
// except that groupings can have divisions of different bit-lengths,
// including divisions that are not the exact number of bytes,
// whereas all segments in an address or address section must have the same bit size and exact number of bytes.
type AddressDivisionGrouping struct {
addressDivisionGroupingInternal
}
// ToSectionBase converts to an address section if the given grouping originated as an address section.
// Otherwise, the result is nil.
//
// ToSectionBase can be called with a nil receiver,
// allowing this method to be used in a chain with methods that may return a nil pointer.
func (grouping *AddressDivisionGrouping) ToSectionBase() *AddressSection {
if grouping == nil || !grouping.isAddressSection() {
return nil
}
return (*AddressSection)(unsafe.Pointer(grouping))
}
// ToIP converts to an IPAddressSection if this grouping originated as an IPv4 or IPv6 section,
// or an implicitly zero-valued IP section.
// If not, ToIP returns nil.
//
// ToIP can be called with a nil receiver,
// enabling you to chain this method with methods that might return a nil pointer.
func (grouping *AddressDivisionGrouping) ToIP() *IPAddressSection {
return grouping.ToSectionBase().ToIP()
}
// ToIPv4 converts to an IPv4AddressSection if this grouping originated as an IPv4 section.
// If not, ToIPv4 returns nil.
//
// ToIPv4 can be called with a nil receiver, enabling you to chain this method with methods that might return a nil pointer.
func (grouping *AddressDivisionGrouping) ToIPv4() *IPv4AddressSection {
return grouping.ToSectionBase().ToIPv4()
}
// ToIPv6 converts to an IPv6AddressSection if this grouping originated as an IPv6 section.
// If not, ToIPv6 returns nil.
//
// ToIPv6 can be called with a nil receiver, enabling you to chain this method with methods that might return a nil pointer.
func (grouping *AddressDivisionGrouping) ToIPv6() *IPv6AddressSection {
return grouping.ToSectionBase().ToIPv6()
}
// ToMAC converts to a MACAddressSection if this grouping originated as a MAC section.
// If not, ToMAC returns nil.
//
// ToMAC can be called with a nil receiver,
// enabling you to chain this method with methods that might return a nil pointer.
func (grouping *AddressDivisionGrouping) ToMAC() *MACAddressSection {
return grouping.ToSectionBase().ToMAC()
}
// ToDivGrouping is an identity method.
//
// ToDivGrouping can be called with a nil receiver,
// enabling you to chain this method with methods that might return a nil pointer.
func (grouping *AddressDivisionGrouping) ToDivGrouping() *AddressDivisionGrouping {
return grouping
}
// IsAdaptiveZero returns true if this is an adaptive zero grouping.
// The adaptive zero grouping, produced by zero sections like IPv4AddressSection{} or AddressDivisionGrouping{},
// can represent a zero-length section of any address type.
// It is not considered equal to constructions of specific zero length sections or
// groupings like NewIPv4Section(nil) which can only represent a zero-length section of a single address type.
func (grouping *AddressDivisionGrouping) IsAdaptiveZero() bool {
return grouping != nil && grouping.matchesZeroGrouping()
}
// IsSectionBase returns true if this address division grouping originated as an address section.
// If so, use ToSectionBase to convert back to the section type.
func (grouping *AddressDivisionGrouping) IsSectionBase() bool {
return grouping != nil && grouping.isAddressSection()
}
// IsIP returns true if this address division grouping originated as an IPv4 or IPv6 section, or a zero-length IP section. If so, use ToIP to convert back to the IP-specific type.
func (grouping *AddressDivisionGrouping) IsIP() bool {
return grouping.ToSectionBase().IsIP()
}
// IsMAC returns true if this grouping originated as a MAC section. If so, use ToMAC to convert back to the MAC-specific type.
func (grouping *AddressDivisionGrouping) IsMAC() bool {
return grouping.ToSectionBase().IsMAC()
}
// IsMixedIPv6v4 returns true if this grouping originated as a mixed IPv6-IPv4 grouping. If so, use ToMixedIPv6v4 to convert back to the more specific grouping type.
func (grouping *AddressDivisionGrouping) IsMixedIPv6v4() bool {
return grouping != nil && grouping.matchesIPv6v4MixedGroupingType()
}
// IsIPv4 returns true if this grouping originated as an IPv4 section. If so, use ToIPv4 to convert back to the IPv4-specific type.
func (grouping *AddressDivisionGrouping) IsIPv4() bool {
return grouping.ToSectionBase().IsIPv4()
}
// IsIPv6 returns true if this grouping originated as an IPv6 section. If so, use ToIPv6 to convert back to the IPv6-specific type.
func (grouping *AddressDivisionGrouping) IsIPv6() bool {
return grouping.ToSectionBase().IsIPv6()
}
// ToMixedIPv6v4 converts to a mixed IPv6/4 address section if this grouping originated as a mixed IPv6/4 address section.
// Otherwise, the result will be nil.
//
// ToMixedIPv6v4 can be called with a nil receiver, enabling you to chain this method with methods that might return a nil pointer.
func (grouping *AddressDivisionGrouping) ToMixedIPv6v4() *IPv6v4MixedAddressGrouping {
if grouping.matchesIPv6v4MixedGroupingType() {
return (*IPv6v4MixedAddressGrouping)(grouping)
}
return nil
}
// GetCount returns the count of possible distinct values for this division grouping.
// If not representing multiple values, the count is 1,
// unless this is a division grouping with no divisions, or an address section with no segments, in which case it is 0.
//
// Use IsMultiple if you simply want to know if the count is greater than 1.
func (grouping *AddressDivisionGrouping) GetCount() *big.Int {
if grouping == nil {
return bigZero()
}
return grouping.getCount()
}
// IsMultiple returns whether this grouping represents multiple values rather than a single value
func (grouping *AddressDivisionGrouping) IsMultiple() bool {
return grouping != nil && grouping.isMultiple()
}
// IsPrefixed returns whether this grouping has an associated prefix length.
func (grouping *AddressDivisionGrouping) IsPrefixed() bool {
if grouping == nil {
return false
}
return grouping.isPrefixed()
}
// CopySubDivisions copies the existing divisions from
// the given start index until but not including the division at the given end index,
// into the given slice, as much as can be fit into the slice,
// returning the number of divisions copied.
func (grouping *AddressDivisionGrouping) CopySubDivisions(start, end int, divs []*AddressDivision) (count int) {
return grouping.copySubDivisions(start, end, divs)
}
// GetDivision returns the division at the given index.
func (grouping *AddressDivisionGrouping) GetDivision(index int) *AddressDivision {
return grouping.getDivision(index)
}
// ForEachDivision visits each segment in order from most significant to least, most significant with index 0,
// calling the given function for each and terminating early if the function returns true.
// ForEachDivision returns the number of visited segments.
func (grouping *AddressDivisionGrouping) ForEachDivision(consumer func(divisionIndex int, division *AddressDivision) (stop bool)) int {
divArray := grouping.getDivArray()
if divArray != nil {
for i, div := range divArray {
if consumer(i, div) {
return i + 1
}
}
}
return len(divArray)
}
// Compare returns a negative integer, zero,
// or a positive integer if this address division grouping is less than, equal, or greater than the given item.
// Any address item is comparable to any other.
// All address items use CountComparator to compare.
func (grouping *AddressDivisionGrouping) Compare(item AddressItem) int {
return CountComparator.Compare(grouping, item)
}
// CompareSize compares the counts of two items, the number of individual items represented in each.
//
// Rather than calculating counts with GetCount,
// there can be more efficient ways of determining whether this grouping represents more individual items than another.
//
// CompareSize returns a positive integer if this address division grouping has a larger count than the item given,
// zero if they are the same, or a negative integer if the other has a larger count.