I need to read some data from network and then parse it into movable/returnable key-value map. I don't want to reallocate all keys and values for map, because i already have them in the container (Vec, String or something else).
I could take a map, where both keys and values are just slices of container. It works, but such map is not movable/returnable. It is even impossible to move/return this map along with container, for example as parts of object
struct ParsedData<'a> {
container: String,
variables: HashMap<&'a str, &'a str>, // all &str are slices of container
}
because this object becames self-borrowing as soon as slices stored in the map.
I thought i could make some "shared slices" type, for example
struct SharedStr {
origin: Rc<str>,
range: Range,
}
impl Borrow<str> for SharedStr {
fn borrow(&self) -> &str {
&self.origin[self.range.start..self.range.end]
}
}
having implemented Borrow trait to allow use this type as keys of map. But this way i have other issue - i can't turn mutable container(Vec or String) into Rc without redundant copying.
Such type
struct SharedString {
origin: Rc<String>,
range: Range,
}
could eliminate redundant copying, but this way i have double-dereferencing, which slowing down working with map with keys and values of such type.
Are there any other ways?