| 1 |
// Copyright ©2011-2013 The bíogo Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
// Package featio provides interfaces for feature I/O functions. |
| 6 |
package featio |
| 7 |
|
| 8 |
import ( |
| 9 |
"github.com/biogo/biogo/feat" |
| 10 |
|
| 11 |
"io" |
| 12 |
) |
| 13 |
|
| 14 |
// Reader is the common feat.Feature reader interface. |
| 15 |
type Reader interface { |
| 16 |
// Read reads a feat.Feature, returning any error that occurs during the read. |
| 17 |
Read() (feat.Feature, error) |
| 18 |
} |
| 19 |
|
| 20 |
// Writer is the common feat.Feature writer interface. |
| 21 |
type Writer interface { |
| 22 |
// Write write a feat.Feature, returning the number of bytes written and any |
| 23 |
// error that occurs during the write. |
| 24 |
Write(feat.Feature) (n int, err error) |
| 25 |
} |
| 26 |
|
| 27 |
// Scanner wraps a Reader to provide a convenient loop interface for reading feature data. |
| 28 |
// Successive calls to the Scan method will step through the features of the provided |
| 29 |
// Reader. Scanning stops unrecoverably at EOF or the first error. |
| 30 |
// |
| 31 |
// Note that it is possible for a Reader to return a valid feature and a non-nil error. So |
| 32 |
// programs that need more control over error handling should use a Reader directly instead. |
| 33 |
type Scanner struct { |
| 34 |
r Reader |
| 35 |
f feat.Feature |
| 36 |
err error |
| 37 |
} |
| 38 |
|
| 39 |
// NewScanner returns a Scanner to read from r. |
| 40 |
func NewScanner(r Reader) *Scanner { return &Scanner{r: r} } |
| 41 |
|
| 42 |
type funcReader func() (feat.Feature, error) |
| 43 |
|
| 44 |
func (f funcReader) Read() (feat.Feature, error) { return f() } |
| 45 |
|
| 46 |
// NewScannerFromFunc returns a Scanner to read features returned by calls to f. |
| 47 |
func NewScannerFromFunc(f func() (feat.Feature, error)) *Scanner { return &Scanner{r: funcReader(f)} } |
| 48 |
|
| 49 |
// Next advances the Scanner past the next feature, which will then be available through |
| 50 |
// the Feat method. It returns false when the scan stops, either by reaching the end of the |
| 51 |
// input or an error. After Next returns false, the Error method will return any error that |
| 52 |
// occurred during scanning, except that if it was io.EOF, Error will return nil. |
| 53 |
func (s *Scanner) Next() bool { |
| 54 |
if s.err != nil { |
| 55 |
return false |
| 56 |
} |
| 57 |
s.f, s.err = s.r.Read() |
| 58 |
return s.err == nil |
| 59 |
} |
| 60 |
|
| 61 |
// Error returns the first non-EOF error that was encountered by the Scanner. |
| 62 |
func (s *Scanner) Error() error { |
| 63 |
if s.err == io.EOF { |
| 64 |
return nil |
| 65 |
} |
| 66 |
return s.err |
| 67 |
} |
| 68 |
|
| 69 |
// Feat returns the most recent feature read by a call to Next. |
| 70 |
func (s *Scanner) Feat() feat.Feature { return s.f } |