[Solved] Optional BufReader<GzDecoder> or BufReader<File>

#1

So I just want something to open as a BufReader if the filename ends in “gz” (I know I should look for magic numbers, im being lazy) and a BufReader otherwise.

So great, both GzDecoder (flate2 crate) and File implement the Read trait and BufReader takes something with the Read trait.

So how do I do this? I’ve tried a bunch of things. I tried variations on the following

extern crate flate2; // 1.0.6
use flate2::read::GzDecoder;
use std::io::BufReader;
use std::fs::File;
use std::io::Read;

pub fn main() {
let filetype = “gz”;
let file = match File::open(“fastq.gz”) {
Ok(file) => file,
Err(error) => panic!(“There was a problem opening the file: {:?}”, error),
};
let reader: BufReader = match filetype {
“gz” => BufReader::new(GzDecoder::new(file)),
_ => BufReader::new(file)
};
}

but Read does not have a known size at compile time which BufReader requires and also here the match arms types dont match (even tho I have specified to interpret them as the trait type not the actual type).

0 Likes

#2

Got it

extern crate flate2; // 1.0.6
use flate2::read::GzDecoder;
use std::io::BufReader;
use std::fs::File;
use std::io::Read;

pub fn main() {
    let filetype = "gz";
    let file = match File::open("fastq.gz") {
            Ok(file) => file,
            Err(error) => panic!("There was a problem opening the file: {:?}", error),
        };

    let reader: Box<Read> = match filetype { 
        "gz" => Box::new(GzDecoder::new(file)), 
        _ => Box::new(file), 
        
    }; 
    let reader = BufReader::new(reader);

}
2 Likes

#3

Nitpick: filetype is always “gz” in your example.

I thought your example used a variable for filename and that you forgot to write code to get the extension. I need more coffee :coffee::smile:

0 Likes