From 04457fdac5c1e2b3d9c8eb002bd53581158e980e Mon Sep 17 00:00:00 2001 From: Louis Date: Wed, 22 Jan 2020 13:13:41 +0100 Subject: [PATCH] Factorization of setPayloadSize and getPayloadSize --- src/protocolP2P/FileList.java | 7 ++----- src/protocolP2P/FilePart.java | 6 ++---- src/protocolP2P/Payload.java | 16 ++++++++++++++++ 3 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/protocolP2P/FileList.java b/src/protocolP2P/FileList.java index 978bf74..e46ad33 100644 --- a/src/protocolP2P/FileList.java +++ b/src/protocolP2P/FileList.java @@ -21,8 +21,7 @@ public class FileList extends Payload { if (RequestResponseCode.fromCode(datagram[RequestResponseCode.RRCODE_POSITION]) != RequestResponseCode.LIST_RESPONSE) { throw new InternalError(); } - int size = (datagram[PAYLOAD_SIZE_POSITON] << (8*3)) | (datagram[PAYLOAD_SIZE_POSITON+1] << (8*2)) | (datagram[PAYLOAD_SIZE_POSITON+2] << 8) | datagram[PAYLOAD_SIZE_POSITON+3]; - + int size = getPayloadSize(datagram); } /** To datagram with padding */ @@ -34,9 +33,7 @@ public class FileList extends Payload { // bits 16-31 are reserved for future use //TODO size int size = ; - for(i=0;i<4;i++) { - datagram[Payload.PAYLOAD_SIZE_POSITON + i] = (byte) (size >> (8 * (3 - i)) & 0xFF); - } + datagram = setPayloadSize(size, datagram); //TODO content } } diff --git a/src/protocolP2P/FilePart.java b/src/protocolP2P/FilePart.java index 4d03f6d..984e98a 100644 --- a/src/protocolP2P/FilePart.java +++ b/src/protocolP2P/FilePart.java @@ -26,7 +26,7 @@ public class FilePart extends Payload { if (RequestResponseCode.fromCode(datagram[RequestResponseCode.RRCODE_POSITION]) != RequestResponseCode.LOAD_RESPONSE) { throw new InternalError(); } - int size = (datagram[PAYLOAD_SIZE_POSITON] << (8*3)) | (datagram[PAYLOAD_SIZE_POSITON+1] << (8*2)) | (datagram[PAYLOAD_SIZE_POSITON+2] << 8) | datagram[PAYLOAD_SIZE_POSITON+3]; + int size = getPayloadSize(datagram); } /** To datagram with padding */ @@ -38,9 +38,7 @@ public class FilePart extends Payload { // bits 16-31 are reserved for future use //TODO size int size = ; - for(i=0;i<4;i++) { - datagram[Payload.PAYLOAD_SIZE_POSITON + i] = (byte) (size >> (8 * (3 - i)) & 0xFF); - } + datagram = setPayloadSize(size, datagram); //TODO content } diff --git a/src/protocolP2P/Payload.java b/src/protocolP2P/Payload.java index 3cece81..4e3cc6c 100644 --- a/src/protocolP2P/Payload.java +++ b/src/protocolP2P/Payload.java @@ -43,4 +43,20 @@ public class Payload { // bits 16-31 are reserved for future use // payload size is 0 (this is what java have initialized datagram) } + + protected static byte[] setPayloadSize(int size, byte[] datagram) { + for(int i=0;i<4;i++) { + datagram[Payload.PAYLOAD_SIZE_POSITON + i] = (byte) (size >> (8 * (3 - i)) & 0xFF); + } + } + return datagram; + } + + protected static int getPayloadSize(byte[] datagram) { + int size = 0; + for(int i=0;i<4;i++) { + size |= ((int)datagram[PAYLOAD_SIZE_POSITON + i]) << (8* i); + } + return size; + } }