//! Implementations of our traits for various [core] types

use crate::error::RenderableOnMinimal;
use crate::message::{MinimalWritableMessage, MutableWritableMessage, ReadableMessage};
use core::fmt::Debug;

impl RenderableOnMinimal for core::convert::Infallible {
    type Error<IE: RenderableOnMinimal + Debug> = core::convert::Infallible;

    fn render<M: crate::MinimalWritableMessage>(
        self,
        _: &mut M,
    ) -> Result<(), core::convert::Infallible> {
        match self {}
    }
}

impl<T: RenderableOnMinimal, E: RenderableOnMinimal> RenderableOnMinimal for Result<T, E> {
    type Error<IE: RenderableOnMinimal + Debug> = Result<T::Error<IE>, E::Error<IE>>;

    fn render<M: crate::MinimalWritableMessage>(
        self,
        msg: &mut M,
    ) -> Result<(), Self::Error<M::UnionError>> {
        match self {
            Ok(t) => t.render(msg).map_err(Ok)?,
            Err(e) => e.render(msg).map_err(Err)?,
        };
        Ok(())
    }
}

impl<T: ReadableMessage> ReadableMessage for &T {
    type Code = T::Code;

    type MessageOption<'a>
        = T::MessageOption<'a>
    where
        Self: 'a;

    type OptionsIter<'a>
        = T::OptionsIter<'a>
    where
        Self: 'a;

    fn code(&self) -> Self::Code {
        (*self).code()
    }

    fn options(&self) -> Self::OptionsIter<'_> {
        (*self).options()
    }

    fn payload(&self) -> &[u8] {
        (*self).payload()
    }
}

impl<T: MinimalWritableMessage> MinimalWritableMessage for &mut T {
    type Code = T::Code;

    type OptionNumber = T::OptionNumber;
    type AddOptionError = T::AddOptionError;
    type SetPayloadError = T::SetPayloadError;
    type UnionError = T::UnionError;

    fn set_code(&mut self, code: Self::Code) {
        (**self).set_code(code)
    }

    fn add_option(
        &mut self,
        number: Self::OptionNumber,
        value: &[u8],
    ) -> Result<(), Self::AddOptionError> {
        (**self).add_option(number, value)
    }

    fn set_payload(&mut self, data: &[u8]) -> Result<(), Self::SetPayloadError> {
        (**self).set_payload(data)
    }
}

impl<T: MutableWritableMessage> MutableWritableMessage for &mut T {
    fn available_space(&self) -> usize {
        (**self).available_space()
    }

    fn payload_mut_with_len(&mut self, len: usize) -> Result<&mut [u8], Self::SetPayloadError> {
        (**self).payload_mut_with_len(len)
    }

    fn truncate(&mut self, len: usize) -> Result<(), Self::SetPayloadError> {
        (**self).truncate(len)
    }

    fn mutate_options<F>(&mut self, callback: F)
    where
        F: FnMut(Self::OptionNumber, &mut [u8]),
    {
        (**self).mutate_options(callback)
    }
}
