zaeleus / noodles

Bioinformatics I/O libraries in Rust
MIT License
477 stars 53 forks source link

record_buf object to sam::Record object? #249

Closed larryns closed 4 months ago

larryns commented 4 months ago

I've been tryiing to test some code I wrote. I built a record_buf object to create a SAM record for testing my function that takes a sam::Record argument. Is there a way to convert the record_buf variable to a sam::Record object. Alternatively, do I need to use a bytes object instead of record_buf?

Thanks for your help and suggestions.

zaeleus commented 4 months ago

When working with different alignment record implementations, it's recommended to use the alignment record trait (sam::alignment::Record), e.g.,

// cargo add noodles@0.67.0 --features sam

use std::io::{self, Write};

use noodles::sam;

fn main() -> io::Result<()> {
    let sam_record = sam::Record::default();
    print_read_name(&sam_record)?;

    let alignment_record_buf = sam::alignment::RecordBuf::builder()
        .set_name(b"r1".into())
        .build();
    print_read_name(&alignment_record_buf)?;

    Ok(())
}

fn print_read_name(record: &impl sam::alignment::Record) -> io::Result<()> {
    const MISSING: &[u8] = b"*";

    let mut stdout = io::stdout();

    if let Some(name) = record.name() {
        stdout.write_all(name.as_bytes())?;
    } else {
        stdout.write_all(MISSING)?;
    }

    writeln!(stdout)
}

As an aside, you may get better visibility with questions by posting to https://github.com/zaeleus/noodles/discussions under the Q&A category.

larryns commented 4 months ago

Thank you. I'll post questions like these in discussions in the future. Thanks for the heads up!