Read directly when the buffer is empty and the requested number of
bytes is greater than the buffer length
let { wrap, flat_map, default_buf_len } = import! std.io.prim
let { Option, Bool } = import! std.types
let { Disposable, dispose, is_disposed } = import! std.disposable
-let { (>), (<=) } = import! std.cmp
+let { (>), (<=), (>=), min } = import! std.cmp
+let { not } = import! std.bool
let { ? } = import! std.int
let { Result } = import! std.result
let { ref, load, (<-) } = import! std.reference
@@ -49,26 +50,33 @@ let buffered reader : [Read a] -> a -> Buffered a =
}
let read_buffered : [Read r] -> Read (Buffered r) =
+ let read_from_buf buf_reader num_bytes =
+ let buf = load buf_reader.buf
+ let num_bytes = min (array.len buf) num_bytes
+
+ let read_buf = array.slice buf 0 num_bytes
+ let rest_buf = array.slice buf num_bytes (array.len buf)
+
+ let _ = buf_reader.buf <- rest_buf
+ Some read_buf
+
let buffered_read buf_reader num_bytes =
let buf = load buf_reader.buf
if num_bytes <= 0 then
wrap (Some [])
- else if array.is_empty buf then
+ else if not (array.is_empty buf) then
+ wrap (read_from_buf buf_reader num_bytes)
+ else if num_bytes >= default_buf_len then
+ read buf_reader.reader num_bytes
+ else
do new_buf = read buf_reader.reader default_buf_len
match new_buf with
| Some new_buf ->
let _ = buf_reader.buf <- new_buf
- buffered_read buf_reader num_bytes
+ wrap (read_from_buf buf_reader num_bytes)
| None -> wrap None
- else
- let num_bytes = if num_bytes > array.len buf then array.len buf else num_bytes
- let read_buf = array.slice buf 0 num_bytes
- let rest_buf = array.slice buf num_bytes (array.len buf)
-
- let _ = buf_reader.buf <- rest_buf
- wrap (Some read_buf)
let buffered_read_to_end buf_reader =
do rest = read_to_end buf_reader.reader
