Skip to content

Commit 03f3900

Browse files
pks-tgitster
authored andcommitted
rust/varint: add safety comments
The `decode_varint()` and `encode_varint()` functions in our Rust crate are reimplementations of the respective C functions. As such, we are naturally forced to use the same interface in both Rust and C, which makes use of raw pointers. The consequence is that the code needs to be marked as unsafe in Rust. It is common practice in Rust to provide safety documentation for every block that is marked as unsafe. This common practice is also enforced by Clippy, Rust's static analyser. We don't have Clippy wired up yet, and we could of course just disable this check. But we're about to wire it up, and it is reasonable to always enforce documentation for unsafe blocks. Add such safety comments to already squelch those warnings now. While at it, also document the functions' behaviour. Helped-by: "brian m. carlson" <[email protected]> Signed-off-by: Patrick Steinhardt <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent e75cd05 commit 03f3900

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/varint.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
/// Decode the variable-length integer stored in `bufp` and return the decoded value.
2+
///
3+
/// Returns 0 in case the decoded integer would overflow u64::MAX.
4+
///
5+
/// # Safety
6+
///
7+
/// The buffer must be NUL-terminated to ensure safety.
18
#[no_mangle]
29
pub unsafe extern "C" fn decode_varint(bufp: *mut *const u8) -> u64 {
310
let mut buf = *bufp;
@@ -22,6 +29,14 @@ pub unsafe extern "C" fn decode_varint(bufp: *mut *const u8) -> u64 {
2229
val
2330
}
2431

32+
/// Encode `value` into `buf` as a variable-length integer unless `buf` is null.
33+
///
34+
/// Returns the number of bytes written, or, if `buf` is null, the number of bytes that would be
35+
/// written to encode the integer.
36+
///
37+
/// # Safety
38+
///
39+
/// `buf` must either be null or point to at least 16 bytes of memory.
2540
#[no_mangle]
2641
pub unsafe extern "C" fn encode_varint(value: u64, buf: *mut u8) -> u8 {
2742
let mut varint: [u8; 16] = [0; 16];

0 commit comments

Comments
 (0)