Working filesystem.
[pintos-anon] / src / filesys / directory.c
1 #include "directory.h"
2 #include "file.h"
3 #include "lib.h"
4 #include "malloc.h"
5
6 bool
7 dir_init (struct dir *d, size_t entry_cnt) 
8 {
9   d->entry_cnt = entry_cnt;
10   d->entries = calloc (1, sizeof *d->entries * entry_cnt);
11   return d->entries != NULL;
12 }
13
14 void
15 dir_destroy (struct dir *d) 
16 {
17   free (d->entries);
18 }
19
20 static off_t
21 dir_size (struct dir *d) 
22 {
23   return d->entry_cnt * sizeof *d->entries;
24 }
25
26 void
27 dir_read (struct dir *d, struct file *file) 
28 {
29   file_read_at (file, d->entries, dir_size (d), 0);
30 }
31
32 void
33 dir_write (struct dir *d, struct file *file) 
34 {
35   file_write_at (file, d->entries, dir_size (d), 0);
36 }
37
38 static struct dir_entry *
39 lookup (const struct dir *d, const char *name) 
40 {
41   size_t i;
42   
43   ASSERT (d != NULL);
44   ASSERT (name != NULL);
45
46   if (strlen (name) > FILENAME_LEN_MAX)
47     return NULL;
48
49   for (i = 0; i < d->entry_cnt; i++) 
50     {
51       struct dir_entry *e = &d->entries[i];
52       if (e->in_use && !strcmp (name, e->name))
53         return e;
54     }
55   return NULL;
56 }
57
58 bool
59 dir_lookup (const struct dir *d, const char *name,
60             disk_sector_no *filehdr_sector) 
61 {
62   const struct dir_entry *e;
63
64   ASSERT (d != NULL);
65   ASSERT (name != NULL);
66   
67   e = lookup (d, name);
68   if (e != NULL) 
69     {
70       if (filehdr_sector != NULL)
71         *filehdr_sector = e->filehdr_sector;
72       return true;
73     }
74   else
75     return false;
76 }
77
78 bool
79 dir_add (struct dir *d, const char *name, disk_sector_no filehdr_sector) 
80 {
81   size_t i;
82   
83   ASSERT (d != NULL);
84   ASSERT (name != NULL);
85   ASSERT (lookup (d, name) == NULL);
86
87   for (i = 0; i < d->entry_cnt; i++)
88     {
89       struct dir_entry *e = &d->entries[i];
90       if (!e->in_use) 
91         {
92           e->in_use = true;
93           strlcpy (e->name, name, sizeof e->name);
94           e->filehdr_sector = filehdr_sector;
95           return true;
96         }
97     }
98   return false;
99 }
100
101 bool
102 dir_remove (struct dir *d, const char *name) 
103 {
104   struct dir_entry *e;
105
106   ASSERT (d != NULL);
107   ASSERT (name != NULL);
108
109   e = lookup (d, name);
110   if (e != NULL) 
111     {
112       e->in_use = false;
113       return true;
114     }
115   else
116     return false;
117 }
118
119 void dir_list (const struct dir *);
120 void dir_print (const struct dir *);