rustwasm / book

The Rust and WebAssembly Book
https://rustwasm.github.io/docs/book/
MIT License
1.73k stars 208 forks source link

Trouble with 5.4 Exercise: Representing each cell as a bit #108

Closed jul1u5 closed 5 years ago

jul1u5 commented 5 years ago

I was reading this book and I wanted to try to do one of the exercises. The problem I am having is with 5.4 chapter's last exercise. On the rust side I used bit-vec crate to represent each cell as a boolean. But I don't know how to create a bit array in JavaScript from memory.buffer. I would appreciate if somebody would give me a hint.

fitzgen commented 5 years ago

You can iterate over bits in a Uint8Array like this:

function* bits(arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < 8; j++) {
      let mask = 1 << j;
      yield (arr[i] & mask) == mask;
    }
  }
}

// Example usage:
for (const bit of bits(new Uint8Array([0b11110000, 0b00111100]))]) {
  if (bit) {
    ...
  } else {
    ...
  }
}

The tutorial already shows how to create a Uint8Array from wasm memory, all that needs to happen now is divide by 8:

const cells = new Uint8Array(memory.buffer, cellsPtr, width * height / 8);

Is this enough to unblock you?

jul1u5 commented 5 years ago

Yeah, that makes sense. Thank you.