Source file src/net/sendfile.go

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build linux || (darwin && !ios) || dragonfly || freebsd || solaris || windows
     6  
     7  package net
     8  
     9  import (
    10  	"internal/poll"
    11  	"io"
    12  	"syscall"
    13  )
    14  
    15  var testHookSupportsSendfile func() bool
    16  
    17  // sendFile copies the contents of r to c using the sendfile
    18  // system call to minimize copies.
    19  //
    20  // if handled == true, sendFile returns the number (potentially zero) of bytes
    21  // copied and any non-EOF error.
    22  //
    23  // if handled == false, sendFile performed no work.
    24  func sendFile(c *netFD, r io.Reader) (written int64, err error, handled bool) {
    25  	if !supportsSendfile() {
    26  		return 0, nil, false
    27  	}
    28  	var remain int64 = 0 // 0 writes the entire file
    29  	lr, ok := r.(*io.LimitedReader)
    30  	if ok {
    31  		remain, r = lr.N, lr.R
    32  		if remain <= 0 {
    33  			return 0, nil, true
    34  		}
    35  	}
    36  	// r might be an *os.File or an os.fileWithoutWriteTo.
    37  	// Type assert to an interface rather than *os.File directly to handle the latter case.
    38  	f, ok := r.(syscall.Conn)
    39  	if !ok {
    40  		return 0, nil, false
    41  	}
    42  
    43  	sc, err := f.SyscallConn()
    44  	if err != nil {
    45  		return 0, nil, false
    46  	}
    47  
    48  	var werr error
    49  	err = sc.Read(func(fd uintptr) bool {
    50  		written, werr, handled = poll.SendFile(&c.pfd, fd, remain)
    51  		return true
    52  	})
    53  	if err == nil {
    54  		err = werr
    55  	}
    56  
    57  	if lr != nil {
    58  		lr.N = remain - written
    59  	}
    60  
    61  	return written, wrapSyscallError("sendfile", err), handled
    62  }
    63  

View as plain text