Created
May 24, 2019 18:36
-
-
Save micromaomao/cf47f5353fbfaa13ba674da41e770a05 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::{io, mem}; | |
use std::io::Write; | |
struct LockHolder { | |
stdout_ptr: *mut io::Stdout, | |
lock_ptr: *mut io::StdoutLock<'static>, | |
} | |
impl LockHolder { | |
fn new() -> Self { | |
unsafe { | |
let stdout = Box::into_raw(Box::new(io::stdout())); | |
let lock = Box::into_raw(Box::new((*stdout).lock())); | |
return Self { stdout_ptr: stdout, lock_ptr: lock }; | |
} | |
} | |
fn print(&mut self, s: &str) -> io::Result<()> { | |
unsafe { | |
(*self.lock_ptr).write(s.as_bytes())?; | |
(*self.lock_ptr).flush()?; | |
return Ok(()); | |
} | |
} | |
} | |
impl Drop for LockHolder { | |
fn drop(&mut self) { | |
unsafe { | |
mem::drop(Box::from_raw(self.lock_ptr)); | |
mem::drop(Box::from_raw(self.stdout_ptr)); | |
} | |
} | |
} | |
fn main() { | |
let mut lh = LockHolder::new(); | |
lh.print("Hello world!\n").unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment