Add new lint: strlen_on_c_strings
This commit is contained in:
parent
3cc6778512
commit
59a164e86c
7 changed files with 141 additions and 0 deletions
16
tests/ui/strlen_on_c_strings.rs
Normal file
16
tests/ui/strlen_on_c_strings.rs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
#![warn(clippy::strlen_on_c_strings)]
|
||||
#![allow(dead_code)]
|
||||
#![feature(rustc_private)]
|
||||
extern crate libc;
|
||||
|
||||
use std::ffi::{CStr, CString};
|
||||
|
||||
fn main() {
|
||||
// CString
|
||||
let cstring = CString::new("foo").expect("CString::new failed");
|
||||
let len = unsafe { libc::strlen(cstring.as_ptr()) };
|
||||
|
||||
// CStr
|
||||
let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
|
||||
let len = unsafe { libc::strlen(cstr.as_ptr()) };
|
||||
}
|
||||
25
tests/ui/strlen_on_c_strings.stderr
Normal file
25
tests/ui/strlen_on_c_strings.stderr
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
error: using `libc::strlen` on a `CString` or `CStr` value
|
||||
--> $DIR/strlen_on_c_strings.rs:11:24
|
||||
|
|
||||
LL | let len = unsafe { libc::strlen(cstring.as_ptr()) };
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
|
||||
= note: `-D clippy::strlen-on-c-strings` implied by `-D warnings`
|
||||
help: try this (you might also need to get rid of `unsafe` block in some cases):
|
||||
|
|
||||
LL | let len = unsafe { cstring.as_bytes().len() };
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error: using `libc::strlen` on a `CString` or `CStr` value
|
||||
--> $DIR/strlen_on_c_strings.rs:15:24
|
||||
|
|
||||
LL | let len = unsafe { libc::strlen(cstr.as_ptr()) };
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
|
||||
help: try this (you might also need to get rid of `unsafe` block in some cases):
|
||||
|
|
||||
LL | let len = unsafe { cstr.to_bytes().len() };
|
||||
| ^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error: aborting due to 2 previous errors
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue