From 00261afbc1c06e2fd8562f832ee734f93338098b Mon Sep 17 00:00:00 2001 From: Louis Schmieder Date: Sun, 25 Apr 2021 20:22:33 +0200 Subject: [PATCH] io: add a `cp` function (#9875) --- vlib/io/io.v | 17 +++++++++++++++++ vlib/io/io_test.v | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 vlib/io/io.v create mode 100644 vlib/io/io_test.v diff --git a/vlib/io/io.v b/vlib/io/io.v new file mode 100644 index 0000000000..45cf7938a4 --- /dev/null +++ b/vlib/io/io.v @@ -0,0 +1,17 @@ +module io + +const ( + buf_max_len = 5 * 1024 +) + +pub fn cp(dst Writer, src Reader) ? { + mut buf := read_all(reader: src) or { + return err + } + dst.write(buf) or { + return + } + unsafe { + buf.free() + } +} diff --git a/vlib/io/io_test.v b/vlib/io/io_test.v new file mode 100644 index 0000000000..2902775b3e --- /dev/null +++ b/vlib/io/io_test.v @@ -0,0 +1,43 @@ +import io + +struct Buf { +pub: + bytes []byte +mut: + i int +} + +struct Writ { +pub mut: + bytes []byte +} + +fn (mut b Buf) read(mut buf []byte) ?int { + if !(b.i < b.bytes.len) { + return none + } + n := copy(buf, b.bytes[b.i..]) + b.i += n + return n +} + +fn (mut w Writ) write(buf []byte) ?int { + if buf.len <= 0 { + return none + } + w.bytes << buf + return buf.len +} + +fn test_copy() { + src := Buf{ + bytes: 'abcdefghij'.repeat(10).bytes() + } + dst := Writ{ + bytes: []byte{} + } + io.cp(dst, src) or { + assert false + } + assert dst.bytes == src.bytes +}