[TS/JS] BigInt implementation (#6998)

* BigInt implementation

* Unit test reading long from existing bytebuffer

* Code review
This commit is contained in:
Alex E
2022-01-06 21:35:37 -05:00
committed by GitHub
parent f28c2b2936
commit ace4a37f22
22 changed files with 225 additions and 256 deletions

View File

@@ -1,5 +1,4 @@
import { FILE_IDENTIFIER_LENGTH, SIZEOF_INT } from "./constants";
import { Long } from "./long";
import { int32, isLittleEndian, float32, float64 } from "./utils";
import { Offset, Table, IGeneratedObject } from "./types";
import { Encoding } from "./encoding";
@@ -75,12 +74,12 @@ export class ByteBuffer {
return this.readInt32(offset) >>> 0;
}
readInt64(offset: number): Long {
return new Long(this.readInt32(offset), this.readInt32(offset + 4));
readInt64(offset: number): bigint {
return BigInt.asIntN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32)));
}
readUint64(offset: number): Long {
return new Long(this.readUint32(offset), this.readUint32(offset + 4));
readUint64(offset: number): bigint {
return BigInt.asUintN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32)));
}
readFloat32(offset: number): number {
@@ -108,8 +107,8 @@ export class ByteBuffer {
}
writeUint16(offset: number, value: number): void {
this.bytes_[offset] = value;
this.bytes_[offset + 1] = value >> 8;
this.bytes_[offset] = value;
this.bytes_[offset + 1] = value >> 8;
}
writeInt32(offset: number, value: number): void {
@@ -120,20 +119,20 @@ export class ByteBuffer {
}
writeUint32(offset: number, value: number): void {
this.bytes_[offset] = value;
this.bytes_[offset + 1] = value >> 8;
this.bytes_[offset + 2] = value >> 16;
this.bytes_[offset + 3] = value >> 24;
this.bytes_[offset] = value;
this.bytes_[offset + 1] = value >> 8;
this.bytes_[offset + 2] = value >> 16;
this.bytes_[offset + 3] = value >> 24;
}
writeInt64(offset: number, value: Long): void {
this.writeInt32(offset, value.low);
this.writeInt32(offset + 4, value.high);
writeInt64(offset: number, value: bigint): void {
this.writeInt32(offset, Number(BigInt.asIntN(32, value)));
this.writeInt32(offset + 4, Number(BigInt.asIntN(32, value >> BigInt(32))));
}
writeUint64(offset: number, value: Long): void {
this.writeUint32(offset, value.low);
this.writeUint32(offset + 4, value.high);
writeUint64(offset: number, value: bigint): void {
this.writeUint32(offset, Number(BigInt.asUintN(32, value)));
this.writeUint32(offset + 4, Number(BigInt.asUintN(32, value >> BigInt(32))));
}
writeFloat32(offset: number, value: number): void {
@@ -301,14 +300,7 @@ export class ByteBuffer {
}
return true;
}
/**
* A helper function to avoid generated code depending on this file directly.
*/
createLong(low: number, high: number): Long {
return Long.create(low, high);
}
/**
* A helper function for generating list for obj api
*/
@@ -341,4 +333,4 @@ export class ByteBuffer {
return ret;
}
}
}