bitburner-src/src/NetscriptPort.ts

80 lines
1.9 KiB
TypeScript
Raw Normal View History

2021-03-14 07:08:24 +01:00
import { Settings } from "./Settings/Settings";
type PortData = string | number;
type Resolver = () => void;
2021-09-24 23:56:30 +02:00
export interface IPort {
write: (value: unknown) => PortData | null;
2022-07-18 09:09:19 +02:00
tryWrite: (value: unknown) => boolean;
read: () => PortData;
peek: () => PortData;
nextWrite: () => Promise<void>;
2021-09-24 23:56:30 +02:00
full: () => boolean;
empty: () => boolean;
clear: () => void;
}
2021-09-22 02:39:25 +02:00
export function NetscriptPort(): IPort {
const data: PortData[] = [];
const resolvers: Resolver[] = [];
2021-09-22 02:39:25 +02:00
return {
write: (value) => {
if (typeof value !== "number" && typeof value !== "string") {
throw new Error(
`port.write: Tried to write type ${typeof value}. Only string and number types may be written to ports.`,
);
}
2021-09-22 02:39:25 +02:00
data.push(value);
while (resolvers.length > 0) {
(resolvers.pop() as Resolver)();
}
2021-09-22 02:39:25 +02:00
if (data.length > Settings.MaxPortCapacity) {
return data.shift() as PortData;
2021-09-22 02:39:25 +02:00
}
return null;
},
tryWrite: (value) => {
if (typeof value != "number" && typeof value != "string") {
throw new Error(
`port.write: Tried to write type ${typeof value}. Only string and number types may be written to ports.`,
);
}
2021-09-22 02:39:25 +02:00
if (data.length >= Settings.MaxPortCapacity) {
return false;
}
data.push(value);
while (resolvers.length > 0) {
(resolvers.pop() as Resolver)();
}
2021-09-22 02:39:25 +02:00
return true;
},
read: () => {
if (data.length === 0) return "NULL PORT DATA";
return data.shift() as PortData;
2021-09-22 02:39:25 +02:00
},
peek: () => {
if (data.length === 0) return "NULL PORT DATA";
return data[0];
2021-09-22 02:39:25 +02:00
},
nextWrite: () => {
return new Promise((res) => resolvers.push(res));
},
full: () => {
2021-09-22 02:39:25 +02:00
return data.length == Settings.MaxPortCapacity;
},
empty: () => {
2021-09-22 02:39:25 +02:00
return data.length === 0;
},
clear: () => {
2021-09-22 02:39:25 +02:00
data.length = 0;
},
};
2021-03-14 07:08:24 +01:00
}