image-png icon indicating copy to clipboard operation
image-png copied to clipboard

`Writer::into_stream_writer()` does not work with borrowed `Write` implementations

Open ravenexp opened this issue 3 years ago • 1 comments

Sample code exhibiting the issue:

use std::io::Write;

fn encode() -> Vec<u8> {
    let mut pngbuf: Vec<u8> = Vec::new();

    {
        let mut encoder = png::Encoder::new(std::io::Cursor::new(&mut pngbuf), 1, 1);
        encoder.set_color(png::ColorType::Grayscale);
        encoder.set_depth(png::BitDepth::Eight);

        let mut writer = encoder
            .write_header()
            .unwrap()
            .into_stream_writer()
            .unwrap();

        writer.write_all(b"x").unwrap();
    }

    pngbuf
}

leads to the following error:

error[E0597]: `pngbuf` does not live long enough
  --> src/main.rs:7:66
   |
7  |         let mut encoder = png::Encoder::new(std::io::Cursor::new(&mut pngbuf), 1, 1);
   |                                             ---------------------^^^^^^^^^^^-
   |                                             |                    |
   |                                             |                    borrowed value does not live long enough
   |                                             argument requires that `pngbuf` is borrowed for `'static`
...
21 | }
   | - `pngbuf` dropped here while still borrowed

error[E0505]: cannot move out of `pngbuf` because it is borrowed
  --> src/main.rs:20:5
   |
7  |         let mut encoder = png::Encoder::new(std::io::Cursor::new(&mut pngbuf), 1, 1);
   |                                             ---------------------------------
   |                                             |                    |
   |                                             |                    borrow of `pngbuf` occurs here
   |                                             argument requires that `pngbuf` is borrowed for `'static`
...
20 |     pngbuf
   |     ^^^^^^ move out of `pngbuf` occurs here

The issue and the possible solutions were previously discussed in https://github.com/image-rs/image-png/issues/298#issuecomment-961964817

Since #298 is closed and this is a actually different issue introduced only in v0.17 I'm submitting a new one.

ravenexp avatar Nov 28 '21 12:11 ravenexp

This version does work:

fn encode() -> Vec<u8> {
    let mut pngbuf: Vec<u8> = Vec::new();

    {
        let mut encoder = png::Encoder::new(std::io::Cursor::new(&mut pngbuf), 1, 1);
        encoder.set_color(png::ColorType::Grayscale);
        encoder.set_depth(png::BitDepth::Eight);

        let mut writer = encoder
            .write_header()
            .unwrap();

        let mut writer = writer
            .stream_writer()
            .unwrap();

        writer.write_all(b"x").unwrap();
    }

    pngbuf
}

fintelia avatar Nov 28 '21 20:11 fintelia