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

     1  package ioselector
     2  
     3  import "os"
     4  
     5  // FileIOSelector represents using standard file I/O.
     6  type FileIOSelector struct {
     7  	fd *os.File // system file descriptor.
     8  }
     9  
    10  // NewFileIOSelector create a new file io selector.
    11  func NewFileIOSelector(fName string, fsize int64) (IOSelector, error) {
    12  	if fsize <= 0 {
    13  		return nil, ErrInvalidFsize
    14  	}
    15  	file, err := openFile(fName, fsize)
    16  	if err != nil {
    17  		return nil, err
    18  	}
    19  	return &FileIOSelector{fd: file}, nil
    20  }
    21  
    22  // Write is a wrapper of os.File WriteAt.
    23  func (fio *FileIOSelector) Write(b []byte, offset int64) (int, error) {
    24  	return fio.fd.WriteAt(b, offset)
    25  }
    26  
    27  // Read is a wrapper of os.File ReadAt.
    28  func (fio *FileIOSelector) Read(b []byte, offset int64) (int, error) {
    29  	return fio.fd.ReadAt(b, offset)
    30  }
    31  
    32  // Sync is a wrapper of os.File Sync.
    33  func (fio *FileIOSelector) Sync() error {
    34  	return fio.fd.Sync()
    35  }
    36  
    37  // Close is a wrapper of os.File Close.
    38  func (fio *FileIOSelector) Close() error {
    39  	return fio.fd.Close()
    40  }
    41  
    42  // Delete file descriptor if we don`t use it anymore.
    43  func (fio *FileIOSelector) Delete() error {
    44  	if err := fio.fd.Close(); err != nil {
    45  		return err
    46  	}
    47  	return os.Remove(fio.fd.Name())
    48  }