// Copyright (C) 2021 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: Apache-2.0 or MIT

use core::fmt;

/// A CTAPHID channel.
///
/// See [§ 11.2.3 of the CTAP specification][spec].
///
/// [spec]: https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-20210615.html#usb-channels
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Channel(u32);

impl Channel {
    /// The broadcast channel (`0xffff_ffff`).
    pub const BROADCAST: Channel = Channel(0xffff_ffff);
}

impl From<u32> for Channel {
    fn from(id: u32) -> Self {
        Self(id)
    }
}

impl From<Channel> for u32 {
    fn from(channel: Channel) -> u32 {
        channel.0
    }
}

impl From<[u8; 4]> for Channel {
    fn from(data: [u8; 4]) -> Self {
        Self::from(u32::from_be_bytes(data))
    }
}

impl fmt::Display for Channel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "0x{:x}", self.0)
    }
}
