Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Querying a type's alignment #14033

Open
HertzDevil opened this issue Dec 1, 2023 · 0 comments
Open

Querying a type's alignment #14033

HertzDevil opened this issue Dec 1, 2023 · 0 comments

Comments

@HertzDevil
Copy link
Contributor

In #7773 there are proposals to control a type's alignment, but there is still no way to query it. Therefore, I suggest the addition of alignof and instance_alignof, which are usable wherever sizeof and instance_sizeof also are:

struct Foo
  @x : Int8
  @y : Int32
  @z : UInt16
end

alignof(Foo) # => 4

@[Extern]
@[Packed]
struct Foo2
  @x : Int8
  @y : Int32
  @z : UInt16
end

alignof(Foo2) # => 1

class Bar
  @x : Int64
end

instance_alignof(Bar) # => 8

class Bar2
end

instance_alignof(Bar2) # => 4

It would become possible to write things like:

@[Align(instance_alignof(Bar))]
buf = uninitialized UInt8[instance_sizeof(Bar)]
bar = buf.to_unsafe.as(Bar)

Also this would provide a means to implement type-aware allocators in native Crystal that align their pointers correctly. The benefits may not be immediately apparent as nothing could have a larger alignment than Int128 (16 bytes) right now, but this could change if eventually #3057 arrives.

The alignment for a single instance variable of a type can be implemented as alignof(Foo, @z). Normally this is identical to alignof(typeof((x = uninitialized Foo; x.@z))), but a separate syntax is necessary because #7773 also allows @[Align] to be applied to an individual instance variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant