set.move 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /// A set data structure.
  2. module pyth::set {
  3. use std::table::{Self, Table};
  4. use std::vector;
  5. /// Empty struct. Used as the value type in mappings to encode a set
  6. struct Unit has store, copy, drop {}
  7. /// A set containing elements of type `A` with support for membership
  8. /// checking.
  9. struct Set<A: copy + drop> has store {
  10. keys: vector<A>,
  11. elems: Table<A, Unit>
  12. }
  13. /// Create a new Set.
  14. public fun new<A: copy + drop>(): Set<A> {
  15. Set {
  16. keys: vector::empty<A>(),
  17. elems: table::new(),
  18. }
  19. }
  20. /// Add a new element to the set.
  21. /// Aborts if the element already exists
  22. public fun add<A: copy + drop>(set: &mut Set<A>, key: A) {
  23. table::add(&mut set.elems, key, Unit {});
  24. vector::push_back(&mut set.keys, key);
  25. }
  26. /// Returns true iff `set` contains an entry for `key`.
  27. public fun contains<A: copy + drop>(set: &Set<A>, key: A): bool {
  28. table::contains(&set.elems, key)
  29. }
  30. /// Removes all elements from the set
  31. public fun empty<A: copy + drop>(set: &mut Set<A>) {
  32. while (!vector::is_empty(&set.keys)) {
  33. table::remove(&mut set.elems, vector::pop_back(&mut set.keys));
  34. }
  35. }
  36. // TODO: destroy_empty, but this is tricky because std::table doesn't
  37. // have this functionality.
  38. }