|
| 1 | +// Copyright 2014-2025 Ulrich Kunitz. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +// Package xio provides tools to handle I/O operations. It contains the |
| 6 | +// [WriteCloserStack] type supporting combining multiple WriterClosers as single |
| 7 | +// [io.WriteCloser]. |
| 8 | +package xio |
| 9 | + |
| 10 | +import ( |
| 11 | + "errors" |
| 12 | + "io" |
| 13 | +) |
| 14 | + |
| 15 | +// WriteCloserStack allows to support multiple WriteClosers to be handled as |
| 16 | +// single WriteCloser. |
| 17 | +type WriteCloserStack struct { |
| 18 | + Stack []io.WriteCloser |
| 19 | +} |
| 20 | + |
| 21 | +// NewWriteCloserStack creates a new WriteCloserStack. It will have an an empty |
| 22 | +// stack. |
| 23 | +func NewWriteCloserStack() *WriteCloserStack { |
| 24 | + return &WriteCloserStack{} |
| 25 | +} |
| 26 | + |
| 27 | +// Write writes data to the top WriteCloser in the stack. If the stack is empty |
| 28 | +// Write will always succeed. |
| 29 | +func (w *WriteCloserStack) Write(p []byte) (n int, err error) { |
| 30 | + k := len(w.Stack) |
| 31 | + if k == 0 { |
| 32 | + return len(p), nil |
| 33 | + } |
| 34 | + return w.Stack[k-1].Write(p) |
| 35 | +} |
| 36 | + |
| 37 | +// Close closes all writers on the stack and combines the errors. It will clear |
| 38 | +// the stack. |
| 39 | +func (w *WriteCloserStack) Close() error { |
| 40 | + var errs []error |
| 41 | + for k := len(w.Stack) - 1; k >= 0; k-- { |
| 42 | + err := w.Stack[k].Close() |
| 43 | + errs = append(errs, err) |
| 44 | + } |
| 45 | + w.Stack = nil |
| 46 | + return errors.Join(errs...) |
| 47 | +} |
| 48 | + |
| 49 | +// Push adds a new WriteCloser to the top of the stack. It panics if the |
| 50 | +// WriteCloser is nil. |
| 51 | +func (w *WriteCloserStack) Push(wc io.WriteCloser) { |
| 52 | + if wc == nil { |
| 53 | + panic("cannot push nil WriteCloser onto stack") |
| 54 | + } |
| 55 | + w.Stack = append(w.Stack, wc) |
| 56 | +} |
0 commit comments