Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pushing to segments_mut creates unrecoverable segment #12

Open
jacg opened this issue Aug 26, 2024 · 1 comment
Open

Pushing to segments_mut creates unrecoverable segment #12

jacg opened this issue Aug 26, 2024 · 1 comment

Comments

@jacg
Copy link

jacg commented Aug 26, 2024

Here is some code illustrating the problem:

use std::env::args;
use img_parts::jpeg::{self, JpegSegment, Jpeg};

const OUR_MARKER: u8 = jpeg::markers::COM;

fn main() {

    // Get path of JPEG from CLI
    let mut args = args();
    let _executable = args.next();
    let path = args.next().unwrap();

    // Read JPEG from file and report number of segments
    let bytes = std::fs::read(path).unwrap();
    let mut jpeg = Jpeg::from_bytes(bytes.into()).unwrap();
    println!("Initial number of segments:                  {}", jpeg.segments().len());

    // Add segment to end, and report number of segments
    let segments = jpeg.segments_mut();
    segments.push(                        // BROKEN
    //segments.insert(segments.len() - 1, // WORKS
        JpegSegment::new_with_contents(
            OUR_MARKER,
            img_parts::Bytes::from("OUR SEGMENT CONTENT")
        )
    );
    println!("Number of segments after adding new segment: {}", jpeg.segments().len());

    // Roundtrip JPEG via bytes and report number of segments
    let new_bytes = {
        let mut bytes = vec![];
        jpeg.encoder().write_to(&mut bytes).unwrap();
        bytes
    };
    let new_jpeg = Jpeg::from_bytes(new_bytes.into()).unwrap();
    println!("Number of segments after roundtrip:          {}", new_jpeg.segments().len());
}

which demonstrates that pushing a new segment to .segments_mut() creates a segment which is accessible from the original JPEG instance, but disappears when the JPEG is serialized and deserialized again.

When push ing the new segment to jpeg.segments_mut(), the serialized representation of the JPEG contains the new segment after EOI and

https://github.com/paolobarbolini/img-parts/blob/main/src/jpeg/image.rs#L53-L55

ignores everything after EOI.

If you replace push(... with insert(<somewhere before last element>, then the new segment is placed before EOI and is recovered when the JPEG is deserialized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
@jacg and others