So, that is a shared reference to the cell itself, not to the T, which, in that case, does allow the code to compile. Unfortunately, however, the code style incurs unnecessary performance costs. Take a look at this assembly comparison
use std::cell::Cell;
#[unsafe(no_mangle)]
fn a1(a: &Cell<Vec<i32>>) {
let mut _v = a.take();
_v.push(10);
a.set(_v);
}
#[unsafe(no_mangle)]
fn a2(a: *mut Vec<i32>) {
unsafe { (*a).push(10); }
}
The Cell :
a1:
pushq %r14
pushq %rbx
subq $24, %rsp
movq %rdi, %rbx
movq 16(%rdi), %rax
movq %rax, 16(%rsp)
movups (%rdi), %xmm0
movaps %xmm0, (%rsp)
movq $0, (%rdi)
movq $4, 8(%rdi)
movq $0, 16(%rdi)
movq 16(%rsp), %r14
cmpq (%rsp), %r14
jne .LBB8_2
movq %rsp, %rdi
callq <alloc::raw_vec::RawVec<i32>>::grow_one
.LBB8_2:
movq 8(%rsp), %rax
movl $10, (%rax,%r14,4)
incq %r14
movq %r14, 16(%rsp)
movq (%rbx), %rsi
movq 8(%rbx), %rdi
movq %r14, 16(%rbx)
movaps (%rsp), %xmm0
movups %xmm0, (%rbx)
testq %rsi, %rsi
je .LBB8_3
shlq $2, %rsi
movl $4, %edx
addq $24, %rsp
popq %rbx
popq %r14
jmpq *__rustc::__rust_dealloc@GOTPCREL(%rip)
.LBB8_3:
addq $24, %rsp
popq %rbx
popq %r14
retq
movq %rax, %rbx
movq (%rsp), %rsi
testq %rsi, %rsi
je .LBB8_6
movq 8(%rsp), %rdi
shlq $2, %rsi
movl $4, %edx
callq *__rustc::__rust_dealloc@GOTPCREL(%rip)
.LBB8_6:
movq %rbx, %rdi
callq _Unwind_Resume@PLT
The zero cost high performance one if there is reference that I talked about before :
a2:
pushq %r14
pushq %rbx
pushq %rax
movq 16(%rdi), %r14
cmpq (%rdi), %r14
je .LBB9_1
.LBB9_2:
movq 8(%rdi), %rax
movl $10, (%rax,%r14,4)
incq %r14
movq %r14, 16(%rdi)
addq $8, %rsp
popq %rbx
popq %r14
retq
.LBB9_1:
movq %rdi, %rbx
callq <alloc::raw_vec::RawVec<i32>>::grow_one
movq %rbx, %rdi
jmp .LBB9_2
The version using the cell performs redundant unnecerery operations: it copies the metadata, zeroes out the original metadata, carries out a mutation, and then copies the metadata once more, all of which translates to extra memory writes. This scales at O(n) relative to the size of the metadata, for a Vec, that’s 24 bytes. Since the set method also copies the metadata, you end up with 48 bytes of copying, plus the overhead of zeroing out the original metadata. Now, consider a "fat" struct, for instance, one containing five Vecs and five Strings, where the metadata size reaches 240 bytes (24 bytes × 10). That results in 480 bytes of copying, and the cost of the zeroing process, all for just a single call
In reality, it should only require copying 8 bytes, the size of a reference, regardless of the actual size of the metadata being pointed to, so it is constant O(1), then would simply perform the mutation and be done without any copying again