Skip to content

Commit

Permalink
fix: while loop stealing cycles
Browse files Browse the repository at this point in the history
  • Loading branch information
Joe Harlow committed Jan 14, 2020
1 parent 8b36893 commit aa761bc
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/json.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import * as std from 'std';
import { put } from './csp.js';
import { setTimeout } from 'os';
import { put, take } from './csp.js';

const timeout = ms =>
new Promise(res => setTimeout(res, ms));

const [
LEFT_PAREN, LEFT_BRACK,
Expand All @@ -19,7 +23,7 @@ const WHITESPACE = [
0x202f, 0x205f, 0x2060, 0x3000, 0xfeff,
];

export async function readJSON(file, out) {
export async function readJSON(file, json) {
let byte, depth = 0, object = false, string = false, buffer = [];

while (byte = file.getByte(), byte !== -1) {
Expand All @@ -41,16 +45,17 @@ export async function readJSON(file, out) {
if (!WHITESPACE.includes(byte)) buffer.push(byte);
if ((object || buffer.length && byte === WHITESPACE[1]) && depth === 0) {
const output = buffer.map(c => String.fromCharCode(c)).join('');
await put(out, output);
await put(json, output);
object = false;
buffer = [];
await timeout(0);
}
} else buffer.push(byte);
}

if (buffer.length) {
const output = buffer.map(c => String.fromCharCode(c)).join('');
await put(out, output);
await put(json, output);
}
};

0 comments on commit aa761bc

Please sign in to comment.