Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tests for ClosureOnce. #41

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 32 additions & 6 deletions libffi-rs/src/high/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,7 @@ macro_rules! define_closure_mod {
pub mod $module {
use std::any::Any;
use std::marker::PhantomData;
use std::{mem, process, ptr};
use std::io::{self, Write};
use std::{mem, ptr};

use super::*;
use crate::{low, middle};
Expand Down Expand Up @@ -387,10 +386,19 @@ macro_rules! define_closure_mod {
}
});
} else {
// There is probably a better way to abort here.
let _ =
io::stderr().write(b"FnOnce closure already used");
process::exit(2);
eprintln!(
"FnOnce closure already used (userdata {:?})",
userdata as *const Option<Callback>);

// When testing we need to panic so that we can
// catch it with #[should_panic].
#[cfg(test)]
panic!("FnOnce closure already used");

// Otherwise, we exit to avoid panicking across
// an FFI boundary.
#[cfg(not(test))]
std::process::exit(2);
}
}
}
Expand Down Expand Up @@ -545,4 +553,22 @@ mod test {
assert_eq!(6, counter.call(1));
assert_eq!(8, counter.call(2));
}

#[test]
fn once_ok() {
let closure = ClosureOnce1::new(|x| x + 1);
let inc = closure.code_ptr();

assert_eq!(4, inc.call(3));
}

#[test]
#[should_panic]
fn once_error() {
let closure = ClosureOnce1::new(|x| x + 1);
let inc = closure.code_ptr();

assert_eq!(4, inc.call(3));
assert_eq!(5, inc.call(4));
}
}