//! Binary data conversion utilities.

use crate::durandal::{err::*, text::mac_roman_conv};
use std::{fmt, num::NonZeroU16};

#[doc(hidden)]
#[macro_export]
macro_rules! _durandal_read_impl {
   // big endian
   (BE $b:expr; $nam:ident u16 $n:expr) => {
      _durandal_read_impl!($b; u16::from_be_bytes, $nam 2 $n);
   };
   (BE $b:expr; $nam:ident i16 $n:expr) => {
      _durandal_read_impl!($b; i16::from_be_bytes, $nam 2 $n);
   };
   (BE $b:expr; $nam:ident u32 $n:expr) => {
      _durandal_read_impl!($b; u32::from_be_bytes, $nam 4 $n);
   };
   (BE $b:expr; $nam:ident i32 $n:expr) => {
      _durandal_read_impl!($b; i32::from_be_bytes, $nam 4 $n);
   };

   // little endian
   (LE $b:expr; $nam:ident u16 $n:expr) => {
      _durandal_read_impl!($b; u16::from_le_bytes, $nam 2 $n);
   };
   (LE $b:expr; $nam:ident i16 $n:expr) => {
      _durandal_read_impl!($b; i16::from_le_bytes, $nam 2 $n);
   };
   (LE $b:expr; $nam:ident u32 $n:expr) => {
      _durandal_read_impl!($b; u32::from_le_bytes, $nam 4 $n);
   };
   (LE $b:expr; $nam:ident i32 $n:expr) => {
      _durandal_read_impl!($b; i32::from_le_bytes, $nam 4 $n);
   };

   // either endianness
   ($e:ident $b:expr; $nam:ident Angle $n:expr) => {
      _durandal_read_impl!($e $b; $nam u16 $n);
      let $nam = Angle::from_bits($nam);
   };
   ($e:ident $b:expr; $nam:ident Fixed $n:expr) => {
      _durandal_read_impl!($e $b; $nam u32 $n);
      let $nam = Fixed::from_bits($nam);
   };
   ($e:ident $b:expr; $nam:ident Unit $n:expr) => {
      _durandal_read_impl!($e $b; $nam u16 $n);
      let $nam = Unit::from_bits($nam);
   };
   ($e:ident $b:expr; $nam:ident OptU16 $n:expr) => {
      _durandal_read_impl!($e $b; $nam u16 $n);
      let $nam = OptU16::from_repr($nam);
   };
   ($e:ident $b:expr; $nam:ident usize u16 $n:expr) => {
      _durandal_read_impl!($e $b; $nam u16 $n);
      let $nam = usize::from($nam);
   };
   ($e:ident $b:expr; $nam:ident usize u32 $n:expr) => {
      _durandal_read_impl!($e $b; $nam u32 $n);
      let $nam = usize_from_u32($nam);
   };

   // no endianness
   ($_:ident $b:expr; $nam:ident       u8 $n:expr) => {let $nam =  $b[$n];};
   ($_:ident $b:expr; $nam:ident slice u8 $n:expr) => {let $nam = &$b[$n];};
   ($_:ident $b:expr; $nam:ident i8 $n:expr) => {
      let $nam = i8::from_ne_bytes([$b[$n]]);
   };
   ($_:ident $b:expr; $nam:ident Ident $n:expr) => {
      let $nam = Ident([$b[$n], $b[$n + 1], $b[$n + 2], $b[$n + 3]]);
   };
   ($_:ident $b:expr; $nam:ident $f:ident $n:expr) => {
      let $nam = $f(&$b[$n])?;
   };
   ($_:ident $b:expr; $nam:ident no_try $f:ident $n:expr) => {
      let $nam = $f(&$b[$n]);
   };

   // worker - creates let statement
   ($b:expr; $pth:path , $nam:ident 2 $n:expr) => {
      let $nam = $pth([$b[$n], $b[$n + 1]]);
   };
   ($b:expr; $pth:path , $nam:ident 4 $n:expr) => {
      let $nam = $pth([$b[$n], $b[$n + 1], $b[$n + 2], $b[$n + 3]]);
   };
}

/// Reads structured data from a byte slice.
///
/// # Syntax
///
/// First start by specifying the endianness, size and source using the syntax
/// `endian, size in source =>` where:
///
/// - `endian` is `BE` or `LE` for big- or little-endian respectively.
/// - `size` is an expression specifying the last index that should be used by
/// this macro in `source`.
/// - `source` is a `u8` slice to read data from.
///
/// After the initializer line, all lines have the syntax
/// `name = type[place] opts;` where:
///
/// - `name` is the binding to put the resulting data in.
/// - `type` is one of:
///   - `u8` or `i8`: one byte will be read at `place`.
///   - `u16` or `i16`: two bytes will be read at `place` with `from_*_bytes`.
///   - `u32` or `i32`: four bytes will be read at `place` with `from_*_bytes`.
///   - `Ident`: four bytes will be read at `place` into an array, disregarding
///     endianness, creating an `Ident` object.
///   - `Angle`: same as `u16`, but the result is passed to
///     `fixed::Angle::from_bits`, resulting in a `fixed::Angle` object.
///   - `Fixed`: same as `u32`, but the result is passed to
///     `fixed::Fixed::from_bits`, resulting in a `fixed::Fixed` object.
///   - `Unit`: same as `u16`, but the result is passed to
///     `fixed::Unit::from_bits`, resulting in a `fixed::Unit` object.
///   - `OptU16`: same as `u16`, but the result is passed to
///     `OptU16::from_repr`, resulting in an `OptU16` object.
///   - The name of a function, which is passed `&source[place]` as its only
///     argument. The function's result has the `?` operator applied to it.
/// - `opts` may be one of:
///   - `slice` when `type` is `u8`: `place` is a range specifying a `u8` slice
///     to be taken from `source`.
///   - `usize` when `type` is `u16` or `u32`: converts the resulting integer to
///     `usize` by `usize_to_u32` for `u32` or by `from` for `u16`.
///   - `no_try` when `type` is a function name: does not use the `?` operator
///     on the resulting function call.
///   - Nothing at all.
/// - `place` is either an integer literal which must be representable as
///   `usize`, or a range, which may only be used when `type` is a function
///   name.
///
/// # Panics
///
/// This macro will not panic unless any index expression used exceeds or
/// equals `size`.
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate maraiah;
/// # use maraiah::durandal::err::*;
/// # fn main() -> ResultS<()>
/// # {
/// let buffer = &[4, 0, 2, 0, 0, 0, 6];
///
/// read_data! {
///    7, LE in buffer =>
///    four = u16[0];
///    two  = u32[2];
///    six  = u8 [6];
/// }
///
/// assert_eq!(four, 4_u16);
/// assert_eq!(two,  2_u32);
/// assert_eq!(six,  6_u8);
/// #    Ok(())
/// # }
/// ```
#[macro_export]
macro_rules! read_data {
   (
      $sz:expr , $ty:ident in $b:expr =>
      $( $nam:ident = $t:ident [ $n:expr ] $( $ex:ident )* ; )*
   ) => {
      $crate::check_data!($sz, $b);
      $($crate::_durandal_read_impl!($ty $b; $nam $($ex)* $t $n);)*
   };
}

/// Checks if there is enough data in `b`.
#[macro_export]
macro_rules! check_data {
   (
      $sz:expr , $b:expr
   ) => {
      if $b.len() < $sz {
         return Err(err_msg("not enough data"));
      }
   };
}

/// Casts a `u32` to a `usize`. For future compatibility.
///
/// # Examples
///
/// ```
/// use maraiah::durandal::bin::usize_from_u32;
///
/// assert_eq!(usize_from_u32(777u32), 777usize);
/// ```
#[inline]
pub const fn usize_from_u32(n: u32) -> usize {n as usize}

/// Creates an `Ident` from a slice.
///
/// # Panics
///
/// A panic will occur if `b.len()` is less than 4.
///
/// # Examples
///
/// ```
/// use maraiah::durandal::bin::{Ident, ident};
///
/// assert_eq!(ident(b"POLY"), Ident([b'P', b'O', b'L', b'Y']));
/// ```
#[inline]
pub const fn ident(b: &[u8]) -> Ident {Ident([b[0], b[1], b[2], b[3]])}

/// Applies `u32::from_be_bytes` to a slice.
///
/// # Panics
///
/// A panic will occur if `b.len()` is less than 4.
///
/// # Examples
///
/// ```
/// use maraiah::durandal::bin::u32b;
///
/// assert_eq!(u32b(&[0x00, 0x0B, 0xDE, 0x31]), 777_777u32);
/// ```
pub fn u32b(b: &[u8]) -> u32 {u32::from_be_bytes([b[0], b[1], b[2], b[3]])}

/// Applies `u16::from_be_bytes` to a slice.
///
/// # Panics
///
/// A panic will occur if `b.len()` is less than 2.
///
/// # Examples
///
/// ```
/// use maraiah::durandal::bin::u16b;
///
/// assert_eq!(u16b(&[0x1E, 0x61]), 7_777u16);
/// ```
pub fn u16b(b: &[u8]) -> u16 {u16::from_be_bytes([b[0], b[1]])}

/// Applies `i32::from_be_bytes` to a slice.
///
/// # Panics
///
/// A panic will occur if `b.len()` is less than 4.
///
/// # Examples
///
/// ```
/// use maraiah::durandal::bin::i32b;
///
/// assert_eq!(i32b(&[0xFF, 0x89, 0x52, 0x0F]), -7_777_777i32);
/// ```
pub fn i32b(b: &[u8]) -> i32 {i32::from_be_bytes([b[0], b[1], b[2], b[3]])}

/// Applies `i16::from_be_bytes` to a slice.
///
/// # Panics
///
/// A panic will occur if `b.len()` is less than 2.
///
/// # Examples
///
/// ```
/// use maraiah::durandal::bin::i16b;
///
/// assert_eq!(i16b(&[0xE1, 0x9F]), -7_777i16);
/// ```
pub fn i16b(b: &[u8]) -> i16 {i16::from_be_bytes([b[0], b[1]])}

/// Applies a read function over a slice.
///
/// Applies `read` over `b`, resulting in a vector of its return values. Each
/// iteration will pass a slice of `b` to `read` for it to read from, and then
/// increments the slice index by the second return value. When there is no
/// data left in `b`, the function returns.
///
/// # Panics
///
/// A panic will occur if the `read` function returns a disjoint index or
/// otherwise panics (by an out of bounds index to `b` or otherwise.)
///
/// # Errors
///
/// Execution will return the result of `read` if `read` returns an error.
///
/// # Examples
///
/// ```
/// use maraiah::durandal::{err::*, bin::{rd_array, u16b}};
///
/// fn read_a_u16(b: &[u8]) -> ResultS<(u16, usize)> {Ok((u16b(b), 2))}
///
/// let inp = &[0x1E, 0x61, 0x03, 0x09];
/// assert_eq!(rd_array(inp, read_a_u16).unwrap(), vec![7_777u16, 777u16]);
/// ```
pub fn rd_array<T, F>(b: &[u8], read: F) -> ResultS<Vec<T>>
   where T: Sized,
         F: Fn(&[u8]) -> ResultS<(T, usize)>
{
   let mut v = Vec::new();
   let mut p = 0;

   while p < b.len() {
      let (r, s) = read(&b[p..])?;
      v.push(r);
      p += s;
   }

   Ok(v)
}

/// Applies a read function a number of times over a slice.
///
/// Applies `read` over `b`, resulting in a vector of its return values. Each
/// iteration will pass a slice of `b` to `read` for it to read from, and then
/// increments the slice index by the second return value. When `n` elements
/// have been read, the function returns.
///
/// # Panics
///
/// A panic will occur if the `read` function returns a disjoint index or
/// otherwise panics (by an out of bounds index to `b` or otherwise.)
///
/// # Errors
///
/// Execution will return the result of `read` if `read` returns an error.
pub fn rd_array_num<T, F>(b: &[u8], n: usize, read: F)
   -> ResultS<(Vec<T>, usize)>
   where T: Sized,
         F: Fn(&[u8]) -> ResultS<(T, usize)>
{
   let mut v = Vec::with_capacity(n);
   let mut p = 0;

   for _ in 0..n {
      let (r, s) = read(&b[p..])?;
      v.push(r);
      p += s;
   }

   Ok((v, p))
}

/// Applies a read function over a slice with an offset table.
///
/// Applies `read` over each offset in `b`, of which there are `num` amount of
/// starting at `p`, resulting in a vector of its return values. Each iteration
/// reads a 32-bit big endian offset from `b`, and then passes a slice of `b`
/// to `read` starting at that offset. When all offsets have been read, the
/// function returns.
///
/// # Panics
///
/// A panic will occur if the `read` function panics.
///
/// # Errors
///
/// Execution will return the result of `read` if `read` returns an error.
pub fn rd_ofstable<T, F>(b: &[u8],
                         mut p: usize,
                         num: usize,
                         read: F)
   -> ResultS<Vec<T>>
   where T: Sized,
         F: Fn(&[u8]) -> ResultS<T>
{
   let mut v = Vec::with_capacity(num);

   for _ in 0..num {
      let ofs = usize_from_u32(u32b(&b[p..p + 4]));
      check_data!(ofs, b);
      v.push(read(&b[ofs..])?);
      p += 4;
   }

   Ok(v)
}

impl OptU16
{
   /// Creates an `OptU16` representing `None`.
   ///
   /// # Examples
   ///
   /// ```
   /// use maraiah::durandal::bin::OptU16;
   ///
   /// assert_eq!(OptU16::none(), OptU16::from_repr(u16::max_value()));
   /// ```
   pub const fn none() -> Self {Self(None)}

   /// Creates an `OptU16` from a `u16`.
   pub fn from_repr(n: u16) -> Self
   {
      if n == u16::max_value() {
         Self(None)
      } else {
         Self(NonZeroU16::new(n + 1))
      }
   }

   /// Returns the `u16` representation.
   ///
   /// # Examples
   ///
   /// ```
   /// use maraiah::durandal::bin::OptU16;
   ///
   /// let u16max = u16::max_value();
   ///
   /// assert_eq!(OptU16::from_repr(500u16).get_repr(), 500u16);
   /// assert_eq!(OptU16::from_repr(u16max).get_repr(), u16max);
   /// assert_eq!(OptU16::from_repr(0u16).get_repr(), 0u16);
   /// ```
   pub fn get_repr(self) -> u16
   {
      match self.0 {
         None    => u16::max_value(),
         Some(n) => n.get() - 1,
      }
   }

   /// Returns the `Option` representation.
   ///
   /// # Examples
   ///
   /// ```
   /// use maraiah::durandal::bin::OptU16;
   ///
   /// assert_eq!(OptU16::from_repr(500u16).get(), Some(500u16));
   /// assert_eq!(OptU16::from_repr(u16::max_value()).get(), None);
   /// assert_eq!(OptU16::from_repr(0u16).get(), Some(0u16));
   /// ```
   pub fn get(self) -> Option<u16>
   {
      match self.0 {
         None    => None,
         Some(n) => Some(n.get() - 1),
      }
   }
}

impl fmt::Debug for OptU16
{
   fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
   {
      match self.get() {
         None    => write!(f, "None"),
         Some(n) => write!(f, "Some({})", n),
      }
   }
}

impl fmt::Debug for Ident
{
   fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
   {
      write!(f, "\"{}\"", mac_roman_conv(&self.0))
   }
}

impl PartialEq<[u8; 4]> for Ident
{
   #[inline]
   fn eq(&self, o: &[u8; 4]) -> bool {self.0 == *o}
}

impl<'a> PartialEq<[u8; 4]> for &'a Ident
{
   #[inline]
   fn eq(&self, o: &[u8; 4]) -> bool {PartialEq::eq(*self, o)}
}

impl<'a> PartialEq<&'a [u8; 4]> for Ident
{
   #[inline]
   fn eq(&self, o: & &'a [u8; 4]) -> bool {PartialEq::eq(self, *o)}
}

/// A four-character-code identifier.
///
/// # Examples
///
/// ```
/// use maraiah::durandal::bin::Ident;
///
/// assert_eq!( Ident(*b"POLY").0, *b"POLY");
/// assert_eq!( Ident(*b"POLY"),   *b"POLY");
/// assert_eq!( Ident(*b"POLY"),    b"POLY");
/// assert_eq!(&Ident(*b"POLY"),   *b"POLY");
/// assert_eq!(&Ident(*b"POLY"),    b"POLY");
/// ```
#[derive(Clone, Copy, Default, Eq, PartialEq)]
#[cfg_attr(feature = "serde_obj", derive(serde::Serialize, serde::Deserialize))]
pub struct Ident(/** The individual bytes of this identifier. */ pub [u8; 4]);

/// An object identified by a `u16` which may be `u16::max_value()` to
/// represent a nulled value.
#[derive(Clone, Copy, Default, Eq, PartialEq)]
#[cfg_attr(feature = "serde_obj", derive(serde::Serialize, serde::Deserialize))]
pub struct OptU16(Option<NonZeroU16>);

// EOF
