bitburner-src/src/Netscript/Pid.ts

41 lines
875 B
TypeScript
Raw Normal View History

import { workerScripts } from "./WorkerScripts";
let pidCounter = 1;
2022-10-09 07:25:31 +02:00
/** Find and return the next available PID for a script */
export function generateNextPid(): number {
2021-09-05 01:09:30 +02:00
let tempCounter = pidCounter;
2021-09-05 01:09:30 +02:00
// Cap the number of search iterations at some arbitrary value to avoid
// infinite loops. We'll assume that players wont have 1mil+ running scripts
let found = false;
for (let i = 0; i < 1e6; ) {
if (!workerScripts.has(tempCounter + i)) {
found = true;
tempCounter = tempCounter + i;
break;
}
2021-09-05 01:09:30 +02:00
if (i === Number.MAX_SAFE_INTEGER - 1) {
i = 1;
} else {
2021-09-05 01:09:30 +02:00
++i;
}
}
if (found) {
pidCounter = tempCounter + 1;
if (pidCounter >= Number.MAX_SAFE_INTEGER) {
pidCounter = 1;
}
2021-09-05 01:09:30 +02:00
return tempCounter;
} else {
return -1;
}
}
export function resetPidCounter(): void {
2021-09-05 01:09:30 +02:00
pidCounter = 1;
}