|
| 1 | +module net |
| 2 | + |
| 3 | +const ( |
| 4 | + crlf = '\r\n' |
| 5 | + msg_peek = 0x02 |
| 6 | + max_read = 400 |
| 7 | +) |
| 8 | + |
| 9 | +// read_line is a *simple*, *non customizable*, blocking line reader. |
| 10 | +// It will *always* return a line, ending with CRLF, or just '', on EOF. |
| 11 | +// NB: if you want more control over the buffer, please use a buffered IO |
| 12 | +// reader instead: `io.new_buffered_reader({reader: io.make_reader(con)})` |
| 13 | +pub fn (con TcpConn) read_line() string { |
| 14 | + mut buf := [max_read]byte{} // where C.recv will store the network data |
| 15 | + mut res := '' // The final result, including the ending \n. |
| 16 | + for { |
| 17 | + mut line := '' // The current line. Can be a partial without \n in it. |
| 18 | + n := C.recv(con.sock.handle, buf, max_read - 1, msg_peek | msg_nosignal) |
| 19 | + if n == -1 { |
| 20 | + return res |
| 21 | + } |
| 22 | + if n == 0 { |
| 23 | + return res |
| 24 | + } |
| 25 | + buf[n] = `\0` |
| 26 | + mut eol_idx := -1 |
| 27 | + for i in 0 .. n { |
| 28 | + if int(buf[i]) == `\n` { |
| 29 | + eol_idx = i |
| 30 | + // Ensure that tos_clone(buf) later, |
| 31 | + // will return *only* the first line (including \n), |
| 32 | + // and ignore the rest |
| 33 | + buf[i + 1] = `\0` |
| 34 | + break |
| 35 | + } |
| 36 | + } |
| 37 | + bufbp := byteptr(buf) |
| 38 | + line = tos_clone(bufbp) |
| 39 | + if eol_idx > 0 { |
| 40 | + // At this point, we are sure that recv returned valid data, |
| 41 | + // that contains *at least* one line. |
| 42 | + // Ensure that the block till the first \n (including it) |
| 43 | + // is removed from the socket's receive queue, so that it does |
| 44 | + // not get read again. |
| 45 | + C.recv(con.sock.handle, buf, eol_idx + 1, msg_nosignal) |
| 46 | + res += line |
| 47 | + break |
| 48 | + } |
| 49 | + // recv returned a buffer without \n in it . |
| 50 | + C.recv(con.sock.handle, buf, n, msg_nosignal) |
| 51 | + res += line |
| 52 | + res += crlf |
| 53 | + break |
| 54 | + } |
| 55 | + return res |
| 56 | +} |
0 commit comments