onecodex / needletail

Fast FASTX parsing and k-mer methods in Rust
MIT License
174 stars 20 forks source link

Sequence parser callback return type #44

Closed mbhall88 closed 4 years ago

mbhall88 commented 4 years ago

It would be nice if the callback provided to the sequence parsers returned a Result rather than () (maybe Result<(), E>).

As an example, say I am wanting to write a record to file based on some condition, it would be nice to exit the callback early if there is an error and pass the error "upwards" rather than having to panic.

let mut reader = // something that implements Read
let mut writer = // something that implements Write
let mut i = 0;
if let Err(parsing_err) = parse_sequence_reader(
    reader,
    |_| {},
    |record| {
        if i % 2 == 0 {
            record.write_fastq(&mut writer, b"\n")?;
        }
        i += 1;
    },
) {
    // do something with the error
}

In the above toy example, we try writing the fastq record to a file handle. This operation returns a result but as the callback must return () the only way to catch if there was a problem writing a record is to panic!. In the above example though we use ? (or we could use something else) to propagate the error upwards and do something with it.

Apologies if there is a better way of doing this that I am missing or if you think this feature is not needed.

Keats commented 4 years ago

I'm going to have a look at the API soon-ish, I'll let you know if I can figure out something nicer.