What is the difference / advantage over `Cow<'_, str>`?
mara-schulke opened this issue · 2 comments
Good question!
Basically, a Cow<'_, str>
can be one of two variants:
It can be a Cow::Owned
. Which means that if you .clone()
this, you are creating copies of the underlying string.
It can also be a Cow::Borrowed
, which means that it is a string slice (borrowed). This makes it immutable. Creating copies is cheap now! But the problem is: the borrow has a lifetime. So, for example if you have a Cow<'a, str>
, it is only valid for the lifetime 'a
. This is fine in some applications. But if you want to store references, or you need to pass this through a tokio::spawn()
, this might give you issues.
To store references or pass them through to async tasks, you can really only do that with Cow<'static, str>
, which is not really useful unless most of your strings are 'static
slices.
So what imstr
does is it works very similar to an Arc<String>
: it has no lifetime associated (because it does it's own reference counting). It is cheap to clone, and can be used in async/multithtreaded code. What imstr
adds on top of that is slicing, because you cannot easily slice an Arc<String>
to get a subslice of the underlying string without copying it. It also adds copy-on-write mutability, so you can use it as you would use a normal String
.
Hope that makes sense, somewhat!
Also, don't use this crate! It was mostly a fun experiment. There is a whole lot of other crates that are interesting as well and fit into a similar niche.
Thank you, got it now!
That's very detailed 😊