1 : /*
2 : * Copyright (c) 2012 The Native Client Authors. All rights reserved.
3 : * Use of this source code is governed by a BSD-style license that can be
4 : * found in the LICENSE file.
5 : */
6 :
7 : #include <errno.h>
8 :
9 : /*
10 : * NaCl Generic I/O interface.
11 : */
12 : #include "native_client/src/include/portability.h"
13 :
14 : #include "native_client/src/shared/gio/gio.h"
15 :
16 : struct GioVtbl const kGioFileVtbl = {
17 : GioFileDtor,
18 : GioFileRead,
19 : GioFileWrite,
20 : GioFileSeek,
21 : GioFileFlush,
22 : GioFileClose,
23 : };
24 :
25 :
26 5 : int GioFileCtor(struct GioFile *self,
27 5 : char const *fname,
28 5 : char const *mode) {
29 5 : self->base.vtbl = (struct GioVtbl *) NULL;
30 5 : self->iop = fopen(fname, mode);
31 5 : if (NULL == self->iop) {
32 0 : return 0;
33 : }
34 5 : self->base.vtbl = &kGioFileVtbl;
35 5 : return 1;
36 5 : }
37 :
38 :
39 1572 : int GioFileRefCtor(struct GioFile *self,
40 1572 : FILE *iop) {
41 1572 : self->iop = iop;
42 :
43 1572 : self->base.vtbl = &kGioFileVtbl;
44 1572 : return 1;
45 : }
46 :
47 :
48 19 : ssize_t GioFileRead(struct Gio *vself,
49 19 : void *buf,
50 19 : size_t count) {
51 19 : struct GioFile *self = (struct GioFile *) vself;
52 19 : size_t ret;
53 :
54 19 : ret = fread(buf, 1, count, self->iop);
55 21 : if (0 == ret && ferror(self->iop)) {
56 0 : errno = EIO;
57 0 : return -1;
58 : }
59 19 : return (ssize_t) ret;
60 19 : }
61 :
62 :
63 576978 : ssize_t GioFileWrite(struct Gio *vself,
64 576978 : const void *buf,
65 576978 : size_t count) {
66 576978 : struct GioFile *self = (struct GioFile *) vself;
67 576978 : size_t ret;
68 :
69 576978 : ret = fwrite(buf, 1, count, self->iop);
70 577988 : if (0 == ret && ferror(self->iop)) {
71 0 : errno = EIO;
72 0 : return -1;
73 : }
74 576978 : return (ssize_t) ret;
75 576978 : }
76 :
77 :
78 14 : off_t GioFileSeek(struct Gio *vself,
79 14 : off_t offset,
80 14 : int whence) {
81 14 : struct GioFile *self = (struct GioFile *) vself;
82 14 : int ret;
83 :
84 14 : ret = fseek(self->iop, (long) offset, whence);
85 16 : if (-1 == ret) return -1;
86 :
87 12 : return (off_t) ftell(self->iop);
88 14 : }
89 :
90 :
91 12802 : int GioFileFlush(struct Gio *vself) {
92 12802 : struct GioFile *self = (struct GioFile *) vself;
93 :
94 12802 : return fflush(self->iop);
95 : }
96 :
97 :
98 5 : int GioFileClose(struct Gio *vself){
99 5 : struct GioFile *self = (struct GioFile *) vself;
100 5 : int rv;
101 5 : rv = (EOF == fclose(self->iop)) ? -1 : 0;
102 5 : if (0 == rv) {
103 5 : self->iop = (FILE *) 0;
104 5 : }
105 5 : return rv;
106 : }
107 :
108 :
109 953 : void GioFileDtor(struct Gio *vself) {
110 953 : struct GioFile *self = (struct GioFile *) vself;
111 953 : if (0 != self->iop) {
112 948 : (void) fclose(self->iop);
113 948 : }
114 953 : }
115 :
116 :
117 0 : int fggetc(struct Gio *gp) {
118 0 : char ch;
119 :
120 0 : return (*gp->vtbl->Read)(gp, &ch, 1) == 1 ? ch : EOF;
121 : }
|