cyclonedx_bom/
utilities.rs

1use crate::errors::BomError;
2use std::convert::TryFrom;
3
4/// Convert an optional list of a type
5///
6/// Used to translate between a common structure in the data model for going between the model version and the specification version
7pub(crate) fn convert_optional_vec<A, B: From<A>>(value: Option<Vec<A>>) -> Option<Vec<B>> {
8    value.map(convert_vec)
9}
10
11/*
12pub(crate) fn try_convert_optional_vec<A, B: TryFrom<A, Error = BomError>>(value: Option<Vec<A>>) -> Option<Result<Vec<B>, BomError>> {
13    value.map(try_convert_vec)
14}
15*/
16
17pub(crate) fn convert_optional<A, B: From<A>>(value: Option<A>) -> Option<B> {
18    value.map(std::convert::Into::into)
19}
20
21pub(crate) fn try_convert_optional<A, B: TryFrom<A>>(
22    value: Option<A>,
23) -> Result<Option<B>, BomError>
24where
25    BomError: From<B::Error>,
26{
27    value.map(B::try_from).transpose().map_err(BomError::from)
28}
29
30pub(crate) fn convert_vec<A, B: From<A>>(value: Vec<A>) -> Vec<B> {
31    value.into_iter().map(std::convert::Into::into).collect()
32}
33
34pub(crate) fn try_convert_vec<A, B: TryFrom<A, Error = BomError>>(
35    value: Vec<A>,
36) -> Result<Vec<B>, BomError> {
37    value
38        .into_iter()
39        .map(std::convert::TryInto::try_into)
40        .collect()
41}
42
43/*
44For cases where you return Result, it's useful to know that .collect() can take iterator of Result<T,E> and collect into Result<Vec<T>, E>, so you can then use ? on the collection:
45
46a.into_iter()
47    .map(|x| x.ok_or(NoneError))
48    .collect::<Result<Vec<_>,_>>()?
49*/