Skip to content
Merged
Show file tree
Hide file tree
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
12 changes: 12 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,12 @@ impl Drop for Session {
/// type Input = &'static str;
/// shimforge::mock!(session, source, fn(Input) -> usize);
/// ```
/// A function that only accepts `'static` borrows needs an `unsafe fn` signature:
/// ```compile_fail
/// let mut session = shimforge::Session::new_global();
/// fn source(value: &'static str) -> usize { value.len() }
/// shimforge::mock!(session, source, fn(&'static str) -> usize);
/// ```
/// A static result cannot become a shorter borrow:
/// ```compile_fail
/// let mut session = shimforge::Session::new_global();
Expand Down Expand Up @@ -559,6 +565,12 @@ fn finish(result: Result<(), Error>, fatal: fn() -> !) {
/// fn source(value: &mut usize) { *value += 1; }
/// shimforge::replace!(session, source => |_| (), fn(&'static mut usize));
/// ```
/// A function that only accepts `'static` borrows needs an `unsafe fn` signature:
/// ```compile_fail
/// let mut session = shimforge::Session::new_global();
/// fn source(value: &'static str) -> usize { value.len() }
/// shimforge::replace!(session, source => |value| value.len(), fn(&'static str) -> usize);
/// ```
/// A static result cannot become a shorter borrow:
/// ```compile_fail
/// let mut session = shimforge::Session::new_global();
Expand Down
24 changes: 24 additions & 0 deletions tests/replacement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,30 @@ fn replacement_preserves_the_borrowed_argument_lifetime() {
assert_eq!(borrowed(owned.as_str()), "b");
}

fn static_label(value: &'static str) -> usize {
value.len()
}

static REMEMBERED_LABEL: Mutex<Option<&'static str>> = Mutex::new(None);

fn remember_label(value: &'static str) -> usize {
*REMEMBERED_LABEL.lock().unwrap() = Some(value);
7
}

#[test]
fn static_only_inputs_are_replaced_through_an_unsafe_signature() {
let _serial = serial_test();
let mut session = Session::new_global();
// A safe signature is rejected for a function that only accepts 'static borrows,
// so it is declared unsafe, and the replacement may keep its argument.
replace!(session, static_label => remember_label, unsafe fn(&'static str) -> usize);
assert_eq!(static_label("kept"), 7);
assert_eq!(*REMEMBERED_LABEL.lock().unwrap(), Some("kept"));
session.restore();
assert_eq!(static_label("kept"), 4);
}

struct Counter {
value: i64,
}
Expand Down
Loading