protoset.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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. /// // Things which would get parsed into an _empty_ `ProtoSet` are,
  328. /// // however, legal, and result in an empty `ProtoSet`:
  329. /// assert_eq!(Ok(ProtoSet::default()), ProtoSet::from_str(""));
  330. /// assert_eq!(Ok(ProtoSet::default()), ProtoSet::from_str(",,,"));
  331. /// #
  332. /// # Ok(protoset)
  333. /// # }
  334. /// # fn main() { do_test(); } // wrap the test so we can use the ? operator
  335. /// ```
  336. fn from_str(version_string: &str) -> Result<Self, Self::Err> {
  337. let mut pairs: Vec<(Version, Version)> = Vec::new();
  338. let pieces: ::std::str::Split<char> = version_string.split(',');
  339. for p in pieces {
  340. if p.is_empty() {
  341. continue;
  342. } else if p.contains('-') {
  343. let mut pair = p.splitn(2, '-');
  344. let low = pair.next().ok_or(ProtoverError::Unparseable)?;
  345. let high = pair.next().ok_or(ProtoverError::Unparseable)?;
  346. let lo: Version = low.parse().or(Err(ProtoverError::Unparseable))?;
  347. let hi: Version = high.parse().or(Err(ProtoverError::Unparseable))?;
  348. if lo == u32::MAX || hi == u32::MAX {
  349. return Err(ProtoverError::ExceedsMax);
  350. }
  351. pairs.push((lo, hi));
  352. } else {
  353. let v: u32 = p.parse().or(Err(ProtoverError::Unparseable))?;
  354. if v == u32::MAX {
  355. return Err(ProtoverError::ExceedsMax);
  356. }
  357. pairs.push((v, v));
  358. }
  359. }
  360. // If we were passed in an empty string, or
  361. // simply a comma, or a pile of commas, then return an empty ProtoSet.
  362. if pairs.len() == 0 {
  363. return Ok(ProtoSet::default());
  364. }
  365. ProtoSet::from_slice(&pairs[..])
  366. }
  367. }
  368. impl ToString for ProtoSet {
  369. /// Contracts a `ProtoSet` of versions into a string.
  370. ///
  371. /// # Returns
  372. ///
  373. /// A `String` representation of this `ProtoSet` in ascending order.
  374. fn to_string(&self) -> String {
  375. let mut final_output: Vec<String> = Vec::new();
  376. for &(lo, hi) in self.iter() {
  377. if lo != hi {
  378. debug_assert!(lo < hi);
  379. final_output.push(format!("{}-{}", lo, hi));
  380. } else {
  381. final_output.push(format!("{}", lo));
  382. }
  383. }
  384. final_output.join(",")
  385. }
  386. }
  387. /// Checks to see if there is a continuous range of integers, starting at the
  388. /// first in the list. Returns the last integer in the range if a range exists.
  389. ///
  390. /// # Inputs
  391. ///
  392. /// `list`, an ordered vector of `u32` integers of "[0-9,-]" representing the
  393. /// supported versions for a single protocol.
  394. ///
  395. /// # Returns
  396. ///
  397. /// A `bool` indicating whether the list contains a range, starting at the first
  398. /// in the list, a`Version` of the last integer in the range, and a `usize` of
  399. /// the index of that version.
  400. ///
  401. /// For example, if given vec![1, 2, 3, 5], find_range will return true,
  402. /// as there is a continuous range, and 3, which is the last number in the
  403. /// continuous range, and 2 which is the index of 3.
  404. fn find_range(list: &Vec<Version>) -> (bool, Version, usize) {
  405. if list.len() == 0 {
  406. return (false, 0, 0);
  407. }
  408. let mut index: usize = 0;
  409. let mut iterable = list.iter().peekable();
  410. let mut range_end = match iterable.next() {
  411. Some(n) => *n,
  412. None => return (false, 0, 0),
  413. };
  414. let mut has_range = false;
  415. while iterable.peek().is_some() {
  416. let n = *iterable.next().unwrap();
  417. if n != range_end + 1 {
  418. break;
  419. }
  420. has_range = true;
  421. range_end = n;
  422. index += 1;
  423. }
  424. (has_range, range_end, index)
  425. }
  426. impl From<Vec<Version>> for ProtoSet {
  427. fn from(mut v: Vec<Version>) -> ProtoSet {
  428. let mut version_pairs: Vec<(Version, Version)> = Vec::new();
  429. v.sort_unstable();
  430. v.dedup();
  431. 'vector: while !v.is_empty() {
  432. let (has_range, end, index): (bool, Version, usize) = find_range(&v);
  433. if has_range {
  434. let first: Version = match v.first() {
  435. Some(x) => *x,
  436. None => continue,
  437. };
  438. let last: Version = match v.get(index) {
  439. Some(x) => *x,
  440. None => continue,
  441. };
  442. debug_assert!(last == end, format!("last = {}, end = {}", last, end));
  443. version_pairs.push((first, last));
  444. v = v.split_off(index + 1);
  445. if v.len() == 0 {
  446. break 'vector;
  447. }
  448. } else {
  449. let last: Version = match v.get(index) {
  450. Some(x) => *x,
  451. None => continue,
  452. };
  453. version_pairs.push((last, last));
  454. v.remove(index);
  455. }
  456. }
  457. ProtoSet::from_slice(&version_pairs[..]).unwrap_or(ProtoSet::default())
  458. }
  459. }
  460. #[cfg(test)]
  461. mod test {
  462. use super::*;
  463. #[test]
  464. fn test_find_range() {
  465. assert_eq!((false, 0, 0), find_range(&vec![]));
  466. assert_eq!((false, 1, 0), find_range(&vec![1]));
  467. assert_eq!((true, 2, 1), find_range(&vec![1, 2]));
  468. assert_eq!((true, 3, 2), find_range(&vec![1, 2, 3]));
  469. assert_eq!((true, 3, 2), find_range(&vec![1, 2, 3, 5]));
  470. }
  471. macro_rules! assert_contains_each {
  472. ($protoset:expr, $versions:expr) => {
  473. for version in $versions {
  474. assert!($protoset.contains(version));
  475. }
  476. };
  477. }
  478. macro_rules! test_protoset_contains_versions {
  479. ($list:expr, $str:expr) => {
  480. let versions: &[Version] = $list;
  481. let protoset: Result<ProtoSet, ProtoverError> = ProtoSet::from_str($str);
  482. assert!(protoset.is_ok());
  483. let p = protoset.unwrap();
  484. assert_contains_each!(p, versions);
  485. };
  486. }
  487. #[test]
  488. fn test_versions_from_str() {
  489. test_protoset_contains_versions!(&[], "");
  490. test_protoset_contains_versions!(&[1], "1");
  491. test_protoset_contains_versions!(&[1, 2], "1,2");
  492. test_protoset_contains_versions!(&[1, 2, 3], "1-3");
  493. test_protoset_contains_versions!(&[1, 2, 5], "1-2,5");
  494. test_protoset_contains_versions!(&[1, 3, 4, 5], "1,3-5");
  495. test_protoset_contains_versions!(&[42, 55, 56, 57, 58], "42,55-58");
  496. }
  497. #[test]
  498. fn test_versions_from_str_ab() {
  499. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("a,b"));
  500. }
  501. #[test]
  502. fn test_versions_from_str_negative_1() {
  503. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("-1"));
  504. }
  505. #[test]
  506. fn test_versions_from_str_hyphens() {
  507. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("--1"));
  508. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("-1-2"));
  509. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("1--2"));
  510. }
  511. #[test]
  512. fn test_versions_from_str_triple() {
  513. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("1-2-3"));
  514. }
  515. #[test]
  516. fn test_versions_from_str_1exclam() {
  517. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("1,!"));
  518. }
  519. #[test]
  520. fn test_versions_from_str_percent_equal() {
  521. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("%="));
  522. }
  523. #[test]
  524. fn test_versions_from_str_whitespace() {
  525. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("1,2\n"));
  526. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("1\r,2"));
  527. assert_eq!(Err(ProtoverError::Unparseable), ProtoSet::from_str("1,\t2"));
  528. }
  529. #[test]
  530. fn test_versions_from_str_overlap() {
  531. assert_eq!(Err(ProtoverError::Overlap), ProtoSet::from_str("1-3,2-4"));
  532. }
  533. #[test]
  534. fn test_versions_from_slice_overlap() {
  535. assert_eq!(
  536. Err(ProtoverError::Overlap),
  537. ProtoSet::from_slice(&[(1, 3), (2, 4)])
  538. );
  539. }
  540. #[test]
  541. fn test_versions_from_str_max() {
  542. assert_eq!(
  543. Err(ProtoverError::ExceedsMax),
  544. ProtoSet::from_str("4294967295")
  545. );
  546. }
  547. #[test]
  548. fn test_versions_from_slice_max() {
  549. assert_eq!(
  550. Err(ProtoverError::ExceedsMax),
  551. ProtoSet::from_slice(&[(4294967295, 4294967295)])
  552. );
  553. }
  554. #[test]
  555. fn test_protoset_contains() {
  556. let protoset: ProtoSet = ProtoSet::from_slice(&[(1, 5), (7, 9), (13, 14)]).unwrap();
  557. for x in 1..6 {
  558. assert!(protoset.contains(&x), format!("should contain {}", x));
  559. }
  560. for x in 7..10 {
  561. assert!(protoset.contains(&x), format!("should contain {}", x));
  562. }
  563. for x in 13..15 {
  564. assert!(protoset.contains(&x), format!("should contain {}", x));
  565. }
  566. for x in [6, 10, 11, 12, 15, 42, 43, 44, 45, 1234584].iter() {
  567. assert!(!protoset.contains(&x), format!("should not contain {}", x));
  568. }
  569. }
  570. #[test]
  571. fn test_protoset_contains_1_3() {
  572. let protoset: ProtoSet = ProtoSet::from_slice(&[(1, 3)]).unwrap();
  573. for x in 1..4 {
  574. assert!(protoset.contains(&x), format!("should contain {}", x));
  575. }
  576. }
  577. macro_rules! assert_protoset_from_vec_contains_all {
  578. ($($x:expr),*) => (
  579. let vec: Vec<Version> = vec!($($x),*);
  580. let protoset: ProtoSet = vec.clone().into();
  581. for x in vec.iter() {
  582. assert!(protoset.contains(&x));
  583. }
  584. )
  585. }
  586. #[test]
  587. fn test_protoset_from_vec_123() {
  588. assert_protoset_from_vec_contains_all!(1, 2, 3);
  589. }
  590. #[test]
  591. fn test_protoset_from_vec_1_315() {
  592. assert_protoset_from_vec_contains_all!(1, 2, 3, 15);
  593. }
  594. #[test]
  595. fn test_protoset_from_vec_unordered() {
  596. let v: Vec<Version> = vec![2, 3, 8, 4, 3, 9, 7, 2];
  597. let ps: ProtoSet = v.into();
  598. assert_eq!(ps.to_string(), "2-4,7-9");
  599. }
  600. #[test]
  601. fn test_protoset_into_vec() {
  602. let ps: ProtoSet = "1-13,42,9001,4294967294".parse().unwrap();
  603. let v: Vec<Version> = ps.into();
  604. assert!(v.contains(&7));
  605. assert!(v.contains(&9001));
  606. assert!(v.contains(&4294967294));
  607. }
  608. }
  609. #[cfg(all(test, feature = "bench"))]
  610. mod bench {
  611. use super::*;
  612. }