]> mj.ucw.cz Git - eval.git/blob - judge/io.c
Isolate: Serialization of calls to AsciiDoc
[eval.git] / judge / io.c
1 /*
2  *      I/O functions for judges
3  *
4  *      (c) 2007 Martin Mares <mj@ucw.cz>
5  */
6
7 #include <stdlib.h>
8 #include <string.h>
9 #include <unistd.h>
10 #include <fcntl.h>
11
12 #include "judge.h"
13
14 #define BUFSIZE 65536
15
16 struct stream *sopen_fd(char *name, int fd)
17 {
18   char *slash = strrchr(name, '/');
19   char *basename = (slash ? slash+1 : name);
20   struct stream *s = xmalloc(sizeof(*s) + BUFSIZE + strlen(basename) + 1);
21   s->fd = fd;
22   s->pos = s->stop = s->buf;
23   s->end = s->buf + BUFSIZE;
24   s->name = s->end;
25   strcpy(s->name, basename);
26   return s;
27 }
28
29 struct stream *sopen_read(char *name)
30 {
31   int fd = open(name, O_RDONLY);
32   if (fd < 0)
33     die("Unable to open %s for reading: %m", name);
34   return sopen_fd(name, fd);
35 }
36
37 struct stream *sopen_write(char *name)
38 {
39   int fd = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
40   if (fd < 0)
41     die("Unable to open %s for writing: %m", name);
42   return sopen_fd(name, fd);
43 }
44
45 void sflush(struct stream *s)
46 {
47   if (s->pos > s->stop)
48     {
49       char *p = s->buf;
50       int len = s->pos - s->buf;
51       while (len > 0)
52         {
53           int c = write(s->fd, p, len);
54           if (c <= 0)
55             die("Error writing %s: %m", s->name);
56           p += c;
57           len -= c;
58         }
59     }
60   s->pos = s->stop = s->buf;
61 }
62
63 void sclose(struct stream *s)
64 {
65   sflush(s);
66   close(s->fd);
67   free(s);
68 }
69
70 static int srefill(struct stream *s)
71 {
72   int len = read(s->fd, s->buf, BUFSIZE);
73   if (len < 0)
74     die("Error reading %s: %m", s->name);
75   s->pos = s->buf;
76   s->stop = s->buf + len;
77   return len;
78 }
79
80 int sgetc_slow(struct stream *s)
81 {
82   return (srefill(s) ? *s->pos++ : -1);
83 }
84
85 int speekc_slow(struct stream *s)
86 {
87   return (srefill(s) ? *s->pos : -1);
88 }