Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow for a special case in bounds checks in UnsafeBuffer.wrap() #211

Closed
artem-anisimov opened this issue Jun 1, 2020 · 0 comments
Closed

Comments

@artem-anisimov
Copy link

Would it make sense for the bounds checks in the UnsafeBuffer.wrap(...) method to allow for the case where the offset equals to the buffer's capacity and the length is zero?

The typical scenario where it's needed is encoding a message that has a header and we want to slice the remaining bytes for the payload. If let's say we are about to encode a heartbeat message that has a zero payload, then the underlying buffer may happen to be of the same size as the header, and then we can't even slice a zero-length buffer from the end and we have to handle it as a special case, which is quite unexpected and inconvenient.

    UnsafeBuffer message = new UnsafeBuffer(new byte[8]);
    UnsafeBuffer payload = new UnsafeBuffer(0, 0);

    payload.wrap(message, 0, 8); // slice 8 bytes from the end - this works fine
    payload.wrap(message, 1, 7); // slice 7 bytes from the end - this works fine
    payload.wrap(message, 2, 6); // ...
    payload.wrap(message, 3, 5);
    payload.wrap(message, 4, 4);
    payload.wrap(message, 5, 3);
    payload.wrap(message, 6, 2);
    payload.wrap(message, 7, 1);
    payload.wrap(message, 8, 0); // slice 0 bytes from the end - ooops, it blows up here, should not this work too?

Note that java.nio.ByteBuffer works just fine in a similar use case:

    ByteBuffer message = ByteBuffer.allocate(8);
    message.put("myHeader".getBytes()); // add a header
    ByteBuffer payload = message.slice(); // we get a zero-length buffer here
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

No branches or pull requests

2 participants