I created a wrapper that will eventually provide a nice API for opening a file inside a tar file, as if it's a regular file. But the error I get is:
error: lifetime may not live long enough
--> src/main.rs:26:43
|
21 | pub fn select_entry(&mut self, filename: &str) -> Result<()> {
| - let's call the lifetime of this reference `'1`
...
26 | self.current_entry = Some(Box::new(entry));
| ^^^^^^^^^^^^^^^ cast requires that `'1` must outlive `'static`
Full code:
use std::io::Read;
use std::path::Path;
use tar::Archive;
use std::fs::File;
use anyhow::Result;
pub struct TarFileReader {
archive: Archive<File>,
current_entry: Option<Box<dyn Read>>,
}
impl TarFileReader {
pub fn new(fname: impl AsRef<Path>) -> Result<Self> {
let file = File::open(fname)?;
let archive = Archive::new(file);
Ok(TarFileReader {
archive,
current_entry: None,
})
}
pub fn select_entry(&mut self, filename: &str) -> Result<()> {
let entries = self.archive.entries()?;
for entry in entries {
let entry = entry?;
if entry.path()?.ends_with(filename) {
self.current_entry = Some(Box::new(entry));
return Ok(());
}
}
panic!("Entry not found in archive");
}
}
impl Read for TarFileReader {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
match self.current_entry {
Some(ref mut entry) => Ok(entry.read(buf)?),
None => panic!("no entry selected"),
}
}
}
Really I want TarFileReader::new() to also find the file, but I'll be happy just understanding why the code doesn't build as is.