10 const tagmapKeySize = 32
17 id tagID // 0-based position in input tagset
21 type tagLibrary struct {
22 tagmap map[tagmapKey]tagInfo
27 func (taglib *tagLibrary) Load(rdr io.Reader) error {
29 scanner := bufio.NewScanner(rdr)
31 data := scanner.Bytes()
32 if len(data) > 0 && data[0] == '>' {
34 seqs = append(seqs, append([]byte(nil), data...))
37 if err := scanner.Err(); err != nil {
40 return taglib.setTags(seqs)
43 func (taglib *tagLibrary) FindAll(buf []byte, fn func(id tagID, pos, taglen int)) {
45 valid := 0 // if valid < taglib.keylen, key has "no data" zeroes that are otherwise indistinguishable from "A"
46 for i, base := range buf {
47 if !isbase[int(base)] {
51 key = ((key << 2) | twobit[int(base)]) & taglib.keymask
54 if valid < taglib.keylen {
56 } else if taginfo, ok := taglib.tagmap[key]; !ok {
58 } else if tagstart := i - taglib.keylen + 1; len(taginfo.tagseq) > taglib.keylen && (len(buf) < i+len(taginfo.tagseq) || !bytes.Equal(taginfo.tagseq, buf[i:i+len(taginfo.tagseq)])) {
59 // key portion matches, but not the entire tag
62 fn(taginfo.id, tagstart, len(taginfo.tagseq))
63 valid = 0 // don't try to match overlapping tags
68 func (taglib *tagLibrary) Len() int {
69 return len(taglib.tagmap)
73 twobit = func() []tagmapKey {
74 r := make([]tagmapKey, 256)
85 isbase = func() []bool {
86 r := make([]bool, 256)
99 func (taglib *tagLibrary) setTags(tags [][]byte) error {
100 taglib.keylen = tagmapKeySize
101 for _, t := range tags {
102 if l := len(t); taglib.keylen > l {
106 taglib.keymask = tagmapKey((1 << (taglib.keylen * 2)) - 1)
107 taglib.tagmap = map[tagmapKey]tagInfo{}
108 for i, tag := range tags {
110 for _, b := range tag[:taglib.keylen] {
111 key = (key << 2) | twobit[int(b)]
113 if _, ok := taglib.tagmap[key]; ok {
114 return fmt.Errorf("first %d bytes of tag %d (%x) are not unique", taglib.keylen, i, key)
116 taglib.tagmap[key] = tagInfo{tagID(i), tag}
121 func (taglib *tagLibrary) Tags() [][]byte {
122 out := make([][]byte, len(taglib.tagmap))
123 untwobit := []byte{'a', 'c', 'g', 't'}
124 for key, info := range taglib.tagmap {
125 seq := make([]byte, taglib.keylen)
126 for i := len(seq) - 1; i >= 0; i-- {
127 seq[i] = untwobit[int(key)&3]
130 out[int(info.id)] = seq