Beingessner: Rust's Unsafe Pointer Types Need An Overhaul
Beingessner: Rust's Unsafe Pointer Types Need An Overhaul
Posted Mar 22, 2022 14:05 UTC (Tue) by farnz (subscriber, #17727)In reply to: Beingessner: Rust's Unsafe Pointer Types Need An Overhaul by wtarreau
Parent article: Beingessner: Rust's Unsafe Pointer Types Need An Overhaul
"restrict" is a promise from the programmer to the compiler, which is why it's a pain to understand.
Using the following names for exposition:
int foo[16]; int * foo_ptr = &foo[0]; int * restrict foo_restrict = foo;
With foo_ptr, the programmer makes no promises about aliasing. There can be a second pointer to any element of foo, and you can use foo[2] and *(foo_ptr + 2) interchangeably.
"restrict" makes a promise to the compiler about using overlapping names, and hence a promise that no aliasing is used for as long as the "restrict" pointer is alive. For as long as foo_restrict is alive, you promise not to access foo directly, or via foo_ptr, and you promise that if you use *(foo_restrict + 4), you have not accessed foo[4] any other way since foo_restrict was initialized, and that you will not access it any other way (e.g. via foo[4], or *(foo_ptr + 4)) until the lifetime of foo_restrict ends.
The usual concrete example is memcpy versus memmove; the inputs to memcpy are "restrict" pointers, because if you do memcpy(foo, bar, 16 * sizeof(foo[0]));, you promise the compiler that until memcpy returns, *(foo + 0) through *(foo + 15) cannot be accessed via *(bar + offset). memmove, on the other hand, permits that overlap, so its input pointers cannot be marked restrict.
The LWN site is currently under high scraper load, so comment display has been suppressed for anonymous users. If you are a human, you may read the comments by clicking the button below:
Note: you can avoid this step in the future by logging into your LWN account.
