| 1046 | const COPY_LIMIT = 16 * 1024 |
| 1047 | |
| 1048 | class Writer { |
| 1049 | private chunks: Array<Uint8Array> = [] |
| 1050 | buffered = 0 |
| 1051 | private offset = 0 |
| 1052 | private readonly records: Array<EntryRecord> = [] |
| 1053 | private current: Streaming | undefined |
| 1054 | |
| 1055 | // Hands out the buffered output, joining runs of small chunks; needs `buffered > 0` |
| 1056 | flush(): Arr.NonEmptyArray<Uint8Array> { |
| 1057 | const out: Array<Uint8Array> = [] |
| 1058 | let run: Array<Uint8Array> = [] |
| 1059 | let runLength = 0 |
| 1060 | const join = () => { |
| 1061 | if (run.length === 1) { |
| 1062 | out.push(run[0]) |
| 1063 | } else if (run.length > 1) { |
| 1064 | const joined = new Uint8Array(runLength) |
| 1065 | let at = 0 |
| 1066 | for (const chunk of run) { |
| 1067 | joined.set(chunk, at) |
| 1068 | at += chunk.length |
| 1069 | } |
| 1070 | out.push(joined) |
| 1071 | } |
| 1072 | run = [] |
| 1073 | runLength = 0 |
| 1074 | } |
| 1075 | for (const chunk of this.chunks) { |
| 1076 | if (chunk.length >= COPY_LIMIT) { |
| 1077 | join() |
| 1078 | out.push(chunk) |
| 1079 | } else { |
| 1080 | run.push(chunk) |
| 1081 | runLength += chunk.length |
| 1082 | } |
| 1083 | } |
| 1084 | join() |
| 1085 | this.chunks = [] |
| 1086 | this.buffered = 0 |
| 1087 | return out as Arr.NonEmptyArray<Uint8Array> |
| 1088 | } |
| 1089 | |
| 1090 | private push(bytes: Uint8Array): void { |
| 1091 | if (bytes.length === 0) return |
| 1092 | this.chunks.push(bytes) |
| 1093 | this.offset += bytes.length |
| 1094 | this.buffered += bytes.length |
| 1095 | } |
| 1096 | |
| 1097 | private record(header: Header, flags: number): EntryRecord { |
| 1098 | const name = textEncoder.encode(header.path) |
| 1099 | if (name.length > MAX16) throw invalidHeader(`path ${JSON.stringify(header.path)} is longer than 65535 bytes`) |
| 1100 | const { date, time } = toDos(header.mtime) |
| 1101 | const seconds = Math.floor(header.mtime.getTime() / 1000) |
| 1102 | const directory = header.type === "Directory" |
| 1103 | const mode = header.mode ?? (directory ? 0o755 : 0o644) |
| 1104 | return { |
| 1105 | name, |