Skip to content

Add RecordingInputStream.asOutputStream()#108

Merged
ato merged 1 commit into
masterfrom
RecordingInputStream-getOutputStream
May 21, 2025
Merged

Add RecordingInputStream.asOutputStream()#108
ato merged 1 commit into
masterfrom
RecordingInputStream-getOutputStream

Conversation

@ato

@ato ato commented May 20, 2025

Copy link
Copy Markdown
Member

Using RecordingInputStream requires an awkward workaround when the API being recorded is not in the form of an InputStream, for example, if it's asynchronous. This adds a method to access the underlying RecordingOutputStream so you can write to it directly when that would be easier.

Before:

byte[] inputBuffer;
InputStream ris = recorder.inputWrap(new InputStream() {
    public int read(byte[] buffer, int off, int len) {
        System.arraycopy(inputBuffer, 0, buffer, off, len);
        return len;
    }

    public int read() { throw new AssertionError(); }
});

void onDataReceived(byte[] chunk) throws IOException {
    byte[] discardBuffer = new byte[chunk.length]
    inputBuffer = chunk;
    ris.read(discardBuffer, 0, chunk.length);
}

After:

InputStream ris = recorder.inputWrap(null);

void onDataReceived(byte[] chunk) throws IOException {
     ris.asOutputStream().write(chunk);
}

@ato

ato commented May 20, 2025

Copy link
Copy Markdown
Member Author

Thinking about it again I realised you can simplify the workaround by passing the data to read() and then have the wrapped InputStream do nothing and just pretend to have written to the buffer. Although I think asOutputStream() is still worth having, because this code is rather deceptive and unexpected. It's also convenient to be able to pass the OutputStream to other the APIs that expect one.

InputStream ris = recorder.inputWrap(new InputStream() {
    public int read(byte[] buffer, int off, int len) {
        return len; // do nothing, buffer already has the expected data
    }

    public int read() { throw new AssertionError(); }
});

void onDataReceived(byte[] chunk) throws IOException {
    ris.read(chunk, 0, chunk.length);
}

@ato ato force-pushed the RecordingInputStream-getOutputStream branch from 3459ef4 to d45d696 Compare May 20, 2025 10:04
Using RecordingInputStream requires an awkward workaround when the API being recorded is not in the form of an InputStream, for example, if it's asynchronous. This adds a method to access the underlying RecordingOutputStream so you can write to it directly when that would be easier.
@ato ato force-pushed the RecordingInputStream-getOutputStream branch from d45d696 to cc85f05 Compare May 21, 2025 04:43
@ato ato merged commit ef054d1 into master May 21, 2025
8 checks passed
@ato ato deleted the RecordingInputStream-getOutputStream branch May 21, 2025 04:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant