]> git.ozlabs.org Git - ccan/blob - ccan/agar/test/grid.c
agar: Re-entrant Abstract Graph Algorithms
[ccan] / ccan / agar / test / grid.c
1 #include "config.h"
2
3 #include <assert.h>
4
5 #include <ccan/container_of/container_of.h>
6 #include <ccan/ptrint/ptrint.h>
7
8 #include <ccan/agar/agar.h>
9
10 #include "simple-graphr.h"
11
12 static const void *grid_first_edge_r(const struct agar_graph *gr,
13                                      const void *nr)
14 {
15         return int2ptr(1);
16 }
17
18 static const void *grid_next_edge_r(const struct agar_graph *gr,
19                                     const void *nr, const void *e)
20 {
21         int index = ptr2int(e);
22
23         if (index < 4)
24                 return int2ptr(index + 1);
25         else
26                 return NULL;           
27 }
28
29 static int grid_edge_info_r(const struct agar_graph *gr,
30                             const void *nr, const void *e,
31                             struct agar_edge_info *eir)
32 {
33         struct grid_graphr *ggr = container_of(gr, struct grid_graphr, gr);
34         int ni = ptr2int(nr);
35         int x = ((ni - 1) % ggr->nx) + 1;
36         int y = ((ni - 1) / ggr->nx) + 1;
37         int i = ptr2int(e);
38
39         assert((x >= 1) && (x <= ggr->nx));
40         assert((y >= 1) && (y <= ggr->ny));
41
42         switch (i) {
43         case 1: /* right */
44                 if (ggr->right && (x != ggr->nx))
45                         eir->to = int2ptr(ni + 1);
46                 break;
47
48         case 2: /* down */
49                 if (ggr->down && (y != ggr->ny))
50                         eir->to = int2ptr(ni + ggr->nx);
51                 break;
52                 
53         case 3: /* left */
54                 if (ggr->left && (x != 1))
55                         eir->to = int2ptr(ni - 1);
56                 break;
57
58         case 4: /* up */
59                 if (ggr->up && (y != 1))
60                         eir->to = int2ptr(ni - ggr->nx);
61                 break;
62
63         default:
64                 assert(0);
65         }
66         return 0;
67 }
68
69 void grid_graphr_init(struct grid_graphr *ggr, int nx, int ny,
70                      bool right, bool down, bool left, bool up)
71 {
72         ggr->nx = nx;
73         ggr->ny = ny;
74         ggr->right = right;
75         ggr->down = down;
76         ggr->left = left;
77         ggr->up = up;
78
79         agar_init_graph(&ggr->gr, grid_first_edge_r, grid_next_edge_r,
80                         grid_edge_info_r);
81 }