3

As a Rust beginner working on one of the first problems on Exercism/Rust (https://exercism.org/tracks/rust/exercises/assembly-line)
I would like to know if it is possible to constrain integer input to a range at compile-time
to be able to have a clean set of match expression cases.

Below is my current implementation of production_rate_per_hour:

pub fn production_rate_per_hour(mut speed: u8) -> f64 {
    speed = cmp::max(speed, 10);

    let cars_per_hour: u8 = 221;

    match speed {
      0 => 0.0,
      1 ..= 4 => (speed * cars_per_hour) as f64,
      5 ..= 8 => (speed * cars_per_hour) as f64 * 0.9,
      9 | 10 => (speed * cars_per_hour) as f64 * 0.77
    }
}

I am trying to write a method that accepts a single mutable u8 argument named speed that I then constrain to the range 0..=10 as follows:

speed = cmp::max(speed, 10);

I then want to match speed on all possible cases, i.e. 0..=10. But since this is a run-time check, the compiler does not see this and tells me to also match integer value 11 and higher:

Compiling assembly-line v0.1.0 (/Users/michahell/Exercism/rust/assembly-line)
error[E0004]: non-exhaustive patterns: `11_u8..=u8::MAX` not covered
  --> src/lib.rs:12:11
   |
12 |     match speed {
   |           ^^^^^ pattern `11_u8..=u8::MAX` not covered
   |
   = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
   = note: the matched value is of type `u8`

I can of course solve this by adding the following case:

// notify
_ => println!("11 or higher")
// or crash
_ => panic!("you've crashed the assembly line!");
// or do something like this:
_ => (cmp::max(speed, 10) * cars_per_hour) as f64 * 0.77;

However, I would like to know if it is possible to constrain the input range at compile-time, and having a "clean" match expression.

Is this possible, if so, how?

4
  • it's an anti pattern question, the match exist to make runtime check it's non sense to not do _ => (10 * cars_per_hour) as f64 * 0.77;
    – Stargateur
    Dec 12, 2021 at 13:53
  • 1
    This seems like a perfect use case for _ => unreachable!(); that is exactly what it is designed for, and it will even hint to the optimizer that the codepath is unreachable. However, i this case I think a better solution would be matching 0 through 9, then _ => handle_like_10.
    – Coder-256
    Dec 12, 2021 at 16:53
  • @Coder-256 oh wow I had not thought of this match-arm setup yet. In the coding challenge however, case 9 and 10 should be treated equally but this is a very nice way of dealing with N+ integers as the "rest" case.
    – Michahell
    Dec 12, 2021 at 22:17
  • 2
    "it will even hint to the optimizer" - only if in a sense that "panicking is a cold path". Optimizer is not allowed to remove panicking code, unless it proves that it is actually unreachable.
    – Cerberus
    Dec 13, 2021 at 4:23

1 Answer 1

7

There is currently no way to express this in the type system.

I assume you mean min instead of max. The typical approach would be:

pub fn production_rate_per_hour(mut speed: u8) -> f64 {
    speed = cmp::min(speed, 10);

    let cars_per_hour: u8 = 221;

    match speed {
      0 => 0.0,
      1 ..= 4 => (speed * cars_per_hour) as f64,
      5 ..= 8 => (speed * cars_per_hour) as f64 * 0.9,
      9 | 10 => (speed * cars_per_hour) as f64 * 0.77,
      _ => unreachable!(),
    }
}

A bug in your program (e.g., accidentally raising the cap to 11) will result in a panic. If this is performance sensitive, you can use unsafe:

_ => unsafe { std::hint::unreachable_unchecked() },

If your claim that this branch is unreachable is false, you get undefined behavior.

Note that in many cases, the compiler will be able to prove the unreachable branch is, in fact, unreachable and elide it completely. This is very common for e.g. modular arithmetic:

Example

pub fn foo(v: u64) -> u8 {
    match v % 8 {
      0 => 0,
      1 ..= 4 => 1,
      5 ..= 7 => 2,
      _ => unreachable!(),
    }
}

Note that after a slight refactoring:

pub fn production_rate_per_hour(speed: u8) -> f64 {
    let speed = speed.min(10);
    let factor = match speed {
      0 => 0.0_f64,
      1 ..= 4 => 1.0,
      5 ..= 8 => 0.9,
      9.. => 0.77,
    };

    let cars_per_hour: u8 = 221;

    factor * (speed * cars_per_hour) as f64
}

There is no case where unreachable is needed. The tradeoff is you no longer get to be very explicit in the match about what values of speed are acceptable. Whether this or a panic is better depends on your context.

4
  • I'm actually really surprised LLVM doesn't remove this panic check, seems like a missed optimization bug.
    – GManNickG
    Dec 12, 2021 at 16:27
  • 3
    @JohnKugelman Alright, silly bug aside: rust.godbolt.org/z/Y3xsdnnsK. If you remove any particular match arm (say by merging it with another) then the panic is elided, else it seems to always be present. Will probably follow up with a rustc ticket after some digging.
    – GManNickG
    Dec 12, 2021 at 17:19
  • Thank you for a great explanation and teaching some concepts in the process. as someone not so bright concerning math it took me a minute to understand the modulo example. two questions about the refactoring example: it seems as though Rust u8 is a boxed type by your use of speed.min(10). I thought they weren't? how does that work? And, why is it needed to suffix the first match arm 0.0 with _f64 but not the others?
    – Michahell
    Dec 12, 2021 at 22:32
  • 1
    @MichaelTrouw Nothing in Rust in boxed unless you explicitly ask for it, so u8 here is not boxed. Being boxed is distinct and different from having methods. In Rust any value can (in principle) define methods. It can look odd coming from other languages where primitive types are treated special. Re: constant, in this case technically the suffix is not needed. In general literal constants do not have a type, but will infer their type from where they are used. Since factor is eventually multiplied by an f64 value, it is deduced to be f64. I only included it out of habit, for clarity.
    – GManNickG
    Dec 12, 2021 at 23:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.