Skip to content

Commit

Permalink
Attribute names and value are now written in UTF-8 if TextEncoder exi…
Browse files Browse the repository at this point in the history
…sts.
  • Loading branch information
jeff-tenhave committed Nov 3, 2017
1 parent c73e0bf commit e201742
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
23 changes: 22 additions & 1 deletion src/lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,29 @@ module.exports.rpad = function rpad(str, len, char) {
* @returns {number}
*/
module.exports.writeField = function writeField(view, fieldLength, str, offset) {
var 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;
12 changes: 7 additions & 5 deletions src/structure.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit e201742

Please sign in to comment.