[sdks] Fix README.md
[mono-project.git] / tools / sgen / sgen-entry-stream.c
blob479f0c24574f81ae61086e043002387532fc3c96
1 /*
2 * sgen-entry-stream.c: EntryStream implementation
4 * Copyright (C) 2016 Xamarin Inc
6 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
7 */
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <glib.h>
12 #include "sgen-entry-stream.h"
14 #define BUFFER_SIZE (1 << 20)
16 void
17 init_stream (EntryStream *stream, int file)
19 stream->file = file;
20 stream->buffer = g_malloc0 (BUFFER_SIZE);
21 stream->end = stream->buffer + BUFFER_SIZE;
22 stream->pos = stream->end;
25 void
26 reset_stream (EntryStream *stream)
28 stream->end = stream->buffer + BUFFER_SIZE;
29 stream->pos = stream->end;
30 lseek (stream->file, 0, SEEK_SET);
33 void
34 close_stream (EntryStream *stream)
36 g_free (stream->buffer);
39 gboolean
40 refill_stream (EntryStream *in, size_t size)
42 size_t remainder = in->end - in->pos;
43 ssize_t refilled;
44 g_assert (size > 0);
45 g_assert (in->pos >= in->buffer);
46 if (in->pos + size <= in->end)
47 return TRUE;
48 memmove (in->buffer, in->pos, remainder);
49 in->pos = in->buffer;
50 refilled = read (in->file, in->buffer + remainder, BUFFER_SIZE - remainder);
51 if (refilled < 0)
52 return FALSE;
53 g_assert (refilled + remainder <= BUFFER_SIZE);
54 in->end = in->buffer + refilled + remainder;
55 return in->end - in->buffer >= size;
58 ssize_t
59 read_stream (EntryStream *stream, void *out, size_t size)
61 if (refill_stream (stream, size)) {
62 memcpy (out, stream->pos, size);
63 stream->pos += size;
64 return size;
66 return 0;