/* This file is in the public domain. */ #include #include #include #include #include #include "util.h" typedef struct wrap_w_priv WRAP_W_PRIV; typedef struct accum_priv ACCUM_PRIV; struct wrap_w_priv { FILE *wrapped; void *cookie; void (*proc)(FILE *, void *, const char *, int); unsigned int flags; } ; struct accum_priv { char *s; int l; char **sp; int *lp; } ; static int wrap_w_w(void *pv, const char *buf, int len) { WRAP_W_PRIV *p; p = pv; (*p->proc)(p->wrapped,p->cookie,buf,len); return(len); } static int wrap_w_c(void *pv) { WRAP_W_PRIV *p; p = pv; if (p->flags & SWW_CLOSE_WRAPPED) fclose(p->wrapped); free(pv); return(0); } FILE *stdio_wrap_w(FILE *wrapped, void *cookie, void (*proc)(FILE *, void *, const char *, int), unsigned int flags) { WRAP_W_PRIV *p; FILE *f; int e; p = malloc(sizeof(WRAP_W_PRIV)); if (! p) return(0); p->wrapped = wrapped; p->cookie = cookie; p->proc = proc; p->flags = flags; f = funopen(p,0,&wrap_w_w,0,&wrap_w_c); if (! f) { e = errno; free(p); errno = e; } return(f); } static int accum_w(void *pv, const char *buf, int len) { ACCUM_PRIV *p; p = pv; if (p->sp) { p->s = realloc(p->s,p->l+len); bcopy(buf,p->s+p->l,len); } p->l += len; return(len); } static int accum_c(void *pv) { ACCUM_PRIV *p; p = pv; if (p->sp) { accum_w(pv,"",1); *p->sp = p->s; p->l --; } if (p->lp) *p->lp = p->l; free(pv); return(0); } FILE *open_accum(char **sp, int *lp) { ACCUM_PRIV *p; FILE *f; int e; p = malloc(sizeof(ACCUM_PRIV)); if (! p) return(0); p->s = 0; p->l = 0; p->sp = sp; p->lp = lp; f = funopen(p,0,&accum_w,0,&accum_c); if (! f) { e = errno; free(p); errno = e; } return(f); } char *blk_to_nulterm(const void *buf, int len) { char *s; s = malloc(len+1); if (s) { if (len > 0) bcopy(buf,s,len); s[len] = '\0'; } return(s); } void set_nonblock(int fd) { fcntl(fd,F_SETFL,fcntl(fd,F_GETFL,0)|O_NONBLOCK); }