Guest User

Untitled

a guest
May 22nd, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. extern crate libc;
  2.  
  3. use std::marker::PhantomData;
  4. use libc::{malloc, free, c_void};
  5.  
  6. trait Trace {}
  7.  
  8. struct MyTrace<'b> {
  9. #[allow(dead_code)]
  10. buf: *mut c_void,
  11. _phantom: PhantomData<&'b c_void>,
  12. }
  13.  
  14. impl<'b> MyTrace<'b> {
  15. fn new() -> Self {
  16. Self{buf: unsafe{malloc(128)}, _phantom: PhantomData}
  17. }
  18. }
  19.  
  20. impl<'b> Trace for MyTrace<'b> {}
  21.  
  22. impl<'b> Drop for MyTrace<'b> {
  23. fn drop(&mut self) {
  24. unsafe{free(self.buf)};
  25. }
  26. }
  27.  
  28. trait Tracer {
  29. fn start(&mut self);
  30. fn stop(&mut self) -> Box<Trace>;
  31. }
  32.  
  33. struct MyTracer<'b> {
  34. trace: Option<MyTrace<'b>>,
  35. }
  36.  
  37. impl<'b> MyTracer<'b> {
  38. fn new() -> Self {
  39. Self{trace: None}
  40. }
  41. }
  42.  
  43. impl<'b> Tracer for MyTracer<'b> {
  44. fn start(&mut self) {
  45. self.trace = Some(MyTrace::new());
  46. // Pretend the buffer is mutated in C here...
  47. }
  48.  
  49. fn stop(&mut self) -> Box<Trace> {
  50. Box::new(self.trace.take().unwrap())
  51. }
  52. }
  53.  
  54. fn main() {
  55. let mut tracer = MyTracer::new();
  56. tracer.start();
  57. let _trace = tracer.stop();
  58. println!("Hello, world!");
  59. }
Add Comment
Please, Sign In to add comment