Skip to content

Commit

Permalink
Backported bugfixes to tuple encoding for large negative bigints to 0…
Browse files Browse the repository at this point in the history
….10.x branch
  • Loading branch information
josephg committed Apr 9, 2020
1 parent f0aa19a commit 4acb185
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions lib/tuple.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ const encode = (into: BufferBuilder, item: TupleItem, versionstampPos: Versionst
into.appendByte(Code.IntZero + (isNeg ? -len : len))
} else if (len < 256) {
into.appendByte(isNeg ? Code.NegIntStart : Code.PosIntEnd)
into.appendByte(len)
into.appendByte(isNeg ? len ^ 0xff : len)
}
into.appendBuffer(rawBytes)
}
Expand Down Expand Up @@ -355,25 +355,27 @@ const encode = (into: BufferBuilder, item: TupleItem, versionstampPos: Versionst
}
}

function packRaw(arr: TupleItem[]): Buffer | UnboundStamp {
if (!Array.isArray(arr)) throw new TypeError('fdb.tuple.pack must be called with an array')
function packRaw(arr?: TupleItem | TupleItem[]): Buffer | UnboundStamp {
if (arr === undefined || Array.isArray(arr) && arr.length === 0) return BUF_EMPTY

if (arr.length === 0) return BUF_EMPTY

let versionstampPos: VersionstampPos = {}
// if (!Array.isArray(arr)) throw new TypeError('fdb.tuple.pack must be called with an array')
const versionstampPos: VersionstampPos = {}
const builder = new BufferBuilder()
for (let i = 0; i < arr.length; i++) {
encode(builder, arr[i], versionstampPos)
// console.log('pack', arr[i], builder.storage)
}

if (Array.isArray(arr)) {
for (let i = 0; i < arr.length; i++) {
encode(builder, arr[i], versionstampPos)
// console.log('pack', arr[i], builder.storage)
}
} else encode(builder, arr, versionstampPos)

const data = builder.make()
return versionstampPos.stamp == null
? data
: {data, stampPos: versionstampPos.stamp, codePos: versionstampPos.code}
}

export const pack = (arr: TupleItem[]): Buffer => {
export const pack = (arr?: TupleItem | TupleItem[]): Buffer => {
const pack = packRaw(arr)
if (!Buffer.isBuffer(pack)) throw new TypeError('Incomplete versionstamp included in vanilla tuple pack')
return pack
Expand Down Expand Up @@ -533,8 +535,9 @@ function decode(buf: Buffer, pos: {p: number}, vsAt: number, noCanonicalize: boo
return decodeBigInt(buf, p, absByteLen, byteLen < 0)
}
} else if (code === Code.NegIntStart || code === Code.PosIntEnd) {
const len = buf[p++]
const bytes = Buffer.alloc(len)
const isNeg = code === Code.NegIntStart
let len = buf[p++]
if (isNeg) len ^= 0xff
pos.p = p + len

return decodeBigInt(buf, p, len, code === Code.NegIntStart)
Expand Down

0 comments on commit 4acb185

Please sign in to comment.