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
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
use std::mem::size_of;
use std::ops::Range;

#[derive(Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
// Map<u16, Vec<u32>>
pub struct ImmutableListMap {
    // offset of std::u32::MAX indicates that the key is not present
    offsets: Vec<u32>,
    values: Vec<u32>,
}

impl ImmutableListMap {
    pub fn get(&self, i: u16) -> &[u32] {
        let i = i as usize;
        let start = self.offsets[i] as usize;
        let end = if i == self.offsets.len() - 1 {
            self.values.len()
        } else {
            self.offsets[i + 1] as usize
        };
        &self.values[start..end]
    }

    pub fn size_in_bytes(&self) -> usize {
        let mut bytes = size_of::<Self>();
        bytes += size_of::<u32>() * self.offsets.len();
        bytes += size_of::<u32>() * self.values.len();

        bytes
    }
}

pub struct ImmutableListMapBuilder {
    entries: Vec<(u16, u32)>,
    num_keys: usize,
}

impl ImmutableListMapBuilder {
    pub fn new(num_keys: usize) -> ImmutableListMapBuilder {
        ImmutableListMapBuilder {
            entries: vec![],
            num_keys,
        }
    }

    pub fn add(&mut self, key: u16, value: u32) {
        self.entries.push((key, value));
    }

    pub fn build(self) -> ImmutableListMap {
        let mut entries = self.entries;
        entries.sort_unstable_by_key(|x| x.0);
        assert!(entries.len() < std::u32::MAX as usize);
        assert!(!entries.is_empty());
        let mut offsets = vec![std::u32::MAX; self.num_keys];
        let mut last_key = entries[0].0;
        offsets[last_key as usize] = 0;
        let mut values = vec![];
        for (index, (key, value)) in entries.iter().enumerate() {
            if last_key != *key {
                last_key = *key;
                offsets[*key as usize] = index as u32;
            }
            values.push(*value);
        }
        for i in (0..offsets.len()).rev() {
            if offsets[i] == std::u32::MAX {
                if i == offsets.len() - 1 {
                    offsets[i] = entries.len() as u32;
                } else {
                    offsets[i] = offsets[i + 1];
                }
            }
        }

        ImmutableListMap { offsets, values }
    }
}

#[derive(Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct UndirectedGraph {
    edges: Vec<(u16, u16)>,
    // Mapping from node id to starting index in edges array
    node_edge_starting_index: U32VecMap,
}

impl UndirectedGraph {
    pub fn with_capacity(start_node: u16, end_node: u16, edges: usize) -> UndirectedGraph {
        UndirectedGraph {
            edges: Vec::with_capacity(edges * 2),
            node_edge_starting_index: U32VecMap::with_capacity(
                start_node as usize,
                end_node as usize,
            ),
        }
    }

    pub fn add_edge(&mut self, node1: u16, node2: u16) {
        self.edges.push((node1, node2));
        self.edges.push((node2, node1));
    }

    pub fn build(&mut self) {
        // Ordering of adjacencies doesn't matter, so just sort by the first node
        self.edges.sort_unstable_by_key(|x| x.0);
        if self.edges.is_empty() {
            return;
        }
        let mut last_node = self.edges[0].0;
        self.node_edge_starting_index.insert(last_node as usize, 0);
        for (index, (node, _)) in self.edges.iter().enumerate() {
            if last_node != *node {
                last_node = *node;
                self.node_edge_starting_index
                    .insert(last_node as usize, index as u32);
            }
        }
    }

    pub fn get_adjacent_nodes(&self, node: u16) -> impl Iterator<Item = u16> + '_ {
        let first_candidate = self.node_edge_starting_index.get(node as usize);
        AdjacentIterator::new(self.edges.iter().skip(first_candidate as usize), node)
    }

    pub fn nodes(&self) -> Vec<u16> {
        let mut result = vec![];
        for &(node, _) in self.edges.iter() {
            if result.is_empty() || result[result.len() - 1] != node {
                result.push(node);
            }
        }

        result
    }
}

struct AdjacentIterator<T> {
    edges: T,
    node: u16,
}

impl<'a, T: Iterator<Item = &'a (u16, u16)>> AdjacentIterator<T> {
    fn new(edges: T, node: u16) -> AdjacentIterator<T> {
        AdjacentIterator { edges, node }
    }
}

impl<'a, T: Iterator<Item = &'a (u16, u16)>> Iterator for AdjacentIterator<T> {
    type Item = u16;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some((node, adjacent)) = self.edges.next() {
            if *node == self.node {
                return Some(*adjacent);
            }
        }
        None
    }
}

#[derive(Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct U16ArrayMap {
    offset: usize,
    elements: Vec<u16>,
}

impl U16ArrayMap {
    pub fn new(start_key: usize, end_key: usize) -> U16ArrayMap {
        U16ArrayMap {
            offset: start_key,
            elements: vec![0; end_key - start_key],
        }
    }

    pub fn size_in_bytes(&self) -> usize {
        size_of::<Self>() + size_of::<u16>() * self.elements.len()
    }

    pub fn swap(&mut self, key: usize, other_key: usize) {
        self.elements.swap(key, other_key);
    }

    pub fn keys(&self) -> Range<usize> {
        self.offset..(self.offset + self.elements.len())
    }

    pub fn insert(&mut self, key: usize, value: u16) {
        self.elements[key - self.offset] = value;
    }

    pub fn get(&self, key: usize) -> u16 {
        self.elements[key - self.offset]
    }

    pub fn decrement(&mut self, key: usize) {
        self.elements[key - self.offset] -= 1;
    }

    pub fn increment(&mut self, key: usize) {
        self.elements[key - self.offset] += 1;
    }
}

#[derive(Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct U32VecMap {
    offset: usize,
    elements: Vec<u32>,
}

impl U32VecMap {
    pub fn new(start_key: usize) -> U32VecMap {
        U32VecMap {
            offset: start_key,
            elements: vec![0; 1],
        }
    }

    pub fn with_capacity(start_key: usize, end_key: usize) -> U32VecMap {
        U32VecMap {
            offset: start_key,
            elements: vec![0; end_key - start_key],
        }
    }

    fn grow_if_necessary(&mut self, index: usize) {
        if index >= self.elements.len() {
            self.elements
                .extend(vec![0; index - self.elements.len() + 1]);
        }
    }

    pub fn size_in_bytes(&self) -> usize {
        size_of::<Self>() + size_of::<u32>() * self.elements.len()
    }

    #[allow(dead_code)]
    pub fn insert(&mut self, key: usize, value: u32) {
        self.grow_if_necessary(key - self.offset);
        self.elements[key - self.offset] = value;
    }

    pub fn get(&self, key: usize) -> u32 {
        if key - self.offset >= self.elements.len() {
            return 0;
        }
        self.elements[key - self.offset]
    }

    pub fn decrement(&mut self, key: usize) {
        self.grow_if_necessary(key - self.offset);
        self.elements[key - self.offset] -= 1;
    }

    pub fn increment(&mut self, key: usize) {
        self.grow_if_necessary(key - self.offset);
        self.elements[key - self.offset] += 1;
    }
}

#[cfg(test)]
mod tests {
    use crate::arraymap::ImmutableListMapBuilder;

    #[test]
    fn list_map() {
        let mut builder = ImmutableListMapBuilder::new(10);
        builder.add(0, 1);
        builder.add(3, 1);
        builder.add(3, 2);

        let map = builder.build();
        assert!(map.get(0).contains(&1));
        assert!(!map.get(0).contains(&2));

        assert!(map.get(3).contains(&1));
        assert!(map.get(3).contains(&2));
        assert!(!map.get(3).contains(&3));

        assert!(!map.get(2).contains(&1));
    }
}