Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does AtomicPtr disallow dynamically sized types?

Tags:

rust

I wanted to create an AtomicPtr to a slice but I was surprised to find out that I couldn't.

struct MyObject {
    ptr: AtomicPtr<[u32]>
}

yields the error:

error[E0277]: the size for values of type `[u32]` cannot be known at compilation time
 --> src/lib.rs:4:5
  |
4 |     ptr: AtomicPtr<[u32]>
  |     ^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `[u32]`
  = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
  = note: required by `std::sync::atomic::AtomicPtr`

See it on the Rust Playground

I personally can't see why this would be the case but I might be missing something. Is there a reason for this restriction? And is there a workaround for achieving the same functionality?

like image 662
kmdreko Avatar asked Mar 03 '23 19:03

kmdreko


1 Answers

It is intentional that AtomicPtr<T> works only with T: Sized because in rust slices and trait objects are fat pointers (the size double respect to normal pointer).

Actually it is not possible to have T: ?Sized because this prevents the guarantee of atomic operation for some platforms, for example ARM.

See here for more details.

like image 88
attdona Avatar answered Mar 05 '23 17:03

attdona