Skip to content

Commit

Permalink
Update hashbrown to 0.15 (#15801)
Browse files Browse the repository at this point in the history
Updating dependencies; adopted version of #15696. (Supercedes #15696.)

Long answer: hashbrown is no longer using ahash by default, meaning that
we can't use the default-hasher methods with ahasher. So, we have to use
the longer-winded versions instead. This takes the opportunity to also
switch our default hasher as well, but without actually enabling the
default-hasher feature for hashbrown, meaning that we'll be able to
change our hasher more easily at the cost of all of these method calls
being obnoxious forever.

One large change from 0.15 is that `insert_unique_unchecked` is now
`unsafe`, and for cases where unsafe code was denied at the crate level,
I replaced it with `insert`.

## Migration Guide

`bevy_utils` has updated its version of `hashbrown` to 0.15 and now
defaults to `foldhash` instead of `ahash`. This means that if you've
hard-coded your hasher to `bevy_utils::AHasher` or separately used the
`ahash` crate in your code, you may need to switch to `foldhash` to
ensure that everything works like it does in Bevy.
  • Loading branch information
clarfonthey authored Dec 10, 2024
1 parent f3974aa commit 711246a
Show file tree
Hide file tree
Showing 78 changed files with 416 additions and 350 deletions.
8 changes: 5 additions & 3 deletions crates/bevy_animation/src/graph.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! The animation graph, which allows animations to be blended together.
use core::iter;
use core::ops::{Index, IndexMut, Range};
use core::{
iter,
ops::{Index, IndexMut, Range},
};
use std::io::{self, Write};

use bevy_asset::{
Expand Down Expand Up @@ -420,7 +422,7 @@ impl AnimationGraph {
Self {
graph,
root,
mask_groups: HashMap::new(),
mask_groups: HashMap::default(),
}
}

Expand Down
3 changes: 1 addition & 2 deletions crates/bevy_animation/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,8 @@ use bevy_reflect::{prelude::ReflectDefault, Reflect, TypePath};
use bevy_time::Time;
use bevy_transform::TransformSystem;
use bevy_utils::{
hashbrown::HashMap,
tracing::{trace, warn},
NoOpHash, PreHashMap, PreHashMapExt, TypeIdMap,
HashMap, NoOpHash, PreHashMap, PreHashMapExt, TypeIdMap,
};
use petgraph::graph::NodeIndex;
use serde::{Deserialize, Serialize};
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_app/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ impl App {
Self {
sub_apps: SubApps {
main: SubApp::new(),
sub_apps: HashMap::new(),
sub_apps: HashMap::default(),
},
runner: Box::new(run_once),
}
Expand Down
6 changes: 3 additions & 3 deletions crates/bevy_asset/src/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,8 @@ pub enum UntypedAssetConversionError {
#[cfg(test)]
mod tests {
use bevy_reflect::PartialReflect;
use bevy_utils::FixedHasher;
use core::hash::BuildHasher;

use super::*;

Expand All @@ -525,9 +527,7 @@ mod tests {

/// Simple utility to directly hash a value using a fixed hasher
fn hash<T: Hash>(data: &T) -> u64 {
let mut hasher = bevy_utils::AHasher::default();
data.hash(&mut hasher);
hasher.finish()
FixedHasher.hash_one(data)
}

/// Typed and Untyped `Handles` should be equivalent to each other and themselves
Expand Down
6 changes: 2 additions & 4 deletions crates/bevy_asset/src/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,11 +418,9 @@ mod tests {

/// Simple utility to directly hash a value using a fixed hasher
fn hash<T: Hash>(data: &T) -> u64 {
use core::hash::Hasher;
use core::hash::BuildHasher;

let mut hasher = bevy_utils::AHasher::default();
data.hash(&mut hasher);
hasher.finish()
bevy_utils::FixedHasher.hash_one(data)
}

/// Typed and Untyped `AssetIds` should be equivalent to each other and themselves
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_asset/src/io/gated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl<R: AssetReader> GatedReader<R> {
/// Creates a new [`GatedReader`], which wraps the given `reader`. Also returns a [`GateOpener`] which
/// can be used to open "path gates" for this [`GatedReader`].
pub fn new(reader: R) -> (Self, GateOpener) {
let gates = Arc::new(RwLock::new(HashMap::new()));
let gates = Arc::new(RwLock::new(HashMap::default()));
(
Self {
reader,
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_asset/src/io/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ impl AssetSourceBuilders {
/// Builds a new [`AssetSources`] collection. If `watch` is true, the unprocessed sources will watch for changes.
/// If `watch_processed` is true, the processed sources will watch for changes.
pub fn build_sources(&mut self, watch: bool, watch_processed: bool) -> AssetSources {
let mut sources = HashMap::new();
let mut sources = <HashMap<_, _>>::default();
for (id, source) in &mut self.sources {
if let Some(data) = source.build(
AssetSourceId::Name(id.clone_owned()),
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_asset/src/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ pub struct LoadedAsset<A: Asset> {
impl<A: Asset> LoadedAsset<A> {
/// Create a new loaded asset. This will use [`VisitAssetDependencies`](crate::VisitAssetDependencies) to populate `dependencies`.
pub fn new_with_dependencies(value: A, meta: Option<Box<dyn AssetMetaDyn>>) -> Self {
let mut dependencies = HashSet::new();
let mut dependencies = <HashSet<_>>::default();
value.visit_dependencies(&mut |id| {
dependencies.insert(id);
});
Expand Down
4 changes: 2 additions & 2 deletions crates/bevy_asset/src/server/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -395,10 +395,10 @@ impl AssetInfos {

loaded_asset.value.insert(loaded_asset_id, world);
let mut loading_deps = loaded_asset.dependencies;
let mut failed_deps = HashSet::new();
let mut failed_deps = <HashSet<_>>::default();
let mut dep_error = None;
let mut loading_rec_deps = loading_deps.clone();
let mut failed_rec_deps = HashSet::new();
let mut failed_rec_deps = <HashSet<_>>::default();
let mut rec_dep_error = None;
loading_deps.retain(|dep_id| {
if let Some(dep_info) = self.get_mut(*dep_id) {
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_asset/src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1544,7 +1544,7 @@ pub fn handle_internal_asset_events(world: &mut World) {
}
};

let mut paths_to_reload = HashSet::new();
let mut paths_to_reload = <HashSet<_>>::default();
let mut handle_event = |source: AssetSourceId<'static>, event: AssetSourceEvent| {
match event {
// TODO: if the asset was processed and the processed file was changed, the first modified event
Expand Down
8 changes: 3 additions & 5 deletions crates/bevy_core/src/name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ use alloc::borrow::Cow;
use bevy_reflect::std_traits::ReflectDefault;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::Reflect;
use bevy_utils::AHasher;
use bevy_utils::FixedHasher;
use core::{
hash::{Hash, Hasher},
hash::{BuildHasher, Hash, Hasher},
ops::Deref,
};

Expand Down Expand Up @@ -80,9 +80,7 @@ impl Name {
}

fn update_hash(&mut self) {
let mut hasher = AHasher::default();
self.name.hash(&mut hasher);
self.hash = hasher.finish();
self.hash = FixedHasher.hash_one(&self.name);
}
}

Expand Down
10 changes: 5 additions & 5 deletions crates/bevy_core_pipeline/src/core_2d/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ pub mod graph {
use core::ops::Range;

use bevy_asset::UntypedAssetId;
use bevy_render::batching::gpu_preprocessing::GpuPreprocessingMode;
use bevy_render::render_phase::PhaseItemBinKey;
use bevy_render::{
batching::gpu_preprocessing::GpuPreprocessingMode, render_phase::PhaseItemBinKey,
};
use bevy_utils::HashMap;
pub use camera_2d::*;
pub use main_opaque_pass_2d_node::*;
Expand All @@ -44,7 +45,6 @@ use crate::{tonemapping::TonemappingNode, upscaling::UpscalingNode};
use bevy_app::{App, Plugin};
use bevy_ecs::{entity::EntityHashSet, prelude::*};
use bevy_math::FloatOrd;
use bevy_render::sync_world::MainEntity;
use bevy_render::{
camera::{Camera, ExtractedCamera},
extract_component::ExtractComponentPlugin,
Expand All @@ -59,7 +59,7 @@ use bevy_render::{
TextureFormat, TextureUsages,
},
renderer::RenderDevice,
sync_world::RenderEntity,
sync_world::{MainEntity, RenderEntity},
texture::TextureCache,
view::{Msaa, ViewDepthTexture},
Extract, ExtractSchedule, Render, RenderApp, RenderSet,
Expand Down Expand Up @@ -423,7 +423,7 @@ pub fn prepare_core_2d_depth_textures(
opaque_2d_phases: Res<ViewBinnedRenderPhases<Opaque2d>>,
views_2d: Query<(Entity, &ExtractedCamera, &Msaa), (With<Camera2d>,)>,
) {
let mut textures = HashMap::default();
let mut textures = <HashMap<_, _>>::default();
for (view, camera, msaa) in &views_2d {
if !opaque_2d_phases.contains_key(&view) || !transparent_2d_phases.contains_key(&view) {
continue;
Expand Down
29 changes: 15 additions & 14 deletions crates/bevy_core_pipeline/src/core_3d/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,12 @@ pub const DEPTH_TEXTURE_SAMPLING_SUPPORTED: bool = true;

use core::ops::Range;

use bevy_render::batching::gpu_preprocessing::{GpuPreprocessingMode, GpuPreprocessingSupport};
use bevy_render::mesh::allocator::SlabId;
use bevy_render::render_phase::PhaseItemBinKey;
use bevy_render::view::GpuCulling;
use bevy_render::{
batching::gpu_preprocessing::{GpuPreprocessingMode, GpuPreprocessingSupport},
mesh::allocator::SlabId,
render_phase::PhaseItemBinKey,
view::GpuCulling,
};
pub use camera_3d::*;
pub use main_opaque_pass_3d_node::*;
pub use main_transparent_pass_3d_node::*;
Expand All @@ -79,7 +81,6 @@ use bevy_color::LinearRgba;
use bevy_ecs::{entity::EntityHashSet, prelude::*};
use bevy_image::{BevyDefault, Image};
use bevy_math::FloatOrd;
use bevy_render::sync_world::MainEntity;
use bevy_render::{
camera::{Camera, ExtractedCamera},
extract_component::ExtractComponentPlugin,
Expand All @@ -95,7 +96,7 @@ use bevy_render::{
TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, TextureView,
},
renderer::RenderDevice,
sync_world::RenderEntity,
sync_world::{MainEntity, RenderEntity},
texture::{ColorAttachment, TextureCache},
view::{ExtractedView, ViewDepthTexture, ViewTarget},
Extract, ExtractSchedule, Render, RenderApp, RenderSet,
Expand Down Expand Up @@ -700,7 +701,7 @@ pub fn prepare_core_3d_depth_textures(
&Msaa,
)>,
) {
let mut render_target_usage = HashMap::default();
let mut render_target_usage = <HashMap<_, _>>::default();
for (view, camera, depth_prepass, camera_3d, _msaa) in &views_3d {
if !opaque_3d_phases.contains_key(&view)
|| !alpha_mask_3d_phases.contains_key(&view)
Expand All @@ -722,7 +723,7 @@ pub fn prepare_core_3d_depth_textures(
.or_insert_with(|| usage);
}

let mut textures = HashMap::default();
let mut textures = <HashMap<_, _>>::default();
for (entity, camera, _, camera_3d, msaa) in &views_3d {
let Some(physical_target_size) = camera.physical_target_size else {
continue;
Expand Down Expand Up @@ -785,7 +786,7 @@ pub fn prepare_core_3d_transmission_textures(
transparent_3d_phases: Res<ViewSortedRenderPhases<Transparent3d>>,
views_3d: Query<(Entity, &ExtractedCamera, &Camera3d, &ExtractedView)>,
) {
let mut textures = HashMap::default();
let mut textures = <HashMap<_, _>>::default();
for (entity, camera, camera_3d, view) in &views_3d {
if !opaque_3d_phases.contains_key(&entity)
|| !alpha_mask_3d_phases.contains_key(&entity)
Expand Down Expand Up @@ -893,11 +894,11 @@ pub fn prepare_prepass_textures(
Has<DeferredPrepass>,
)>,
) {
let mut depth_textures = HashMap::default();
let mut normal_textures = HashMap::default();
let mut deferred_textures = HashMap::default();
let mut deferred_lighting_id_textures = HashMap::default();
let mut motion_vectors_textures = HashMap::default();
let mut depth_textures = <HashMap<_, _>>::default();
let mut normal_textures = <HashMap<_, _>>::default();
let mut deferred_textures = <HashMap<_, _>>::default();
let mut deferred_lighting_id_textures = <HashMap<_, _>>::default();
let mut motion_vectors_textures = <HashMap<_, _>>::default();
for (
entity,
camera,
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_core_pipeline/src/oit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ fn configure_depth_texture_usages(

// Find all the render target that potentially uses OIT
let primary_window = p.get_single().ok();
let mut render_target_has_oit = HashSet::new();
let mut render_target_has_oit = <HashSet<_>>::default();
for (camera, has_oit) in &cameras {
if has_oit {
render_target_has_oit.insert(camera.target.normalize(primary_window));
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_core_pipeline/src/upscaling/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ fn prepare_view_upscaling_pipelines(
blit_pipeline: Res<BlitPipeline>,
view_targets: Query<(Entity, &ViewTarget, Option<&ExtractedCamera>)>,
) {
let mut output_textures = HashSet::new();
let mut output_textures = <HashSet<_>>::default();
for (entity, view_target, camera) in view_targets.iter() {
let out_texture_id = view_target.out_texture().id();
let blend_state = if let Some(extracted_camera) = camera {
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_dev_tools/src/ui_debug_overlay/inset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ struct DrawnLines {
impl DrawnLines {
fn new(width: f32) -> Self {
DrawnLines {
lines: HashMap::new(),
lines: HashMap::default(),
width,
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_diagnostic/src/diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use core::hash::{Hash, Hasher};

use bevy_app::{App, SubApp};
use bevy_ecs::system::{Deferred, Res, Resource, SystemBuffer, SystemParam};
use bevy_utils::{hashbrown::HashMap, Duration, Instant, PassHash};
use bevy_utils::{Duration, HashMap, Instant, PassHash};
use const_fnv1a_hash::fnv1a_hash_str_64;

use crate::DEFAULT_MAX_HISTORY_LENGTH;
Expand Down
4 changes: 2 additions & 2 deletions crates/bevy_ecs/src/archetype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@ impl Archetype {
// component in the `table_components` vector
component_index
.entry(component_id)
.or_insert_with(HashMap::new)
.or_default()
.insert(id, ArchetypeRecord { column: Some(idx) });
}

Expand All @@ -420,7 +420,7 @@ impl Archetype {
);
component_index
.entry(component_id)
.or_insert_with(HashMap::new)
.or_default()
.insert(id, ArchetypeRecord { column: None });
}
Self {
Expand Down
9 changes: 6 additions & 3 deletions crates/bevy_ecs/src/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ impl BundleInfo {

if deduped.len() != component_ids.len() {
// TODO: Replace with `Vec::partition_dedup` once https://github.com/rust-lang/rust/issues/54279 is stabilized
let mut seen = HashSet::new();
let mut seen = <HashSet<_>>::default();
let mut dups = Vec::new();
for id in component_ids {
if !seen.insert(id) {
Expand Down Expand Up @@ -1422,8 +1422,11 @@ impl Bundles {
.or_insert_with(|| {
let (id, storages) =
initialize_dynamic_bundle(bundle_infos, components, Vec::from(component_ids));
self.dynamic_bundle_storages
.insert_unique_unchecked(id, storages);
// SAFETY: The ID always increases when new bundles are added, and so, the ID is unique.
unsafe {
self.dynamic_bundle_storages
.insert_unique_unchecked(id, storages);
}
(component_ids.into(), id)
});
*bundle_id
Expand Down
3 changes: 2 additions & 1 deletion crates/bevy_ecs/src/entity/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ impl BuildHasher for EntityHash {
///
/// If you have an unusual case -- say all your indices are multiples of 256
/// or most of the entities are dead generations -- then you might want also to
/// try [`AHasher`](bevy_utils::AHasher) for a slower hash computation but fewer lookup conflicts.
/// try [`DefaultHasher`](bevy_utils::DefaultHasher) for a slower hash
/// computation but fewer lookup conflicts.
#[derive(Debug, Default)]
pub struct EntityHasher {
hash: u64,
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_ecs/src/entity/visit_entities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ mod tests {
let mut entity_map = EntityHashMap::<Entity>::default();
let mut remapped = Foo {
ordered: vec![],
unordered: HashSet::new(),
unordered: HashSet::default(),
single: Entity::PLACEHOLDER,
not_an_entity: foo.not_an_entity.clone(),
};
Expand Down
13 changes: 4 additions & 9 deletions crates/bevy_ecs/src/intern.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,8 @@ impl<T: ?Sized> Default for Interner<T> {

#[cfg(test)]
mod tests {
use core::hash::{Hash, Hasher};
use std::collections::hash_map::DefaultHasher;
use bevy_utils::FixedHasher;
use core::hash::{BuildHasher, Hash, Hasher};

use crate::intern::{Internable, Interned, Interner};

Expand Down Expand Up @@ -250,13 +250,8 @@ mod tests {

assert_eq!(a, b);

let mut hasher = DefaultHasher::default();
a.hash(&mut hasher);
let hash_a = hasher.finish();

let mut hasher = DefaultHasher::default();
b.hash(&mut hasher);
let hash_b = hasher.finish();
let hash_a = FixedHasher.hash_one(a);
let hash_b = FixedHasher.hash_one(b);

assert_eq!(hash_a, hash_b);
}
Expand Down
Loading

0 comments on commit 711246a

Please sign in to comment.