Skip to content

No NewReader()/NewWriter() stream wrapper classes #57

Description

@sumanjeet0012

Go provides NewReader(r io.Reader) Reader and NewWriter(w io.Writer) Writer wrapper classes with ReadMultihash() and WriteMultihash() methods. Python has Multihash.read()/write() static/instance methods but no dedicated wrapper classes.

Problem

Go's io.go:

type Reader interface {
    io.Reader
    ReadMultihash() (Multihash, error)
}

type Writer interface {
    io.Writer
    WriteMultihash(Multihash) error
}

func NewReader(r io.Reader) Reader { return &mhReader{r} }
func NewWriter(w io.Writer) Writer { return &mhWriter{w} }

The mhReader.ReadMultihash() method reads varints directly from the stream (not buffering the entire input), handles io.ByteReader for efficiency, and validates the result with Cast().

Python's Multihash.read() is a classmethod that works similarly but there's no MultihashReader class that wraps a stream and provides a clean interface for reading multiple multihashes.

Proposed Solution

Add wrapper classes:

class MultihashReader:
    """Wraps a binary stream with ReadMultihash() capability."""

    def __init__(self, stream: BinaryIO):
        self._stream = stream

    def read(self, buf: bytearray) -> int:
        """Standard read interface."""
        return self._stream.readinto(buf)

    def read_multihash(self) -> Multihash:
        """Read one multihash from the stream."""
        return Multihash.read(self._stream)


class MultihashWriter:
    """Wraps a binary stream with WriteMultihash() capability."""

    def __init__(self, stream: BinaryIO):
        self._stream = stream

    def write(self, buf: bytes) -> int:
        """Standard write interface."""
        return self._stream.write(buf)

    def write_multihash(self, mh: Multihash) -> int:
        """Write one multihash to the stream."""
        return mh.write(self._stream)

Export from __init__.py and add tests.

Related

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions