buffer_put.c (1848B)
1 /* Public domain. */ 2 3 #include "buffer.h" 4 #include "str.h" 5 #include "byte.h" 6 #include "error.h" 7 8 static int allwrite(int (*op)( int fd, const char* buf, unsigned int len ),int fd,const char *buf,unsigned int len) 9 { 10 int w; 11 12 while (len) { 13 w = op(fd,buf,len); 14 if (w == -1) { 15 if (errno == error_intr) continue; 16 return -1; /* note that some data may have been written */ 17 } 18 if (w == 0) ; /* luser's fault */ 19 buf += w; 20 len -= w; 21 } 22 return 0; 23 } 24 25 int buffer_flush(buffer *s) 26 { 27 int p; 28 29 p = s->p; 30 if (!p) return 0; 31 s->p = 0; 32 return allwrite(s->op,s->fd,s->x,p); 33 } 34 35 int buffer_putalign(buffer *s,const char *buf,unsigned int len) 36 { 37 unsigned int n; 38 39 while (len > (n = s->n - s->p)) { 40 byte_copy(s->x + s->p,n,buf); s->p += n; buf += n; len -= n; 41 if (buffer_flush(s) == -1) return -1; 42 } 43 /* now len <= s->n - s->p */ 44 byte_copy(s->x + s->p,len,buf); 45 s->p += len; 46 return 0; 47 } 48 49 int buffer_put(buffer *s,const char *buf,unsigned int len) 50 { 51 unsigned int n; 52 53 n = s->n; 54 if (len > n - s->p) { 55 if (buffer_flush(s) == -1) return -1; 56 /* now s->p == 0 */ 57 if (n < BUFFER_OUTSIZE) n = BUFFER_OUTSIZE; 58 while (len > s->n) { 59 if (n > len) n = len; 60 if (allwrite(s->op,s->fd,buf,n) == -1) return -1; 61 buf += n; 62 len -= n; 63 } 64 } 65 /* now len <= s->n - s->p */ 66 byte_copy(s->x + s->p,len,buf); 67 s->p += len; 68 return 0; 69 } 70 71 int buffer_putflush(buffer *s,const char *buf,unsigned int len) 72 { 73 if (buffer_flush(s) == -1) return -1; 74 return allwrite(s->op,s->fd,buf,len); 75 } 76 77 int buffer_putsalign(buffer *s,const char *buf) 78 { 79 return buffer_putalign(s,buf,str_len(buf)); 80 } 81 82 int buffer_puts(buffer *s,const char *buf) 83 { 84 return buffer_put(s,buf,str_len(buf)); 85 } 86 87 int buffer_putsflush(buffer *s,const char *buf) 88 { 89 return buffer_putflush(s,buf,str_len(buf)); 90 }