sel4_sync_trivial/
lib.rs

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
//
// Copyright 2024, Colias Group, LLC
//
// SPDX-License-Identifier: BSD-2-Clause
//

#![no_std]

use core::cell::Cell;
use core::sync::atomic::{AtomicBool, Ordering};

pub struct PanickingRawMutex {
    locked: AtomicBool,
}

impl PanickingRawMutex {
    pub const fn new() -> Self {
        Self {
            locked: AtomicBool::new(false),
        }
    }
}

impl Default for PanickingRawMutex {
    fn default() -> Self {
        Self::new()
    }
}

unsafe impl lock_api::RawMutex for PanickingRawMutex {
    type GuardMarker = lock_api::GuardNoSend; // TODO

    #[allow(clippy::declare_interior_mutable_const)]
    const INIT: Self = Self::new();

    fn lock(&self) {
        if !self.try_lock() {
            panic!("lock contention")
        }
    }

    fn try_lock(&self) -> bool {
        let was_locked = self.locked.swap(true, Ordering::Acquire);
        !was_locked
    }

    unsafe fn unlock(&self) {
        self.locked.store(false, Ordering::Release)
    }
}

pub struct UnsyncPanickingRawMutex {
    locked: Cell<bool>,
}

impl UnsyncPanickingRawMutex {
    pub const fn new() -> Self {
        Self {
            locked: Cell::new(false),
        }
    }
}

impl Default for UnsyncPanickingRawMutex {
    fn default() -> Self {
        Self::new()
    }
}

unsafe impl lock_api::RawMutex for UnsyncPanickingRawMutex {
    type GuardMarker = lock_api::GuardNoSend; // TODO

    #[allow(clippy::declare_interior_mutable_const)]
    const INIT: Self = Self::new();

    fn lock(&self) {
        if !self.try_lock() {
            panic!("lock contention")
        }
    }

    fn try_lock(&self) -> bool {
        let was_locked = self.locked.replace(true);
        !was_locked
    }

    unsafe fn unlock(&self) {
        self.locked.set(false)
    }
}