Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.54 KB | None | 0 0
  1. fn i_from_slice<T>(slice: &[u8]) -> Option<T>
  2. {
  3. if slice.len() == std::mem::size_of::<T>() {
  4. Some(unsafe { std::mem::transmute_copy(&slice) })
  5. } else {
  6. None
  7. }
  8. }
  9.  
  10. fn i_from_slice_v2<T>(slice: &[u8]) -> Option<T>
  11. {
  12. if slice.len() == std::mem::size_of::<T>() {
  13. Some(unsafe { std::mem::transmute_copy(&slice[0]) })
  14. } else {
  15. None
  16. }
  17. }
  18.  
  19. fn main() {
  20. let x = [0xFF,0xFF]; // should transmute to be 65535
  21. println!("{:?}", i_from_slice::<u16>(&x));
  22. println!("{:?}", i_from_slice_v2::<u16>(&x));
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement