rwf2 / Rocket

A web framework for Rust.

Home Page:https://rocket.rs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Implement `PartialEq` for `http::Status` with derive macro

frondeus opened this issue · comments

API Docs to Existing Functionality

https://api.rocket.rs/v0.5/rocket/http/struct.Status

Problems with Existing Functionality

Status does not implement PartialEq via derive(PartialEq), which causes it to lack StructuralPartialEq.

It prohibits using status in match:

match status {
    Status::Unauthorized => { ... },
    Status::NotFound => { ... },
    _ => { ... }
}

because Status::Unauthorized is a constant which triggers error:

error: to use a constant of type `rocket::http::Status` in a pattern, `rocket::http::Status` must be annotated with `#[derive(PartialEq)]`
  --> my_project/src/errors.rs:40:13
   |
40 |             Status::Unauthorized => { ... },
   |             ^^^^^^^^^^^^^^^^^^^^
   |
   = note: the traits must be derived, manual `impl`s are not sufficient
   = note: see https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html for details

Suggested Changes

I've looked at current implementation of PartialEq for Status:
https://github.com/rwf2/Rocket/blob/1a3ef5b23fdf4a4619fa9b5d3f24cff6f8008085/core/http/src/status.rs#L363C1-L367C2

And it seems that there is nothing prohibiting automatic derive.

Alternatives Considered

An alternative solution to my match expression is something like this:

match status {
    status if status == Status::Unauthorized => { ... },
    status if status == Status::TooManyRequests => { ... },
}

But it doesn't feel idiomatic.

Another would be to use code directly:

match status.code {
    401 => { ... },
    429 => { ... }
}

But here I'm more prone to the typo than using existing constant.

Additional Context

No response

System Checks

  • I do not believe that this suggestion can or should be implemented outside of Rocket.

  • I was unable to find a previous suggestion for this change.

Yes, we should do this. This is an artifact of Status originally having had a second "reason" field, which prevented using the derives. This field was later removed. If you could submit a PR, that would be helpful.

As an addendum, we should also derive Eq, PartialOrd and Ord, for the same reason.

I'm eager to do the PR, should I also include Hash? It also seems to be a good candidate for derive.

Yeah, might as well.