NETSCRIPT: added portHandle.nextWrite() (#187)

This commit is contained in:
LJ 2022-11-03 03:17:29 -07:00 committed by GitHub
parent 3ce4dcf612
commit 9eb5f7ef23
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 0 deletions

@ -1,11 +1,13 @@
import { Settings } from "./Settings/Settings";
type PortData = string | number;
type Resolver = () => void;
export interface IPort {
write: (value: unknown) => PortData | null;
tryWrite: (value: unknown) => boolean;
read: () => PortData;
peek: () => PortData;
nextWrite: () => Promise<void>;
full: () => boolean;
empty: () => boolean;
clear: () => void;
@ -13,6 +15,7 @@ export interface IPort {
export function NetscriptPort(): IPort {
const data: PortData[] = [];
const resolvers: Resolver[] = [];
return {
write: (value) => {
@ -22,6 +25,9 @@ export function NetscriptPort(): IPort {
);
}
data.push(value);
while (resolvers.length > 0) {
(resolvers.pop() as Resolver)();
}
if (data.length > Settings.MaxPortCapacity) {
return data.shift() as PortData;
}
@ -38,6 +44,9 @@ export function NetscriptPort(): IPort {
return false;
}
data.push(value);
while (resolvers.length > 0) {
(resolvers.pop() as Resolver)();
}
return true;
},
@ -51,6 +60,10 @@ export function NetscriptPort(): IPort {
return data[0];
},
nextWrite: () => {
return new Promise((res) => resolvers.push(res));
},
full: () => {
return data.length == Settings.MaxPortCapacity;
},

@ -998,6 +998,13 @@ export interface NetscriptPort {
*/
tryWrite(value: string | number): boolean;
/**
* Sleeps until the port is written to.
* @remarks
* RAM cost: 0 GB
*/
nextWrite(): Promise<void>;
/**
* Shift an element out of the port.
* @remarks