All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ch.fritteli.maze.generator.serialization.v3.SerializerDeserializerV3 Maven / Gradle / Ivy

package ch.fritteli.maze.generator.serialization.v3;

import ch.fritteli.maze.generator.model.Maze;
import ch.fritteli.maze.generator.model.Position;
import ch.fritteli.maze.generator.model.Tile;
import lombok.experimental.UtilityClass;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Header bytes are:
 * 
 *   byte     hex    meaning
 *     00     0x1a   magic
 *     01     0xb1   magic
 *     02     0x03   version (0x00 -> dev, 0x01, 0x02 -> deprecated, 0x03 -> stable)
 *     03..06        width (int)
 *     07..10        height (int)
 *     11..14        start-x (int)
 *     15..18        start-y (int)
 *     19..22        end-x (int)
 *     23..26        end-y (int)
 *     27..34        random seed number (long)
 *     35            length of the algorithm's name (number of bytes of the Java String) (unsigned byte)
 *     36..(36+len)  algorithm's name (bytes of the Java String) (byte...)
 *     36+len+1..    tiles
 * 
* Extraneous space (poss. last nibble) is ignored. */ @UtilityClass public class SerializerDeserializerV3 { public final byte VERSION_BYTE = 0x03; /** * Serializes the {@code maze} into a byte array. * * @param maze The {@link Maze} to be serialized. * @return The resulting byte array. */ @NotNull public byte[] serialize(@NotNull final Maze maze) { final MazeOutputStreamV3 stream = new MazeOutputStreamV3(); stream.writeHeader(); stream.writeMazeData(maze); return stream.toByteArray(); } /** * Deserializes the byte array into an instance of {@link Maze}. * * @param bytes The byte array to be deserialized. * @return An instance of {@link Maze}. */ @NotNull public Maze deserialize(@NotNull final byte[] bytes) throws IOException { final MazeInputStreamV3 stream = new MazeInputStreamV3(bytes); stream.checkHeader(); return stream.readMazeData(); } @NotNull Maze createMaze(@NotNull final Tile[][] field, final int width, final int height, @NotNull final Position start, @NotNull final Position end, final long randomSeed, @NotNull final String algorithm) { try { final Constructor constructor = Maze.class.getDeclaredConstructor( Tile[][].class, Integer.TYPE, Integer.TYPE, Position.class, Position.class, Long.TYPE, String.class ); constructor.setAccessible(true); return constructor.newInstance(field, width, height, start, end, randomSeed, algorithm); } catch (@NotNull final NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { throw new RuntimeException("Can not deserialize Maze from maze data.", e); } } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy