summaryrefslogtreecommitdiffstats
path: root/pkg/utils
diff options
context:
space:
mode:
authorJesse Duffield <jessedduffield@gmail.com>2022-08-07 09:44:50 +1000
committerJesse Duffield <jessedduffield@gmail.com>2022-08-07 11:16:14 +1000
commit755ae0ef846d6a42678d0b8cb2c37108f79a0458 (patch)
tree8ef20b395f85fa174c122665ca46eb2d7d9b7ff4 /pkg/utils
parent7410acd1aaa97f678295a328264360802346b33a (diff)
add deadlock mutex package
write to deadlock stderr after closing gocui more deadlock checking
Diffstat (limited to 'pkg/utils')
-rw-r--r--pkg/utils/once_writer.go31
-rw-r--r--pkg/utils/once_writer_test.go19
2 files changed, 50 insertions, 0 deletions
diff --git a/pkg/utils/once_writer.go b/pkg/utils/once_writer.go
new file mode 100644
index 000000000..aecf20369
--- /dev/null
+++ b/pkg/utils/once_writer.go
@@ -0,0 +1,31 @@
+package utils
+
+import (
+ "io"
+ "sync"
+)
+
+// This wraps a writer and ensures that before we actually write anything we call a given function first
+
+type OnceWriter struct {
+ writer io.Writer
+ once sync.Once
+ f func()
+}
+
+var _ io.Writer = &OnceWriter{}
+
+func NewOnceWriter(writer io.Writer, f func()) *OnceWriter {
+ return &OnceWriter{
+ writer: writer,
+ f: f,
+ }
+}
+
+func (self *OnceWriter) Write(p []byte) (n int, err error) {
+ self.once.Do(func() {
+ self.f()
+ })
+
+ return self.writer.Write(p)
+}
diff --git a/pkg/utils/once_writer_test.go b/pkg/utils/once_writer_test.go
new file mode 100644
index 000000000..47f64bb61
--- /dev/null
+++ b/pkg/utils/once_writer_test.go
@@ -0,0 +1,19 @@
+package utils
+
+import (
+ "bytes"
+ "testing"
+)
+
+func TestOnceWriter(t *testing.T) {
+ innerWriter := bytes.NewBuffer(nil)
+ counter := 0
+ onceWriter := NewOnceWriter(innerWriter, func() {
+ counter += 1
+ })
+ _, _ = onceWriter.Write([]byte("hello"))
+ _, _ = onceWriter.Write([]byte("hello"))
+ if counter != 1 {
+ t.Errorf("expected counter to be 1, got %d", counter)
+ }
+}