Skip to content

Commit 390fcc0

Browse files
committed
kernel_cmdline: impl From<String> for utf8::Cmdline
This is an obvious thing one might want to do. Ensures we can make an owned Cmdline directly from an owned String. Signed-off-by: John Eckersberg <[email protected]>
1 parent 8e83e3a commit 390fcc0

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

crates/kernel_cmdline/src/bytes.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,16 @@ impl<'a> Cmdline<'a> {
202202

203203
removed
204204
}
205+
206+
#[cfg(test)]
207+
pub(crate) fn is_owned(&self) -> bool {
208+
matches!(self.0, Cow::Owned(_))
209+
}
210+
211+
#[cfg(test)]
212+
pub(crate) fn is_borrowed(&self) -> bool {
213+
matches!(self.0, Cow::Borrowed(_))
214+
}
205215
}
206216

207217
impl<'a> AsRef<[u8]> for Cmdline<'a> {

crates/kernel_cmdline/src/utf8.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,15 @@ impl<'a, T: AsRef<str> + ?Sized> From<&'a T> for Cmdline<'a> {
2626
}
2727
}
2828

29+
impl From<String> for Cmdline<'static> {
30+
/// Creates a new `Cmdline` from a `String`.
31+
///
32+
/// Takes ownership of input and maintains it for internal owned data.
33+
fn from(input: String) -> Self {
34+
Self(bytes::Cmdline::from(input.into_bytes()))
35+
}
36+
}
37+
2938
/// An iterator over UTF-8 kernel command line parameters.
3039
///
3140
/// This is created by the `iter` method on `CmdlineUTF8`.
@@ -125,6 +134,16 @@ impl<'a> Cmdline<'a> {
125134
pub fn remove(&mut self, key: &ParameterKey) -> bool {
126135
self.0.remove(&key.0)
127136
}
137+
138+
#[cfg(test)]
139+
pub(crate) fn is_owned(&self) -> bool {
140+
self.0.is_owned()
141+
}
142+
143+
#[cfg(test)]
144+
pub(crate) fn is_borrowed(&self) -> bool {
145+
self.0.is_borrowed()
146+
}
128147
}
129148

130149
impl<'a> AsRef<str> for Cmdline<'a> {
@@ -439,6 +458,23 @@ mod tests {
439458
// example taken lovingly from:
440459
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/kernel/params.c?id=89748acdf226fd1a8775ff6fa2703f8412b286c8#n160
441460
let kargs = Cmdline::from("foo=bar,bar2 baz=fuz wiz");
461+
assert!(kargs.is_borrowed());
462+
let mut iter = kargs.iter();
463+
464+
assert_eq!(iter.next(), Some(param("foo=bar,bar2")));
465+
assert_eq!(iter.next(), Some(param("baz=fuz")));
466+
assert_eq!(iter.next(), Some(param("wiz")));
467+
assert_eq!(iter.next(), None);
468+
469+
// Test the find API
470+
assert_eq!(kargs.find("foo").unwrap().value().unwrap(), "bar,bar2");
471+
assert!(kargs.find("nothing").is_none());
472+
}
473+
474+
#[test]
475+
fn test_kargs_simple_from_string() {
476+
let kargs = Cmdline::from("foo=bar,bar2 baz=fuz wiz".to_string());
477+
assert!(kargs.is_owned());
442478
let mut iter = kargs.iter();
443479

444480
assert_eq!(iter.next(), Some(param("foo=bar,bar2")));

0 commit comments

Comments
 (0)