Skip to content

Commit

Permalink
add Scanner.Contains (#75)
Browse files Browse the repository at this point in the history
  • Loading branch information
nofun97 authored Jun 5, 2020
1 parent 1e57441 commit f2e7de0
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
9 changes: 9 additions & 0 deletions parser/scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,15 @@ var (
DefaultLimit = 1
)

func (s Scanner) Contains(sn Scanner) bool {
if s.Filename() != sn.Filename() || s.src != sn.src {
return false
}

return s.sliceStart <= sn.sliceStart &&
s.sliceStart+s.sliceLength >= sn.sliceStart+sn.sliceLength
}

func (s Scanner) Context(limitLines int) string {
end := s.sliceStart + s.sliceLength
lineno, colno := s.Position()
Expand Down
46 changes: 46 additions & 0 deletions parser/scanner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,52 @@ func TestScannerMerge(t *testing.T) {
assertMergedScannerErr(t, errors.New("scanners' sources are not the same: {one\ntwo\nthree\nfour } vs {another src }"), []Scanner{*NewScanner(str), *NewScanner("another src")})
}

func TestContains(t *testing.T) {
t.Parallel()

// in the middle
s1 := NewScannerAt("this is a random sentence", 5, 3)
s2 := NewScannerAt("this is a random sentence", 6, 1)
assert.True(t, s1.Contains(*s2))

// same range
s2.sliceStart = 5
s2.sliceLength = 3
assert.True(t, s1.Contains(*s2))

// start same, smaller length
s2.sliceLength = 2
assert.True(t, s1.Contains(*s2))

// start in the middle, end at the same part
s2.sliceStart = 6
assert.True(t, s1.Contains(*s2))

// start earlier
s2.sliceStart = 4
assert.False(t, s1.Contains(*s2))

// start in the middle, end outside
s2.sliceStart = 6
s2.sliceLength = 5
assert.False(t, s1.Contains(*s2))

// start and end outside range
s2.sliceStart = 4
s2.sliceLength = 5
assert.False(t, s1.Contains(*s2))

// different filename
s1 = NewScannerWithFilename("file1", "file1.wbnf")
s2 = NewScannerWithFilename("file2", "file2.wbnf")
assert.False(t, s1.Contains(*s2))

// different source
s1 = NewScanner("source1")
s2 = NewScanner("source2")
assert.False(t, s1.Contains(*s2))
}

func assertMergedScanner(t *testing.T, src source, offset, length int, items []Scanner) {
s, err := MergeScanners(items...)
assert.NoError(t, err)
Expand Down

0 comments on commit f2e7de0

Please sign in to comment.