protohackers/main.ts

51 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-09-26 20:57:53 -05:00
import { copy } from "https://deno.land/std@0.157.0/streams/conversion.ts?s=copy";
import { Buffer } from "https://deno.land/std@0.157.0/io/buffer.ts";
2022-09-23 14:39:50 -05:00
import { ByteSet } from "https://deno.land/x/bytes@1.0.3/mod.ts";
2022-09-23 13:33:17 -05:00
2022-09-26 20:57:53 -05:00
const QUERY_SIZE = 9;
const PORT = 5588;
2022-09-23 13:33:17 -05:00
2022-09-26 20:57:53 -05:00
const listener = Deno.listen({ port: 5588 });
console.log(`Listening on 0.0.0.0:${PORT}`);
2022-09-23 13:33:17 -05:00
for await (const conn of listener) {
2022-09-26 20:57:53 -05:00
console.log("Connection established:", conn.remoteAddr);
2022-09-23 14:37:43 -05:00
try {
2022-09-26 20:57:53 -05:00
meansToAnEnd(conn);
2022-09-23 14:37:43 -05:00
} catch (e) {
2022-09-26 20:57:53 -05:00
console.error(conn.remoteAddr, e);
2022-09-23 14:37:43 -05:00
}
2022-09-26 20:57:53 -05:00
console.log("Connection closed:", conn.remoteAddr);
2022-09-23 13:33:17 -05:00
}
2022-09-23 14:37:43 -05:00
// problem 2
2022-09-26 20:57:53 -05:00
async function meansToAnEnd(conn: Deno.Conn) {
2022-09-23 14:37:43 -05:00
try {
2022-09-26 20:57:53 -05:00
for await (const query of queries(conn)) {
console.log("Query:", query);
conn.write(ByteSet.from(Uint8Array.from([0]), "big").buffer);
2022-09-23 14:37:43 -05:00
}
2022-09-26 20:57:53 -05:00
console.log("Done!");
} catch (err) {
console.error(err);
2022-09-23 14:37:43 -05:00
}
}
2022-09-26 20:57:53 -05:00
function queries(conn: Deno.Conn) {
2022-09-23 14:37:43 -05:00
return {
async *[Symbol.asyncIterator]() {
2022-09-26 20:57:53 -05:00
const b = new Uint8Array(1024);
const q = new Uint8Array();
let bytesRead = 0;
console.debug(b.length);
while (bytesRead < QUERY_SIZE) {
const n = await conn.read(b);
bytesRead += n;
console.debug(n, b.length);
2022-09-23 14:37:43 -05:00
}
2022-09-26 20:57:53 -05:00
yield q;
},
};
2022-09-23 14:37:43 -05:00
}