Short strings impl copy

Ibefore I flesh out this idea I was hoping to get some sanity feedback. would it make sense for short rust strings to implement copy?
Is it currently possible for a struct to dynamically implement or not implement a trait?

something like impl copy for string where len <= 20

Edit:
It sounds like something like an enum with an ArrayString and String is what I was thinking of. However there are possible costs like extra checks on each data access for adding this as a language default which was my primary question.

Rust is a typed language, and to keep it simple, allocated Strings all have the same type, as do all string literals which have type &'static str.
So how would you see this work?

No, you cannot dynamically implement a trait.

1 Like

Remember that Copy means "can be copied via memcpy". So String, which owns a dynamic memory allocation (for non-zero capacity) cannot be Copy, even if it's short.

A string-but-not-String type that doesn't do allocations, however, could be Copy β€” for example arraystring::ArrayString - Rust is Copy.

1 Like

This got me thinking: if we had enum variants as types, could one variant be Copy and another not? A hypothetical enum VarString { Smol([u8; 24]), Bigg(Vec<u8>) } could be Copy as long as it’s statically known to be Smol? Not sure if that would have any benefit though :stuck_out_tongue: (One could of course do the same in current Rust using wrapped types albeit with poorer ergonomics.)

1 Like

That is just the same as if let Smol(smol) = string with the wrapped type (of smol) being Copy – which is already the case today.

2 Likes

Rust doesn't have any Small String Optimization built in, so it doesn't have any concept of a "short string".

SSO has been intentionally left out, because it adds trade-offs (like extra checks on each data access) and you can use a library to implement your own flavor of SSO (there are many crates for this with various levels of compactness and unsafety).

The bigger problem is that "short string" would require typestate. In Rust currently a type is always the same thing with the same behavior, and doesn't have any state (like "short" vs "long"), so Rust couldn't easily express conditional Copy for it. You could create something like SSOString<State> and impl Copy for SSOString<Short>, but it may be cumbersome to use. Const generics aren't advanced enough for this yet.

3 Likes