UNPKG

reign

Version:

A persistent, typed-objects implementation.

106 lines (90 loc) 2.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.make = make; var _backing = require("backing"); var _backing2 = _interopRequireDefault(_backing); var _ = require("../.."); var _string = require("../../random/string"); var _string2 = _interopRequireDefault(_string); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function make(realm) { const StringType = realm.StringType; const T = realm.T; const pool = realm.strings; const RawString = T.String; const InternedString = new StringType({ name: 'InternedString', byteLength: 8, // Pointer byteAlignment: 8, constructor: function constructor(input) { if (this instanceof InternedString) { throw new TypeError(`InternedString is not a constructor.`); } else { return input == null ? '' : '' + input; } }, cast: function cast(input) { return input == null ? '' : '' + input; }, accepts: function accepts(input) { return typeof input === 'string'; }, initialize: function initialize(backing, pointerAddress, initialInput) { if (!initialInput) { backing.setFloat64(pointerAddress, 0); } else { backing.setFloat64(pointerAddress, pool.add(initialInput)); } }, store: function store(backing, pointerAddress, input) { const existing = backing.getFloat64(pointerAddress); if (!input) { if (existing !== 0) { pool.unref(existing); backing.setFloat64(pointerAddress, 0); } } else { const address = pool.add(input); if (address !== existing) { if (existing !== 0) { pool.unref(existing); } backing.setFloat64(pointerAddress, address); } } }, load: RawString.load, clear: function clear(backing, pointerAddress) { const existing = backing.getFloat64(pointerAddress); if (existing !== 0) { pool.unref(existing); backing.setFloat64(pointerAddress, 0); } }, randomValue: _string2.default, emptyValue: function emptyValue() { return ''; }, hashValue: hashString, equal: function equal(valueA, valueB) { return valueA === valueB; }, flowType: function flowType() { return `string`; } }); return InternedString; } /** * Returns the hash for the given string. */ function hashString(input) { let hash = 0x811c9dc5; for (let i = 0; i < input.length; i++) { hash ^= input.charCodeAt(i); hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24); } return hash >>> 0; }