| 1 | package kallsyms |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "io" |
| 7 | ) |
| 8 | |
| 9 | // reader is a line and word-oriented reader built for reading /proc/kallsyms. |
| 10 | // It takes an io.Reader and iterates its contents line by line, then word by |
| 11 | // word. |
| 12 | // |
| 13 | // It's designed to allow partial reading of lines without paying the cost of |
| 14 | // allocating objects that will never be accessed, resulting in less work for |
| 15 | // the garbage collector. |
| 16 | type reader struct { |
| 17 | s *bufio.Scanner |
| 18 | line []byte |
| 19 | word []byte |
| 20 | |
| 21 | err error |
| 22 | } |
| 23 | |
| 24 | func newReader(r io.Reader) *reader { |
| 25 | return &reader{ |
| 26 | s: bufio.NewScanner(r), |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | // Bytes returns the current word as a byte slice. |
| 31 | func (r *reader) Bytes() []byte { |
| 32 | return r.word |
| 33 | } |
| 34 | |
| 35 | // Text returns the output of Bytes as a string. |
| 36 | func (r *reader) Text() string { |
| 37 | return string(r.Bytes()) |
| 38 | } |
| 39 | |
| 40 | // Line advances the reader to the next line in the input. Calling Line resets |
| 41 | // the current word, making [reader.Bytes] and [reader.Text] return empty |
| 42 | // values. Follow this up with a call to [reader.Word]. |
| 43 | // |
| 44 | // Like [bufio.Scanner], [reader.Err] needs to be checked after Line returns |
| 45 | // false to determine if an error occurred during reading. |
| 46 | // |
| 47 | // Returns true if Line can be called again. Returns false if all lines in the |
| 48 | // input have been read. |
| 49 | func (r *reader) Line() bool { |
| 50 | for r.s.Scan() { |
| 51 | line := r.s.Bytes() |
| 52 | if len(line) == 0 { |
| 53 | continue |
| 54 | } |
| 55 | |
| 56 | r.line = line |
| 57 | r.word = nil |
| 58 | |
| 59 | return true |
| 60 | } |
| 61 | if err := r.s.Err(); err != nil { |
| 62 | r.err = err |
| 63 | } |
| 64 | |
| 65 | return false |
| 66 | } |
| 67 | |
| 68 | // Word advances the reader to the next word in the current line. |
| 69 | // |
| 70 | // Returns true if a word is found and Word should be called again. Returns |
| 71 | // false when all words on the line have been read. |
| 72 | func (r *reader) Word() bool { |
| 73 | line := bytes.TrimSpace(r.line) |
| 74 | |
| 75 | if len(line) == 0 { |
| 76 | return false |
| 77 | } |
| 78 | |
| 79 | var found bool |
| 80 | r.word, r.line, found = bytes.Cut(line, []byte{' '}) |
| 81 | if !found { |
| 82 | r.word, r.line, _ = bytes.Cut(line, []byte{'\t'}) |
| 83 | } |
| 84 | return true |
| 85 | } |
| 86 | |
| 87 | func (r *reader) Err() error { |
| 88 | return r.err |
| 89 | } |