Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. use std::{
  2. alloc::{alloc, dealloc, Layout},
  3. ops::Deref,
  4. };
  5.  
  6. fn use_1(it: &Heap) {
  7. // some complicated logic
  8. drop(it); // we're done with it
  9. }
  10.  
  11. fn use_2(it: &Heap) {
  12. // some complicated logic
  13. drop(it); // we're done with it
  14. }
  15.  
  16. fn main() {
  17. let it = Heap::new(0);
  18.  
  19. // some complicated logic
  20.  
  21. use_1(&it);
  22.  
  23. // some complicated logic
  24.  
  25. use_2(&it);
  26.  
  27. // some complicated logic
  28.  
  29. drop(it); // we're done with it
  30. }
  31.  
  32. struct Heap(*mut u8);
  33.  
  34. impl Heap {
  35. fn new(it: u64) -> Self {unsafe{
  36. let ptr = alloc(Layout::new::<u64>());
  37. *(ptr as *mut _) = it;
  38. Heap(ptr)
  39. }}
  40. }
  41.  
  42. impl Deref for Heap {
  43. type Target = u64;
  44. fn deref(&self) -> &u64 {unsafe{
  45. &*(self.0 as *mut u64)
  46. }}
  47. }
  48.  
  49. impl Drop for Heap {
  50. fn drop(&mut self) {unsafe{
  51. dealloc(self.0, Layout::new::<u64>());
  52. }}
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement