header un/packing
This commit is contained in:
@@ -2,9 +2,9 @@ package com.muwire.core.util
|
||||
|
||||
class DataUtil {
|
||||
|
||||
private static int MAX_SHORT = (0x1 << 16) - 1
|
||||
private final static int MAX_SHORT = (0x1 << 16) - 1
|
||||
|
||||
static writeUnsignedShort(int value, OutputStream os) {
|
||||
static void writeUnsignedShort(int value, OutputStream os) {
|
||||
if (value > MAX_SHORT || value < 0)
|
||||
throw new IllegalArgumentException("$value invalid")
|
||||
|
||||
@@ -14,4 +14,26 @@ class DataUtil {
|
||||
os.write(msb)
|
||||
os.write(lsb)
|
||||
}
|
||||
|
||||
private final static int MAX_HEADER = 0x7FFFFF
|
||||
|
||||
static void packHeader(int length, byte [] header) {
|
||||
if (header.length != 3)
|
||||
throw new IllegalArgumentException("header length $header.length")
|
||||
if (length < 0 || length > MAX_HEADER)
|
||||
throw new IllegalArgumentException("length $length")
|
||||
|
||||
header[2] = (byte) (length & 0xFF)
|
||||
header[1] = (byte) ((length >> 8) & 0xFF)
|
||||
header[0] = (byte) ((length >> 16) & 0x7F)
|
||||
}
|
||||
|
||||
static int readLength(byte [] header) {
|
||||
if (header.length != 3)
|
||||
throw new IllegalArgumentException("header length $header.length")
|
||||
|
||||
return (((int)(header[0] & 0x7F)) << 16) |
|
||||
((int)(header[1] & 0xFF << 8)) |
|
||||
((int)header[2] & 0xFF)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,4 +26,21 @@ class DataUtilTest {
|
||||
fail()
|
||||
} catch (IllegalArgumentException expected) {}
|
||||
}
|
||||
|
||||
private static header(int value) {
|
||||
byte [] header = new byte[3]
|
||||
DataUtil.packHeader(value, header)
|
||||
assert value == DataUtil.readLength(header)
|
||||
}
|
||||
|
||||
@Test
|
||||
void testHeader() {
|
||||
header(0)
|
||||
header(1)
|
||||
header(8 * 1024 * 1024 - 1)
|
||||
try {
|
||||
header(8 * 1024 * 1024)
|
||||
fail()
|
||||
} catch (IllegalArgumentException expected) {}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user