summaryrefslogtreecommitdiff
path: root/plugins/dumb/dumb-kode54/src/helpers/memfile.c
blob: 6fcbbc7cd375dc64172d9d519f01cac67956a2f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*  _______         ____    __         ___    ___
 * \    _  \       \    /  \  /       \   \  /   /       '   '  '
 *  |  | \  \       |  |    ||         |   \/   |         .      .
 *  |  |  |  |      |  |    ||         ||\  /|  |
 *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
 *  |  |  |  |      |  |    ||         ||    |  |         .      .
 *  |  |_/  /        \  \__//          ||    |  |
 * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
 *                                                      /  \
 *                                                     / .  \
 * memfile.c - Module for reading data from           / / \  \
 *             memory using a DUMBFILE.              | <  /   \_
 *                                                   |  \/ /\   /
 * By entheh.                                         \_  /  > /
 *                                                      | \ / /
 *                                                      |  ' /
 *                                                       \__/
 */

#include <stdlib.h>
#include <string.h>

#include "dumb.h"



typedef struct MEMFILE MEMFILE;

struct MEMFILE
{
	const char *ptr;
	long left;
};



static int dumb_memfile_skip(void *f, long n)
{
	MEMFILE *m = f;
	if (n > m->left) return -1;
	m->ptr += n;
	m->left -= n;
	return 0;
}



static int dumb_memfile_getc(void *f)
{
	MEMFILE *m = f;
	if (m->left <= 0) return -1;
	m->left--;
	return *(const unsigned char *)m->ptr++;
}



static long dumb_memfile_getnc(char *ptr, long n, void *f)
{
	MEMFILE *m = f;
	if (n > m->left) n = m->left;
	memcpy(ptr, m->ptr, n);
	m->ptr += n;
	m->left -= n;
	return n;
}



static void dumb_memfile_close(void *f)
{
	free(f);
}



static const DUMBFILE_SYSTEM memfile_dfs = {
	NULL,
	&dumb_memfile_skip,
	&dumb_memfile_getc,
	&dumb_memfile_getnc,
	&dumb_memfile_close
};



DUMBFILE *dumbfile_open_memory(const char *data, long size)
{
	MEMFILE *m = malloc(sizeof(*m));
	if (!m) return NULL;

	m->ptr = data;
	m->left = size;

	return dumbfile_open_ex(m, &memfile_dfs);
}