-
Notifications
You must be signed in to change notification settings - Fork 8
/
set.oc
68 lines (55 loc) · 1.34 KB
/
set.oc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//! A hash-set implementation.
import std::map::{ Map, Item, Iterator as MapIterator }
import std::mem
struct Set<T> {
map: &Map<T, bool>
size: u32
}
def Set::new(): &Set<T> {
let set = mem::alloc<Set<T>>()
set.map = Map<T, bool>::new()
return set
}
[operator "+="]
def Set::add(&this, key: T) {
.map.insert(key, true)
.size = .map.size
}
[operator "-="]
def Set::remove(&this, key: T) {
.map.remove(key)
.size = .map.size
}
def Set::clear(&this) {
.map.clear()
.size = 0
}
[operator "+="]
def Set::extend(&this, other: &Set<T>) {
.map.extend(other.map)
.size = .map.size
}
[operator "-="]
def Set::subtract(&this, other: &Set<T>) {
for let iter = other.iter(); iter.has_value(); iter.next() {
.remove(iter.cur())
}
.size = .map.size
}
[operator "in"]
def Set::contains(&this, key: T): bool => .map.contains(key)
def Set::iter(&this): Iterator<T> => Iterator<T>::make(this)
def Set::is_empty(&this): bool => .map.size == 0
def Set::free(&this) {
.map.free()
mem::free(this)
}
struct Iterator<T> {
map_iter: MapIterator<T, bool>
}
def Iterator::make(set: &Set<T>): Iterator<T> => Iterator<T>(set.map.iter())
def Iterator::has_value(&this): bool => .map_iter.has_value()
def Iterator::cur(&this): T => .map_iter.cur().key
def Iterator::next(&this) {
.map_iter.next()
}