Skip to content

Commit

Permalink
[u8; n] / &[u8] / u8 iterator conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
blckngm committed Dec 28, 2023
1 parent 130a6b5 commit 28798f1
Showing 1 changed file with 57 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use proc_macro2 as m4;
use quote::quote;

use super::super::utilities::{builder_name, entity_name, field_name, usize_lit};
use super::super::utilities::{builder_name, entity_name, field_name, reader_name, usize_lit};
use crate::ast::{self as ast, HasName};

pub(in super::super) trait ImplBuilder: HasName {
Expand Down Expand Up @@ -119,8 +119,48 @@ impl ImplBuilder for ast::Array {
impl ast::Array {
pub(crate) fn gen_from(&self) -> m4::TokenStream {
let entity = entity_name(self.name());
let reader = reader_name(self.name());
let item_name = entity_name(self.item().typ().name());
let n = self.item_count();
let maybe_byte_arr = if self.item().typ().name() == "byte" {
quote!(
impl From<[u8; #n]> for #entity {
fn from(value: [u8; #n]) -> Self {
#reader::new_unchecked(&value).to_entity()
}
}

impl ::core::convert::TryFrom<&[u8]> for #entity {
type Error = ::core::array::TryFromSliceError;
fn try_from(value: &[u8]) -> Result<Self, ::core::array::TryFromSliceError> {
Ok(<[u8; #n]>::try_from(value)?.into())
}
}

impl From<#entity> for [u8; #n] {
#[track_caller]
fn from(value: #entity) -> Self {
::core::convert::TryFrom::try_from(value.as_slice()).unwrap()
}
}

impl<'a> From<#reader<'a>> for &'a [u8; #n] {
#[track_caller]
fn from(value: #reader<'a>) -> Self {
::core::convert::TryFrom::try_from(value.as_slice()).unwrap()
}
}

impl<'a> From<&'a #reader<'a>> for &'a [u8; #n] {
#[track_caller]
fn from(value: &'a #reader<'a>) -> Self {
::core::convert::TryFrom::try_from(value.as_slice()).unwrap()
}
}
)
} else {
quote!()
};
let nth = (0..n).map(|i| quote::format_ident!("nth{}", i));
quote!(
impl From<[#item_name; #n]> for #entity {
Expand All @@ -138,10 +178,13 @@ impl ast::Array {
}

impl From<#entity> for [#item_name; #n] {
#[track_caller]
fn from(value: #entity) -> Self {
[#(value.#nth(),)*]
}
}

#maybe_byte_arr
)
}
}
Expand Down Expand Up @@ -228,13 +271,26 @@ impl ImplBuilder for ast::DynVec {

fn gen_from_iter(name: &str, item_name: &str) -> m4::TokenStream {
let entity = entity_name(name);
let maybe_byte_vec = if item_name == "byte" {
quote!(
impl ::core::iter::FromIterator<u8> for #entity {
fn from_iter<T: IntoIterator<Item = u8>>(iter: T) -> Self {
Self::new_builder().extend(iter.into_iter().map(Into::into)).build()
}
}
)
} else {
quote!()
};
let item_name = entity_name(item_name);
quote!(
impl ::core::iter::FromIterator<#item_name> for #entity {
fn from_iter<T: IntoIterator<Item = #item_name>>(iter: T) -> Self {
Self::new_builder().extend(iter).build()
}
}

#maybe_byte_vec
)
}

Expand Down

0 comments on commit 28798f1

Please sign in to comment.