utility to write unsigned shorts

pull/4/head
Zlatin Balevsky 2018-07-27 08:10:50 +01:00
parent 3e02161b7d
commit e38fc4242b
2 changed files with 46 additions and 0 deletions

View File

@ -0,0 +1,17 @@
package com.muwire.core.util
class DataUtil {
private static int MAX_SHORT = (0x1 << 16) - 1
static writeUnsignedShort(int value, OutputStream os) {
if (value > MAX_SHORT || value < 0)
throw new IllegalArgumentException("$value invalid")
byte lsb = (byte) (value & 0xFF)
byte msb = (byte) (value >> 8)
os.write(msb)
os.write(lsb)
}
}

View File

@ -0,0 +1,29 @@
package com.muwire.core.util
import static org.junit.Assert.fail
import org.junit.Test
class DataUtilTest {
private static void usVal(int value) {
ByteArrayOutputStream baos = new ByteArrayOutputStream()
DataUtil.writeUnsignedShort(value, baos)
def is = new DataInputStream(new ByteArrayInputStream(baos.toByteArray()))
assert is.readUnsignedShort() == value
}
@Test
void testUnsignedShort() {
usVal(0)
usVal(20)
usVal(Short.MAX_VALUE)
usVal(Short.MAX_VALUE + 1)
usVal(0xFFFF)
try {
usVal(0xFFFF + 1)
fail()
} catch (IllegalArgumentException expected) {}
}
}