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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
use super::freelist::*;
use std::ptr::NonNull;

#[derive(Debug)]
pub struct IntArrayFreeList {
    pub head: i32,
    pub heads: i32,
    pub table: Option<Vec<i32>>,
    parent: Option<NonNull<IntArrayFreeList>>,
}

unsafe impl Send for IntArrayFreeList {}
unsafe impl Sync for IntArrayFreeList {}

impl FreeList for IntArrayFreeList {
    fn head(&self) -> i32 {
        self.head
    }
    fn heads(&self) -> i32 {
        self.heads
    }
    fn get_entry(&self, index: i32) -> i32 {
        self.table()[index as usize]
    }
    fn set_entry(&mut self, index: i32, value: i32) {
        self.table_mut()[index as usize] = value;
    }
}

impl IntArrayFreeList {
    pub fn new(units: usize, grain: i32, heads: usize) -> Self {
        debug_assert!(units <= MAX_UNITS as usize && heads <= MAX_HEADS as usize);
        // allocate the data structure, including space for top & bottom sentinels
        let len = (units + 1 + heads) << 1;
        let mut iafl = IntArrayFreeList {
            head: -1,
            heads: heads as _,
            table: Some(vec![0; len]), // len=2052
            parent: None,
        };
        iafl.initialize_heap(units as _, grain);
        iafl
    }
    pub fn from_parent(parent: &IntArrayFreeList, ordinal: i32) -> Self {
        let parent_ptr = std::ptr::NonNull::from(parent);
        let iafl = IntArrayFreeList {
            head: -(1 + ordinal),
            heads: parent.heads,
            table: None,
            parent: Some(parent_ptr),
        };
        debug_assert!(-iafl.head <= iafl.heads);
        iafl
    }
    pub(crate) fn get_ordinal(&self) -> i32 {
        -self.head - 1
    }
    fn table(&self) -> &Vec<i32> {
        match self.parent {
            Some(p) => unsafe { p.as_ref().table() },
            None => self.table.as_ref().unwrap(),
        }
    }

    // FIXME: We need a safe implementation

    fn table_mut(&mut self) -> &mut Vec<i32> {
        match self.parent {
            Some(mut p) => unsafe { p.as_mut().table_mut() },
            None => self.table.as_mut().unwrap(),
        }
    }
    pub fn resize_freelist(&mut self, units: usize, grain: i32) {
        // debug_assert!(self.parent.is_none() && !selected_plan::PLAN.is_initialized());
        *self.table_mut() = vec![0; (units + 1 + self.heads as usize) << 1];
        self.initialize_heap(units as _, grain);
    }
}

#[cfg(test)]
mod tests {
    use super::FreeList;
    use super::*;

    const LIST_SIZE: usize = 5;
    const TOP_SENTINEL: i32 = -1;
    const FIRST_UNIT: i32 = 0;
    const LAST_UNIT: i32 = LIST_SIZE as i32 - 1;
    const BOTTOM_SENTINEL: i32 = LIST_SIZE as i32;

    #[test]
    #[allow(clippy::cognitive_complexity)] // extensive checks, and it doesn't matter for tests
    fn new_free_list_grain1() {
        let l = IntArrayFreeList::new(LIST_SIZE, 1, 1);
        assert_eq!(l.head(), TOP_SENTINEL);

        assert_eq!(l.get_prev(TOP_SENTINEL), LAST_UNIT);
        assert_eq!(l.get_next(TOP_SENTINEL), FIRST_UNIT);

        assert_eq!(l.get_size(FIRST_UNIT), 1);
        assert_eq!(l.get_left(FIRST_UNIT), -1);
        assert_eq!(l.get_prev(FIRST_UNIT), -1);
        assert_eq!(l.get_right(FIRST_UNIT), 1);
        assert_eq!(l.get_next(FIRST_UNIT), 1);
        assert!(l.is_free(FIRST_UNIT));
        assert!(l.is_coalescable(FIRST_UNIT));
        assert!(!l.is_multi(FIRST_UNIT));

        assert_eq!(l.get_size(1), 1);
        assert_eq!(l.get_left(1), 0);
        assert_eq!(l.get_prev(1), 0);
        assert_eq!(l.get_right(1), 2);
        assert_eq!(l.get_next(1), 2);
        assert!(l.is_free(1));
        assert!(l.is_coalescable(1));
        assert!(!l.is_multi(1));

        assert_eq!(l.get_size(LAST_UNIT), 1);
        assert_eq!(l.get_left(LAST_UNIT), LAST_UNIT - 1);
        assert_eq!(l.get_prev(LAST_UNIT), LAST_UNIT - 1);
        assert_eq!(l.get_right(LAST_UNIT), BOTTOM_SENTINEL);
        assert_eq!(l.get_next(LAST_UNIT), -1);
        assert!(l.is_free(LAST_UNIT));
        assert!(l.is_coalescable(LAST_UNIT));
        assert!(!l.is_multi(LAST_UNIT));

        assert_eq!(l.get_prev(BOTTOM_SENTINEL), BOTTOM_SENTINEL);
        assert_eq!(l.get_next(BOTTOM_SENTINEL), BOTTOM_SENTINEL);
    }

    #[test]
    #[allow(clippy::cognitive_complexity)] // extensive checks, and it doesn't matter for tests
    fn new_free_list_grain2() {
        let l = IntArrayFreeList::new(LIST_SIZE, 2, 1);
        assert_eq!(l.head(), TOP_SENTINEL);

        assert_eq!(l.get_prev(TOP_SENTINEL), LAST_UNIT);
        assert_eq!(l.get_next(TOP_SENTINEL), FIRST_UNIT);

        assert_eq!(l.get_size(FIRST_UNIT), 2);
        assert_eq!(l.get_left(FIRST_UNIT), -1);
        assert_eq!(l.get_prev(FIRST_UNIT), -1);
        assert_eq!(l.get_right(FIRST_UNIT), 2);
        assert_eq!(l.get_next(FIRST_UNIT), 2);
        assert!(l.is_free(FIRST_UNIT));
        assert!(l.is_coalescable(FIRST_UNIT));
        assert!(l.is_multi(FIRST_UNIT));

        assert_eq!(l.get_size(2), 2);
        assert_eq!(l.get_left(2), 0);
        assert_eq!(l.get_prev(2), 0);
        assert_eq!(l.get_right(2), 4);
        assert_eq!(l.get_next(2), 4);
        assert!(l.is_free(2));
        assert!(l.is_coalescable(2));
        assert!(l.is_multi(2));

        assert_eq!(l.get_size(LAST_UNIT), 1);
        assert_eq!(l.get_left(LAST_UNIT), LAST_UNIT - 2);
        assert_eq!(l.get_prev(LAST_UNIT), LAST_UNIT - 2);
        assert_eq!(l.get_right(LAST_UNIT), BOTTOM_SENTINEL);
        assert_eq!(l.get_next(LAST_UNIT), -1);
        assert!(l.is_free(LAST_UNIT));
        assert!(l.is_coalescable(LAST_UNIT));
        assert!(!l.is_multi(LAST_UNIT));

        assert_eq!(l.get_prev(BOTTOM_SENTINEL), BOTTOM_SENTINEL);
        assert_eq!(l.get_next(BOTTOM_SENTINEL), BOTTOM_SENTINEL);
    }

    #[test]
    #[should_panic]
    fn free_list_access_out_of_bounds() {
        let l = IntArrayFreeList::new(LIST_SIZE, 1, 1);
        l.get_size((LIST_SIZE + 1) as i32);
    }

    #[test]
    fn alloc_fit() {
        let mut l = IntArrayFreeList::new(LIST_SIZE, 2, 1);
        let result = l.alloc(2);
        assert_eq!(result, 0);

        const NEXT: i32 = 2;

        assert_eq!(l.get_prev(TOP_SENTINEL), LAST_UNIT);
        assert_eq!(l.get_next(TOP_SENTINEL), NEXT);

        assert_eq!(l.get_size(FIRST_UNIT), 2);
        assert_eq!(l.get_left(FIRST_UNIT), -1);
        assert_eq!(l.get_prev(FIRST_UNIT), -1);
        assert_eq!(l.get_right(FIRST_UNIT), 2);
        assert_eq!(l.get_next(FIRST_UNIT), 2);
        assert!(!l.is_free(FIRST_UNIT)); // not free
        assert!(l.is_coalescable(FIRST_UNIT));
        assert!(l.is_multi(FIRST_UNIT));

        assert_eq!(l.get_size(2), 2);
        assert_eq!(l.get_left(2), 0);
        assert_eq!(l.get_prev(2), -1); // no prev now
        assert_eq!(l.get_right(2), 4);
        assert_eq!(l.get_next(2), 4);
        assert!(l.is_free(2));
        assert!(l.is_coalescable(2));
        assert!(l.is_multi(2));
    }

    #[test]
    #[allow(clippy::cognitive_complexity)] // extensive checks, and it doesn't matter for tests
    fn alloc_split() {
        let mut l = IntArrayFreeList::new(LIST_SIZE, 2, 1);
        let result = l.alloc(1);
        assert_eq!(result, 0);

        const NEXT: i32 = 1;
        assert_eq!(l.get_prev(TOP_SENTINEL), LAST_UNIT);
        assert_eq!(l.get_next(TOP_SENTINEL), NEXT);

        assert_eq!(l.get_size(FIRST_UNIT), 1);
        assert_eq!(l.get_left(FIRST_UNIT), -1);
        assert_eq!(l.get_prev(FIRST_UNIT), 1); // prev is 1 now
        assert_eq!(l.get_right(FIRST_UNIT), 1); // right is 1 now
        assert_eq!(l.get_next(FIRST_UNIT), 2);
        assert!(!l.is_free(FIRST_UNIT)); // not free
        assert!(l.is_coalescable(FIRST_UNIT));
        assert!(!l.is_multi(FIRST_UNIT)); // not multi

        assert_eq!(l.get_size(1), 1);
        assert_eq!(l.get_left(1), 0); // unit1's left is 0
        assert_eq!(l.get_prev(1), -1); // unit1's prev is -1 (no prev, unit1 is removed form the list)
        assert_eq!(l.get_right(1), 2);
        assert_eq!(l.get_next(1), 2);
        assert!(l.is_free(1)); // not free
        assert!(l.is_coalescable(1));
        assert!(!l.is_multi(1)); // not multi

        assert_eq!(l.get_size(2), 2);
        assert_eq!(l.get_left(2), 1);
        assert_eq!(l.get_prev(2), 1); // uni2's prev is 1 now
        assert_eq!(l.get_right(2), 4);
        assert_eq!(l.get_next(2), 4);
        assert!(l.is_free(2));
        assert!(l.is_coalescable(2));
        assert!(l.is_multi(2));
    }

    #[test]
    fn alloc_split_twice() {
        let mut l = IntArrayFreeList::new(LIST_SIZE, 2, 1);
        // Alloc size 1 and cause split
        let res1 = l.alloc(1);
        assert_eq!(res1, 0);
        // Alloc size 1
        let res2 = l.alloc(1);
        assert_eq!(res2, 1);

        // Next available unit has no prev now
        assert_eq!(l.get_prev(2), -1);
    }

    #[test]
    fn alloc_skip() {
        let mut l = IntArrayFreeList::new(LIST_SIZE, 2, 1);
        // Alloc size 1 and cause split
        let res1 = l.alloc(1);
        assert_eq!(res1, 0);
        // Alloc size 2, we skip unit1
        let res2 = l.alloc(2);
        assert_eq!(res2, 2);

        // unit1 is still free, and linked with unit4
        assert!(l.is_free(1));
        assert_eq!(l.get_next(1), 4);
        assert_eq!(l.get_prev(4), 1);
    }

    #[test]
    fn alloc_exhaust() {
        let mut l = IntArrayFreeList::new(LIST_SIZE, 2, 1);
        let res1 = l.alloc(2);
        assert_eq!(res1, 0);
        let res2 = l.alloc(2);
        assert_eq!(res2, 2);
        let res3 = l.alloc(2);
        assert_eq!(res3, FAILURE);
    }

    #[test]
    fn free_unit() {
        let mut l = IntArrayFreeList::new(LIST_SIZE, 2, 1);
        let res1 = l.alloc(2);
        assert_eq!(res1, 0);
        let res2 = l.alloc(2);
        assert_eq!(res2, 2);

        // Unit4 is still free, but has no prev
        assert_eq!(l.get_prev(4), -1);

        // Free Unit2
        let freed = l.free(res2, false);
        assert_eq!(freed, res2);
        assert!(l.is_free(res2));
    }

    #[test]
    fn free_coalesce() {
        let mut l = IntArrayFreeList::new(LIST_SIZE, 2, 1);
        let res1 = l.alloc(2);
        assert_eq!(res1, 0);
        let res2 = l.alloc(2);
        assert_eq!(res2, 2);

        // Free Unit2. It will coalesce with Unit4
        let coalesced_size = l.free(res2, true);
        assert_eq!(coalesced_size, 3);
    }

    #[test]
    fn free_cant_coalesce() {
        let mut l = IntArrayFreeList::new(LIST_SIZE, 2, 1);
        let res1 = l.alloc(2);
        assert_eq!(res1, 0);
        let res2 = l.alloc(2);
        assert_eq!(res2, 2);
        let res3 = l.alloc(1);
        assert_eq!(res3, 4);

        // Free Unit2. It cannot coalesce with Unit4
        let coalesced_size = l.free(res2, true);
        assert_eq!(coalesced_size, 2);
    }

    #[test]
    fn free_realloc() {
        let mut l = IntArrayFreeList::new(LIST_SIZE, 2, 1);
        let res1 = l.alloc(2);
        assert_eq!(res1, 0);
        let res2 = l.alloc(2);
        assert_eq!(res2, 2);

        // Unit4 is still free, but has no prev
        assert_eq!(l.get_prev(4), -1);

        // Free Unit2
        let freed = l.free(res2, false);
        assert_eq!(freed, res2);
        assert!(l.is_free(res2));

        // Alloc again
        let res3 = l.alloc(2);
        assert_eq!(res3, 2);
        assert!(!l.is_free(res3));

        let res4 = l.alloc(1);
        assert_eq!(res4, 4);
    }

    #[test]
    fn multi_heads_alloc_free() {
        let parent = IntArrayFreeList::new(LIST_SIZE, 1, 2);
        let mut child1 = IntArrayFreeList::from_parent(&parent, 0);
        let child2 = IntArrayFreeList::from_parent(&parent, 1);

        // child1 alloc
        let res = child1.alloc(1);
        assert_eq!(res, 0);
        assert!(!parent.is_free(0));
        assert!(!child1.is_free(0));
        assert!(!child2.is_free(0));

        // child1 free
        child1.free(0, false);
        assert!(parent.is_free(0));
        assert!(child1.is_free(0));
        assert!(child2.is_free(0));
    }

    #[test]
    #[should_panic]
    fn multi_heads_exceed_heads() {
        let parent = IntArrayFreeList::new(LIST_SIZE, 1, 2);
        let _child1 = IntArrayFreeList::from_parent(&parent, 0);
        let _child2 = IntArrayFreeList::from_parent(&parent, 1);
        let _child3 = IntArrayFreeList::from_parent(&parent, 2);
    }
}