From b6198ad516fca50c296742c7693713895ede89d2 Mon Sep 17 00:00:00 2001 From: Michael Sloan Date: Tue, 18 Mar 2025 00:20:21 -0600 Subject: [PATCH] Add `Ord` and `PartialOrd` impls for gpui entity types (#26968) Motivation is to be able to use entities as TreeMap keys. Release Notes: - N/A Co-authored-by: Nathan --- crates/gpui/src/app/entity_map.rs | 49 +++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/crates/gpui/src/app/entity_map.rs b/crates/gpui/src/app/entity_map.rs index 60b59079a94dd850ad8c75890b664450a30bb972..9504c1f1ff361f33f05672415e6d3582255aa57d 100644 --- a/crates/gpui/src/app/entity_map.rs +++ b/crates/gpui/src/app/entity_map.rs @@ -7,6 +7,7 @@ use slotmap::{KeyData, SecondaryMap, SlotMap}; use std::{ any::{type_name, Any, TypeId}, cell::RefCell, + cmp::Ordering, fmt::{self, Display}, hash::{Hash, Hasher}, marker::PhantomData, @@ -350,6 +351,18 @@ impl PartialEq for AnyEntity { impl Eq for AnyEntity {} +impl Ord for AnyEntity { + fn cmp(&self, other: &Self) -> Ordering { + self.entity_id.cmp(&other.entity_id) + } +} + +impl PartialOrd for AnyEntity { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + impl std::fmt::Debug for AnyEntity { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("AnyEntity") @@ -495,6 +508,18 @@ impl PartialEq> for Entity { } } +impl Ord for Entity { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.entity_id().cmp(&other.entity_id()) + } +} + +impl PartialOrd for Entity { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + /// A type erased, weak reference to a entity. #[derive(Clone)] pub struct AnyWeakEntity { @@ -599,6 +624,18 @@ impl PartialEq for AnyWeakEntity { impl Eq for AnyWeakEntity {} +impl Ord for AnyWeakEntity { + fn cmp(&self, other: &Self) -> Ordering { + self.entity_id.cmp(&other.entity_id) + } +} + +impl PartialOrd for AnyWeakEntity { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + /// A weak reference to a entity of the given type. #[derive(Deref, DerefMut)] pub struct WeakEntity { @@ -711,6 +748,18 @@ impl PartialEq> for WeakEntity { } } +impl Ord for WeakEntity { + fn cmp(&self, other: &Self) -> Ordering { + self.entity_id().cmp(&other.entity_id()) + } +} + +impl PartialOrd for WeakEntity { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + #[cfg(any(test, feature = "leak-detection"))] static LEAK_BACKTRACE: std::sync::LazyLock = std::sync::LazyLock::new(|| std::env::var("LEAK_BACKTRACE").map_or(false, |b| !b.is_empty()));