setup_read_cleanup 0.8.0

A library for safely transitioning through the three phases of shared resource access: setup, read, and cleanup.
Documentation
// Copyright (C) 2025 Takayuki Sato. All Rights Reserved.
// This program is free software under MIT License.
// See the file LICENSE in this distribution for more details.

use crate::Phase;

use std::fmt;

impl fmt::Display for Phase {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

pub(crate) const PHASE_SETUP: u8 = 0;
pub(crate) const PHASE_READ: u8 = 1;
pub(crate) const PHASE_CLEANUP: u8 = 2;
pub(crate) const PHASE_SETUP_TO_READ: u8 = 3;
pub(crate) const PHASE_READ_TO_CLEANUP: u8 = 4;
pub(crate) const PHASE_SETUP_TO_CLEANUP: u8 = 5;

pub(crate) fn u8_to_phase(phase_u8: u8) -> Phase {
    match phase_u8 {
        PHASE_SETUP => Phase::Setup,
        PHASE_READ => Phase::Read,
        PHASE_CLEANUP => Phase::Cleanup,
        PHASE_SETUP_TO_READ => Phase::Setup,
        PHASE_READ_TO_CLEANUP => Phase::Cleanup,
        PHASE_SETUP_TO_CLEANUP => Phase::Cleanup,
        _ => Phase::Cleanup,
    }
}

#[cfg(test)]
mod tests_of_phase {
    use super::*;

    #[test]
    fn test_debug() {
        assert_eq!(format!("{:?}", Phase::Setup), "Setup");
        assert_eq!(format!("{:?}", Phase::Read), "Read");
        assert_eq!(format!("{:?}", Phase::Cleanup), "Cleanup");
    }

    #[test]
    fn test_display() {
        assert_eq!(format!("{}", Phase::Setup), "Setup");
        assert_eq!(format!("{}", Phase::Read), "Read");
        assert_eq!(format!("{}", Phase::Cleanup), "Cleanup");
    }

    #[test]
    fn test_u8_to_phase() {
        assert_eq!(u8_to_phase(PHASE_SETUP), Phase::Setup);
        assert_eq!(u8_to_phase(PHASE_READ), Phase::Read);
        assert_eq!(u8_to_phase(PHASE_CLEANUP), Phase::Cleanup);
        assert_eq!(u8_to_phase(PHASE_SETUP_TO_READ), Phase::Setup);
        assert_eq!(u8_to_phase(PHASE_READ_TO_CLEANUP), Phase::Cleanup);
        assert_eq!(u8_to_phase(PHASE_SETUP_TO_CLEANUP), Phase::Cleanup);
        assert_eq!(u8_to_phase(10), Phase::Cleanup);
    }
}