目前未stable,使用前需要#![feature(asm)]
,调用asm
宏的格式为:
asm!(assembly template
: output operands
: input operands
: clobbers
: options
);
如https://github.com/dalek-cryptography/subtle/blob/master/src/lib.rs
中的volatile
是一个类型修饰符(type specifier),作为指令关键字,确保本条指令不会因编译器的优化而省略,且要求每次直接读值。
/// This function is a best-effort attempt to prevent the compiler
/// from knowing anything about the value of the returned `u8`, other
/// than its type.
///
/// Uses inline asm when available, otherwise it's a no-op.
#[cfg(all(feature = "nightly", not(any(target_arch = "asmjs", target_arch = "wasm32"))))]
fn black_box(input: u8) -> u8 {
debug_assert!((input == 0u8) | (input == 1u8));
// Pretend to access a register containing the input. We "volatile" here
// because some optimisers treat assembly templates without output operands
// as "volatile" while others do not.
unsafe { asm!("" :: "r"(&input) :: "volatile") }
input
}
参考资料: [1] https://doc.rust-lang.org/1.12.0/book/inline-assembly.html