Source file src/net/sendfile_unix_alt.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 (darwin && !ios) || dragonfly || freebsd || solaris
     6  
     7  package net
     8  
     9  import (
    10  	"internal/poll"
    11  	"io"
    12  	"syscall"
    13  )
    14  
    15  const supportsSendfile = true
    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  	var remain int64 = 0 // 0 writes the entire file
    26  	lr, ok := r.(*io.LimitedReader)
    27  	if ok {
    28  		remain, r = lr.N, lr.R
    29  		if remain <= 0 {
    30  			return 0, nil, true
    31  		}
    32  	}
    33  	// r might be an *os.File or an os.fileWithoutWriteTo.
    34  	// Type assert to an interface rather than *os.File directly to handle the latter case.
    35  	f, ok := r.(syscall.Conn)
    36  	if !ok {
    37  		return 0, nil, false
    38  	}
    39  
    40  	sc, err := f.SyscallConn()
    41  	if err != nil {
    42  		return 0, nil, false
    43  	}
    44  
    45  	var werr error
    46  	err = sc.Read(func(fd uintptr) bool {
    47  		written, werr, handled = poll.SendFile(&c.pfd, int(fd), remain)
    48  		return true
    49  	})
    50  	if err == nil {
    51  		err = werr
    52  	}
    53  
    54  	if lr != nil {
    55  		lr.N = remain - written
    56  	}
    57  
    58  	return written, wrapSyscallError("sendfile", err), handled
    59  }
    60  

View as plain text