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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/*
 * SPDX-License-Identifier: MIT
 */
use std::marker::PhantomData;
use std::ptr::{addr_of, null, null_mut};

use spa_sys::spa_list;

use pipewire_wrapper_proc_macro::RawWrapper;

use crate::wrapper::RawWrapper;

#[derive(RawWrapper, Debug)]
#[repr(transparent)]
pub struct ListRef {
    #[raw]
    raw: spa_sys::spa_list,
}

/// Linked list element.
/// Usually, data structures should have [spa_sys::spa_list] pointer at the first place.
/// So, the pointer to the list element can be casted to the structure itself.
/// In general, this struct should not be used outside the library.
///
/// # Example
/// ```
/// use spa_sys::spa_list;
/// struct TestElement {
///    link: spa_list,
///    payload: u32,
/// }
/// ```
pub trait ListElement {
    /// Raw pointer to the list element
    fn as_list_ptr(&self) -> *mut spa_list;

    /// Cast the list element pointer to Self
    fn from_list_ptr(ptr: *mut spa_list) -> *mut Self;

    /// Init the list element as detached.
    ///
    /// # Safety
    ///
    /// [Self::as_list_ptr] must provide valid non-null pointer, that will not be changed in future.
    unsafe fn init_detached(&mut self) {
        let list = self.as_list_ptr();
        (*list).prev = list;
        (*list).next = list;
    }

    /// Remove the element from the list
    ///
    /// # Safety
    ///
    /// [Self::as_list_ptr] must provide valid non-null pointer, that will not be changed in future.
    unsafe fn remove(&mut self) {
        let list = self.as_list_ptr();

        (*(*list).prev).next = (*list).next;
        (*(*list).next).prev = (*list).prev;
    }
}

impl ListElement for ListRef {
    fn as_list_ptr(&self) -> *mut spa_list {
        self.as_raw_ptr()
    }

    fn from_list_ptr(ptr: *mut spa_list) -> *mut Self {
        ptr as *mut Self
    }
}

/// Linked list with [ListElement]
/// In general, this struct should not be used outside the library.
pub trait List
where
    Self: Sized,
{
    type Elem: ListElement;

    /// Raw pointer to the list itself
    fn as_list_ptr(&self) -> *mut spa_list;

    /// Cast the list pointer to Self
    fn from_list_ptr(ptr: *mut spa_list) -> *mut Self;

    /// Init the list structure as empty list
    fn init(&mut self) {
        unsafe {
            let list = self.as_list_ptr();
            (*list).next = list;
            (*list).prev = list;
        }
    }

    /// Check if this list was initialized
    fn initialized(&self) -> bool {
        unsafe {
            let list = self.as_list_ptr();
            !(*list).prev.is_null()
        }
    }

    fn empty(&self) -> bool {
        let list = self.as_list_ptr();
        unsafe { (*list).next == (*list).prev && std::ptr::eq((*list).next, list) }
    }

    /// Insert [ListElement] to the list
    ///
    /// # Safety
    ///
    /// [Self::as_list_ptr] must provide valid non-null pointer, that will not be changed in future.
    unsafe fn insert(&mut self, elem: &mut Self::Elem) {
        let list = self.as_list_ptr();
        let elem = elem.as_list_ptr();
        (*elem).prev = list;
        (*elem).next = (*list).next;
        (*list).next = elem;
        (*(*elem).next).prev = elem;
    }

    /// Join two lists
    ///
    /// # Safety
    ///
    /// [Self::as_list_ptr] must provide valid non-null pointer, that will not be changed in future.
    unsafe fn insert_list(&mut self, other: &mut Self) {
        if !other.empty() {
            let list = self.as_list_ptr();
            let other = other.as_list_ptr();
            (*(*other).next).prev = list;
            (*(*other).prev).next = (*list).next;
            (*(*list).next).prev = (*other).prev;
            (*list).next = (*other).next;
        }
    }

    /// Get the next element from the list
    ///
    /// # Safety
    ///
    /// [Self::as_list_ptr] must provide valid non-null pointer, that will not be changed in future.
    unsafe fn next(&self, current: &Self::Elem) -> Option<&mut Self::Elem> {
        let link = (*current.as_list_ptr()).next;
        if link == self.as_list_ptr() {
            None
        } else {
            Some(&mut *Self::Elem::from_list_ptr(link))
        }
    }

    /// Get the previous element from the list
    ///
    /// # Safety
    ///
    /// [Self::as_list_ptr] must provide valid non-null pointer, that will not be changed in future.
    unsafe fn prev(&self, current: &Self::Elem) -> Option<&mut Self::Elem> {
        let link = (*current.as_list_ptr()).prev;
        if link == self.as_list_ptr() {
            None
        } else {
            Some(&mut *Self::Elem::from_list_ptr(link))
        }
    }

    /// Get the first element from the list
    ///
    /// # Safety
    ///
    /// [Self::as_list_ptr] must provide valid non-null pointer, that will not be changed in future.
    unsafe fn first(&self) -> Option<&mut Self::Elem> {
        let list = self.as_list_ptr();
        let first = (*list).next;
        if first == list {
            None
        } else {
            Some(&mut *Self::Elem::from_list_ptr(first))
        }
    }

    /// Get the last element from the list
    ///
    /// # Safety
    ///
    /// [Self::as_list_ptr] must provide valid non-null pointer, that will not be changed in future.
    unsafe fn last(&self) -> Option<&mut Self::Elem> {
        let list = self.as_list_ptr();
        let last = (*list).prev;
        if last == list {
            None
        } else {
            Some(&mut *Self::Elem::from_list_ptr(last))
        }
    }

    /// Append element to the list
    ///
    /// # Safety
    ///
    /// [Self::as_list_ptr] must provide valid non-null pointer, that will not be changed in future.
    unsafe fn append(&mut self, elem: &mut Self::Elem) {
        let list = (*self.as_list_ptr()).prev;
        let elem = elem.as_list_ptr();
        (*elem).prev = list;
        (*elem).next = (*list).next;
        (*list).next = elem;
        (*(*elem).next).prev = elem;
    }

    /// Prepend element to the list
    ///
    /// # Safety
    ///
    /// [Self::as_list_ptr] must provide valid non-null pointer, that will not be changed in future.
    unsafe fn prepend(&mut self, elem: &mut Self::Elem) {
        self.insert(elem)
    }

    /// Clean the list
    ///
    /// # Safety
    ///
    /// [Self::as_list_ptr] must provide valid non-null pointer, that will not be changed in future.
    unsafe fn clean(&mut self) {
        while let Some(first) = self.first() {
            first.remove()
        }
    }

    /// Get the list iterator
    ///
    /// # Safety
    ///
    /// [Self::as_list_ptr] must provide valid non-null pointer, that will not be changed in future.
    unsafe fn iter(&self) -> ListIterator<Self> {
        ListIterator {
            list: self,
            element: None,
        }
    }

    /// Get the list mut iterator
    ///
    /// # Safety
    ///
    /// [Self::as_list_ptr] must provide valid non-null pointer, that will not be changed in future.
    unsafe fn iter_mut(&self) -> ListMutIterator<Self> {
        ListMutIterator {
            list: self,
            element: None,
        }
    }
}

pub struct ListIterator<'l, L: List> {
    list: &'l L,
    element: Option<&'l L::Elem>,
}

impl<'l, L: List> Iterator for ListIterator<'l, L> {
    type Item = &'l L::Elem;

    fn next(&mut self) -> Option<Self::Item> {
        let next_ptr = if let Some(element) = self.element {
            unsafe { (*element.as_list_ptr()).next }
        } else {
            unsafe { (*self.list.as_list_ptr()).next }
        };
        if next_ptr == self.list.as_list_ptr() {
            None
        } else {
            self.element = unsafe { Some(&*(L::Elem::from_list_ptr(next_ptr))) };
            self.element
        }
    }
}

pub struct ListMutIterator<'l, L: List> {
    list: &'l L,
    element: Option<*mut spa_list>,
}

impl<'l, L: List> Iterator for ListMutIterator<'l, L> {
    type Item = &'l mut L::Elem;

    fn next(&mut self) -> Option<Self::Item> {
        let next_ptr = if let Some(element) = self.element {
            unsafe { (*element).next }
        } else {
            unsafe { (*self.list.as_list_ptr()).next }
        };
        if next_ptr == self.list.as_list_ptr() {
            None
        } else {
            self.element = Some(next_ptr);
            unsafe { Some(&mut *(L::Elem::from_list_ptr(next_ptr))) }
        }
    }
}

#[repr(C)]
#[cfg(test)]
#[derive(RawWrapper)]
struct TestList {
    #[raw]
    list: spa_list,
}

#[repr(C)]
#[cfg(test)]
#[derive(Debug)]
struct TestElement {
    link: spa_list,
    payload: u32,
}

#[cfg(test)]
impl ListElement for TestElement {
    fn as_list_ptr(&self) -> *mut spa_list {
        addr_of!(self.link) as *mut _
    }

    fn from_list_ptr(ptr: *mut spa_list) -> *mut Self {
        ptr as *mut Self
    }
}

#[cfg(test)]
impl List for TestList {
    type Elem = TestElement;

    fn as_list_ptr(&self) -> *mut spa_list {
        addr_of!(self.list) as *mut _
    }

    fn from_list_ptr(ptr: *mut spa_list) -> *mut Self {
        ptr as *mut Self
    }
}

#[cfg(test)]
impl TestElement {
    fn new(payload: u32) -> Self {
        Self {
            link: spa_list {
                next: null_mut(),
                prev: null_mut(),
            },
            payload,
        }
    }
}

#[cfg(test)]
impl Default for TestList {
    fn default() -> Self {
        Self {
            list: spa_list {
                next: null_mut(),
                prev: null_mut(),
            },
        }
    }
}

#[test]
fn test_init() {
    let mut list = TestList::default();

    unsafe {
        assert!(!list.initialized());
        list.init();
        assert!(list.initialized());
    }
}

#[test]
fn test_empty() {
    let mut list = TestList::default();
    unsafe {
        list.init();
        assert!(list.empty());
    }
}

#[test]
fn test_insert() {
    let mut list = TestList::default();

    unsafe {
        list.init();
        let mut elem1 = TestElement::new(1);
        let mut elem2 = TestElement::new(2);
        assert!(list.empty());

        list.insert(&mut elem1);

        assert!(!list.empty());
        assert_eq!(list.first().unwrap().payload, elem1.payload);
        assert!(list.next(&elem1).is_none());
        assert!(list.prev(&elem1).is_none());

        list.insert(&mut elem2);
        assert_eq!(list.first().unwrap().payload, elem2.payload);
        assert_eq!(list.next(&elem2).unwrap().payload, elem1.payload);
        assert!(list.next(&elem1).is_none());
    }
}

#[test]
fn test_insert_list() {
    let mut list1 = TestList::default();
    let mut list2 = TestList::default();

    unsafe {
        list1.init();
        list2.init();
        let mut elem1 = TestElement::new(1);
        let mut elem2 = TestElement::new(2);
        let mut elem3 = TestElement::new(3);
        let mut elem4 = TestElement::new(4);

        list1.insert(&mut elem1);
        list1.insert(&mut elem2);

        list2.insert(&mut elem3);
        list2.insert(&mut elem4);

        list1.insert_list(&mut list2);

        let current = list1.first();
        assert_eq!(current.as_ref().unwrap().payload, 4);
        let current = list1.next(current.unwrap());
        assert_eq!(current.as_ref().unwrap().payload, 3);
        let current = list1.next(current.unwrap());
        assert_eq!(current.as_ref().unwrap().payload, 2);
        let current = list1.next(current.unwrap());
        assert_eq!(current.as_ref().unwrap().payload, 1);
        let current = list1.next(current.unwrap());
        assert!(current.is_none());
    }
}

#[test]
fn test_iterator() {
    let mut list1 = TestList::default();
    unsafe {
        let mut elem1 = TestElement::new(1);
        let mut elem2 = TestElement::new(2);
        let mut elem3 = TestElement::new(3);
        let mut elem4 = TestElement::new(4);

        list1.init();
        list1.insert(&mut elem1);
        list1.insert(&mut elem2);
        list1.insert(&mut elem3);
        list1.insert(&mut elem4);

        let mut iter = list1.iter();

        assert_eq!(iter.next().unwrap().payload, 4);
        assert_eq!(iter.next().unwrap().payload, 3);
        assert_eq!(iter.next().unwrap().payload, 2);
        assert_eq!(iter.next().unwrap().payload, 1);

        assert!(iter.next().is_none());
    }
}

#[test]
fn test_mut_iterator() {
    let mut list1 = TestList::default();
    unsafe {
        let mut elem1 = TestElement::new(1);
        let mut elem2 = TestElement::new(2);
        let mut elem3 = TestElement::new(3);
        let mut elem4 = TestElement::new(4);

        list1.init();
        list1.insert(&mut elem1);
        list1.insert(&mut elem2);
        list1.insert(&mut elem3);
        list1.insert(&mut elem4);

        let mut iter = list1.iter_mut();

        assert_eq!(iter.next().unwrap().payload, 4);
        assert_eq!(iter.next().unwrap().payload, 3);
        assert_eq!(iter.next().unwrap().payload, 2);
        assert_eq!(iter.next().unwrap().payload, 1);

        assert!(iter.next().is_none());
    }
}