| 1 |
package dnsutil |
| 2 |
|
| 3 |
// Common compares the names a and b and returns how many labels they have in common starting |
| 4 |
// from the *right*. The comparison stops at the first inequality. For example: |
| 5 |
// |
| 6 |
// - www.miek.nl. and miek.nl. have two labels in common: miek and nl |
| 7 |
// - www.miek.nl. and www.bla.nl. have one label in common: nl |
| 8 |
// - . and . have no labels in common. |
| 9 |
// |
| 10 |
// a and b must be syntactically valid domain names, see [IsName] and [IsFqdn]. |
| 11 |
func Common(a, b string) (n int) { |
| 12 |
// copy-ish of CompareName |
| 13 |
if a == "." || b == "." { // shortcut root, as we would return 1 |
| 14 |
return 0 |
| 15 |
} |
| 16 |
|
| 17 |
lasta := len(a) |
| 18 |
lastb := len(b) |
| 19 |
for { |
| 20 |
cura, overshota := Prev(a, lasta) |
| 21 |
curb, overshotb := Prev(b, lastb) |
| 22 |
x := compareLabel(a[cura:lasta-1], b[curb:lastb-1]) |
| 23 |
if x != 0 { |
| 24 |
return n |
| 25 |
} |
| 26 |
n++ |
| 27 |
if overshota || overshotb { |
| 28 |
return n |
| 29 |
} |
| 30 |
lasta = cura |
| 31 |
lastb = curb |
| 32 |
} |
| 33 |
} |