rust-ascii icon indicating copy to clipboard operation
rust-ascii copied to clipboard

Most functions could be const

Open PvdBerg1998 opened this issue 6 years ago • 4 comments

See title. I'm not an expert on what subset of const functions are stabilized yet, but I think a lot could already be const fn (think AsciiChar::as_byte).

PvdBerg1998 avatar Mar 22 '19 21:03 PvdBerg1998

Many methods can, but it's not yet possible to convert from other types, and without those, making other methods const doesn't seem all that useful.

Creating AsciiChar from u8 or char requires transmute or match (but with 129 arms!). Going from &str or &[u8] to &AsciiStr or back requires "dereferencing" raw pointers (or transmute). Vec::new() surprisingly isn't const yet either, so AsciiString::new() cannot be const either. While writing this i remembered reading about an union transmute trick, but it turns out that only works for constants, not const fns. ugh.

For many of the functions that can be made const, it isn't as simple as slapping const on them either. For example AsciiChar::is_blank() has to be changed from self == AsciiChar::Space || self == AsciiChar::Tab to (self as u8 == b' ') | (self as u8 == b'\t').

For AsciiChar::as_byte() you can instead write as u8, and then you can use u8's .is_ascii_xxx() methods instead of AsciiChars. Are there other methods that would still be useful to you as const fn even without converting from primitive types? Thank you for opening an issue anyway, I had considered opening one as a note and to track what is possible.

tormol avatar Mar 23 '19 23:03 tormol

Most AsciiChar methods has been made const fn with version 1.0.0. I figured out that a const fn AsciiChar::new() was possible by indexing into a constant array.

For AsciiStr and AsciiString everything above still holds, so I'm leaving this issue open until they can be created in const contexts.

  • [x] AsciiChar::new()
  • [x] AsciiStr::new()
  • [x] AsciiString::new()

tormol avatar Aug 26 '19 17:08 tormol

Most AsciiChar methods has been made const fn with version 1.0.0. I figured out that a const fn AsciiChar::new() was possible by indexing into a constant array.

For AsciiStr and AsciiString everything above still holds, so I'm leaving this issue open until they can be created in const contexts.

* [x]  `AsciiChar::new()`

* [ ]  `AsciiStr::new()`

* [ ]  `AsciiString::new()`

It seems that AsciiStr::new() no longer exists as of 1.0.0 :cat2:

JOE1994 avatar Jun 10 '20 17:06 JOE1994

AsciiStr::new() was removed so that it can be added back as a const fn when possible without any backwards compatibility restrictions. So if that's possible now then feel free to add it!

tormol avatar Jun 10 '20 21:06 tormol