在 java.nio.Buffer 源碼中發現一個精妙的邊界檢查實現:
static void checkBounds(int off, int len, int size) {
if ((off | len | (off + len) | (size - (off + len))) < 0)
throw new IndexOutOfBoundsException();
}
常規寫法會使用多條件邏輯或:
if (off < 0 || len < 0 || (off + len) < 0 || (size - (off + len)) < 0)
|:任一操作數對應位為 1 則結果位為 1| 運算後結果最高位必為 1,即結果 < 0因此 (off | len | (off+len) | (size-(off+len))) < 0 等價於四個條件任一為真。
注意:需確保運算不溢出(此處參數為 int,邏輯安全)。