1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
use utils::{TextIterator, IntoTextIterator};
use std::collections::VecDeque;
use std::iter;
pub struct Finder {
start_codons: Vec<VecDeque<u8>>,
stop_codons: Vec<VecDeque<u8>>,
min_len: usize,
}
impl Finder {
pub fn new<'a>(start_codons: Vec<&'a [u8; 3]>,
stop_codons: Vec<&'a [u8; 3]>,
min_len: usize)
-> Self {
Finder {
start_codons: start_codons.into_iter()
.map(|x| {
x.into_iter()
.map(|&x| x as u8)
.collect::<VecDeque<u8>>()
})
.collect(),
stop_codons: stop_codons.into_iter()
.map(|x| {
x.into_iter()
.map(|&x| x as u8)
.collect::<VecDeque<u8>>()
})
.collect(),
min_len: min_len,
}
}
pub fn find_all<'a, I: IntoTextIterator<'a>>(&'a self, seq: I) -> Matches<I::IntoIter> {
Matches {
finder: self,
state: State::new(),
seq: seq.into_iter().enumerate(),
}
}
}
pub struct Orf {
pub start: usize,
pub end: usize,
pub offset: i8,
}
struct State {
start_pos: [Option<usize>; 3],
codon: VecDeque<u8>,
}
impl State {
pub fn new() -> Self {
State {
start_pos: [None, None, None],
codon: VecDeque::new(),
}
}
}
pub struct Matches<'a, I: TextIterator<'a>> {
finder: &'a Finder,
state: State,
seq: iter::Enumerate<I>,
}
impl<'a, I: Iterator<Item = &'a u8>> Iterator for Matches<'a, I> {
type Item = Orf;
fn next(&mut self) -> Option<Orf> {
let mut result: Option<Orf> = None;
let mut offset: usize;
for (index, &nuc) in self.seq.by_ref() {
if self.state.codon.len() >= 3 {
self.state.codon.pop_front();
}
self.state.codon.push_back(nuc);
offset = (index + 1) % 3;
if self.state.start_pos[offset].is_some() {
if self.finder.stop_codons.contains(&self.state.codon) {
if index + 1 - self.state.start_pos[offset].unwrap() > self.finder.min_len {
result = Some(Orf {
start: self.state.start_pos[offset].unwrap() - 2,
end: index + 1,
offset: offset as i8,
});
}
self.state.start_pos[offset] = None;
}
} else if self.finder.start_codons.contains(&self.state.codon) {
self.state.start_pos[offset] = Some(index);
}
if result.is_some() {
return result;
}
}
None
}
}