Cleanup hasher complexity (#1306)

This commit is contained in:
Jaco Greeff
2019-08-14 09:37:35 +02:00
committed by GitHub
parent 230898ca04
commit 53256fe0b2
@@ -7,36 +7,24 @@ import { u8aConcat, u8aToU8a } from '@polkadot/util';
import { blake2AsU8a, xxhashAsU8a } from '@polkadot/util-crypto';
type HasherInput = string | Buffer | Uint8Array;
type HasherCheck = 'isBlake2128' | 'isBlake2256' | 'isTwox128' | 'isTwox256' | 'isTwox64Concat';
export type HasherFunction = (data: HasherInput) => Uint8Array;
const DEFAULT = (data: HasherInput): Uint8Array => xxhashAsU8a(data, 128);
const map: Record<HasherCheck, HasherFunction> = {
isBlake2128: (data: HasherInput): Uint8Array => blake2AsU8a(data, 128),
isBlake2256: (data: HasherInput): Uint8Array => blake2AsU8a(data, 256),
isTwox128: (data: HasherInput): Uint8Array => xxhashAsU8a(data, 128),
isTwox256: (data: HasherInput): Uint8Array => xxhashAsU8a(data, 256),
isTwox64Concat: (data: HasherInput): Uint8Array => u8aConcat(xxhashAsU8a(data, 64), u8aToU8a(data))
};
export default function getHasher (hasher?: StorageHasher): HasherFunction {
// This one is the default for PlainType storage keys
if (!hasher) {
return (data: HasherInput): Uint8Array => xxhashAsU8a(data, 128);
}
const [, fn] = (hasher && Object.entries(map).find(([check]): boolean =>
hasher[check as HasherCheck]
)) || [undefined, DEFAULT];
if (hasher.isBlake2128) {
return (data: HasherInput): Uint8Array => blake2AsU8a(data, 128);
}
if (hasher.isBlake2256) {
return (data: HasherInput): Uint8Array => blake2AsU8a(data, 256);
}
if (hasher.isTwox128) {
return (data: HasherInput): Uint8Array => xxhashAsU8a(data, 128);
}
if (hasher.isTwox256) {
return (data: HasherInput): Uint8Array => xxhashAsU8a(data, 256);
}
if (hasher.isTwox64Concat) {
return (data: HasherInput): Uint8Array => u8aConcat(xxhashAsU8a(data, 64), u8aToU8a(data));
}
// All cases should be handled above, but if not, return Twox128 for
// backwards-compatbility
return (data: HasherInput): Uint8Array => xxhashAsU8a(data, 128);
return fn;
}