Answer of exercise 4

The idea is to copy the string to output into the buffer. We need to take into account the case where there is not enough space in the buffer (in that case the buffer needs to emptied), and also the case where the string is longer than the buffer (in that case it can be written directly). Here is a possible solution.

let output_string chan s = let avail = String.length chan.out_buffer - chan.out_pos in if String.length s <= avail then begin String.blit s 0 chan.out_buffer chan.out_pos (String.length s); chan.out_pos <- chan.out_pos + String.length s end else if chan.out_pos = 0 then begin ignore (write chan.out_fd s 0 (String.length s)) end else begin String.blit s 0 chan.out_buffer chan.out_pos avail; let out_buffer_size = String.length chan.out_buffer in ignore (write chan.out_fd chan.out_buffer 0 out_buffer_size); let remaining = String.length s - avail in if remaining < out_buffer_size then begin String.blit s avail chan.out_buffer 0 remaining; chan.out_pos <- remaining end else begin ignore (write chan.out_fd s avail remaining); chan.out_pos <- 0 end end;;
* * *