library: Normalize safety-for-unsafe-block comments

Almost all safety comments are of the form `// SAFETY:`,
so normalize the rest and fix a few of them that should
have been a `/// # Safety` section instead.

Furthermore, make `tidy` only allow the uppercase form. While
currently `tidy` only checks `core`, it is a good idea to prevent
`core` from drifting to non-uppercase comments, so that later
we can start checking `alloc` etc. too.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
This commit is contained in:
Miguel Ojeda 2021-02-24 05:48:44 +01:00
parent fe1bf8e05c
commit eefec8abda
7 changed files with 26 additions and 19 deletions

View File

@ -278,14 +278,14 @@ impl<'a, K: Ord, V> VacantEntry<'a, K, V> {
pub fn insert(self, value: V) -> &'a mut V { pub fn insert(self, value: V) -> &'a mut V {
let out_ptr = match self.handle.insert_recursing(self.key, value) { let out_ptr = match self.handle.insert_recursing(self.key, value) {
(Fit(_), val_ptr) => { (Fit(_), val_ptr) => {
// Safety: We have consumed self.handle and the handle returned. // SAFETY: We have consumed self.handle and the handle returned.
let map = unsafe { self.dormant_map.awaken() }; let map = unsafe { self.dormant_map.awaken() };
map.length += 1; map.length += 1;
val_ptr val_ptr
} }
(Split(ins), val_ptr) => { (Split(ins), val_ptr) => {
drop(ins.left); drop(ins.left);
// Safety: We have consumed self.handle and the reference returned. // SAFETY: We have consumed self.handle and the reference returned.
let map = unsafe { self.dormant_map.awaken() }; let map = unsafe { self.dormant_map.awaken() };
let root = map.root.as_mut().unwrap(); let root = map.root.as_mut().unwrap();
root.push_internal_level().push(ins.kv.0, ins.kv.1, ins.right); root.push_internal_level().push(ins.kv.0, ins.kv.1, ins.right);

View File

@ -1938,13 +1938,13 @@ impl<T, A: Allocator> Vec<T, A> {
pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) { pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
let ptr = self.as_mut_ptr(); let ptr = self.as_mut_ptr();
// Safety: // SAFETY:
// - `ptr` is guaranteed to be in bounds for `capacity` elements // - `ptr` is guaranteed to be in bounds for `capacity` elements
// - `len` is guaranteed to less or equal to `capacity` // - `len` is guaranteed to less or equal to `capacity`
// - `MaybeUninit<T>` has the same layout as `T` // - `MaybeUninit<T>` has the same layout as `T`
let spare_ptr = unsafe { ptr.cast::<MaybeUninit<T>>().add(self.len) }; let spare_ptr = unsafe { ptr.cast::<MaybeUninit<T>>().add(self.len) };
// Safety: // SAFETY:
// - `ptr` is guaranteed to be valid for `len` elements // - `ptr` is guaranteed to be valid for `len` elements
// - `spare_ptr` is offseted from `ptr` by `len`, so it doesn't overlap `initialized` slice // - `spare_ptr` is offseted from `ptr` by `len`, so it doesn't overlap `initialized` slice
unsafe { unsafe {
@ -2154,7 +2154,8 @@ pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<
} }
trait ExtendFromWithinSpec { trait ExtendFromWithinSpec {
/// Safety: /// # Safety
///
/// - `src` needs to be valid index /// - `src` needs to be valid index
/// - `self.capacity() - self.len()` must be `>= src.len()` /// - `self.capacity() - self.len()` must be `>= src.len()`
unsafe fn spec_extend_from_within(&mut self, src: Range<usize>); unsafe fn spec_extend_from_within(&mut self, src: Range<usize>);
@ -2165,14 +2166,14 @@ impl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
let initialized = { let initialized = {
let (this, spare) = self.split_at_spare_mut(); let (this, spare) = self.split_at_spare_mut();
// Safety: // SAFETY:
// - caller guaratees that src is a valid index // - caller guaratees that src is a valid index
let to_clone = unsafe { this.get_unchecked(src) }; let to_clone = unsafe { this.get_unchecked(src) };
to_clone.iter().cloned().zip(spare.iter_mut()).map(|(e, s)| s.write(e)).count() to_clone.iter().cloned().zip(spare.iter_mut()).map(|(e, s)| s.write(e)).count()
}; };
// Safety: // SAFETY:
// - elements were just initialized // - elements were just initialized
unsafe { unsafe {
let new_len = self.len() + initialized; let new_len = self.len() + initialized;
@ -2187,11 +2188,11 @@ impl<T: Copy, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
{ {
let (init, spare) = self.split_at_spare_mut(); let (init, spare) = self.split_at_spare_mut();
// Safety: // SAFETY:
// - caller guaratees that `src` is a valid index // - caller guaratees that `src` is a valid index
let source = unsafe { init.get_unchecked(src) }; let source = unsafe { init.get_unchecked(src) };
// Safety: // SAFETY:
// - Both pointers are created from unique slice references (`&mut [_]`) // - Both pointers are created from unique slice references (`&mut [_]`)
// so they are valid and do not overlap. // so they are valid and do not overlap.
// - Elements are :Copy so it's OK to to copy them, without doing // - Elements are :Copy so it's OK to to copy them, without doing
@ -2203,7 +2204,7 @@ impl<T: Copy, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) }; unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) };
} }
// Safety: // SAFETY:
// - The elements were just initialized by `copy_nonoverlapping` // - The elements were just initialized by `copy_nonoverlapping`
self.len += count; self.len += count;
} }

View File

@ -106,7 +106,7 @@ impl<I: Write> BufferedCopySpec for BufWriter<I> {
Ok(0) => return Ok(len), // EOF reached Ok(0) => return Ok(len), // EOF reached
Ok(bytes_read) => { Ok(bytes_read) => {
assert!(bytes_read <= spare_cap.len()); assert!(bytes_read <= spare_cap.len());
// Safety: The initializer contract guarantees that either it or `read` // SAFETY: The initializer contract guarantees that either it or `read`
// will have initialized these bytes. And we just checked that the number // will have initialized these bytes. And we just checked that the number
// of bytes is within the buffer capacity. // of bytes is within the buffer capacity.
unsafe { buf.set_len(buf.len() + bytes_read) }; unsafe { buf.set_len(buf.len() + bytes_read) };

View File

@ -440,13 +440,17 @@ impl<T> SyncOnceCell<T> {
res res
} }
/// Safety: The value must be initialized /// # Safety
///
/// The value must be initialized
unsafe fn get_unchecked(&self) -> &T { unsafe fn get_unchecked(&self) -> &T {
debug_assert!(self.is_initialized()); debug_assert!(self.is_initialized());
(&*self.value.get()).assume_init_ref() (&*self.value.get()).assume_init_ref()
} }
/// Safety: The value must be initialized /// # Safety
///
/// The value must be initialized
unsafe fn get_unchecked_mut(&mut self) -> &mut T { unsafe fn get_unchecked_mut(&mut self) -> &mut T {
debug_assert!(self.is_initialized()); debug_assert!(self.is_initialized());
(&mut *self.value.get()).assume_init_mut() (&mut *self.value.get()).assume_init_mut()
@ -456,7 +460,7 @@ impl<T> SyncOnceCell<T> {
unsafe impl<#[may_dangle] T> Drop for SyncOnceCell<T> { unsafe impl<#[may_dangle] T> Drop for SyncOnceCell<T> {
fn drop(&mut self) { fn drop(&mut self) {
if self.is_initialized() { if self.is_initialized() {
// Safety: The cell is initialized and being dropped, so it can't // SAFETY: The cell is initialized and being dropped, so it can't
// be accessed again. We also don't touch the `T` other than // be accessed again. We also don't touch the `T` other than
// dropping it, which validates our usage of #[may_dangle]. // dropping it, which validates our usage of #[may_dangle].
unsafe { (&mut *self.value.get()).assume_init_drop() }; unsafe { (&mut *self.value.get()).assume_init_drop() };

View File

@ -8,7 +8,9 @@ mod tests;
pub const MAIN_SEP_STR: &str = "\\"; pub const MAIN_SEP_STR: &str = "\\";
pub const MAIN_SEP: char = '\\'; pub const MAIN_SEP: char = '\\';
// Safety: `bytes` must be a valid wtf8 encoded slice /// # Safety
///
/// `bytes` must be a valid wtf8 encoded slice
#[inline] #[inline]
unsafe fn bytes_as_os_str(bytes: &[u8]) -> &OsStr { unsafe fn bytes_as_os_str(bytes: &[u8]) -> &OsStr {
// &OsStr is layout compatible with &Slice, which is compatible with &Wtf8, // &OsStr is layout compatible with &Slice, which is compatible with &Wtf8,
@ -130,7 +132,7 @@ fn parse_next_component(path: &OsStr, verbatim: bool) -> (&OsStr, &OsStr) {
// The max `separator_end` is `bytes.len()` and `bytes[bytes.len()..]` is a valid index. // The max `separator_end` is `bytes.len()` and `bytes[bytes.len()..]` is a valid index.
let path = &path.bytes()[separator_end..]; let path = &path.bytes()[separator_end..];
// Safety: `path` is a valid wtf8 encoded slice and each of the separators ('/', '\') // SAFETY: `path` is a valid wtf8 encoded slice and each of the separators ('/', '\')
// is encoded in a single byte, therefore `bytes[separator_start]` and // is encoded in a single byte, therefore `bytes[separator_start]` and
// `bytes[separator_end]` must be code point boundaries and thus // `bytes[separator_end]` must be code point boundaries and thus
// `bytes[..separator_start]` and `bytes[separator_end..]` are valid wtf8 slices. // `bytes[..separator_start]` and `bytes[separator_end..]` are valid wtf8 slices.

View File

@ -103,7 +103,7 @@ impl StaticRWLock {
/// The lock is automatically unlocked when the returned guard is dropped. /// The lock is automatically unlocked when the returned guard is dropped.
#[inline] #[inline]
pub fn read_with_guard(&'static self) -> RWLockReadGuard { pub fn read_with_guard(&'static self) -> RWLockReadGuard {
// Safety: All methods require static references, therefore self // SAFETY: All methods require static references, therefore self
// cannot be moved between invocations. // cannot be moved between invocations.
unsafe { unsafe {
self.0.read(); self.0.read();
@ -117,7 +117,7 @@ impl StaticRWLock {
/// The lock is automatically unlocked when the returned guard is dropped. /// The lock is automatically unlocked when the returned guard is dropped.
#[inline] #[inline]
pub fn write_with_guard(&'static self) -> RWLockWriteGuard { pub fn write_with_guard(&'static self) -> RWLockWriteGuard {
// Safety: All methods require static references, therefore self // SAFETY: All methods require static references, therefore self
// cannot be moved between invocations. // cannot be moved between invocations.
unsafe { unsafe {
self.0.write(); self.0.write();

View File

@ -289,7 +289,7 @@ pub fn check(path: &Path, bad: &mut bool) {
suppressible_tidy_err!(err, skip_undocumented_unsafe, "undocumented unsafe"); suppressible_tidy_err!(err, skip_undocumented_unsafe, "undocumented unsafe");
} }
} }
if line.contains("// SAFETY:") || line.contains("// Safety:") { if line.contains("// SAFETY:") {
last_safety_comment = true; last_safety_comment = true;
} else if line.trim().starts_with("//") || line.trim().is_empty() { } else if line.trim().starts_with("//") || line.trim().is_empty() {
// keep previous value // keep previous value