I’m traversing and parsing slice in Rust, and would like to build dynamic error message which indicates the slice data length when exception is thrown. Code is as below:
fn1(
records: &[u8],
) -> Result<Vec<DocRecord>, nom::Err<nom::error::Error<&[u8]>>> {
let mut collection = Vec::new();
let mut data = records;
while !data.is_empty() {
let doc_record;
(data, doc_record) = Self::fn2()(input).map_err(|_| {
let error_message = format!(
"Parsing Error. Current data length: {}",
data.len()
);
nom::Err::Error(nom::error::Error::new(error_message.as_bytes(), nom::error::ErrorKind::Fail))
})?;
collection.push(doc_record);
}
Ok(collection)
}
However build shows error saying error_message.as_bytes()
is borrowed and the line returns a value referencing data owned by the current function. I then modified to
fn1(
records: &[u8],
) -> Result<Vec<DocRecord>, nom::Err<nom::error::Error<&[u8]>>> {
let mut collection = Vec::new();
let mut data = records;
while !data.is_empty() {
let doc_record;
let error_message = format!(
"Parsing Error. Current data length: {}",
data.len()
);
(data, doc_record) = Self::fn2()(input).map_err(|_| {
nom::Err::Error(nom::error::Error::new(error_message.as_bytes(), nom::error::ErrorKind::Fail))
})?;
collection.push(doc_record);
}
Ok(collection)
}
but still got the same error.
So how to get over this returns a value referencing data owned by the current function
issue? Thanks