2020-07-06 15:41:45 +00:00
|
|
|
// Copyright © 2020 Intel Corporation
|
|
|
|
//
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
//
|
|
|
|
|
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::fmt;
|
2021-11-08 15:52:53 +00:00
|
|
|
use std::num::ParseIntError;
|
2020-07-06 15:41:45 +00:00
|
|
|
use std::str::FromStr;
|
|
|
|
|
|
|
|
#[derive(Default)]
|
|
|
|
pub struct OptionParser {
|
|
|
|
options: HashMap<String, OptionParserValue>,
|
|
|
|
}
|
|
|
|
|
|
|
|
struct OptionParserValue {
|
|
|
|
value: Option<String>,
|
|
|
|
requires_value: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum OptionParserError {
|
|
|
|
UnknownOption(String),
|
|
|
|
InvalidSyntax(String),
|
|
|
|
Conversion(String, String),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for OptionParserError {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
match self {
|
2022-12-14 11:41:15 +00:00
|
|
|
OptionParserError::UnknownOption(s) => write!(f, "unknown option: {s}"),
|
|
|
|
OptionParserError::InvalidSyntax(s) => write!(f, "invalid syntax:{s}"),
|
2020-07-06 15:41:45 +00:00
|
|
|
OptionParserError::Conversion(field, value) => {
|
2022-12-14 11:41:15 +00:00
|
|
|
write!(f, "unable to convert {value} for {field}")
|
2020-07-06 15:41:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
type OptionParserResult<T> = std::result::Result<T, OptionParserError>;
|
|
|
|
|
2022-08-08 12:50:59 +00:00
|
|
|
fn split_commas(s: &str) -> OptionParserResult<Vec<String>> {
|
2021-11-10 09:34:25 +00:00
|
|
|
let mut list: Vec<String> = Vec::new();
|
2022-08-08 12:47:38 +00:00
|
|
|
let mut opened_brackets = 0;
|
2022-08-08 13:04:59 +00:00
|
|
|
let mut in_quotes = false;
|
2022-08-08 12:47:38 +00:00
|
|
|
let mut current = String::new();
|
|
|
|
|
|
|
|
for c in s.trim().chars() {
|
|
|
|
match c {
|
|
|
|
'[' => {
|
|
|
|
opened_brackets += 1;
|
|
|
|
current.push('[');
|
|
|
|
}
|
|
|
|
']' => {
|
|
|
|
opened_brackets -= 1;
|
|
|
|
if opened_brackets < 0 {
|
|
|
|
return Err(OptionParserError::InvalidSyntax(s.to_owned()));
|
|
|
|
}
|
|
|
|
current.push(']');
|
|
|
|
}
|
2022-08-08 13:04:59 +00:00
|
|
|
'"' => in_quotes = !in_quotes,
|
2022-08-08 12:47:38 +00:00
|
|
|
',' => {
|
2022-08-08 13:04:59 +00:00
|
|
|
if opened_brackets > 0 || in_quotes {
|
2022-08-08 12:47:38 +00:00
|
|
|
current.push(',')
|
|
|
|
} else {
|
|
|
|
list.push(current);
|
|
|
|
current = String::new();
|
|
|
|
}
|
2021-11-10 09:34:25 +00:00
|
|
|
}
|
2022-08-08 12:47:38 +00:00
|
|
|
c => current.push(c),
|
2021-11-10 09:34:25 +00:00
|
|
|
}
|
2022-08-08 12:47:38 +00:00
|
|
|
}
|
|
|
|
list.push(current);
|
2021-11-10 09:34:25 +00:00
|
|
|
|
2022-08-08 13:04:59 +00:00
|
|
|
if opened_brackets != 0 || in_quotes {
|
2022-08-08 12:47:38 +00:00
|
|
|
return Err(OptionParserError::InvalidSyntax(s.to_owned()));
|
2021-11-10 09:34:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(list)
|
|
|
|
}
|
|
|
|
|
2020-07-06 15:41:45 +00:00
|
|
|
impl OptionParser {
|
|
|
|
pub fn new() -> Self {
|
|
|
|
Self {
|
|
|
|
options: HashMap::new(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn parse(&mut self, input: &str) -> OptionParserResult<()> {
|
|
|
|
if input.trim().is_empty() {
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
|
2022-08-08 12:50:59 +00:00
|
|
|
for option in split_commas(input)?.iter() {
|
2022-04-21 11:13:11 +00:00
|
|
|
let parts: Vec<&str> = option.splitn(2, '=').collect();
|
2020-07-06 15:41:45 +00:00
|
|
|
|
|
|
|
match self.options.get_mut(parts[0]) {
|
|
|
|
None => return Err(OptionParserError::UnknownOption(parts[0].to_owned())),
|
|
|
|
Some(value) => {
|
|
|
|
if value.requires_value {
|
|
|
|
if parts.len() != 2 {
|
|
|
|
return Err(OptionParserError::InvalidSyntax((*option).to_owned()));
|
|
|
|
}
|
|
|
|
value.value = Some(parts[1].trim().to_owned());
|
|
|
|
} else {
|
|
|
|
value.value = Some(String::new());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn add(&mut self, option: &str) -> &mut Self {
|
|
|
|
self.options.insert(
|
|
|
|
option.to_owned(),
|
|
|
|
OptionParserValue {
|
|
|
|
value: None,
|
|
|
|
requires_value: true,
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn add_valueless(&mut self, option: &str) -> &mut Self {
|
|
|
|
self.options.insert(
|
|
|
|
option.to_owned(),
|
|
|
|
OptionParserValue {
|
|
|
|
value: None,
|
|
|
|
requires_value: false,
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get(&self, option: &str) -> Option<String> {
|
|
|
|
self.options
|
|
|
|
.get(option)
|
|
|
|
.and_then(|v| v.value.clone())
|
|
|
|
.and_then(|s| if s.is_empty() { None } else { Some(s) })
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn is_set(&self, option: &str) -> bool {
|
|
|
|
self.options
|
|
|
|
.get(option)
|
|
|
|
.and_then(|v| v.value.as_ref())
|
|
|
|
.is_some()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn convert<T: FromStr>(&self, option: &str) -> OptionParserResult<Option<T>> {
|
|
|
|
match self.get(option) {
|
|
|
|
None => Ok(None),
|
|
|
|
Some(v) => Ok(Some(v.parse().map_err(|_| {
|
|
|
|
OptionParserError::Conversion(option.to_owned(), v.to_owned())
|
|
|
|
})?)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct Toggle(pub bool);
|
|
|
|
|
|
|
|
pub enum ToggleParseError {
|
|
|
|
InvalidValue(String),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FromStr for Toggle {
|
|
|
|
type Err = ToggleParseError;
|
|
|
|
|
|
|
|
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
|
|
|
|
match s.to_lowercase().as_str() {
|
|
|
|
"" => Ok(Toggle(false)),
|
|
|
|
"on" => Ok(Toggle(true)),
|
|
|
|
"off" => Ok(Toggle(false)),
|
|
|
|
"true" => Ok(Toggle(true)),
|
|
|
|
"false" => Ok(Toggle(false)),
|
|
|
|
_ => Err(ToggleParseError::InvalidValue(s.to_owned())),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct ByteSized(pub u64);
|
|
|
|
|
2020-09-08 14:51:00 +00:00
|
|
|
#[derive(Debug)]
|
2020-07-06 15:41:45 +00:00
|
|
|
pub enum ByteSizedParseError {
|
|
|
|
InvalidValue(String),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FromStr for ByteSized {
|
|
|
|
type Err = ByteSizedParseError;
|
|
|
|
|
|
|
|
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
|
|
|
|
Ok(ByteSized({
|
|
|
|
let s = s.trim();
|
|
|
|
let shift = if s.ends_with('K') {
|
|
|
|
10
|
|
|
|
} else if s.ends_with('M') {
|
|
|
|
20
|
|
|
|
} else if s.ends_with('G') {
|
|
|
|
30
|
|
|
|
} else {
|
|
|
|
0
|
|
|
|
};
|
|
|
|
|
|
|
|
let s = s.trim_end_matches(|c| c == 'K' || c == 'M' || c == 'G');
|
|
|
|
s.parse::<u64>()
|
|
|
|
.map_err(|_| ByteSizedParseError::InvalidValue(s.to_owned()))?
|
|
|
|
<< shift
|
|
|
|
}))
|
|
|
|
}
|
|
|
|
}
|
2020-08-28 16:20:12 +00:00
|
|
|
|
|
|
|
pub struct IntegerList(pub Vec<u64>);
|
|
|
|
|
|
|
|
pub enum IntegerListParseError {
|
|
|
|
InvalidValue(String),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FromStr for IntegerList {
|
|
|
|
type Err = IntegerListParseError;
|
|
|
|
|
|
|
|
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
|
|
|
|
let mut integer_list = Vec::new();
|
2021-11-08 10:57:17 +00:00
|
|
|
let ranges_list: Vec<&str> = s
|
|
|
|
.trim()
|
|
|
|
.trim_matches(|c| c == '[' || c == ']')
|
|
|
|
.split(',')
|
|
|
|
.collect();
|
2020-08-28 16:20:12 +00:00
|
|
|
|
|
|
|
for range in ranges_list.iter() {
|
|
|
|
let items: Vec<&str> = range.split('-').collect();
|
|
|
|
|
|
|
|
if items.len() > 2 {
|
2020-09-23 20:31:53 +00:00
|
|
|
return Err(IntegerListParseError::InvalidValue((*range).to_string()));
|
2020-08-28 16:20:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
let start_range = items[0]
|
|
|
|
.parse::<u64>()
|
|
|
|
.map_err(|_| IntegerListParseError::InvalidValue(items[0].to_owned()))?;
|
|
|
|
|
|
|
|
integer_list.push(start_range);
|
|
|
|
|
|
|
|
if items.len() == 2 {
|
|
|
|
let end_range = items[1]
|
|
|
|
.parse::<u64>()
|
|
|
|
.map_err(|_| IntegerListParseError::InvalidValue(items[1].to_owned()))?;
|
|
|
|
if start_range >= end_range {
|
2020-09-23 20:31:53 +00:00
|
|
|
return Err(IntegerListParseError::InvalidValue((*range).to_string()));
|
2020-08-28 16:20:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for i in start_range..end_range {
|
|
|
|
integer_list.push(i + 1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(IntegerList(integer_list))
|
|
|
|
}
|
|
|
|
}
|
2020-08-31 12:20:20 +00:00
|
|
|
|
2021-11-08 15:52:53 +00:00
|
|
|
pub trait TupleValue {
|
2021-11-10 09:34:25 +00:00
|
|
|
fn parse_value(input: &str) -> Result<Self, TupleError>
|
2021-11-08 15:52:53 +00:00
|
|
|
where
|
|
|
|
Self: Sized;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TupleValue for u64 {
|
2021-11-10 09:34:25 +00:00
|
|
|
fn parse_value(input: &str) -> Result<Self, TupleError> {
|
|
|
|
input.parse::<u64>().map_err(TupleError::InvalidInteger)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TupleValue for Vec<u8> {
|
|
|
|
fn parse_value(input: &str) -> Result<Self, TupleError> {
|
|
|
|
Ok(IntegerList::from_str(input)
|
|
|
|
.map_err(TupleError::InvalidIntegerList)?
|
|
|
|
.0
|
|
|
|
.iter()
|
|
|
|
.map(|v| *v as u8)
|
|
|
|
.collect())
|
2021-11-08 15:52:53 +00:00
|
|
|
}
|
|
|
|
}
|
2020-08-31 12:20:20 +00:00
|
|
|
|
2021-11-08 15:52:53 +00:00
|
|
|
impl TupleValue for Vec<u64> {
|
2021-11-10 09:34:25 +00:00
|
|
|
fn parse_value(input: &str) -> Result<Self, TupleError> {
|
|
|
|
Ok(IntegerList::from_str(input)
|
|
|
|
.map_err(TupleError::InvalidIntegerList)?
|
|
|
|
.0)
|
2021-11-08 15:52:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-10 09:34:25 +00:00
|
|
|
pub struct Tuple<S, T>(pub Vec<(S, T)>);
|
2021-11-08 15:52:53 +00:00
|
|
|
|
|
|
|
pub enum TupleError {
|
2020-08-31 12:20:20 +00:00
|
|
|
InvalidValue(String),
|
2021-11-10 09:34:25 +00:00
|
|
|
SplitOutsideBrackets(OptionParserError),
|
|
|
|
InvalidIntegerList(IntegerListParseError),
|
|
|
|
InvalidInteger(ParseIntError),
|
2020-08-31 12:20:20 +00:00
|
|
|
}
|
|
|
|
|
2021-11-10 09:34:25 +00:00
|
|
|
impl<S: FromStr, T: TupleValue> FromStr for Tuple<S, T> {
|
2021-11-08 15:52:53 +00:00
|
|
|
type Err = TupleError;
|
2020-08-31 12:20:20 +00:00
|
|
|
|
|
|
|
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
|
2021-11-10 09:34:25 +00:00
|
|
|
let mut list: Vec<(S, T)> = Vec::new();
|
2020-08-31 12:20:20 +00:00
|
|
|
|
2022-08-08 14:00:37 +00:00
|
|
|
let body = s
|
|
|
|
.trim()
|
|
|
|
.strip_prefix('[')
|
|
|
|
.and_then(|s| s.strip_suffix(']'))
|
|
|
|
.ok_or_else(|| TupleError::InvalidValue(s.to_string()))?;
|
|
|
|
|
|
|
|
let tuples_list = split_commas(body).map_err(TupleError::SplitOutsideBrackets)?;
|
2020-08-31 12:20:20 +00:00
|
|
|
for tuple in tuples_list.iter() {
|
|
|
|
let items: Vec<&str> = tuple.split('@').collect();
|
|
|
|
|
|
|
|
if items.len() != 2 {
|
2021-11-08 15:52:53 +00:00
|
|
|
return Err(TupleError::InvalidValue((*tuple).to_string()));
|
2020-08-31 12:20:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
let item1 = items[0]
|
2021-11-10 09:34:25 +00:00
|
|
|
.parse::<S>()
|
2021-11-08 15:52:53 +00:00
|
|
|
.map_err(|_| TupleError::InvalidValue(items[0].to_owned()))?;
|
2021-11-10 09:34:25 +00:00
|
|
|
let item2 = TupleValue::parse_value(items[1])?;
|
2020-08-31 12:20:20 +00:00
|
|
|
|
|
|
|
list.push((item1, item2));
|
|
|
|
}
|
|
|
|
|
2021-11-08 15:52:53 +00:00
|
|
|
Ok(Tuple(list))
|
2020-08-31 12:20:20 +00:00
|
|
|
}
|
|
|
|
}
|
2020-09-04 07:36:10 +00:00
|
|
|
|
2022-03-01 18:25:30 +00:00
|
|
|
#[derive(Default)]
|
2020-09-04 07:36:10 +00:00
|
|
|
pub struct StringList(pub Vec<String>);
|
|
|
|
|
|
|
|
pub enum StringListParseError {
|
|
|
|
InvalidValue(String),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FromStr for StringList {
|
|
|
|
type Err = StringListParseError;
|
|
|
|
|
|
|
|
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
|
2021-11-08 10:57:17 +00:00
|
|
|
let string_list: Vec<String> = s
|
|
|
|
.trim()
|
|
|
|
.trim_matches(|c| c == '[' || c == ']')
|
|
|
|
.split(',')
|
|
|
|
.map(|e| e.to_owned())
|
|
|
|
.collect();
|
2020-09-04 07:36:10 +00:00
|
|
|
|
|
|
|
Ok(StringList(string_list))
|
|
|
|
}
|
|
|
|
}
|
2022-08-08 12:36:05 +00:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_option_parser() {
|
|
|
|
let mut parser = OptionParser::new();
|
|
|
|
parser
|
|
|
|
.add("size")
|
|
|
|
.add("mergeable")
|
|
|
|
.add("hotplug_method")
|
2022-08-08 12:46:47 +00:00
|
|
|
.add("hotplug_size")
|
2022-08-08 13:04:59 +00:00
|
|
|
.add("topology")
|
|
|
|
.add("cmdline");
|
2022-08-08 12:36:05 +00:00
|
|
|
|
|
|
|
assert!(parser.parse("size=128M,hanging_param").is_err());
|
|
|
|
assert!(parser.parse("size=128M,too_many_equals=foo=bar").is_err());
|
|
|
|
assert!(parser.parse("size=128M,file=/dev/shm").is_err());
|
|
|
|
|
2022-08-08 12:46:47 +00:00
|
|
|
assert!(parser.parse("size=128M").is_ok());
|
2022-08-08 12:36:05 +00:00
|
|
|
assert_eq!(parser.get("size"), Some("128M".to_owned()));
|
|
|
|
assert!(!parser.is_set("mergeable"));
|
|
|
|
assert!(parser.is_set("size"));
|
2022-08-08 12:46:47 +00:00
|
|
|
|
|
|
|
assert!(parser.parse("size=128M,mergeable=on").is_ok());
|
|
|
|
assert_eq!(parser.get("size"), Some("128M".to_owned()));
|
|
|
|
assert_eq!(parser.get("mergeable"), Some("on".to_owned()));
|
|
|
|
|
|
|
|
assert!(parser
|
|
|
|
.parse("size=128M,mergeable=on,topology=[1,2]")
|
|
|
|
.is_ok());
|
|
|
|
assert_eq!(parser.get("size"), Some("128M".to_owned()));
|
|
|
|
assert_eq!(parser.get("mergeable"), Some("on".to_owned()));
|
|
|
|
assert_eq!(parser.get("topology"), Some("[1,2]".to_owned()));
|
|
|
|
|
|
|
|
assert!(parser
|
|
|
|
.parse("size=128M,mergeable=on,topology=[[1,2],[3,4]]")
|
|
|
|
.is_ok());
|
|
|
|
assert_eq!(parser.get("size"), Some("128M".to_owned()));
|
|
|
|
assert_eq!(parser.get("mergeable"), Some("on".to_owned()));
|
|
|
|
assert_eq!(parser.get("topology"), Some("[[1,2],[3,4]]".to_owned()));
|
|
|
|
|
|
|
|
assert!(parser.parse("topology=[").is_err());
|
2022-08-08 13:04:59 +00:00
|
|
|
assert!(parser.parse("topology=[[[]]]]").is_err());
|
|
|
|
|
|
|
|
assert!(parser.parse("cmdline=\"console=ttyS0,9600n8\"").is_ok());
|
|
|
|
assert_eq!(
|
|
|
|
parser.get("cmdline"),
|
|
|
|
Some("console=ttyS0,9600n8".to_owned())
|
|
|
|
);
|
|
|
|
assert!(parser.parse("cmdline=\"").is_err());
|
|
|
|
assert!(parser.parse("cmdline=\"\"\"").is_err());
|
2022-08-08 12:36:05 +00:00
|
|
|
}
|
|
|
|
}
|