diff --git a/src/bytes.rs b/src/bytes.rs new file mode 100644 index 0000000..300175f --- /dev/null +++ b/src/bytes.rs @@ -0,0 +1,29 @@ +use std::ffi::c_void; +use std::ptr; + +#[cfg(nightly)] +#[inline(never)] +pub fn explicit_prune(buffer: &mut[u8]) { + + unsafe { + ptr::write_bytes(buffer.as_mut_ptr() as *mut c_void, 0, buffer.len()); + if cfg!(target_arch = "x86_64") || cfg !(target_arch = "x86") { + asm!("clflush [{}]", in(reg)buffer.as_mut_ptr()); + } else { + asm!("") + } + } +} + +#[cfg(not(nightly))] +#[inline] +pub fn explicit_prune(buffer: &mut[u8]) { + + extern "C" { + fn explicit_bzero(_: *mut c_void, _:usize); + } + + unsafe { + explicit_bzero(buffer.as_mut_ptr() as *mut c_void, buffer.len()); + } +} diff --git a/src/ext.rs b/src/ext.rs index a8917cd..4bbaf41 100644 --- a/src/ext.rs +++ b/src/ext.rs @@ -57,7 +57,7 @@ pub trait HexStringSliceIterExt } impl HexStringSliceIterExt for S - where S: AsRef<[u8]> +where S: AsRef<[u8]> { fn hex(&self) -> HexStringSliceIter<'_> { diff --git a/src/lib.rs b/src/lib.rs index 21cae37..4f38050 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,6 +9,7 @@ pub mod key; mod cha; mod stream; +mod bytes; pub use stream::Sink; pub use key::{ diff --git a/src/stream.rs b/src/stream.rs index 587888a..1b893c8 100644 --- a/src/stream.rs +++ b/src/stream.rs @@ -118,36 +118,12 @@ where W: Write /// Clear the internal buffer while keeping it allocated for further use. /// /// This does not affect operations at all, all it does is 0 out the left-over temporary buffer from the last operation(s). - #[cfg_attr(all(nightly, feature="explicit_clear"), inline(never))] // We don't want this asm! being inlined and preventing other optimisations on caller functions. + #[inline] pub fn prune(&mut self) { #[cfg(feature="explicit_clear")] { - use std::ffi::c_void; - - #[cfg(nightly)] - #[inline(never)] unsafe fn explicit_bzero(p: *mut c_void, s: usize) - { - std::ptr::write_bytes(p, 0, s); - - asm!(""); - } - #[cfg(not(nightly))] - extern "C" { - fn explicit_bzero(_: *mut c_void, _:usize); - } - - unsafe { - explicit_bzero(self.buffer.as_mut_ptr() as *mut c_void, self.buffer.len()); - - #[cfg(nightly)] - if cfg!(target_arch = "x86_64") || cfg!(target_arch = "x86"){ - asm!( - "clflush [{}]", - in(reg) self.buffer.as_mut_ptr() - ); - } - } + bytes::explicit_prune(&mut self.buffer[..]); return; } #[cfg(not(feature="explicit_clear"))]