use std::sync::Arc;
use std::sync::atomic::AtomicU32;
use orbit_core::Fleet;
#[cfg(unix)]
use orbit_core::shm::ring_segment_name;
mod error;
mod id;
mod orbital;
mod table;
mod wake;
pub use error::{Error, Result};
pub use id::{Kind, OrbitalId, Primitive};
pub use orbital::Orbital;
pub use table::{ATOMIC_CAPACITY, ATOMIC_KIND};
use table::Table;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "macos"))]
fn waits_supported() -> bool {
orbit_core::sync::supported()
}
#[cfg(not(any(
target_os = "linux",
target_os = "freebsd",
target_os = "macos"
)))]
fn waits_supported() -> bool {
false
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "macos"))]
pub(crate) fn wait_on(
word: &AtomicU32,
expected: u32,
) -> Result<()> {
orbit_core::sync::wait_word(word, expected).map_err(Error::Io)
}
#[cfg(not(any(
target_os = "linux",
target_os = "freebsd",
target_os = "macos"
)))]
pub(crate) fn wait_on(
_word: &AtomicU32,
_expected: u32,
) -> Result<()> {
Err(unsupported())
}
pub(crate) fn wake_on(word: &AtomicU32) {
#[cfg(any(
target_os = "linux",
target_os = "freebsd",
target_os = "macos"
))]
let _ = orbit_core::sync::wake_word(word);
#[cfg(not(any(
target_os = "linux",
target_os = "freebsd",
target_os = "macos"
)))]
let _ = word;
}
fn unsupported() -> Error {
Error::Io(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"orbit-atomic needs a platform that can wait on a shared word: Linux, FreeBSD, or macOS 14.4 or later",
))
}
#[derive(Clone)]
pub struct Orbitals {
table: Arc<Table>,
}
impl Orbitals {
pub fn new(fleet: Arc<Fleet>) -> Result<Self> {
if !waits_supported() {
return Err(unsupported());
}
let table = if fleet.is_shm() {
#[cfg(unix)]
{
table::shm_table(&ring_segment_name(fleet.name(), ATOMIC_KIND))?
}
#[cfg(not(unix))]
unreachable!("non-Unix fleets cannot use POSIX SHM")
} else {
table::memory_table(&fleet)
};
Ok(Self { table })
}
pub fn allocate<T: Primitive>(
&self,
initial: T,
) -> Result<Orbital<T>> {
let (id, slot) = self.table.allocate(T::KIND, initial.into_word())?;
Ok(Orbital::new(slot, id, Arc::clone(&self.table)))
}
pub fn open<T: Primitive>(
&self,
id: OrbitalId,
) -> Result<Orbital<T>> {
let slot = self.table.open(id, T::KIND)?;
Ok(Orbital::new(slot, id, Arc::clone(&self.table)))
}
pub fn reset_all(&self) -> Result<()> {
self.table.reset()
}
#[cfg(unix)]
pub fn unlink(&self) -> Result<()> {
self.table.unlink()
}
}