Created
September 3, 2017 21:57
-
-
Save nickman/82d23903f9d6004e635a5d6ceddda949 to your computer and use it in GitHub Desktop.
Netty Int Array Codec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Random; | |
import io.netty.buffer.ByteBuf; | |
import io.netty.buffer.UnpooledByteBufAllocator; | |
public class IntArrayCodec { | |
static final int MAP_WIDTH = 10; | |
static final int MAP_HEIGHT = 10; | |
static final Random RANDOM = new Random(System.currentTimeMillis()); | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
int[][] map = new int[MAP_WIDTH][MAP_HEIGHT]; | |
for(int w = 0; w < MAP_WIDTH; w++) { | |
for(int h = 0; h < MAP_HEIGHT; h++) { | |
map[w][h] = RANDOM.nextInt(); | |
} | |
} | |
ByteBuf buf = fromArray(MAP_WIDTH, MAP_HEIGHT, map); | |
int[][] newMap = fromBuf(buf); | |
if(Arrays.deepEquals(map, newMap)) { | |
System.out.println("Arrays Match"); | |
} else { | |
System.err.println("Array Mismatch"); | |
} | |
} | |
static ByteBuf fromArray(int width, int height, int[][] map) { | |
ByteBuf buf = UnpooledByteBufAllocator.DEFAULT.buffer((width * height * 4) + 8); | |
buf.writeInt(width); | |
buf.writeInt(height); | |
for(int w = 0; w < width; w++) { | |
for(int h = 0; h < height; h++) { | |
buf.writeInt(map[w][h]); | |
} | |
} | |
// rewind the buff (not needed when transmitting) | |
buf.readerIndex(0); | |
return buf; | |
} | |
static int[][] fromBuf(ByteBuf buf) { | |
int width = buf.readInt(); | |
int height = buf.readInt(); | |
int[][] map = new int[width][height]; | |
for(int w = 0; w < width; w++) { | |
for(int h = 0; h < height; h++) { | |
map[w][h] = buf.readInt(); | |
} | |
} | |
return map; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment