go.mway.dev/x@v0.0.0-20240520034138-950aede9a3fb/io/nop.go (about)

     1  // Copyright (c) 2024 Matt Way
     2  //
     3  // Permission is hereby granted, free of charge, to any person obtaining a copy
     4  // of this software and associated documentation files (the "Software"), to
     5  // deal in the Software without restriction, including without limitation the
     6  // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
     7  // sell copies of the Software, and to permit persons to whom the Software is
     8  // furnished to do so, subject to the following conditions:
     9  //
    10  // The above copyright notice and this permission notice shall be included in
    11  // all copies or substantial portions of the Software.
    12  //
    13  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    14  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    15  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    16  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    17  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    18  // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
    19  // IN THE THE SOFTWARE.
    20  
    21  // Package io provides I/O-related helpers and utilities.
    22  package io
    23  
    24  import (
    25  	"io"
    26  )
    27  
    28  var (
    29  	// Nop is an [io.ReadWriteCloser] that does nothing.
    30  	Nop io.ReadWriteCloser = nop{}
    31  	// NopReader is an [io.Reader] that reads no data and always returns EOF.
    32  	NopReader io.Reader = Nop
    33  	// NopReadCloser is an [io.ReadCloser] that reads no data, always returns
    34  	// EOF, and does not error on close.
    35  	NopReadCloser io.ReadCloser = Nop
    36  	// NopWriter is an [io.Writer] that writes no data and always returns nil.
    37  	NopWriter io.Writer = Nop
    38  	// NopWriteCloser is an [io.WriteCloser] that writes no data, always
    39  	// returns nil, and does not error on close.
    40  	NopWriteCloser io.WriteCloser = Nop
    41  
    42  	_ io.StringWriter = nop{}
    43  )
    44  
    45  type nop struct{}
    46  
    47  func (nop) Read([]byte) (int, error) {
    48  	return 0, io.EOF
    49  }
    50  
    51  func (nop) Write(p []byte) (int, error) {
    52  	return io.Discard.Write(p)
    53  }
    54  
    55  func (nop) WriteString(s string) (int, error) {
    56  	return io.Discard.(io.StringWriter).WriteString(s)
    57  }
    58  
    59  func (nop) Close() error {
    60  	return nil
    61  }