File: sync_writer.go

package info (click to toggle)
git-lfs 3.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,808 kB
  • sloc: sh: 21,256; makefile: 507; ruby: 417
file content (55 lines) | stat: -rw-r--r-- 1,209 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package tools

import "io"

// closeFn is the type of func Close() in the io.Closer interface.
type closeFn func() error

// syncFn is the type of func Sync() in the *os.File implementation.
type syncFn func() error

// SyncWriter provides a wrapper around an io.Writer that synchronizes all
// write after they occur, if the underlying writer supports synchronization.
type SyncWriter struct {
	w io.Writer

	closeFn closeFn
	syncFn  syncFn
}

// NewSyncWriter returns a new instance of the *SyncWriter that sends all writes
// to the given io.Writer.
func NewSyncWriter(w io.Writer) *SyncWriter {
	sw := &SyncWriter{
		w: w,
	}

	if sync, ok := w.(interface {
		Sync() error
	}); ok {
		sw.syncFn = sync.Sync
	} else {
		sw.syncFn = func() error { return nil }
	}

	if close, ok := w.(io.Closer); ok {
		sw.closeFn = close.Close
	} else {
		sw.closeFn = func() error { return nil }
	}

	return sw
}

// Write will write to the file and perform a Sync() if writing succeeds.
func (w *SyncWriter) Write(b []byte) error {
	if _, err := w.w.Write(b); err != nil {
		return err
	}
	return w.syncFn()
}

// Close will call Close() on the underlying file
func (w *SyncWriter) Close() error {
	return w.closeFn()
}