Skip to content

Commit e201742

Browse files
committed
Attribute names and value are now written in UTF-8 if TextEncoder exists.
1 parent c73e0bf commit e201742

2 files changed

Lines changed: 29 additions & 6 deletions

File tree

src/lib.js

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,29 @@ module.exports.rpad = function rpad(str, len, char) {
2626
* @returns {number}
2727
*/
2828
module.exports.writeField = function writeField(view, fieldLength, str, offset) {
29+
var buffer = toBuffer(str);
2930
for (var i = 0; i < fieldLength; i++) {
30-
view.setUint8(offset, str.charCodeAt(i)); offset++;
31+
view.setUint8(offset, buffer[i]); offset++;
3132
}
3233
return offset;
3334
};
35+
36+
/**
37+
* @param {string} str
38+
* @returns {object}
39+
*/
40+
function toBuffer(str) {
41+
if (typeof TextEncoder === "function") {
42+
var encoder = new TextEncoder();
43+
return encoder.encode(str);
44+
}
45+
46+
var buffer = new Uint16Array(str.length);
47+
for (var i = 0; i < str.length; i++) {
48+
buffer[i] = str.charCodeAt(i);
49+
}
50+
51+
return buffer;
52+
}
53+
54+
module.exports.toBuffer = toBuffer;

src/structure.js

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,17 @@ module.exports = function structure(data, meta) {
4444
view.setInt8(32 + fieldDescLength - 1, 0x0D);
4545

4646
field_meta.forEach(function(f, i) {
47+
var offset = 32 + i * 32;
4748
// field name
48-
f.name.split('').slice(0, 8).forEach(function(c, x) {
49-
view.setInt8(32 + i * 32 + x, c.charCodeAt(0));
49+
var buf = lib.toBuffer(f.name).slice(0, 11);
50+
buf.forEach(function(b, x) {
51+
view.setInt8(offset + x, b);
5052
});
5153
// field type
52-
view.setInt8(32 + i * 32 + 11, f.type.charCodeAt(0));
54+
view.setInt8(offset + 11, f.type.charCodeAt(0));
5355
// field length
54-
view.setInt8(32 + i * 32 + 16, f.size);
55-
if (f.type == 'N') view.setInt8(32 + i * 32 + 17, 3);
56+
view.setInt8(offset + 16, f.size);
57+
if (f.type == 'N') view.setInt8(offset + 17, 3);
5658
});
5759

5860
offset = fieldDescLength + 32;

0 commit comments

Comments
 (0)