Skip to content

Commit 7f4b393

Browse files
authored
Update const_safety.md
1 parent 5dd1390 commit 7f4b393

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

const_safety.md

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -113,17 +113,28 @@ const-safe result. For example, the following function is const-safe (after
113113
some extensions of the miri engine that are already implemented in miri) even
114114
though it uses raw pointer operations:
115115
```rust
116-
const fn test_eq<T>(x: &T, y: &T) -> bool {
117-
unconst { x as *const _ == y as *const _ }
116+
const fn slice_eq(x: &[u32], y: &[u32]) -> bool {
117+
if x.len() != y.len() {
118+
return false;
119+
}
120+
// equal length and address -> memory must be equal, too
121+
if unconst { x as *const [u32] as *const u32 == y as *const [u32] as *const u32 } {
122+
return true;
123+
}
124+
// assume the following is legal const code for the purpose of this function
125+
x.iter().eq(y.iter())
118126
}
119127
```
120128
On the other hand, the following function is *not* const-safe and hence it is considered a bug to mark it as such:
121129
```
122-
const fn convert<T>(x: &T) -> usize {
123-
unconst { x as *const _ as usize }
130+
const fn ptr_eq<T>(x: &T, y: &T) -> bool {
131+
unconst { x as *const T == y as *const T }
124132
}
125133
```
126134

135+
If the function were invoked as `ptr_eq(&42, &42)` the result depends on the potential
136+
deduplication of the memory of the `42`s.
137+
127138
## Open questions
128139

129140
* Do we allow unconst operations in `unsafe` blocks, or do we have some other

0 commit comments

Comments
 (0)