| 1 | // Copyright ©2020 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 fai |
| 6 | |
| 7 | import ( |
| 8 | "errors" |
| 9 | "io" |
| 10 | ) |
| 11 | |
| 12 | // File is a sequence file with an FAI index. |
| 13 | type File struct { |
| 14 | Index |
| 15 | |
| 16 | r io.ReaderAt |
| 17 | } |
| 18 | |
| 19 | // NewFile returns the sequence file for the given reader and associates it with |
| 20 | // the specified index. |
| 21 | func NewFile(r io.ReaderAt, idx Index) *File { |
| 22 | return &File{r: r, Index: idx} |
| 23 | } |
| 24 | |
| 25 | // Seq returns a handle to the complete sequence identified by the given name. |
| 26 | func (f *File) Seq(name string) (*Seq, error) { |
| 27 | rec, ok := f.Index[name] |
| 28 | if !ok { |
| 29 | return nil, errors.New("fai: no sequence") |
| 30 | } |
| 31 | return &Seq{r: f.r, Record: rec, end: rec.Length}, nil |
| 32 | } |
| 33 | |
| 34 | // Seq returns a handle to the sequence identified by the given name from the |
| 35 | // start position until the end position. |
| 36 | func (f *File) SeqRange(name string, start, end int) (*Seq, error) { |
| 37 | if start < 0 || end < 0 || end < start { |
| 38 | return nil, errors.New("fai: index out of range") |
| 39 | } |
| 40 | rec, ok := f.Index[name] |
| 41 | if !ok { |
| 42 | return nil, errors.New("fai: no sequence") |
| 43 | } |
| 44 | if rec.Length < start || rec.Length < end { |
| 45 | return nil, errors.New("fai: index out of range") |
| 46 | } |
| 47 | return &Seq{r: f.r, Record: rec, cur: start, start: start, end: end}, nil |
| 48 | } |
| 49 | |
| 50 | // Seq is a handle to a sequence segment obtained from a File. |
| 51 | type Seq struct { |
| 52 | Record |
| 53 | |
| 54 | r io.ReaderAt |
| 55 | |
| 56 | cur int |
| 57 | start, end int |
| 58 | } |
| 59 | |
| 60 | // Reset resets the position of the cursor into the sequence segment to the original start. |
| 61 | func (s *Seq) Reset() { |
| 62 | s.cur = s.start |
| 63 | } |
| 64 | |
| 65 | // Read reads sequence data from the Seq into b. |
| 66 | func (s *Seq) Read(b []byte) (int, error) { |
| 67 | if len(b) == 0 { |
| 68 | return 0, nil |
| 69 | } |
| 70 | var n int |
| 71 | end := int(s.Record.position(s.end)) |
| 72 | for s.cur < s.end { |
| 73 | cur := s.Record.position(s.cur) |
| 74 | eol := min(s.Record.endOfLineOffset(s.cur), end-int(cur)) |
| 75 | _n, err := s.r.ReadAt(b[:min(eol, len(b))], cur) |
| 76 | s.cur += _n |
| 77 | n += _n |
| 78 | b = b[_n:] |
| 79 | if err != nil || len(b) == 0 { |
| 80 | return n, err |
| 81 | } |
| 82 | } |
| 83 | return n, io.EOF |
| 84 | } |
| 85 | |
| 86 | func min(a, b int) int { |
| 87 | if a < b { |
| 88 | return a |
| 89 | } |
| 90 | return b |
| 91 | } |