Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to represent an OsStr or OsString literal?

Tags:

rust

I'd like to define an OsStr constant for an extension comparison that's going to happen many times. For example:

const DCM_EXTENSION: Option<&'static OsStr> = Some("dcm");
const DCM_EXTENSION: Option<&'static OsStr> = Some(OsStr::new("dcm"));

This should make it trivial and unfallable to do the comparison:

if entry.file_type().is_file() && entry.path().extension() == DCM_EXTENSION:

Neither method works due to lack of const fn and a type mismatch, respectively.

My current workaround is to convert at runtime before doing any comparisons:

const DCM_EXTENSION_STR: Option<&'static str> = Some("dcm");

main!(|args: Cli, log_level: verbosity| {
    let dcm_extension = DCM_EXTENSION_STR.map(OsStr::new);
    // ...
});

I figure this avoids a per-access penalty that lazy_static would impose and works out to a one-time runtime penalty that is negligible.

like image 229
spease Avatar asked Mar 12 '18 01:03

spease


1 Answers

No, there is not (yet).

However, OsStr::new cannot fail (it does not return a Result or list any panic conditions). AsRef is "a cheap reference-to-reference conversion".

This means you can create a string literal and convert it to an OsStr at the site of use and expect there to be basically no overhead. Inspecting the assembly may even show that the types completely disappear at compile time (zero overhead).

like image 64
Shepmaster Avatar answered Nov 15 '22 07:11

Shepmaster