Migrate usage of the Hash trait for cache invalidation to the dedicated CacheHash trait (#4051)

* WIP start migrating usages of hash for cache invalidadion to dedicated trait

* Finish migrating usages

* Code review

* Add comments clearifying the reasoning for using random ids in the VectorModification cach hash impl

* Fix some remaining hash violations

* Finish migration and fix compilation

* Fix import ordering

* Cleanup

* Fix code review stuff

---------

Co-authored-by: Keavon Chambers <keavon@keavon.com>
This commit is contained in:
Dennis Kobert
2026-04-27 05:18:47 +00:00
committed by GitHub
co-authored by Keavon Chambers
parent 7bb01c9651
commit 3d84e63ef9
64 changed files with 828 additions and 448 deletions
@@ -0,0 +1,17 @@
[package]
name = "graphene-hash"
version = "0.0.0"
edition = "2024"
authors = ["Graphite Authors <contact@graphite.art>"]
description = "CacheHash trait and derive macro for cache invalidation hashing in Graphite"
license = "MIT OR Apache-2.0"
publish = false
[features]
default = ["std"]
std = []
derive = ["graphene-hash-derive"]
[dependencies]
graphene-hash-derive = { path = "derive", optional = true }
glam = { workspace = true }
@@ -0,0 +1,19 @@
[package]
name = "graphene-hash-derive"
version = "0.0.0"
edition = "2024"
authors = ["Graphite Authors <contact@graphite.art>"]
description = "#[derive(CacheHash)]"
license = "MIT OR Apache-2.0"
publish = false
[lib]
proc-macro = true
[dependencies]
proc-macro2 = { workspace = true }
quote = { workspace = true }
syn = { workspace = true }
[dev-dependencies]
graphene-hash = { path = "..", features = ["derive"] }
@@ -0,0 +1,129 @@
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{Data, DeriveInput, Fields, parse_macro_input};
/// Derives `CacheHash` for a struct or enum.
///
/// All fields must implement `CacheHash`. Fields annotated with `#[cache_hash(skip)]`
/// are excluded from hashing.
///
/// # Example
///
/// ```
/// # use graphene_hash::CacheHash;
/// #[derive(CacheHash)]
/// pub struct MyNode {
/// pub value: f64,
/// pub count: u32,
/// #[cache_hash(skip)]
/// pub debug_label: String,
/// }
/// ```
#[proc_macro_derive(CacheHash, attributes(cache_hash))]
pub fn derive_cache_hash(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let name = &ast.ident;
let mut generics = ast.generics.clone();
for param in &mut generics.params {
if let syn::GenericParam::Type(type_param) = param {
type_param.bounds.push(syn::parse_quote!(graphene_hash::CacheHash));
}
}
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let body = match &ast.data {
Data::Struct(s) => hash_fields(&s.fields, quote! { self }),
Data::Enum(e) => {
let arms = e.variants.iter().map(|variant| {
let variant_name = &variant.ident;
let (pattern, hash_body) = match &variant.fields {
Fields::Unit => (quote! {}, quote! {}),
Fields::Unnamed(fields) => {
let bindings: Vec<_> = (0..fields.unnamed.len())
.map(|i| {
let ident = proc_macro2::Ident::new(&format!("f{i}"), proc_macro2::Span::call_site());
quote! { #ident }
})
.collect();
let hash_stmts = fields.unnamed.iter().enumerate().filter_map(|(i, field)| {
if has_skip_attr(&field.attrs) {
return None;
}
let ident = proc_macro2::Ident::new(&format!("f{i}"), proc_macro2::Span::call_site());
Some(quote! { graphene_hash::CacheHash::cache_hash(#ident, state); })
});
(quote! { (#(#bindings,)*) }, quote! { #(#hash_stmts)* })
}
Fields::Named(fields) => {
let names: Vec<_> = fields.named.iter().map(|f| f.ident.as_ref().unwrap()).collect();
let hash_stmts = fields.named.iter().filter_map(|field| {
if has_skip_attr(&field.attrs) {
return None;
}
let ident = field.ident.as_ref().unwrap();
Some(quote! { graphene_hash::CacheHash::cache_hash(#ident, state); })
});
(quote! { { #(#names,)* } }, quote! { #(#hash_stmts)* })
}
};
quote! {
Self::#variant_name #pattern => { #hash_body }
}
});
quote! {
::core::hash::Hash::hash(&::core::mem::discriminant(self), state);
match self {
#(#arms)*
}
}
}
Data::Union(_) => return syn::Error::new(ast.ident.span(), "CacheHash cannot be derived for unions").to_compile_error().into(),
};
quote! {
impl #impl_generics graphene_hash::CacheHash for #name #ty_generics #where_clause {
fn cache_hash<H: ::core::hash::Hasher>(&self, state: &mut H) {
#body
}
}
}
.into()
}
fn hash_fields(fields: &Fields, self_expr: TokenStream2) -> TokenStream2 {
match fields {
Fields::Unit => quote! {},
Fields::Unnamed(fields) => {
let stmts = fields.unnamed.iter().enumerate().filter_map(|(i, field)| {
if has_skip_attr(&field.attrs) {
return None;
}
let index = syn::Index::from(i);
Some(quote! { graphene_hash::CacheHash::cache_hash(&#self_expr.#index, state); })
});
quote! { #(#stmts)* }
}
Fields::Named(fields) => {
let stmts = fields.named.iter().filter_map(|field| {
if has_skip_attr(&field.attrs) {
return None;
}
let ident = field.ident.as_ref().unwrap();
Some(quote! { graphene_hash::CacheHash::cache_hash(&#self_expr.#ident, state); })
});
quote! { #(#stmts)* }
}
}
}
fn has_skip_attr(attrs: &[syn::Attribute]) -> bool {
attrs.iter().any(|attr| {
if !attr.path().is_ident("cache_hash") {
return false;
}
attr.parse_args::<syn::Ident>().map(|id| id == "skip").unwrap_or(false)
})
}
@@ -0,0 +1,237 @@
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "derive")]
pub use graphene_hash_derive::CacheHash;
pub trait CacheHash {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H);
}
/// Wrapper that implements `std::hash::Hash` by delegating to `CacheHash`.
///
/// Use this to store `CacheHash` types in `HashMap`/`HashSet` keys,
/// making it explicit that float fields are hashed via bit patterns.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CacheHashWrapper<T>(pub T);
impl<T: CacheHash> core::hash::Hash for CacheHashWrapper<T> {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.0.cache_hash(state);
}
}
impl<T: CacheHash> CacheHash for core::ops::RangeInclusive<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.start().cache_hash(state);
self.end().cache_hash(state);
}
}
impl<T> core::ops::Deref for CacheHashWrapper<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
// Bulk impl for types that already implement std::hash::Hash — delegates directly.
#[macro_export]
macro_rules! impl_via_hash {
($($t:ty),* $(,)?) => {
$(
impl $crate::CacheHash for $t {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
core::hash::Hash::hash(self, state);
}
}
)*
};
}
impl_via_hash! {
bool, char,
u8, u16, u32, u64, u128, usize,
i8, i16, i32, i64, i128, isize,
// glam integer vector types have Hash
glam::UVec2, glam::UVec3, glam::UVec4,
glam::IVec2, glam::IVec3, glam::IVec4,
glam::I64Vec2, glam::I64Vec3, glam::I64Vec4,
glam::U64Vec2, glam::U64Vec3, glam::U64Vec4,
glam::BVec2, glam::BVec3, glam::BVec4,
}
#[cfg(feature = "std")]
impl_via_hash! {
String,
}
impl<'a> CacheHash for std::borrow::Cow<'a, str> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
core::hash::Hash::hash(self, state);
}
}
impl CacheHash for str {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
core::hash::Hash::hash(self, state);
}
}
impl CacheHash for () {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, _state: &mut H) {}
}
// f32 and f64: hash via bit pattern so NaN is handled deterministically.
impl CacheHash for f32 {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
core::hash::Hash::hash(&self.to_bits(), state);
}
}
impl CacheHash for f64 {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
core::hash::Hash::hash(&self.to_bits(), state);
}
}
// glam float vector/matrix types: hash each component via to_bits().
macro_rules! impl_glam_array {
($($t:ty),* $(,)?) => {
$(
impl CacheHash for $t {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
for v in self.to_array() {
CacheHash::cache_hash(&v, state);
}
}
}
)*
};
}
macro_rules! impl_glam_cols {
($($t:ty),* $(,)?) => {
$(
impl CacheHash for $t {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
for v in self.to_cols_array() {
CacheHash::cache_hash(&v, state);
}
}
}
)*
};
}
impl_glam_array! {
glam::Vec2, glam::Vec3, glam::Vec3A, glam::Vec4,
glam::DVec2, glam::DVec3, glam::DVec4,
}
impl_glam_cols! {
glam::Mat2, glam::Mat3, glam::Mat3A, glam::Mat4,
glam::DMat2, glam::DMat3, glam::DMat4,
glam::Affine2, glam::Affine3A,
glam::DAffine2, glam::DAffine3,
}
// Quat / DQuat — to_array gives [x, y, z, w] as floats
impl_glam_array! {
glam::Quat, glam::DQuat,
}
// Generic container impls.
impl<T: CacheHash> CacheHash for Option<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
match self {
None => core::hash::Hash::hash(&0u8, state),
Some(v) => {
core::hash::Hash::hash(&1u8, state);
v.cache_hash(state);
}
}
}
}
impl<T: CacheHash> CacheHash for [T] {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
core::hash::Hash::hash(&self.len(), state);
for item in self {
item.cache_hash(state);
}
}
}
impl<T: CacheHash, const N: usize> CacheHash for [T; N] {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
for item in self {
item.cache_hash(state);
}
}
}
#[cfg(feature = "std")]
impl<T: CacheHash> CacheHash for Vec<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.as_slice().cache_hash(state);
}
}
#[cfg(feature = "std")]
impl<T: CacheHash + ?Sized> CacheHash for Box<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
(**self).cache_hash(state);
}
}
#[cfg(feature = "std")]
impl<T: CacheHash + ?Sized> CacheHash for std::sync::Arc<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
(**self).cache_hash(state);
}
}
impl<T: CacheHash + ?Sized> CacheHash for &T {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
(**self).cache_hash(state);
}
}
// Tuple impls.
macro_rules! impl_tuple {
($($T:ident),+) => {
impl<$($T: CacheHash),+> CacheHash for ($($T,)+) {
#[inline]
#[allow(non_snake_case)]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
let ($($T,)+) = self;
$($T.cache_hash(state);)+
}
}
};
}
impl_tuple!(A, B);
impl_tuple!(A, B, C);
impl_tuple!(A, B, C, D);
impl_tuple!(A, B, C, D, E);
impl_tuple!(A, B, C, D, E, F);