Merge branch 'pu'
[jungerl.git] / lib / posix_drv / c_src / erl_driver_tk.c
blobb5b3f2f8fc523a2a374c32c11c0717850ee5ae96
1 /*
2 ** Copyright (c) 2003, Scott Lystig Fritchie. All rights reserved.
3 ** See the file "../LICENSE" for license details.
4 */
6 #include <stdio.h>
7 #include <stdarg.h>
9 #include <erl_driver.h>
10 #include <erl_driver_tk.h>
12 int edtk_debug_flag = 1;
14 void *
15 edtk_driver_alloc_wrapper(size_t size)
17 ErlDrvBinary *eb;
19 edtk_debug("%s: top", __FUNCTION__);
20 if ((eb = driver_alloc_binary(size)) != NULL) {
21 edtk_debug("%s: size %lu eb = 0x%lx orig_bytes = 0x%lx", __FUNCTION__, size, eb, eb->orig_bytes);
22 return eb->orig_bytes;
23 } else {
24 return NULL;
28 void *
29 edtk_driver_realloc_wrapper(void *p, size_t size)
31 ErlDrvBinary *eb, *neweb;
33 edtk_debug("%s: top", __FUNCTION__);
34 if ((eb = edtk_alloced_ptr2ErlDrvBinary(p)) != NULL) {
35 if ((neweb = driver_realloc_binary(eb, size)) != NULL) {
36 return neweb->orig_bytes;
37 } else {
38 return NULL;
40 } else {
41 return NULL;
45 void
46 edtk_driver_free_wrapper(void *p)
48 ErlDrvBinary *eb;
50 edtk_debug("%s: top", __FUNCTION__);
51 if ((eb = edtk_alloced_ptr2ErlDrvBinary(p)) != NULL) {
52 edtk_debug("%s: eb = 0x%lx p = 0x%lx", __FUNCTION__, eb, p);
53 driver_free_binary(eb);
57 /* QQQ Make this a macro, use scratch static ErlDrvBinary? */
58 ErlDrvBinary *
59 edtk_alloced_ptr2ErlDrvBinary(void *p)
61 ErlDrvBinary stackeb;
62 int offset = stackeb.orig_bytes - (char *) &stackeb;
64 if (p != NULL) {
65 edtk_debug("%s: p = 0x%lx eb = 0x%lx", __FUNCTION__, p, (ErlDrvBinary *) ((char *) p - offset));
66 return (ErlDrvBinary *) ((char *) p - offset);
67 } else {
68 return NULL;
72 int
73 edtk_debug(char *f, ...)
75 va_list ap;
76 int res;
78 va_start(ap, f);
79 if (edtk_debug_flag) {
80 res = vfprintf(DEBUGIO, f, ap);
81 fprintf(DEBUGIO, "\r\n");
83 va_end(ap);
84 return res;
87 void
88 edtk_debug_errcall(const char *errpfx, char *msg)
90 if (edtk_debug_flag)
91 fprintf(stderr, "\t\t\t\t\t%s: %s: %s\r\n", __FUNCTION__, errpfx, msg);
94 void
95 edtk_free_data(void *data)
97 if (data != NULL)
98 sys_free(data);
102 ** Arg want_contiguous: if true, return error if the 'n' we're forwarding
103 ** past are in a single contiguous buffer.
105 ** Return value:
106 ** -1 = error
107 ** 0 = Success, there is no more data to be read
108 ** 1 = Success
112 edtk_ev_forward_N(ErlIOVec *ev, int n, int *pp, int *qp, int want_contiguous)
114 int forward_pos = *pp + n;
116 if ((*qp) >= ev->vsize) {
117 return -1;
119 if (forward_pos < ev->iov[*qp].iov_len) {
120 *pp += n;
121 return 1;
122 } else if (forward_pos == ev->iov[*qp].iov_len) {
123 (*qp)++;
124 *pp = 0;
125 if ((*qp) < ev->vsize) {
126 return 1;
127 } else {
128 return 0;
130 } else {
131 n -= (ev->iov[*qp].iov_len - *pp);
132 (*qp)++;
133 (*pp) = 0;
134 if ((*qp) < ev->vsize && ! want_contiguous) {
135 return edtk_ev_forward_N(ev, n, pp, qp, want_contiguous);
136 } else {
137 return -1;