Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Attribute names and value are now written in UTF-8 if TextEncoder exists #26

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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