github.com/leonlxy/hyperledger@v1.0.0-alpha.0.20170427033203-34922035d248/common/ledger/blkstorage/fsblkstorage/blockfile_rw.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  		 http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package fsblkstorage
    18  
    19  import (
    20  	"os"
    21  )
    22  
    23  ////  WRITER ////
    24  type blockfileWriter struct {
    25  	filePath string
    26  	file     *os.File
    27  }
    28  
    29  func newBlockfileWriter(filePath string) (*blockfileWriter, error) {
    30  	writer := &blockfileWriter{filePath: filePath}
    31  	return writer, writer.open()
    32  }
    33  
    34  func (w *blockfileWriter) truncateFile(targetSize int) error {
    35  	fileStat, err := w.file.Stat()
    36  	if err != nil {
    37  		return err
    38  	}
    39  	if fileStat.Size() > int64(targetSize) {
    40  		w.file.Truncate(int64(targetSize))
    41  	}
    42  	return nil
    43  }
    44  
    45  func (w *blockfileWriter) append(b []byte, sync bool) error {
    46  	_, err := w.file.Write(b)
    47  	if err != nil {
    48  		return err
    49  	}
    50  	if sync {
    51  		return w.file.Sync()
    52  	}
    53  	return nil
    54  }
    55  
    56  func (w *blockfileWriter) open() error {
    57  	file, err := os.OpenFile(w.filePath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0660)
    58  	if err != nil {
    59  		return err
    60  	}
    61  	w.file = file
    62  	return nil
    63  }
    64  
    65  func (w *blockfileWriter) close() error {
    66  	return w.file.Close()
    67  }
    68  
    69  ////  READER ////
    70  type blockfileReader struct {
    71  	file *os.File
    72  }
    73  
    74  func newBlockfileReader(filePath string) (*blockfileReader, error) {
    75  	file, err := os.OpenFile(filePath, os.O_RDONLY, 0600)
    76  	if err != nil {
    77  		return nil, err
    78  	}
    79  	reader := &blockfileReader{file}
    80  	return reader, nil
    81  }
    82  
    83  func (r *blockfileReader) read(offset int, length int) ([]byte, error) {
    84  	b := make([]byte, length)
    85  	_, err := r.file.ReadAt(b, int64(offset))
    86  	if err != nil {
    87  		return nil, err
    88  	}
    89  	return b, nil
    90  }
    91  
    92  func (r *blockfileReader) close() error {
    93  	return r.file.Close()
    94  }