/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as i18n from './i18n_ast'; export function digestMessage(message: i18n.Message): string { return strHash(serializeNodes(message.nodes).join('') + `[${message.meaning}]`); } /** * String hash function similar to java.lang.String.hashCode(). * The hash code for a string is computed as * s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], * where s[i] is the ith character of the string and n is the length of * the string. We mod the result to make it between 0 (inclusive) and 2^32 (exclusive). * * Based on goog.string.hashCode from the Google Closure library * https://github.com/google/closure-library/ * * @internal */ // TODO(vicb): better algo (less collisions) ? export function strHash(str: string): string { let result: number = 0; for (var i = 0; i < str.length; ++i) { // Normalize to 4 byte range, 0 ... 2^32. result = (31 * result + str.charCodeAt(i)) >>> 0; } return result.toString(16); } /** * Serialize the i18n ast to something xml-like in order to generate an UID. * * The visitor is also used in the i18n parser tests * * @internal */ class _SerializerVisitor implements i18n.Visitor { visitText(text: i18n.Text, context: any): any { return text.value; } visitContainer(container: i18n.Container, context: any): any { return `[${container.children.map(child => child.visit(this)).join(', ')}]`; } visitIcu(icu: i18n.Icu, context: any): any { let strCases = Object.keys(icu.cases).map((k: string) => `${k} {${icu.cases[k].visit(this)}}`); return `{${icu.expression}, ${icu.type}, ${strCases.join(', ')}}`; } visitTagPlaceholder(ph: i18n.TagPlaceholder, context: any): any { return ph.isVoid ? `` : `${ph.children.map(child => child.visit(this)).join(', ')}`; } visitPlaceholder(ph: i18n.Placeholder, context: any): any { return `${ph.value}`; } visitIcuPlaceholder(ph: i18n.IcuPlaceholder, context?: any): any { return `${ph.value.visit(this)}`; } } const serializerVisitor = new _SerializerVisitor(); export function serializeNodes(nodes: i18n.Node[]): string[] { return nodes.map(a => a.visit(serializerVisitor, null)); }