Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

Use no-op hasher for TypeId hashing (#58629)

Lukas Wirtha85f8ad090d7
diff --git a/Cargo.lock b/Cargo.lock
index a3e46c9eb17..cc852164064 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3479,6 +3479,7 @@ dependencies = [
name = "collections"
version = "0.1.0"
dependencies = [
+ "gpui_util",
"indexmap 2.11.4",
"rustc-hash 2.1.1",
]
diff --git a/crates/collab/src/rpc.rs b/crates/collab/src/rpc.rs
index b5870daf330..ef46033d128 100644
--- a/crates/collab/src/rpc.rs
+++ b/crates/collab/src/rpc.rs
@@ -30,7 +30,7 @@ use axum::{
response::IntoResponse,
routing::get,
};
-use collections::{HashMap, HashSet};
+use collections::{HashSet, TypeIdHashMap};
pub use connection_pool::{ConnectionPool, ZedVersion};
use core::fmt::{self, Debug, Formatter};
use futures::TryFutureExt as _;
@@ -313,7 +313,7 @@ pub struct Server {
peer: Arc<Peer>,
pub connection_pool: Arc<parking_lot::Mutex<ConnectionPool>>,
app_state: Arc<AppState>,
- handlers: HashMap<TypeId, MessageHandler>,
+ handlers: TypeIdHashMap<MessageHandler>,
teardown: watch::Sender<bool>,
}
diff --git a/crates/collections/Cargo.toml b/crates/collections/Cargo.toml
index aa3dd899a72..2a86e88d4f6 100644
--- a/crates/collections/Cargo.toml
+++ b/crates/collections/Cargo.toml
@@ -19,3 +19,4 @@ test-support = []
[dependencies]
indexmap.workspace = true
rustc-hash.workspace = true
+gpui_util.workspace = true
diff --git a/crates/collections/src/collections.rs b/crates/collections/src/collections.rs
index 8e6c334d2bd..9a7f4942c8b 100644
--- a/crates/collections/src/collections.rs
+++ b/crates/collections/src/collections.rs
@@ -2,10 +2,12 @@ pub type HashMap<K, V> = FxHashMap<K, V>;
pub type HashSet<T> = FxHashSet<T>;
pub type IndexMap<K, V> = indexmap::IndexMap<K, V, rustc_hash::FxBuildHasher>;
pub type IndexSet<T> = indexmap::IndexSet<T, rustc_hash::FxBuildHasher>;
+pub type TypeIdHashMap<V> =
+ std::collections::HashMap<std::any::TypeId, V, gpui_util::TypeIdHashBuilder>;
+pub type TypeIdHashSet = std::collections::HashSet<std::any::TypeId, gpui_util::TypeIdHashBuilder>;
pub use indexmap::Equivalent;
-pub use rustc_hash::FxHasher;
-pub use rustc_hash::{FxHashMap, FxHashSet};
+pub use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet, FxHasher};
pub use std::collections::*;
pub mod vecmap;
diff --git a/crates/command_palette_hooks/src/command_palette_hooks.rs b/crates/command_palette_hooks/src/command_palette_hooks.rs
index bd8f9375b77..a137e5f1c89 100644
--- a/crates/command_palette_hooks/src/command_palette_hooks.rs
+++ b/crates/command_palette_hooks/src/command_palette_hooks.rs
@@ -4,7 +4,7 @@
use std::{any::TypeId, rc::Rc};
-use collections::HashSet;
+use collections::{HashSet, TypeIdHashSet};
use derive_more::{Deref, DerefMut};
use gpui::{Action, App, BorrowAppContext, Global, Task, WeakEntity};
use workspace::Workspace;
@@ -18,10 +18,10 @@ pub fn init(cx: &mut App) {
#[derive(Default)]
pub struct CommandPaletteFilter {
hidden_namespaces: HashSet<&'static str>,
- hidden_action_types: HashSet<TypeId>,
+ hidden_action_types: TypeIdHashSet,
/// Actions that have explicitly been shown. These should be shown even if
/// they are in a hidden namespace.
- shown_action_types: HashSet<TypeId>,
+ shown_action_types: TypeIdHashSet,
}
#[derive(Deref, DerefMut, Default)]
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index 8eca77a5fa4..9826a81da6c 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -74,6 +74,7 @@ mod selection;
pub(crate) use actions::*;
pub use clipboard::ClipboardSelection;
pub use code_actions::CodeActionProvider;
+use collections::TypeIdHashMap;
pub use completions::CompletionProvider;
#[cfg(test)]
pub(crate) use completions::snippet_candidate_suffixes;
@@ -993,10 +994,10 @@ pub struct Editor {
show_indent_guides: Option<bool>,
buffers_with_disabled_indent_guides: HashSet<BufferId>,
highlight_order: usize,
- highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
+ highlighted_rows: TypeIdHashMap<Vec<RowHighlight>>,
background_highlights: HashMap<HighlightKey, BackgroundHighlight>,
navigation_overlays: HashMap<NavigationOverlayKey, Arc<[NavigationTargetOverlay]>>,
- gutter_highlights: HashMap<TypeId, GutterHighlight>,
+ gutter_highlights: TypeIdHashMap<GutterHighlight>,
scrollbar_marker_state: ScrollbarMarkerState,
active_indent_guides_state: ActiveIndentGuidesState,
nav_history: Option<ItemNavHistory>,
@@ -1116,7 +1117,7 @@ pub struct Editor {
breadcrumb_header: Option<String>,
focused_block: Option<FocusedBlock>,
next_scroll_position: NextScrollCursorCenterTopBottom,
- addons: HashMap<TypeId, Box<dyn Addon>>,
+ addons: TypeIdHashMap<Box<dyn Addon>>,
registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
load_diff_task: Option<Shared<Task<()>>>,
/// Whether we are temporarily displaying a diff other than git's
@@ -2191,10 +2192,10 @@ impl Editor {
show_indent_guides,
buffers_with_disabled_indent_guides: HashSet::default(),
highlight_order: 0,
- highlighted_rows: HashMap::default(),
+ highlighted_rows: Default::default(),
background_highlights: HashMap::default(),
navigation_overlays: HashMap::default(),
- gutter_highlights: HashMap::default(),
+ gutter_highlights: Default::default(),
scrollbar_marker_state: ScrollbarMarkerState::default(),
active_indent_guides_state: ActiveIndentGuidesState::default(),
nav_history: None,
@@ -2337,7 +2338,7 @@ impl Editor {
breadcrumb_header: None,
focused_block: None,
next_scroll_position: NextScrollCursorCenterTopBottom::default(),
- addons: HashMap::default(),
+ addons: Default::default(),
registered_buffers: HashMap::default(),
_scroll_cursor_center_top_bottom_task: Task::ready(()),
selection_mark_mode: false,
diff --git a/crates/gpui/src/action.rs b/crates/gpui/src/action.rs
index b270bd0965e..b72d24027f5 100644
--- a/crates/gpui/src/action.rs
+++ b/crates/gpui/src/action.rs
@@ -1,5 +1,5 @@
use anyhow::{Context as _, Result};
-use collections::HashMap;
+use collections::{HashMap, TypeIdHashMap};
pub use gpui_macros::Action;
pub use no_action::{NoAction, Unbind, is_no_action, is_unbind};
use serde_json::json;
@@ -232,7 +232,7 @@ type ActionBuilder = fn(json: serde_json::Value) -> anyhow::Result<Box<dyn Actio
pub(crate) struct ActionRegistry {
by_name: HashMap<&'static str, ActionData>,
- names_by_type_id: HashMap<TypeId, &'static str>,
+ names_by_type_id: TypeIdHashMap<&'static str>,
all_names: Vec<&'static str>, // So we can return a static slice.
deprecated_aliases: HashMap<&'static str, &'static str>, // deprecated name -> preferred name
deprecation_messages: HashMap<&'static str, &'static str>, // action name -> deprecation message
diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs
index 22a05b450ea..3631499fa98 100644
--- a/crates/gpui/src/app.rs
+++ b/crates/gpui/src/app.rs
@@ -25,7 +25,7 @@ use slotmap::SlotMap;
pub use async_context::*;
#[cfg(any(test, feature = "test-support"))]
pub use bench_context::{BenchAppContext, BenchWindowContext};
-use collections::{FxHashMap, FxHashSet, HashMap, VecDeque};
+use collections::{FxHashMap, FxHashSet, HashMap, TypeIdHashMap, TypeIdHashSet, VecDeque};
pub use context::*;
pub use entity_map::*;
use gpui_util::{ResultExt, debug_panic};
@@ -630,7 +630,7 @@ pub struct App {
pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
pub(crate) global_action_listeners:
- FxHashMap<TypeId, Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
+ TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
pending_effects: VecDeque<Effect>,
pub(crate) observers: SubscriberSet<EntityId, Handler>,
@@ -655,7 +655,7 @@ pub struct App {
// callbacks are marked cancelled at this point as this will also shutdown
// the tokio runtime. As any task attempting to spawn a blocking tokio task,
// might panic.
- pub(crate) globals_by_type: FxHashMap<TypeId, Box<dyn Any>>,
+ pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
// assets
pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
@@ -665,7 +665,7 @@ pub struct App {
// below is plain data, the drop order is insignificant here
pub(crate) pending_notifications: FxHashSet<EntityId>,
- pub(crate) pending_global_notifications: FxHashSet<TypeId>,
+ pub(crate) pending_global_notifications: TypeIdHashSet,
pub(crate) restart_path: Option<PathBuf>,
pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
pub(crate) propagate_event: bool,
@@ -738,7 +738,7 @@ impl App {
loading_assets: Default::default(),
asset_source,
http_client,
- globals_by_type: FxHashMap::default(),
+ globals_by_type: Default::default(),
entities,
new_entity_observers: SubscriberSet::new(),
windows: SlotMap::with_key(),
@@ -748,10 +748,10 @@ impl App {
keymap: Rc::new(RefCell::new(Keymap::default())),
keyboard_layout,
keyboard_mapper,
- global_action_listeners: FxHashMap::default(),
+ global_action_listeners: Default::default(),
pending_effects: VecDeque::new(),
pending_notifications: FxHashSet::default(),
- pending_global_notifications: FxHashSet::default(),
+ pending_global_notifications: Default::default(),
observers: SubscriberSet::new(),
tracked_entities: FxHashMap::default(),
window_invalidators_by_entity: FxHashMap::default(),
diff --git a/crates/gpui/src/asset_cache.rs b/crates/gpui/src/asset_cache.rs
index 9afbba8a0ed..bab0b2682ef 100644
--- a/crates/gpui/src/asset_cache.rs
+++ b/crates/gpui/src/asset_cache.rs
@@ -2,7 +2,7 @@ use crate::{App, SharedString, SharedUri};
use futures::{Future, TryFutureExt};
use std::fmt::Debug;
-use std::hash::{Hash, Hasher};
+use std::hash::{BuildHasher, Hash};
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::sync::Arc;
@@ -78,7 +78,5 @@ where
/// Use a quick, non-cryptographically secure hash function to get an identifier from data
pub fn hash<T: Hash>(data: &T) -> u64 {
- let mut hasher = collections::FxHasher::default();
- data.hash(&mut hasher);
- hasher.finish()
+ collections::FxBuildHasher.hash_one(data)
}
diff --git a/crates/gpui/src/inspector.rs b/crates/gpui/src/inspector.rs
index ad3ba6a4b69..12995f03a8a 100644
--- a/crates/gpui/src/inspector.rs
+++ b/crates/gpui/src/inspector.rs
@@ -22,7 +22,7 @@ pub use conditional::*;
mod conditional {
use super::*;
use crate::{AnyElement, App, Context, Empty, IntoElement, Render, Window};
- use collections::FxHashMap;
+ use collections::{FxHashMap, TypeIdHashMap};
use std::any::{Any, TypeId};
/// `GlobalElementId` qualified by source location of element construction.
@@ -64,14 +64,14 @@ mod conditional {
struct InspectedElement {
id: InspectorElementId,
- states: FxHashMap<TypeId, Box<dyn Any>>,
+ states: TypeIdHashMap<Box<dyn Any>>,
}
impl InspectedElement {
fn new(id: InspectorElementId) -> Self {
InspectedElement {
id,
- states: FxHashMap::default(),
+ states: Default::default(),
}
}
}
diff --git a/crates/gpui/src/keymap.rs b/crates/gpui/src/keymap.rs
index eaf582a0074..ade499b890b 100644
--- a/crates/gpui/src/keymap.rs
+++ b/crates/gpui/src/keymap.rs
@@ -5,9 +5,8 @@ pub use binding::*;
pub use context::*;
use crate::{Action, AsKeystroke, Keystroke, Unbind, is_no_action, is_unbind};
-use collections::{HashMap, HashSet};
+use collections::{HashSet, TypeIdHashMap};
use smallvec::SmallVec;
-use std::any::TypeId;
/// An opaque identifier of which version of the keymap is currently active.
/// The keymap's version is changed whenever bindings are added or removed.
@@ -18,7 +17,7 @@ pub struct KeymapVersion(usize);
#[derive(Default)]
pub struct Keymap {
bindings: Vec<KeyBinding>,
- binding_indices_by_action_id: HashMap<TypeId, SmallVec<[usize; 3]>>,
+ binding_indices_by_action_id: TypeIdHashMap<SmallVec<[usize; 3]>>,
disabled_binding_indices: Vec<usize>,
version: KeymapVersion,
}
diff --git a/crates/gpui_util/src/lib.rs b/crates/gpui_util/src/lib.rs
index eac1e2559a2..ee210cb7487 100644
--- a/crates/gpui_util/src/lib.rs
+++ b/crates/gpui_util/src/lib.rs
@@ -391,3 +391,58 @@ impl<F: FnOnce()> Drop for Deferred<F> {
pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
Deferred(Some(f))
}
+
+#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
+pub struct TypeIdHashBuilder;
+
+impl std::hash::BuildHasher for TypeIdHashBuilder {
+ type Hasher = TypeIdHasher;
+
+ fn build_hasher(&self) -> Self::Hasher {
+ TypeIdHasher::default()
+ }
+}
+
+#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
+pub struct TypeIdHasher {
+ value: u64,
+}
+
+impl std::hash::Hasher for TypeIdHasher {
+ #[inline]
+ fn write(&mut self, bytes: &[u8]) {
+ // TypeId should only hash its first 8 bytes
+ if let Some(bytes) = bytes.get(..8) {
+ bytes
+ .as_array()
+ .map(|&array| self.value = u64::from_ne_bytes(array))
+ .unwrap_or_else(|| unreachable!("slice was sliced to 8 bytes"));
+ } else {
+ debug_panic!(
+ "expected a 64-bit value, did you use this hasher with something other than a TypeId?"
+ );
+ }
+ }
+
+ #[inline]
+ fn finish(&self) -> u64 {
+ self.value
+ }
+}
+
+#[test]
+fn type_id_hasher() {
+ use core::any::TypeId;
+ use core::hash::{Hash, Hasher};
+ fn verify_hashing_with(type_id: TypeId) {
+ let mut hasher = TypeIdHasher::default();
+ type_id.hash(&mut hasher);
+ assert_ne!(hasher.finish(), 0);
+ }
+ // Pick a variety of types, just to demonstrate it’s all sane. Normal, zero-sized, unsized, &c.
+ verify_hashing_with(TypeId::of::<usize>());
+ verify_hashing_with(TypeId::of::<()>());
+ verify_hashing_with(TypeId::of::<str>());
+ verify_hashing_with(TypeId::of::<&str>());
+ verify_hashing_with(TypeId::of::<Vec<u8>>());
+}
diff --git a/crates/project/src/debugger/session.rs b/crates/project/src/debugger/session.rs
index fc5f56395cc..185722034a2 100644
--- a/crates/project/src/debugger/session.rs
+++ b/crates/project/src/debugger/session.rs
@@ -15,7 +15,7 @@ use crate::debugger::dap_command::{DataBreakpointContext, ReadMemory};
use crate::debugger::memory::{self, Memory, MemoryIterator, MemoryPageBuilder, PageAddress};
use anyhow::{Context as _, Result, anyhow, bail};
use base64::Engine;
-use collections::{HashMap, HashSet, IndexMap};
+use collections::{HashMap, HashSet, IndexMap, TypeIdHashMap};
use dap::adapters::{DebugAdapterBinary, DebugAdapterName};
use dap::messages::Response;
use dap::requests::{Request, RunInTerminal, StartDebugging};
@@ -704,7 +704,7 @@ pub struct Session {
output: Box<circular_buffer::CircularBuffer<MAX_TRACKED_OUTPUT_EVENTS, dap::OutputEvent>>,
watchers: HashMap<SharedString, Watcher>,
is_session_terminated: bool,
- requests: HashMap<TypeId, HashMap<RequestSlot, Shared<Task<Option<()>>>>>,
+ requests: TypeIdHashMap<HashMap<RequestSlot, Shared<Task<Option<()>>>>>,
pub(crate) breakpoint_store: Entity<BreakpointStore>,
ignore_breakpoints: bool,
exception_breakpoints: BTreeMap<String, (ExceptionBreakpointsFilter, IsEnabled)>,
@@ -876,7 +876,7 @@ impl Session {
watchers: HashMap::default(),
output_token: OutputToken(0),
output: circular_buffer::CircularBuffer::boxed(),
- requests: HashMap::default(),
+ requests: Default::default(),
background_tasks: Vec::default(),
restart_task: None,
is_session_terminated: false,
diff --git a/crates/rpc/src/proto_client.rs b/crates/rpc/src/proto_client.rs
index 4b0b4bc7440..be3d418c9e9 100644
--- a/crates/rpc/src/proto_client.rs
+++ b/crates/rpc/src/proto_client.rs
@@ -1,5 +1,5 @@
use anyhow::{Context, Result};
-use collections::HashMap;
+use collections::{HashMap, TypeIdHashMap};
use futures::{
Future, FutureExt as _, Stream, StreamExt as _,
channel::oneshot,
@@ -88,11 +88,11 @@ pub trait ProtoClient: Send + Sync {
#[derive(Default)]
pub struct ProtoMessageHandlerSet {
- pub entity_types_by_message_type: HashMap<TypeId, TypeId>,
+ pub entity_types_by_message_type: TypeIdHashMap<TypeId>,
pub entities_by_type_and_remote_id: HashMap<(TypeId, u64), EntityMessageSubscriber>,
- pub entity_id_extractors: HashMap<TypeId, fn(&dyn AnyTypedEnvelope) -> u64>,
- pub entities_by_message_type: HashMap<TypeId, AnyWeakEntity>,
- pub message_handlers: HashMap<TypeId, ProtoMessageHandler>,
+ pub entity_id_extractors: TypeIdHashMap<fn(&dyn AnyTypedEnvelope) -> u64>,
+ pub entities_by_message_type: TypeIdHashMap<AnyWeakEntity>,
+ pub message_handlers: TypeIdHashMap<ProtoMessageHandler>,
}
pub type ProtoMessageHandler = Arc<
diff --git a/crates/settings/src/settings_store.rs b/crates/settings/src/settings_store.rs
index 38ccd483297..725e5552873 100644
--- a/crates/settings/src/settings_store.rs
+++ b/crates/settings/src/settings_store.rs
@@ -1,5 +1,5 @@
use anyhow::{Context as _, Result};
-use collections::{BTreeMap, HashMap, btree_map, hash_map};
+use collections::{BTreeMap, HashMap, TypeIdHashMap, btree_map, hash_map};
use fs::Fs;
use futures::{
FutureExt, StreamExt,
@@ -143,7 +143,7 @@ pub struct SettingsLocation<'a> {
}
pub struct SettingsStore {
- setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
+ setting_values: TypeIdHashMap<Box<dyn AnySettingValue>>,
default_settings: Rc<SettingsContent>,
user_settings: Option<UserSettingsContent>,
global_settings: Option<Box<SettingsContent>>,
diff --git a/crates/workspace/src/workspace.rs b/crates/workspace/src/workspace.rs
index c275b8720e1..5f522e5cc61 100644
--- a/crates/workspace/src/workspace.rs
+++ b/crates/workspace/src/workspace.rs
@@ -48,7 +48,7 @@ use client::{
ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
proto::{self, ErrorCode, PanelId, PeerId},
};
-use collections::{HashMap, HashSet, hash_map};
+use collections::{HashMap, HashSet, TypeIdHashMap, hash_map};
use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
use fs::Fs;
use futures::{
@@ -819,7 +819,7 @@ type BuildProjectItemForPathFn =
#[derive(Clone, Default)]
struct ProjectItemRegistry {
- build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
+ build_project_item_fns_by_type: TypeIdHashMap<BuildProjectItemFn>,
build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
}
@@ -947,7 +947,7 @@ pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
}
#[derive(Default)]
-pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
+pub struct FollowableViewRegistry(TypeIdHashMap<FollowableViewDescriptor>);
struct FollowableViewDescriptor {
from_state_proto: fn(
@@ -1020,7 +1020,7 @@ struct SerializableItemDescriptor {
#[derive(Default)]
struct SerializableItemRegistry {
descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
- descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
+ descriptors_by_type: TypeIdHashMap<SerializableItemDescriptor>,
}
impl Global for SerializableItemRegistry {}