Skip to content

Commit 00261af

Browse files
io: add a cp function (#9875)
1 parent 7184629 commit 00261af

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

vlib/io/io.v

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
module io
2+
3+
const (
4+
buf_max_len = 5 * 1024
5+
)
6+
7+
pub fn cp(dst Writer, src Reader) ? {
8+
mut buf := read_all(reader: src) or {
9+
return err
10+
}
11+
dst.write(buf) or {
12+
return
13+
}
14+
unsafe {
15+
buf.free()
16+
}
17+
}

vlib/io/io_test.v

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import io
2+
3+
struct Buf {
4+
pub:
5+
bytes []byte
6+
mut:
7+
i int
8+
}
9+
10+
struct Writ {
11+
pub mut:
12+
bytes []byte
13+
}
14+
15+
fn (mut b Buf) read(mut buf []byte) ?int {
16+
if !(b.i < b.bytes.len) {
17+
return none
18+
}
19+
n := copy(buf, b.bytes[b.i..])
20+
b.i += n
21+
return n
22+
}
23+
24+
fn (mut w Writ) write(buf []byte) ?int {
25+
if buf.len <= 0 {
26+
return none
27+
}
28+
w.bytes << buf
29+
return buf.len
30+
}
31+
32+
fn test_copy() {
33+
src := Buf{
34+
bytes: 'abcdefghij'.repeat(10).bytes()
35+
}
36+
dst := Writ{
37+
bytes: []byte{}
38+
}
39+
io.cp(dst, src) or {
40+
assert false
41+
}
42+
assert dst.bytes == src.bytes
43+
}

0 commit comments

Comments
 (0)