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

feat: add utility functions for dealing with Uint8Arrays #55

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"iso-url": "^0.4.7",
"it-glob": "0.0.8",
"merge-options": "^2.0.0",
"multibase": "^2.0.0",
"nanoid": "^3.1.3",
"node-fetch": "^2.6.0",
"stream-to-it": "^0.2.0"
Expand Down
32 changes: 32 additions & 0 deletions src/uint8arrays/compare.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
'use strict'

/**
* Can be used with Array.sort to sort and array with Uint8Array entries
*
* @param {Uint8Array} a
* @param {Uint8Array} b
* @returns {Number}
*/
function compare (a, b) {
for (let i = 0; i < a.byteLength; i++) {
if (a[i] < b[i]) {
return -1
}

if (a[i] > b[i]) {
return 1
}
}

if (a.byteLength > b.byteLength) {
return 1
}

if (a.byteLength < b.byteLength) {
return -1
}

return 0
}

module.exports = compare
41 changes: 41 additions & 0 deletions src/uint8arrays/concat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use strict'

/**
* Returns a new Uint8Array created by concatenating the passed Arrays
*
* @param {Array<Array|TypedArray>} arrs
* @param {Number} length
* @returns {Uint8Array}
*/
function concat (arrs, length) {
if (!length) {
length = arrs.reduce((acc, curr) => {
if (ArrayBuffer.isView(curr)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 The logic that verifies each array and takes it's size is happening here once and then again down below. Could you maybe factor out that logic to byteLength(arr) function that returns length or throws if not a valid input ?

return acc + curr.byteLength
} else if (Array.isArray(curr)) {
return acc + curr.length
}

throw new Error('Invalid input passed to concat, should be an Array or ArrayBuffer view')
}, 0)
}

const output = new Uint8Array(length)
let offset = 0

arrs.forEach(arr => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 I'd encourage for here as I expect to be in hot code paths.

output.set(arr, offset)

if (ArrayBuffer.isView(arr)) {
offset += arr.byteLength
} else if (Array.isArray(arr)) {
offset += arr.length
} else {
throw new Error('Invalid input passed to concat, should be an Array or ArrayBuffer view')
}
})

return output
}

module.exports = concat
28 changes: 28 additions & 0 deletions src/uint8arrays/equals.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict'

/**
* Returns true if the two passed Uint8Arrays have the same content
*
* @param {Uint8Array} a
* @param {Uint8Array} b
* @returns {boolean}
*/
function equals (a, b) {
if (a === b) {
return true
}

if (a.byteLength !== b.byteLength) {
return false
}

for (let i = 0; i < a.byteLength; i++) {
if (a[i] !== b[i]) {
return false
}
}

return true
}

module.exports = equals
24 changes: 24 additions & 0 deletions src/uint8arrays/from-string.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict'

const multibase = require('multibase')
const { names } = require('multibase/src/constants')
const TextEncoder = require('../text-encoder')
const utf8Encoder = new TextEncoder('utf8')

function fromString (string, encoding = 'utf8') {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you please add some comment what this supposed to do and a note what encoding this supposed to support.

if (encoding !== 'utf8') {
const base = names[encoding]

if (!base) {
throw new Error('Unknown base')
}

string = `${base.code}${string}`

return Uint8Array.from(multibase.decode(string))
Copy link
Member Author

@achingbrain achingbrain Jul 30, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can get rid of the copy when multiformats/js-multibase#63 is merged, though it depends on this PR. What larks.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This whole circular dependence makes me feel uncomfortable:

  • It is awkward that you have to prefix string to decode
  • Non trivial chunk of code is being pulled in now where in most cases I think you only care about utf-8
  • multibase also uses this function which could short circuit (if things are overlooked)

It also doesn't appear like other encodings are used anywhere, so is this really necessary ? If so I think it would be far better to factor out logic behind multibase.decode(string) into separate library that just exposes underlying encoders / decoders and share it between multibase and this.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can call .base to get the underlying base encoder without prefix

}

return utf8Encoder.encode(string)
}

module.exports = fromString
15 changes: 15 additions & 0 deletions src/uint8arrays/to-string.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict'

const multibase = require('multibase')
const TextDecoder = require('../text-decoder')
const utf8Decoder = new TextDecoder('utf8')

function toString (buf, encoding = 'utf8') {
if (encoding !== 'utf8') {
buf = multibase.encode(encoding, buf).subarray(1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same sentiment as above.

}

return utf8Decoder.decode(buf)
}

module.exports = toString
49 changes: 49 additions & 0 deletions test/uint8array/compare.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
'use strict'

/* eslint-env mocha */
const { expect } = require('aegir/utils/chai')
const compare = require('../../src/uint8arrays/compare')

describe('Uint8Array compare', () => {
it('is stable', () => {
const a = Uint8Array.from([0, 1, 2, 3])
const b = Uint8Array.from([0, 1, 2, 3])

expect([a, b].sort(compare)).to.deep.equal([
a,
b
])
expect([b, a].sort(compare)).to.deep.equal([
b,
a
])
})

it('compares two Uint8Arrays', () => {
const a = Uint8Array.from([0, 1, 2, 4])
const b = Uint8Array.from([0, 1, 2, 3])

expect([a, b].sort(compare)).to.deep.equal([
b,
a
])
expect([b, a].sort(compare)).to.deep.equal([
b,
a
])
})

it('compares two Uint8Arrays with different lengths', () => {
const a = Uint8Array.from([0, 1, 2, 3, 4])
const b = Uint8Array.from([0, 1, 2, 3])

expect([a, b].sort(compare)).to.deep.equal([
b,
a
])
expect([b, a].sort(compare)).to.deep.equal([
b,
a
])
})
})
53 changes: 53 additions & 0 deletions test/uint8array/concat.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
'use strict'

/* eslint-env mocha */
const { expect } = require('aegir/utils/chai')
const concat = require('../../src/uint8arrays/concat')

describe('Uint8Array concat', () => {
it('concats two Uint8Arrays', () => {
const a = Uint8Array.from([0, 1, 2, 3])
const b = Uint8Array.from([4, 5, 6, 7])
const c = Uint8Array.from([0, 1, 2, 3, 4, 5, 6, 7])

expect(concat([a, b])).to.deep.equal(c)
})

it('concats two Uint8Arrays with a length', () => {
const a = Uint8Array.from([0, 1, 2, 3])
const b = Uint8Array.from([4, 5, 6, 7])
const c = Uint8Array.from([0, 1, 2, 3, 4, 5, 6, 7])

expect(concat([a, b], 8)).to.deep.equal(c)
})

it('concats mixed Uint8Arrays and Arrays', () => {
const a = Uint8Array.from([0, 1, 2, 3])
const b = [4, 5, 6, 7]
const c = Uint8Array.from([0, 1, 2, 3, 4, 5, 6, 7])

expect(concat([a, b])).to.deep.equal(c)
})

it('concats mixed Uint8Arrays and Arrays with a length', () => {
const a = Uint8Array.from([0, 1, 2, 3])
const b = [4, 5, 6, 7]
const c = Uint8Array.from([0, 1, 2, 3, 4, 5, 6, 7])

expect(concat([a, b], 8)).to.deep.equal(c)
})

it('throws when passed non ArrayBuffer views/Arrays', () => {
const a = Uint8Array.from([0, 1, 2, 3])
const b = 'Hello world'

expect(() => concat([a, b])).to.throw(/Invalid input/)
})

it('throws when passed non ArrayBuffer views/Arrays with a length', () => {
const a = Uint8Array.from([0, 1, 2, 3])
const b = 'Hello world'

expect(() => concat([a, b], 100)).to.throw(/Invalid input/)
})
})
28 changes: 28 additions & 0 deletions test/uint8array/equals.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict'

/* eslint-env mocha */
const { expect } = require('aegir/utils/chai')
const equals = require('../../src/uint8arrays/equals')

describe('Uint8Array equals', () => {
it('finds two Uint8Arrays equal', () => {
const a = Uint8Array.from([0, 1, 2, 3])
const b = Uint8Array.from([0, 1, 2, 3])

expect(equals(a, b)).to.be.true()
})

it('finds two Uint8Arrays not equal', () => {
const a = Uint8Array.from([0, 1, 2, 3])
const b = Uint8Array.from([0, 1, 2, 4])

expect(equals(a, b)).to.be.false()
})

it('finds two Uint8Arrays with different lengths not equal', () => {
const a = Uint8Array.from([0, 1, 2, 3])
const b = Uint8Array.from([0, 1, 2, 3, 4])

expect(equals(a, b)).to.be.false()
})
})
29 changes: 29 additions & 0 deletions test/uint8array/from-string.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use strict'

/* eslint-env mocha */
const { expect } = require('aegir/utils/chai')
const fromString = require('../../src/uint8arrays/from-string')
const TextEncoder = require('../../src/text-encoder')

describe('Uint8Array fromString', () => {
it('creates a Uint8Array from a string', () => {
const str = 'hello world'
const arr = new TextEncoder('utf8').encode(str)

expect(fromString(str)).to.deep.equal(arr)
})

it('creates a Uint8Array from a base16 string', () => {
const str = '00010203aabbcc'
const arr = Uint8Array.from([0, 1, 2, 3, 170, 187, 204])

expect(fromString(str, 'base16')).to.deep.equal(arr)
})

it('creates a Uint8Array from a base64 string', () => {
const str = 'AAECA6q7zA'
const arr = Uint8Array.from([0, 1, 2, 3, 170, 187, 204])

expect(fromString(str, 'base64')).to.deep.equal(arr)
})
})
29 changes: 29 additions & 0 deletions test/uint8array/to-string.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use strict'

/* eslint-env mocha */
const { expect } = require('aegir/utils/chai')
const toString = require('../../src/uint8arrays/to-string')
const TextEncoder = require('../../src/text-encoder')

describe('Uint8Array toString', () => {
it('creates a String from a Uint8Array', () => {
const str = 'hello world'
const arr = new TextEncoder('utf8').encode(str)

expect(toString(arr)).to.deep.equal(str)
})

it('creates a hex string from a Uint8Array', () => {
const str = '00010203aabbcc'
const arr = Uint8Array.from([0, 1, 2, 3, 170, 187, 204])

expect(toString(arr, 'base16')).to.deep.equal(str)
})

it('creates a base64 string from a Uint8Array', () => {
const str = 'AAECA6q7zA'
const arr = Uint8Array.from([0, 1, 2, 3, 170, 187, 204])

expect(toString(arr, 'base64')).to.deep.equal(str)
})
})