fix(ripple-keypairs): make bytesToHex work with typed arrays (Uint8Array) (#1975)

This works the same as before for Array inputs, but it should now also
work correctly with a wider range of Iterable or ArrayLike input types.

In particular, this makes it work with typed arrays such as Uint8Array,
which previously produced invalid output due to the hex numerals being
coerced back to the element type before the call to `join('')`.
This commit is contained in:
Pi Delport
2022-04-28 22:18:39 +02:00
committed by GitHub
parent f17d0ef810
commit 86001d51f9
3 changed files with 17 additions and 7 deletions

View File

@@ -1,5 +1,9 @@
# ripple-keypairs Release History
## Unreleased
- Extend `bytesToHex` to work correctly with any input type accepted by `Array.from`.
In particular, it now produces correct output for typed arrays such as `UInt8Array`.
## 1.1.1 (2021-12-1)
- Fix issue where npm < 7 was not allowed to install the library

View File

@@ -2,13 +2,11 @@ import * as assert from 'assert'
import * as hashjs from 'hash.js'
import * as BN from 'bn.js'
function bytesToHex(a): string {
return a
.map((byteValue) => {
const hex = byteValue.toString(16).toUpperCase()
return hex.length > 1 ? hex : `0${hex}`
})
.join('')
function bytesToHex(a: Iterable<number> | ArrayLike<number>): string {
return Array.from(a, (byteValue) => {
const hex = byteValue.toString(16).toUpperCase()
return hex.length > 1 ? hex : `0${hex}`
}).join('')
}
function hexToBytes(a): number[] {

View File

@@ -11,4 +11,12 @@ describe('utils', () => {
it('hexToBytes - DEADBEEF', () => {
assert.deepEqual(utils.hexToBytes('DEADBEEF'), [222, 173, 190, 239])
})
it('bytesToHex - DEADBEEF', () => {
assert.deepEqual(utils.bytesToHex([222, 173, 190, 239]), 'DEADBEEF')
});
it('bytesToHex - DEADBEEF (Uint8Array)', () => {
assert.deepEqual(utils.bytesToHex(new Uint8Array([222, 173, 190, 239])), 'DEADBEEF')
});
})