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

There is a potential runtime exception #27

Open
Liloveyang opened this issue Mar 12, 2020 · 0 comments
Open

There is a potential runtime exception #27

Liloveyang opened this issue Mar 12, 2020 · 0 comments

Comments

@Liloveyang
Copy link

Liloveyang commented Mar 12, 2020

Hello developer, first of all, thank you for opening your code. We developed a tool to scan whether there is runtime exception in the source code of the project. Then we scanned your code and found a method that may need to add try catch module! It is the putto method of rembulan-runtime \src\main\java\net\sandius\rembulan\stringbytestring.java.

Error reason: there is not enough space for ByteBuffer to store byte array parsed by string. Here is my test code,Thank you for your reply.

import sun.nio.cs.UTF_32;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Objects;

public class StringByteString {
    private final String string;
    private final Charset charset;

    private int byteHashCode;
    private int byteLength;

    StringByteString(String s, Charset charset) {
        this.string = Objects.requireNonNull(s);
        this.charset = Objects.requireNonNull(charset);
        if (!charset.canEncode()) {
            throw new IllegalArgumentException("Charset cannot encode: " + charset.name());
        }
        this.byteHashCode = 0;
        this.byteLength = string.isEmpty() ? 0 : -1;
    }

    private byte[] toBytes() {
        // TODO: cache the result
        return string.getBytes(charset);
    }

    public byte[] getBytes() {
        byte[] bytes = toBytes();

        // must make a defensive copy
        return Arrays.copyOf(bytes, bytes.length);
    }

    public void putTo(ByteBuffer buffer) {
        // ByteBuffer cannot be directly extended: it's safe to use a possibly cached array
        buffer.put(toBytes());
    }

    public static void main(String[] args) {
        StringByteString stringByteString = new StringByteString("I am Test",new UTF_32());
        ByteBuffer byteBuffer = ByteBuffer.allocate(2);
        stringByteString.putTo(byteBuffer);
    }
}
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

1 participant