Skip to content

Commit 8226862

Browse files
committed
Merge pull request #4320 from kfeuz/network_readbytes
Added readBytes(max) to net library
2 parents 7375bbe + 587193e commit 8226862

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

java/libraries/net/src/processing/net/Client.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,36 @@ public byte[] readBytes() {
406406
}
407407

408408

409+
/**
410+
* <h3>Advanced</h3>
411+
* Return a byte array of anything that's in the serial buffer
412+
* up to the specified maximum number of bytes.
413+
* Not particularly memory/speed efficient, because it creates
414+
* a byte array on each read, but it's easier to use than
415+
* readBytes(byte b[]) (see below).
416+
*
417+
* @param max the maximum number of bytes to read
418+
*/
419+
public byte[] readBytes(int max) {
420+
if (bufferIndex == bufferLast) return null;
421+
422+
synchronized (buffer) {
423+
int length = bufferLast - bufferIndex;
424+
if (length > max) length = max;
425+
byte outgoing[] = new byte[length];
426+
System.arraycopy(buffer, bufferIndex, outgoing, 0, length);
427+
428+
bufferIndex += length;
429+
if (bufferIndex == bufferLast) {
430+
bufferIndex = 0; // rewind
431+
bufferLast = 0;
432+
}
433+
434+
return outgoing;
435+
}
436+
}
437+
438+
409439
/**
410440
* <h3>Advanced</h3>
411441
* Grab whatever is in the serial buffer, and stuff it into a

0 commit comments

Comments
 (0)