Skip to content

Commit

Permalink
bam/lazy/record/sequence: Add bases iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
zaeleus committed Sep 23, 2023
1 parent 5ef824e commit 38836a4
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
6 changes: 6 additions & 0 deletions noodles-bam/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## Unreleased

### Added

* bam/lazy/record/sequence: Add bases iterator (`Sequence::iter`).

## 0.46.0 - 2023-09-21

### Changed
Expand Down
31 changes: 31 additions & 0 deletions noodles-bam/src/lazy/record/sequence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@ impl<'a> Sequence<'a> {
pub fn len(&self) -> usize {
self.base_count
}

/// Returns an iterator over the bases in the sequence.
pub fn iter(&self) -> impl Iterator<Item = sam::record::sequence::Base> + '_ {
use crate::record::codec::decoder::sequence::decode_base;

self.src
.iter()
.flat_map(|&b| [decode_base(b >> 4), decode_base(b)])
.take(self.base_count)
}
}

impl<'a> AsRef<[u8]> for Sequence<'a> {
Expand All @@ -48,3 +58,24 @@ impl<'a> TryFrom<Sequence<'a>> for sam::record::Sequence {
Ok(sam_sequence)
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_iter() {
use sam::record::sequence::Base;

let sequence = Sequence::new(&[], 0);
assert!(sequence.iter().next().is_none());

let sequence = Sequence::new(&[0x12, 0x40], 3);
let actual: Vec<_> = sequence.iter().collect();
assert_eq!(actual, [Base::A, Base::C, Base::G]);

let sequence = Sequence::new(&[0x12, 0x48], 4);
let actual: Vec<_> = sequence.iter().collect();
assert_eq!(actual, [Base::A, Base::C, Base::G, Base::T]);
}
}
2 changes: 1 addition & 1 deletion noodles-bam/src/record/codec/decoder/sequence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ where
Ok(())
}

fn decode_base(n: u8) -> Base {
pub(crate) fn decode_base(n: u8) -> Base {
match n & 0x0f {
0 => Base::Eq,
1 => Base::A,
Expand Down

0 comments on commit 38836a4

Please sign in to comment.