/*
==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--

Namaste

Copyright (C) 2019, 2021-2025  Anonymous

There are several releases over multiple years,
they are listed as ranges, such as: "2021-2025".

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--
*/

#![cfg(any(target_os="android", target_os="l4re", target_os="linux"))]
#![doc(cfg(any(target_os="android", target_os="l4re", target_os="linux")))]

use {
    std::io::{Error, Read, Write},
    crate::Result,
};

/// # Command
#[derive(Debug, Clone, Copy)]
pub (crate) enum Cmd {

    /// # Duplicates server file descriptor
    DuplicateServerFd,

}

impl Cmd {

    /// # ID
    const fn id(&self) -> u8 {
        *self as u8
    }

    pub fn encode<W>(&self, writer: &mut W) -> Result<()> where W: Write {
        writer.write_all(&[self.id()])
    }

    pub fn decode<R>(reader: &mut R) -> Result<Self> where R: Read {
        let mut buf = [u8::MIN];
        reader.read_exact(&mut buf)?;
        Self::try_from(&buf[0])
    }

}

impl TryFrom<&u8> for Cmd {

    type Error = Error;

    fn try_from(id: &u8) -> Result<Self> {
        for cmd in [Self::DuplicateServerFd] {
            if &cmd.id() == id {
                return Ok(cmd);
            }
        }

        Err(err!("Unknown ID: {id}"))
    }

}

impl TryFrom<u8> for Cmd {

    type Error = Error;

    fn try_from(id: u8) -> Result<Self> {
        Self::try_from(&id)
    }

}
