xref: /plan9/sys/src/libString/s_read.c (revision 80ee5cbfe36716af62da8896207e9763b8e3d760)
1 #include <u.h>
2 #include <libc.h>
3 #include <bio.h>
4 #include "String.h"
5 
6 enum
7 {
8 	Minread=	256,
9 };
10 
11 /* Append up to 'len' input bytes to the string 'to'.
12  *
13  * Returns the number of characters read.
14  */
15 extern int
s_read(Biobuf * fp,String * to,int len)16 s_read(Biobuf *fp, String *to, int len)
17 {
18 	int rv;
19 	int n;
20 
21 	if(to->ref > 1)
22 		sysfatal("can't s_read a shared string");
23 	for(rv = 0; rv < len; rv += n){
24 		n = to->end - to->ptr;
25 		if(n < Minread){
26 			s_grow(to, Minread);
27 			n = to->end - to->ptr;
28 		}
29 		if(n > len - rv)
30 			n = len - rv;
31 		n = Bread(fp, to->ptr, n);
32 		if(n <= 0)
33 			break;
34 		to->ptr += n;
35 	}
36 	s_terminate(to);
37 	return rv;
38 }
39