| 1 |
// SPDX-License-Identifier: MPL-2.0 |
| 2 |
|
| 3 |
// Copyright (C) 2025 Aleksa Sarai <[email protected]> |
| 4 |
// Copyright (C) 2025 SUSE LLC |
| 5 |
// |
| 6 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 7 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 8 |
// file, You can obtain one at https://mozilla.org/MPL/2.0/. |
| 9 |
|
| 10 |
// Package fd provides a drop-in interface-based replacement of [*os.File] that |
| 11 |
// allows for things like noop-Close wrappers to be used. |
| 12 |
// |
| 13 |
// [*os.File]: https://pkg.go.dev/os#File |
| 14 |
package fd |
| 15 |
|
| 16 |
import ( |
| 17 |
"io" |
| 18 |
"os" |
| 19 |
) |
| 20 |
|
| 21 |
// Fd is an interface that mirrors most of the API of [*os.File], allowing you |
| 22 |
// to create wrappers that can be used in place of [*os.File]. |
| 23 |
// |
| 24 |
// [*os.File]: https://pkg.go.dev/os#File |
| 25 |
type Fd interface { |
| 26 |
io.Closer |
| 27 |
Name() string |
| 28 |
Fd() uintptr |
| 29 |
} |
| 30 |
|
| 31 |
// Compile-time interface checks. |
| 32 |
var ( |
| 33 |
_ Fd = (*os.File)(nil) |
| 34 |
_ Fd = noClose{} |
| 35 |
) |
| 36 |
|
| 37 |
type noClose struct{ inner Fd } |
| 38 |
|
| 39 |
func (f noClose) Name() string { return f.inner.Name() } |
| 40 |
func (f noClose) Fd() uintptr { return f.inner.Fd() } |
| 41 |
|
| 42 |
func (f noClose) Close() error { return nil } |
| 43 |
|
| 44 |
// NopCloser returns an [*os.File]-like object where the [Close] method is now |
| 45 |
// a no-op. |
| 46 |
// |
| 47 |
// Note that for [*os.File] and similar objects, the Go garbage collector will |
| 48 |
// still call [Close] on the underlying file unless you use |
| 49 |
// [runtime.SetFinalizer] to disable this behaviour. This is up to the caller |
| 50 |
// to do (if necessary). |
| 51 |
// |
| 52 |
// [*os.File]: https://pkg.go.dev/os#File |
| 53 |
// [Close]: https://pkg.go.dev/io#Closer |
| 54 |
// [runtime.SetFinalizer]: https://pkg.go.dev/runtime#SetFinalizer |
| 55 |
func NopCloser(f Fd) Fd { return noClose{inner: f} } |