github.com/iceber/iouring-go@v0.0.0-20230403020409-002cfd2e2a90/examples/cat/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/iceber/iouring-go"
     8  )
     9  
    10  const blockSize int64 = 32 * 1024
    11  
    12  var buffers [][]byte
    13  
    14  func getBuffers(size int64) [][]byte {
    15  	blocks := int(size / blockSize)
    16  	if size%blockSize != 0 {
    17  		blocks++
    18  	}
    19  
    20  	for i := 0; i < blocks-len(buffers); i++ {
    21  		buffers = append(buffers, make([]byte, blockSize))
    22  	}
    23  
    24  	bs := buffers[:blocks]
    25  	if size%blockSize != 0 {
    26  		bs[blocks-1] = bs[blocks-1][:size%blockSize]
    27  	}
    28  	return bs
    29  }
    30  
    31  func readAndPrint(iour *iouring.IOURing, file *os.File) error {
    32  	stat, err := file.Stat()
    33  	if err != nil {
    34  		return err
    35  	}
    36  	size := stat.Size()
    37  	buffers := getBuffers(size)
    38  
    39  	request, err := iour.SubmitRequest(iouring.Readv(int(file.Fd()), buffers), nil)
    40  	<-request.Done()
    41  	if err := request.Err(); err != nil {
    42  		return request.Err()
    43  	}
    44  
    45  	fmt.Println(file.Name(), ":")
    46  	for _, buffer := range request.GetRequestBuffers() {
    47  		fmt.Printf("%s", buffer)
    48  	}
    49  	fmt.Println()
    50  	return err
    51  }
    52  
    53  func main() {
    54  	if len(os.Args) <= 1 {
    55  		fmt.Printf("Usage: %s file1 file2 ...\n", os.Args[0])
    56  	}
    57  
    58  	iour, err := iouring.New(1)
    59  	if err != nil {
    60  		panic(err)
    61  	}
    62  	defer iour.Close()
    63  
    64  	for _, filename := range os.Args[1:] {
    65  		file, err := os.Open(filename)
    66  		if err != nil {
    67  			fmt.Printf("open file error: %v\n", err)
    68  			return
    69  		}
    70  		if err := readAndPrint(iour, file); err != nil {
    71  			fmt.Printf("cat %s error: %v\n", filename, err)
    72  			return
    73  		}
    74  	}
    75  }