Add label functions and tests

This commit is contained in:
Miek Gieben 2012-01-10 15:55:52 +01:00
parent 15d82f0b34
commit d2acd22822
4 changed files with 81 additions and 21 deletions

View File

@ -15,6 +15,7 @@ GOFILES=\
edns.go\
keygen.go\
kscan.go\
labels.go\
msg.go\
nsec3.go \
rawmsg.go \

View File

@ -268,24 +268,3 @@ func Fqdn(s string) string {
}
return s + "."
}
// SplitLabels splits a domainname string into its labels.
// No syntax checks are performed.
// TODO: labels functions...
func SplitLabels(s string) (labels []string) {
last := byte('.')
k := 0
l := 0
for i := 0; i < len(s); i++ {
if s[i] == '.' {
if last == '\\' {
// do nothing
break
}
labels[l] = s[k:i]
k = i+1 // + dot
}
last = s[i]
}
return
}

30
label_test.go Normal file
View File

@ -0,0 +1,30 @@
package dns
import (
"testing"
)
func TestCompareLabels(t *testing.T) {
s1 := "www.miek.nl."
s2 := "miek.nl."
s3 := "www.bla.nl."
s4 := "nl.www.bla."
s5 := "nl"
if CompareLabels(s1, s2) != 2 {
t.Logf("%s with %s should be %d", s1, s2, 2)
t.Fail()
}
if CompareLabels(s1, s3) != 1 {
t.Logf("%s with %s should be %d", s1, s3, 1)
t.Fail()
}
if CompareLabels(s3, s4) != 0 {
t.Logf("%s with %s should be %d", s3, s4, 0)
t.Fail()
}
if CompareLabels(s1, s5) != 1 {
t.Logf("%s with %s should be %d", s1, s5, 1)
t.Fail()
}
}

50
labels.go Normal file
View File

@ -0,0 +1,50 @@
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 {
last := byte('.')
k := 0
labels := make([]string, 0)
s = Fqdn(s) // Make fully qualified
for i := 0; i < len(s); i++ {
if s[i] == '.' {
if last == '\\' {
// do nothing
break
}
labels = append(labels,s[k:i])
k = i + 1 // + dot
}
last = s[i]
}
return labels
}
// CompareLabels compares the strings s1 and s2 and
// returns how many labels they have in common.
// The compare start with the right most label and stops at
// the label that is different.
// 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
for {
if x1 < 0 || x2 < 0 {
break
}
if l1[x1] == l2[x2] {
n++
} else {
break
}
x1--
x2--
}
return
}