Skip to content

Commit c387f01

Browse files
committed
Auto merge of #118154 - ChrisDenton:win-clippy, r=scottmcm
Fix some clippy lints for library/std/src/sys/windows These issues were shown by running `x clippy` on `library/std` and filtering for `windows/` paths. I think running clippy on the full std would be great but I wanted to start smaller and with something that's hopefully easier to review. It'd be good to eventually run clippy in CI but that's a bigger conversation. I've created separate commits for each clippy lint fixed (with the commit title set to the lint name) and reviewed the changes myself. Most of the fixes here are trivial. r? libs
2 parents 1e9dda7 + b9fe367 commit c387f01

File tree

14 files changed

+43
-45
lines changed

14 files changed

+43
-45
lines changed

Diff for: library/std/src/os/windows/io/handle.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -504,7 +504,7 @@ impl AsHandle for fs::File {
504504
impl From<fs::File> for OwnedHandle {
505505
#[inline]
506506
fn from(file: fs::File) -> OwnedHandle {
507-
file.into_inner().into_inner().into_inner().into()
507+
file.into_inner().into_inner().into_inner()
508508
}
509509
}
510510

Diff for: library/std/src/os/windows/io/socket.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ impl BorrowedSocket<'_> {
127127
info.iAddressFamily,
128128
info.iSocketType,
129129
info.iProtocol,
130-
&mut info,
130+
&info,
131131
0,
132132
sys::c::WSA_FLAG_OVERLAPPED | sys::c::WSA_FLAG_NO_HANDLE_INHERIT,
133133
)
@@ -147,7 +147,7 @@ impl BorrowedSocket<'_> {
147147
info.iAddressFamily,
148148
info.iSocketType,
149149
info.iProtocol,
150-
&mut info,
150+
&info,
151151
0,
152152
sys::c::WSA_FLAG_OVERLAPPED,
153153
)

Diff for: library/std/src/sys/windows/api.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ pub fn set_file_information_by_handle<T: SetFileInformation>(
132132
size: u32,
133133
) -> Result<(), WinError> {
134134
let result = c::SetFileInformationByHandle(handle, class, info, size);
135-
(result != 0).then_some(()).ok_or_else(|| get_last_error())
135+
(result != 0).then_some(()).ok_or_else(get_last_error)
136136
}
137137
// SAFETY: The `SetFileInformation` trait ensures that this is safe.
138138
unsafe { set_info(handle, T::CLASS, info.as_ptr(), info.size()) }

Diff for: library/std/src/sys/windows/c.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#![allow(nonstandard_style)]
44
#![cfg_attr(test, allow(dead_code))]
55
#![unstable(issue = "none", feature = "windows_c")]
6+
#![allow(clippy::style)]
67

78
use crate::ffi::CStr;
89
use crate::mem;
@@ -81,7 +82,7 @@ pub fn nt_success(status: NTSTATUS) -> bool {
8182

8283
impl UNICODE_STRING {
8384
pub fn from_ref(slice: &[u16]) -> Self {
84-
let len = slice.len() * mem::size_of::<u16>();
85+
let len = mem::size_of_val(slice);
8586
Self { Length: len as _, MaximumLength: len as _, Buffer: slice.as_ptr() as _ }
8687
}
8788
}

Diff for: library/std/src/sys/windows/fs.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ impl DirEntry {
156156
}
157157

158158
pub fn path(&self) -> PathBuf {
159-
self.root.join(&self.file_name())
159+
self.root.join(self.file_name())
160160
}
161161

162162
pub fn file_name(&self) -> OsString {
@@ -548,7 +548,7 @@ impl File {
548548
let user = super::args::from_wide_to_user_path(
549549
subst.iter().copied().chain([0]).collect(),
550550
)?;
551-
Ok(PathBuf::from(OsString::from_wide(&user.strip_suffix(&[0]).unwrap_or(&user))))
551+
Ok(PathBuf::from(OsString::from_wide(user.strip_suffix(&[0]).unwrap_or(&user))))
552552
} else {
553553
Ok(PathBuf::from(OsString::from_wide(subst)))
554554
}
@@ -786,7 +786,7 @@ fn open_link_no_reparse(parent: &File, name: &[u16], access: u32) -> io::Result<
786786
// tricked into following a symlink. However, it may not be available in
787787
// earlier versions of Windows.
788788
static ATTRIBUTES: AtomicU32 = AtomicU32::new(c::OBJ_DONT_REPARSE);
789-
let mut object = c::OBJECT_ATTRIBUTES {
789+
let object = c::OBJECT_ATTRIBUTES {
790790
ObjectName: &mut name_str,
791791
RootDirectory: parent.as_raw_handle(),
792792
Attributes: ATTRIBUTES.load(Ordering::Relaxed),
@@ -795,7 +795,7 @@ fn open_link_no_reparse(parent: &File, name: &[u16], access: u32) -> io::Result<
795795
let status = c::NtCreateFile(
796796
&mut handle,
797797
access,
798-
&mut object,
798+
&object,
799799
&mut io_status,
800800
crate::ptr::null_mut(),
801801
0,
@@ -874,7 +874,7 @@ impl fmt::Debug for File {
874874
// FIXME(#24570): add more info here (e.g., mode)
875875
let mut b = f.debug_struct("File");
876876
b.field("handle", &self.handle.as_raw_handle());
877-
if let Ok(path) = get_path(&self) {
877+
if let Ok(path) = get_path(self) {
878878
b.field("path", &path);
879879
}
880880
b.finish()
@@ -1193,7 +1193,7 @@ pub fn readlink(path: &Path) -> io::Result<PathBuf> {
11931193
let mut opts = OpenOptions::new();
11941194
opts.access_mode(0);
11951195
opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
1196-
let file = File::open(&path, &opts)?;
1196+
let file = File::open(path, &opts)?;
11971197
file.readlink()
11981198
}
11991199

@@ -1407,7 +1407,7 @@ pub fn symlink_junction<P: AsRef<Path>, Q: AsRef<Path>>(
14071407
#[allow(dead_code)]
14081408
fn symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()> {
14091409
let d = DirBuilder::new();
1410-
d.mkdir(&junction)?;
1410+
d.mkdir(junction)?;
14111411

14121412
let mut opts = OpenOptions::new();
14131413
opts.write(true);

Diff for: library/std/src/sys/windows/handle.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ impl Handle {
8181
let res = unsafe { self.synchronous_read(buf.as_mut_ptr().cast(), buf.len(), None) };
8282

8383
match res {
84-
Ok(read) => Ok(read as usize),
84+
Ok(read) => Ok(read),
8585

8686
// The special treatment of BrokenPipe is to deal with Windows
8787
// pipe semantics, which yields this error when *reading* from
@@ -107,7 +107,7 @@ impl Handle {
107107
unsafe { self.synchronous_read(buf.as_mut_ptr().cast(), buf.len(), Some(offset)) };
108108

109109
match res {
110-
Ok(read) => Ok(read as usize),
110+
Ok(read) => Ok(read),
111111
Err(ref e) if e.raw_os_error() == Some(c::ERROR_HANDLE_EOF as i32) => Ok(0),
112112
Err(e) => Err(e),
113113
}
@@ -121,7 +121,7 @@ impl Handle {
121121
Ok(read) => {
122122
// Safety: `read` bytes were written to the initialized portion of the buffer
123123
unsafe {
124-
cursor.advance(read as usize);
124+
cursor.advance(read);
125125
}
126126
Ok(())
127127
}
@@ -189,7 +189,7 @@ impl Handle {
189189
}
190190

191191
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
192-
self.synchronous_write(&buf, None)
192+
self.synchronous_write(buf, None)
193193
}
194194

195195
pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
@@ -202,7 +202,7 @@ impl Handle {
202202
}
203203

204204
pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
205-
self.synchronous_write(&buf, Some(offset))
205+
self.synchronous_write(buf, Some(offset))
206206
}
207207

208208
pub fn try_clone(&self) -> io::Result<Self> {

Diff for: library/std/src/sys/windows/io.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ impl<'a> IoSlice<'a> {
3636

3737
#[inline]
3838
pub fn as_slice(&self) -> &[u8] {
39-
unsafe { slice::from_raw_parts(self.vec.buf as *mut u8, self.vec.len as usize) }
39+
unsafe { slice::from_raw_parts(self.vec.buf, self.vec.len as usize) }
4040
}
4141
}
4242

@@ -70,12 +70,12 @@ impl<'a> IoSliceMut<'a> {
7070

7171
#[inline]
7272
pub fn as_slice(&self) -> &[u8] {
73-
unsafe { slice::from_raw_parts(self.vec.buf as *mut u8, self.vec.len as usize) }
73+
unsafe { slice::from_raw_parts(self.vec.buf, self.vec.len as usize) }
7474
}
7575

7676
#[inline]
7777
pub fn as_mut_slice(&mut self) -> &mut [u8] {
78-
unsafe { slice::from_raw_parts_mut(self.vec.buf as *mut u8, self.vec.len as usize) }
78+
unsafe { slice::from_raw_parts_mut(self.vec.buf, self.vec.len as usize) }
7979
}
8080
}
8181

Diff for: library/std/src/sys/windows/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ pub unsafe fn init(_argc: isize, _argv: *const *const u8, _sigpipe: u8) {
6363

6464
// Normally, `thread::spawn` will call `Thread::set_name` but since this thread already
6565
// exists, we have to call it ourselves.
66-
thread::Thread::set_name(&CStr::from_bytes_with_nul_unchecked(b"main\0"));
66+
thread::Thread::set_name(CStr::from_bytes_with_nul_unchecked(b"main\0"));
6767
}
6868

6969
// SAFETY: must be called only once during runtime cleanup.
@@ -150,7 +150,7 @@ pub fn decode_error_kind(errno: i32) -> ErrorKind {
150150

151151
pub fn unrolled_find_u16s(needle: u16, haystack: &[u16]) -> Option<usize> {
152152
let ptr = haystack.as_ptr();
153-
let mut start = &haystack[..];
153+
let mut start = haystack;
154154

155155
// For performance reasons unfold the loop eight times.
156156
while start.len() >= 8 {

Diff for: library/std/src/sys/windows/net.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,7 @@ impl Socket {
162162

163163
let mut timeout = c::timeval {
164164
tv_sec: cmp::min(timeout.as_secs(), c_long::MAX as u64) as c_long,
165-
tv_usec: (timeout.subsec_nanos() / 1000) as c_long,
165+
tv_usec: timeout.subsec_micros() as c_long,
166166
};
167167

168168
if timeout.tv_sec == 0 && timeout.tv_usec == 0 {

Diff for: library/std/src/sys/windows/os.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,7 @@ pub fn getenv(k: &OsStr) -> Option<OsString> {
297297
let k = to_u16s(k).ok()?;
298298
super::fill_utf16_buf(
299299
|buf, sz| unsafe { c::GetEnvironmentVariableW(k.as_ptr(), buf, sz) },
300-
|buf| OsStringExt::from_wide(buf),
300+
OsStringExt::from_wide,
301301
)
302302
.ok()
303303
}
@@ -356,13 +356,13 @@ pub fn home_dir() -> Option<PathBuf> {
356356
crate::env::var_os("HOME")
357357
.or_else(|| crate::env::var_os("USERPROFILE"))
358358
.map(PathBuf::from)
359-
.or_else(|| home_dir_crt())
359+
.or_else(home_dir_crt)
360360
}
361361

362362
pub fn exit(code: i32) -> ! {
363363
unsafe { c::ExitProcess(code as c::UINT) }
364364
}
365365

366366
pub fn getpid() -> u32 {
367-
unsafe { c::GetCurrentProcessId() as u32 }
367+
unsafe { c::GetCurrentProcessId() }
368368
}

Diff for: library/std/src/sys/windows/path.rs

+5-7
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ impl<'a> PrefixParserSlice<'a, '_> {
7878
fn strip_prefix(&self, prefix: &str) -> Option<Self> {
7979
self.prefix[self.index..]
8080
.starts_with(prefix.as_bytes())
81-
.then(|| Self { index: self.index + prefix.len(), ..*self })
81+
.then_some(Self { index: self.index + prefix.len(), ..*self })
8282
}
8383

8484
fn prefix_bytes(&self) -> &'a [u8] {
@@ -147,12 +147,10 @@ pub fn parse_prefix(path: &OsStr) -> Option<Prefix<'_>> {
147147
None
148148
}
149149
}
150-
} else if let Some(drive) = parse_drive(path) {
151-
// C:
152-
Some(Disk(drive))
153150
} else {
154-
// no prefix
155-
None
151+
// If it has a drive like `C:` then it's a disk.
152+
// Otherwise there is no prefix.
153+
parse_drive(path).map(Disk)
156154
}
157155
}
158156

@@ -252,7 +250,7 @@ pub(crate) fn get_long_path(mut path: Vec<u16>, prefer_verbatim: bool) -> io::Re
252250
// \\?\UNC\
253251
const UNC_PREFIX: &[u16] = &[SEP, SEP, QUERY, SEP, U, N, C, SEP];
254252

255-
if path.starts_with(VERBATIM_PREFIX) || path.starts_with(NT_PREFIX) || path == &[0] {
253+
if path.starts_with(VERBATIM_PREFIX) || path.starts_with(NT_PREFIX) || path == [0] {
256254
// Early return for paths that are already verbatim or empty.
257255
return Ok(path);
258256
} else if path.len() < LEGACY_MAX_PATH {

Diff for: library/std/src/sys/windows/process.rs

+5-6
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ impl Command {
245245
}
246246

247247
pub fn get_current_dir(&self) -> Option<&Path> {
248-
self.cwd.as_ref().map(|cwd| Path::new(cwd))
248+
self.cwd.as_ref().map(Path::new)
249249
}
250250

251251
pub unsafe fn raw_attribute<T: Copy + Send + Sync + 'static>(
@@ -463,7 +463,7 @@ fn resolve_exe<'a>(
463463

464464
// Search the directories given by `search_paths`.
465465
let result = search_paths(parent_paths, child_paths, |mut path| {
466-
path.push(&exe_path);
466+
path.push(exe_path);
467467
if !has_extension {
468468
path.set_extension(EXE_EXTENSION);
469469
}
@@ -657,7 +657,7 @@ impl Process {
657657
}
658658

659659
pub fn id(&self) -> u32 {
660-
unsafe { c::GetProcessId(self.handle.as_raw_handle()) as u32 }
660+
unsafe { c::GetProcessId(self.handle.as_raw_handle()) }
661661
}
662662

663663
pub fn main_thread_handle(&self) -> BorrowedHandle<'_> {
@@ -917,9 +917,8 @@ fn make_proc_thread_attribute_list(
917917
)
918918
};
919919

920-
let mut proc_thread_attribute_list = ProcThreadAttributeList(
921-
vec![MaybeUninit::uninit(); required_size as usize].into_boxed_slice(),
922-
);
920+
let mut proc_thread_attribute_list =
921+
ProcThreadAttributeList(vec![MaybeUninit::uninit(); required_size].into_boxed_slice());
923922

924923
// Once we've allocated the necessary memory, it's safe to invoke
925924
// `InitializeProcThreadAttributeList` to properly initialize the list.

Diff for: library/std/src/sys/windows/stdio.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ fn write_valid_utf8_to_console(handle: c::HANDLE, utf8: &str) -> io::Result<usiz
195195
MaybeUninit::slice_assume_init_ref(&utf16[..result as usize])
196196
};
197197

198-
let mut written = write_u16s(handle, &utf16)?;
198+
let mut written = write_u16s(handle, utf16)?;
199199

200200
// Figure out how many bytes of as UTF-8 were written away as UTF-16.
201201
if written == utf16.len() {
@@ -207,7 +207,7 @@ fn write_valid_utf8_to_console(handle: c::HANDLE, utf8: &str) -> io::Result<usiz
207207
// write the missing surrogate out now.
208208
// Buffering it would mean we have to lie about the number of bytes written.
209209
let first_code_unit_remaining = utf16[written];
210-
if first_code_unit_remaining >= 0xDCEE && first_code_unit_remaining <= 0xDFFF {
210+
if matches!(first_code_unit_remaining, 0xDCEE..=0xDFFF) {
211211
// low surrogate
212212
// We just hope this works, and give up otherwise
213213
let _ = write_u16s(handle, &utf16[written..written + 1]);
@@ -266,7 +266,7 @@ impl io::Read for Stdin {
266266
let mut bytes_copied = self.incomplete_utf8.read(buf);
267267

268268
if bytes_copied == buf.len() {
269-
return Ok(bytes_copied);
269+
Ok(bytes_copied)
270270
} else if buf.len() - bytes_copied < 4 {
271271
// Not enough space to get a UTF-8 byte. We will use the incomplete UTF8.
272272
let mut utf16_buf = [MaybeUninit::new(0); 1];
@@ -332,7 +332,7 @@ fn read_u16s_fixup_surrogates(
332332
// and it is not 0, so we know that `buf[amount - 1]` have been
333333
// initialized.
334334
let last_char = unsafe { buf[amount - 1].assume_init() };
335-
if last_char >= 0xD800 && last_char <= 0xDBFF {
335+
if matches!(last_char, 0xD800..=0xDBFF) {
336336
// high surrogate
337337
*surrogate = last_char;
338338
amount -= 1;

Diff for: library/std/src/sys/windows/time.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::cmp::Ordering;
22
use crate::fmt;
33
use crate::mem;
4-
use crate::ptr::{null, null_mut};
4+
use crate::ptr::null;
55
use crate::sys::c;
66
use crate::sys_common::IntoInner;
77
use crate::time::Duration;
@@ -240,7 +240,7 @@ impl WaitableTimer {
240240
c::TIMER_ALL_ACCESS,
241241
)
242242
};
243-
if handle != null_mut() { Ok(Self { handle }) } else { Err(()) }
243+
if !handle.is_null() { Ok(Self { handle }) } else { Err(()) }
244244
}
245245
pub fn set(&self, duration: Duration) -> Result<(), ()> {
246246
// Convert the Duration to a format similar to FILETIME.

0 commit comments

Comments
 (0)