Skip to content

Commit 578579b

Browse files
committed
dlt-rs: add TryFrom<&str> for DltId
Makes it more convenient to create a DLtId instance from a string slice. Signed-off-by: Alexander Mohr <[email protected]>
1 parent ebad0ae commit 578579b

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

dlt-rs/src/lib.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,26 @@ impl DltId {
294294
}
295295
}
296296

297+
impl TryFrom<&str> for DltId {
298+
type Error = DltError;
299+
300+
fn try_from(value: &str) -> Result<Self, Self::Error> {
301+
let bytes = value.as_bytes();
302+
if bytes.is_empty() || bytes.len() > DLT_ID_SIZE_USIZE {
303+
return Err(DltError::InvalidInput);
304+
}
305+
let mut padded = [0u8; DLT_ID_SIZE_USIZE];
306+
padded
307+
.get_mut(..bytes.len())
308+
.ok_or(DltError::InvalidInput)?
309+
.copy_from_slice(bytes);
310+
Ok(DltId {
311+
bytes: padded,
312+
len: bytes.len(),
313+
})
314+
}
315+
}
316+
297317
/// DLT trace status
298318
///
299319
/// Controls whether network trace messages (like packet captures) are enabled.
@@ -960,4 +980,16 @@ mod tests {
960980
let id4 = DltId::new(b"A").unwrap();
961981
assert_ne!(id1, id4);
962982
}
983+
984+
#[test]
985+
fn test_dlt_id_try_from_str() {
986+
let id = DltId::try_from("APP").unwrap();
987+
assert_eq!(id.as_str().unwrap(), "APP");
988+
989+
let long_id_result = DltId::try_from("TOOLONG");
990+
assert_eq!(long_id_result.unwrap_err(), DltError::InvalidInput);
991+
992+
let empty_id_result = DltId::try_from("");
993+
assert_eq!(empty_id_result.unwrap_err(), DltError::InvalidInput);
994+
}
963995
}

0 commit comments

Comments
 (0)