set.move 1.4 KB

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