Introduction2But Preon turns that arround: you just provide it the blueprints of the data structure, and Preon willmake sure the data gets loaded into the appropriate places.Now, the big question is of course: how does Preon know how to load data from a sequence of bitsand reconstruct a data structure? What is the recipe? It turns out, the recipe is the data structureitself; it's just classes and attributes, period. And in case it the information provided by the datastructure is not enough, we will just augment it using annotations.So, let's look at an example. Example 1, “First data structure” defines a data structure defining thecoordinates of the two points defining a rectangle, in some coordinate system.
Example 1. First data structure
class Rectangle {private int x1;private int y1;private int x2;private int y2;}
Let's just say that the data would be encoded on disk as four consecutive 32-bit integers. In that case,this is the way you would decode a Rectangle from a file:
byte[] buffer = new byte[] {0, 0, 0, 1,0, 0, 0, 2,0, 0, 0, 3,0, 0, 0, 4};Codec<Rectangle> codec = Codecs.create(Rectangle.class);Rectangle rect = Codecs.decode(codec, buffer);
That's how easy it is. Although... To be perfectly honest, the example is not entirely complete yet. If you would use the code as-is, you would not get anything at all. (Well, an empty Rectangle, maybe.)Problem is, Preon does
not
assume anything about your decoding requirements. In order to tellPreon that it needs to decode the x1, y1, x2 and y2 fields, you will need to explicitly state it in thedefinition of the data structure, like this:
Example 2. First data structure annotated
class Rectangle {@Bound private int x1;@Bound private int y1;@Bound private int x2;@Bound private int y2;}
Add a Comment