-
Notifications
You must be signed in to change notification settings - Fork 81
/
mod.rs
257 lines (219 loc) · 6.99 KB
/
mod.rs
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// Copyright 2020 Manuel Landesfeind, Evotec International GmbH
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
//!
//! Module for working with faidx-indexed FASTA files.
//!
use std::ffi;
use std::path::Path;
use url::Url;
use crate::htslib;
use crate::errors::{Error, Result};
use crate::utils::path_as_bytes;
/// A Fasta reader.
#[derive(Debug)]
pub struct Reader {
inner: *mut htslib::faidx_t,
}
impl Reader {
/// Create a new Reader from a path.
///
/// # Arguments
///
/// * `path` - the path to open.
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
Self::new(&path_as_bytes(path, true)?)
}
/// Create a new Reader from an URL.
///
/// # Arguments
///
/// * `url` - the url to open
pub fn from_url(url: &Url) -> Result<Self, Error> {
Self::new(url.as_str().as_bytes())
}
/// Internal function to create a Reader from some sort of path (could be file path but also URL).
/// The path or URL will be handled by the c-implementation transparently.
///
/// # Arguments
///
/// * `path` - the path or URL to open
fn new(path: &[u8]) -> Result<Self, Error> {
let cpath = ffi::CString::new(path).unwrap();
let inner = unsafe { htslib::fai_load(cpath.as_ptr()) };
Ok(Self { inner })
}
/// Fetch the sequence as a byte array.
///
/// # Arguments
///
/// * `name` - the name of the template sequence (e.g., "chr1")
/// * `begin` - the offset within the template sequence (starting with 0)
/// * `end` - the end position to return (if smaller than `begin`, the behavior is undefined).
pub fn fetch_seq<N: AsRef<str>>(&self, name: N, begin: usize, end: usize) -> Result<&[u8]> {
if begin > std::i64::MAX as usize {
return Err(Error::FaidxPositionTooLarge);
}
if end > std::i64::MAX as usize {
return Err(Error::FaidxPositionTooLarge);
}
let cname = ffi::CString::new(name.as_ref().as_bytes()).unwrap();
let len_out: i64 = 0;
let cseq = unsafe {
let ptr = htslib::faidx_fetch_seq64(
self.inner, //*const faidx_t,
cname.as_ptr(), // c_name
begin as htslib::hts_pos_t, // p_beg_i
end as htslib::hts_pos_t, // p_end_i
&mut (len_out as htslib::hts_pos_t), //len
);
ffi::CStr::from_ptr(ptr)
};
Ok(cseq.to_bytes())
}
/// Fetches the sequence and returns it as string.
///
/// # Arguments
///
/// * `name` - the name of the template sequence (e.g., "chr1")
/// * `begin` - the offset within the template sequence (starting with 0)
/// * `end` - the end position to return (if smaller than `begin`, the behavior is undefined).
pub fn fetch_seq_string<N: AsRef<str>>(
&self,
name: N,
begin: usize,
end: usize,
) -> Result<String> {
let bytes = self.fetch_seq(name, begin, end)?;
Ok(std::str::from_utf8(bytes).unwrap().to_owned())
}
/// Fetches the number of sequences in the fai index
pub fn n_seqs(&self) -> u64 {
let n = unsafe { htslib::faidx_nseq(self.inner) };
n as u64
}
/// Fetches the i-th sequence name
///
/// # Arguments
///
/// * `i` - index to query
pub fn seq_name(&self, i: i32) -> Result<String> {
let cname = unsafe {
let ptr = htslib::faidx_iseq(self.inner, i);
ffi::CStr::from_ptr(ptr)
};
let out = match cname.to_str() {
Ok(s) => s.to_string(),
Err(_) => {
return Err(Error::FaidxBadSeqName);
}
};
Ok(out)
}
}
impl Drop for Reader {
fn drop(&mut self) {
unsafe {
htslib::fai_destroy(self.inner);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn open_reader() -> Reader {
Reader::from_path(format!("{}/test/test_cram.fa", env!("CARGO_MANIFEST_DIR")))
.ok()
.unwrap()
}
#[test]
fn faidx_open() {
open_reader();
}
#[test]
fn faidx_read_chr_first_base() {
let r = open_reader();
let bseq = r.fetch_seq("chr1", 0, 0).unwrap();
assert_eq!(bseq.len(), 1);
assert_eq!(bseq, b"G");
let seq = r.fetch_seq_string("chr1", 0, 0).unwrap();
assert_eq!(seq.len(), 1);
assert_eq!(seq, "G");
}
#[test]
fn faidx_read_chr_start() {
let r = open_reader();
let bseq = r.fetch_seq("chr1", 0, 9).unwrap();
assert_eq!(bseq.len(), 10);
assert_eq!(bseq, b"GGGCACAGCC");
let seq = r.fetch_seq_string("chr1", 0, 9).unwrap();
assert_eq!(seq.len(), 10);
assert_eq!(seq, "GGGCACAGCC");
}
#[test]
fn faidx_read_chr_between() {
let r = open_reader();
let bseq = r.fetch_seq("chr1", 4, 14).unwrap();
assert_eq!(bseq.len(), 11);
assert_eq!(bseq, b"ACAGCCTCACC");
let seq = r.fetch_seq_string("chr1", 4, 14).unwrap();
assert_eq!(seq.len(), 11);
assert_eq!(seq, "ACAGCCTCACC");
}
#[test]
fn faidx_read_chr_end() {
let r = open_reader();
let bseq = r.fetch_seq("chr1", 110, 120).unwrap();
assert_eq!(bseq.len(), 10);
assert_eq!(bseq, b"CCCCTCCGTG");
let seq = r.fetch_seq_string("chr1", 110, 120).unwrap();
assert_eq!(seq.len(), 10);
assert_eq!(seq, "CCCCTCCGTG");
}
#[test]
fn faidx_read_twice_string() {
let r = open_reader();
let seq = r.fetch_seq_string("chr1", 110, 120).unwrap();
assert_eq!(seq.len(), 10);
assert_eq!(seq, "CCCCTCCGTG");
let seq = r.fetch_seq_string("chr1", 5, 9).unwrap();
assert_eq!(seq.len(), 5);
assert_eq!(seq, "CAGCC");
}
#[test]
fn faidx_read_twice_bytes() {
let r = open_reader();
let seq = r.fetch_seq("chr1", 110, 120).unwrap();
assert_eq!(seq.len(), 10);
assert_eq!(seq, b"CCCCTCCGTG");
let seq = r.fetch_seq("chr1", 5, 9).unwrap();
assert_eq!(seq.len(), 5);
assert_eq!(seq, b"CAGCC");
}
#[test]
fn faidx_position_too_large() {
let r = open_reader();
let position_too_large = i64::MAX as usize;
let res = r.fetch_seq("chr1", position_too_large, position_too_large + 1);
assert_eq!(res, Err(Error::FaidxPositionTooLarge));
}
#[test]
fn faidx_n_seqs() {
let r = open_reader();
assert_eq!(r.n_seqs(), 3);
}
#[test]
fn faidx_seq_name() {
let r = open_reader();
let n = r.seq_name(1).unwrap();
assert_eq!(n, "chr2");
}
#[test]
fn open_many_readers() {
for _ in 0..500_000 {
let reader = open_reader();
drop(reader);
}
}
}