diff --git a/src/lib.js b/src/lib.js index 0c7ff80..f2d99e6 100644 --- a/src/lib.js +++ b/src/lib.js @@ -26,8 +26,29 @@ module.exports.rpad = function rpad(str, len, char) { * @returns {number} */ module.exports.writeField = function writeField(view, fieldLength, str, offset) { + const buffer = toBuffer(str); for (var i = 0; i < fieldLength; i++) { - view.setUint8(offset, str.charCodeAt(i)); offset++; + view.setUint8(offset, buffer[i]); offset++; } return offset; }; + +/** + * @param {string} str + * @returns {object} + */ +function toBuffer(str) { + if (typeof TextEncoder === "function") { + var encoder = new TextEncoder(); + return encoder.encode(str); + } + + var buffer = new Uint16Array(str.length); + for (var i = 0; i < str.length; i++) { + buffer[i] = str.charCodeAt(i); + } + + return buffer; +} + +module.exports.toBuffer = toBuffer; diff --git a/src/structure.js b/src/structure.js index 4b02783..7555f9e 100644 --- a/src/structure.js +++ b/src/structure.js @@ -44,15 +44,17 @@ module.exports = function structure(data, meta) { view.setInt8(32 + fieldDescLength - 1, 0x0D); field_meta.forEach(function(f, i) { + var offset = 32 + i * 32; // field name - f.name.split('').slice(0, 8).forEach(function(c, x) { - view.setInt8(32 + i * 32 + x, c.charCodeAt(0)); + var buf = lib.toBuffer(f.name).slice(0, 11); + buf.forEach(function(b, x) { + view.setInt8(offset + x, b); }); // field type - view.setInt8(32 + i * 32 + 11, f.type.charCodeAt(0)); + view.setInt8(offset + 11, f.type.charCodeAt(0)); // field length - view.setInt8(32 + i * 32 + 16, f.size); - if (f.type == 'N') view.setInt8(32 + i * 32 + 17, 3); + view.setInt8(offset + 16, f.size); + if (f.type == 'N') view.setInt8(offset + 17, 3); }); offset = fieldDescLength + 32;