xref: /plan9-contrib/sys/src/libndb/ndbreorder.c (revision 95a264b3d2508e9e4f5589ac908b62aedc5a9755)
1 #include <u.h>
2 #include <libc.h>
3 #include <bio.h>
4 #include <ndb.h>
5 
6 /*
7  *  reorder the tuple to put x's line first in the entry and x fitst in its line
8  */
9 Ndbtuple*
ndbreorder(Ndbtuple * t,Ndbtuple * x)10 ndbreorder(Ndbtuple *t, Ndbtuple *x)
11 {
12 	Ndbtuple *nt;
13 	Ndbtuple *last, *prev;
14 
15 	/* if x is first, we're done */
16 	if(x == t)
17 		return t;
18 
19 	/* find end of x's line */
20 	for(last = x; last->line == last->entry; last = last->line)
21 		;
22 
23 	/* rotate to make this line first */
24 	if(last->line != t){
25 
26 		/* detach this line and everything after it from the entry */
27 		for(nt = t; nt->entry != last->line; nt = nt->entry)
28 			;
29 		nt->entry = nil;
30 
31 		/* switch */
32 		for(nt = last; nt->entry != nil; nt = nt->entry)
33 			;
34 		nt->entry = t;
35 	}
36 
37 	/* rotate line to make x first */
38 	if(x != last->line){
39 
40 		/* find entry before x */
41 		for(prev = last; prev->line != x; prev = prev->line);
42 			;
43 
44 		/* detach line */
45 		nt = last->entry;
46 		last->entry = last->line;
47 
48 		/* reattach */
49 		prev->entry = nt;
50 	}
51 
52 	return x;
53 }
54