From fbb129286293dd59c8debaeac6758b77c0ac43a6 Mon Sep 17 00:00:00 2001 From: Zlatin Balevsky Date: Fri, 27 Jul 2018 08:59:46 +0100 Subject: [PATCH] header un/packing --- .../com/muwire/core/util/DataUtil.groovy | 26 +++++++++++++++++-- .../com/muwire/core/util/DataUtilTest.groovy | 17 ++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/core/src/main/groovy/com/muwire/core/util/DataUtil.groovy b/core/src/main/groovy/com/muwire/core/util/DataUtil.groovy index bcbc00ff..fd4eef40 100644 --- a/core/src/main/groovy/com/muwire/core/util/DataUtil.groovy +++ b/core/src/main/groovy/com/muwire/core/util/DataUtil.groovy @@ -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) + } } diff --git a/core/src/test/groovy/com/muwire/core/util/DataUtilTest.groovy b/core/src/test/groovy/com/muwire/core/util/DataUtilTest.groovy index 869496fe..7ebf6185 100644 --- a/core/src/test/groovy/com/muwire/core/util/DataUtilTest.groovy +++ b/core/src/test/groovy/com/muwire/core/util/DataUtilTest.groovy @@ -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) {} + } }