Rfcs: Statically-sized stack strings

Created on 6 Jun 2018  ·  8Comments  ·  Source: rust-lang/rfcs

Sometimes, some specialists strive to store strings stackwise. Sadly, one's stock in stack strings is shot down on stable. See, in spite of 'static strings storing size statically, they're symbolised solely as a slice. So what service should stack-stored strings serve? Scrutinise surely:

const fn splice<
    const SOURCE_A: &str,
    const SOURCE_B: &str,
>() -> StaticStr<SOURCE_A.len() + SOURCE_B.len()> {
    let mut scratch = [0u8; SOURCE_A.len() + SOURCE_B.len()];

    // ...

    StaticStr::new(scratch).unwrap() // Surity of success
}

const SALUTATION: &str = "Hello";
const SPOT: &str = "world";

const SPLICED_STRING: &str = &splice::<SALUTATION, SPOT>();

"Simply store a slice", you shout. A slice from splice's scope survives not the 'static span! Sure, &'static str supplying splice solves this specific strait, but stack strings support spawning several services for &'static strs.

T-libs

Most helpful comment

Seems a somewhat scholarly sample. Surely a superior specimen should sway our software society significantly.

All 8 comments

Perhaps once const generics land we could do Utf8<const N: usize> which internally wraps a [u8; N] and can be coerced into a str.

We should just make ArrayString do that and ArrayVec should coerce to a [T; N].

Seems a somewhat scholarly sample. Surely a superior specimen should sway our software society significantly.

Going to add a comment here that this came up again while I was coding, and the more that think about it, the more I wish this had language support. While it is true that a standard Utf8<N> wrapper would solve most problems, it doesn't solve the problem that you currently cannot safely coerce a string literal into an array.

Although the end type could be something like Utf8<N>, this would require some level of language support to do safely. From what it seems, you'd have to sacrifice safety by calling some form of from_utf8_unchecked or messing around with pointer casts.

Some form of SmallVec can currently be done using arrays, but no such safe equivalent exists for strings that can hold all these guarantees.

I think I don't even understand the problem.

Do you want to put an array on the stack, copy some string data into it, then take a string slice of it?

@Lokathor Essentially, yes. But that's currently not possible to do with safe code.

Technically, unsized locals can solve part of the issue, but not all of it.

Did you mean "You can do it, just not efficiently"? Because you _can_ do it, but just with a check.

...yes. I don't know why I forgot that part.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mqudsi picture mqudsi  ·  3Comments

3442853561 picture 3442853561  ·  3Comments

p-avital picture p-avital  ·  3Comments

steveklabnik picture steveklabnik  ·  4Comments

camden-smallwood-zz picture camden-smallwood-zz  ·  3Comments