protoset.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. // Copyright (c) 2018, The Tor Project, Inc.
  2. // Copyright (c) 2018, isis agora lovecruft
  3. // See LICENSE for licensing information
  4. //! Sets for lazily storing ordered, non-overlapping ranges of integers.
  5. use std::cmp;
  6. use std::iter;
  7. use std::slice;
  8. use std::str::FromStr;
  9. use std::u32;
  10. use errors::ProtoverError;
  11. /// A single version number.
  12. pub type Version = u32;
  13. /// A `ProtoSet` stores an ordered `Vec<T>` of `(low, high)` pairs of ranges of
  14. /// non-overlapping protocol versions.
  15. ///
  16. /// # Examples
  17. ///
  18. /// ```
  19. /// use std::str::FromStr;
  20. ///
  21. /// use protover::errors::ProtoverError;
  22. /// use protover::protoset::ProtoSet;
  23. /// use protover::protoset::Version;
  24. ///
  25. /// # fn do_test() -> Result<ProtoSet, ProtoverError> {
  26. /// let protoset: ProtoSet = ProtoSet::from_str("3-5,8")?;
  27. ///
  28. /// // We could also equivalently call:
  29. /// let protoset: ProtoSet = "3-5,8".parse()?;
  30. ///
  31. /// assert!(protoset.contains(&4));
  32. /// assert!(!protoset.contains(&7));
  33. ///
  34. /// let expanded: Vec<Version> = protoset.clone().into();
  35. ///
  36. /// assert_eq!(&expanded[..], &[3, 4, 5, 8]);
  37. ///
  38. /// let contracted: String = protoset.clone().to_string();
  39. ///
  40. /// assert_eq!(contracted, "3-5,8".to_string());
  41. /// # Ok(protoset)
  42. /// # }
  43. /// # fn main() { do_test(); } // wrap the test so we can use the ? operator
  44. #[derive(Clone, Debug, Eq, PartialEq, Hash)]
  45. pub struct ProtoSet {
  46. pub(crate) pairs: Vec<(Version, Version)>,
  47. }
  48. impl Default for ProtoSet {
  49. fn default() -> Self {
  50. let pairs: Vec<(Version, Version)> = Vec::new();
  51. ProtoSet { pairs }
  52. }
  53. }
  54. impl<'a> ProtoSet {
  55. /// Create a new `ProtoSet` from a slice of `(low, high)` pairs.
  56. ///
  57. /// # Inputs
  58. ///
  59. /// We do not assume the input pairs are deduplicated or ordered.
  60. pub fn from_slice(low_high_pairs: &'a [(Version, Version)]) -> Result<Self, ProtoverError> {
  61. let mut pairs: Vec<(Version, Version)> = Vec::with_capacity(low_high_pairs.len());
  62. for &(low, high) in low_high_pairs {
  63. pairs.push((low, high));
  64. }
  65. // Sort the pairs without reallocation and remove all duplicate pairs.
  66. pairs.sort_unstable();
  67. pairs.dedup();
  68. ProtoSet { pairs }.is_ok()
  69. }
  70. }
  71. /// Expand this `ProtoSet` to a `Vec` of all its `Version`s.
  72. ///
  73. /// # Examples
  74. ///
  75. /// ```
  76. /// use std::str::FromStr;
  77. /// use protover::protoset::ProtoSet;
  78. /// use protover::protoset::Version;
  79. /// # use protover::errors::ProtoverError;
  80. ///
  81. /// # fn do_test() -> Result<Vec<Version>, ProtoverError> {
  82. /// let protoset: ProtoSet = ProtoSet::from_str("3-5,21")?;
  83. /// let versions: Vec<Version> = protoset.into();
  84. ///
  85. /// assert_eq!(&versions[..], &[3, 4, 5, 21]);
  86. /// #
  87. /// # Ok(versions)
  88. /// # }
  89. /// # fn main() { do_test(); } // wrap the test so we can use the ? operator
  90. /// ```
  91. impl Into<Vec<Version>> for ProtoSet {
  92. fn into(self) -> Vec<Version> {
  93. let mut versions: Vec<Version> = Vec::new();
  94. for &(low, high) in self.iter() {
  95. versions.extend(low..high + 1);
  96. }
  97. versions
  98. }
  99. }
  100. impl ProtoSet {
  101. /// Get an iterator over the `(low, high)` `pairs` in this `ProtoSet`.
  102. pub fn iter(&self) -> slice::Iter<(Version, Version)> {
  103. self.pairs.iter()
  104. }
  105. /// Expand this `ProtoSet` into a `Vec` of all its `Version`s.
  106. ///
  107. /// # Examples
  108. ///
  109. /// ```
  110. /// # use protover::errors::ProtoverError;
  111. /// use protover::protoset::ProtoSet;
  112. ///
  113. /// # fn do_test() -> Result<bool, ProtoverError> {
  114. /// let protoset: ProtoSet = "3-5,9".parse()?;
  115. ///
  116. /// assert_eq!(protoset.expand(), vec![3, 4, 5, 9]);
  117. ///
  118. /// let protoset: ProtoSet = "1,3,5-7".parse()?;
  119. ///
  120. /// assert_eq!(protoset.expand(), vec![1, 3, 5, 6, 7]);
  121. /// #
  122. /// # Ok(true)
  123. /// # }
  124. /// # fn main() { do_test(); } // wrap the test so we can use the ? operator
  125. /// ```
  126. pub fn expand(self) -> Vec<Version> {
  127. self.into()
  128. }
  129. pub fn len(&self) -> usize {
  130. let mut length: usize = 0;
  131. for &(low, high) in self.iter() {
  132. length += (high as usize - low as usize) + 1;
  133. }
  134. length
  135. }
  136. /// Check that this `ProtoSet` is well-formed.
  137. ///
  138. /// This is automatically called in `ProtoSet::from_str()`.
  139. ///
  140. /// # Errors
  141. ///
  142. /// * `ProtoverError::LowGreaterThanHigh`: if its `pairs` were not
  143. /// well-formed, i.e. a `low` in a `(low, high)` was higher than the
  144. /// previous `high`,
  145. /// * `ProtoverError::Overlap`: if one or more of the `pairs` are
  146. /// overlapping,
  147. /// * `ProtoverError::ExceedsMax`: if the number of versions when expanded
  148. /// would exceed `MAX_PROTOCOLS_TO_EXPAND`, and
  149. ///
  150. /// # Returns
  151. ///
  152. /// A `Result` whose `Ok` is this `Protoset`, and whose `Err` is one of the
  153. /// errors enumerated in the Errors section above.
  154. fn is_ok(self) -> Result<ProtoSet, ProtoverError> {
  155. let mut last_high: Version = 0;
  156. for &(low, high) in self.iter() {
  157. if low == u32::MAX || high == u32::MAX {
  158. return Err(ProtoverError::ExceedsMax);
  159. }
  160. if low <= last_high {
  161. return Err(ProtoverError::Overlap);
  162. } else if low > high {
  163. return Err(ProtoverError::LowGreaterThanHigh);
  164. }
  165. last_high = high;
  166. }
  167. Ok(self)
  168. }
  169. /// Determine if this `ProtoSet` contains no `Version`s.
  170. ///
  171. /// # Returns
  172. ///
  173. /// * `true` if this `ProtoSet`'s length is zero, and
  174. /// * `false` otherwise.
  175. ///
  176. /// # Examples
  177. ///
  178. /// ```
  179. /// use protover::protoset::ProtoSet;
  180. ///
  181. /// let protoset: ProtoSet = ProtoSet::default();
  182. ///
  183. /// assert!(protoset.is_empty());
  184. /// ```
  185. pub fn is_empty(&self) -> bool {
  186. self.pairs.len() == 0
  187. }
  188. /// Determine if `version` is included within this `ProtoSet`.
  189. ///
  190. /// # Inputs
  191. ///
  192. /// * `version`: a `Version`.
  193. ///
  194. /// # Returns
  195. ///
  196. /// `true` if the `version` is contained within this set; `false` otherwise.
  197. ///
  198. /// # Examples
  199. ///
  200. /// ```
  201. /// # use protover::errors::ProtoverError;
  202. /// use protover::protoset::ProtoSet;
  203. ///
  204. /// # fn do_test() -> Result<ProtoSet, ProtoverError> {
  205. /// let protoset: ProtoSet = ProtoSet::from_slice(&[(0, 5), (7, 9), (13, 14)])?;
  206. ///
  207. /// assert!(protoset.contains(&5));
  208. /// assert!(!protoset.contains(&10));
  209. /// #
  210. /// # Ok(protoset)
  211. /// # }
  212. /// # fn main() { do_test(); } // wrap the test so we can use the ? operator
  213. /// ```
  214. pub fn contains(&self, version: &Version) -> bool {
  215. for &(low, high) in self.iter() {
  216. if low <= *version && *version <= high {
  217. return true;
  218. }
  219. }
  220. false
  221. }
  222. /// Returns all the `Version`s in `self` which are not also in the `other`
  223. /// `ProtoSet`.
  224. ///
  225. /// # Examples
  226. ///
  227. /// ```
  228. /// # use protover::errors::ProtoverError;
  229. /// use protover::protoset::ProtoSet;
  230. ///
  231. /// # fn do_test() -> Result<bool, ProtoverError> {
  232. /// let protoset: ProtoSet = "1,3-6,10-12,15-16".parse()?;
  233. /// let other: ProtoSet = "2,5-7,9-11,14-20".parse()?;
  234. ///
  235. /// let subset: ProtoSet = protoset.and_not_in(&other);
  236. ///
  237. /// assert_eq!(subset.expand(), vec![1, 3, 4, 12]);
  238. /// #
  239. /// # Ok(true)
  240. /// # }
  241. /// # fn main() { do_test(); } // wrap the test so we can use the ? operator
  242. /// ```
  243. pub fn and_not_in(&self, other: &Self) -> Self {
  244. if self.is_empty() || other.is_empty() {
  245. return self.clone();
  246. }
  247. let pairs = self.iter().flat_map(|&(lo, hi)| {
  248. let the_end = (hi + 1, hi + 1); // special case to mark the end of the range.
  249. let excluded_ranges = other
  250. .iter()
  251. .cloned() // have to be owned tuples, to match iter::once(the_end).
  252. .skip_while(move|&(_, hi2)| hi2 < lo) // skip the non-overlapping ranges.
  253. .take_while(move|&(lo2, _)| lo2 <= hi) // take all the overlapping ones.
  254. .chain(iter::once(the_end));
  255. let mut nextlo = lo;
  256. excluded_ranges.filter_map(move |(excluded_lo, excluded_hi)| {
  257. let pair = if nextlo < excluded_lo {
  258. Some((nextlo, excluded_lo - 1))
  259. } else {
  260. None
  261. };
  262. nextlo = cmp::min(excluded_hi, u32::MAX - 1) + 1;
  263. pair
  264. })
  265. });
  266. let pairs = pairs.collect();
  267. ProtoSet::is_ok(ProtoSet { pairs }).expect("should be already sorted")
  268. }
  269. }
  270. impl FromStr for ProtoSet {
  271. type Err = ProtoverError;
  272. /// Parse the unique version numbers supported by a subprotocol from a string.
  273. ///
  274. /// # Inputs
  275. ///
  276. /// * `version_string`, a string comprised of "[0-9,-]"
  277. ///
  278. /// # Returns
  279. ///
  280. /// A `Result` whose `Ok` value is a `ProtoSet` holding all of the unique
  281. /// version numbers.
  282. ///
  283. /// The returned `Result`'s `Err` value is an `ProtoverError` appropriate to
  284. /// the error.
  285. ///
  286. /// # Errors
  287. ///
  288. /// This function will error if:
  289. ///
  290. /// * the `version_string` is an equals (`"="`) sign,
  291. /// * the expansion of a version range produces an error (see
  292. /// `expand_version_range`),
  293. /// * any single version number is not parseable as an `u32` in radix 10, or
  294. /// * there are greater than 2^16 version numbers to expand.
  295. ///
  296. /// # Examples
  297. ///
  298. /// ```
  299. /// use std::str::FromStr;
  300. ///
  301. /// use protover::errors::ProtoverError;
  302. /// use protover::protoset::ProtoSet;
  303. ///
  304. /// # fn do_test() -> Result<ProtoSet, ProtoverError> {
  305. /// let protoset: ProtoSet = ProtoSet::from_str("2-5,8")?;
  306. ///
  307. /// assert!(protoset.contains(&5));
  308. /// assert!(!protoset.contains(&10));
  309. ///
  310. /// // We can also equivalently call `ProtoSet::from_str` by doing (all
  311. /// // implementations of `FromStr` can be called this way, this one isn't
  312. /// // special):
  313. /// let protoset: ProtoSet = "4-6,12".parse()?;
  314. ///
  315. /// // Calling it (either way) can take really large ranges (up to `u32::MAX`):
  316. /// let protoset: ProtoSet = "1-70000".parse()?;
  317. /// let protoset: ProtoSet = "1-4294967296".parse()?;
  318. ///
  319. /// // There are lots of ways to get an `Err` from this function. Here are
  320. /// // a few:
  321. /// assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("="));
  322. /// assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("-"));
  323. /// assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("not_an_int"));
  324. /// assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("3-"));
  325. /// assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("1-,4"));
  326. ///
  327. /// // An empty string is, however, legal, and results in an
  328. /// // empty `ProtoSet`:
  329. /// assert_eq!(Ok(ProtoSet::default()), ProtoSet::from_str(""));
  330. /// #
  331. /// # Ok(protoset)
  332. /// # }
  333. /// # fn main() { do_test(); } // wrap the test so we can use the ? operator
  334. /// ```
  335. fn from_str(version_string: &str) -> Result<Self, Self::Err> {
  336. // If we were passed in an empty string, then return an empty ProtoSet.
  337. if version_string.is_empty() {
  338. return Ok(Self::default());
  339. }
  340. let mut pairs: Vec<(Version, Version)> = Vec::new();
  341. let pieces: ::std::str::Split<char> = version_string.split(',');
  342. for p in pieces {
  343. if p.contains('-') {
  344. let mut pair = p.splitn(2, '-');
  345. let low = pair.next().ok_or(ProtoverError::Unparseable)?;
  346. let high = pair.next().ok_or(ProtoverError::Unparseable)?;
  347. let lo: Version = low.parse().or(Err(ProtoverError::Unparseable))?;
  348. let hi: Version = high.parse().or(Err(ProtoverError::Unparseable))?;
  349. pairs.push((lo, hi));
  350. } else {
  351. let v: u32 = p.parse().or(Err(ProtoverError::Unparseable))?;
  352. pairs.push((v, v));
  353. }
  354. }
  355. ProtoSet::from_slice(&pairs[..])
  356. }
  357. }
  358. impl ToString for ProtoSet {
  359. /// Contracts a `ProtoSet` of versions into a string.
  360. ///
  361. /// # Returns
  362. ///
  363. /// A `String` representation of this `ProtoSet` in ascending order.
  364. fn to_string(&self) -> String {
  365. let mut final_output: Vec<String> = Vec::new();
  366. for &(lo, hi) in self.iter() {
  367. if lo != hi {
  368. debug_assert!(lo < hi);
  369. final_output.push(format!("{}-{}", lo, hi));
  370. } else {
  371. final_output.push(format!("{}", lo));
  372. }
  373. }
  374. final_output.join(",")
  375. }
  376. }
  377. /// Checks to see if there is a continuous range of integers, starting at the
  378. /// first in the list. Returns the last integer in the range if a range exists.
  379. ///
  380. /// # Inputs
  381. ///
  382. /// `list`, an ordered vector of `u32` integers of "[0-9,-]" representing the
  383. /// supported versions for a single protocol.
  384. ///
  385. /// # Returns
  386. ///
  387. /// A `bool` indicating whether the list contains a range, starting at the first
  388. /// in the list, a`Version` of the last integer in the range, and a `usize` of
  389. /// the index of that version.
  390. ///
  391. /// For example, if given vec![1, 2, 3, 5], find_range will return true,
  392. /// as there is a continuous range, and 3, which is the last number in the
  393. /// continuous range, and 2 which is the index of 3.
  394. fn find_range(list: &Vec<Version>) -> (bool, Version, usize) {
  395. if list.len() == 0 {
  396. return (false, 0, 0);
  397. }
  398. let mut index: usize = 0;
  399. let mut iterable = list.iter().peekable();
  400. let mut range_end = match iterable.next() {
  401. Some(n) => *n,
  402. None => return (false, 0, 0),
  403. };
  404. let mut has_range = false;
  405. while iterable.peek().is_some() {
  406. let n = *iterable.next().unwrap();
  407. if n != range_end + 1 {
  408. break;
  409. }
  410. has_range = true;
  411. range_end = n;
  412. index += 1;
  413. }
  414. (has_range, range_end, index)
  415. }
  416. impl From<Vec<Version>> for ProtoSet {
  417. fn from(mut v: Vec<Version>) -> ProtoSet {
  418. let mut version_pairs: Vec<(Version, Version)> = Vec::new();
  419. v.sort_unstable();
  420. v.dedup();
  421. 'vector: while !v.is_empty() {
  422. let (has_range, end, index): (bool, Version, usize) = find_range(&v);
  423. if has_range {
  424. let first: Version = match v.first() {
  425. Some(x) => *x,
  426. None => continue,
  427. };
  428. let last: Version = match v.get(index) {
  429. Some(x) => *x,
  430. None => continue,
  431. };
  432. debug_assert!(last == end, format!("last = {}, end = {}", last, end));
  433. version_pairs.push((first, last));
  434. v = v.split_off(index + 1);
  435. if v.len() == 0 {
  436. break 'vector;
  437. }
  438. } else {
  439. let last: Version = match v.get(index) {
  440. Some(x) => *x,
  441. None => continue,
  442. };
  443. version_pairs.push((last, last));
  444. v.remove(index);
  445. }
  446. }
  447. ProtoSet::from_slice(&version_pairs[..]).unwrap_or(ProtoSet::default())
  448. }
  449. }
  450. #[cfg(test)]
  451. mod test {
  452. use super::*;
  453. #[test]
  454. fn test_find_range() {
  455. assert_eq!((false, 0, 0), find_range(&vec![]));
  456. assert_eq!((false, 1, 0), find_range(&vec![1]));
  457. assert_eq!((true, 2, 1), find_range(&vec![1, 2]));
  458. assert_eq!((true, 3, 2), find_range(&vec![1, 2, 3]));
  459. assert_eq!((true, 3, 2), find_range(&vec![1, 2, 3, 5]));
  460. }
  461. macro_rules! assert_contains_each {
  462. ($protoset:expr, $versions:expr) => {
  463. for version in $versions {
  464. assert!($protoset.contains(version));
  465. }
  466. };
  467. }
  468. macro_rules! test_protoset_contains_versions {
  469. ($list:expr, $str:expr) => {
  470. let versions: &[Version] = $list;
  471. let protoset: Result<ProtoSet, ProtoverError> = ProtoSet::from_str($str);
  472. assert!(protoset.is_ok());
  473. let p = protoset.unwrap();
  474. assert_contains_each!(p, versions);
  475. };
  476. }
  477. #[test]
  478. fn test_versions_from_str() {
  479. test_protoset_contains_versions!(&[], "");
  480. test_protoset_contains_versions!(&[1], "1");
  481. test_protoset_contains_versions!(&[1, 2], "1,2");
  482. test_protoset_contains_versions!(&[1, 2, 3], "1-3");
  483. test_protoset_contains_versions!(&[1, 2, 5], "1-2,5");
  484. test_protoset_contains_versions!(&[1, 3, 4, 5], "1,3-5");
  485. test_protoset_contains_versions!(&[42, 55, 56, 57, 58], "42,55-58");
  486. }
  487. #[test]
  488. fn test_versions_from_str_ab() {
  489. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("a,b"));
  490. }
  491. #[test]
  492. fn test_versions_from_str_negative_1() {
  493. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("-1"));
  494. }
  495. #[test]
  496. fn test_versions_from_str_commas() {
  497. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str(","));
  498. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("1,,2"));
  499. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("1,2,"));
  500. }
  501. #[test]
  502. fn test_versions_from_str_hyphens() {
  503. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("--1"));
  504. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("-1-2"));
  505. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("1--2"));
  506. }
  507. #[test]
  508. fn test_versions_from_str_triple() {
  509. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("1-2-3"));
  510. }
  511. #[test]
  512. fn test_versions_from_str_1exclam() {
  513. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("1,!"));
  514. }
  515. #[test]
  516. fn test_versions_from_str_percent_equal() {
  517. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("%="));
  518. }
  519. #[test]
  520. fn test_versions_from_str_whitespace() {
  521. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("1,2\n"));
  522. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("1\r,2"));
  523. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("1,\t2"));
  524. }
  525. #[test]
  526. fn test_versions_from_str_overlap() {
  527. assert_eq!(Err(ProtoverError::Overlap), ProtoSet::from_str("1-3,2-4"));
  528. }
  529. #[test]
  530. fn test_versions_from_slice_overlap() {
  531. assert_eq!(
  532. Err(ProtoverError::Overlap),
  533. ProtoSet::from_slice(&[(1, 3), (2, 4)])
  534. );
  535. }
  536. #[test]
  537. fn test_versions_from_str_max() {
  538. assert_eq!(
  539. Err(ProtoverError::ExceedsMax),
  540. ProtoSet::from_str("4294967295")
  541. );
  542. }
  543. #[test]
  544. fn test_versions_from_slice_max() {
  545. assert_eq!(
  546. Err(ProtoverError::ExceedsMax),
  547. ProtoSet::from_slice(&[(4294967295, 4294967295)])
  548. );
  549. }
  550. #[test]
  551. fn test_protoset_contains() {
  552. let protoset: ProtoSet = ProtoSet::from_slice(&[(1, 5), (7, 9), (13, 14)]).unwrap();
  553. for x in 1..6 {
  554. assert!(protoset.contains(&x), format!("should contain {}", x));
  555. }
  556. for x in 7..10 {
  557. assert!(protoset.contains(&x), format!("should contain {}", x));
  558. }
  559. for x in 13..15 {
  560. assert!(protoset.contains(&x), format!("should contain {}", x));
  561. }
  562. for x in [6, 10, 11, 12, 15, 42, 43, 44, 45, 1234584].iter() {
  563. assert!(!protoset.contains(&x), format!("should not contain {}", x));
  564. }
  565. }
  566. #[test]
  567. fn test_protoset_contains_1_3() {
  568. let protoset: ProtoSet = ProtoSet::from_slice(&[(1, 3)]).unwrap();
  569. for x in 1..4 {
  570. assert!(protoset.contains(&x), format!("should contain {}", x));
  571. }
  572. }
  573. macro_rules! assert_protoset_from_vec_contains_all {
  574. ($($x:expr),*) => (
  575. let vec: Vec<Version> = vec!($($x),*);
  576. let protoset: ProtoSet = vec.clone().into();
  577. for x in vec.iter() {
  578. assert!(protoset.contains(&x));
  579. }
  580. )
  581. }
  582. #[test]
  583. fn test_protoset_from_vec_123() {
  584. assert_protoset_from_vec_contains_all!(1, 2, 3);
  585. }
  586. #[test]
  587. fn test_protoset_from_vec_1_315() {
  588. assert_protoset_from_vec_contains_all!(1, 2, 3, 15);
  589. }
  590. #[test]
  591. fn test_protoset_from_vec_unordered() {
  592. let v: Vec<Version> = vec![2, 3, 8, 4, 3, 9, 7, 2];
  593. let ps: ProtoSet = v.into();
  594. assert_eq!(ps.to_string(), "2-4,7-9");
  595. }
  596. #[test]
  597. fn test_protoset_into_vec() {
  598. let ps: ProtoSet = "1-13,42,9001,4294967294".parse().unwrap();
  599. let v: Vec<Version> = ps.into();
  600. assert!(v.contains(&7));
  601. assert!(v.contains(&9001));
  602. assert!(v.contains(&4294967294));
  603. }
  604. }
  605. #[cfg(all(test, feature = "bench"))]
  606. mod bench {
  607. use super::*;
  608. }