-
Notifications
You must be signed in to change notification settings - Fork 10
Fix zero length types #8
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
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thank you for the PR!
Notes: this conflicts with #1, which ideally should go first
A few questions:
- how does Box handle that? Maybe we can just do the same here instead of checking for size twice and returning
Box::new(value)
- have you confirmed that the extra statements don't ruin our optimized LLVM IR?
The size check is zero-cost at runtime with optimization on. Rust generates binary code for every <T>, so mem::size_of::<T>() can be replaced with a constant. In fact: The entire call is removed by the optimizer: Check the assembly here: pub fn alloc_box(some:usize)->Box<Debug> {
if some==12345 {
Box::alloc().init(EmptyType{})
} else {
Box::alloc().init(NonEmptyType{ string:"some string"})
}
} becomes playground::alloc_box:
cmpq $12345, %rdi
jne .LBB12_2 // if some==12345
movl $1, %eax // Box::alloc().init(EmptyType{})
leaq .L__unnamed_6(%rip), %rdx
retq
.LBB12_2:
pushq %rax // Box::alloc().init(NonEmptyType{ string:"some string"})
movl $16, %edi
movl $8, %esi
callq *__rust_alloc@GOTPCREL(%rip)
leaq .L__unnamed_7(%rip), %rcx
movq %rcx, (%rax)
movq $11, 8(%rax)
leaq .L__unnamed_8(%rip), %rdx
addq $8, %rsp
retq So my PR should not have any consequences on runtime behaviour if optimization is turned on - except for being faster with empty types
That is your decision. If you merge #1 I will gladly adapt this PR. But IMO a memory safety error is of higher priority. Edit: I have adapted the playground to remove the alloc for the string, for brevity |
Ok, fair enough. Thank you! |
8: Fix zero length types r=kvark a=eun-ice This pull request seems to fix a memory issue, by just referring to Box::new for zero-length types. Since Box does not allocate for zero-length types and mem::size_of::<T> is constant for any given generic type, this change should not negatively affect performance. Co-authored-by: Aron Wieck <[email protected]>
Build succeeded |
This pull request seems to fix a memory issue, by just referring to Box::new for zero-length types.
Since Box does not allocate for zero-length types and mem::size_of:: is constant for any given generic type, this change should not negatively affect performance.