Add more efficient label test functions

Also add tests for it.
This commit is contained in:
Miek Gieben 2013-06-20 14:24:14 +00:00
parent d526e0beee
commit 1d22bfdb4d
2 changed files with 50 additions and 9 deletions

27
label_test.go Normal file
View File

@ -0,0 +1,27 @@
// Copyright 2011 Miek Gieben. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package dns
import (
"testing"
)
func TestLenLabels(t *testing.T) {
labels := map[string]int{
"miek.nl": 2,
".": 0,
"www.miek.nl.": 3,
"www.miek.nl": 3,
"www..miek.nl": 4,
`www\.miek.nl`: 2,
`www\\.miek.nl`: 3,
}
for owner, lab := range labels {
if l := LenLabels2(owner); l != lab {
t.Logf("%s should have %d labels, got %d\n", owner, lab, l)
t.Fail()
}
}
}

View File

@ -64,14 +64,14 @@ func CompareLabels(s1, s2 string) (n int) {
return
}
// LenLabels returns the number of labels in a domain name.
func LenLabels(s string) (labels int) {
// lenLabels returns the number of labels in a domain name.
func lenLabels(s string) (labels int) {
if s == "." {
return
}
last := byte('.')
lastlast := byte('.')
s = Fqdn(s) // Make fully qualified
s = Fqdn(s)
for i := 0; i < len(s); i++ {
if s[i] == '.' {
if last == '\\' {
@ -88,6 +88,24 @@ func LenLabels(s string) (labels int) {
return
}
// LenLabels returns the number of labels in the string s
func LenLabels(s string) (labels int) {
if s == "." {
return
}
s = Fqdn(s)
off := 0
end := false
for {
off, end = nextLabel(s, off+1)
if end {
return
}
labels++
}
}
// NextLabel returns the index of the start of the next label in the
// string s. The bool end is true when the end of the string has been
// reached.
@ -95,10 +113,10 @@ func nextLabel(s string, offset int) (i int, end bool) {
// The other label function are quite generous with memory,
// this one does not allocate.
quote := false
for i = 0; i < len(s); i++ {
for i = offset; i < len(s); i++ {
switch s[i] {
case '\\':
quote = true
quote = !quote
default:
quote = false
case '.':
@ -110,8 +128,4 @@ func nextLabel(s string, offset int) (i int, end bool) {
}
}
return i, true
}