Class Pairs

java.lang.Object
dev.relism.flash.bytes.Pairs

public final class Pairs extends Object
The allocation-free idiom for returning two ints from a method without an object: pack both into one long, unpack at the call site. Already used, hand-rolled, in four places (Http1HeaderMap.findFirst, QueryParams.findFirst, and others) before this class existed — this is the single named home for the shifts so they are not duplicated (and potentially inconsistently duplicated — e.g. one copy masking with 0xFFFFFFFFL and another forgetting to) five times over.

Why this works

A long is 64 bits; each packed int is 32. pack(int, int) left-shifts the high half into the top 32 bits and OR's the low half into the bottom 32. lo(long) must mask with 0xFFFFFFFFL rather than simply cast to int after no mask, because a right-shift of a negative long sign-extends — the mask discards everything above bit 31 before the narrowing cast happens implicitly. hi(long) needs no mask: a right-shift by 32 already leaves only the original high bits in the low 32 positions of the result.

Encoding convention used across this codebase

Every findFirst-shaped method in this codebase packs (start << 32) | length, i.e. hi() == start and lo() == length. -1L is the shared "not found" sentinel (a valid (start, length) pair can never be negative, since both halves are non-negative offsets/lengths).
  • Method Details

    • pack

      public static long pack(int hi, int lo)
      Packs two ints into one long: hi in the upper 32 bits, lo in the lower 32.
    • hi

      public static int hi(long packed)
      Extracts the upper 32 bits packed by pack(int, int).
    • lo

      public static int lo(long packed)
      Extracts the lower 32 bits packed by pack(int, int).