From 7858cd68cff790f56af78b667acff5d2e6522da1 Mon Sep 17 00:00:00 2001 From: pantonshire Date: Sun, 5 Nov 2023 10:49:58 +0000 Subject: [PATCH] reference conversions for FmtWriteSink and IoWriteSink --- src/sink.rs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/sink.rs b/src/sink.rs index 239b55a..9c14906 100644 --- a/src/sink.rs +++ b/src/sink.rs @@ -25,8 +25,27 @@ macro_rules! sink_fmt { pub use sink_fmt; +#[repr(transparent)] pub struct FmtWriteSink(pub W); +impl FmtWriteSink { + #[inline] + #[must_use] + pub fn from_ref(w: &W) -> &Self { + // SAFETY: + // `FmtWriteSink` uses `repr(transparent)`, so it has the same memory layout as `W`. + unsafe { &*(w as *const W as *const Self) } + } + + #[inline] + #[must_use] + pub fn from_mut(w: &mut W) -> &mut Self { + // SAFETY: + // `FmtWriteSink` uses `repr(transparent)`, so it has the same memory layout as `W`. + unsafe { &mut *(w as *mut W as *mut Self) } + } +} + impl StrSink for FmtWriteSink { type Error = fmt::Error; @@ -149,6 +168,24 @@ mod io_sink { #[repr(transparent)] pub struct IoWriteSink(pub W); + impl IoWriteSink { + #[inline] + #[must_use] + pub fn from_ref(w: &W) -> &Self { + // SAFETY: + // `IoWriteSink` uses `repr(transparent)`, so it has the same memory layout as `W`. + unsafe { &*(w as *const W as *const Self) } + } + + #[inline] + #[must_use] + pub fn from_mut(w: &mut W) -> &mut Self { + // SAFETY: + // `IoWriteSink` uses `repr(transparent)`, so it has the same memory layout as `W`. + unsafe { &mut *(w as *mut W as *mut Self) } + } + } + impl StrSink for IoWriteSink { type Error = io::Error;