Line data Source code
1 : // Copyright 2023 The LevelDB-Go and Pebble Authors. All rights reserved. Use 2 : // of this source code is governed by a BSD-style license that can be found in 3 : // the LICENSE file. 4 : 5 : package objstorageprovider 6 : 7 : import ( 8 : "bufio" 9 : 10 : "github.com/cockroachdb/pebble/objstorage" 11 : "github.com/cockroachdb/pebble/vfs" 12 : ) 13 : 14 : // NewFileWritable returns a Writable that uses a file as underlying storage. 15 1 : func NewFileWritable(file vfs.File) objstorage.Writable { 16 1 : return newFileBufferedWritable(file) 17 1 : } 18 : 19 : type fileBufferedWritable struct { 20 : file vfs.File 21 : bw *bufio.Writer 22 : } 23 : 24 : var _ objstorage.Writable = (*fileBufferedWritable)(nil) 25 : 26 1 : func newFileBufferedWritable(file vfs.File) *fileBufferedWritable { 27 1 : return &fileBufferedWritable{ 28 1 : file: file, 29 1 : bw: bufio.NewWriter(file), 30 1 : } 31 1 : } 32 : 33 : // Write is part of the objstorage.Writable interface. 34 1 : func (w *fileBufferedWritable) Write(p []byte) error { 35 1 : // Ignoring the length written since bufio.Writer.Write is guaranteed to 36 1 : // return an error if the length written is < len(p). 37 1 : _, err := w.bw.Write(p) 38 1 : return err 39 1 : } 40 : 41 : // Finish is part of the objstorage.Writable interface. 42 1 : func (w *fileBufferedWritable) Finish() error { 43 1 : err := w.bw.Flush() 44 1 : if err == nil { 45 1 : err = w.file.Sync() 46 1 : } 47 1 : err = firstError(err, w.file.Close()) 48 1 : w.bw = nil 49 1 : w.file = nil 50 1 : return err 51 : } 52 : 53 : // Abort is part of the objstorage.Writable interface. 54 0 : func (w *fileBufferedWritable) Abort() { 55 0 : _ = w.file.Close() 56 0 : w.bw = nil 57 0 : w.file = nil 58 0 : } 59 : 60 1 : func firstError(err0, err1 error) error { 61 1 : if err0 != nil { 62 0 : return err0 63 0 : } 64 1 : return err1 65 : }