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)
72 func (taglib *tagLibrary) TagLen() int {
77 twobit = func() []tagmapKey {
78 r := make([]tagmapKey, 256)
89 isbase = func() []bool {
90 r := make([]bool, 256)
103 func (taglib *tagLibrary) setTags(tags [][]byte) error {
104 taglib.keylen = tagmapKeySize
105 for _, t := range tags {
106 if l := len(t); taglib.keylen > l {
110 taglib.keymask = tagmapKey((1 << (taglib.keylen * 2)) - 1)
111 taglib.tagmap = map[tagmapKey]tagInfo{}
112 for i, tag := range tags {
114 for _, b := range tag[:taglib.keylen] {
115 key = (key << 2) | twobit[int(b)]
117 if _, ok := taglib.tagmap[key]; ok {
118 return fmt.Errorf("first %d bytes of tag %d (%x) are not unique", taglib.keylen, i, key)
120 taglib.tagmap[key] = tagInfo{tagID(i), tag}
125 func (taglib *tagLibrary) Tags() [][]byte {
126 out := make([][]byte, len(taglib.tagmap))
127 untwobit := []byte{'a', 'c', 'g', 't'}
128 for key, info := range taglib.tagmap {
129 seq := make([]byte, taglib.keylen)
130 for i := len(seq) - 1; i >= 0; i-- {
131 seq[i] = untwobit[int(key)&3]
134 out[int(info.id)] = seq