dns-packet-typescript
Version:
An abstract-encoding compliant module for encoding / decoding DNS packets
73 lines • 2.03 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodingLength = exports.decode = exports.encode = void 0;
function encode(data, buf, offset) {
if (offset === void 0) { offset = 0; }
if (!Array.isArray(data))
data = [data];
for (var i = 0; i < data.length; i++) {
if (typeof data[i] === 'string') {
data[i] = Buffer.from(data[i]);
}
if (!Buffer.isBuffer(data[i])) {
throw new Error('Must be a Buffer');
}
}
// just a hack for type
var _data = data;
if (!buf)
buf = Buffer.allocUnsafe(encodingLength(_data));
if (!offset)
offset = 0;
var oldOffset = offset;
offset += 2;
_data.forEach(function (d) {
buf[offset++] = d.length;
d.copy(buf, offset, 0, d.length);
offset += d.length;
});
buf.writeUInt16BE(offset - oldOffset - 2, oldOffset);
encode.bytes = offset - oldOffset;
return buf;
}
exports.encode = encode;
encode.bytes = 0;
function decode(buf, offset) {
if (offset === void 0) { offset = 0; }
if (!offset)
offset = 0;
var oldOffset = offset;
var remaining = buf.readUInt16BE(offset);
offset += 2;
var data = [];
while (remaining > 0) {
var len = buf[offset++];
--remaining;
if (remaining < len) {
throw new Error('Buffer overflow');
}
data.push(buf.slice(offset, offset + len));
offset += len;
remaining -= len;
}
decode.bytes = offset - oldOffset;
return data;
}
exports.decode = decode;
decode.bytes = 0;
function encodingLength(data) {
if (!Array.isArray(data))
data = [data];
var length = 2;
data.forEach(function (buf) {
if (typeof buf === 'string') {
length += Buffer.byteLength(buf) + 1;
}
else {
length += buf.length + 1;
}
});
return length;
}
exports.encodingLength = encodingLength;
//# sourceMappingURL=rtxt.js.map
;