update LV and TLV code
Rust/spacepackets/pipeline/head This commit looks good Details

This commit is contained in:
Robin Müller 2023-08-16 16:27:10 +02:00
parent 0f49672829
commit 83db710950
Signed by: muellerr
GPG Key ID: FCE0B2BD2195142F
4 changed files with 88 additions and 52 deletions

View File

@ -8,6 +8,15 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
# [unreleased]
## Changed
- The `Tlv` and `Lv` API return `&[u8]` instead of `Option<&[u8]>`.
## Added
- Added `raw_data` API for `Tlv` and `Lv` to retrieve the whole `Lv`/`Tlv` slice if the object
was created from a raw bytestream.
# [v0.7.0-beta.0] 2023-08-16
- Moved MSRV from v1.60 to v1.61.

View File

@ -15,10 +15,19 @@ pub const MIN_LV_LEN: usize = 1;
/// * `data`: If the LV is generated from a raw bytestream, this will be the lifetime of
/// the raw bytestream. If the LV is generated from a raw slice or a similar data reference,
/// this will be the lifetime of that data reference.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[derive(Debug, Copy, Clone, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Lv<'data> {
data: Option<&'data [u8]>,
data: &'data [u8],
// If the LV was generated from a raw bytestream, this will contain the start of the
// full LV.
pub(crate) raw_data: Option<&'data [u8]>,
}
impl PartialEq for Lv<'_> {
fn eq(&self, other: &Self) -> bool {
self.data == other.data
}
}
pub(crate) fn generic_len_check_data_serialization(
@ -53,12 +62,18 @@ impl<'data> Lv<'data> {
if data.len() > u8::MAX as usize {
return Err(TlvLvError::DataTooLarge(data.len()));
}
Ok(Lv { data: Some(data) })
Ok(Lv {
data,
raw_data: None,
})
}
/// Creates a LV with an empty value field.
pub fn new_empty() -> Lv<'data> {
Lv { data: None }
Lv {
data: &[],
raw_data: None,
}
}
/// Helper function to build a string LV. This is especially useful for the file or directory
@ -77,10 +92,7 @@ impl<'data> Lv<'data> {
/// Returns the length of the value part, not including the length byte.
pub fn len_value(&self) -> usize {
if self.data.is_none() {
return 0;
}
self.data.unwrap().len()
self.data.len()
}
/// Returns the full raw length, including the length byte.
@ -90,18 +102,26 @@ impl<'data> Lv<'data> {
/// Checks whether the value field is empty.
pub fn is_empty(&self) -> bool {
self.data.is_none()
self.data.len() == 0
}
pub fn value(&self) -> Option<&[u8]> {
pub fn value(&self) -> &[u8] {
self.data
}
/// If the LV was generated from a raw bytestream using [Self::from_bytes], the raw start
/// of the LV can be retrieved with this method.
pub fn raw_data(&self) -> Option<&[u8]> {
self.raw_data
}
/// Convenience function to extract the value as a [str]. This is useful if the LV is
/// known to contain a [str], for example being a file name.
pub fn value_as_str(&self) -> Option<Result<&'data str, Utf8Error>> {
self.data?;
Some(core::str::from_utf8(self.data.unwrap()))
if self.is_empty() {
return None;
}
Some(core::str::from_utf8(self.data))
}
/// Writes the LV to a raw buffer. Please note that the first byte will contain the length
@ -118,15 +138,14 @@ impl<'data> Lv<'data> {
}
pub(crate) fn write_to_be_bytes_no_len_check(&self, buf: &mut [u8]) -> usize {
if self.data.is_none() {
if self.is_empty() {
buf[0] = 0;
return MIN_LV_LEN;
}
let data = self.data.unwrap();
// Length check in constructor ensures the length always has a valid value.
buf[0] = data.len() as u8;
buf[MIN_LV_LEN..data.len() + MIN_LV_LEN].copy_from_slice(data);
MIN_LV_LEN + data.len()
buf[0] = self.data.len() as u8;
buf[MIN_LV_LEN..self.data.len() + MIN_LV_LEN].copy_from_slice(self.data);
MIN_LV_LEN + self.data.len()
}
pub(crate) fn from_be_bytes_no_len_check(
@ -134,11 +153,10 @@ impl<'data> Lv<'data> {
) -> Result<Lv<'data>, ByteConversionError> {
let value_len = buf[0] as usize;
generic_len_check_deserialization(buf, value_len + MIN_LV_LEN)?;
let mut data = None;
if value_len > 0 {
data = Some(&buf[MIN_LV_LEN..MIN_LV_LEN + value_len])
}
Ok(Self { data })
Ok(Self {
data: &buf[MIN_LV_LEN..MIN_LV_LEN + value_len],
raw_data: Some(buf),
})
}
}
@ -155,8 +173,8 @@ pub mod tests {
let lv_res = Lv::new(&lv_data);
assert!(lv_res.is_ok());
let lv = lv_res.unwrap();
assert!(lv.value().is_some());
let val = lv.value().unwrap();
assert!(lv.value().len() > 0);
let val = lv.value();
assert_eq!(val[0], 1);
assert_eq!(val[1], 2);
assert_eq!(val[2], 3);
@ -172,7 +190,6 @@ pub mod tests {
assert_eq!(lv_empty.len_value(), 0);
assert_eq!(lv_empty.len_full(), 1);
assert!(lv_empty.is_empty());
assert_eq!(lv_empty.value(), None);
let mut buf: [u8; 4] = [0xff; 4];
let res = lv_empty.write_to_be_bytes(&mut buf);
assert!(res.is_ok());
@ -211,10 +228,9 @@ pub mod tests {
assert!(lv.is_ok());
let lv = lv.unwrap();
assert!(!lv.is_empty());
assert!(lv.value().is_some());
assert_eq!(lv.len_value(), 4);
assert_eq!(lv.len_full(), 5);
let val = lv.value().unwrap();
let val = lv.value();
assert_eq!(val[0], 1);
assert_eq!(val[1], 2);
assert_eq!(val[2], 3);
@ -228,7 +244,6 @@ pub mod tests {
assert!(lv_empty.is_ok());
let lv_empty = lv_empty.unwrap();
assert!(lv_empty.is_empty());
assert!(lv_empty.value().is_none());
}
#[test]
@ -282,14 +297,14 @@ pub mod tests {
let res = res.unwrap();
assert_eq!(res, 8 + 1);
assert_eq!(buf[0], 8);
assert_eq!(buf[1], 't' as u8);
assert_eq!(buf[2], 'e' as u8);
assert_eq!(buf[3], 's' as u8);
assert_eq!(buf[4], 't' as u8);
assert_eq!(buf[5], '.' as u8);
assert_eq!(buf[6], 'b' as u8);
assert_eq!(buf[7], 'i' as u8);
assert_eq!(buf[8], 'n' as u8);
assert_eq!(buf[1], b't');
assert_eq!(buf[2], b'e');
assert_eq!(buf[3], b's');
assert_eq!(buf[4], b't');
assert_eq!(buf[5], b'.');
assert_eq!(buf[6], b'b');
assert_eq!(buf[7], b'i');
assert_eq!(buf[8], b'n');
}
#[test]
fn test_str_helper() {

View File

@ -718,6 +718,8 @@ mod tests {
assert_eq!(default_conf.crc_flag, CrcFlag::NoCrc);
assert_eq!(default_conf.file_flag, LargeFileFlag::Normal);
}
#[test]
fn test_pdu_header_setter() {
let src_id = UnsignedByteFieldU8::new(1);
let dest_id = UnsignedByteFieldU8::new(2);

View File

@ -109,7 +109,7 @@ impl<'data> Tlv<'data> {
Ok(self.len_full())
}
pub fn value(&self) -> Option<&[u8]> {
pub fn value(&self) -> &[u8] {
self.lv.value()
}
@ -134,10 +134,20 @@ impl<'data> Tlv<'data> {
/// [Self::len_full].
pub fn from_bytes(buf: &'data [u8]) -> Result<Tlv<'data>, TlvLvError> {
generic_len_check_deserialization(buf, MIN_TLV_LEN)?;
Ok(Self {
let mut tlv = Self {
tlv_type_field: TlvTypeField::from(buf[0]),
lv: Lv::from_bytes(&buf[MIN_LV_LEN..])?,
})
};
// We re-use this field so we do not need an additional struct field to store the raw start
// of the TLV.
tlv.lv.raw_data = Some(buf);
Ok(tlv)
}
/// If the TLV was generated from a raw bytestream using [Self::from_bytes], the raw start
/// of the TLV can be retrieved with this method.
pub fn raw_data(&self) -> Option<&[u8]> {
self.lv.raw_data()
}
}
@ -242,13 +252,14 @@ impl<'data> TryFrom<Tlv<'data>> for EntityIdTlv {
return Err(TlvLvError::InvalidValueLength(value.len_value()));
}
Ok(Self::new(
UnsignedByteField::new_from_be_bytes(value.len_value(), value.value().unwrap())
.map_err(|e| match e {
UnsignedByteField::new_from_be_bytes(value.len_value(), value.value()).map_err(
|e| match e {
UnsignedByteFieldError::ByteConversionError(e) => e,
// This can not happen, we checked for the length validity, and the data is always smaller than
// 255 bytes.
_ => panic!("unexpected error"),
})?,
},
)?,
))
}
}
@ -454,8 +465,8 @@ mod tests {
use crate::cfdp::TlvLvError;
use crate::util::{UbfU8, UnsignedEnum};
const TLV_TEST_STR_0: &'static str = "hello.txt";
const TLV_TEST_STR_1: &'static str = "hello2.txt";
const TLV_TEST_STR_0: &str = "hello.txt";
const TLV_TEST_STR_1: &str = "hello2.txt";
#[test]
fn test_basic() {
@ -472,8 +483,7 @@ mod tests {
assert_eq!(tlv_res.len_full(), 3);
assert_eq!(tlv_res.len_value(), 1);
assert!(!tlv_res.is_empty());
assert!(tlv_res.value().is_some());
assert_eq!(tlv_res.value().unwrap()[0], 5);
assert_eq!(tlv_res.value()[0], 5);
}
#[test]
@ -507,14 +517,14 @@ mod tests {
);
assert_eq!(tlv_from_raw.len_value(), 1);
assert_eq!(tlv_from_raw.len_full(), 3);
assert!(tlv_from_raw.value().is_some());
assert_eq!(tlv_from_raw.value().unwrap()[0], 5);
assert!(tlv_from_raw.value().len() > 0);
assert_eq!(tlv_from_raw.value()[0], 5);
}
#[test]
fn test_empty() {
let tlv_empty = Tlv::new_empty(TlvType::MsgToUser);
assert!(tlv_empty.value().is_none());
assert_eq!(tlv_empty.value().len(), 0);
assert!(tlv_empty.is_empty());
assert_eq!(tlv_empty.len_full(), 2);
assert_eq!(tlv_empty.len_value(), 0);
@ -538,11 +548,11 @@ mod tests {
let mut buf: [u8; 4] = [0; 4];
buf[0] = TlvType::MsgToUser as u8;
buf[1] = 0;
let tlv_empty = Tlv::from_bytes(&mut buf);
let tlv_empty = Tlv::from_bytes(&buf);
assert!(tlv_empty.is_ok());
let tlv_empty = tlv_empty.unwrap();
assert!(tlv_empty.is_empty());
assert!(tlv_empty.value().is_none());
assert_eq!(tlv_empty.value().len(), 0);
assert_eq!(
tlv_empty.tlv_type_field(),
TlvTypeField::Standard(TlvType::MsgToUser)
@ -570,7 +580,7 @@ mod tests {
buf[0] = 3;
buf[1] = 1;
buf[2] = 5;
let tlv = Tlv::from_bytes(&mut buf);
let tlv = Tlv::from_bytes(&buf);
assert!(tlv.is_ok());
let tlv = tlv.unwrap();
assert_eq!(tlv.tlv_type_field(), TlvTypeField::Custom(3));