dns/labels.go

55 lines
1.1 KiB
Go
Raw Normal View History

2012-01-11 01:55:52 +11:00
package dns
// Holds a bunch of helper functions for dealing with labels.
// SplitLabels splits a domainname string into its labels.
func SplitLabels(s string) []string {
k := 0
labels := make([]string, 0)
2012-01-28 10:35:37 +11:00
last := byte('.')
lastlast := byte('.')
s = Fqdn(s) // Make fully qualified
2012-01-11 01:55:52 +11:00
for i := 0; i < len(s); i++ {
if s[i] == '.' {
2012-01-28 10:35:37 +11:00
if last == '\\' {
if lastlast != '\\' {
// do nothing
continue
}
2012-01-11 01:55:52 +11:00
}
labels = append(labels, s[k:i])
2012-01-11 01:55:52 +11:00
k = i + 1 // + dot
}
2012-01-28 10:35:37 +11:00
lastlast = last
last = s[i]
2012-01-11 01:55:52 +11:00
}
return labels
}
// CompareLabels compares the strings s1 and s2 and
2012-01-11 02:04:32 +11:00
// returns how many labels they have in common starting from the right.
2012-01-11 18:51:43 +11:00
// The comparison stops at the first inequality.
2012-01-11 02:04:32 +11:00
//
2012-01-11 01:55:52 +11:00
// www.miek.nl and miek.nl have two labels in common: miek and nl
// www.miek.nl and www.bla.nl have one label in common: nl
func CompareLabels(s1, s2 string) (n int) {
l1 := SplitLabels(s1)
l2 := SplitLabels(s2)
x1 := len(l1) - 1
x2 := len(l2) - 1
2012-01-11 01:55:52 +11:00
for {
if x1 < 0 || x2 < 0 {
break
}
if l1[x1] == l2[x2] {
n++
} else {
break
}
x1--
x2--
}
return
}