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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use libc;
use std::ffi;
use std::path::Path;
use std::ptr;
use url::Url;
pub mod errors;
use crate::htslib;
use crate::tbx::errors::{Error, Result};
fn path_as_bytes<'a, P: 'a + AsRef<Path>>(path: P, must_exist: bool) -> Result<Vec<u8>> {
if path.as_ref().exists() || !must_exist {
Ok(path
.as_ref()
.to_str()
.ok_or(Error::NonUnicodePath)?
.as_bytes()
.to_owned())
} else {
Err(Error::FileNotFound {
path: path.as_ref().to_owned(),
})
}
}
pub trait Read: Sized {
fn read(&mut self, record: &mut Vec<u8>) -> Result<bool>;
fn records(&mut self) -> Records<'_, Self>;
fn header(&self) -> &Vec<String>;
}
#[derive(Debug)]
pub struct Reader {
header: Vec<String>,
hts_file: *mut htslib::htsFile,
hts_format: htslib::htsExactFormat,
tbx: *mut htslib::tbx_t,
buf: htslib::kstring_t,
itr: Option<*mut htslib::hts_itr_t>,
tid: i64,
start: i64,
end: i64,
}
unsafe impl Send for Reader {}
const KS_SEP_LINE: i32 = 2;
impl Reader {
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
Self::new(&path_as_bytes(path, true)?)
}
pub fn from_url(url: &Url) -> Result<Self> {
Self::new(url.as_str().as_bytes())
}
fn new(path: &[u8]) -> Result<Self> {
let path = ffi::CString::new(path).unwrap();
let c_str = ffi::CString::new("r").unwrap();
let hts_file = unsafe { htslib::hts_open(path.as_ptr(), c_str.as_ptr()) };
unsafe {
if (*hts_file).format.category != htslib::htsFormatCategory_region_list
&& (*hts_file).format.format != htslib::htsExactFormat_sam
{
return Err(Error::InvalidIndex);
}
}
let hts_format = unsafe { (*htslib::hts_get_format(hts_file)).format };
let tbx = unsafe { htslib::tbx_index_load(path.as_ptr()) };
let mut header = Vec::new();
let mut buf = htslib::kstring_t {
l: 0,
m: 0,
s: ptr::null_mut(),
};
unsafe {
while htslib::hts_getline(hts_file, KS_SEP_LINE, &mut buf) >= 0 {
if buf.l > 0 && i32::from(*buf.s) == (*tbx).conf.meta_char {
header.push(String::from(ffi::CStr::from_ptr(buf.s).to_str().unwrap()));
} else {
break;
}
}
}
if tbx.is_null() {
Err(Error::InvalidIndex)
} else {
Ok(Reader {
header,
hts_file,
hts_format,
tbx,
buf,
itr: None,
tid: -1,
start: -1,
end: -1,
})
}
}
pub fn tid(&self, name: &str) -> Result<u64> {
let name_cstr = ffi::CString::new(name.as_bytes()).unwrap();
let res = unsafe { htslib::tbx_name2id(self.tbx, name_cstr.as_ptr()) };
if res < 0 {
Err(Error::UnknownSequence {
sequence: name.to_owned(),
})
} else {
Ok(res as u64)
}
}
pub fn fetch(&mut self, tid: u64, start: u64, end: u64) -> Result<()> {
self.tid = tid as i64;
self.start = start as i64;
self.end = end as i64;
if let Some(itr) = self.itr {
unsafe {
htslib::hts_itr_destroy(itr);
}
}
let itr = unsafe {
htslib::hts_itr_query(
(*self.tbx).idx,
tid as i32,
start as i64,
end as i64,
Some(htslib::tbx_readrec),
)
};
if itr.is_null() {
self.itr = None;
Err(Error::Fetch)
} else {
self.itr = Some(itr);
Ok(())
}
}
pub fn seqnames(&self) -> Vec<String> {
let mut result = Vec::new();
let mut nseq: i32 = 0;
let seqs = unsafe { htslib::tbx_seqnames(self.tbx, &mut nseq) };
for i in 0..nseq {
unsafe {
result.push(String::from(
ffi::CStr::from_ptr(*seqs.offset(i as isize))
.to_str()
.unwrap(),
));
}
}
unsafe {
libc::free(seqs as *mut libc::c_void);
};
result
}
pub fn set_threads(&mut self, n_threads: usize) -> Result<()> {
assert!(n_threads > 0, "n_threads must be > 0");
let r = unsafe { htslib::hts_set_threads(self.hts_file, n_threads as i32) };
if r != 0 {
Err(Error::SetThreads)
} else {
Ok(())
}
}
}
fn overlap(tid1: i64, begin1: i64, end1: i64, tid2: i64, begin2: i64, end2: i64) -> bool {
(tid1 == tid2) && (begin1 < end2) && (begin2 < end1)
}
impl Read for Reader {
fn read(&mut self, record: &mut Vec<u8>) -> Result<bool> {
match self.itr {
Some(itr) => {
loop {
let ret = unsafe {
htslib::hts_itr_next(
htslib::hts_get_bgzfp(self.hts_file),
itr,
&mut self.buf as *mut htslib::kstring_t as *mut libc::c_void,
self.tbx as *mut libc::c_void,
)
};
if ret == -1 {
return Ok(false);
} else if ret == -2 {
return Err(Error::TruncatedRecord);
} else if ret < 0 {
panic!("Return value should not be <0 but was: {}", ret);
}
let (tid, start, end) =
unsafe { ((*itr).curr_tid, (*itr).curr_beg, (*itr).curr_end) };
if overlap(self.tid, self.start, self.end, tid as i64, start, end) {
*record =
unsafe { Vec::from(ffi::CStr::from_ptr(self.buf.s).to_str().unwrap()) };
return Ok(true);
}
}
}
_ => Err(Error::NoIter),
}
}
fn records(&mut self) -> Records<'_, Self> {
Records { reader: self }
}
fn header(&self) -> &Vec<String> {
&self.header
}
}
impl Drop for Reader {
fn drop(&mut self) {
unsafe {
if self.itr.is_some() {
htslib::hts_itr_destroy(self.itr.unwrap());
}
htslib::tbx_destroy(self.tbx);
htslib::hts_close(self.hts_file);
}
}
}
#[derive(Debug)]
pub struct Records<'a, R: Read> {
reader: &'a mut R,
}
impl<'a, R: Read> Iterator for Records<'a, R> {
type Item = Result<Vec<u8>>;
fn next(&mut self) -> Option<Result<Vec<u8>>> {
let mut record = Vec::new();
match self.reader.read(&mut record) {
Ok(false) => None,
Ok(true) => Some(Ok(record)),
Err(err) => Some(Err(err)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bed_basic() {
let reader = Reader::from_path("test/test_bed3.bed.gz")
.ok()
.expect("Error opening file.");
assert_eq!(
reader.seqnames(),
vec![String::from("chr1"), String::from("chr2")]
);
assert_eq!(reader.tid("chr1").unwrap(), 0);
assert_eq!(reader.tid("chr2").unwrap(), 1);
assert!(reader.tid("chr3").is_err());
}
#[test]
fn bed_fetch_from_chr1_read_api() {
let mut reader = Reader::from_path("test/test_bed3.bed.gz")
.ok()
.expect("Error opening file.");
let chr1_id = reader.tid("chr1").unwrap();
assert!(reader.fetch(chr1_id, 1000, 1003).is_ok());
let mut record = Vec::new();
assert!(reader.read(&mut record).is_ok());
assert_eq!(record, Vec::from("chr1\t1001\t1002"));
assert_eq!(reader.read(&mut record), Ok(false));
}
#[test]
fn bed_fetch_from_chr1_iterator_api() {
let mut reader = Reader::from_path("test/test_bed3.bed.gz")
.ok()
.expect("Error opening file.");
let chr1_id = reader.tid("chr1").unwrap();
assert!(reader.fetch(chr1_id, 1000, 1003).is_ok());
let records: Vec<Vec<u8>> = reader.records().map(|r| r.unwrap()).collect();
assert_eq!(records, vec![Vec::from("chr1\t1001\t1002")]);
}
#[test]
fn test_fails_on_bam() {
let reader = Reader::from_path("test/test.bam");
assert!(reader.is_err());
}
#[test]
fn test_fails_on_non_existiant() {
let reader = Reader::from_path("test/no_such_file");
assert!(reader.is_err());
}
#[test]
fn test_fails_on_vcf() {
let reader = Reader::from_path("test/test_left.vcf");
assert!(reader.is_err());
}
}