From 44e93dc531079be622c79dc578f29c2bfea1642e Mon Sep 17 00:00:00 2001 From: Simon Warta Date: Thu, 4 Jan 2024 16:18:46 +0100 Subject: [PATCH] Elaborate on set_to_csv and att tests --- libwasmvm/src/cache.rs | 91 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/libwasmvm/src/cache.rs b/libwasmvm/src/cache.rs index 920b084c4..88778fa55 100644 --- a/libwasmvm/src/cache.rs +++ b/libwasmvm/src/cache.rs @@ -273,6 +273,11 @@ impl From for AnalysisReport { } } +/// Takes a set of string-like elements and returns a comma-separated list. +/// Since no escaping or quoting is applied to the elements, the caller needs to ensure +/// only simple alphanumeric values are used. +/// +/// The order of the output elements is determined by the iteration order of the provided set. fn set_to_csv(set: BTreeSet>) -> String { let list: Vec<&str> = set.iter().map(|e| e.as_ref()).collect(); list.join(",") @@ -772,6 +777,92 @@ mod tests { ])), "A,AA,B,C,a,aa,b,c", ); + + // str + assert_eq!( + set_to_csv(BTreeSet::from_iter(vec![ + "a", "aa", "b", "c", "A", "AA", "B", "C", + ])), + "A,AA,B,C,a,aa,b,c", + ); + + // custom type + #[derive(PartialEq, Eq, Ord, Clone, Copy)] + enum Number { + One = 1, + Two = 2, + Three = 3, + Eleven = 11, + Twelve = 12, + } + + impl AsRef for Number { + fn as_ref(&self) -> &str { + use Number::*; + match self { + One => "1", + Two => "2", + Three => "3", + Eleven => "11", + Twelve => "12", + } + } + } + + impl PartialOrd for Number { + fn partial_cmp(&self, other: &Self) -> Option { + // sort by value + (*self as i32).partial_cmp(&(*other as i32)) + } + } + + assert_eq!( + set_to_csv(BTreeSet::from_iter([ + Number::One, + Number::Two, + Number::Three, + Number::Eleven, + Number::Twelve, + ])), + "1,2,3,11,12", + ); + + #[derive(PartialEq, Eq, Ord)] + enum Color { + Red, + Green, + Blue, + Yellow, + } + + impl AsRef for Color { + fn as_ref(&self) -> &str { + use Color::*; + match self { + Red => "red", + Green => "green", + Blue => "blue", + Yellow => "yellow", + } + } + } + + impl PartialOrd for Color { + fn partial_cmp(&self, other: &Self) -> Option { + // sort by name + self.as_ref().partial_cmp(other.as_ref()) + } + } + + assert_eq!( + set_to_csv(BTreeSet::from_iter([ + Color::Red, + Color::Green, + Color::Blue, + Color::Yellow, + ])), + "blue,green,red,yellow", + ); } #[test]