github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/io/pipe.go (about) 1 // Copyright 2009 The Go Authors. 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 // Pipe adapter to connect code expecting an io.Reader 6 // with code expecting an io.Writer. 7 8 package io 9 10 import ( 11 "github.com/shogo82148/std/errors" 12 ) 13 14 // ErrClosedPipeは、クローズされたパイプに対する読み取りまたは書き込み操作で使用されるエラーです。 15 var ErrClosedPipe = errors.New("io: read/write on closed pipe") 16 17 // PipeReaderは、パイプの読み取り側です。 18 type PipeReader struct{ pipe } 19 20 // Readは、標準のReadインターフェースを実装します。 21 // パイプからデータを読み取り、ライターが到着するか、書き込み側が閉じられるまでブロックします。 22 // 書き込み側がエラーで閉じられた場合、そのエラーがerrとして返されます。 23 // それ以外の場合、errはEOFです。 24 func (r *PipeReader) Read(data []byte) (n int, err error) 25 26 // Closeは、リーダーを閉じます。パイプの書き込み半分への後続の書き込みは、 27 // エラー [ErrClosedPipe] を返します。 28 func (r *PipeReader) Close() error 29 30 // CloseWithErrorは、リーダーを閉じます。パイプの書き込み半分への後続の書き込みは、エラーerrを返します。 31 // 32 // CloseWithErrorは、以前にエラーが存在する場合、前のエラーを上書きせず、常にnilを返します。 33 func (r *PipeReader) CloseWithError(err error) error 34 35 // PipeWriterは、パイプの書き込み側です。 36 type PipeWriter struct{ r PipeReader } 37 38 // Writeは、標準のWriteインターフェースを実装します。 39 // データをパイプに書き込み、1つ以上のリーダーがすべてのデータを消費するか、 40 // 読み取り側が閉じられるまでブロックします。 41 // 読み取り側がエラーで閉じられた場合、そのエラーがerrとして返されます。 42 // それ以外の場合、errは [ErrClosedPipe] です。 43 func (w *PipeWriter) Write(data []byte) (n int, err error) 44 45 // Close closes the writer; subsequent reads from the 46 // read half of the pipe will return no bytes and EOF. 47 func (w *PipeWriter) Close() error 48 49 // CloseWithError closes the writer; subsequent reads from the 50 // read half of the pipe will return no bytes and the error err, 51 // or EOF if err is nil. 52 // 53 // CloseWithError never overwrites the previous error if it exists 54 // and always returns nil. 55 func (w *PipeWriter) CloseWithError(err error) error 56 57 // Pipe creates a synchronous in-memory pipe. 58 // It can be used to connect code expecting an [io.Reader] 59 // with code expecting an [io.Writer]. 60 // 61 // Reads and Writes on the pipe are matched one to one 62 // except when multiple Reads are needed to consume a single Write. 63 // That is, each Write to the [PipeWriter] blocks until it has satisfied 64 // one or more Reads from the [PipeReader] that fully consume 65 // the written data. 66 // The data is copied directly from the Write to the corresponding 67 // Read (or Reads); there is no internal buffering. 68 // 69 // It is safe to call Read and Write in parallel with each other or with Close. 70 // Parallel calls to Read and parallel calls to Write are also safe: 71 // the individual calls will be gated sequentially. 72 func Pipe() (*PipeReader, *PipeWriter)