import { BufReader, UnexpectedEOFError } from "../io/bufio.ts";import { charCode } from "../io/util.ts";
const asciiDecoder = new TextDecoder();function str(buf: Uint8Array | null | undefined): string { if (buf == null) { return ""; } else { return asciiDecoder.decode(buf); }}
export class ProtocolError extends Error { constructor(msg: string) { super(msg); this.name = "ProtocolError"; }}
export function append(a: Uint8Array, b: Uint8Array): Uint8Array { if (a == null) { return b; } else { const output = new Uint8Array(a.length + b.length); output.set(a, 0); output.set(b, a.length); return output; }}
export class TextProtoReader { constructor(readonly r: BufReader) {}
async readLine(): Promise<string | Deno.EOF> { const s = await this.readLineSlice(); if (s === Deno.EOF) return Deno.EOF; return str(s); }
async readMIMEHeader(): Promise<Headers | Deno.EOF> { const m = new Headers(); let line: Uint8Array | undefined;
let buf = await this.r.peek(1); if (buf === Deno.EOF) { return Deno.EOF; } else if (buf[0] == charCode(" ") || buf[0] == charCode("\t")) { line = (await this.readLineSlice()) as Uint8Array; }
buf = await this.r.peek(1); if (buf === Deno.EOF) { throw new UnexpectedEOFError(); } else if (buf[0] == charCode(" ") || buf[0] == charCode("\t")) { throw new ProtocolError( `malformed MIME header initial line: ${str(line)}` ); }
while (true) { const kv = await this.readLineSlice(); if (kv === Deno.EOF) throw new UnexpectedEOFError(); if (kv.byteLength === 0) return m;
let i = kv.indexOf(charCode(":")); if (i < 0) { throw new ProtocolError(`malformed MIME header line: ${str(kv)}`); } let endKey = i; while (endKey > 0 && kv[endKey - 1] == charCode(" ")) { endKey--; }
const key = str(kv.subarray(0, endKey));
if (key == "") { continue; }
i++; while ( i < kv.byteLength && (kv[i] == charCode(" ") || kv[i] == charCode("\t")) ) { i++; } const value = str(kv.subarray(i));
try { m.append(key, value); } catch {} } }
async readLineSlice(): Promise<Uint8Array | Deno.EOF> { let line: Uint8Array | undefined; while (true) { const r = await this.r.readLine(); if (r === Deno.EOF) return Deno.EOF; const { line: l, more } = r;
if (!line && !more) { if (this.skipSpace(l) === 0) { return new Uint8Array(0); } return l; }
line = append(line, l); if (!more) { break; } } return line; }
skipSpace(l: Uint8Array): number { let n = 0; for (let i = 0; i < l.length; i++) { if (l[i] === charCode(" ") || l[i] === charCode("\t")) { continue; } n++; } return n; }}