Debian Codegraph @

sort.go

raw
1 package dns
2
3 import (
4 "sort"
5 )
6
7 // Compare returns an integer comparing two RRs according to "Canonical Form and Order of Resource Records" in
8 // RFC 4034 Section 6. Note the TTL is skipped when comparing.
9 // The result will be 0 if a == b, -1 if a < b, and +1 if a > b.
10 func Compare(a, b RR) int {
11 x := CompareName(a.Header().Name, b.Header().Name)
12 if x != 0 {
13 return x
14 }
15
16 at := RRToType(a)
17 bt := RRToType(b)
18
19 if at < bt {
20 return -1
21 }
22 if at > bt {
23 return +1
24 }
25
26 if a.Header().Class < b.Header().Class {
27 return -1
28 }
29 if a.Header().Class > b.Header().Class {
30 return 1
31 }
32
33 return compare(a, b)
34 }
35
36 var _ sort.Interface = RRset{}
37
38 func (set RRset) Len() int { return len(set) }
39 func (set RRset) Less(i, j int) bool { return Compare(set[i], set[j]) == -1 }
40 func (set RRset) Swap(i, j int) { set[i], set[j] = set[j], set[i] }
41
42 // CompareName compares the name a and b as defined in RFC 4034, canonical ordering of names.
43 // If a label is the asterisks label "*" it is always equal (wildcard match). TODO(miek): this isn't
44 // implemented?
45 func CompareName(a, b string) int {
46 // See https://bert-hubert.blogspot.com/2015/10/how-to-do-fast-canonical-ordering-of.html
47 // Also exact copy of dnsutil/common.go
48 lasta := len(a)
49 lastb := len(b)
50 for {
51 cura, overshota := dnsutilPrev(a, lasta)
52 curb, overshotb := dnsutilPrev(b, lastb)
53 if overshota && overshotb {
54 return compareLabel(a[cura:lasta-1], b[curb:lastb-1])
55 }
56 x := compareLabel(a[cura:lasta-1], b[curb:lastb-1])
57 if x != 0 || (overshota && overshotb) {
58 return x
59 }
60 if overshota {
61 return -1
62 }
63 if overshotb {
64 return 1
65 }
66
67 lasta = cura
68 lastb = curb
69 }
70 }
71
72 // Equal returns true if a and b are equal. See [Compare].
73 func Equal(a, b RR) bool { return Compare(a, b) == 0 }
74
75 // EqualName returns true if the domain names a and b are equal. See [CompareName].
76 func EqualName(a, b string) bool { return CompareName(a, b) == 0 }
77
78 // CompareSerial compares serial numbers a and b using RFC 1982 serial number arithmetic.
79 // Returns -1 if a < b, +1 if a > b, and 0 if a == b. The result is undefined when the
80 // difference is exactly 2^31.
81 func CompareSerial(a, b uint32) int {
82 if a == b {
83 return 0
84 }
85 // Use uint32 modular subtraction per RFC 1982 Section 3.2. If (a - b) mod 2^32 is in
86 // (0, 2^31), a is greater; otherwise a is less (or undefined at exactly 2^31).
87 if (a - b) <= MaxSerialIncrement {
88 return 1
89 }
90 return -1
91 }
92
93 // EqualSerial return true if a and b are equal. This function is here for consistency only.
94 func EqualSerial(a, b uint32) bool { return a == b }