From 3e82926d524241d2df41729f674ec6ed14463037 Mon Sep 17 00:00:00 2001
From: Wei Gao <gaowei66@huawei.com>
Date: Fri, 19 Feb 2021 08:23:18 +0800
Subject: [PATCH] clippy: implement high level v1.51 cargo clippy.

Signed-off-by: Wei Gao <gaowei66@huawei.com>
---
 boot_loader/src/x86_64/gdt.rs                | 18 ++++----
 device_model/src/micro_vm/mod.rs             |  8 ++--
 device_model/src/virtio/balloon.rs           |  4 +-
 device_model/src/virtio/block.rs             | 30 +++++--------
 device_model/src/virtio/net.rs               | 47 ++++++++++----------
 machine_manager/src/config/balloon.rs        |  2 +-
 machine_manager/src/config/chardev.rs        | 14 +++---
 machine_manager/src/config/fs.rs             | 12 ++---
 machine_manager/src/config/iothread.rs       | 13 +++---
 machine_manager/src/config/machine_config.rs |  4 +-
 machine_manager/src/config/mod.rs            |  8 ++--
 machine_manager/src/config/network.rs        | 12 ++---
 machine_manager/src/qmp/mod.rs               |  2 +-
 machine_manager/src/socket.rs                | 11 +++--
 util/src/arg_parser.rs                       | 11 +++--
 util/src/seccomp.rs                          |  6 +--
 16 files changed, 87 insertions(+), 115 deletions(-)

diff --git a/boot_loader/src/x86_64/gdt.rs b/boot_loader/src/x86_64/gdt.rs
index 557e4cf..3ce97b6 100644
--- a/boot_loader/src/x86_64/gdt.rs
+++ b/boot_loader/src/x86_64/gdt.rs
@@ -10,8 +10,6 @@
 // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 // See the Mulan PSL v2 for more details.
 
-use std::convert::Into;
-
 // /*
 //  * Constructor for a conventional segment GDT (or LDT) entry.
 //  * This is a macro so it can be used in initializers.
@@ -53,11 +51,11 @@ impl GdtEntry {
 //   Bits(22): D/B, Default Operation Size
 //   Bits(23): G, Granularity
 //   Bits(24 - 31): Base Address 24, 31
-impl Into<kvm_bindings::kvm_segment> for GdtEntry {
-    fn into(self) -> kvm_bindings::kvm_segment {
-        let base = (self.0 >> 16 & 0x00ff_ffff) | (self.0 >> (56 - 24) & 0xff00_0000);
-        let limit = (self.0 >> (48 - 16) & 0x000f_0000) | (self.0 & 0x0000_ffff);
-        let flags = (self.0 >> 40) & 0x0000_f0ff;
+impl From<GdtEntry> for kvm_bindings::kvm_segment {
+    fn from(item: GdtEntry) -> Self {
+        let base = (item.0 >> 16 & 0x00ff_ffff) | (item.0 >> (56 - 24) & 0xff00_0000);
+        let limit = (item.0 >> (48 - 16) & 0x000f_0000) | (item.0 & 0x0000_ffff);
+        let flags = (item.0 >> 40) & 0x0000_f0ff;
 
         kvm_bindings::kvm_segment {
             base,
@@ -75,9 +73,9 @@ impl Into<kvm_bindings::kvm_segment> for GdtEntry {
     }
 }
 
-impl Into<u64> for GdtEntry {
-    fn into(self) -> u64 {
-        self.0
+impl From<GdtEntry> for u64 {
+    fn from(item: GdtEntry) -> Self {
+        item.0
     }
 }
 
diff --git a/device_model/src/micro_vm/mod.rs b/device_model/src/micro_vm/mod.rs
index 8cc4fb6..23243c2 100644
--- a/device_model/src/micro_vm/mod.rs
+++ b/device_model/src/micro_vm/mod.rs
@@ -357,10 +357,12 @@ impl LightMachine {
     #[cfg(target_arch = "x86_64")]
     fn arch_init(vm_fd: &VmFd) -> Result<()> {
         vm_fd.create_irq_chip()?;
-        vm_fd.set_tss_address(0xfffb_d000 as usize)?;
+        vm_fd.set_tss_address(0xfffb_d000_usize)?;
 
-        let mut pit_config = kvm_pit_config::default();
-        pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
+        let pit_config = kvm_pit_config {
+            flags: KVM_PIT_SPEAKER_DUMMY,
+            pad: Default::default(),
+        };
         vm_fd.create_pit2(pit_config)?;
 
         Ok(())
diff --git a/device_model/src/virtio/balloon.rs b/device_model/src/virtio/balloon.rs
index 6e5f391..470e866 100644
--- a/device_model/src/virtio/balloon.rs
+++ b/device_model/src/virtio/balloon.rs
@@ -427,14 +427,12 @@ impl BalloonIoHandler {
 /// * `fd` - Raw file descriptor.
 /// * `handler` - Handle function.
 fn build_event_notifier(fd: RawFd, handler: Box<NotifierCallback>) -> EventNotifier {
-    let mut handlers = Vec::new();
-    handlers.push(Arc::new(Mutex::new(handler)));
     EventNotifier::new(
         NotifierOperation::AddShared,
         fd,
         None,
         EventSet::IN,
-        handlers,
+        vec![Arc::new(Mutex::new(handler))],
     )
 }
 
diff --git a/device_model/src/virtio/block.rs b/device_model/src/virtio/block.rs
index 6ca2ce6..913afd3 100644
--- a/device_model/src/virtio/block.rs
+++ b/device_model/src/virtio/block.rs
@@ -52,7 +52,7 @@ const CONFIG_SPACE_SIZE: usize = 16;
 /// Used to compute the number of sectors.
 const SECTOR_SHIFT: u8 = 9;
 /// Size of a sector of the block device.
-const SECTOR_SIZE: u64 = (0x01 as u64) << SECTOR_SHIFT;
+const SECTOR_SIZE: u64 = (0x01_u64) << SECTOR_SHIFT;
 /// Size of the dummy block device.
 const DUMMY_IMG_SIZE: u64 = 0;
 
@@ -604,14 +604,12 @@ impl BlockIoHandler {
 }
 
 fn build_event_notifier(fd: RawFd, handler: Box<NotifierCallback>) -> EventNotifier {
-    let mut handlers = Vec::new();
-    handlers.push(Arc::new(Mutex::new(handler)));
     EventNotifier::new(
         NotifierOperation::AddShared,
         fd,
         None,
         EventSet::IN,
-        handlers,
+        vec![Arc::new(Mutex::new(handler))],
     )
 }
 
@@ -684,7 +682,7 @@ pub struct Block {
     /// Bit mask of features negotiated by the backend and the frontend.
     driver_features: u64,
     /// Config space of the block device.
-    config_space: Vec<u8>,
+    config_space: [u8; CONFIG_SPACE_SIZE],
     /// Callback to trigger interrupt.
     interrupt_cb: Option<Arc<VirtioBlockInterrupt>>,
     /// The sending half of Rust's channel to send the image file.
@@ -706,31 +704,24 @@ impl Block {
             disk_sectors: 0,
             device_features: 0,
             driver_features: 0,
-            config_space: Vec::with_capacity(CONFIG_SPACE_SIZE),
+            config_space: [0u8; CONFIG_SPACE_SIZE],
             interrupt_cb: None,
             sender: None,
             update_evt: EventFd::new(libc::EFD_NONBLOCK).unwrap(),
         }
     }
 
-    fn build_device_config_space(&mut self) -> Result<()> {
+    fn build_device_config_space(&mut self) {
         // capacity: 64bits
         let num_sectors = DUMMY_IMG_SIZE >> SECTOR_SHIFT;
         for i in 0..8 {
-            self.config_space.push((num_sectors >> (8 * i)) as u8);
-        }
-
-        // size_max=0: 32bits
-        for _ in 0..4 {
-            self.config_space.push(0_u8);
+            self.config_space[i] = (num_sectors >> (8 * i)) as u8;
         }
 
         // seg_max=128-2: 32bits
         for i in 0..4 {
-            self.config_space.push((126 >> (8 * i)) as u8);
+            self.config_space[12 + i] = (126 >> (8 * i)) as u8;
         }
-
-        Ok(())
     }
 }
 
@@ -746,12 +737,11 @@ impl VirtioDevice for Block {
         self.device_features |= 1_u64 << VIRTIO_BLK_F_SEG_MAX;
         self.device_features |= 1_u64 << VIRTIO_F_RING_EVENT_IDX;
 
-        self.build_device_config_space()
-            .chain_err(|| "Failed to build config space for block")?;
+        self.build_device_config_space();
 
         let mut disk_size = DUMMY_IMG_SIZE;
 
-        if self.blk_cfg.path_on_host != "" {
+        if !self.blk_cfg.path_on_host.is_empty() {
             self.disk_image = None;
 
             let mut file = if self.blk_cfg.direct {
@@ -1049,7 +1039,7 @@ mod tests {
         assert_eq!(block.disk_sectors, 0);
         assert_eq!(block.device_features, 0);
         assert_eq!(block.driver_features, 0);
-        assert_eq!(block.config_space.len(), 0);
+        assert_eq!(block.config_space.len(), 16);
         assert!(block.disk_image.is_none());
         assert!(block.interrupt_cb.is_none());
         assert!(block.sender.is_none());
diff --git a/device_model/src/virtio/net.rs b/device_model/src/virtio/net.rs
index 468b3db..23d0899 100644
--- a/device_model/src/virtio/net.rs
+++ b/device_model/src/virtio/net.rs
@@ -304,7 +304,7 @@ impl NetIoHandler {
         Ok(())
     }
 
-    fn update_evt_handler(net_io: &Arc<Mutex<Self>>) -> Option<Vec<EventNotifier>> {
+    fn update_evt_handler(net_io: &Arc<Mutex<Self>>) -> Vec<EventNotifier> {
         let mut locked_net_io = net_io.lock().unwrap();
         locked_net_io.tap = match locked_net_io.receiver.recv() {
             Ok(tap) => tap,
@@ -319,25 +319,26 @@ impl NetIoHandler {
             locked_net_io.tap_fd = tap.as_raw_fd();
         }
 
-        let mut notifiers = Vec::new();
-        notifiers.push(build_event_notifier(
-            locked_net_io.update_evt,
-            None,
-            NotifierOperation::Delete,
-            EventSet::IN,
-        ));
-        notifiers.push(build_event_notifier(
-            locked_net_io.rx.queue_evt.as_raw_fd(),
-            None,
-            NotifierOperation::Delete,
-            EventSet::IN,
-        ));
-        notifiers.push(build_event_notifier(
-            locked_net_io.tx.queue_evt.as_raw_fd(),
-            None,
-            NotifierOperation::Delete,
-            EventSet::IN,
-        ));
+        let mut notifiers = vec![
+            build_event_notifier(
+                locked_net_io.update_evt,
+                None,
+                NotifierOperation::Delete,
+                EventSet::IN,
+            ),
+            build_event_notifier(
+                locked_net_io.rx.queue_evt.as_raw_fd(),
+                None,
+                NotifierOperation::Delete,
+                EventSet::IN,
+            ),
+            build_event_notifier(
+                locked_net_io.tx.queue_evt.as_raw_fd(),
+                None,
+                NotifierOperation::Delete,
+                EventSet::IN,
+            ),
+        ];
         if old_tap_fd != -1 {
             notifiers.push(build_event_notifier(
                 old_tap_fd,
@@ -349,7 +350,7 @@ impl NetIoHandler {
         drop(locked_net_io);
 
         notifiers.append(&mut EventNotifierHelper::internal_notifiers(net_io.clone()));
-        Some(notifiers)
+        notifiers
     }
 }
 
@@ -373,7 +374,7 @@ impl EventNotifierHelper for NetIoHandler {
         let cloned_net_io = net_io.clone();
         let handler: Box<NotifierCallback> = Box::new(move |_, fd: RawFd| {
             read_fd(fd);
-            NetIoHandler::update_evt_handler(&cloned_net_io)
+            Some(NetIoHandler::update_evt_handler(&cloned_net_io))
         });
         let mut notifiers = Vec::new();
         let update_fd = locked_net_io.update_evt;
@@ -569,7 +570,7 @@ impl VirtioDevice for Net {
             self.device_features |= build_device_config_space(&mut self.device_config, mac);
         }
 
-        if self.net_cfg.host_dev_name != "" {
+        if !self.net_cfg.host_dev_name.is_empty() {
             self.tap = None;
             self.tap = create_tap(None, Some(&self.net_cfg.host_dev_name))
                 .chain_err(|| "Failed to open tap with file path")?;
diff --git a/machine_manager/src/config/balloon.rs b/machine_manager/src/config/balloon.rs
index f27a7fb..cedc2be 100644
--- a/machine_manager/src/config/balloon.rs
+++ b/machine_manager/src/config/balloon.rs
@@ -39,7 +39,7 @@ impl VmConfig {
             balloon.deflate_on_oom = default.into();
         }
         if let Some(should_empty) = cmd_parser.get_value::<String>("")? {
-            if should_empty != "" {
+            if !should_empty.is_empty() {
                 return Err(ErrorKind::InvalidParam(should_empty).into());
             }
         }
diff --git a/machine_manager/src/config/chardev.rs b/machine_manager/src/config/chardev.rs
index 1fad279..532d4c7 100644
--- a/machine_manager/src/config/chardev.rs
+++ b/machine_manager/src/config/chardev.rs
@@ -65,23 +65,19 @@ impl ConfigCheck for ConsoleConfig {
 impl VmConfig {
     /// Add new virtio-console device to `VmConfig`.
     fn add_console(&mut self, console: ConsoleConfig) -> Result<()> {
-        if let Some(mut consoles) = self.consoles.clone() {
-            for c in &consoles {
+        if self.consoles.is_some() {
+            for c in self.consoles.as_ref().unwrap() {
                 if c.console_id == console.console_id {
                     return Err(ErrorKind::IdRepeat(
-                        c.console_id.to_string(),
                         "virtio-console".to_string(),
+                        c.console_id.to_string(),
                     )
                     .into());
                 }
             }
-
-            consoles.push(console);
-            self.consoles = Some(consoles);
+            self.consoles.as_mut().unwrap().push(console);
         } else {
-            let mut consoles: Vec<ConsoleConfig> = Vec::new();
-            consoles.push(console);
-            self.consoles = Some(consoles);
+            self.consoles = Some(vec![console]);
         }
 
         Ok(())
diff --git a/machine_manager/src/config/fs.rs b/machine_manager/src/config/fs.rs
index 76e0801..c0e40b3 100644
--- a/machine_manager/src/config/fs.rs
+++ b/machine_manager/src/config/fs.rs
@@ -101,21 +101,17 @@ impl ConfigCheck for DriveConfig {
 impl VmConfig {
     /// Add new block device to `VmConfig`.
     fn add_drive(&mut self, drive: DriveConfig) -> Result<()> {
-        if let Some(mut drives) = self.drives.clone() {
-            for d in &drives {
+        if self.drives.is_some() {
+            for d in self.drives.as_ref().unwrap() {
                 if d.drive_id == drive.drive_id {
                     return Err(
                         ErrorKind::IdRepeat("drive".to_string(), d.drive_id.to_string()).into(),
                     );
                 }
             }
-
-            drives.push(drive);
-            self.drives = Some(drives);
+            self.drives.as_mut().unwrap().push(drive);
         } else {
-            let mut drives: Vec<DriveConfig> = Vec::new();
-            drives.push(drive);
-            self.drives = Some(drives);
+            self.drives = Some(vec![drive]);
         }
 
         Ok(())
diff --git a/machine_manager/src/config/iothread.rs b/machine_manager/src/config/iothread.rs
index 4957c2a..fca14df 100644
--- a/machine_manager/src/config/iothread.rs
+++ b/machine_manager/src/config/iothread.rs
@@ -52,8 +52,8 @@ impl ConfigCheck for IothreadConfig {
 impl VmConfig {
     /// Add new iothread device to `VmConfig`.
     fn add_iothread(&mut self, iothread: IothreadConfig) -> Result<()> {
-        if let Some(mut iothreads) = self.iothreads.clone() {
-            if iothreads.len() >= MAX_IOTHREAD_NUM {
+        if self.iothreads.is_some() {
+            if self.iothreads.as_ref().unwrap().len() >= MAX_IOTHREAD_NUM {
                 return Err(ErrorKind::IllegalValue(
                     "Iothread number".to_string(),
                     0,
@@ -64,7 +64,7 @@ impl VmConfig {
                 .into());
             }
 
-            for t in &iothreads {
+            for t in self.iothreads.as_ref().unwrap() {
                 if t.id == iothread.id {
                     return Err(
                         ErrorKind::IdRepeat("iothread".to_string(), t.id.to_string()).into(),
@@ -72,12 +72,9 @@ impl VmConfig {
                 }
             }
 
-            iothreads.push(iothread);
-            self.iothreads = Some(iothreads);
+            self.iothreads.as_mut().unwrap().push(iothread);
         } else {
-            let mut iothreads: Vec<IothreadConfig> = Vec::new();
-            iothreads.push(iothread);
-            self.iothreads = Some(iothreads);
+            self.iothreads = Some(vec![iothread]);
         }
 
         Ok(())
diff --git a/machine_manager/src/config/machine_config.rs b/machine_manager/src/config/machine_config.rs
index 1bf2d12..f5d39aa 100644
--- a/machine_manager/src/config/machine_config.rs
+++ b/machine_manager/src/config/machine_config.rs
@@ -109,7 +109,7 @@ impl MachineConfig {
                             ErrorKind::ConvertValueFailed("vcpu_count".to_string(), item_str)
                         })?;
                         // limit cpu count
-                        if cpu < MIN_NR_CPUS || cpu > MAX_NR_CPUS {
+                        if !(MIN_NR_CPUS..=MAX_NR_CPUS).contains(&cpu) {
                             return Err(ErrorKind::IllegalValue(
                                 "CPU number".to_string(),
                                 MIN_NR_CPUS,
@@ -244,7 +244,7 @@ impl VmConfig {
         };
 
         // limit cpu count
-        if cpu < MIN_NR_CPUS || cpu > MAX_NR_CPUS {
+        if !(MIN_NR_CPUS..=MAX_NR_CPUS).contains(&cpu) {
             return Err(ErrorKind::IllegalValue(
                 "CPU number".to_string(),
                 MIN_NR_CPUS,
diff --git a/machine_manager/src/config/mod.rs b/machine_manager/src/config/mod.rs
index 77c78e6..7d940c6 100644
--- a/machine_manager/src/config/mod.rs
+++ b/machine_manager/src/config/mod.rs
@@ -333,7 +333,7 @@ impl CmdParser {
     fn get_value<T: FromStr>(&self, param_field: &str) -> Result<Option<T>> {
         match self.params.get(param_field) {
             Some(value) => {
-                let field_msg = if param_field == "" {
+                let field_msg = if param_field.is_empty() {
                     &self.name
                 } else {
                     param_field
@@ -370,9 +370,9 @@ impl FromStr for ExBool {
     }
 }
 
-impl Into<bool> for ExBool {
-    fn into(self) -> bool {
-        self.inner
+impl From<ExBool> for bool {
+    fn from(item: ExBool) -> Self {
+        item.inner
     }
 }
 
diff --git a/machine_manager/src/config/network.rs b/machine_manager/src/config/network.rs
index 8ac5cf2..3487ab1 100644
--- a/machine_manager/src/config/network.rs
+++ b/machine_manager/src/config/network.rs
@@ -103,21 +103,17 @@ impl ConfigCheck for NetworkInterfaceConfig {
 impl VmConfig {
     /// Add new network device to `VmConfig`
     fn add_netdev(&mut self, net: NetworkInterfaceConfig) -> Result<()> {
-        if let Some(mut nets) = self.nets.clone() {
-            for n in &nets {
+        if self.nets.is_some() {
+            for n in self.nets.as_ref().unwrap() {
                 if n.iface_id == net.iface_id {
                     return Err(
                         ErrorKind::IdRepeat("netdev".to_string(), n.iface_id.to_string()).into(),
                     );
                 }
             }
-
-            nets.push(net);
-            self.nets = Some(nets);
+            self.nets.as_mut().unwrap().push(net);
         } else {
-            let mut nets: Vec<NetworkInterfaceConfig> = Vec::new();
-            nets.push(net);
-            self.nets = Some(nets);
+            self.nets = Some(vec![net]);
         }
 
         Ok(())
diff --git a/machine_manager/src/qmp/mod.rs b/machine_manager/src/qmp/mod.rs
index 5828fb8..0ced9fe 100644
--- a/machine_manager/src/qmp/mod.rs
+++ b/machine_manager/src/qmp/mod.rs
@@ -310,7 +310,7 @@ pub fn create_timestamp() -> TimeStamp {
         .duration_since(UNIX_EPOCH)
         .expect("Time went backwards");
     let seconds = u128::from(since_the_epoch.as_secs());
-    let microseconds = (since_the_epoch.as_nanos() - seconds * 1_000_000_000) / (1_000 as u128);
+    let microseconds = (since_the_epoch.as_nanos() - seconds * 1_000_000_000) / (1_000_u128);
     TimeStamp {
         seconds: seconds as u64,
         microseconds: microseconds as u64,
diff --git a/machine_manager/src/socket.rs b/machine_manager/src/socket.rs
index 526923d..0d7a788 100644
--- a/machine_manager/src/socket.rs
+++ b/machine_manager/src/socket.rs
@@ -177,10 +177,7 @@ impl Socket {
     }
 
     /// Create socket's accepted stream to `event_notifier`.
-    fn create_event_notifier(
-        &mut self,
-        shared_socket: Arc<Mutex<Self>>,
-    ) -> Option<Vec<EventNotifier>> {
+    fn create_event_notifier(&mut self, shared_socket: Arc<Mutex<Self>>) -> Vec<EventNotifier> {
         let mut notifiers = Vec::new();
         self.accept();
 
@@ -225,7 +222,7 @@ impl Socket {
         );
 
         notifiers.push(notifier);
-        Some(notifiers)
+        notifiers
     }
 }
 
@@ -236,7 +233,9 @@ impl EventNotifierHelper for Socket {
         let socket = shared_socket.clone();
         let mut handlers = Vec::new();
         let handler: Box<dyn Fn(EventSet, RawFd) -> Option<Vec<EventNotifier>>> =
-            Box::new(move |_, _| socket.lock().unwrap().create_event_notifier(socket.clone()));
+            Box::new(move |_, _| {
+                Some(socket.lock().unwrap().create_event_notifier(socket.clone()))
+            });
 
         handlers.push(Arc::new(Mutex::new(handler)));
 
diff --git a/util/src/arg_parser.rs b/util/src/arg_parser.rs
index c774d4e..9240a22 100644
--- a/util/src/arg_parser.rs
+++ b/util/src/arg_parser.rs
@@ -276,9 +276,10 @@ impl<'a> ArgParser<'a> {
 impl<'a> Arg<'a> {
     /// Create a new arg with arg's name.
     pub fn with_name(name: &'a str) -> Self {
-        let mut arg = Arg::default();
-        arg.name = name;
-        arg
+        Arg {
+            name,
+            ..Default::default()
+        }
     }
 
     /// Set long argument for arg.
@@ -524,9 +525,7 @@ impl<'a> Arg<'a> {
 
 impl<'a> ArgMatches<'a> {
     fn new(args: BTreeMap<&'a str, Arg<'a>>) -> Self {
-        let mut arg_matches = ArgMatches::default();
-        arg_matches.args = args;
-        arg_matches
+        ArgMatches { args }
     }
 
     /// Get the single value for `arg`.
diff --git a/util/src/seccomp.rs b/util/src/seccomp.rs
index 7a782c6..e700ea3 100644
--- a/util/src/seccomp.rs
+++ b/util/src/seccomp.rs
@@ -172,9 +172,9 @@ pub enum SeccompOpt {
     Allow,
 }
 
-impl Into<u32> for SeccompOpt {
-    fn into(self) -> u32 {
-        match self {
+impl From<SeccompOpt> for u32 {
+    fn from(seccomp_opt: SeccompOpt) -> Self {
+        match seccomp_opt {
             SeccompOpt::Kill => SECCOMP_RET_KILL,
             SeccompOpt::Trap => SECCOMP_RET_TRAP,
             SeccompOpt::Errno(x) => SECCOMP_RET_ERRNO | (x & SECCOMP_RET_MASK),
-- 
2.27.0

