Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

little endian bitfield #95

Open
rom1504 opened this issue Jan 13, 2019 · 1 comment
Open

little endian bitfield #95

rom1504 opened this issue Jan 13, 2019 · 1 comment

Comments

@rom1504
Copy link
Member

rom1504 commented Jan 13, 2019

our current implementation of bitfield is big endian

some protocols such as diablo2 are fully little endian, even their bitfields

2 ways to do that :

  1. implement it ourselves
  2. use https://github.com/inolen/bit-buffer

I'm not too confident on being able to do 1 easily.

Might try to do 2

@rom1504
Copy link
Member Author

rom1504 commented Jan 13, 2019

proposal : (untested)

const { BitStream } = require('bit-buffer')

function toArrayBuffer (buf) {
  const ab = new ArrayBuffer(buf.length)
  const view = new Uint8Array(ab)
  for (let i = 0; i < buf.length; ++i) {
    view[i] = buf[i]
  }
  return ab
}

function toBuffer (ab) {
  const buf = Buffer.alloc(ab.byteLength)
  const view = new Uint8Array(ab)
  for (let i = 0; i < buf.length; ++i) {
    buf[i] = view[i]
  }
  return buf
}

function readBitFieldLE (buffer, offset, typeArgs) {
  const reader = new BitStream(toArrayBuffer(buffer.slice(offset)))
  const results = {}
  let length = 0
  results.value = typeArgs.reduce((acc, { size, signed, name }) => {
    acc[name] = reader.readBits(size, signed)
    length += size
    return acc
  }, {})
  results.size = length
  return results
}
function writeBitFieldLE (value, buffer, offset, typeArgs) {
  const arr = new ArrayBuffer(sizeOfBitFieldLE(value, typeArgs))
  const stream = new BitStream(arr)
  typeArgs.forEach(({ size, signed, name }) => {
    const val = value[name]
    stream.writeBits(val, size)
    offset += size
  })
  const newBuffer = toBuffer(arr)
  newBuffer.copy(buffer, offset)

  return offset
}

function sizeOfBitFieldLE (value, typeArgs) {
  return Math.ceil(typeArgs.reduce((acc, { size }) => {
    return acc + size
  }, 0) / 8)
}

module.exports = { 'bitfieldLE': [readBitFieldLE, writeBitFieldLE, sizeOfBitFieldLE] }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant