debug_ptr/lib.rs
1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! A wrapper around AtomicPtr that automatically adds a blackbox hint to
5//! prevent it from being optimized out. Intended to be used as a write-
6//! only pointer used to easily find interested variables when debugging.
7
8#![forbid(unsafe_code)]
9
10use std::sync::atomic::AtomicPtr;
11use std::sync::atomic::Ordering;
12
13/// A pointer wrapper for debugging purposes
14pub struct DebugPtr<T>(AtomicPtr<T>);
15
16impl<T> DebugPtr<T> {
17 /// Creates a new debug pointer, initialized to null.
18 pub const fn new() -> Self {
19 DebugPtr(AtomicPtr::new(std::ptr::null_mut()))
20 }
21
22 /// Stores the provided reference as an AtomicPtr and uses a blackbox
23 /// hint to prevent it from being optimized out.
24 pub fn store(&self, ptr: &T) {
25 self.0
26 .store(std::ptr::from_ref(ptr).cast_mut(), Ordering::Relaxed);
27 std::hint::black_box(&self.0);
28 }
29}