#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "gd.h"
#include "gdhelpers.h"
typedef struct ssIOCtx
{
gdIOCtx ctx;
gdSourcePtr src;
gdSinkPtr snk;
} ssIOCtx;
typedef struct ssIOCtx *ssIOCtxPtr;
gdIOCtx *gdNewSSCtx (gdSourcePtr src, gdSinkPtr snk);
static int sourceGetbuf (gdIOCtx *, void *, int);
static int sourceGetchar (gdIOCtx * ctx);
static int sinkPutbuf (gdIOCtx * ctx, const void *buf, int size);
static void sinkPutchar (gdIOCtx * ctx, int a);
static void gdFreeSsCtx (gdIOCtx * ctx);
gdIOCtx * gdNewSSCtx (gdSourcePtr src, gdSinkPtr snk)
{
ssIOCtxPtr ctx;
ctx = (ssIOCtxPtr) gdMalloc (sizeof (ssIOCtx));
ctx->src = src;
ctx->snk = snk;
ctx->ctx.getC = sourceGetchar;
ctx->ctx.getBuf = sourceGetbuf;
ctx->ctx.putC = sinkPutchar;
ctx->ctx.putBuf = sinkPutbuf;
ctx->ctx.tell = NULL;
ctx->ctx.seek = NULL;
ctx->ctx.gd_free = gdFreeSsCtx;
return (gdIOCtx *) ctx;
}
static void gdFreeSsCtx (gdIOCtx * ctx)
{
gdFree(ctx);
}
static int sourceGetbuf (gdIOCtx * ctx, void *buf, int size)
{
ssIOCtx *lctx;
int res;
lctx = (ssIOCtx *) ctx;
res = ((lctx->src->source) (lctx->src->context, buf, size));
if (res == 0) {
return EOF;
} else if (res < 0) {
return 0;
} else {
return res;
}
}
static int sourceGetchar (gdIOCtx * ctx)
{
int res;
unsigned char buf;
res = sourceGetbuf (ctx, &buf, 1);
if (res == 1) {
return buf;
} else {
return EOF;
}
}
static int sinkPutbuf (gdIOCtx * ctx, const void *buf, int size)
{
ssIOCtxPtr lctx;
int res;
lctx = (ssIOCtx *) ctx;
res = (lctx->snk->sink) (lctx->snk->context, buf, size);
if (res <= 0) {
return 0;
} else {
return res;
}
}
static void sinkPutchar (gdIOCtx * ctx, int a)
{
unsigned char b;
b = a;
sinkPutbuf (ctx, &b, 1);
}