zandaqo / structurae

Data structures for high-performance JavaScript applications.
MIT License
694 stars 21 forks source link

Java Support? #27

Open jfuehner opened 2 years ago

jfuehner commented 2 years ago

Was curious if it is possible to convert Java objects into a View and sent to browser for JavaScript consumption? Any examples?

zandaqo commented 2 years ago

Sure. View objects of fixed size are just raw buffers where data is laid out sequentially without any padding, pointers etc. For example, the following schema:

{
  $id: "Pet",
  type: "object",
  properties: {
    name: { type: "string", maxLength: 6 },
    age: { type: "number", btype: "uint8" },
  },
};

results in a buffer where 6 bytes of UTF8 string are followed by one byte integer, 7 bytes total. This sort of buffer or byte array can be created in any language supporting byte manipulations. In C/C++ one can just use structs with #pragma pack(1) directive to disable alignment. I am not sure what would be the easiest way of doing the same in Java, but it does have a number of primitives working with bytes, including ByteBuffer class, so something along the following lines should work:

...
  // get utf8 bytes of our name string;
  byte[] name = "Arthur".getBytes("UTF-8");
  // encode age as one byte
  byte age = 10;
  // allocate 7 bytes of buffer
  ByteBuffer buffer = ByteBuffer.allocate(7);
  // write the name at the beginning 
  buffer.put(name);
  // write age as the last byte
  buffer.put(6, age);
...