Hacker News new | ask | show | jobs
by messe 1098 days ago
> allow supporting any number of spaces

As long as nothing is depending on 'static lifetime further down the line. (EDIT: ignore and see below)

> (or at least increase the upper limit to 16)

That should be doable for sure. Even something like (I'm not a rust developer, just have a passing familiarity, so my syntax may be off):

    IndentStyle::Spaces(n) if 0 < n && n <= 16 => &"                "[0..n as usize],
I think that would condense it all down into one line, rather than having special cases for all of 1 through 16.

EDIT: after toying around in the rust playground, I think the following will support any indent level (within the bounds of the u8 type).

At the top level:

    static INDENTS: [u8: 256] = [' '; 256];
And then in the as_str function:

    IndentStyle::Spaces(n) => std::str::from_utf8(&INDENTS[0..n as usize]).unwrap()
1 comments

The [0..n] slicing is what I was surprised to not see being done. As for what you're suggesting, using from_utf8 adds a overhead to check that you're giving it valid UTF-8 (this does not get optimized away). Dipping into unsafe can help here:

    const INDENTS: [u8; 256] = [b' '; 256];
    // ...
    IndentStyle::Spaces(n) => unsafe { std::str::from_utf8_unchecked(&INDENTS[0..n as usize]) },

But I would consider having INDENTS be a &str to get the cheap slicing without needing unsafe. Since putting in a string literal of 256 spaces is nasty I would use the const_format crate to generate the constant:

    const INDENTS: &str = str_repeat!(" ", 256);
Closing the loop, this is now implemented and on main, thanks to msdrigg: https://github.com/helix-editor/helix/pull/7429
This makes me happy, thanks for sharing
Nice!
I'm not sure I could justify bringing in a package for a one-liner, just to avoid an "unsafe" which could be easily documented in a comment as actually safe.