From 1f586fdcdace10a157f3a9160f69def6c4ff08c3 Mon Sep 17 00:00:00 2001 From: Miek Gieben Date: Thu, 12 Sep 2013 09:58:42 +0100 Subject: [PATCH] Fixup PrevLabel and add a test --- labels.go | 7 +++++-- labels_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/labels.go b/labels.go index 4467b415..7742dbd9 100644 --- a/labels.go +++ b/labels.go @@ -146,13 +146,16 @@ func NextLabel(s string, offset int) (i int, end bool) { // PrevLabel returns the index of the label when starting from the right and // jumping n labels to the left. -// The bool start is true when the start of the string has been reached. +// The bool start is true when the start of the string has been overshot. func PrevLabel(s string, n int) (i int, start bool) { + if n == 0 { + return len(s), false + } lab := Split(s) if lab == nil { return 0, true } - if len(lab) < n { + if n > len(lab) { return 0, true } return lab[len(lab)-n], false diff --git a/labels_test.go b/labels_test.go index 1945fa64..bcad98e6 100644 --- a/labels_test.go +++ b/labels_test.go @@ -94,6 +94,35 @@ func TestSplit2(t *testing.T) { } } +func TestPrevLabel(t *testing.T) { + type prev struct { + string + int + } + prever := map[prev]int{ + prev{"www.miek.nl.", 0}: 12, + prev{"www.miek.nl.", 1}: 9, + prev{"www.miek.nl.", 2}: 4, + + prev{"www.miek.nl", 0}: 11, + prev{"www.miek.nl", 1}: 9, + prev{"www.miek.nl", 2}: 4, + + prev{"www.miek.nl.", 5}: 0, + prev{"www.miek.nl", 5}: 0, + + prev{"www.miek.nl.", 3}: 0, + prev{"www.miek.nl", 3}: 0, + } + for s, i := range prever { + x, ok := PrevLabel(s.string, s.int) + if i != x { + t.Logf("Label should be %d, got %d, %t: preving %d, %s\n", i, x, ok, s.int, s.string) + t.Fail() + } + } +} + func TestCountLabel(t *testing.T) { splitter := map[string]int{ "www.miek.nl.": 3,