nightmaremail

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

substdo.c (2020B)


      1 #include "substdio.h"
      2 #include "str.h"
      3 #include "byte.h"
      4 #include "error.h"
      5 
      6 static int allwrite(ssize_t (*op)(), int fd, char *buf, size_t len)
      7 {
      8   ssize_t w;
      9 
     10   while (len) {
     11     w = op(fd,buf,len);
     12     if (w == -1) {
     13       if (errno == error_intr) continue;
     14       return -1; /* note that some data may have been written */
     15     }
     16     /* if (w == 0), luser's fault */
     17     buf += w;
     18     len -= w;
     19   }
     20   return 0;
     21 }
     22 
     23 int substdio_flush(substdio *s)
     24 {
     25   int p;
     26  
     27   p = s->p;
     28   if (!p) return 0;
     29   s->p = 0;
     30   return allwrite(s->op,s->fd,s->x,p);
     31 }
     32 
     33 int substdio_bput(substdio *s, char *buf, size_t len)
     34 {
     35   unsigned int n;
     36  
     37   while (len > (n = s->n - s->p)) {
     38     byte_copy(s->x + s->p,n,buf);
     39     s->p += n;
     40     buf += n;
     41     len -= n;
     42     if (substdio_flush(s) == -1) return -1;
     43   }
     44   /* now len <= s->n - s->p */
     45   byte_copy(s->x + s->p,len,buf);
     46   s->p += len;
     47   return 0;
     48 }
     49 
     50 int substdio_put(substdio *s, char *buf, size_t len)
     51 {
     52   unsigned int n = s->n; /* how many bytes to write in next chunk */
     53  
     54   /* check if the input would fit in the buffer without flushing */
     55   if (len > n - (unsigned int)s->p) {
     56     if (substdio_flush(s) == -1) return -1;
     57     /* now s->p == 0 */
     58     if (n < SUBSTDIO_OUTSIZE) n = SUBSTDIO_OUTSIZE;
     59     /* as long as the remainder would not fit into s->x write it directly
     60      * from buf to s->fd. */
     61     while (len > (unsigned int)s->n) {
     62       if (n > len) n = len;
     63       if (allwrite(s->op,s->fd,buf,n) == -1) return -1;
     64       buf += n;
     65       len -= n;
     66     }
     67   }
     68   /* now len <= s->n - s->p */
     69   byte_copy(s->x + s->p,len,buf);
     70   s->p += len;
     71   return 0;
     72 }
     73 
     74 int substdio_putflush(substdio *s, char *buf, size_t len)
     75 {
     76   if (substdio_flush(s) == -1) return -1;
     77   return allwrite(s->op,s->fd,buf,len);
     78 }
     79 
     80 int substdio_bputs(substdio *s, char *buf)
     81 {
     82   return substdio_bput(s,buf,str_len(buf));
     83 }
     84 
     85 int substdio_puts(substdio *s, char *buf)
     86 {
     87   return substdio_put(s,buf,str_len(buf));
     88 }
     89 
     90 int substdio_putsflush(substdio *s, char *buf)
     91 {
     92   return substdio_putflush(s,buf,str_len(buf));
     93 }