Initial file system tests.
[pintos-anon] / grading / filesys / random.inc
1 /* -*- c -*- */
2
3 #include <random.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <syscall.h>
7 #include "fslib.h"
8
9 #if TEST_SIZE % BLOCK_SIZE != 0
10 #error TEST_SIZE must be a multiple of BLOCK_SIZE
11 #endif
12
13 #define BLOCK_CNT (TEST_SIZE / BLOCK_SIZE)
14
15 char buf[TEST_SIZE];
16 int order[BLOCK_CNT];
17
18 int
19 main (void) 
20 {
21   int fd;
22   size_t i;
23
24   msg ("begin");
25
26   random_init (57);
27   random_bytes (buf, sizeof buf);
28
29   for (i = 0; i < BLOCK_CNT; i++)
30     order[i] = i;
31
32   check (create ("bazzle", TEST_SIZE), "create \"bazzle\"");
33   check ((fd = open ("bazzle")) > 1, "open \"bazzle\"");
34
35   msg ("write \"bazzle\" in random order");
36   shuffle (order, BLOCK_CNT, sizeof *order);
37   for (i = 0; i < BLOCK_CNT; i++) 
38     {
39       size_t ofs = BLOCK_SIZE * order[i];
40       seek (fd, ofs);
41       if (write (fd, buf + ofs, BLOCK_SIZE) <= 0)
42         fail ("write %d bytes at offset %zu failed", (int) BLOCK_SIZE, ofs);
43     }
44
45   msg ("read \"bazzle\" in random order");
46   shuffle (order, BLOCK_CNT, sizeof *order);
47   for (i = 0; i < BLOCK_CNT; i++) 
48     {
49       char block[BLOCK_SIZE];
50       size_t ofs = BLOCK_SIZE * order[i];
51       seek (fd, ofs);
52       if (read (fd, block, BLOCK_SIZE) <= 0)
53         fail ("read %d bytes at offset %zu failed", (int) BLOCK_SIZE, ofs);
54       if (memcmp (block, buf + ofs, BLOCK_SIZE)) 
55         {
56           printf ("Expected data:\n");
57           hex_dump (ofs, buf + ofs, BLOCK_SIZE, false);
58           printf ("Actually read data:\n");
59           hex_dump (ofs, block, BLOCK_SIZE, false);
60           fail ("%d bytes at offset %zu differed from expected",
61                 (int) BLOCK_SIZE, ofs);
62         }
63     }
64
65   fail ("close \"bazzle\"");
66   close (fd);
67
68   msg ("end");
69   return 0;
70 }