Skip to content

Conversation

nebkor
Copy link
Contributor

@nebkor nebkor commented Jul 30, 2025

This exposes the private Level::from_usize() and LevelFilter::from_usize() functions as fallible conversions. My motivation is to avoid having to use std::mem::transmute(), which is unsafe, when I want to convert a value I got doing my_log_level as usize back to a LevelFilter.

@nebkor
Copy link
Contributor Author

nebkor commented Jul 30, 2025

My specific case was to use it in this function:

fn change_log_level(delta: isize) {
    let level = log::max_level() as isize;
    let max = log::LevelFilter::max() as isize;
    let level = (level + delta).clamp(0, max) as usize;
    // levelfilter is repr(usize) so this is safe
    let level = unsafe { std::mem::transmute::<usize, LevelFilter>(level) };

    log::set_max_level(level);
}

and I was surprised I had to reach for transmute (or otherwise do something clunky like match on each level).

@Thomasdezeeuw
Copy link
Collaborator

I don't think we want to commit to this, see #460.

@nebkor
Copy link
Contributor Author

nebkor commented Jul 31, 2025

I don't think we want to commit to this, see #460.

I see that issue except as was pointed out there, and if I may point it out here, you're already committed to repr(usize).

@nebkor nebkor closed this Aug 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants