From 313dc174806e719568fea637d438cb3671f89b1a Mon Sep 17 00:00:00 2001 From: Ruediger Klaehn Date: Wed, 24 Jul 2024 18:38:32 +0300 Subject: [PATCH] Add more tests for the somewhat weird get_as_ptr hack. Again, this is just a workaround until the same_channel thing gets merged. --- iroh-blobs/src/util/progress.rs | 41 +++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/iroh-blobs/src/util/progress.rs b/iroh-blobs/src/util/progress.rs index 9a824c9155..a44cde0064 100644 --- a/iroh-blobs/src/util/progress.rs +++ b/iroh-blobs/src/util/progress.rs @@ -557,6 +557,8 @@ impl AsyncChannelProgressSender { } } +/// Given a value that is aligned and sized like a pointer, return the value of +/// the pointer as a usize. fn get_as_ptr(value: &T) -> Option { use std::mem; if mem::size_of::() == std::mem::size_of::() @@ -570,6 +572,9 @@ fn get_as_ptr(value: &T) -> Option { } fn same_channel(a: &async_channel::Sender, b: &async_channel::Sender) -> bool { + // This relies on async_channel::Sender being just a newtype wrapper around + // an Arc>, so if two senders point to the same channel, the + // pointers will be the same. get_as_ptr(a).unwrap() == get_as_ptr(b).unwrap() } @@ -715,3 +720,39 @@ impl io::Result<()> + 'stati self.0.set_len(size).await } } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + + #[test] + fn get_as_ptr_works() { + struct Wrapper(Arc); + let x = Wrapper(Arc::new(1u64)); + assert_eq!( + get_as_ptr(&x).unwrap(), + Arc::as_ptr(&x.0) as usize - 2 * std::mem::size_of::() + ); + } + + #[test] + fn get_as_ptr_wrong_use() { + struct Wrapper(#[allow(dead_code)] u8); + let x = Wrapper(1); + assert!(get_as_ptr(&x).is_none()); + } + + #[test] + fn test_sender_is_ptr() { + assert_eq!( + std::mem::size_of::(), + std::mem::size_of::>() + ); + assert_eq!( + std::mem::align_of::(), + std::mem::align_of::>() + ); + } +}