use std::{cell::Cell, fmt::{Debug, Display, Formatter}, ops::Deref}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; /// [`SyncCell`], but [`Sync`]. /// /// This is just an `Cell`, except it implements `Sync` /// if `T` implements `Sync`. pub struct SyncCell(Cell); unsafe impl Sync for SyncCell {} impl SyncCell { #[inline] pub const fn new(value: T) -> Self { Self(Cell::new(value)) } } impl Default for SyncCell { fn default() -> Self { Self::new(T::default()) } } impl Deref for SyncCell { type Target = Cell; #[inline] fn deref(&self) -> &Self::Target { &self.0 } } impl Clone for SyncCell { #[inline] fn clone(&self) -> Self { Self::new(self.get()) } } impl Debug for SyncCell { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { Debug::fmt(&self.get(), f) } } impl Display for SyncCell { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { Display::fmt(&self.get(), f) } } impl Serialize for SyncCell where T: Copy + Serialize, { fn serialize(&self, serializer: S) -> Result { self.0.serialize(serializer) } } impl<'de, T> Deserialize<'de> for SyncCell where T: Copy + Deserialize<'de>, { fn deserialize>(deserializer: D) -> Result { Ok(Self::new(T::deserialize(deserializer)?)) } }