forked from lesismal/nbio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sendfile_std.go
63 lines (56 loc) · 1001 Bytes
/
sendfile_std.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright 2020 lesismal. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
//go:build windows
// +build windows
package nbio
import (
"io"
"os"
"github.com/lesismal/nbio/mempool"
)
// Sendfile .
func (c *Conn) Sendfile(f *os.File, remain int64) (written int64, err error) {
if f == nil {
return 0, nil
}
if remain <= 0 {
stat, e := f.Stat()
if err != nil {
return 0, e
}
remain = stat.Size()
}
for remain > 0 {
bufLen := 1024 * 32
if bufLen > int(remain) {
bufLen = int(remain)
}
buf := mempool.Malloc(bufLen)
nr, er := f.Read(buf)
if nr > 0 {
nw, ew := c.Write(buf[0:nr])
mempool.Free(buf)
if nw < 0 {
nw = 0
}
remain -= int64(nw)
written += int64(nw)
if ew != nil {
err = ew
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
}
if er != nil {
if er != io.EOF {
err = er
}
break
}
}
return written, err
}