dup_filter.rs 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. /*! Filter duplicate shows of credentials and open invitations by id
  2. * (which will typically be a Scalar). This implementation just keeps
  3. * the table of seen ids in memory, but a production one would of course
  4. * use a disk-backed database. */
  5. use std::cmp::Eq;
  6. use std::collections::HashMap;
  7. use std::hash::Hash;
  8. /// Each instance of DupFilter maintains its own independent table of
  9. /// seen ids. IdType will typically be Scalar.
  10. #[derive(Default, Debug)]
  11. pub struct DupFilter<IdType> {
  12. seen_table: HashMap<IdType, ()>,
  13. }
  14. impl<IdType: Hash + Eq + Copy> DupFilter<IdType> {
  15. /// Check to see if the id is in the seen table, but do not add it
  16. /// to the seen table. Return true if it is already in the table,
  17. /// false if not.
  18. pub fn check(&self, id: &IdType) -> bool {
  19. self.seen_table.contains_key(id)
  20. }
  21. /// As atomically as possible, check to see if the id is in the seen
  22. /// table, and add it if not. Return Ok(()) if it was not already
  23. /// in the table, and Err(()) if it was.
  24. pub fn filter(&mut self, id: &IdType) -> Result<(), ()> {
  25. match self.seen_table.insert(*id, ()) {
  26. None => Ok(()),
  27. Some(()) => Err(()),
  28. }
  29. }
  30. }