1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
//! # Atomic Bitfield
//!  Provides a bitfield abstraction for the core atomic types. This crate is `no_std` compatible
//! by default, and does not itself use any `unsafe` code.
//!
//! __Note__: On `stable` this crate assumes the presence of the following atomics
//! which may cause compilation to fail on certain platforms.
//! * `Atomic{U,I}32` and smaller
//! * `Atomic{U,I}size`
//! * `Atomic{U,I}64` on 64 bit platforms
//!
//! The `nightly` feature of this crate enables `target_has_atomic` and uses
//! that instead to detect which atomic types are available.
//!
//! # Usage Example
//! ```
//! use core::sync::atomic::{AtomicU8, Ordering::Relaxed};
//! use atomic_bitfield::AtomicBitField as _;
//!
//! let flags = AtomicU8::new(0b1000);
//!
//! let prev_state = flags.set_bit(0, Relaxed);
//! assert_eq!(prev_state, false);
//! assert_eq!(flags.load(Relaxed), 0b1001);
//!
//! let prev_state = flags.toggle_bit(3, Relaxed);
//! assert_eq!(prev_state, true);
//! assert_eq!(flags.load(Relaxed), 0b0001);
//!
//! let prev_state = flags.swap_bit(0, false, Relaxed);
//! assert_eq!(prev_state, true);
//! assert_eq!(flags.load(Relaxed), 0b0000);
//! ```

#![cfg_attr(feature = "nightly", feature(cfg_target_has_atomic))]
#![cfg_attr(not(test), no_std)]
#![forbid(unsafe_code)]

use bit_field::BitField as _;
use core::{
	mem,
	sync::atomic::{self, Ordering},
};

/// Generic trait for manipulating bits atomically.
pub trait AtomicBitField: Sized {
	/// Returns the number of bits in this atomic type.
	#[inline]
	fn bit_len() -> usize {
		mem::size_of::<Self>() * 8
	}

	/// Atomically sets the bit to `new_val` at index `bit` (zero-indexed), returning the previous value.
	///
	/// ## Panics
	///
	/// This method will panic if the bit index is out of bounds of the bit field.
	#[inline]
	fn swap_bit(&self, bit: usize, new_val: bool, ord: Ordering) -> bool {
		assert!(bit < Self::bit_len());

		if new_val {
			self.set_bit(bit, ord)
		} else {
			self.clear_bit(bit, ord)
		}
	}

	/// Atomically retrieves the bit at index `bit` (zero-indexed).
	///
	/// ## Panics
	///
	/// This method will panic if the bit index is out of bounds of the bit field.
	fn get_bit(&self, bit: usize, ord: Ordering) -> bool;

	/// Atomically sets the bit to `true` at index `bit` (zero-indexed), returning the previous value.
	///
	/// ## Panics
	///
	/// This method will panic if the bit index is out of bounds of the bit field.
	fn set_bit(&self, bit: usize, ord: Ordering) -> bool;

	/// Atomically clears the bit (sets to `false`) at index `bit` (zero-indexed), returning the previous value.
	///
	/// ## Panics
	///
	/// This method will panic if the bit index is out of bounds of the bit field.
	fn clear_bit(&self, bit: usize, ord: Ordering) -> bool;

	/// Atomically toggles the bit (`0 -> 1`, `1 -> 0`) at index `bit` (zero-indexed), returning the previous value.
	///
	/// ## Panics
	///
	/// This method will panic if the bit index is out of bounds of the bit field.
	fn toggle_bit(&self, bit: usize, ord: Ordering) -> bool;
}

macro_rules! atomic_bitfield_impl_generate {
	($($atomic_t:ty),*) => ($(
		impl AtomicBitField for $atomic_t {
			#[inline]
			fn get_bit(&self, bit: usize, ord: Ordering) -> bool {
				assert!(bit < Self::bit_len());
				self.load(ord) & (1 << bit) != 0
			}

			#[inline]
			fn set_bit(&self, bit: usize, ord: Ordering) -> bool {
				assert!(bit < Self::bit_len());
				let prev = self.fetch_or(1 << bit, ord);
				prev.get_bit(bit)
			}

			#[inline]
			fn clear_bit(&self, bit: usize, ord: Ordering) -> bool {
				assert!(bit < Self::bit_len());
				let prev = self.fetch_and(!(1 << bit), ord);
				prev.get_bit(bit)
			}

			#[inline]
			fn toggle_bit(&self, bit: usize, ord: Ordering) -> bool {
				assert!(bit < Self::bit_len());
				let prev = self.fetch_xor(1 << bit, ord);
				prev.get_bit(bit)
			}
		}
	)*)
}

cfg_if::cfg_if! {
	if #[cfg(feature = "nightly")] {
		#[cfg(target_has_atomic = "8")]
		atomic_bitfield_impl_generate!(atomic::AtomicU8, atomic::AtomicI8);

		#[cfg(target_has_atomic = "16")]
		atomic_bitfield_impl_generate!(atomic::AtomicU16, atomic::AtomicI16);

		#[cfg(target_has_atomic = "32")]
		atomic_bitfield_impl_generate!(atomic::AtomicU32, atomic::AtomicI32);

		#[cfg(target_has_atomic = "64")]
		atomic_bitfield_impl_generate!(atomic::AtomicU64, atomic::AtomicI64);

		#[cfg(target_has_atomic = "ptr")]
		atomic_bitfield_impl_generate!(atomic::AtomicUsize, atomic::AtomicIsize);
	} else {
		use atomic::*;
		atomic_bitfield_impl_generate!(AtomicU8, AtomicU16, AtomicU32, AtomicUsize, AtomicI8, AtomicI16, AtomicI32, AtomicIsize);

		#[cfg(target_pointer_width = "64")]
		atomic_bitfield_impl_generate!(AtomicU64, AtomicI64);
	}
}

#[cfg(test)]
mod test;