Skip to content

Commit

Permalink
Implement PartialEq/Eq and PartialOrd/Ord for TeamMemberRole (
Browse files Browse the repository at this point in the history
#2862)

The traits must be implemented manually to make all `Other` variants return the
same ordering value.
  • Loading branch information
GnomedDev committed May 19, 2024
1 parent feecb05 commit 4e5189c
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions src/model/application/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,37 @@ pub enum TeamMemberRole {
Other(String),
}

impl TeamMemberRole {
fn discriminant(&self) -> u8 {
match self {
Self::Admin => 3,
Self::Developer => 2,
Self::ReadOnly => 1,
Self::Other(_) => 0,
}
}
}

impl PartialEq for TeamMemberRole {
fn eq(&self, other: &Self) -> bool {
self.discriminant() == other.discriminant()
}
}

impl Eq for TeamMemberRole {}

impl PartialOrd for TeamMemberRole {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}

impl Ord for TeamMemberRole {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.discriminant().cmp(&other.discriminant())
}
}

bitflags! {
/// The flags of the application.
///
Expand Down Expand Up @@ -234,3 +265,38 @@ pub struct InstallParams {
pub scopes: Vec<Scope>,
pub permissions: Permissions,
}

#[cfg(test)]
mod team_role_ordering {
use super::TeamMemberRole;

fn other(val: &str) -> TeamMemberRole {
TeamMemberRole::Other(String::from(val))
}

#[test]
fn test_normal_ordering() {
let mut roles = [
TeamMemberRole::Developer,
TeamMemberRole::Admin,
other(""),
TeamMemberRole::ReadOnly,
other("test"),
];

roles.sort();

assert_eq!(roles, [
other(""),
other("test"),
TeamMemberRole::ReadOnly,
TeamMemberRole::Developer,
TeamMemberRole::Admin,
]);
}

#[test]
fn test_other_eq() {
assert_eq!(other("").cmp(&other("")), std::cmp::Ordering::Equal);
}
}

0 comments on commit 4e5189c

Please sign in to comment.