diff --git a/src/java.base/share/classes/java/net/DatagramPacket.java b/src/java.base/share/classes/java/net/DatagramPacket.java index 55e0eae0fb673..cf1b256dabc41 100644 --- a/src/java.base/share/classes/java/net/DatagramPacket.java +++ b/src/java.base/share/classes/java/net/DatagramPacket.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,10 @@ package java.net; +import java.util.Objects; + +import jdk.internal.util.Preconditions; + /** * This class represents a datagram packet. *

@@ -285,12 +289,9 @@ public synchronized int getLength() { * @since 1.2 */ public synchronized void setData(byte[] buf, int offset, int length) { - /* this will check to see if buf is null */ - if (length < 0 || offset < 0 || - (length + offset) < 0 || - ((length + offset) > buf.length)) { - throw new IllegalArgumentException("illegal length or offset"); - } + Objects.requireNonNull(buf); + Preconditions.checkFromIndexSize(offset, length, buf.length, + Preconditions.outOfBoundsExceptionFormatter(IllegalArgumentException::new)); this.buf = buf; this.length = length; this.bufLength = length; @@ -394,8 +395,9 @@ public synchronized void setData(byte[] buf) { * Set the length for this packet. The length of the packet is * the number of bytes from the packet's data buffer that will be * sent, or the number of bytes of the packet's data buffer that - * will be used for receiving data. The length must be lesser or - * equal to the offset plus the length of the packet's buffer. + * will be used for receiving data. The {@code length} plus the + * {@link #getOffset() offset} must be lesser or equal to the + * length of the packet's data buffer. * * @param length the length to set for this packet. * @@ -409,10 +411,8 @@ public synchronized void setData(byte[] buf) { * @since 1.1 */ public synchronized void setLength(int length) { - if ((length + offset) > buf.length || length < 0 || - (length + offset) < 0) { - throw new IllegalArgumentException("illegal length"); - } + Preconditions.checkFromIndexSize(offset, length, buf.length, + Preconditions.outOfBoundsExceptionFormatter(IllegalArgumentException::new)); this.length = length; this.bufLength = this.length; }