beth-parser
Version:
Parser library for Bethesda's Creation Engine data files
61 lines • 2.28 kB
JavaScript
;
exports.__esModule = true;
var iconv_lite_1 = require("iconv-lite");
/**
* Strings data serializer.
*/
var StringsSerializer = /** @class */ (function () {
/**
* @param strings Strings dictionary.
* @param padded Whether to use padded format.
* @param encoding String encoding.
*/
function StringsSerializer(padded, encoding) {
if (padded === void 0) { padded = false; }
if (encoding === void 0) { encoding = "utf-8"; }
this.padded = padded;
this.encoding = encoding;
}
/**
* Serialize strings into data buffer.
*/
StringsSerializer.prototype.serialize = function (strings) {
var _this = this;
var ids = Object.keys(strings).map(Number);
var directorySize = ids.length * 8;
var dataSize = 0;
// Create string to buffer dictionary
var dictionary = ids.reduce(function (result, stringId) {
var text = strings[stringId];
if (!result[text]) {
result[text] = iconv_lite_1.encode(text, _this.encoding);
dataSize += +_this.padded * 8 + result[text].length + 1;
}
return result;
}, {});
var buffer = Buffer.alloc(8 + directorySize + dataSize);
// Write header
buffer.writeUInt32LE(ids.length, 0);
buffer.writeUInt32LE(dataSize, 4);
// Serialize data
Object.keys(dictionary).reduce(function (offset, text) {
var encoded = dictionary[text];
dictionary[text] = offset;
if (_this.padded) {
buffer.writeUInt32LE(encoded.length + 1, 8 + directorySize + offset);
offset += 4;
}
encoded.copy(buffer, 8 + directorySize + offset);
return offset + encoded.length + 1;
}, 0);
// Serialize dictionary
ids.forEach(function (id, index) {
buffer.writeUInt32LE(+id, 8 + index * 8);
buffer.writeUInt32LE(dictionary[strings[id]], 8 + index * 8 + 4);
});
return buffer;
};
return StringsSerializer;
}());
exports["default"] = StringsSerializer;
//# sourceMappingURL=StringsSerializer.js.map