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

@ -998,6 +998,13 @@ export interface NetscriptPort {
*/ */
tryWrite(value: string | number): boolean; 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. * Shift an element out of the port.
* @remarks * @remarks