Skip to content

React-native bigint64 deserialization problem - refactoring/bigint64le #16

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

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Next Next commit
React-native compatible big int deserialization
  • Loading branch information
Admdebian committed Nov 29, 2021
commit 89928fbd1651640c04c989ba595b29d295aa1e03
28 changes: 4 additions & 24 deletions src/readBig.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { Buffer } from 'buffer'

// https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L758
const ERR_BUFFER_OUT_OF_BOUNDS = () => new Error('Attempt to access memory outside buffer bounds')

Expand Down Expand Up @@ -28,30 +26,12 @@ function boundsError(value: number, length: number) {
throw ERR_OUT_OF_RANGE('offset', `>= 0 and <= ${length}`, value)
}

// https://github.com/nodejs/node/blob/v14.17.0/lib/internal/buffer.js#L129-L145
// This function works with react-native >= 0.66.1
export function readBigInt64LE(buffer: Buffer, offset = 0): bigint {
validateNumber(offset, 'offset')
const first = buffer[offset]
const last = buffer[offset + 7]
if (first === undefined || last === undefined) boundsError(offset, buffer.length - 8)
// tslint:disable-next-line:no-bitwise
const val = buffer[offset + 4] + buffer[offset + 5] * 2 ** 8 + buffer[offset + 6] * 2 ** 16 + (last << 24) // Overflow
return (
(BigInt(val) << BigInt(32)) + // tslint:disable-line:no-bitwise
BigInt(first + buffer[++offset] * 2 ** 8 + buffer[++offset] * 2 ** 16 + buffer[++offset] * 2 ** 24)
)
return BigInt(buffer.readIntLE(offset, 8))
}

// https://github.com/nodejs/node/blob/v14.17.0/lib/internal/buffer.js#L89-L107
// This function works with react-native >= 0.66.1
export function readBigUInt64LE(buffer: Buffer, offset = 0): bigint {
validateNumber(offset, 'offset')
const first = buffer[offset]
const last = buffer[offset + 7]
if (first === undefined || last === undefined) boundsError(offset, buffer.length - 8)

const lo = first + buffer[++offset] * 2 ** 8 + buffer[++offset] * 2 ** 16 + buffer[++offset] * 2 ** 24

const hi = buffer[++offset] + buffer[++offset] * 2 ** 8 + buffer[++offset] * 2 ** 16 + last * 2 ** 24

return BigInt(lo) + (BigInt(hi) << BigInt(32)) // tslint:disable-line:no-bitwise
return BigInt(buffer.readUIntLE(offset, 8))
}