json icon indicating copy to clipboard operation
json copied to clipboard

In situ parsing

Open dtolnay opened this issue 8 years ago • 5 comments

pub fn from_mut_str<'a, T>(s: &'a mut str) -> Result<T>
where
    T: Deserialize<'a>;

Strings with escape sequences are decoded in place!

// before
"{\"msg\":\"abc\\nxyz\"}"

// after
"{\"msg\":\"abc\nxyzz\"}"
            ^^^^^^^^ output &str

dtolnay avatar May 10 '17 03:05 dtolnay

&[u8], &[Option<u8>], and &[u16] can be decoded in place as well, since every element of a JSON array takes up at least two bytes. With some effort this can apply to tuples and structs too.

I can imagine doing something clever to represent maps, but that might be going a bit too far.

lambda-fairy avatar May 12 '17 08:05 lambda-fairy

What would happen to the end of the string here? Because the result is shorter than the actual buffer.

Would the input itself have any guarantees?

clarfonthey avatar May 15 '17 19:05 clarfonthey

There are no guarantees around what modification is made to the input string. In the example above, b'z' happens to be duplicated to account for the difference in length.

dtolnay avatar May 15 '17 19:05 dtolnay

Oh, I see. I missed the single b'z' so it looked like the string was shortened, which didn't seem right.

clarfonthey avatar May 16 '17 00:05 clarfonthey

This would be pretty cool. Does anyone have an implementation of this in-place (and no_std) unescaping? I can't find one, but maybe my google-fu just isn't good enough.

EDIT: Got a prototype working. This was much easier than I thought, just needed some time to think on it.

saethlin avatar Nov 22 '18 03:11 saethlin