github.com/biogo/biogo@v1.0.4/io/seqio/seqio.go (about) 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 seqio provides interfaces for sequence I/O functions. 6 package seqio 7 8 import ( 9 "github.com/biogo/biogo/seq" 10 11 "io" 12 ) 13 14 // A SequenceAppender is a generic sequence type that can append elements. 15 type SequenceAppender interface { 16 SetName(string) error 17 SetDescription(string) error 18 seq.Appender 19 seq.Sequence 20 } 21 22 // Reader is the common seq.Sequence reader interface. 23 type Reader interface { 24 // Read reads a seq.Sequence, returning the sequence and any error that 25 // occurred during the read. 26 Read() (seq.Sequence, error) 27 } 28 29 // Writer is the common seq.Sequence writer interface. 30 type Writer interface { 31 // Write write a seq.Sequence, returning the number of bytes written and any 32 // error that occurs during the write. 33 Write(seq.Sequence) (int, error) 34 } 35 36 // Scanner wraps a Reader to provide a convenient loop interface for reading sequence data. 37 // Successive calls to the Scan method will step through the sequences of the provided 38 // Reader. Scanning stops unrecoverably at EOF or the first error. 39 // 40 // Note that it is possible for a Reader to return a valid sequence and a non-nil error. So 41 // programs that need more control over error handling should use a Reader directly instead. 42 type Scanner struct { 43 r Reader 44 seq seq.Sequence 45 err error 46 } 47 48 // NewScanner returns a Scanner to read from r. 49 func NewScanner(r Reader) *Scanner { return &Scanner{r: r} } 50 51 type funcReader func() (seq.Sequence, error) 52 53 func (f funcReader) Read() (seq.Sequence, error) { return f() } 54 55 // NewScannerFromFunc returns a Scanner to read sequences returned by calls to f. 56 func NewScannerFromFunc(f func() (seq.Sequence, error)) *Scanner { return &Scanner{r: funcReader(f)} } 57 58 // Next advances the Scanner past the next sequence, which will then be available through 59 // the Seq method. It returns false when the scan stops, either by reaching the end of the 60 // input or an error. After Next returns false, the Error method will return any error that 61 // occurred during scanning, except that if it was io.EOF, Error will return nil. 62 func (s *Scanner) Next() bool { 63 if s.err != nil { 64 return false 65 } 66 s.seq, s.err = s.r.Read() 67 return s.err == nil 68 } 69 70 // Error returns the first non-EOF error that was encountered by the Scanner. 71 func (s *Scanner) Error() error { 72 if s.err == io.EOF { 73 return nil 74 } 75 return s.err 76 } 77 78 // Seq returns the most recent sequence read by a call to Next. 79 func (s *Scanner) Seq() seq.Sequence { return s.seq }