Code

t0081 (line-buffer): add buffering tests
[git.git] / test-line-buffer.c
1 /*
2  * test-line-buffer.c: code to exercise the svn importer's input helper
3  */
5 #include "git-compat-util.h"
6 #include "vcs-svn/line_buffer.h"
8 static uint32_t strtouint32(const char *s)
9 {
10         char *end;
11         uintmax_t n = strtoumax(s, &end, 10);
12         if (*s == '\0' || *end != '\0')
13                 die("invalid count: %s", s);
14         return (uint32_t) n;
15 }
17 static void handle_command(const char *command, const char *arg, struct line_buffer *buf)
18 {
19         switch (*command) {
20         case 'c':
21                 if (!prefixcmp(command, "copy ")) {
22                         buffer_copy_bytes(buf, strtouint32(arg));
23                         return;
24                 }
25         case 'r':
26                 if (!prefixcmp(command, "read ")) {
27                         const char *s = buffer_read_string(buf, strtouint32(arg));
28                         fputs(s, stdout);
29                         return;
30                 }
31         case 's':
32                 if (!prefixcmp(command, "skip ")) {
33                         buffer_skip_bytes(buf, strtouint32(arg));
34                         return;
35                 }
36         default:
37                 die("unrecognized command: %s", command);
38         }
39 }
41 static void handle_line(const char *line, struct line_buffer *stdin_buf)
42 {
43         const char *arg = strchr(line, ' ');
44         if (!arg)
45                 die("no argument in line: %s", line);
46         handle_command(line, arg + 1, stdin_buf);
47 }
49 int main(int argc, char *argv[])
50 {
51         struct line_buffer stdin_buf = LINE_BUFFER_INIT;
52         struct line_buffer file_buf = LINE_BUFFER_INIT;
53         struct line_buffer *input = &stdin_buf;
54         const char *filename;
55         char *s;
57         if (argc == 1)
58                 filename = NULL;
59         else if (argc == 2)
60                 filename = argv[1];
61         else
62                 usage("test-line-buffer [file] < script");
64         if (buffer_init(&stdin_buf, NULL))
65                 die_errno("open error");
66         if (filename) {
67                 if (buffer_init(&file_buf, filename))
68                         die_errno("error opening %s", filename);
69                 input = &file_buf;
70         }
72         while ((s = buffer_read_line(&stdin_buf)))
73                 handle_line(s, input);
75         if (filename && buffer_deinit(&file_buf))
76                 die("error reading from %s", filename);
77         if (buffer_deinit(&stdin_buf))
78                 die("input error");
79         if (ferror(stdout))
80                 die("output error");
81         buffer_reset(&stdin_buf);
82         return 0;
83 }