public ByteBuffer write(Packet packet) {
		Integer foundId = packetMapping.inverse().get(packet.getClass());
		if (foundId == null) throw new IllegalArgumentException("Unknown packet class: " + packet.getClass());
		short id = foundId.shortValue();

		ByteBuffer serialized = packet.serialize();
		if (serialized.limit() > Short.MAX_VALUE) throw new IllegalArgumentException("Packet is too long, length=" + serialized.limit());
		short len = (short)serialized.limit();

		ByteBuffer result = ByteBuffer.allocate(4 + len);
		result.putShort(id);
		result.putShort(len);
		result.put(serialized);
		result.flip();

		return result;
	}