Files
learngo/logparser/v5/pipe/logcount.go

40 lines
913 B
Go
Raw Permalink Normal View History

2019-08-26 21:52:47 +03:00
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
2019-10-30 19:34:44 +03:00
// For more tutorials : https://learngoprogramming.com
// In-person training : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus
2019-08-26 21:52:47 +03:00
2019-08-28 23:46:42 +03:00
package pipe
2019-08-26 21:52:47 +03:00
import "fmt"
2019-08-28 23:46:42 +03:00
// logCount counts the yielded records.
2019-08-26 21:52:47 +03:00
type logCount struct {
2019-08-28 23:46:42 +03:00
Iterator
2019-08-26 21:52:47 +03:00
n int
}
2019-08-28 23:46:42 +03:00
// Each yields to the inner iterator while counting the records.
// Reports the record number on an error.
func (lc *logCount) Each(yield func(Record) error) error {
2019-08-29 16:08:46 +03:00
count := func(r Record) error {
2019-08-26 21:52:47 +03:00
lc.n++
2019-08-28 23:46:42 +03:00
return yield(r)
2019-08-29 16:08:46 +03:00
}
err := lc.Iterator.Each(count)
2019-08-26 21:52:47 +03:00
if err != nil {
// lc.n+1: iterator.each won't call yield on err
return fmt.Errorf("record %d: %v", lc.n+1, err)
}
return nil
}
2019-08-28 23:46:42 +03:00
// count returns the last read record number.
2019-08-26 21:52:47 +03:00
func (lc *logCount) count() int {
return lc.n
}