Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clippy fix1 #369

Open
wants to merge 22 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions mbedtls-platform-support/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ use std::env;
fn main() {
let env_components = env::var("DEP_MBEDTLS_PLATFORM_COMPONENTS").unwrap();
let mut sys_platform_components = HashMap::<_, HashSet<_>>::new();
for mut kv in env_components.split(",").map(|component| component.splitn(2, "=")) {
for mut kv in env_components.split(',').map(|component| component.splitn(2, '=')) {
let k = kv.next().unwrap();
let v = kv.next().unwrap();
sys_platform_components.entry(k).or_insert_with(Default::default).insert(v);
println!(r#"cargo:rustc-cfg=sys_{}="{}""#, k, v);
println!(r#"cargo:rustc-cfg=sys_{k}="{v}""#);
}

let mut b = cc::Build::new();
Expand Down
1 change: 1 addition & 0 deletions mbedtls-platform-support/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* option. This file may not be copied, modified, or distributed except
* according to those terms. */

#![allow(unexpected_cfgs)]
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(not(feature = "std"))]
Expand Down
10 changes: 5 additions & 5 deletions mbedtls-platform-support/src/self_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@
* option. This file may not be copied, modified, or distributed except
* according to those terms. */

//! MbedTLS self tests.
//! `MbedTLS` self tests.
//!
//! Calling MbedTLS self test functions before they're enabled using the
//! Calling `MbedTLS` self test functions before they're enabled using the
//! `enable()` function here will result in a panic.
//!
//! Using this module in multithreaded or async environment will fail. The self
//! test functions rely on global variables to track operations and anything
//! non-self-test related operations will clobber these variables, resulting in
//! self test failures. Make sure no other code uses MbedTLS while running the
//! self test failures. Make sure no other code uses `MbedTLS` while running the
//! self tests. Multiple self test operations done simultaneously may also
//! return failures.

Expand Down Expand Up @@ -53,7 +53,7 @@ pub unsafe extern "C" fn rand() -> c_int {
rand_f.expect("Called self-test rand without enabling self-test")()
}

/// Set callback functions to enable the MbedTLS self tests.
/// Set callback functions to enable the `MbedTLS` self tests.
///
/// `rand` only needs to be set on platforms that don't have a `rand()`
/// function in libc. `log` only needs to be set when using `no_std`, i.e.
Expand Down Expand Up @@ -94,7 +94,7 @@ pub unsafe fn disable() {
/// # Safety
///
/// The caller needs to ensure this function is not called while *any other*
/// MbedTLS function is called. See the module documentation for more
/// `MbedTLS` function is called. See the module documentation for more
/// information.
pub use mbedtls_sys::{
aes_self_test as aes, arc4_self_test as arc4, aria_self_test as aria, base64_self_test as base64,
Expand Down
43 changes: 31 additions & 12 deletions mbedtls-sys/build/bindgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ impl bindgen::callbacks::ParseCallbacks for MbedtlsParseCallbacks {
}

fn int_macro(&self, _name: &str, value: i64) -> Option<bindgen::callbacks::IntKind> {
if value < (i32::MIN as i64) || value > (i32::MAX as i64) {
if value < i64::from(i32::MIN) || value > i64::from(i32::MAX) {
Some(bindgen::callbacks::IntKind::LongLong)
} else {
Some(bindgen::callbacks::IntKind::Int)
Expand Down Expand Up @@ -87,7 +87,7 @@ fn generate_deprecated_union_accessors(bindings: &str) -> String {
}

let mut impl_builder = UnionImplBuilder::default();
syn::visit::visit_file(&mut impl_builder, &syn::parse_file(&bindings).unwrap());
syn::visit::visit_file(&mut impl_builder, &syn::parse_file(bindings).unwrap());

impl_builder.impls
}
Expand All @@ -96,7 +96,7 @@ impl super::BuildConfig {
pub fn bindgen(&self) {
let mut input = String::new();
for h in headers::enabled_ordered() {
let _ = writeln!(input, "#include <mbedtls/{}>", h);
let _ = writeln!(input, "#include <mbedtls/{h}>");
}

let mut cc = cc::Build::new();
Expand All @@ -115,14 +115,12 @@ impl super::BuildConfig {
// uses the correct headers
let compiler = cc.get_compiler();
if compiler.is_like_gnu() {
let output = compiler.to_command().args(&["--print-sysroot"]).output();
match output {
Ok(sysroot) => {
let path = std::str::from_utf8(&sysroot.stdout).expect("Malformed sysroot");
let trimmed_path = path.strip_suffix("\r\n").or(path.strip_suffix("\n")).unwrap_or(&path);
cc.flag(&format!("--sysroot={}", trimmed_path));
}
_ => {} // skip toolchains without a configured sysroot
let output = compiler.to_command().args(["--print-sysroot"]).output();
// skip toolchains without a configured sysroot
if let Ok(sysroot) = output {
let path = std::str::from_utf8(&sysroot.stdout).expect("Malformed sysroot");
let trimmed_path = path.strip_suffix("\r\n").or_else(|| path.strip_suffix("\n")).unwrap_or(path);
cc.flag(&format!("--sysroot={trimmed_path}"));
};
}

Expand All @@ -146,7 +144,28 @@ impl super::BuildConfig {
.derive_default(true)
.prepend_enum_name(false)
.translate_enum_integer_types(true)
.raw_line("#![allow(dead_code, deref_nullptr, non_snake_case, non_camel_case_types, non_upper_case_globals, invalid_value)]")
.raw_line("#![allow(")
.raw_line(" dead_code,")
.raw_line(" deref_nullptr,")
.raw_line(" invalid_value,")
.raw_line(" non_snake_case,")
.raw_line(" non_camel_case_types,")
.raw_line(" non_upper_case_globals")
.raw_line(")]")
.raw_line("#![allow(")
.raw_line(" clippy::cast_lossless,")
.raw_line(" clippy::cast_possible_truncation,")
.raw_line(" clippy::default_trait_access,")
.raw_line(" clippy::missing_safety_doc,")
.raw_line(" clippy::must_use_candidate,")
.raw_line(" clippy::pub_underscore_fields,")
.raw_line(" clippy::unreadable_literal,")
.raw_line(" clippy::used_underscore_binding,")
.raw_line(" clippy::useless_transmute,")
.raw_line(" clippy::semicolon_if_nothing_returned,")
.raw_line(" clippy::type_complexity,")
.raw_line(" clippy::wildcard_imports")
.raw_line(")]")
.generate()
.expect("bindgen error")
.to_string();
Expand Down
7 changes: 4 additions & 3 deletions mbedtls-sys/build/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>, at your
* option. This file may not be copied, modified, or distributed except
* according to those terms. */
#![allow(clippy::unwrap_used)]

extern crate bindgen;
extern crate cmake;
Expand Down Expand Up @@ -82,7 +83,7 @@ impl BuildConfig {
fn new() -> Self {
let out_dir = PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR environment not set?"));
let config_h = out_dir.join("config.h");
let mbedtls_src = PathBuf::from(env::var("RUST_MBEDTLS_SYS_SOURCE").unwrap_or("vendor".to_owned()));
let mbedtls_src = PathBuf::from(env::var("RUST_MBEDTLS_SYS_SOURCE").unwrap_or_else(|_| "vendor".to_owned()));
let mbedtls_include = mbedtls_src.join("include");

let mut cflags = vec![];
Expand All @@ -93,11 +94,11 @@ impl BuildConfig {
cflags.push("-fno-stack-protector".into());
}

BuildConfig {
config_h,
Self {
out_dir,
mbedtls_src,
mbedtls_include,
config_h,
cflags,
}
}
Expand Down
4 changes: 1 addition & 3 deletions mbedtls-sys/build/cmake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ impl super::BuildConfig {
}

println!("cargo:rerun-if-env-changed=RUST_MBED_C_COMPILER_BAREMETAL");
let c_compiler_baremetal = std::env::var("RUST_MBED_C_COMPILER_BAREMETAL")
.map(|val| val == "1")
.unwrap_or_default();
let c_compiler_baremetal = std::env::var("RUST_MBED_C_COMPILER_BAREMETAL").is_ok_and(|val| val == "1");

let target = std::env::var("TARGET").expect("TARGET environment variable should be set in build scripts");
// thumbv6m-none-eabi, thumbv7em-none-eabi, thumbv7em-none-eabihf,
Expand Down
35 changes: 19 additions & 16 deletions mbedtls-sys/build/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,28 +15,28 @@ pub enum Macro {
#[allow(dead_code)]
DefinedAs(&'static str),
}
use self::Macro::*;
use self::Macro::{Defined, DefinedAs, Undefined};

impl Macro {
pub fn define(self, name: &'static str) -> String {
match self {
Undefined => String::new(),
Defined => format!("#define {}\n", name),
DefinedAs(v) => format!("#define {} {}\n", name, v),
Defined => format!("#define {name}\n"),
DefinedAs(v) => format!("#define {name} {v}\n"),
}
}
}

pub type CDefine = (&'static str, Macro);

pub const PREFIX: &'static str = r#"
pub const PREFIX: &str = r"
Taowyoo marked this conversation as resolved.
Show resolved Hide resolved
#ifndef MBEDTLS_CONFIG_H
#define MBEDTLS_CONFIG_H

#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
#define _CRT_SECURE_NO_DEPRECATE 1
#endif
"#;
";

/*

Expand Down Expand Up @@ -64,8 +64,8 @@ for line in open('vendor/include/mbedtls/config.h').readlines():
print format(match.group(1), "Undefined") + (" // default: %s" % (match.group(2)))
*/

#[cfg_attr(rustfmt, rustfmt_skip)]
const DEFAULT_DEFINES: &'static [CDefine] = &[
#[rustfmt::skip]
const DEFAULT_DEFINES: &[CDefine] = &[
("MBEDTLS_HAVE_ASM", Defined),
("MBEDTLS_NO_UDBL_DIVISION", Undefined),
("MBEDTLS_NO_64BIT_MULTIPLICATION", Undefined),
Expand Down Expand Up @@ -408,17 +408,20 @@ const DEFAULT_DEFINES: &'static [CDefine] = &[
pub fn default_defines() -> HashMap<&'static str, Macro> {
let mut defines = HashMap::new();

for (key, value) in DEFAULT_DEFINES.iter() {
if defines.insert(*key, *value).is_some() {
panic!("Duplicate default define in {}: {}", file!(), key);
}
for (key, value) in DEFAULT_DEFINES {
assert!(
defines.insert(*key, *value).is_none(),
"Duplicate default define in {}: {}",
file!(),
key
);
}

defines
}

#[cfg_attr(rustfmt, rustfmt_skip)]
pub const FEATURE_DEFINES: &'static [(&'static str, CDefine)] = &[
#[rustfmt::skip]
pub const FEATURE_DEFINES: &[(&str, CDefine)] = &[
("time", ("MBEDTLS_HAVE_TIME", Defined)),
("time", ("MBEDTLS_HAVE_TIME_DATE", Defined)),
("havege", ("MBEDTLS_HAVEGE_C", Defined)),
Expand All @@ -442,8 +445,8 @@ pub const FEATURE_DEFINES: &'static [(&'static str, CDefine)] = &[
("trusted_cert_callback", ("MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK", Defined)),
];

#[cfg_attr(rustfmt, rustfmt_skip)]
pub const PLATFORM_DEFINES: &'static [(&'static str, &'static str, CDefine)] = &[
#[rustfmt::skip]
pub const PLATFORM_DEFINES: &[(&str, &str, CDefine)] = &[
("time", "libc", ("MBEDTLS_TIMING_C", Defined)),
("time", "custom", ("MBEDTLS_PLATFORM_TIME_MACRO", DefinedAs("mbedtls_time"))),
("time", "custom", ("MBEDTLS_PLATFORM_TIME_TYPE_MACRO", DefinedAs("long long"))),
Expand All @@ -456,7 +459,7 @@ pub const PLATFORM_DEFINES: &'static [(&'static str, &'static str, CDefine)] = &
("std", "entropy", ("MBEDTLS_ENTROPY_C", Defined)),
];

pub const SUFFIX: &'static str = r#"
pub const SUFFIX: &str = r#"
#if defined(TARGET_LIKE_MBED)
#include "mbedtls/target_config.h"
#endif
Expand Down
12 changes: 7 additions & 5 deletions mbedtls-sys/build/features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ impl Features {

for (feature, components) in &self.platform_components {
for component in components {
println!(r#"cargo:rustc-cfg={}_component="{}""#, feature, component);
println!(r#"cargo:rustc-cfg={feature}_component="{component}""#);
}
}
println!(
Expand All @@ -69,7 +69,7 @@ impl Features {
.flat_map(|(feature, components)| {
components
.iter()
.map(move |component| format!(r#"{}_component={}"#, feature, component))
.map(move |component| format!(r#"{feature}_component={component}"#))
})
.collect::<Vec<_>>()
.join(",")
Expand All @@ -78,7 +78,9 @@ impl Features {

fn with_feature(&mut self, feature: &'static str) -> Option<&mut HashSet<&'static str>> {
if self.have_feature(feature) {
Some(self.platform_components.entry(feature).or_insert_with(HashSet::new))
Some(self.platform_components.entry(feature).or_default())
//This should be the same
//Some(self.platform_components.entry(feature).or_insert_with(HashSet::new))
} else {
None
}
Expand All @@ -96,11 +98,11 @@ impl Features {
}

fn env_have_target_cfg(var: &'static str, value: &'static str) -> bool {
let env = format!("CARGO_CFG_TARGET_{}", var).to_uppercase().replace("-", "_");
let env = format!("CARGO_CFG_TARGET_{var}").to_uppercase().replace('-', "_");
env::var_os(env).map_or(false, |s| s == value)
}

fn env_have_feature(feature: &'static str) -> bool {
let env = format!("CARGO_FEATURE_{}", feature).to_uppercase().replace("-", "_");
let env = format!("CARGO_FEATURE_{feature}").to_uppercase().replace('-', "_");
env::var_os(env).is_some()
}
4 changes: 2 additions & 2 deletions mbedtls-sys/build/headers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ use crate::features::FEATURES;
* )
*/

#[cfg_attr(rustfmt, rustfmt_skip)]
pub const ORDERED: &'static [(Option<&'static str>, &'static str)] = &[
#[rustfmt::skip]
pub const ORDERED: &[(Option<&'static str>, &str)] = &[
(None, "config_psa.h"),
(None, "platform_time.h"),
(None, "platform_util.h"),
Expand Down
1 change: 1 addition & 0 deletions mbedtls-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* option. This file may not be copied, modified, or distributed except
* according to those terms. */

#![allow(unexpected_cfgs)]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
extern crate core;
Expand Down
2 changes: 1 addition & 1 deletion mbedtls-sys/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* option. This file may not be copied, modified, or distributed except
* according to those terms. */

#![allow(non_camel_case_types)]
#![allow(non_camel_case_types, clippy::module_name_repetitions)]

pub type int8_t = i8;
pub type int16_t = i16;
Expand Down
15 changes: 8 additions & 7 deletions mbedtls/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>, at your
* option. This file may not be copied, modified, or distributed except
* according to those terms. */
#![allow(clippy::unwrap_used)]

use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, HashSet};
Expand All @@ -14,8 +15,8 @@ use rustc_version::Channel;
use std::env;

/// Retrieves or generates a metadata value used for symbol name mangling to ensure unique C symbols.
/// When building with Cargo, the metadata value is extracted from the OUT_DIR environment variable.
/// For Bazel builds, this method generate the suffix by hashing part of the crate OUT_DIR,
/// When building with Cargo, the metadata value is extracted from the `OUT_DIR` environment variable.
/// For Bazel builds, this method generate the suffix by hashing part of the crate `OUT_DIR`,
/// which are sufficient for ensuring symbol uniqueness.
fn get_compilation_symbol_suffix() -> String {
let out_dir: std::path::PathBuf = std::env::var_os("OUT_DIR").unwrap().into();
Expand All @@ -31,15 +32,15 @@ fn get_compilation_symbol_suffix() -> String {
crate_.starts_with("mbedtls-"),
"Expected second to last component of OUT_DIR to start with 'mbedtls-'"
);
return crate_[8..].to_owned(); // Return the part after "mbedtls-"
crate_[8..].to_owned() // Return the part after "mbedtls-"
} else if out_dir.iter().rfind(|p| *p == "bazel-out").is_some() {
// If Bazel is used as build system.
let mut hasher = DefaultHasher::new();
// Reverse the iterator and hash until we find "bazel-out"
for p in out_dir.iter().rev().take_while(|p| *p != "bazel-out") {
p.hash(&mut hasher);
}
return format!("{:016x}", hasher.finish());
format!("{:016x}", hasher.finish())
} else {
panic!("unexpected OUT_DIR format: {}", out_dir.display());
}
Expand All @@ -51,16 +52,16 @@ fn main() {
println!("cargo:rustc-cfg=nightly");
}
let symbol_suffix = get_compilation_symbol_suffix();
println!("cargo:rustc-env=RUST_MBEDTLS_SYMBOL_SUFFIX={}", symbol_suffix);
println!("cargo:rustc-env=RUST_MBEDTLS_SYMBOL_SUFFIX={symbol_suffix}");
println!("cargo:rerun-if-env-changed=CARGO_PKG_VERSION");

let env_components = env::var("DEP_MBEDTLS_PLATFORM_COMPONENTS").unwrap();
let mut sys_platform_components = HashMap::<_, HashSet<_>>::new();
for mut kv in env_components.split(",").map(|component| component.splitn(2, "=")) {
for mut kv in env_components.split(',').map(|component| component.splitn(2, '=')) {
let k = kv.next().unwrap();
let v = kv.next().unwrap();
sys_platform_components.entry(k).or_insert_with(Default::default).insert(v);
println!(r#"cargo:rustc-cfg=sys_{}="{}""#, k, v);
println!(r#"cargo:rustc-cfg=sys_{k}="{v}""#);
}

let mut b = cc::Build::new();
Expand Down
Loading
Loading