summaryrefslogtreecommitdiff
path: root/lib/slists.c
blob: 00f3c84f48ed35e24ecba554374d012a80a8e7b6 (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
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
/*
 *	BIRD Library -- Safe Linked Lists
 *
 *	(c) 1998 Martin Mares <mj@ucw.cz>
 *
 *	Can be freely distributed and used under the terms of the GNU GPL.
 */

#define _BIRD_SLISTS_C_

#include "nest/bird.h"
#include "lib/slists.h"

static inline void
s_merge(snode *from, snode *to)
{
  siterator *f, *g;

  if (!(f = from->readers))
    return;
  if (!(g = to->readers))
    {
      /* Fast path */
      to->readers = f;
      f->prev = (siterator *) to;
    fixup:
      while (f && f->node)
	{
	  f->node = NULL;
	  f = f->next;
	}
      return;
    }
  /* Really merging */
  while (g->next)
    g = g->next;
  g->next = f;
  f->prev = g;
  goto fixup;
}

snode *
s_get(siterator *i)
{
  siterator *f, *g;
  snode *n;

  if (!(n = i->node))
    {
      /*
       * No node found. We have to walk the iterator list backwards
       * to find where are we linked.
       */
      f = i;
      while (!f->null)
	f = f->prev;
      n = (snode *) f;
    }
  f = i->prev;				/* Maybe the snode itself */
  g = i->next;
  f->next = g;
  if (g)
    g->prev = f;

  i->prev = NULL;
  i->next = NULL;
  return n;
}

void
s_put(siterator *i, snode *n)
{
  siterator *f;

  i->node = n;
  if (f = n->readers)
    f->prev = i;
  i->next = f;
  n->readers = i;
  i->prev = (siterator *) n;
  i->null = NULL;
}

void
s_add_tail(slist *l, snode *n)
{
  snode *z = l->tail;

  n->next = (snode *) &l->null;
  n->prev = z;
  z->next = n;
  l->tail = n;
  n->readers = NULL;
}

void
s_add_head(slist *l, snode *n)
{
  snode *z = l->head;

  n->next = z;
  n->prev = (snode *) &l->head;
  z->prev = n;
  l->head = n;
  n->readers = NULL;
}

void
s_insert_node(snode *n, snode *after)
{
  snode *z = after->next;

  n->next = z;
  n->prev = after;
  after->next = n;
  z->prev = n;
  n->readers = NULL;
}

void
s_rem_node(snode *n)
{
  snode *z = n->prev;
  snode *x = n->next;

  z->next = x;
  x->prev = z;
  s_merge(n, x);
}

void
s_init_list(slist *l)
{
  l->head = (snode *) &l->null;
  l->null = NULL;
  l->tail = (snode *) &l->head;
  l->tail_readers = NULL;
}

void
s_add_tail_list(slist *to, slist *l)
{
  snode *p = to->tail;
  snode *q = l->head;

  p->next = q;
  q->prev = p;
  q = l->tail;
  q->next = (snode *) &to->null;
  to->tail = q;
  s_merge((snode *) &l->null, (snode *) &to->null);
}