Skip to main content

osal_rs/posix/
types.rs

1/***************************************************************************
2 *
3 * osal-rs
4 * Copyright (C) 2026 Antonio Salsi <passy.linux@zresa.it>
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <https://www.gnu.org/licenses/>.
18 *
19 ***************************************************************************/
20
21//! POSIX type definitions and handle wrappers.
22//!
23//! This module provides type aliases and handle types that interface with the
24//! POSIX threading API (pthreads). Types are generated at build time based on
25//! the detected target architecture's native word size.
26//!
27//! # Generated Types
28//!
29//! The following types are generated by the build script, based on the host
30//! architecture reported by `uname`:
31//!
32//! - `TickType` - System tick counter type (`u32` on 32-bit, `u64` on 64-bit)
33//! - `BaseType` - Basic signed integer type for return values
34//! - `UBaseType` - Basic unsigned integer type
35//! - `StackType` - Type used for stack allocation
36//!
37//! # Handle Types
38//!
39//! POSIX OS objects are referenced through opaque pointers (handles):
40//!
41//! - `ThreadHandle` - References a pthread
42//! - `QueueHandle` - References a message queue
43//! - `SemaphoreHandle` - References a semaphore
44//! - `MutexHandle` - References a mutex
45//! - `EventGroupHandle` - References an event group
46//! - `TimerHandle` - References a timer
47
48// Include build-time generated types based on the target architecture.
49// This file is generated by the build script and contains:
50// - TickType: System tick counter type
51// - BaseType: Basic signed integer type
52// - UBaseType: Basic unsigned integer type
53// - StackType: Stack allocation type
54include!(concat!(env!("OUT_DIR"), "/types_generated.rs"));
55
56use core::ffi::{ c_ulong, c_void };
57use core::fmt::Debug;
58
59use crate::posix::ffi::{pthread_cond_t, pthread_mutex_t};
60
61/// POSIX opaque handle types for OS primitives.
62///
63/// These handles are opaque pointers used to reference POSIX/pthread-backed
64/// objects. They should not be dereferenced directly; instead, use the safe
65/// wrappers provided by this crate (e.g., `Thread`, `Queue`, `Semaphore`, etc.).
66
67/// Backing handle for [`crate::os::Queue`], [`crate::os::Semaphore`] and
68/// [`crate::os::EventGroup`]: a `pthread_mutex_t` + `pthread_cond_t` pair.
69///
70/// These three primitives share the same "wait on a condition, guarded by a
71/// mutex" shape, so they all reuse this one handle type (see
72/// [`QueueHandle`], [`SemaphoreHandle`], [`EventGroupHandle`]) instead of
73/// each defining their own. Not constructible from outside this crate other
74/// than via [`Default`]; the safe wrapper types are what application code
75/// should use.
76///
77/// # Examples
78///
79/// ```
80/// use osal_rs::os::types::ClockMonotonicHandle;
81///
82/// // A never-initialized handle reports as empty.
83/// let handle = ClockMonotonicHandle::default();
84/// assert!(handle.is_empty());
85/// ```
86#[derive(Default)]
87pub struct ClockMonotonicHandle (
88    pub(in crate::posix) pthread_mutex_t,
89    pub(in crate::posix) pthread_cond_t,
90);
91
92impl Debug for ClockMonotonicHandle {
93    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
94        f.debug_struct("ClockMonotonicHandle")
95            .field("handle", &(&raw const self).addr())
96            .finish()
97    }
98}
99
100impl ClockMonotonicHandle {
101    /// Returns `true` if this handle is still in its never-initialized (or
102    /// already-deleted) state, i.e. both the mutex and condition variable
103    /// are all-zero.
104    ///
105    /// # Examples
106    ///
107    /// ```
108    /// use osal_rs::os::types::ClockMonotonicHandle;
109    ///
110    /// assert!(ClockMonotonicHandle::default().is_empty());
111    /// ```
112    pub fn is_empty(&self) -> bool {
113        self.0.is_empty() && self.1.is_empty()
114    }
115}
116
117/// Opaque POSIX thread identifier (`pthread_t`).
118///
119/// glibc defines `pthread_t` as `unsigned long int`, so `c_ulong` has the
120/// correct size/representation on every target this crate builds for. `0`
121/// is used throughout this crate as the "no thread" sentinel (see
122/// [`crate::os::ThreadFn::is_null`]).
123pub type ThreadHandle = c_ulong;
124
125/// Backing handle for [`crate::os::Queue`]/[`crate::os::QueueStreamed`].
126/// See [`ClockMonotonicHandle`] for why this is a mutex/condvar pair rather
127/// than a queue-specific type.
128pub type QueueHandle = ClockMonotonicHandle;
129
130/// Backing handle for [`crate::os::Semaphore`].
131/// See [`ClockMonotonicHandle`] for why this is a mutex/condvar pair rather
132/// than a semaphore-specific type (plain POSIX unnamed semaphores can't
133/// enforce a maximum count or use priority inheritance).
134pub type SemaphoreHandle = ClockMonotonicHandle;
135
136/// Backing handle for [`crate::os::EventGroup`].
137/// See [`ClockMonotonicHandle`] for why this is a mutex/condvar pair rather
138/// than an event-group-specific type.
139pub type EventGroupHandle = ClockMonotonicHandle;
140
141/// Opaque POSIX per-process timer identifier (`timer_t`, `<time.h>`).
142///
143/// glibc defines `timer_t` as `void *`, so `*mut c_void` has the correct
144/// size/representation on every target this crate builds for.
145pub type TimerHandle = *mut c_void;
146
147/// Backing handle for [`crate::os::Mutex`]/[`crate::os::RawMutex`]: a bare
148/// `pthread_mutex_t`, with no condition variable attached since a mutex has
149/// nothing to wait on beyond acquiring the lock itself.
150pub type MutexHandle = pthread_mutex_t;
151
152/// Type alias for event group bits.
153///
154/// Represents a set of event flags where each bit can be set or cleared
155/// independently. The underlying type is `TickType`, matching the native
156/// word size of the target architecture. The top byte is reserved (see
157/// [`crate::os::EventGroup::MAX_MASK`]), so only the lower bits are usable
158/// as flags.
159///
160/// # Examples
161///
162/// ```
163/// use osal_rs::os::types::EventBits;
164///
165/// const READY: EventBits = 1 << 0;
166/// const ERROR: EventBits = 1 << 1;
167///
168/// let bits: EventBits = READY | ERROR;
169/// assert_eq!(bits & READY, READY);
170/// ```
171pub type EventBits = TickType;