Skip to main content

extended_htslib/bam/
header.rs

1// Copyright 2014 Johannes Köster.
2// Licensed under the MIT license (http://opensource.org/licenses/MIT)
3// This file may not be copied, modified, or distributed
4// except according to those terms.
5
6use crate::bam::HeaderView;
7use crate::errors::{Error, Result};
8use lazy_static::lazy_static;
9use linear_map::LinearMap;
10use regex::Regex;
11use std::borrow::Cow;
12use std::collections::HashMap;
13
14/// A BAM header.
15#[derive(Debug, Clone)]
16pub struct Header {
17    records: Vec<Vec<u8>>,
18}
19
20impl Default for Header {
21    fn default() -> Self {
22        Self::new()
23    }
24}
25
26impl Header {
27    /// Create a new header.
28    pub fn new() -> Self {
29        Header {
30            records: Vec::new(),
31        }
32    }
33
34    pub fn from_template(header: &HeaderView) -> Self {
35        let mut record = header.as_bytes().to_owned();
36        // Strip off any trailing newline character.
37        // Otherwise there could be a blank line in the
38        // header which samtools (<=1.6) will complain
39        // about
40        while let Some(&last_char) = record.last() {
41            if last_char == b'\n' {
42                record.pop();
43            } else {
44                break;
45            }
46        }
47        Header {
48            records: vec![record],
49        }
50    }
51
52    /// Add a record to the header.
53    pub fn push_record(&mut self, record: &HeaderRecord<'_>) -> &mut Self {
54        self.records.push(record.to_bytes());
55        self
56    }
57
58    /// Add a comment to the header.
59    pub fn push_comment(&mut self, comment: &[u8]) -> &mut Self {
60        self.records.push([&b"@CO"[..], comment].join(&b'\t'));
61        self
62    }
63
64    pub fn to_bytes(&self) -> Vec<u8> {
65        self.records.join(&b'\n')
66    }
67
68    /// This returns a header as a HashMap.
69    /// Comment lines starting with "@CO" will NOT be included in the HashMap.
70    /// Comment lines can be obtained by the `comments` function.
71    pub fn to_hashmap(&self) -> Result<HashMap<String, Vec<LinearMap<String, String>>>> {
72        let mut header_map = HashMap::default();
73
74        lazy_static! {
75            static ref REC_TYPE_RE: Regex = Regex::new(r"@([A-Z][A-Z])").unwrap();
76            static ref TAG_RE: Regex = Regex::new(r"([A-Za-z][A-Za-z0-9]):([ -~]*)").unwrap();
77        }
78        if let Ok(header_string) = String::from_utf8(self.to_bytes()) {
79            for line in header_string.split('\n').filter(|x| !x.is_empty()) {
80                let parts: Vec<_> = line.split('\t').filter(|x| !x.is_empty()).collect();
81                if parts.is_empty() {
82                    continue;
83                }
84                let record_type = REC_TYPE_RE
85                    .captures(parts[0])
86                    .and_then(|captures| captures.get(1))
87                    .map(|m| m.as_str().to_owned());
88
89                if let Some(record_type) = record_type {
90                    if record_type == "CO" {
91                        continue;
92                    }
93                    let mut field = LinearMap::default();
94                    for part in parts.iter().skip(1) {
95                        if let Some(cap) = TAG_RE.captures(part) {
96                            let tag = cap.get(1).unwrap().as_str().to_owned();
97                            let value = cap.get(2).unwrap().as_str().to_owned();
98                            field.insert(tag, value);
99                        } else {
100                            return Err(Error::HeaderParse);
101                        }
102                    }
103                    header_map
104                        .entry(record_type)
105                        .or_insert_with(Vec::new)
106                        .push(field);
107                } else {
108                    return Err(Error::HeaderParse);
109                }
110            }
111            Ok(header_map)
112        } else {
113            Err(Error::HeaderParse)
114        }
115    }
116
117    /// Returns an iterator of comment lines.
118    pub fn comments(&'_ self) -> impl Iterator<Item = Cow<'_, str>> {
119        self.records.iter().flat_map(|r| {
120            r.split(|x| x == &b'\n')
121                .filter(|x| x.starts_with(b"@CO\t"))
122                .map(|x| String::from_utf8_lossy(&x[4..]))
123        })
124    }
125}
126
127/// Header record.
128#[derive(Debug, Clone)]
129pub struct HeaderRecord<'a> {
130    rec_type: Vec<u8>,
131    tags: Vec<(&'a [u8], Vec<u8>)>,
132}
133
134impl<'a> HeaderRecord<'a> {
135    /// Create a new header record.
136    /// See SAM format specification for possible record types.
137    pub fn new(rec_type: &'a [u8]) -> Self {
138        HeaderRecord {
139            rec_type: [&b"@"[..], rec_type].concat(),
140            tags: Vec::new(),
141        }
142    }
143
144    /// Add a new tag to the record.
145    ///
146    /// # Arguments
147    ///
148    /// * `tag` - the tag identifier
149    /// * `value` - the value. Can be any type convertible into a string. Preferably numbers or
150    ///   strings.
151    pub fn push_tag<V: ToString>(&mut self, tag: &'a [u8], value: V) -> &mut Self {
152        self.tags.push((tag, value.to_string().into_bytes()));
153        self
154    }
155
156    fn to_bytes(&self) -> Vec<u8> {
157        let mut out = Vec::new();
158        out.extend(self.rec_type.iter());
159        for &(tag, ref value) in self.tags.iter() {
160            out.push(b'\t');
161            out.extend(tag.iter());
162            out.push(b':');
163            out.extend(value.iter());
164        }
165        out
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::HeaderRecord;
172    use crate::bam::Header;
173
174    #[test]
175    fn test_push_tag() {
176        let mut record = HeaderRecord::new(b"HD");
177        record.push_tag(b"X1", 0);
178        record.push_tag(b"X2", 0);
179
180        let x = "x".to_string();
181        record.push_tag(b"X3", x.as_str());
182        record.push_tag(b"X4", &x);
183        record.push_tag(b"X5", x);
184
185        assert_eq!(record.to_bytes(), b"@HD\tX1:0\tX2:0\tX3:x\tX4:x\tX5:x");
186    }
187
188    #[test]
189    fn test_header_hash_map() {
190        let mut records = Vec::new();
191        let mut record = HeaderRecord::new(b"HD");
192        record.push_tag(b"X1", 0);
193        records.push(record);
194        let mut record = HeaderRecord::new(b"PG");
195        record.push_tag(b"ID", "mytool");
196        records.push(record);
197        let mut record = HeaderRecord::new(b"PG");
198        record.push_tag(b"ID", "other_tool");
199        records.push(record);
200        let header = Header {
201            records: records.into_iter().map(|rec| rec.to_bytes()).collect(),
202        };
203        let hm = header.to_hashmap().unwrap();
204        assert!(hm.contains_key("HD"));
205        assert!(hm.contains_key("PG"));
206        assert_eq!(hm.get("HD").unwrap().len(), 1);
207        assert_eq!(hm.get("PG").unwrap().len(), 2);
208    }
209}