Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update First(n int) to read no more data than necessary #199

Merged
merged 4 commits into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions script.go
Original file line number Diff line number Diff line change
Expand Up @@ -514,21 +514,24 @@ func (p *Pipe) FilterScan(filter func(string, io.Writer)) *Pipe {

// First produces only the first n lines of the pipe's contents, or all the
// lines if there are less than n. If n is zero or negative, there is no output
// at all.
// at all. When n lines have been produced, First stops reading its input and
// sends EOF to its output.
func (p *Pipe) First(n int) *Pipe {
if p.Error() != nil {
return p
}
if n <= 0 {
return NewPipe()
}
i := 0
return p.FilterScan(func(line string, w io.Writer) {
if i >= n {
return
return p.Filter(func(r io.Reader, w io.Writer) error {
scanner := newScanner(r)
for i := 0; i < n && scanner.Scan(); i++ {
_, err := fmt.Fprintln(w, scanner.Text())
if err != nil {
return err
}
}
fmt.Fprintln(w, line)
i++
return scanner.Err()
})
}

Expand Down
18 changes: 18 additions & 0 deletions script_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,24 @@ func TestFirstHasNoEffectGivenLessThanNInputLines(t *testing.T) {
}
}

func TestFirstDoesNotConsumeUnnecessaryData(t *testing.T) {
t.Parallel()
// First uses a 4096-byte buffer, so will always read at least
// that much, but no more (once N lines have been read).
r := strings.NewReader(strings.Repeat("line\n", 1000))
got, err := script.NewPipe().WithReader(r).First(1).String()
if err != nil {
t.Fatal(err)
}
want := "line\n"
if want != got {
t.Errorf("want output %q, got %q", want, got)
}
if r.Len() == 0 {
t.Errorf("no data left in reader")
}
}

func TestFreqHandlesLongLines(t *testing.T) {
t.Parallel()
got, err := script.Echo(longLine).Freq().Slice()
Expand Down
Loading