Skip to content

Commit

Permalink
perf: add overflow check
Browse files Browse the repository at this point in the history
  • Loading branch information
Vovchyk committed Oct 9, 2024
1 parent a108557 commit 4aef18d
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ public static void checkArraycopyParams(int srcLength, int srcPos, byte[] dest,
if (length < 0) {
throw new IndexOutOfBoundsException("invalid 'length': " + length);
}
if (srcPos < 0 || srcPos + length > srcLength) {
if (srcPos < 0 || Long.sum(srcPos, length) > srcLength) {
throw new IndexOutOfBoundsException("invalid 'srcPos' and/or 'length': [" + srcPos + ";" + length + ")");
}
if (destPos < 0 || destPos + length > dest.length) {
if (destPos < 0 || Long.sum(destPos, length) > dest.length) {
throw new IndexOutOfBoundsException("invalid 'destPos' and/or 'length': [" + destPos + ";" + length + ")");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,10 @@ default byte[] copyArrayOfRange(int from, int to) {
if (from < 0 || from > length()) {
throw new IndexOutOfBoundsException("invalid 'from': " + from);
}
int newLength = to - from;
if (newLength < 0) {
if (to < from) {
throw new IllegalArgumentException(from + " > " + to);
}
int newLength = to - from;
byte[] copy = new byte[newLength];
arraycopy(from, copy, 0, Math.min(length() - from, newLength));
return copy;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,11 @@ default String toHexString() {
* @return the hexadecimal representation of the bytes in the range of {@code offset} and {@code length}.
*/
default String toHexStringV2(int offset, int length) {
int endIndex = offset + length;
if (offset < 0 || length < 0 || endIndex > length()) {
if (offset < 0 || length < 0 || Long.sum(offset, length) > length()) {
throw new IndexOutOfBoundsException("invalid 'offset' and/or 'length': " + offset + "; " + length);
}

int endIndex = offset + length;
StringBuilder sb = new StringBuilder(length * 2);
for (int i = offset; i < endIndex; i++) {
byte b = byteAt(i);
Expand All @@ -106,7 +106,7 @@ class PrintableBytesHexFormatter implements PrintableBytes.Formatter<HexPrintabl
@Override
public String toFormattedString(@Nonnull HexPrintableBytes printableBytes, int off, int length) {
int bytesLen = Objects.requireNonNull(printableBytes).length();
if (off + length > bytesLen) {
if (off < 0 || length < 0 || Long.sum(off, length) > bytesLen) {
throw new IndexOutOfBoundsException("invalid 'off' and/or 'length': " + off + "; " + length);
}

Expand Down

0 comments on commit 4aef18d

Please sign in to comment.