Skip to content

Consider to refactor json::Encoder::buffer_encode #14302

@edwardw

Description

@edwardw

Here is the implementation of json::Encoder::buffer_encode:

pub struct Encoder<'a> {
    wr: &'a mut io::Writer,
}
impl<'a> Encoder<'a> {
    pub fn buffer_encode<T:Encodable<Encoder<'a>, io::IoError>>(to_encode_object: &T) -> Vec<u8>  {
        let mut m = MemWriter::new();
        {
            let mut encoder = Encoder::new(&mut m as &mut io::Writer);
            let _ = to_encode_object.encode(&mut encoder);
        }
        m.unwrap()
    }
}

Note that to_encode_object has type Encodable<Encoder<'a>> so to_encode_object.encode(...) requires an Encoder instance with lifetime 'a, which in turn requires a Writer instance of lifetime 'a, but the given one m is only stack local. rustc should reject it.

The reason why this is legit now is because of a bug in variance.rs#L744-L748, where an extra contravariant constraint should be added in presence of a trait reference. That bug is a soundness issue as well as a backward compatibility hazard, manifested in bugs such as #12470 and #14285.

But the patch for the trait reference variance bug is blocked by otherwise invalid json::Encoder::buffer_encode. We need to refactor it first. Nominate.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions