1 : /*
2 : * Copyright 2008 The Native Client Authors. All rights reserved.
3 : * Use of this source code is governed by a BSD-style license that can
4 : * be 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 : GioFileRead,
18 : GioFileWrite,
19 : GioFileSeek,
20 : GioFileFlush,
21 : GioFileClose,
22 : GioFileDtor,
23 : };
24 :
25 :
26 : int GioFileCtor(struct GioFile *self,
27 : 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 : }
37 :
38 :
39 : int GioFileRefCtor(struct GioFile *self,
40 246 : FILE *iop) {
41 246 : self->iop = iop;
42 :
43 246 : self->base.vtbl = &kGioFileVtbl;
44 246 : return 1;
45 : }
46 :
47 :
48 : ssize_t GioFileRead(struct Gio *vself,
49 : void *buf,
50 19 : size_t count) {
51 19 : struct GioFile *self = (struct GioFile *) vself;
52 : size_t ret;
53 :
54 19 : ret = fread(buf, 1, count, self->iop);
55 19 : if (0 == ret && ferror(self->iop)) {
56 0 : errno = EIO;
57 0 : return -1;
58 : }
59 19 : return (ssize_t) ret;
60 : }
61 :
62 :
63 : ssize_t GioFileWrite(struct Gio *vself,
64 : const void *buf,
65 285277 : size_t count) {
66 285277 : struct GioFile *self = (struct GioFile *) vself;
67 : size_t ret;
68 :
69 285277 : ret = fwrite(buf, 1, count, self->iop);
70 285277 : if (0 == ret && ferror(self->iop)) {
71 0 : errno = EIO;
72 0 : return -1;
73 : }
74 285277 : return (ssize_t) ret;
75 : }
76 :
77 :
78 : off_t GioFileSeek(struct Gio *vself,
79 : off_t offset,
80 14 : int whence) {
81 14 : struct GioFile *self = (struct GioFile *) vself;
82 : int ret;
83 :
84 14 : ret = fseek(self->iop, (long) offset, whence);
85 14 : if (-1 == ret) return -1;
86 :
87 12 : return (off_t) ftell(self->iop);
88 : }
89 :
90 :
91 6749 : int GioFileFlush(struct Gio *vself) {
92 6749 : struct GioFile *self = (struct GioFile *) vself;
93 :
94 6749 : return fflush(self->iop);
95 : }
96 :
97 :
98 5 : int GioFileClose(struct Gio *vself){
99 5 : struct GioFile *self = (struct GioFile *) vself;
100 : int rv;
101 5 : rv = (EOF == fclose(self->iop)) ? -1 : 0;
102 5 : if (0 == rv) {
103 5 : self->iop = (FILE *) 0;
104 : }
105 5 : return rv;
106 : }
107 :
108 :
109 165 : void GioFileDtor(struct Gio *vself) {
110 165 : struct GioFile *self = (struct GioFile *) vself;
111 165 : if (0 != self->iop) {
112 160 : (void) fclose(self->iop);
113 : }
114 165 : }
115 :
116 :
117 0 : int fggetc(struct Gio *gp) {
118 : char ch;
119 :
120 0 : return (*gp->vtbl->Read)(gp, &ch, 1) == 1 ? ch : EOF;
121 : }
|