]> git.cameronkatri.com Git - mandoc.git/blob - dba_write.c
POSIX allows PATH_MAX to not be defined, meaning "unlimited".
[mandoc.git] / dba_write.c
1 /* $Id: dba_write.c,v 1.2 2016/07/20 00:23:14 schwarze Exp $ */
2 /*
3 * Copyright (c) 2016 Ingo Schwarze <schwarze@openbsd.org>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 *
17 * Low-level functions for serializing allocation-based data to disk.
18 * The interface is defined in "dba_write.h".
19 */
20 #include "config.h"
21
22 #include <assert.h>
23 #include <endian.h>
24 #if HAVE_ERR
25 #include <err.h>
26 #endif
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <stdint.h>
30 #include <stdio.h>
31
32 #include "dba_write.h"
33
34 static FILE *ofp;
35
36
37 int
38 dba_open(const char *fname)
39 {
40 ofp = fopen(fname, "w");
41 return ofp == NULL ? -1 : 0;
42 }
43
44 int
45 dba_close(void)
46 {
47 return fclose(ofp) == EOF ? -1 : 0;
48 }
49
50 int32_t
51 dba_tell(void)
52 {
53 long pos;
54
55 if ((pos = ftell(ofp)) == -1)
56 err(1, "ftell");
57 if (pos >= INT32_MAX) {
58 errno = EOVERFLOW;
59 err(1, "ftell = %ld", pos);
60 }
61 return pos;
62 }
63
64 void
65 dba_seek(int32_t pos)
66 {
67 if (fseek(ofp, pos, SEEK_SET) == -1)
68 err(1, "fseek(%d)", pos);
69 }
70
71 int32_t
72 dba_align(void)
73 {
74 int32_t pos;
75
76 pos = dba_tell();
77 while (pos & 3) {
78 dba_char_write('\0');
79 pos++;
80 }
81 return pos;
82 }
83
84 int32_t
85 dba_skip(int32_t nmemb, int32_t sz)
86 {
87 const int32_t out[5] = {0, 0, 0, 0, 0};
88 int32_t i, pos;
89
90 assert(sz >= 0);
91 assert(nmemb > 0);
92 assert(nmemb <= 5);
93 pos = dba_tell();
94 for (i = 0; i < sz; i++)
95 if (nmemb - fwrite(&out, sizeof(out[0]), nmemb, ofp))
96 err(1, "fwrite");
97 return pos;
98 }
99
100 void
101 dba_char_write(int c)
102 {
103 if (putc(c, ofp) == EOF)
104 err(1, "fputc");
105 }
106
107 void
108 dba_str_write(const char *str)
109 {
110 if (fputs(str, ofp) == EOF)
111 err(1, "fputs");
112 dba_char_write('\0');
113 }
114
115 void
116 dba_int_write(int32_t i)
117 {
118 i = htobe32(i);
119 if (fwrite(&i, sizeof(i), 1, ofp) != 1)
120 err(1, "fwrite");
121 }