-
Notifications
You must be signed in to change notification settings - Fork 76
/
mod.rs
201 lines (171 loc) · 5.81 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
// 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())
}
}
#[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));
}
}