misc clippy fixes

the trivial ones ;)

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
This commit is contained in:
Fabian Grünbichler 2022-02-08 14:57:16 +01:00
parent bb9e503964
commit dcf5a0f62d
32 changed files with 74 additions and 84 deletions

View File

@ -53,20 +53,18 @@ impl SizeUnit {
11..=20 => SizeUnit::Kibi,
_ => SizeUnit::Byte,
}
} else if size >= 1_000_000_000_000_000.0 {
SizeUnit::PByte
} else if size >= 1_000_000_000_000.0 {
SizeUnit::TByte
} else if size >= 1_000_000_000.0 {
SizeUnit::GByte
} else if size >= 1_000_000.0 {
SizeUnit::MByte
} else if size >= 1_000.0 {
SizeUnit::KByte
} else {
if size >= 1_000_000_000_000_000.0 {
SizeUnit::PByte
} else if size >= 1_000_000_000_000.0 {
SizeUnit::TByte
} else if size >= 1_000_000_000.0 {
SizeUnit::GByte
} else if size >= 1_000_000.0 {
SizeUnit::MByte
} else if size >= 1_000.0 {
SizeUnit::KByte
} else {
SizeUnit::Byte
}
SizeUnit::Byte
}
}
}

View File

@ -22,7 +22,7 @@ pub const OPENID_SCOPE_ARRAY_SCHEMA: Schema = ArraySchema::new(
pub const OPENID_SCOPE_LIST_FORMAT: ApiStringFormat =
ApiStringFormat::PropertyString(&OPENID_SCOPE_ARRAY_SCHEMA);
pub const OPENID_DEFAILT_SCOPE_LIST: &'static str = "email profile";
pub const OPENID_DEFAILT_SCOPE_LIST: &str = "email profile";
pub const OPENID_SCOPE_LIST_SCHEMA: Schema = StringSchema::new("OpenID Scope List")
.format(&OPENID_SCOPE_LIST_FORMAT)
.default(OPENID_DEFAILT_SCOPE_LIST)

View File

@ -351,14 +351,14 @@ impl HttpClient {
let mut https = HttpsConnector::with_connector(httpc, ssl_connector_builder.build(), PROXMOX_BACKUP_TCP_KEEPALIVE_TIME);
if let Some(rate_in) = options.limit.rate_in {
let burst_in = options.limit.burst_in.unwrap_or_else(|| rate_in).as_u64();
let burst_in = options.limit.burst_in.unwrap_or(rate_in).as_u64();
https.set_read_limiter(Some(Arc::new(Mutex::new(
RateLimiter::new(rate_in.as_u64(), burst_in)
))));
}
if let Some(rate_out) = options.limit.rate_out {
let burst_out = options.limit.burst_out.unwrap_or_else(|| rate_out).as_u64();
let burst_out = options.limit.burst_out.unwrap_or(rate_out).as_u64();
https.set_write_limiter(Some(Arc::new(Mutex::new(
RateLimiter::new(rate_out.as_u64(), burst_out)
))));

View File

@ -349,7 +349,7 @@ pub fn get_encryption_key_password() -> Result<Vec<u8>, Error> {
// If we're on a TTY, query the user for a password
if tty::stdin_isatty() {
return Ok(tty::read_password("Encryption Key Password: ")?);
return tty::read_password("Encryption Key Password: ");
}
bail!("no password input mechanism available");

View File

@ -119,7 +119,7 @@ impl KeyConfig {
/// Creates a new, unencrypted key.
pub fn without_password(raw_key: [u8; 32]) -> Result<Self, Error> {
// always compute fingerprint
let crypt_config = CryptConfig::new(raw_key.clone())?;
let crypt_config = CryptConfig::new(raw_key)?;
let fingerprint = Some(Fingerprint::new(crypt_config.fingerprint()));
let created = proxmox_time::epoch_i64();
@ -186,7 +186,7 @@ impl KeyConfig {
let created = proxmox_time::epoch_i64();
// always compute fingerprint
let crypt_config = CryptConfig::new(raw_key.clone())?;
let crypt_config = CryptConfig::new(*raw_key)?;
let fingerprint = Some(Fingerprint::new(crypt_config.fingerprint()));
Ok(Self {
@ -257,7 +257,7 @@ impl KeyConfig {
let mut result = [0u8; 32];
result.copy_from_slice(&key);
let crypt_config = CryptConfig::new(result.clone())?;
let crypt_config = CryptConfig::new(result)?;
let fingerprint = Fingerprint::new(crypt_config.fingerprint());
if let Some(ref stored_fingerprint) = self.fingerprint {
if &fingerprint != stored_fingerprint {

View File

@ -492,7 +492,7 @@ mod test {
let input = "";
let mut parser = NetworkParser::new(&input.as_bytes()[..]);
let mut parser = NetworkParser::new(input.as_bytes());
let config = parser.parse_interfaces(None)?;
@ -502,7 +502,7 @@ mod test {
assert_eq!(output, expected);
// run again using output as input
let mut parser = NetworkParser::new(&output.as_bytes()[..]);
let mut parser = NetworkParser::new(output.as_bytes());
let config = parser.parse_interfaces(None)?;
@ -518,7 +518,7 @@ mod test {
let input = "#c1\n\n#c2\n\niface test inet manual\n";
let mut parser = NetworkParser::new(&input.as_bytes()[..]);
let mut parser = NetworkParser::new(input.as_bytes());
let config = parser.parse_interfaces(None)?;
@ -546,7 +546,7 @@ mod test {
iface ens21 inet manual\n\
iface ens22 inet manual\n";
let mut parser = NetworkParser::new(&input.as_bytes()[..]);
let mut parser = NetworkParser::new(input.as_bytes());
let config = parser.parse_interfaces(None)?;
@ -597,7 +597,7 @@ mod test {
\taddress fe80::5496:35ff:fe99:5a6a/64\n\
\tgateway fe80::1\n";
let mut parser = NetworkParser::new(&input.as_bytes()[..]);
let mut parser = NetworkParser::new(input.as_bytes());
let config = parser.parse_interfaces(None)?;

View File

@ -421,7 +421,7 @@ impl <R: BufRead> NetworkParser<R> {
address_family_v6 = true;
}
if let Some(mut interface) = config.interfaces.get_mut(&iface) {
if let Some(interface) = config.interfaces.get_mut(&iface) {
if address_family_v4 {
set_method_v4(interface, config_method)?;
}
@ -429,7 +429,7 @@ impl <R: BufRead> NetworkParser<R> {
set_method_v6(interface, config_method)?;
}
self.parse_iface_attributes(&mut interface, address_family_v4, address_family_v6)?;
self.parse_iface_attributes(interface, address_family_v4, address_family_v6)?;
} else {
let mut interface = Interface::new(iface.clone());
if address_family_v4 {

View File

@ -167,10 +167,8 @@ pub fn insert_key(key: [u8;32], key_config: KeyConfig, force: bool) -> Result<()
None => bail!("missing encryption key fingerprint - internal error"),
};
if !force {
if config_map.get(&fingerprint).is_some() {
bail!("encryption key '{}' already exists.", fingerprint);
}
if !force && config_map.get(&fingerprint).is_some() {
bail!("encryption key '{}' already exists.", fingerprint);
}
let item = EncryptionKeyInfo::new(key, fingerprint.clone());

View File

@ -281,7 +281,7 @@ impl BackupDir {
pub fn backup_time_to_string(backup_time: i64) -> Result<String, Error> {
// fixme: can this fail? (avoid unwrap)
Ok(proxmox_time::epoch_to_rfc3339_utc(backup_time)?)
proxmox_time::epoch_to_rfc3339_utc(backup_time)
}
}

View File

@ -356,7 +356,7 @@ impl DataStore {
full_path.push(backup_group.group_path());
full_path.push("owner");
let owner = proxmox_sys::fs::file_read_firstline(full_path)?;
Ok(owner.trim_end().parse()?) // remove trailing newline
owner.trim_end().parse() // remove trailing newline
}
pub fn owns_backup(&self, backup_group: &BackupGroup, auth_id: &Authid) -> Result<bool, Error> {

View File

@ -714,7 +714,7 @@ impl<R: ReadChunk> ReadAt for LocalDynamicReadAt<R> {
MaybeReady::Ready(tokio::task::block_in_place(move || {
let mut reader = self.inner.lock().unwrap();
reader.seek(SeekFrom::Start(offset))?;
Ok(reader.read(buf)?)
reader.read(buf)
}))
}

View File

@ -243,7 +243,7 @@ fn unload(
if let Some(to_slot) = status.find_free_slot(false) {
sg_pt_changer::unload(&mut file, to_slot, drivenum)?;
return Ok(());
Ok(())
} else {
bail!("Drive '{}' unload failure - no free slot", drivenum);
}

View File

@ -116,13 +116,13 @@ impl <R: BlockRead> BlockedReader<R> {
proxmox_sys::io_bail!("detected tape block after block-stream end marker");
}
Err(BlockReadError::EndOfFile) => {
return Ok(());
Ok(())
}
Err(BlockReadError::EndOfStream) => {
proxmox_sys::io_bail!("got unexpected end of tape");
}
Err(BlockReadError::Error(err)) => {
return Err(err);
Err(err)
}
}
}

View File

@ -471,7 +471,7 @@ pub fn read_element_status<F: AsRawFd>(file: &mut F) -> Result<MtxStatus, Error>
for drive in status.drives.iter_mut() {
if let Some(source_address) = drive.loaded_slot {
let source_address = source_address as u16;
drive.loaded_slot = slot_map.get(&source_address).map(|v| *v);
drive.loaded_slot = slot_map.get(&source_address).copied();
}
}
@ -672,7 +672,7 @@ fn decode_element_status_page(
import_export_slots: Vec::new(),
};
let mut reader = &data[..];
let mut reader = data;
let head: ElementStatusHeader = unsafe { reader.read_be_value()? };
@ -715,7 +715,7 @@ fn decode_element_status_page(
}
for descriptor in descr_data.chunks_exact(descr_len) {
let mut reader = &descriptor[..];
let mut reader = descriptor;
match subhead.element_type_code {
1 => {

View File

@ -79,7 +79,7 @@ impl DataCompressionModePage {
if enable {
self.flags2 |= 128;
} else {
self.flags2 = self.flags2 & 127;
self.flags2 &= 127;
}
}
@ -389,7 +389,7 @@ impl SgTape {
bail!("got unexpected data len ({} != {}", data.len(), expected_size);
}
let mut reader = &data[..];
let mut reader = data;
let page: ReadPositionLongPage = unsafe { reader.read_be_value()? };
@ -445,10 +445,8 @@ impl SgTape {
sg_raw.do_command(&cmd)
.map_err(|err| format_err!("move to EOD failed - {}", err))?;
if write_missing_eof {
if !self.check_filemark()? {
self.write_filemarks(1, false)?;
}
if write_missing_eof && !self.check_filemark()? {
self.write_filemarks(1, false)?;
}
Ok(())
@ -611,7 +609,7 @@ impl SgTape {
/// Read Volume Statistics
pub fn volume_statistics(&mut self) -> Result<Lp17VolumeStatistics, Error> {
return read_volume_statistics(&mut self.file);
read_volume_statistics(&mut self.file)
}
pub fn set_encryption(
@ -651,9 +649,9 @@ impl SgTape {
//println!("WRITE {:?}", data);
match sg_raw.do_out_command(&cmd, data) {
Ok(()) => { return Ok(false) }
Ok(()) => { Ok(false) }
Err(ScsiError::Sense(SenseInfo { sense_key: 0, asc: 0, ascq: 2 })) => {
return Ok(true); // LEOM
Ok(true) // LEOM
}
Err(err) => {
proxmox_sys::io_bail!("write failed - {}", err);
@ -910,7 +908,7 @@ impl SgTape {
// assume max. 16000 medium passes
// see: https://en.wikipedia.org/wiki/Linear_Tape-Open
let wearout: f64 = (passes as f64)/(16000.0 as f64);
let wearout: f64 = (passes as f64)/16000.0_f64;
status.medium_passes = Some(passes);
status.medium_wearout = Some(wearout);

View File

@ -217,7 +217,7 @@ struct SspDataEncryptionAlgorithmDescriptor {
fn decode_spin_data_encryption_caps(data: &[u8]) -> Result<u8, Error> {
proxmox_lang::try_block!({
let mut reader = &data[..];
let mut reader = data;
let _page: SspDataEncryptionCapabilityPage = unsafe { reader.read_be_value()? };
let mut aes_gcm_index = None;
@ -268,7 +268,7 @@ struct SspDataEncryptionStatusPage {
fn decode_spin_data_encryption_status(data: &[u8]) -> Result<DataEncryptionStatus, Error> {
proxmox_lang::try_block!({
let mut reader = &data[..];
let mut reader = data;
let page: SspDataEncryptionStatusPage = unsafe { reader.read_be_value()? };
if page.page_code != 0x20 {

View File

@ -123,7 +123,7 @@ pub fn read_mam_attributes<F: AsRawFd>(file: &mut F) -> Result<Vec<MamAttribute>
fn decode_mam_attributes(data: &[u8]) -> Result<Vec<MamAttribute>, Error> {
let mut reader = &data[..];
let mut reader = data;
let data_len: u32 = unsafe { reader.read_be_value()? };

View File

@ -39,7 +39,7 @@ pub fn report_density<F: AsRawFd>(file: &mut F) -> Result<u8, Error> {
let mut max_density = 0u8;
proxmox_lang::try_block!({
let mut reader = &data[..];
let mut reader = data;
let page_len: u16 = unsafe { reader.read_be_value()? };
let page_len = page_len as usize;

View File

@ -91,7 +91,7 @@ impl SgPt {
/// Peripheral device type text (see `inquiry` command)
///
/// see <https://en.wikipedia.org/wiki/SCSI_Peripheral_Device_Type>
pub const PERIPHERAL_DEVICE_TYPE_TEXT: [&'static str; 32] = [
pub const PERIPHERAL_DEVICE_TYPE_TEXT: [&str; 32] = [
"Disk Drive",
"Tape Drive",
"Printer",
@ -142,7 +142,7 @@ pub const SENSE_KEY_VOLUME_OVERFLOW: u8 = 0x0d;
pub const SENSE_KEY_MISCOMPARE: u8 = 0x0e;
/// Sense Key Descriptions
pub const SENSE_KEY_DESCRIPTIONS: [&'static str; 16] = [
pub const SENSE_KEY_DESCRIPTIONS: [&str; 16] = [
"No Sense",
"Recovered Error",
"Not Ready",
@ -486,13 +486,13 @@ impl <'a, F: AsRawFd> SgRaw<'a, F> {
let res_cat = unsafe { get_scsi_pt_result_category(ptvp.as_ptr()) };
match res_cat {
SCSI_PT_RESULT_GOOD => return Ok(()),
SCSI_PT_RESULT_GOOD => Ok(()),
SCSI_PT_RESULT_STATUS => {
let status = unsafe { get_scsi_pt_status_response(ptvp.as_ptr()) };
if status != 0 {
return Err(format_err!("unknown scsi error - status response {}", status).into());
}
return Ok(());
Ok(())
}
SCSI_PT_RESULT_SENSE => {
if sense_len == 0 {
@ -528,7 +528,7 @@ impl <'a, F: AsRawFd> SgRaw<'a, F> {
}
};
return Err(ScsiError::Sense(sense));
Err(ScsiError::Sense(sense))
}
SCSI_PT_RESULT_TRANSPORT_ERR => return Err(format_err!("scsi command failed: transport error").into()),
SCSI_PT_RESULT_OS_ERR => {
@ -676,7 +676,7 @@ pub fn scsi_inquiry<F: AsRawFd>(
.map_err(|err| format_err!("SCSI inquiry failed - {}", err))?;
proxmox_lang::try_block!({
let mut reader = &data[..];
let mut reader = data;
let page: InquiryPage = unsafe { reader.read_be_value()? };
@ -725,7 +725,7 @@ pub fn scsi_mode_sense<F: AsRawFd, P: Endian>(
.map_err(|err| format_err!("mode sense failed - {}", err))?;
proxmox_lang::try_block!({
let mut reader = &data[..];
let mut reader = data;
let head: ModeParameterHeader = unsafe { reader.read_be_value()? };
let expected_len = head.mode_data_len as usize + 2;
@ -788,7 +788,7 @@ pub fn scsi_request_sense<F: AsRawFd>(
bail!("received unexpected sense code '0x{:02x}'", code);
}
let mut reader = &data[..];
let mut reader = data;
let sense: RequestSenseFixed = unsafe { reader.read_be_value()? };

View File

@ -24,7 +24,7 @@ fn asn1_time_to_unix(time: &openssl::asn1::Asn1TimeRef) -> Result<i64, Error> {
bail!("failed to parse ASN1 time");
}
let mut c_tm = unsafe { c_tm.assume_init() };
Ok(proxmox_time::timegm(&mut c_tm)?)
proxmox_time::timegm(&mut c_tm)
}
pub struct CertInfo {
@ -57,11 +57,11 @@ impl CertInfo {
}
pub fn subject_name(&self) -> Result<String, Error> {
Ok(x509name_to_string(self.x509.subject_name())?)
x509name_to_string(self.x509.subject_name())
}
pub fn issuer_name(&self) -> Result<String, Error> {
Ok(x509name_to_string(self.x509.issuer_name())?)
x509name_to_string(self.x509.issuer_name())
}
pub fn fingerprint(&self) -> Result<String, Error> {

View File

@ -1451,7 +1451,7 @@ impl ReadAt for BufferedDynamicReadAt {
MaybeReady::Ready(tokio::task::block_in_place(move || {
let mut reader = self.inner.lock().unwrap();
reader.seek(SeekFrom::Start(offset))?;
Ok(reader.read(buf)?)
reader.read(buf)
}))
}

View File

@ -279,7 +279,7 @@ async fn mount_do(param: Value, pipe: Option<Fd>) -> Result<Value, Error> {
let chunk_reader = RemoteChunkReader::new(client.clone(), crypt_config, file_info.chunk_crypt_mode(), HashMap::new());
let reader = CachedChunkReader::new(chunk_reader, index, 8).seekable();
let name = &format!("{}:{}/{}", repo.to_string(), path, archive_name);
let name = &format!("{}:{}/{}", repo, path, archive_name);
let name_escaped = proxmox_sys::systemd::escape_unit(name, false);
let mut session = pbs_fuse_loop::FuseLoopSession::map_loop(size, reader, &name_escaped, options).await?;

View File

@ -271,7 +271,7 @@ impl BlockRestoreDriver for QemuBlockDriver {
None => {
let err = format!(
"invalid JSON received from /status call: {}",
status.to_string()
status
);
extra["error"] = json!(err);
}

View File

@ -80,7 +80,7 @@ lazy_static! {
#[api]
/// Lists all current items
fn list_items() -> Result<Vec<String>, Error> {
Ok(ITEM_MAP.lock().unwrap().keys().map(|k| k.clone()).collect())
Ok(ITEM_MAP.lock().unwrap().keys().cloned().collect())
}
#[api(

View File

@ -206,7 +206,7 @@ impl ApiConfig {
let logger_options = FileLogOptions {
append: true,
file_opts: file_opts.unwrap_or(CreateOptions::default()),
file_opts: file_opts.unwrap_or_default(),
..Default::default()
};
let request_log = Arc::new(Mutex::new(FileLogger::new(&path, logger_options)?));
@ -246,7 +246,7 @@ impl ApiConfig {
let logger_options = FileLogOptions {
append: true,
prefix_time: true,
file_opts: file_opts.unwrap_or(CreateOptions::default()),
file_opts: file_opts.unwrap_or_default(),
..Default::default()
};
let auth_log = Arc::new(Mutex::new(FileLogger::new(&path, logger_options)?));

View File

@ -205,7 +205,7 @@ pub fn extract_cookie(cookie: &str, cookie_name: &str) -> Option<String> {
/// We assume cookie_name is already url encoded.
pub fn cookie_from_header(headers: &http::HeaderMap, cookie_name: &str) -> Option<String> {
if let Some(Ok(cookie)) = headers.get("COOKIE").map(|v| v.to_str()) {
extract_cookie(&cookie, cookie_name)
extract_cookie(cookie, cookie_name)
} else {
None
}

View File

@ -377,7 +377,7 @@ async fn get_request_parameters<S: 'static + BuildHasher + Send>(
}
}
param_schema.verify_json(&params)?;
return Ok(params);
Ok(params)
} else {
parse_query_parameters(param_schema, utf8_data, &parts, &uri_param)
}

View File

@ -901,7 +901,7 @@ impl WorkerTask {
pub fn request_abort(&self) {
let prev_abort = self.abort_requested.swap(true, Ordering::SeqCst);
if !prev_abort { // log abort one time
self.log_message(format!("received abort request ..."));
self.log_message("received abort request ...".to_string());
}
// noitify listeners
let mut data = self.data.lock().unwrap();

View File

@ -719,7 +719,7 @@ impl DiskState {
components.push(component);
}
let mut bucket = match Bucket::filter_mut(buckets, &bucket_type, &components) {
let bucket = match Bucket::filter_mut(buckets, &bucket_type, &components) {
Some(bucket) => bucket,
None => bail!(
"bucket/component path not found: {}/{}/{}",
@ -732,7 +732,7 @@ impl DiskState {
// bucket found, check mount
let mountpoint = self
.filesystems
.ensure_mounted(&mut bucket)
.ensure_mounted(bucket)
.map_err(|err| {
format_err!(
"mounting '{}/{}/{}' failed: {}",

View File

@ -52,7 +52,7 @@ pub fn dump_rrd(path: String) -> Result<(), Error> {
let rrd = RRD::load(&PathBuf::from(path), false)?;
serde_json::to_writer_pretty(std::io::stdout(), &rrd)?;
println!("");
println!();
Ok(())
}

View File

@ -63,8 +63,8 @@ impl RRDCache {
) -> Result<Self, Error> {
let basedir = basedir.as_ref().to_owned();
let file_options = file_options.unwrap_or_else(|| CreateOptions::new());
let dir_options = dir_options.unwrap_or_else(|| CreateOptions::new());
let file_options = file_options.unwrap_or_else(CreateOptions::new);
let dir_options = dir_options.unwrap_or_else(CreateOptions::new);
create_path(&basedir, Some(dir_options.clone()), Some(dir_options.clone()))
.map_err(|err: Error| format_err!("unable to create rrdb stat dir - {}", err))?;

View File

@ -148,11 +148,7 @@ async fn register_account(
std::io::stdout().flush()?;
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
if input.trim().eq_ignore_ascii_case("y") {
true
} else {
false
}
input.trim().eq_ignore_ascii_case("y")
} else {
println!("No Terms of Service found, proceeding.");
true