Upstream version 10.38.222.0
[platform/framework/web/crosswalk.git] / src / native_client / src / shared / gio / gio_mem_snapshot.c
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 /*
8  * NaCl Generic I/O interface implementation: in-memory snapshot of a file.
9  */
10
11 #include "native_client/src/include/portability.h"
12 #include <stdio.h>
13 #include <sys/stat.h>
14 #include <stdlib.h>
15
16 #include "native_client/src/shared/gio/gio.h"
17
18 struct GioVtbl const  kGioMemoryFileSnapshotVtbl = {
19   GioMemoryFileSnapshotDtor,
20   GioMemoryFileRead,
21   GioMemoryFileWrite,
22   GioMemoryFileSeek,
23   GioMemoryFileFlush,
24   GioMemoryFileClose,
25 };
26
27
28 int   GioMemoryFileSnapshotCtor(struct GioMemoryFileSnapshot  *self,
29                                 const char                    *filename) {
30   FILE            *iop;
31   struct stat     stbuf;
32   char            *buffer;
33
34   ((struct Gio *) self)->vtbl = (struct GioVtbl *) NULL;
35   if (0 == (iop = fopen(filename, "rb"))) {
36     return 0;
37   }
38   if (fstat(fileno(iop), &stbuf) == -1) {
39  abort0:
40     fclose(iop);
41     return 0;
42   }
43   if (0 == (buffer = malloc(stbuf.st_size))) {
44     goto abort0;
45   }
46   if (fread(buffer, 1, stbuf.st_size, iop) != (size_t) stbuf.st_size) {
47  abort1:
48     free(buffer);
49     goto abort0;
50   }
51   if (GioMemoryFileCtor(&self->base, buffer, stbuf.st_size) == 0) {
52     goto abort1;
53   }
54   (void) fclose(iop);
55
56   ((struct Gio *) self)->vtbl = &kGioMemoryFileSnapshotVtbl;
57   return 1;
58 }
59
60
61 void GioMemoryFileSnapshotDtor(struct Gio                     *vself) {
62   struct GioMemoryFileSnapshot  *self = (struct GioMemoryFileSnapshot *)
63       vself;
64   free(self->base.buffer);
65   GioMemoryFileDtor(vself);
66 }