Skip to content

Commit

Permalink
vcf/variant/record_buf: Add conversion from &variant::Record
Browse files Browse the repository at this point in the history
  • Loading branch information
zaeleus committed Mar 15, 2024
1 parent 5dc55b3 commit 33ce450
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
1 change: 1 addition & 0 deletions noodles-vcf/src/variant/record_buf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

pub mod alternate_bases;
pub mod builder;
mod convert;
pub mod filters;
pub mod ids;
pub mod info;
Expand Down
76 changes: 76 additions & 0 deletions noodles-vcf/src/variant/record_buf/convert.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use std::io;

use super::RecordBuf;
use crate::{variant::Record, Header};

impl RecordBuf {
/// Converts a variant record to a buffer.
pub fn try_from_variant_record<R>(header: &Header, record: &R) -> io::Result<Self>
where
R: Record,
{
use super::{samples::Keys, Samples};

let mut record_buf = RecordBuf::default();

*record_buf.reference_sequence_name_mut() = record.reference_sequence_name(header)?.into();
*record_buf.position_mut() = record.position().transpose()?;
*record_buf.ids_mut() = record.ids().iter().map(String::from).collect();

let raw_reference_bases: Vec<_> =
record.reference_bases().iter().collect::<io::Result<_>>()?;
*record_buf.reference_bases_mut() = String::from_utf8(raw_reference_bases)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;

let raw_alternate_bases: Vec<_> = record
.alternate_bases()
.iter()
.map(|result| result.map(String::from))
.collect::<io::Result<_>>()?;
*record_buf.alternate_bases_mut() = raw_alternate_bases.into();

*record_buf.quality_score_mut() = record.quality_score().transpose()?;

*record_buf.filters_mut() = record
.filters()
.iter(header)
.map(|result| result.map(String::from))
.collect::<io::Result<_>>()?;

*record_buf.info_mut() = record
.info()
.iter(header)
.map(|result| {
result.and_then(|(key, value)| {
let v = value.map(|v| v.try_into()).transpose()?;
Ok((String::from(key), v))
})
})
.collect::<io::Result<_>>()?;

let samples = record.samples()?;

let column_names: Vec<_> = samples
.column_names(header)
.map(|result| result.map(String::from))
.collect::<io::Result<_>>()?;
let keys = Keys::try_from(column_names)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;

let values = samples
.iter()
.map(|sample| {
sample
.iter(header)
.map(|result| {
result.and_then(|(_, value)| value.map(|v| v.try_into()).transpose())
})
.collect()
})
.collect::<io::Result<_>>()?;

*record_buf.samples_mut() = Samples::new(keys, values);

Ok(record_buf)
}
}

0 comments on commit 33ce450

Please sign in to comment.