[rust] Add SAFETY comments for unsafe blocks
Adds SAFETY comments for the two instances of unsafe blocks that are *not* just FFI. It seems like overkill to annotate all the FFI calls so i'm skipping that, let me know if anyone has strong preferences otherwise.
Joe Savona committed
Aug 17, 2023 at 15:23 UTC
a905a029018e6ea699405ec9bac45c0ad62282b8
2 files changed
+11
-1
compiler/forget/crates/forget_hermes_parser/src/generated_extension.rs
+7
-1
@@ -31,7 +31,13 @@ pub struct Context {
31
32
impl Context {
33
pub fn new(parser: &NullTerminatedBuf) -> Self {
34
- let start: usize = unsafe { parser.as_ptr() as usize };
34
+ // SAFETY: This function returns a pointer to the underlying
35
+ // buffer. It is safe to get the pointer, it is only unsafe to
36
+ // use that pointer in unsafe ways. We only use the value to
37
+ // calculate offsets (and only use safe APIs to access the string
38
+ // based on those offsets).
39
+ let ptr = unsafe { parser.as_ptr() };
40
+ let start = ptr as usize;
41
Self { start }
42
}
43
}
compiler/forget/crates/forget_utils/src/pointer_address.rs
+4
@@ -16,6 +16,10 @@ pub struct PointerAddress(usize);
16
17
impl PointerAddress {
18
pub fn new<T>(ptr: &T) -> Self {
19
+ // SAFETY: We convert the pointer into a usize for use as an identifier.
20
+ // This is _safe_ but may lead to logical bugs if different values can
21
+ // be stored at the same memory address within the lifetime of the
22
+ // PointerAddress.
23
let ptr_address: usize = unsafe { std::mem::transmute(ptr) };
24
Self(ptr_address)
25
}