Skip to content

Commit

Permalink
Adds cppbind::type_info::align
Browse files Browse the repository at this point in the history
  • Loading branch information
ultimaweapon committed Oct 17, 2024
1 parent dddae2b commit df65599
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 3 deletions.
4 changes: 3 additions & 1 deletion cppbind.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
#include <stddef.h>

#define CPPBIND_CLASS(n) \
template<> const size_t cppbind::type_info<n>::size = sizeof(n)
template<> const size_t cppbind::type_info<n>::size = sizeof(n); \
template<> const size_t cppbind::type_info<n>::align = alignof(n)

namespace cppbind {
template<typename T>
struct type_info {
static const size_t size;
static const size_t align;
};
}

Expand Down
16 changes: 14 additions & 2 deletions macros/src/cpp.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use self::class::Class;
use crate::META;
use proc_macro2::TokenStream;
use proc_macro2::{Literal, TokenStream};
use quote::{format_ident, quote};
use syn::parse::{Parse, ParseStream};
use syn::Error;
Expand Down Expand Up @@ -46,6 +46,17 @@ fn render_class(item: Class) -> syn::Result<TokenStream> {
}
};

// Get alignment.
let align = match meta.align {
Some(v) => v,
None => {
return Err(Error::new_spanned(
class,
format_args!("cppbind::type_info<{name}>::align not found"),
))
}
};

// Render constructors.
let mut impls = TokenStream::new();

Expand All @@ -63,6 +74,7 @@ fn render_class(item: Class) -> syn::Result<TokenStream> {
}

// Compose.
let align = Literal::usize_unsuffixed(align);
let mem = if name.chars().next().unwrap().is_uppercase() {
format_ident!("{name}Memory")
} else {
Expand All @@ -81,7 +93,7 @@ fn render_class(item: Class) -> syn::Result<TokenStream> {
}

#[allow(non_camel_case_types)]
#[repr(transparent)]
#[repr(C, align(#align))]
pub struct #mem([::std::mem::MaybeUninit<u8>; #size]);

impl #mem {
Expand Down
6 changes: 6 additions & 0 deletions macros/src/meta.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,12 @@ impl Metadata {
.map(|v| usize::from_ne_bytes(v.try_into().unwrap()))
.ok_or_else(|| SymbolError::GetDataFailed(index))
.map(Some)?;
} else if *ty == Segment::Ident("align".into()) {
info.align = section
.get(off..(off + len))
.map(|v| usize::from_ne_bytes(v.try_into().unwrap()))
.ok_or_else(|| SymbolError::GetDataFailed(index))
.map(Some)?;
} else {
return Err(SymbolError::UnknownCppbindSymbol);
}
Expand Down
1 change: 1 addition & 0 deletions macros/src/meta/ty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
#[derive(Default)]
pub struct TypeInfo {
pub size: Option<usize>,
pub align: Option<usize>,
}

0 comments on commit df65599

Please sign in to comment.