*** empty log message ***
[coreutils.git] / lib / cycle-check.c
blobfb1746fcf7afdb39ee4268b5b5bd0414b37c8f85
1 /* help detect directory cycles efficiently
2 Copyright 2003 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
7 any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; see the file COPYING.
16 If not, write to the Free Software Foundation,
17 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
19 /* Written by Jim Meyering */
21 #if HAVE_CONFIG_H
22 # include <config.h>
23 #endif
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <stdio.h>
28 #include <assert.h>
29 #include <stdlib.h>
31 #if HAVE_STDBOOL_H
32 # include <stdbool.h>
33 #else
34 typedef enum {false = 0, true = 1} bool;
35 #endif
37 #include "cycle-check.h"
38 #include "xalloc.h"
40 #define SAME_INODE(Stat_buf_1, Stat_buf_2) \
41 ((Stat_buf_1).st_ino == (Stat_buf_2).st_ino \
42 && (Stat_buf_1).st_dev == (Stat_buf_2).st_dev)
44 #define CC_MAGIC 9827862
46 static inline bool
47 is_power_of_two (unsigned int i)
49 return (i & (i - 1)) == 0;
52 void
53 cycle_check_init (struct cycle_check_state *state)
55 state->chdir_counter = 0;
56 state->magic = CC_MAGIC;
59 /* In traversing a directory hierarchy, call this function once for each
60 descending chdir call, with SB corresponding to the chdir operand.
61 If SB corresponds to a directory that has already been seen,
62 return true to indicate that there is a directory cycle.
63 Note that this is done `lazily', which means that some of
64 the directories in the cycle may be processed twice before
65 the cycle is detected. */
67 bool
68 cycle_check (struct cycle_check_state *state, struct stat const *sb)
70 assert (state->magic == CC_MAGIC);
72 /* If the current directory ever happens to be the same
73 as the one we last recorded for the cycle detection,
74 then it's obviously part of a cycle. */
75 if (state->chdir_counter && SAME_INODE (*sb, state->dev_ino))
76 return true;
78 /* If the number of `descending' chdir calls is a power of two,
79 record the dev/ino of the current directory. */
80 if (is_power_of_two (++(state->chdir_counter)))
82 state->dev_ino.st_dev = sb->st_dev;
83 state->dev_ino.st_ino = sb->st_ino;
86 return false;