nstdlib-nightly
Version:
Node.js standard library converted to runtime-agnostic ES modules.
79 lines (62 loc) • 1.97 kB
JavaScript
// Source: https://github.com/nodejs/node/blob/65eff1eb/lib/internal/dgram.js
import { codes as __codes__ } from "nstdlib/lib/internal/errors";
import { UDP } from "nstdlib/stub/binding/udp_wrap";
import { guessHandleType } from "nstdlib/lib/internal/util";
import { isInt32, validateFunction } from "nstdlib/lib/internal/validators";
import { UV_EINVAL } from "nstdlib/stub/binding/uv";
import * as __hoisted_dns__ from "nstdlib/lib/dns";
const { ERR_SOCKET_BAD_TYPE } = __codes__;
const kStateSymbol = Symbol("state symbol");
let dns; // Lazy load for startup performance.
function lookup4(lookup, address, callback) {
return lookup(address || "127.0.0.1", 4, callback);
}
function lookup6(lookup, address, callback) {
return lookup(address || "::1", 6, callback);
}
function newHandle(type, lookup) {
if (lookup === undefined) {
if (dns === undefined) {
dns = __hoisted_dns__;
}
lookup = dns.lookup;
} else {
validateFunction(lookup, "lookup");
}
if (type === "udp4") {
const handle = new UDP();
handle.lookup = Function.prototype.bind.call(lookup4, handle, lookup);
return handle;
}
if (type === "udp6") {
const handle = new UDP();
handle.lookup = Function.prototype.bind.call(lookup6, handle, lookup);
handle.bind = handle.bind6;
handle.connect = handle.connect6;
handle.send = handle.send6;
return handle;
}
throw new ERR_SOCKET_BAD_TYPE();
}
function _createSocketHandle(address, port, addressType, fd, flags) {
const handle = newHandle(addressType);
let err;
if (isInt32(fd) && fd > 0) {
const type = guessHandleType(fd);
if (type !== "UDP") {
err = UV_EINVAL;
} else {
err = handle.open(fd);
}
} else if (port || address) {
err = handle.bind(address, port || 0, flags);
}
if (err) {
handle.close();
return err;
}
return handle;
}
export { kStateSymbol };
export { _createSocketHandle };
export { newHandle };