I parse struct with serde_json and then convert the result into some other.
So at the first step I want minimize time and cpu usage taking into consideration that
the mostly I work with strings.
I thought that Cow<str>
is ideal type it allocate memory if string contains special symbols,
and just borrow from origin if there is no need for allocation.
This is works for plain &str
type:
let origin = "\"aaa\"";
let x: &str = serde_json::from_str(origin).unwrap();
println!("{:?} vs {:?}", origin.as_ptr(), x.as_ptr());
x will point to &origin[1..origin.len()-1]
.
But for some reason this is not work for Cow
:
let origin = "\"aaa\"";
let x: std::borrow::Cow<str> = serde_json::from_str(origin).unwrap();
println!("{:?} vs {:?}", origin.as_ptr(), x.as_ptr());
Cow
will always become Cow::Owned
instead of Cow::Borrowed
.
Is any way to force serde_json
allocate memory only if there is need for allocation?