Reading the NSA's Codebase: LemonGraph Review, Part 4: Compressed, Sortable Integers
This brief article looks at why LemonGraph is using its integer coding since it is less efficient than using a variant sized integer.
Join the DZone community and get the full member experience.Join For Free
Before going over the actual query implementation, I wanted to talk about something that I just realized. I said previously that I don’t understand why LemonGraph is using its integer encoding method because it is less efficient than using a variant sized integer. What I didn’t take into account is that the method LemonGraph is using gives short, but sortable, integers.
Here is the encoding method:
Now, let’s see what kind of binary output this will generate when given a few numbers:
The key here is that the number of bytes is stored as the first item. This means that when we compare two numbers using memcmp(), the number with more bytes is considered greater. This is indeed the case because if you need more bytes to store a number, it is obviously larger.
What about two numbers that have the same number of bytes? This is handled by a simple binary comparison of the values. If they are the same size, the fact that the encode() output them in big-endian format means that we can compare them using memcmp() and be done with it.
This is a really nice way to both keep the values sorted and to avoid storing the full 8 bytes for numbers that are usually much smaller.
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.