#[repr(C)]
pub struct AtomicMaybeUninit<T: Primitive> { /* private fields */ }
Expand description

A potentially uninitialized integer type which can be safely shared between threads.

This type has the same in-memory representation as the underlying integer type, MaybeUninit<T>.

Implementations

Creates a new atomic value from a potentially uninitialized integer.

This is const fn on Rust 1.61+. See also const_new function.

Examples
use std::mem::MaybeUninit;

use atomic_maybe_uninit::AtomicMaybeUninit;

let v = AtomicMaybeUninit::new(MaybeUninit::new(5_i32));

// Equivalent to:
let v = AtomicMaybeUninit::from(5_i32);

Returns a mutable reference to the underlying integer.

This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.

Examples
use std::mem::MaybeUninit;

use atomic_maybe_uninit::AtomicMaybeUninit;

let mut v = AtomicMaybeUninit::from(5_i32);
unsafe { assert_eq!((*v.get_mut()).assume_init(), 5) }
*v.get_mut() = MaybeUninit::new(10);
unsafe { assert_eq!((*v.get_mut()).assume_init(), 10) }

Consumes the atomic and returns the contained value.

This is safe because passing self by value guarantees that no other threads are concurrently accessing the atomic data.

Examples
use atomic_maybe_uninit::AtomicMaybeUninit;

let v = AtomicMaybeUninit::from(5_i32);
unsafe { assert_eq!(v.into_inner().assume_init(), 5) }

Loads a value from the atomic integer.

load takes an Ordering argument which describes the memory ordering of this operation. Possible values are SeqCst, Acquire and Relaxed.

Panics

Panics if order is Release or AcqRel.

Examples
use std::sync::atomic::Ordering;

use atomic_maybe_uninit::AtomicMaybeUninit;

let v = AtomicMaybeUninit::from(5_i32);
unsafe { assert_eq!(v.load(Ordering::Relaxed).assume_init(), 5) }

Stores a value into the atomic integer.

store takes an Ordering argument which describes the memory ordering of this operation. Possible values are SeqCst, Release and Relaxed.

Panics

Panics if order is Acquire or AcqRel.

Examples
use std::{mem::MaybeUninit, sync::atomic::Ordering};

use atomic_maybe_uninit::AtomicMaybeUninit;

let v = AtomicMaybeUninit::from(5_i32);
v.store(MaybeUninit::new(10), Ordering::Relaxed);
unsafe { assert_eq!(v.load(Ordering::Relaxed).assume_init(), 10) }

Stores a value into the atomic integer, returning the previous value.

swap takes an Ordering argument which describes the memory ordering of this operation. All ordering modes are possible. Note that using Acquire makes the store part of this operation Relaxed, and using Release makes the load part Relaxed.

Examples
use std::{mem::MaybeUninit, sync::atomic::Ordering};

use atomic_maybe_uninit::AtomicMaybeUninit;

let v = AtomicMaybeUninit::from(5_i32);
unsafe {
    assert_eq!(v.swap(MaybeUninit::new(10), Ordering::Relaxed).assume_init(), 5);
    assert_eq!(v.load(Ordering::Relaxed).assume_init(), 10);
}

Stores a value into the atomic integer if the current value is the same as the current value.

The return value is a result indicating whether the new value was written and containing the previous value. On success this value is guaranteed to be equal to current.

compare_exchange takes two Ordering arguments to describe the memory ordering of this operation. success describes the required ordering for the read-modify-write operation that takes place if the comparison with current succeeds. failure describes the required ordering for the load operation that takes place when the comparison fails. Using Acquire as success ordering makes the store part of this operation Relaxed, and using Release makes the successful load Relaxed. The failure ordering can only be SeqCst, Acquire or Relaxed.

Panics

Panics if failure is Release, AcqRel.

Notes

Comparison of two values containing uninitialized bytes may fail even if they are equivalent as Rust’s type, because their contents are not frozen until a pointer to the value containing uninitialized bytes is passed to asm!.

For example, the following example could be an infinite loop:

use std::{
    mem::{self, MaybeUninit},
    sync::atomic::Ordering,
};

use atomic_maybe_uninit::AtomicMaybeUninit;

#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(C, align(4))]
struct Test(u8, u16);

unsafe {
    let x = mem::transmute::<_, MaybeUninit<u32>>(Test(0, 0));
    let v = AtomicMaybeUninit::new(x);
    while v
        .compare_exchange(
            mem::transmute::<_, MaybeUninit<u32>>(Test(0, 0)),
            mem::transmute::<_, MaybeUninit<u32>>(Test(1, 0)),
            Ordering::AcqRel,
            Ordering::Acquire,
        )
        .is_err()
    {}
}

To work around this problem, you need to use a helper like the following.

// Adapted from https://github.com/crossbeam-rs/crossbeam/blob/crossbeam-utils-0.8.10/crossbeam-utils/src/atomic/atomic_cell.rs#L1081-L1110
unsafe fn atomic_compare_exchange(
    v: &AtomicMaybeUninit<u32>,
    mut current: Test,
    new: Test,
) -> Result<Test, Test> {
    let mut current_raw = mem::transmute::<_, MaybeUninit<u32>>(current);
    let new_raw = mem::transmute::<_, MaybeUninit<u32>>(new);
    loop {
        match v.compare_exchange_weak(current_raw, new_raw, Ordering::AcqRel, Ordering::Acquire)
        {
            Ok(_) => break Ok(current),
            Err(previous_raw) => {
                let previous = mem::transmute_copy(&previous_raw);

                if !Test::eq(&previous, &current) {
                    break Err(previous);
                }

                // The compare-exchange operation has failed and didn't store `new`. The
                // failure is either spurious, or `previous` was semantically equal to
                // `current` but not byte-equal. Let's retry with `previous` as the new
                // `current`.
                current = previous;
                current_raw = previous_raw;
            }
        }
    }
}

unsafe {
    let x = mem::transmute::<_, MaybeUninit<u32>>(Test(0, 0));
    let v = AtomicMaybeUninit::new(x);
    while atomic_compare_exchange(&v, Test(0, 0), Test(1, 0)).is_err() {}
}

See crossbeam-rs/crossbeam#315 for more details.

Also, Valgrind reports “Conditional jump or move depends on uninitialized value(s)” error if there is such comparison.

Examples
use std::{mem::MaybeUninit, sync::atomic::Ordering};

use atomic_maybe_uninit::AtomicMaybeUninit;

unsafe {
    let v = AtomicMaybeUninit::from(5_i32);

    assert_eq!(
        v.compare_exchange(
            MaybeUninit::new(5),
            MaybeUninit::new(10),
            Ordering::Acquire,
            Ordering::Relaxed
        )
        .unwrap()
        .assume_init(),
        5
    );
    assert_eq!(v.load(Ordering::Relaxed).assume_init(), 10);

    assert_eq!(
        v.compare_exchange(
            MaybeUninit::new(6),
            MaybeUninit::new(12),
            Ordering::SeqCst,
            Ordering::Acquire
        )
        .unwrap_err()
        .assume_init(),
        10
    );
    assert_eq!(v.load(Ordering::Relaxed).assume_init(), 10);
}

Stores a value into the atomic integer if the current value is the same as the current value.

This function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms. The return value is a result indicating whether the new value was written and containing the previous value.

compare_exchange_weak takes two Ordering arguments to describe the memory ordering of this operation. success describes the required ordering for the read-modify-write operation that takes place if the comparison with current succeeds. failure describes the required ordering for the load operation that takes place when the comparison fails. Using Acquire as success ordering makes the store part of this operation Relaxed, and using Release makes the successful load Relaxed. The failure ordering can only be SeqCst, Acquire or Relaxed.

Panics

Panics if failure is Release, AcqRel.

Notes

Comparison of two values containing uninitialized bytes may fail even if they are equivalent as Rust’s type, because their contents are not frozen until a pointer to the value containing uninitialized bytes is passed to asm!.

See compare_exchange for details.

Examples
use std::{mem::MaybeUninit, sync::atomic::Ordering};

use atomic_maybe_uninit::AtomicMaybeUninit;

let v = AtomicMaybeUninit::from(5_i32);

unsafe {
    let mut old = v.load(Ordering::Relaxed);
    loop {
        let new = old.assume_init() * 2;
        match v.compare_exchange_weak(
            old,
            MaybeUninit::new(new),
            Ordering::SeqCst,
            Ordering::Relaxed,
        ) {
            Ok(_) => break,
            Err(x) => old = x,
        }
    }
}

Fetches the value, and applies a function to it that returns an optional new value. Returns a Result of Ok(previous_value) if the function returned Some(_), else Err(previous_value).

Note: This may call the function multiple times if the value has been changed from other threads in the meantime, as long as the function returns Some(_), but the function will have been applied only once to the stored value.

fetch_update takes two Ordering arguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings of compare_exchange respectively.

Using Acquire as success ordering makes the store part of this operation Relaxed, and using Release makes the final successful load Relaxed. The (failed) load ordering can only be SeqCst, Acquire or Relaxed.

Panics

Panics if fetch_order is Release, AcqRel.

Examples
use std::{mem::MaybeUninit, sync::atomic::Ordering};

use atomic_maybe_uninit::AtomicMaybeUninit;

unsafe {
    let v = AtomicMaybeUninit::from(5_i32);
    assert_eq!(
        v.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None).unwrap_err().assume_init(),
        5
    );
    assert_eq!(
        v.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(MaybeUninit::new(
            x.assume_init() + 1
        )))
        .unwrap()
        .assume_init(),
        5
    );
    assert_eq!(v.load(Ordering::SeqCst).assume_init(), 6);
}

Creates a new atomic value from a potentially uninitialized integer. Unlike new, this is always const fn.

Creates a new atomic value from a potentially uninitialized integer. Unlike new, this is always const fn.

Creates a new atomic value from a potentially uninitialized integer. Unlike new, this is always const fn.

Creates a new atomic value from a potentially uninitialized integer. Unlike new, this is always const fn.

Creates a new atomic value from a potentially uninitialized integer. Unlike new, this is always const fn.

Creates a new atomic value from a potentially uninitialized integer. Unlike new, this is always const fn.

Creates a new atomic value from a potentially uninitialized integer. Unlike new, this is always const fn.

Creates a new atomic value from a potentially uninitialized integer. Unlike new, this is always const fn.

Creates a new atomic value from a potentially uninitialized integer. Unlike new, this is always const fn.

Creates a new atomic value from a potentially uninitialized integer. Unlike new, this is always const fn.

Creates a new atomic value from a potentially uninitialized integer. Unlike new, this is always const fn.

Creates a new atomic value from a potentially uninitialized integer. Unlike new, this is always const fn.

Trait Implementations

Formats the value using the given formatter. Read more

Creates a new atomic value from a potentially uninitialized integer.

Creates a new atomic value from an initialized integer.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Converts to this type from the input type.

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.