From 4b148529a17367d2a0d85016d8326db93058b0fc Mon Sep 17 00:00:00 2001 From: Eryn Wells Date: Sun, 8 Jun 2025 17:34:42 -0700 Subject: [PATCH] [bitboard] Fix the warning about shared references to mutable static data I've lived with this warning for a long time because I didn't really understand it. ``` warning: `chessfriend_core` (lib) generated 1 warning (run `cargo fix --lib -p chessfriend_core` to apply 1 suggestion) warning: creating a shared reference to mutable static is discouraged --> bitboard/src/library.rs:66:9 ``` I was able to fix this by creating a new type with a single OnceLock attribute. The OnceLock acts as a cell, making it mutable, even if self is not. So, you can declare the MoveLibraryWrapper non-mutable static, but still initialize the library inside the Cell. --- bitboard/src/library.rs | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/bitboard/src/library.rs b/bitboard/src/library.rs index c878f8f..6a60392 100644 --- a/bitboard/src/library.rs +++ b/bitboard/src/library.rs @@ -60,16 +60,8 @@ pub(crate) const LIGHT_SQUARES: BitBoard = pub(crate) const DARK_SQUARES: BitBoard = BitBoard(!LIGHT_SQUARES.0); pub(super) fn library() -> &'static MoveLibrary { - static mut MOVE_LIBRARY: OnceLock = OnceLock::new(); - - unsafe { - MOVE_LIBRARY.get_or_init(|| { - let mut library = MoveLibrary::new(); - library.init(); - - library - }) - } + static MOVE_LIBRARY: MoveLibraryWrapper = MoveLibraryWrapper::new(); + MOVE_LIBRARY.library() } macro_rules! library_getter { @@ -80,6 +72,26 @@ macro_rules! library_getter { }; } +struct MoveLibraryWrapper { + library: OnceLock, +} + +impl MoveLibraryWrapper { + const fn new() -> Self { + Self { + library: OnceLock::::new(), + } + } + + fn library(&self) -> &MoveLibrary { + self.library.get_or_init(|| { + let mut library = MoveLibrary::new(); + library.init(); + library + }) + } +} + #[derive(Debug)] pub(super) struct MoveLibrary { // Rays