New module, file-set.
[gnulib.git] / lib / file-set.c
1 /* Specialized functions to manipulate a set of files.
2    Copyright (C) 2007 Free Software Foundation, Inc.
3
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.
8
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.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 /* written by Jim Meyering */
19
20 #include <config.h>
21 #include "file-set.h"
22
23 #include "hash-triple.h"
24 #include "xalloc.h"
25
26 /* Record file, FILE, and dev/ino from *STATS, in the hash table, HT.
27    If HT is NULL, return immediately.
28    If memory allocation fails, exit immediately.  */
29 void
30 record_file (Hash_table *ht, char const *file, struct stat const *stats)
31 {
32   struct F_triple *ent;
33
34   if (ht == NULL)
35     return;
36
37   ent = xmalloc (sizeof *ent);
38   ent->name = xstrdup (file);
39   ent->st_ino = stats->st_ino;
40   ent->st_dev = stats->st_dev;
41
42   {
43     struct F_triple *ent_from_table = hash_insert (ht, ent);
44     if (ent_from_table == NULL)
45       {
46         /* Insertion failed due to lack of memory.  */
47         xalloc_die ();
48       }
49
50     if (ent_from_table != ent)
51       {
52         /* There was alread a matching entry in the table, so ENT was
53            not inserted.  Free it.  */
54         triple_free (ent);
55       }
56   }
57 }
58
59 /* Return true if there is an entry in hash table, HT,
60    for the file described by FILE and STATS.  */
61 bool
62 seen_file (Hash_table const *ht, char const *file,
63            struct stat const *stats)
64 {
65   struct F_triple new_ent;
66
67   if (ht == NULL)
68     return false;
69
70   new_ent.name = (char *) file;
71   new_ent.st_ino = stats->st_ino;
72   new_ent.st_dev = stats->st_dev;
73
74   return !!hash_lookup (ht, &new_ent);
75 }