Skip to content

Commit 11934dc

Browse files
Rename, relax validation, convert to arraybuf instead of hex
1 parent e39cf99 commit 11934dc

File tree

2 files changed

+12
-14
lines changed

2 files changed

+12
-14
lines changed

src/core/format/KeyGenerator.ts

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,12 @@ export class KeyGenerator {
2323
* @param {string} input Input string
2424
* @returns {UInt64} Deterministic uint64 value for the given string
2525
*/
26-
public static fromString(input: string): UInt64 {
26+
public static generateUInt64Key(input: string): UInt64 {
2727
if (input.length === 0) {
2828
throw Error(`Input must not be empty`);
2929
}
30-
if (input.length > 1024) {
31-
throw Error(`Input exceeds 1024 characters (has ${input.length})`);
32-
}
33-
const hex = sha3_256(input)
34-
return UInt64.fromHex(hex.substr(0, 16))
30+
const buf = sha3_256.arrayBuffer(input);
31+
const result = new Uint32Array(buf);
32+
return new UInt64([result[0], (result[1] | 0x80000000) >>> 0]);
3533
}
3634
}

test/core/format/KeyGenerator.spec.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,20 +20,20 @@ import { KeyGenerator } from '../../../src/core/format/KeyGenerator';
2020
describe('key generator', () => {
2121
describe('generate key from string', () => {
2222
it('throws if input is empty', () => {
23-
expect(() => KeyGenerator.fromString('')).to.throw(Error, 'Input must not be empty');
23+
expect(() => KeyGenerator.generateUInt64Key('')).to.throw(Error, 'Input must not be empty');
2424
})
2525
it('returns UInt64', () => {
26-
expect(KeyGenerator.fromString('a')).to.be.instanceOf(UInt64);
26+
expect(KeyGenerator.generateUInt64Key('a')).to.be.instanceOf(UInt64);
2727
})
2828
it('generates correct keys', () => {
29-
expect(KeyGenerator.fromString('a').toHex()).to.equal('80084BF2FBA02475');
29+
expect(KeyGenerator.generateUInt64Key('a').toHex()).to.equal('F524A0FBF24B0880');
3030
})
3131
it('generates keys deterministically', () => {
32-
expect(KeyGenerator.fromString('abc').toHex()).to.equal('3A985DA74FE225B2');
33-
expect(KeyGenerator.fromString('abc').toHex()).to.equal('3A985DA74FE225B2');
34-
expect(KeyGenerator.fromString('def').toHex()).to.equal('8E0D8F672252ACB0');
35-
expect(KeyGenerator.fromString('def').toHex()).to.equal('8E0D8F672252ACB0');
36-
expect(KeyGenerator.fromString('abc').toHex()).to.equal('3A985DA74FE225B2');
32+
expect(KeyGenerator.generateUInt64Key('abc').toHex()).to.equal('B225E24FA75D983A');
33+
expect(KeyGenerator.generateUInt64Key('abc').toHex()).to.equal('B225E24FA75D983A');
34+
expect(KeyGenerator.generateUInt64Key('def').toHex()).to.equal('B0AC5222678F0D8E');
35+
expect(KeyGenerator.generateUInt64Key('def').toHex()).to.equal('B0AC5222678F0D8E');
36+
expect(KeyGenerator.generateUInt64Key('abc').toHex()).to.equal('B225E24FA75D983A');
3737
})
3838
})
3939
});

0 commit comments

Comments
 (0)