Skip to content

Commit 76aefef

Browse files
committed
implement TryFrom<&Cmdline> for String
In some cases, having a String representation of the Linux command line can be useful. This is the case of vmm-reference which otherwise would require a conversion dance between string types. Signed-off-by: Alvise Rigo <a.rigo@virtualopensystems.com>
1 parent 35cb0d0 commit 76aefef

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

src/cmdline/mod.rs

+51
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,37 @@ impl Cmdline {
516516
}
517517
}
518518

519+
/// Convert a Cmdline to String
520+
///
521+
/// # Examples
522+
///
523+
/// ```rust
524+
/// # use linux_loader::cmdline::*;
525+
/// let mut cl = Cmdline::new(20).unwrap();
526+
/// cl.insert_str("foo").unwrap();
527+
/// cl.insert_init_args("bar").unwrap();
528+
/// assert_eq!(String::try_from(&cl).unwrap(), "foo -- bar");
529+
/// ```
530+
impl TryFrom<&Cmdline> for String {
531+
type Error = Error;
532+
533+
fn try_from(value: &Cmdline) -> result::Result<Self, Self::Error> {
534+
if value.boot_args.is_empty() && value.init_args.is_empty() {
535+
Ok("".to_string())
536+
} else if value.boot_args.is_empty() {
537+
Err(Error::NoBootArgsInserted)
538+
} else if value.init_args.is_empty() {
539+
Ok(value.boot_args.to_string())
540+
} else {
541+
Ok(format!(
542+
"{}{}{}",
543+
value.boot_args, INIT_ARGS_SEPARATOR, value.init_args
544+
)
545+
.to_string())
546+
}
547+
}
548+
}
549+
519550
impl TryFrom<Cmdline> for Vec<u8> {
520551
type Error = Error;
521552

@@ -867,4 +898,24 @@ mod tests {
867898
b"console=ttyS0 nomodules -- /etc/password --param\0"
868899
);
869900
}
901+
902+
#[test]
903+
fn test_string_from_cmdline() {
904+
let mut cl = Cmdline::new(CMDLINE_MAX_SIZE).unwrap();
905+
906+
assert_eq!(String::try_from(&cl).unwrap(), "");
907+
cl.insert_init_args("bar").unwrap();
908+
// This must fail as it is not allowed to have only init args
909+
let err = String::try_from(&cl).unwrap_err();
910+
assert_eq!(err, Error::NoBootArgsInserted);
911+
912+
// However, inserting only bootargs is permitted
913+
cl = Cmdline::new(CMDLINE_MAX_SIZE).unwrap();
914+
cl.insert_str("foo").unwrap();
915+
assert_eq!(String::try_from(&cl).unwrap(), "foo");
916+
917+
// Test also the concatenation of arguments
918+
cl.insert_init_args("bar").unwrap();
919+
assert_eq!(String::try_from(&cl).unwrap(), "foo -- bar");
920+
}
870921
}

0 commit comments

Comments
 (0)