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.
8 * NaCl Generic I/O interface implementation: memory buffer-based I/O.
10 #include "native_client/src/include/portability.h"
15 #include "native_client/src/shared/gio/gio.h"
18 * Memory file is just read/write from/to an in-memory buffer. Once
19 * the buffer is consumed, there is no refilling/flushing.
22 #if !defined(SIZE_T_MAX)
23 # define SIZE_T_MAX ((size_t) -1)
26 struct GioVtbl const kGioMemoryFileVtbl = {
36 int GioMemoryFileCtor(struct GioMemoryFile *self,
39 self->buffer = buffer;
43 self->base.vtbl = &kGioMemoryFileVtbl;
48 ssize_t GioMemoryFileRead(struct Gio *vself,
51 struct GioMemoryFile *self = (struct GioMemoryFile *) vself;
55 /* 0 <= self->curpos && self->curpos <= self->len */
56 remain = self->len - self->curpos;
57 /* 0 <= remain <= self->len */
61 /* 0 <= count && count <= remain */
65 newpos = self->curpos + count;
66 /* self->curpos <= newpos && newpos <= self->len */
68 memcpy(buf, self->buffer + self->curpos, count);
69 self->curpos = newpos;
74 ssize_t GioMemoryFileWrite(struct Gio *vself,
77 struct GioMemoryFile *self = (struct GioMemoryFile *) vself;
81 /* 0 <= self->curpos && self->curpos <= self->len */
82 remain = self->len - self->curpos;
83 /* 0 <= remain <= self->len */
87 /* 0 <= count && count <= remain */
91 newpos = self->curpos + count;
92 /* self->curpos <= newpos && newpos <= self->len */
94 memcpy(self->buffer + self->curpos, buf, count);
95 self->curpos = newpos;
96 /* we never extend a memory file */
101 off_t GioMemoryFileSeek(struct Gio *vself,
104 struct GioMemoryFile *self = (struct GioMemoryFile *) vself;
105 size_t new_pos = (size_t) -1;
112 new_pos = self->curpos + offset;
115 new_pos = (size_t) (self->len + offset);
122 * on error, new_pos should be SIZE_T_MAX. On overflow it will either
123 * be greater than self->len, or will have wrapped around.
124 * TODO (ilewis): Detect wraparound and return an error.
126 if (new_pos > self->len) {
130 self->curpos = new_pos;
131 return (off_t) new_pos;
135 int GioMemoryFileClose(struct Gio *vself) {
136 UNREFERENCED_PARAMETER(vself);
141 int GioMemoryFileFlush(struct Gio *vself) {
142 UNREFERENCED_PARAMETER(vself);
147 void GioMemoryFileDtor(struct Gio *vself) {
148 UNREFERENCED_PARAMETER(vself);