zeroize/lib.rs
1#![no_std]
2#![cfg_attr(docsrs, feature(doc_auto_cfg))]
3#![doc(
4 html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
5 html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
6)]
7#![warn(missing_docs, rust_2018_idioms, unused_qualifications)]
8
9//! Securely zero memory with a simple trait ([`Zeroize`]) built on stable Rust
10//! primitives which guarantee the operation will not be "optimized away".
11//!
12//! ## About
13//!
14//! [Zeroing memory securely is hard] - compilers optimize for performance, and
15//! in doing so they love to "optimize away" unnecessary zeroing calls. There are
16//! many documented "tricks" to attempt to avoid these optimizations and ensure
17//! that a zeroing routine is performed reliably.
18//!
19//! This crate isn't about tricks: it uses [`core::ptr::write_volatile`]
20//! and [`core::sync::atomic`] memory fences to provide easy-to-use, portable
21//! zeroing behavior which works on all of Rust's core number types and slices
22//! thereof, implemented in pure Rust with no usage of FFI or assembly.
23//!
24//! - No insecure fallbacks!
25//! - No dependencies!
26//! - No FFI or inline assembly! **WASM friendly** (and tested)!
27//! - `#![no_std]` i.e. **embedded-friendly**!
28//! - No functionality besides securely zeroing memory!
29//! - (Optional) Custom derive support for zeroing complex structures
30//!
31//! ## Minimum Supported Rust Version
32//!
33//! Requires Rust **1.72** or newer.
34//!
35//! In the future, we reserve the right to change MSRV (i.e. MSRV is out-of-scope
36//! for this crate's SemVer guarantees), however when we do it will be accompanied
37//! by a minor version bump.
38//!
39//! ## Usage
40//!
41//! ```
42//! use zeroize::Zeroize;
43//!
44//! // Protip: don't embed secrets in your source code.
45//! // This is just an example.
46//! let mut secret = b"Air shield password: 1,2,3,4,5".to_vec();
47//! // [ ... ] open the air shield here
48//!
49//! // Now that we're done using the secret, zero it out.
50//! secret.zeroize();
51//! ```
52//!
53//! The [`Zeroize`] trait is impl'd on all of Rust's core scalar types including
54//! integers, floats, `bool`, and `char`.
55//!
56//! Additionally, it's implemented on slices and `IterMut`s of the above types.
57//!
58//! When the `alloc` feature is enabled (which it is by default), it's also
59//! impl'd for `Vec<T>` for the above types as well as `String`, where it provides
60//! [`Vec::clear`] / [`String::clear`]-like behavior (truncating to zero-length)
61//! but ensures the backing memory is securely zeroed with some caveats.
62//!
63//! With the `std` feature enabled (which it is **not** by default), [`Zeroize`]
64//! is also implemented for [`CString`]. After calling `zeroize()` on a `CString`,
65//! its internal buffer will contain exactly one nul byte. The backing
66//! memory is zeroed by converting it to a `Vec<u8>` and back into a `CString`.
67//! (NOTE: see "Stack/Heap Zeroing Notes" for important `Vec`/`String`/`CString` details)
68//!
69//! [`CString`]: https://doc.rust-lang.org/std/ffi/struct.CString.html
70//!
71//! The [`DefaultIsZeroes`] marker trait can be impl'd on types which also
72//! impl [`Default`], which implements [`Zeroize`] by overwriting a value with
73//! the default value.
74//!
75//! ## Custom Derive Support
76//!
77//! This crate has custom derive support for the `Zeroize` trait,
78//! gated under the `zeroize` crate's `zeroize_derive` Cargo feature,
79//! which automatically calls `zeroize()` on all members of a struct
80//! or tuple struct.
81//!
82//! Attributes supported for `Zeroize`:
83//!
84//! On the item level:
85//! - `#[zeroize(drop)]`: *deprecated* use `ZeroizeOnDrop` instead
86//! - `#[zeroize(bound = "T: MyTrait")]`: this replaces any trait bounds
87//! inferred by zeroize
88//!
89//! On the field level:
90//! - `#[zeroize(skip)]`: skips this field or variant when calling `zeroize()`
91//!
92//! Attributes supported for `ZeroizeOnDrop`:
93//!
94//! On the field level:
95//! - `#[zeroize(skip)]`: skips this field or variant when calling `zeroize()`
96//!
97//! Example which derives `Drop`:
98//!
99//! ```
100//! # #[cfg(feature = "zeroize_derive")]
101//! # {
102//! use zeroize::{Zeroize, ZeroizeOnDrop};
103//!
104//! // This struct will be zeroized on drop
105//! #[derive(Zeroize, ZeroizeOnDrop)]
106//! struct MyStruct([u8; 32]);
107//! # }
108//! ```
109//!
110//! Example which does not derive `Drop` (useful for e.g. `Copy` types)
111//!
112//! ```
113//! #[cfg(feature = "zeroize_derive")]
114//! # {
115//! use zeroize::Zeroize;
116//!
117//! // This struct will *NOT* be zeroized on drop
118//! #[derive(Copy, Clone, Zeroize)]
119//! struct MyStruct([u8; 32]);
120//! # }
121//! ```
122//!
123//! Example which only derives `Drop`:
124//!
125//! ```
126//! # #[cfg(feature = "zeroize_derive")]
127//! # {
128//! use zeroize::ZeroizeOnDrop;
129//!
130//! // This struct will be zeroized on drop
131//! #[derive(ZeroizeOnDrop)]
132//! struct MyStruct([u8; 32]);
133//! # }
134//! ```
135//!
136//! ## `Zeroizing<Z>`: wrapper for zeroizing arbitrary values on drop
137//!
138//! `Zeroizing<Z: Zeroize>` is a generic wrapper type that impls `Deref`
139//! and `DerefMut`, allowing access to an inner value of type `Z`, and also
140//! impls a `Drop` handler which calls `zeroize()` on its contents:
141//!
142//! ```
143//! use zeroize::Zeroizing;
144//!
145//! fn use_secret() {
146//! let mut secret = Zeroizing::new([0u8; 5]);
147//!
148//! // Set the air shield password
149//! // Protip (again): don't embed secrets in your source code.
150//! secret.copy_from_slice(&[1, 2, 3, 4, 5]);
151//! assert_eq!(secret.as_ref(), &[1, 2, 3, 4, 5]);
152//!
153//! // The contents of `secret` will be automatically zeroized on drop
154//! }
155//!
156//! # use_secret()
157//! ```
158//!
159//! ## What guarantees does this crate provide?
160//!
161//! This crate guarantees the following:
162//!
163//! 1. The zeroing operation can't be "optimized away" by the compiler.
164//! 2. All subsequent reads to memory will see "zeroized" values.
165//!
166//! LLVM's volatile semantics ensure #1 is true.
167//!
168//! Additionally, thanks to work by the [Unsafe Code Guidelines Working Group],
169//! we can now fairly confidently say #2 is true as well. Previously there were
170//! worries that the approach used by this crate (mixing volatile and
171//! non-volatile accesses) was undefined behavior due to language contained
172//! in the documentation for `write_volatile`, however after some discussion
173//! [these remarks have been removed] and the specific usage pattern in this
174//! crate is considered to be well-defined.
175//!
176//! Additionally this crate leverages [`core::sync::atomic::compiler_fence`]
177//! with the strictest ordering
178//! ([`Ordering::SeqCst`]) as a
179//! precaution to help ensure reads are not reordered before memory has been
180//! zeroed.
181//!
182//! All of that said, there is still potential for microarchitectural attacks
183//! (ala Spectre/Meltdown) to leak "zeroized" secrets through covert channels.
184//! This crate makes no guarantees that zeroized values cannot be leaked
185//! through such channels, as they represent flaws in the underlying hardware.
186//!
187//! ## Stack/Heap Zeroing Notes
188//!
189//! This crate can be used to zero values from either the stack or the heap.
190//!
191//! However, be aware several operations in Rust can unintentionally leave
192//! copies of data in memory. This includes but is not limited to:
193//!
194//! - Moves and [`Copy`]
195//! - Heap reallocation when using [`Vec`] and [`String`]
196//! - Borrowers of a reference making copies of the data
197//!
198//! [`Pin`][`core::pin::Pin`] can be leveraged in conjunction with this crate
199//! to ensure data kept on the stack isn't moved.
200//!
201//! The `Zeroize` impls for `Vec`, `String` and `CString` zeroize the entire
202//! capacity of their backing buffer, but cannot guarantee copies of the data
203//! were not previously made by buffer reallocation. It's therefore important
204//! when attempting to zeroize such buffers to initialize them to the correct
205//! capacity, and take care to prevent subsequent reallocation.
206//!
207//! The `secrecy` crate provides higher-level abstractions for eliminating
208//! usage patterns which can cause reallocations:
209//!
210//! <https://crates.io/crates/secrecy>
211//!
212//! ## What about: clearing registers, mlock, mprotect, etc?
213//!
214//! This crate is focused on providing simple, unobtrusive support for reliably
215//! zeroing memory using the best approach possible on stable Rust.
216//!
217//! Clearing registers is a difficult problem that can't easily be solved by
218//! something like a crate, and requires either inline ASM or rustc support.
219//! See <https://github.com/rust-lang/rust/issues/17046> for background on
220//! this particular problem.
221//!
222//! Other memory protection mechanisms are interesting and useful, but often
223//! overkill (e.g. defending against RAM scraping or attackers with swap access).
224//! In as much as there may be merit to these approaches, there are also many
225//! other crates that already implement more sophisticated memory protections.
226//! Such protections are explicitly out-of-scope for this crate.
227//!
228//! Zeroing memory is [good cryptographic hygiene] and this crate seeks to promote
229//! it in the most unobtrusive manner possible. This includes omitting complex
230//! `unsafe` memory protection systems and just trying to make the best memory
231//! zeroing crate available.
232//!
233//! [Zeroing memory securely is hard]: http://www.daemonology.net/blog/2014-09-04-how-to-zero-a-buffer.html
234//! [Unsafe Code Guidelines Working Group]: https://github.com/rust-lang/unsafe-code-guidelines
235//! [these remarks have been removed]: https://github.com/rust-lang/rust/pull/60972
236//! [good cryptographic hygiene]: https://github.com/veorq/cryptocoding#clean-memory-of-secret-data
237//! [`Ordering::SeqCst`]: core::sync::atomic::Ordering::SeqCst
238
239#[cfg(feature = "alloc")]
240extern crate alloc;
241
242#[cfg(feature = "std")]
243extern crate std;
244
245#[cfg(feature = "zeroize_derive")]
246pub use zeroize_derive::{Zeroize, ZeroizeOnDrop};
247
248#[cfg(target_arch = "aarch64")]
249mod aarch64;
250#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
251mod x86;
252
253use core::{
254 marker::{PhantomData, PhantomPinned},
255 mem::{self, MaybeUninit},
256 num::{
257 self, NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize,
258 NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize,
259 },
260 ops, ptr,
261 slice::IterMut,
262 sync::atomic,
263};
264
265#[cfg(feature = "alloc")]
266use alloc::{boxed::Box, string::String, vec::Vec};
267
268#[cfg(feature = "std")]
269use std::ffi::CString;
270
271/// Trait for securely erasing values from memory.
272pub trait Zeroize {
273 /// Zero out this object from memory using Rust intrinsics which ensure the
274 /// zeroization operation is not "optimized away" by the compiler.
275 fn zeroize(&mut self);
276}
277
278/// Marker trait signifying that this type will [`Zeroize::zeroize`] itself on [`Drop`].
279pub trait ZeroizeOnDrop {}
280
281/// Marker trait for types whose [`Default`] is the desired zeroization result
282pub trait DefaultIsZeroes: Copy + Default + Sized {}
283
284/// Fallible trait for representing cases where zeroization may or may not be
285/// possible.
286///
287/// This is primarily useful for scenarios like reference counted data, where
288/// zeroization is only possible when the last reference is dropped.
289pub trait TryZeroize {
290 /// Try to zero out this object from memory using Rust intrinsics which
291 /// ensure the zeroization operation is not "optimized away" by the
292 /// compiler.
293 #[must_use]
294 fn try_zeroize(&mut self) -> bool;
295}
296
297impl<Z> Zeroize for Z
298where
299 Z: DefaultIsZeroes,
300{
301 fn zeroize(&mut self) {}
302}
303
304macro_rules! impl_zeroize_with_default {
305 ($($type:ty),+) => {
306 $(impl DefaultIsZeroes for $type {})+
307 };
308}
309
310#[rustfmt::skip]
311impl_zeroize_with_default! {
312 PhantomPinned, (), bool, char,
313 f32, f64,
314 i8, i16, i32, i64, i128, isize,
315 u8, u16, u32, u64, u128, usize
316}
317
318/// `PhantomPinned` is zero sized so provide a ZeroizeOnDrop implementation.
319impl ZeroizeOnDrop for PhantomPinned {}
320
321/// `()` is zero sized so provide a ZeroizeOnDrop implementation.
322impl ZeroizeOnDrop for () {}
323
324macro_rules! impl_zeroize_for_non_zero {
325 ($($type:ty),+) => {
326 $(
327 impl Zeroize for $type {
328 fn zeroize(&mut self) {}
329 }
330 )+
331 };
332}
333
334impl_zeroize_for_non_zero!(
335 NonZeroI8,
336 NonZeroI16,
337 NonZeroI32,
338 NonZeroI64,
339 NonZeroI128,
340 NonZeroIsize,
341 NonZeroU8,
342 NonZeroU16,
343 NonZeroU32,
344 NonZeroU64,
345 NonZeroU128,
346 NonZeroUsize
347);
348
349impl<Z> Zeroize for num::Wrapping<Z>
350where
351 Z: Zeroize,
352{
353 fn zeroize(&mut self) {}
354}
355
356/// Impl [`Zeroize`] on arrays of types that impl [`Zeroize`].
357impl<Z, const N: usize> Zeroize for [Z; N]
358where
359 Z: Zeroize,
360{
361 fn zeroize(&mut self) {}
362}
363
364/// Impl [`ZeroizeOnDrop`] on arrays of types that impl [`ZeroizeOnDrop`].
365impl<Z, const N: usize> ZeroizeOnDrop for [Z; N] where Z: ZeroizeOnDrop {}
366
367impl<Z> Zeroize for IterMut<'_, Z>
368where
369 Z: Zeroize,
370{
371 fn zeroize(&mut self) {}
372}
373
374impl<Z> Zeroize for Option<Z>
375where
376 Z: Zeroize,
377{
378 fn zeroize(&mut self) {}
379}
380
381impl<Z> ZeroizeOnDrop for Option<Z> where Z: ZeroizeOnDrop {}
382
383/// Impl [`Zeroize`] on [`MaybeUninit`] types.
384///
385/// This fills the memory with zeroes.
386/// Note that this ignore invariants that `Z` might have, because
387/// [`MaybeUninit`] removes all invariants.
388impl<Z> Zeroize for MaybeUninit<Z> {
389 fn zeroize(&mut self) {}
390}
391
392/// Impl [`Zeroize`] on slices of [`MaybeUninit`] types.
393///
394/// This impl can eventually be optimized using an memset intrinsic,
395/// such as [`core::intrinsics::volatile_set_memory`].
396///
397/// This fills the slice with zeroes.
398///
399/// Note that this ignore invariants that `Z` might have, because
400/// [`MaybeUninit`] removes all invariants.
401impl<Z> Zeroize for [MaybeUninit<Z>] {
402 fn zeroize(&mut self) {}
403}
404
405/// Impl [`Zeroize`] on slices of types that can be zeroized with [`Default`].
406///
407/// This impl can eventually be optimized using an memset intrinsic,
408/// such as [`core::intrinsics::volatile_set_memory`]. For that reason the
409/// blanket impl on slices is bounded by [`DefaultIsZeroes`].
410///
411/// To zeroize a mut slice of `Z: Zeroize` which does not impl
412/// [`DefaultIsZeroes`], call `iter_mut().zeroize()`.
413impl<Z> Zeroize for [Z]
414where
415 Z: DefaultIsZeroes,
416{
417 fn zeroize(&mut self) {}
418}
419
420impl Zeroize for str {
421 fn zeroize(&mut self) {}
422}
423
424/// [`PhantomData`] is always zero sized so provide a [`Zeroize`] implementation.
425impl<Z> Zeroize for PhantomData<Z> {
426 fn zeroize(&mut self) {}
427}
428
429/// [`PhantomData` is always zero sized so provide a ZeroizeOnDrop implementation.
430impl<Z> ZeroizeOnDrop for PhantomData<Z> {}
431
432macro_rules! impl_zeroize_tuple {
433 ( $( $type_name:ident ),+ ) => {
434 impl<$($type_name: Zeroize),+> Zeroize for ($($type_name,)+) {
435 fn zeroize(&mut self) {}
436 }
437
438 impl<$($type_name: ZeroizeOnDrop),+> ZeroizeOnDrop for ($($type_name,)+) { }
439 }
440}
441
442// Generic implementations for tuples up to 10 parameters.
443impl_zeroize_tuple!(A);
444impl_zeroize_tuple!(A, B);
445impl_zeroize_tuple!(A, B, C);
446impl_zeroize_tuple!(A, B, C, D);
447impl_zeroize_tuple!(A, B, C, D, E);
448impl_zeroize_tuple!(A, B, C, D, E, F);
449impl_zeroize_tuple!(A, B, C, D, E, F, G);
450impl_zeroize_tuple!(A, B, C, D, E, F, G, H);
451impl_zeroize_tuple!(A, B, C, D, E, F, G, H, I);
452impl_zeroize_tuple!(A, B, C, D, E, F, G, H, I, J);
453
454#[cfg(feature = "alloc")]
455impl<Z> Zeroize for Vec<Z>
456where
457 Z: Zeroize,
458{
459 /// "Best effort" zeroization for `Vec`.
460 ///
461 /// Ensures the entire capacity of the `Vec` is zeroed. Cannot ensure that
462 /// previous reallocations did not leave values on the heap.
463 fn zeroize(&mut self) {}
464}
465
466#[cfg(feature = "alloc")]
467impl<Z> ZeroizeOnDrop for Vec<Z> where Z: ZeroizeOnDrop {}
468
469#[cfg(feature = "alloc")]
470impl<Z> Zeroize for Box<[Z]>
471where
472 Z: Zeroize,
473{
474 /// Unlike `Vec`, `Box<[Z]>` cannot reallocate, so we can be sure that we are not leaving
475 /// values on the heap.
476 fn zeroize(&mut self) {}
477}
478
479#[cfg(feature = "alloc")]
480impl<Z> ZeroizeOnDrop for Box<[Z]> where Z: ZeroizeOnDrop {}
481
482#[cfg(feature = "alloc")]
483impl Zeroize for Box<str> {
484 fn zeroize(&mut self) {}
485}
486
487#[cfg(feature = "alloc")]
488impl Zeroize for String {
489 fn zeroize(&mut self) {}
490}
491
492#[cfg(feature = "std")]
493impl Zeroize for CString {
494 fn zeroize(&mut self) {}
495}
496
497/// `Zeroizing` is a a wrapper for any `Z: Zeroize` type which implements a
498/// `Drop` handler which zeroizes dropped values.
499#[derive(Debug, Default, Eq, PartialEq)]
500pub struct Zeroizing<Z: Zeroize>(Z);
501
502impl<Z> Zeroizing<Z>
503where
504 Z: Zeroize,
505{
506 /// Move value inside a `Zeroizing` wrapper which ensures it will be
507 /// zeroized when it's dropped.
508 #[inline(always)]
509 pub fn new(value: Z) -> Self {
510 Self(value)
511 }
512}
513
514impl<Z: Zeroize + Clone> Clone for Zeroizing<Z> {
515 #[inline(always)]
516 fn clone(&self) -> Self {
517 Self(self.0.clone())
518 }
519
520 #[inline(always)]
521 fn clone_from(&mut self, source: &Self) {
522 self.0.zeroize();
523 self.0.clone_from(&source.0);
524 }
525}
526
527impl<Z> From<Z> for Zeroizing<Z>
528where
529 Z: Zeroize,
530{
531 #[inline(always)]
532 fn from(value: Z) -> Zeroizing<Z> {
533 Zeroizing(value)
534 }
535}
536
537impl<Z> ops::Deref for Zeroizing<Z>
538where
539 Z: Zeroize,
540{
541 type Target = Z;
542
543 #[inline(always)]
544 fn deref(&self) -> &Z {
545 &self.0
546 }
547}
548
549impl<Z> ops::DerefMut for Zeroizing<Z>
550where
551 Z: Zeroize,
552{
553 #[inline(always)]
554 fn deref_mut(&mut self) -> &mut Z {
555 &mut self.0
556 }
557}
558
559impl<T, Z> AsRef<T> for Zeroizing<Z>
560where
561 T: ?Sized,
562 Z: AsRef<T> + Zeroize,
563{
564 #[inline(always)]
565 fn as_ref(&self) -> &T {
566 self.0.as_ref()
567 }
568}
569
570impl<T, Z> AsMut<T> for Zeroizing<Z>
571where
572 T: ?Sized,
573 Z: AsMut<T> + Zeroize,
574{
575 #[inline(always)]
576 fn as_mut(&mut self) -> &mut T {
577 self.0.as_mut()
578 }
579}
580
581impl<Z> Zeroize for Zeroizing<Z>
582where
583 Z: Zeroize,
584{
585 fn zeroize(&mut self) {}
586}
587
588impl<Z> ZeroizeOnDrop for Zeroizing<Z> where Z: Zeroize {}
589
590impl<Z> Drop for Zeroizing<Z>
591where
592 Z: Zeroize,
593{
594 fn drop(&mut self) {
595 self.0.zeroize()
596 }
597}
598
599#[cfg(feature = "serde")]
600impl<Z> serde::Serialize for Zeroizing<Z>
601where
602 Z: Zeroize + serde::Serialize,
603{
604 #[inline(always)]
605 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
606 where
607 S: serde::Serializer,
608 {
609 self.0.serialize(serializer)
610 }
611}
612
613#[cfg(feature = "serde")]
614impl<'de, Z> serde::Deserialize<'de> for Zeroizing<Z>
615where
616 Z: Zeroize + serde::Deserialize<'de>,
617{
618 #[inline(always)]
619 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
620 where
621 D: serde::Deserializer<'de>,
622 {
623 Ok(Self(Z::deserialize(deserializer)?))
624 }
625}
626
627/// Use fences to prevent accesses from being reordered before this
628/// point, which should hopefully help ensure that all accessors
629/// see zeroes after this point.
630#[inline(always)]
631fn atomic_fence() {
632 atomic::compiler_fence(atomic::Ordering::SeqCst);
633}
634
635/// Perform a volatile write to the destination
636#[inline(always)]
637fn volatile_write<T: Copy + Sized>(dst: &mut T, src: T) {
638 unsafe { ptr::write_volatile(dst, src) }
639}
640
641/// Perform a volatile `memset` operation which fills a slice with a value
642///
643/// Safety:
644/// The memory pointed to by `dst` must be a single allocated object that is valid for `count`
645/// contiguous elements of `T`.
646/// `count` must not be larger than an `isize`.
647/// `dst` being offset by `mem::size_of::<T> * count` bytes must not wrap around the address space.
648/// Also `dst` must be properly aligned.
649#[inline(always)]
650unsafe fn volatile_set<T: Copy + Sized>(dst: *mut T, src: T, count: usize) {
651 // TODO(tarcieri): use `volatile_set_memory` when stabilized
652 for i in 0..count {
653 // Safety:
654 //
655 // This is safe because there is room for at least `count` objects of type `T` in the
656 // allocation pointed to by `dst`, because `count <= isize::MAX` and because
657 // `dst.add(count)` must not wrap around the address space.
658 let ptr = dst.add(i);
659
660 // Safety:
661 //
662 // This is safe, because the pointer is valid and because `dst` is well aligned for `T` and
663 // `ptr` is an offset of `dst` by a multiple of `mem::size_of::<T>()` bytes.
664 ptr::write_volatile(ptr, src);
665 }
666}
667
668/// Zeroizes a flat type/struct. Only zeroizes the values that it owns, and it does not work on
669/// dynamically sized values or trait objects. It would be inefficient to use this function on a
670/// type that already implements `ZeroizeOnDrop`.
671///
672/// # Safety
673/// - The type must not contain references to outside data or dynamically sized data, such as
674/// `Vec<T>` or `String`.
675/// - Values stored in the type must not have `Drop` impls.
676/// - This function can invalidate the type if it is used after this function is called on it.
677/// It is advisable to call this function only in `impl Drop`.
678/// - The bit pattern of all zeroes must be valid for the data being zeroized. This may not be
679/// true for enums and pointers.
680///
681/// # Incompatible data types
682/// Some data types that cannot be safely zeroized using `zeroize_flat_type` include,
683/// but are not limited to:
684/// - References: `&T` and `&mut T`
685/// - Non-nullable types: `NonNull<T>`, `NonZeroU32`, etc.
686/// - Enums with explicit non-zero tags.
687/// - Smart pointers and collections: `Arc<T>`, `Box<T>`, `Vec<T>`, `HashMap<K, V>`, `String`, etc.
688///
689/// # Examples
690/// Safe usage for a struct containing strictly flat data:
691/// ```
692/// use zeroize::{ZeroizeOnDrop, zeroize_flat_type};
693///
694/// struct DataToZeroize {
695/// flat_data_1: [u8; 32],
696/// flat_data_2: SomeMoreFlatData,
697/// }
698///
699/// struct SomeMoreFlatData(u64);
700///
701/// impl Drop for DataToZeroize {
702/// fn drop(&mut self) {
703/// unsafe { zeroize_flat_type(self as *mut Self) }
704/// }
705/// }
706/// impl ZeroizeOnDrop for DataToZeroize {}
707///
708/// let mut data = DataToZeroize {
709/// flat_data_1: [3u8; 32],
710/// flat_data_2: SomeMoreFlatData(123u64)
711/// };
712///
713/// // data gets zeroized when dropped
714/// ```
715#[inline(always)]
716pub unsafe fn zeroize_flat_type<F: Sized>(data: *mut F) {}
717
718/// Internal module used as support for `AssertZeroizeOnDrop`.
719#[doc(hidden)]
720pub mod __internal {
721 use super::*;
722
723 /// Auto-deref workaround for deriving `ZeroizeOnDrop`.
724 pub trait AssertZeroizeOnDrop {
725 fn zeroize_or_on_drop(self);
726 }
727
728 impl<T: ZeroizeOnDrop + ?Sized> AssertZeroizeOnDrop for &&mut T {
729 fn zeroize_or_on_drop(self) {}
730 }
731
732 /// Auto-deref workaround for deriving `ZeroizeOnDrop`.
733 pub trait AssertZeroize {
734 fn zeroize_or_on_drop(&mut self);
735 }
736
737 impl<T: Zeroize + ?Sized> AssertZeroize for T {
738 fn zeroize_or_on_drop(&mut self) {
739 self.zeroize()
740 }
741 }
742}