Skip to content

Native Map.bit reconstructs a shared key prefix to read one bit #1724

Closed

Description

@oxura

Bend 2.0.37, main e5527d5be0c441d00f1f7d2fb61eb464fa478e5c, Linux x86_64, Clang 22.1.8.

The native Map.bit implementation walks through Base and reconstructs the visited key prefix before handing the key back. A shared key cannot reuse the original nodes. A C path can read the same presence/code bits and return the original key word instead. This is the native counterpart of the JS-only #1702, not a request to change the trie encoding or Base.

Seven alternating process pairs on a 256-character shared key, 131,072 bit queries:

Native fold Current main Direct read
Median inside IO.now interval 115 ms 43 ms
Checksum 16143 16143
Original shared key afterward True True

The bit position varies over all 8,448 positions in this key. Each character has one presence bit and 32 MSB-first U32 bits, including codes outside Unicode. Positions beyond the key must be false and must not narrow to U32.

Save as map_bit.bend:

import Base

def fold(n: Nat, r: String & Bool, acc: U32) -> U32:
  match n:
    case 0n:
      (key, b) = r
      U32.add(acc, U32.from_nat(String.length(key)))
    case 1n+p:
      (key, b) = r
      +q = p
      fold(q, Map.bit(key, Nat.mod(q, 8448n)), U32.add(acc, Bool.to_u32(b)))

def run(+key: String) -> IO(Unit):
  do IO<Unit>:
    start : Nat <- IO.now()
    sum : U32 <- IO.pure(U32, fold(131072n, Map.bit(key, 0n), 0))
    end : Nat <- IO.now()
    IO.print(U32.show(sum))
    IO.print(Nat.show(Nat.sub(end, start)))
    IO.print(Bool.show(String.eq(key, String.repeat("a", 256n))))

def main() -> IO(Unit):
  run(String.repeat("a", 256n))
bun bend2/main.ts map_bit.bend -o map_bit
./map_bit --threads 1

The three lines are checksum, elapsed milliseconds, and the original-key check. Independent checksum oracle (not calling Bend or Map.bit):

let sum = 1; // the initial query is the first presence bit
for (let i = 1; i < 131072; i++) {
  const off = (i % 8448) % 33;
  sum += off === 0 ? 1 : (97 >>> (32 - off)) & 1;
}
console.log(sum + 256); // 16143, including final returned-key length
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions