From 27241c6921be4fdfd82ea5011c43d5b97093ecfa Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 7 Aug 2025 15:25:44 +1000 Subject: [PATCH] Mark `RECURSIVE_COUNT_*` as `const`. From the `thread_local` docs: > This macro supports a special `const {}` syntax that can be used when > the initialization expression can be evaluated as a constant. This can > enable a more efficient thread local implementation that can avoid > lazy initialization. For types that do not need to be dropped, this > can enable an even more efficient implementation that does not need to > track any additional state. The `RECURSIVE_COUNT_*` values currently don't use this, but they can. This changes the generated code from this: ``` #[allow(non_upper_case_globals)] const RECURSIVE_COUNT_Example: ::std::thread::LocalKey<::core::cell::Cell> = { #[inline] fn __init() -> ::core::cell::Cell { ::core::cell::Cell::new(0) } unsafe { ::std::thread::LocalKey::new(const { if ::std::mem::needs_drop::<::core::cell::Cell>() { |init| { #[thread_local] static VAL: ::std::thread::local_impl::LazyStorage< ::core::cell::Cell, (), > = ::std::thread::local_impl::LazyStorage::new(); VAL.get_or_init(init, __init) } } else { |init| { #[thread_local] static VAL: ::std::thread::local_impl::LazyStorage< ::core::cell::Cell, !, > = ::std::thread::local_impl::LazyStorage::new(); VAL.get_or_init(init, __init) } } }) } }; ``` to this: ``` #[allow(non_upper_case_globals)] const RECURSIVE_COUNT_Example: ::std::thread::LocalKey<::core::cell::Cell> = { const __INIT: ::core::cell::Cell = { ::core::cell::Cell::new(0) }; unsafe { ::std::thread::LocalKey::new(const { if ::std::mem::needs_drop::<::core::cell::Cell>() { |_| { #[thread_local] static VAL: ::std::thread::local_impl::EagerStorage< ::core::cell::Cell, > = ::std::thread::local_impl::EagerStorage::new(__INIT); VAL.get() } } else { |_| { #[thread_local] static VAL: ::core::cell::Cell = __INIT; &VAL } } }) } }; ``` Note in both cases the `else` block is the relevant one because `Cell` doesn't need drop. --- derive/src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/derive/src/lib.rs b/derive/src/lib.rs index 81c0274..86701ca 100644 --- a/derive/src/lib.rs +++ b/derive/src/lib.rs @@ -60,7 +60,9 @@ fn expand_derive_arbitrary(input: syn::DeriveInput) -> Result { const _: () = { ::std::thread_local! { #[allow(non_upper_case_globals)] - static #recursive_count: ::core::cell::Cell = ::core::cell::Cell::new(0); + static #recursive_count: ::core::cell::Cell = const { + ::core::cell::Cell::new(0) + }; } #[automatically_derived]