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
//! A package containing useful utilities for writing save accessors.

use super::Error;
use crate::sync::{RawMutex, RawMutexGuard};
use crate::timer::{Timer, Divider};

/// A timeout type used to prevent hardware errors in save media from hanging
/// the game.
pub struct Timeout {
    timer: Option<Timer>,
}
impl Timeout {
    /// Creates a new timeout from the timer passed to [`set_timer_for_timeout`].
    ///
    /// ## Errors
    ///
    /// If another timeout has already been created.
    #[inline(never)]
    pub fn new(timer: Option<Timer>) -> Self {
        Timeout { timer }
    }

    /// Starts this timeout.
    pub fn start(&mut self) {
        if let Some(timer) = &mut self.timer {
            timer.set_enabled(false);
            timer.set_divider(Divider::Divider1024);
            timer.set_interrupt(false);
            timer.set_overflow_amount(0xFFFF);
            timer.set_cascade(false);
            timer.set_enabled(true);
        }
    }

    /// Returns whether a number of milliseconds has passed since the last call
    /// to [`Timeout::start()`].
    pub fn check_timeout_met(&self, check_ms: u16) -> bool {
        if let Some(timer) = &self.timer {
            check_ms * 17 < timer.value()
        } else {
            false
        }
    }
}
impl Drop for Timeout {
    fn drop(&mut self) {
        if let Some(timer) = &mut self.timer {
            timer.set_enabled(false);
        }
    }
}

pub fn lock_media_access() -> Result<RawMutexGuard<'static>, Error> {
    static LOCK: RawMutex = RawMutex::new();
    match LOCK.try_lock() {
        Some(x) => Ok(x),
        None => Err(Error::MediaInUse),
    }
}