qemu_command_builder/
memory.rs

1use bon::Builder;
2
3use crate::to_command::ToCommand;
4
5#[derive(Debug, Clone, Hash, Ord, PartialOrd, Eq, PartialEq)]
6pub enum MemoryUnit {
7    Bytes(u64),
8    MegaBytes(u64),
9    GigaBytes(u64),
10}
11
12/// Sets guest startup RAM size to megs megabytes. Default is 128 MiB.
13/// Optionally, a suffix of "M" or "G" can be used to signify a value in
14/// megabytes or gigabytes respectively. Optional pair slots, maxmem
15/// could be used to set amount of hotpluggable memory slots and maximum
16/// amount of memory. Note that maxmem must be aligned to the page size.
17///
18/// For example, the following command-line sets the guest startup RAM
19/// size to 1GB, creates 3 slots to hotplug additional memory and sets
20/// the maximum memory the guest can reach to 4GB:
21///
22/// `-m 1G,slots=3,maxmem=4G`
23///
24/// If slots and maxmem are not specified, memory hotplug won't be
25/// enabled and the guest startup RAM will never increase.
26#[derive(Debug, Clone, Hash, Ord, PartialOrd, Eq, PartialEq, Builder)]
27pub struct Memory {
28    mem: MemoryUnit,
29    slots: Option<usize>,
30    maxmem: Option<MemoryUnit>,
31}
32
33impl ToCommand for Memory {
34    fn to_command(&self) -> Vec<String> {
35        let mut cmd = vec![];
36
37        cmd.push("-m".to_string());
38
39        let mut arg = String::new();
40        match &self.mem {
41            MemoryUnit::Bytes(amount) => {
42                arg.push_str(format!("{}", amount).as_str());
43            }
44            MemoryUnit::MegaBytes(amount) => {
45                arg.push_str(format!("{}M", amount).as_str());
46            }
47            MemoryUnit::GigaBytes(amount) => {
48                arg.push_str(format!("{}G", amount).as_str());
49            }
50        }
51        if let Some(slots) = self.slots {
52            arg.push_str(format!(",slots={}", slots).as_str());
53        }
54        if let Some(maxmem) = &self.maxmem {
55            match maxmem {
56                MemoryUnit::Bytes(amount) => {
57                    arg.push_str(format!(",maxmem={}", amount).as_str());
58                }
59                MemoryUnit::MegaBytes(amount) => {
60                    arg.push_str(format!(",maxmem={}M", amount).as_str());
61                }
62                MemoryUnit::GigaBytes(amount) => {
63                    arg.push_str(format!(",maxmem={}G", amount).as_str());
64                }
65            }
66        }
67        cmd.push(arg);
68
69        cmd
70    }
71}