summaryrefslogtreecommitdiffstats
path: root/lib/datastruct/list.h
blob: 3084e88b565db2727a9d680a55e5b9a0736020b2 (plain)
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
/*
 * Copyright (C) 2001 Sistina Software
 *
 * This file is released under the LGPL.
 */

#ifndef _LVM_LIST_H
#define _LVM_LIST_H

#include <assert.h>

struct list {
	struct list *n, *p;
};

static inline void list_init(struct list *head)
{
	head->n = head->p = head;
}

static inline void list_add(struct list *head, struct list *elem)
{
	assert(head->n);

	elem->n = head;
	elem->p = head->p;

	head->p->n = elem;
	head->p = elem;
}

static inline void list_add_h(struct list *head, struct list *elem)
{
	assert(head->n);

	elem->n = head->n;
	elem->p = head;

	head->n->p = elem;
	head->n = elem;
}

static inline void list_del(struct list *elem)
{
	elem->n->p = elem->p;
	elem->p->n = elem->n;
}

static inline int list_empty(struct list *head)
{
	return head->n == head;
}

static inline int list_end(struct list *head, struct list *elem)
{
	return elem->n == head;
}

#define list_iterate(v, head) \
	for (v = (head)->n; v != head; v = v->n)

#define list_iterate_safe(v, t, head) \
	for (v = (head)->n, t = v->n; v != head; v = t, t = v->n)

static inline unsigned int list_size(const struct list *head)
{
	unsigned int s = 0;
	const struct list *v;

	list_iterate(v, head)
	    s++;

	return s;
}

#define list_item(v, t) \
    ((t *)((uintptr_t)(v) - (uintptr_t)&((t *) 0)->list))

/* Given a known element in a known structure, locate another */
#define struct_field(v, t, e, f) \
    (((t *)((uintptr_t)(v) - (uintptr_t)&((t *) 0)->e))->f)

/* Given a known element in a known structure, locate the list head */
#define list_head(v, t, e) struct_field(v, t, e, list)

#endif