2

Is there a Java equivalent of Python's "construct" library? I want to write "structs" like so:

message = Struct("message",
    UBInt8("protocol"),
    UBInt16("length"),
    MetaField("data", lambda ctx: ctx["length"])
)

It doesn't have to specifically be a library with some sort of abstraction using the Java language. I mean, it could be a "portable" format, with an API for parsing the documents. I guess this could work out with XML, but it would be be a lot more ugly.

I realize I could just inter-operate with Python, but I don't want to do that.

someguy
  • 7,144
  • 12
  • 43
  • 57
  • I've not yet tested it but I also found https://github.com/raydac/java-binary-block-parser which seems to have feature parity with Construct – Alastair McCormack Jul 21 '17 at 11:35

2 Answers2

2

I've looked a lot around and all I could find was Ragel (www.complang.org/ragel), that can also produce Java code. It looked too complex for me so I've started some work to port Construct to Java. I suspect it would be easier to make something like that in Scala, Groovy or JavaScript.

Construct on GitHub: https://github.com/MostAwesomeDude/construct

java construct: https://github.com/ZiglioNZ/construct

I've spent a couple of days on it, mostly looking for equivalents of python's expressive classes. The most useful java classes I've found are: java.util.Scanner, java.util.Formatter and java.nio.ByteBuffer. It's a big task so I want to focus on something small like creating simple parsers and formatters for ByteBuffers.

[Update]

I've ported enough code to parse and build some of the protocols that come with Python Construct, such as ethernet, arp and ipv4. Check it out at https://github.com/ZiglioNZ/construct

[Update: new Release]

Java Construct 1.1.2 is now available, see release notes.

ZiglioUK
  • 2,573
  • 4
  • 27
  • 32
0

You can use DataInput/DataOutput (and their implementations) to convert any set of values from/to a set of bytes. This doesn't give you an object where you can use names to access the individual fields, though - you would have to create such yourself.

It depends a bit on what you want to do - do you have a fixed data format to send/receive on wire, or does this vary from time to time?

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
  • Not what I want. I want to do some declarative programming. For instance, several packets have this "message" block where I have to read the length, colour, font etc.. To reduce boilerplate code, I could declare a "message" structure and embed into the packets. – someguy Mar 06 '11 at 17:32