This commit is contained in:
Emil Fresk 2024-02-15 15:43:25 +01:00
parent 7a2f605b52
commit a76f650c46
3 changed files with 92 additions and 1 deletions

View file

@ -28,6 +28,7 @@ portable-atomic = { version = "1", default-features = false }
embedded-hal = { version = "1.0", optional = true }
embedded-hal-async = { version = "1.0", optional = true }
embedded-hal-bus = { version = "0.1.0", optional = true, features = ["async"] }
bitflags = "2"
[dev-dependencies]
tokio = { version = "1", features = ["rt", "macros", "time"] }

View file

@ -0,0 +1,89 @@
//! A channel operating on bitflags.
use bitflags::{Bits, Flags};
use core::sync::atomic::{AtomicU16, AtomicU8, Ordering};
//
// Bit channel
//
pub struct BitChannel<T: Flags>
where
T: Flags,
T::Bits: AtomicType,
{
atomic: <T::Bits as AtomicType>::Atomic,
}
impl<T> BitChannel<T>
where
T: Flags,
T::Bits: AtomicType,
{
pub const fn new() -> Self {
BitChannel {
atomic: T::Bits::ATOMIC_ZERO,
}
}
pub fn test(&self) {
T::Bits::fetch_and(&self.atomic, T::Bits::EMPTY, Ordering::Relaxed);
}
}
pub trait AtomicType: Sized {
type Atomic: From<Self>;
const ATOMIC_ZERO: Self::Atomic;
fn fetch_and(a: &Self::Atomic, b: Self, order: Ordering) -> Self;
}
impl AtomicType for u16 {
type Atomic = AtomicU16;
const ATOMIC_ZERO: Self::Atomic = AtomicU16::new(0);
fn fetch_and(a: &Self::Atomic, b: Self, order: Ordering) -> Self {
a.fetch_and(b, order)
}
}
impl AtomicType for u8 {
type Atomic = AtomicU8;
const ATOMIC_ZERO: Self::Atomic = AtomicU8::new(0);
fn fetch_and(a: &Self::Atomic, b: Self, order: Ordering) -> Self {
a.fetch_and(b, order)
}
}
// etc...
#[cfg(test)]
mod tests {
use super::*;
use bitflags::bitflags;
bitflags! {
struct FlagsU8: u8 {
const A = 1;
const B = 2;
}
}
bitflags! {
struct FlagsU16: u16 {
const A = 1;
const B = 2;
}
}
#[test]
fn test() {
let a = BitChannel::<FlagsU8>::new();
let b = BitChannel::<FlagsU16>::new();
}
}

View file

@ -1,9 +1,10 @@
//! Synchronization primitives for asynchronous contexts.
#![no_std]
#![deny(missing_docs)]
#![warn(missing_docs)]
pub mod arbiter;
pub mod bit_channel;
pub mod channel;
pub use portable_atomic;