github.com/flower-corp/rosedb@v1.1.2-0.20230117132829-21dc4f7b319a/ioselector/io_selector.go (about)

     1  package ioselector
     2  
     3  import (
     4  	"errors"
     5  	"os"
     6  )
     7  
     8  // ErrInvalidFsize invalid file size.
     9  var ErrInvalidFsize = errors.New("fsize can`t be zero or negative")
    10  
    11  // FilePerm default permission of the newly created log file.
    12  const FilePerm = 0644
    13  
    14  // IOSelector io selector for fileio and mmap, used by wal and value log right now.
    15  type IOSelector interface {
    16  	// Write a slice to log file at offset.
    17  	// It returns the number of bytes written and an error, if any.
    18  	Write(b []byte, offset int64) (int, error)
    19  
    20  	// Read a slice from offset.
    21  	// It returns the number of bytes read and any error encountered.
    22  	Read(b []byte, offset int64) (int, error)
    23  
    24  	// Sync commits the current contents of the file to stable storage.
    25  	// Typically, this means flushing the file system's in-memory copy
    26  	// of recently written data to disk.
    27  	Sync() error
    28  
    29  	// Close closes the File, rendering it unusable for I/O.
    30  	// It will return an error if it has already been closed.
    31  	Close() error
    32  
    33  	// Delete delete the file.
    34  	// Must close it before delete, and will unmap if in MMapSelector.
    35  	Delete() error
    36  }
    37  
    38  // open file and truncate it if necessary.
    39  func openFile(fName string, fsize int64) (*os.File, error) {
    40  	fd, err := os.OpenFile(fName, os.O_CREATE|os.O_RDWR, FilePerm)
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  
    45  	stat, err := fd.Stat()
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  
    50  	if stat.Size() < fsize {
    51  		if err := fd.Truncate(fsize); err != nil {
    52  			return nil, err
    53  		}
    54  	}
    55  	return fd, nil
    56  }