writertoutils

package module
v1.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 28, 2024 License: MIT Imports: 2 Imported by: 4

README

WriterTo Utils

Go Reference codecov CI

Useful functions & types that extend the functionality of the io.WriterTo interface in Golang.

MultiWriterTo

A simple utility that concatenates multiple io.WriterTo objects, into a single writing stream.

func main() {
    r1 := strings.NewReader("hello, ")  // implements io.WriterTo
    r2 := strings.NewReader("world!") // implements io.WriterTo

    multiWriter := multiwriterto.MultiWriterTo(r1, r2)
    buffer := new(bytes.Buffer)

    // writes "hello, world!" to the buffer!
    n, err := multiWriter.WriteTo(buffer)
}

BinaryMarshalerAdapter

Convert any encoding.BinaryMarshaler interface to a io.WriterTo interface.

func main() {
    marshaler := MyMarshaler() // implements: MarshalBinary() (data []byte, err error)

    writerTo := multiwriterto.BinaryMarshalerAdapter(marshaler)
    buffer := new(bytes.Buffer)

    // calls MarshalBinary() and writes the binary data to the buffer!
    n, err := writerTo.WriteTo(buffer)
}

BufferWriterTo

The behavior of the standard bytes.Buffer writes the buffer content on a call to WriteTo only once, and then it empties (subsequent calls write 0 bytes).

Use BufferWriterTo in the case that you want any call to WriteTo to write the same buffer to the provided writer.

func main() {
    bufferWriterTo := multiwriterto.BufferWriterTo({}byte['h', 'i', '!', '\n'])

    // output 3 lines of 'hi!'
    for i := 0; i < 3; i++ {
    		bufferWriterTo.WriteTo(os.Stdout)
    }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BinaryMarshalerAdapter

func BinaryMarshalerAdapter(marshaler encoding.BinaryMarshaler) io.WriterTo

An adapter from the encoding.BinaryMarshaler interface to the io.WriterTo interface.

func BufferWriterTo added in v1.2.0

func BufferWriterTo(buffer []byte) io.WriterTo

BufferWriterTo writes the same buffer each time the WriteTo metho is called.

func MultiWriterTo

func MultiWriterTo(writerTos ...io.WriterTo) io.WriterTo

Implements the io.WriterTo interface.

WriteTo writes data from all of the provided writers to w, one after another until all data has been written or an error has occurred. The return value n is the number of total bytes written. If an error has been encountered during the write, it is also returned.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL