| use std::collections::HashSet; |
| use loda_rust_core::util::{BigIntVec, BigIntVecToString}; |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| pub struct PreventFlooding { |
| hashset: HashSet<String>, |
| } |
|
|
| pub enum PreventFloodingError { |
| AlreadyRegistered |
| } |
|
|
| impl PreventFlooding { |
| pub fn new() -> Self { |
| Self { |
| hashset: HashSet::<String>::new(), |
| } |
| } |
|
|
| #[allow(dead_code)] |
| pub fn contains(&self, bigintvec: &BigIntVec) -> bool { |
| let s: String = bigintvec.to_compact_comma_string(); |
| if self.hashset.contains(&s) { |
| return true; |
| } |
| false |
| } |
|
|
| pub fn try_register(&mut self, bigintvec: &BigIntVec) -> Result<(), PreventFloodingError> { |
| let s: String = bigintvec.to_compact_comma_string(); |
| if self.hashset.contains(&s) { |
| |
| return Err(PreventFloodingError::AlreadyRegistered); |
| } |
| self.hashset.insert(s); |
|
|
| |
| Ok(()) |
| } |
|
|
| pub fn len(&self) -> usize { |
| self.hashset.len() |
| } |
| } |
|
|
| #[cfg(test)] |
| mod tests { |
| use super::*; |
| use loda_rust_core::util::BigIntVecFromI64; |
| |
| #[test] |
| fn test_10000_try_register() { |
| let mut pf = PreventFlooding::new(); |
| let bigintvec = BigIntVec::from_i64array(&[1, 2, 3, 4, 5]); |
| assert_eq!(pf.try_register(&bigintvec).is_ok(), true); |
| assert_eq!(pf.try_register(&bigintvec).is_ok(), false); |
| } |
|
|
| #[test] |
| fn test_10001_contains() { |
| let mut pf = PreventFlooding::new(); |
| assert_eq!(pf.contains(&BigIntVec::from_i64array(&[1, 1, 1, 1, 1])), false); |
| assert_eq!(pf.contains(&BigIntVec::from_i64array(&[1, 2, 3, 4, 5])), false); |
| assert_eq!(pf.try_register(&BigIntVec::from_i64array(&[1, 2, 3, 4, 5])).is_ok(), true); |
| assert_eq!(pf.try_register(&BigIntVec::from_i64array(&[1, 1, 1, 1, 1])).is_ok(), true); |
| assert_eq!(pf.contains(&BigIntVec::from_i64array(&[1, 1, 1, 1, 1])), true); |
| assert_eq!(pf.contains(&BigIntVec::from_i64array(&[1, 2, 3, 4, 5])), true); |
| assert_eq!(pf.contains(&BigIntVec::from_i64array(&[1984, 1984, 1984])), false); |
| } |
| } |
|
|