Struct rust_examples::orphan::OrphanInstanceTest [−][src]
pub struct OrphanInstanceTest;Expand description
This test demonstrates that Rust disallows Orphan Instances.
Variation of the Hash table Problem
ⓘ
pub mod module_b {
use crate::orphan::model::Entity;
use std::cmp::Ordering;
// Implements `Ord` for `Entity` in which `X` < `Y`
impl Ord for Entity {
fn cmp(&self, other: &Self) -> Ordering {
use Entity::*;
match (self, other) {
(X, X) | (Y, Y) => Ordering::Equal,
(X, Y) => Ordering::Less,
(Y, X) => Ordering::Greater,
}
}
}
impl PartialOrd for Entity {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
// Sorts given entities using `Ord` implementation for `Entity` contained in this module
pub fn prioritize(entities: &mut [Entity]) {
entities.sort();
}
}
#[test]
#[should_fail]
fn priority_inversion() {
use crate::orphan::{model::Entity, module_a, module_b};
let mut entities = vec![Entity::X, Entity::Y];
module_a::prioritize(&mut entities);
assert_eq!(entities, vec![Entity::Y, Entity::X]);
module_b::prioritize(&mut entities);
// This would fail if orphan instances were allowed
// - i.e. the behavior would depend on the *scope* rather than *types*
assert_eq!(entities, vec![Entity::Y, Entity::X]);
}