-
Notifications
You must be signed in to change notification settings - Fork 34
Mapping
Mapping is a strong mechanism embedded into JBBP to map parsed structures to a class to make access to the parsed data much easier.
By default JBBP parser parses binary data to its structure representation and it is possible to get access to the data by their names, paths or even types if the types are unique in parsed data but such way is too verbose, thus the mapping mechanism was developed and it can be called by .mapTo() method of a parsed strcuture
JBBPFieldStruct struct = ...;
struct.mapTo(classToMap.class);
You can map parsed data to an instance of a class, or provide just a class and its instance will be created automatically by some hack methods, in Oracle JDK for instance it will be created without a constructor call and in Android with a constructor call but by slower way< so that keep it in your mind if you work with the mechanism. To provide a prepared instance of a class is fastest way in the case. Mapper checks fields of the class for @Bin annotation which can contain some extra information to help figure out the mapped field in parsed data, the annotation can be defined for whole class and will be used by default for each class field. Transient fields will be removed from processing, so that you can use the keyword to exclude a field from mapping process. By default the mapper takes the field name and the field type and finds in the parsed structure fields for the name and the type which can be mapped to the field, such behaviour can be changed by redefinition attributes in @Bin annotation for the field. By default the mapper does such mapping of field type:
- byte map to parsed byte field
- char map to parsed ushort field
- short map to parsed short field
- boolean map to parsed bool field
- int and float map to parsed int field
- long and double map to parsed long field
- a non-primitive by default it will be mapped to a structure, for String you can make direct definition of mapped field, it allows BIT_ARRAY, BYTE_ARRAY, UBYTE_ARRAY, SHORT_ARRAY and USHORT_ARRAY.
- byte[] map to byte[]
- char[] map to ushort[]
- short[] map to short[]
- boolean[] map to bool[]
- int[] and float[] map to int[]
- long[] and double[] map to long[]
- a non-primitive[] will be mapped to structure array and each structure will be mapped to field of each array item
Mapping with String
class Parsed {
@Bin(path = "struct.a") byte num;
@Bin(path = "struct.b",type = BinType.BYTE_ARRAY) String str;
}
final Parsed parsed = JBBPParser.prepare("int start; struct { byte a; byte [3] b; } int end;").parse(new byte[]{1,2,3,4, 5, (byte)'a', (byte)'b', (byte)'c', 6,7,8,9}).mapTo(Parsed.class);
assertEquals(0x05, parsed.num);
assertEquals("abc", parsed.str);