Skip to content

Commit

Permalink
bed/record: Parse strand as Strand
Browse files Browse the repository at this point in the history
  • Loading branch information
zaeleus committed Jul 11, 2024
1 parent 48d16e0 commit 265c3c8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
3 changes: 2 additions & 1 deletion noodles-bed/src/record.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use noodles_core::Position;

use self::fields::Fields;
pub use self::other_fields::OtherFields;
use crate::feature::record_buf::Strand;

/// A BED record.
#[derive(Clone, Default, Eq, PartialEq)]
Expand Down Expand Up @@ -40,7 +41,7 @@ impl Record {
}

/// Returns the strand.
pub fn strand(&self) -> Option<&[u8]> {
pub fn strand(&self) -> Option<io::Result<Option<Strand>>> {
self.0.strand()
}

Expand Down
34 changes: 32 additions & 2 deletions noodles-bed/src/record/fields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use lexical_core::FromLexical;
use noodles_core::Position;

pub(crate) use self::bounds::Bounds;
use crate::feature::record_buf::Strand;

#[derive(Clone, Eq, PartialEq)]
pub(crate) struct Fields {
Expand Down Expand Up @@ -55,9 +56,9 @@ impl Fields {
self.get(SCORE_INDEX).map(parse_int)
}

pub(super) fn strand(&self) -> Option<&[u8]> {
pub(super) fn strand(&self) -> Option<io::Result<Option<Strand>>> {
const STRAND_INDEX: usize = 2;
self.get(STRAND_INDEX)
self.get(STRAND_INDEX).map(parse_strand)
}

pub(super) fn get(&self, i: usize) -> Option<&[u8]> {
Expand All @@ -77,3 +78,32 @@ impl Default for Fields {
fn parse_int<N: FromLexical>(buf: &[u8]) -> io::Result<N> {
lexical_core::parse(buf).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}

fn parse_strand(buf: &[u8]) -> io::Result<Option<Strand>> {
const MISSING: &[u8] = b".";
const FORWARD: &[u8] = b"+";
const REVERSE: &[u8] = b"-";

match buf {
MISSING => Ok(None),
FORWARD => Ok(Some(Strand::Forward)),
REVERSE => Ok(Some(Strand::Reverse)),
_ => Err(io::Error::new(io::ErrorKind::InvalidData, "invalid strand")),
}
}

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

#[test]
fn test_parse_strand() -> io::Result<()> {
assert!(parse_strand(b".")?.is_none());
assert_eq!(parse_strand(b"+")?, Some(Strand::Forward));
assert_eq!(parse_strand(b"-")?, Some(Strand::Reverse));

assert!(matches!(parse_strand(b"n"), Err(e) if e.kind() == io::ErrorKind::InvalidData));

Ok(())
}
}

0 comments on commit 265c3c8

Please sign in to comment.