Skip to content

Instantly share code, notes, and snippets.

@barafael
Created August 16, 2022 22:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barafael/eced6665c58b02fcc9b3b6d4cf26707d to your computer and use it in GitHub Desktop.
Save barafael/eced6665c58b02fcc9b3b6d4cf26707d to your computer and use it in GitHub Desktop.
trait PushUnique {
type Item;
fn push_unique(&mut self, item: Self::Item) -> Result<(), Self::Item>;
}
impl<T> PushUnique for Vec<T>
where
T: PartialEq,
{
type Item = T;
fn push_unique(&mut self, item: Self::Item) -> Result<(), Self::Item> {
if self.contains(&item) {
Err(item)
} else {
self.push(item);
Ok(())
}
}
}
#[cfg(test)]
mod test {
use super::PushUnique;
#[test]
fn can_push_single() {
let mut v = Vec::new();
v.push_unique(0).unwrap();
}
#[test]
fn cant_push_multiple() {
let v = Vec::new();
let mut v: Vec<_> = v.into();
assert!(v.push_unique(0).is_ok());
assert!(v.push_unique(0).is_err());
}
}
use std::slice;
pub fn scrutinize<T>(_x: T) {
let p = &_x;
let s = unsafe {
let p = p as *const T as *mut u8;
slice::from_raw_parts(p, std::mem::size_of::<T>())
};
dbg!(s);
}
#[cfg(test)]
mod test {
use crate::scrutinize::scrutinize;
use std::mem::MaybeUninit;
#[test]
fn zeroize() {
let a = &() as *const ();
let b = &() as *const ();
println!("{:?}", a.cmp(&b));
}
#[test]
fn arghhhh() {
let bytes = MaybeUninit::<bool>::uninit();
dbg!(&bytes);
scrutinize(bytes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment