@amritk/nish-x86_64-linux 0.34.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -81,7 +81,25 @@
81
81
  * Written from RFC 9112 and RFC 9110, not ported from another implementation.
82
82
  */
83
83
  import { copyBytes } from "nish/bytes"
84
- import { extract, loadU8x16, u8x16 } from "nish:simd"
84
+ import {
85
+ and,
86
+ any,
87
+ bitmask,
88
+ eq,
89
+ extract,
90
+ gt,
91
+ loadU8x16,
92
+ lt,
93
+ mask8x16,
94
+ ne,
95
+ or,
96
+ replace,
97
+ select,
98
+ splatU8x16,
99
+ store,
100
+ subWrapping,
101
+ u8x16,
102
+ } from "nish:simd"
85
103
 
86
104
  /** `next()`: the input so far holds no further event; feed more. */
87
105
  export const HTTP1_NEED_MORE: i32 = 0
@@ -147,21 +165,16 @@ class Http1ListTally {
147
165
  * on a kept-alive connection follow one another through the same parser.
148
166
  */
149
167
  export class Http1Parser {
150
- // The fields are declared widest first, references before numbers before
151
- // flags, so the struct carries no padding; the groups say what each is.
152
-
153
- // --- the request: valid from its `HTTP1_HEAD` until the `next()` after its `HTTP1_END`
154
- method: string = ""
155
- target: string = ""
156
- /** The field names, in lowercase, in the order they arrived; `values` beside them. */
157
- names: string[]
158
- values: string[]
159
- /** The `Upgrade` field when `Connection` asked for it, else empty. */
160
- upgrade: string = ""
161
- /** The buffer the last `HTTP1_BODY`'s bytes are in, at `bodyOff`, `bodyLen` long. */
162
- body: u8[]
163
- /** What was wrong, once `next()` said `HTTP1_ERROR`; for a log, not for the response. */
164
- reason: string = ""
168
+ // The fields a request reads come first, so that a kept-alive connection
169
+ // whose parser has gone cold between requests brings back two or three
170
+ // cache lines of it, not all four: the buffers, then the offsets `feed`,
171
+ // `buffered`, `http1TakeLine` and the head's lines move, then the flags,
172
+ // then the rest of the request's numbers and the caller's limits. What only
173
+ // `keepText`, an error or a chunked body reads follows. Each group packs as
174
+ // widest first does, and the flags' two bytes of padding are the only ones:
175
+ // the struct is the 200 bytes its fields sum to, rounded to 8.
176
+
177
+ // --- the request's buffers -------------------------------------------------
165
178
  /** The bytes fed and not yet consumed are `buf[start .. end)`. */
166
179
  buf: u8[]
167
180
  /**
@@ -173,52 +186,22 @@ export class Http1Parser {
173
186
  head: u8[]
174
187
  /** Four entries per field, into `head`: name start and end, value start and end (OWS trimmed). */
175
188
  spans: i32[]
176
- /** Reused by every list `http1Tally` walks. */
177
- tally: Http1ListTally
178
-
179
- // --- limits, the caller's --------------------------------------------------
180
- maxTarget: i32 = 0
181
- maxHeaderBytes: i32 = 0
182
- maxHeaders: i32 = 0
183
- maxBody: i32 = 0
184
- /** The most body bytes one `HTTP1_BODY` hands over; a caller's number, 2^30 unless set. */
185
- maxChunk: i32 = 1073741824
186
-
187
- /** The minor version: 0 for HTTP/1.0, 1 for HTTP/1.1 and anything above it. */
188
- minor: i32 = 1
189
- /** The declared body length, or -1 when the request has none or is chunked. */
190
- contentLength: i32 = -1
191
- bodyOff: i32 = 0
192
- bodyLen: i32 = 0
193
- /** The status code to answer once `next()` said `HTTP1_ERROR`. */
194
- status: i32 = 0
195
- /** The method is `head[methodStart .. methodEnd)` and the target `head[targetStart .. targetEnd)`. */
196
- methodStart: i32 = 0
197
- methodEnd: i32 = 0
198
- targetStart: i32 = 0
199
- targetEnd: i32 = 0
200
- /** How many fields the request's header section kept: the spans of field `i` are `spans[4 * i ..]`. */
201
- headerCount: i32 = 0
202
- /** How much of `head` the request uses. */
203
- headLength: i32 = 0
189
+ /** The buffer the last `HTTP1_BODY`'s bytes are in, at `bodyOff`, `bodyLen` long. */
190
+ body: u8[]
204
191
 
205
- // --- internal --------------------------------------------------------------
192
+ // --- where the parser is ----------------------------------------------------
206
193
  start: i32 = 0
207
194
  end: i32 = 0
208
195
  /** Where the search for the next LF resumes, so a line fed a byte at a time is scanned once. */
209
196
  scan: i32 = 0
210
197
  state: i32 = 0
211
- /** Bytes left in a length-delimited body or in the current chunk. */
212
- left: i32 = 0
213
- /** De-chunked body bytes so far, against `maxBody`. */
214
- bodyTotal: i32 = 0
215
- /** Bytes of the header or trailer section so far, against `maxHeaderBytes`. */
216
- sectionBytes: i32 = 0
217
- /** Field lines of the request so far, its trailers included, against `maxHeaders`. */
218
- fieldCount: i32 = 0
219
198
  /** The line `http1TakeLine` found is `buf[lineStart .. lineEnd)`, its CRLF dropped. */
220
199
  lineStart: i32 = 0
221
200
  lineEnd: i32 = 0
201
+ /** How many fields the request's header section kept: the spans of field `i` are `spans[4 * i ..]`. */
202
+ headerCount: i32 = 0
203
+ /** How much of `head` the request uses. */
204
+ headLength: i32 = 0
222
205
  /**
223
206
  * Whether the line being scanned holds a byte a field value may not: a
224
207
  * control byte other than HTAB, or DEL (RFC 9110 §5.5). `http1TakeLine`
@@ -242,6 +225,50 @@ export class Http1Parser {
242
225
  */
243
226
  keepText: boolean = true
244
227
 
228
+ // --- the request's numbers: valid from its `HTTP1_HEAD` until the `next()` after its `HTTP1_END`
229
+ /** Bytes of the header or trailer section so far, against `maxHeaderBytes`. */
230
+ sectionBytes: i32 = 0
231
+ /** Field lines of the request so far, its trailers included, against `maxHeaders`. */
232
+ fieldCount: i32 = 0
233
+ /** The minor version: 0 for HTTP/1.0, 1 for HTTP/1.1 and anything above it. */
234
+ minor: i32 = 1
235
+ /** Bytes left in a length-delimited body or in the current chunk. */
236
+ left: i32 = 0
237
+ /** The declared body length, or -1 when the request has none or is chunked. */
238
+ contentLength: i32 = -1
239
+ bodyOff: i32 = 0
240
+ bodyLen: i32 = 0
241
+ /** The method is `head[methodStart .. methodEnd)` and the target `head[targetStart .. targetEnd)`. */
242
+ methodStart: i32 = 0
243
+ methodEnd: i32 = 0
244
+ targetStart: i32 = 0
245
+ targetEnd: i32 = 0
246
+
247
+ // --- limits, the caller's --------------------------------------------------
248
+ maxTarget: i32 = 0
249
+ maxHeaderBytes: i32 = 0
250
+ maxHeaders: i32 = 0
251
+ maxBody: i32 = 0
252
+ /** The most body bytes one `HTTP1_BODY` hands over; a caller's number, 2^30 unless set. */
253
+ maxChunk: i32 = 1073741824
254
+
255
+ // --- what `keepText`, an error or a chunked body reads ----------------------
256
+ method: string = ""
257
+ target: string = ""
258
+ /** The field names, in lowercase, in the order they arrived; `values` beside them. */
259
+ names: string[]
260
+ values: string[]
261
+ /** The `Upgrade` field when `Connection` asked for it, else empty. */
262
+ upgrade: string = ""
263
+ /** What was wrong, once `next()` said `HTTP1_ERROR`; for a log, not for the response. */
264
+ reason: string = ""
265
+ /** Reused by every list `http1Tally` walks. */
266
+ tally: Http1ListTally
267
+ /** The status code to answer once `next()` said `HTTP1_ERROR`. */
268
+ status: i32 = 0
269
+ /** De-chunked body bytes so far, against `maxBody`. */
270
+ bodyTotal: i32 = 0
271
+
245
272
  /**
246
273
  * Each limit is clamped into 0 to 2^30, so that the sums the parser makes
247
274
  * of them (a request line is the method, the target and ten bytes more)
@@ -256,12 +283,15 @@ export class Http1Parser {
256
283
  // head kept, at HTTP1_FIRST_INPUT and HTTP1_FIRST_HEAD bytes: a parser
257
284
  // that is built and never fed (a pool's spare slot) costs neither, and a
258
285
  // caller that lends them out between requests puts empty ones here.
286
+ // The spans are made first: the arena places each block after the last,
287
+ // so their header and first entries sit just behind the parser's fields
288
+ // rather than behind four empty arrays.
289
+ this.spans = new Array<i32>(64)
259
290
  this.buf = []
260
291
  this.body = this.buf
292
+ this.head = []
261
293
  this.names = []
262
294
  this.values = []
263
- this.head = []
264
- this.spans = new Array<i32>(64)
265
295
  this.tally = new Http1ListTally()
266
296
  this.restart()
267
297
  }
@@ -669,8 +699,9 @@ const http1TakeLine = (p: Http1Parser, limit: i32, overStatus: i32): i32 => {
669
699
  * third (0x57ffffff). No byte below 33 or above 126 is a tchar.
670
700
  * `http1IsTokenByte` reads them as two 64-bit masks, one for the bytes 0 to
671
701
  * 63 and one for 64 to 127, so the test is a select and a shift with no
672
- * branch on the byte: a name or method scan is the parser's hottest loop
673
- * after the line scan (`bench/http1-parse`).
702
+ * branch on the byte. A field name goes sixteen bytes at a time through
703
+ * `http1NonTokenLanes`, the same set; this test is for the method, a trailer's
704
+ * name, and a name's last bytes when fewer than sixteen are left in the head.
674
705
  */
675
706
  const HTTP1_TCHAR_32: i32 = 67071226
676
707
  const HTTP1_TCHAR_64: i32 = -939524098
@@ -684,6 +715,66 @@ export const http1IsTokenByte = (c: i32): boolean => {
684
715
  return c >= 0 && c < 128 && ((word >> toU64(c & 63)) & toU64(1)) !== toU64(0)
685
716
  }
686
717
 
718
+ /**
719
+ * Which lanes of `v` are not tchars, as `http1IsTokenByte` answers for each,
720
+ * bit `k` for lane `k`: a byte outside 33 to 126, or one of the seventeen
721
+ * delimiters among them, `"` `(` `)` `,` `/` `:` to `@` (seven), `[` `\` `]`
722
+ * `{` and `}`. A name is mostly one vector, so these compares run once for
723
+ * the sixteen bytes where the table test ran once for each.
724
+ */
725
+ const http1NonTokenLanes = (v: u8x16): i32 => {
726
+ const outside: mask8x16 = gt(subWrapping(v, splatU8x16(33)), splatU8x16(93))
727
+ const quote: mask8x16 = or(eq(v, splatU8x16(34)), lt(subWrapping(v, splatU8x16(40)), splatU8x16(2)))
728
+ const comma: mask8x16 = or(eq(v, splatU8x16(44)), eq(v, splatU8x16(47)))
729
+ const colon: mask8x16 = lt(subWrapping(v, splatU8x16(58)), splatU8x16(7))
730
+ const bracket: mask8x16 = lt(subWrapping(v, splatU8x16(91)), splatU8x16(3))
731
+ const brace: mask8x16 = or(eq(v, splatU8x16(123)), eq(v, splatU8x16(125)))
732
+ return bitmask(or(or(or(outside, quote), or(comma, colon)), or(bracket, brace)))
733
+ }
734
+
735
+ /**
736
+ * Lowercases a field name in `head` from `k`, sixteen bytes at a time, and
737
+ * answers where it ends: the first byte before `stop` that is not a tchar, or
738
+ * `stop`. Each vector's name lanes are lowered, and every other lane is
739
+ * stored back as it was, so the value after the name and the bytes past the
740
+ * line keep their case. A tail of under sixteen bytes before `head`'s end
741
+ * goes a byte at a time. The answer and the bytes written are the byte loop's.
742
+ */
743
+ const http1LowerName = (head: u8[], k0: i32, stop: i32): i32 => {
744
+ // Lane `j` holds `j`: the name's lanes are those below its length.
745
+ const lanes: u8x16 = u8x16(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
746
+ let k: i32 = k0
747
+ while (k >= 0 && k < stop && k <= toI32(head.length) - 16) {
748
+ const v: u8x16 = loadU8x16(head, k)
749
+ const bad: i32 = http1NonTokenLanes(v)
750
+ let run: i32 = 16
751
+ if (bad !== 0) {
752
+ run = toI32(31) - toI32(Math.clz32(toU32(bad & -bad)))
753
+ }
754
+ if (run > stop - k) {
755
+ run = stop - k
756
+ }
757
+ const upper: mask8x16 = and(
758
+ lt(subWrapping(v, splatU8x16(65)), splatU8x16(26)),
759
+ lt(lanes, splatU8x16(toU8(run)))
760
+ )
761
+ store(select(upper, or(v, splatU8x16(32)), v), head, k)
762
+ k += run
763
+ if (run < 16) {
764
+ return k
765
+ }
766
+ }
767
+ while (k >= 0 && k < stop && k < toI32(head.length)) {
768
+ const c: i32 = toI32(head[k])
769
+ if (!http1IsTokenByte(c)) {
770
+ break
771
+ }
772
+ head[k] = toU8(c >= 65 && c <= 90 ? c + 32 : c)
773
+ k += 1
774
+ }
775
+ return k
776
+ }
777
+
687
778
  /** Whether `c` may appear in a field value (RFC 9110 §5.5): HTAB, SP, VCHAR or obs-text. */
688
779
  export const http1IsValueByte = (c: i32): boolean => c === 9 || (c >= 32 && c !== 127)
689
780
 
@@ -1012,18 +1103,7 @@ const http1FieldLine = (p: Http1Parser, keep: boolean): i32 => {
1012
1103
  let i: i32 = a
1013
1104
  if (keep) {
1014
1105
  at = http1HeadAppend(p, a, b)
1015
- const head: u8[] = p.head
1016
- let k: i32 = at
1017
- const stop: i32 = at + (b - a)
1018
- while (k >= 0 && k < stop && k < toI32(head.length)) {
1019
- const c: i32 = toI32(head[k])
1020
- if (!http1IsTokenByte(c)) {
1021
- break
1022
- }
1023
- head[k] = toU8(c >= 65 && c <= 90 ? c + 32 : c)
1024
- k += 1
1025
- }
1026
- i = a + (k - at)
1106
+ i = a + (http1LowerName(p.head, at, at + (b - a)) - at)
1027
1107
  } else {
1028
1108
  while (i >= 0 && i < b && i < toI32(buf.length) && http1IsTokenByte(toI32(buf[i]))) {
1029
1109
  i += 1
@@ -1046,7 +1126,12 @@ const http1FieldLine = (p: Http1Parser, keep: boolean): i32 => {
1046
1126
  if (keep) {
1047
1127
  let valueStart: i32 = nameEnd + 1
1048
1128
  let valueEnd: i32 = b
1049
- while (valueStart >= 0 && valueStart < valueEnd && valueStart < n && http1IsOws(toI32(buf[valueStart]))) {
1129
+ while (
1130
+ valueStart >= 0 &&
1131
+ valueStart < valueEnd &&
1132
+ valueStart < toI32(buf.length) &&
1133
+ http1IsOws(toI32(buf[valueStart]))
1134
+ ) {
1050
1135
  valueStart += 1
1051
1136
  }
1052
1137
  while (valueEnd > valueStart && valueEnd - 1 >= 0 && http1IsOws(toI32(buf[valueEnd - 1]))) {
@@ -1512,7 +1597,7 @@ const http1HexDigits = (len: i32): i32 => {
1512
1597
  * with `out` untouched. An empty window writes nothing and answers `at`,
1513
1598
  * because a chunk of size zero ends the body. A window outside `data` panics.
1514
1599
  */
1515
- export const http1WriteChunk = (out: u8[], at: i32, data: u8[], off: i32, len: i32): i32 => {
1600
+ export const http1WriteChunk = (out: u8[], at: i32, data: readonly u8[], off: i32, len: i32): i32 => {
1516
1601
  const size: i32 = toI32(data.length)
1517
1602
  if (off < 0 || len < 0 || off > size || len > size - off) {
1518
1603
  panic("http1WriteChunk: the window is outside the buffer")
@@ -1591,14 +1676,39 @@ const http1BytesAreToken = (bytes: u8[]): boolean => {
1591
1676
  return toI32(bytes.length) > 0
1592
1677
  }
1593
1678
 
1594
- /** Whether every byte of `bytes` may stand in a field value. */
1679
+ /**
1680
+ * Whether no lane of `v` is a byte a field value may not hold: below 32 and
1681
+ * not HTAB, or DEL. `http1IsValueByte` on sixteen bytes at once, exactly, so
1682
+ * a vector may overlap one already checked.
1683
+ */
1684
+ const http1LanesAreFieldText = (v: u8x16): boolean => {
1685
+ const control: mask8x16 = and(lt(v, splatU8x16(32)), ne(v, splatU8x16(9)))
1686
+ return !any(or(control, eq(v, splatU8x16(127))))
1687
+ }
1688
+
1689
+ /**
1690
+ * Whether every byte of `bytes` may stand in a field value: sixteen at a
1691
+ * time, the last vector ending at the last byte and overlapping the one
1692
+ * before it, and one at a time below sixteen.
1693
+ */
1595
1694
  const http1BytesAreFieldText = (bytes: u8[]): boolean => {
1596
- for (const b of bytes) {
1597
- if (!http1IsValueByte(toI32(b))) {
1695
+ const n: i32 = toI32(bytes.length)
1696
+ if (n < 16) {
1697
+ for (let k: i32 = 0; k < n; k += 1) {
1698
+ if (!http1IsValueByte(toI32(bytes[k]))) {
1699
+ return false
1700
+ }
1701
+ }
1702
+ return true
1703
+ }
1704
+ let k: i32 = 0
1705
+ while (k >= 0 && k <= n - 16) {
1706
+ if (!http1LanesAreFieldText(loadU8x16(bytes, k))) {
1598
1707
  return false
1599
1708
  }
1709
+ k += 16
1600
1710
  }
1601
- return true
1711
+ return k === n || http1LanesAreFieldText(loadU8x16(bytes, n - 16))
1602
1712
  }
1603
1713
 
1604
1714
  /** Whether the octets of `bytes` spell `word`, which is lowercase, in any ASCII case: a field name compared as RFC 9110 §5.1 says. */
@@ -1628,6 +1738,14 @@ const http1DecimalDigits = (n: i32): i32 => {
1628
1738
  /** Writes `text` at `out[at ..)`, which the caller has made sure holds it, and answers where it ends. */
1629
1739
  export const http1PutText = (out: u8[], at: i32, text: string): i32 => {
1630
1740
  const n: i32 = toI32(text.length)
1741
+ if (at >= 0 && at <= toI32(out.length) - n) {
1742
+ // It fits, the case every caller makes sure of: one test, then a loop
1743
+ // with no bounds check in it.
1744
+ for (let k: i32 = 0; k < n; k += 1) {
1745
+ out[at + k] = toU8(text.charCodeAt(k))
1746
+ }
1747
+ return at + n
1748
+ }
1631
1749
  for (let k: i32 = 0; k < n && at + k < toI32(out.length); k += 1) {
1632
1750
  if (at + k >= 0) {
1633
1751
  out[at + k] = toU8(text.charCodeAt(k))
@@ -1669,6 +1787,50 @@ const http1PutBytes = (out: u8[], at: i32, bytes: u8[]): i32 => {
1669
1787
  return at + n
1670
1788
  }
1671
1789
 
1790
+ /**
1791
+ * Writes `text`, at most sixteen ASCII bytes, at `out[at ..)`, likewise, as
1792
+ * one sixteen-byte store of `v`, which holds `text` in its first lanes: when
1793
+ * `at + 16` does not pass `limit`, the end of the head being written, whose
1794
+ * every byte from `at` on is written after this one, so the lanes past
1795
+ * `text` are overwritten before the head is done. Byte by byte otherwise.
1796
+ */
1797
+ const http1PutFixed = (out: u8[], at: i32, limit: i32, v: u8x16, text: string): i32 => {
1798
+ if (at >= 0 && at <= limit - 16 && limit <= toI32(out.length)) {
1799
+ store(v, out, at)
1800
+ return at + toI32(text.length)
1801
+ }
1802
+ return http1PutText(out, at, text)
1803
+ }
1804
+
1805
+ /**
1806
+ * Writes `HTTP/1.1 `, the three digits of `status`, which is 100 to 599, and
1807
+ * a space at `out[at ..)`, likewise: one store, the digits replacing three
1808
+ * lanes of the constant.
1809
+ */
1810
+ const http1PutStatusLine = (out: u8[], at: i32, limit: i32, status: i32): i32 => {
1811
+ const hundreds: i32 = status / 100
1812
+ const tens: i32 = (status / 10) % 10
1813
+ const ones: i32 = status % 10
1814
+ if (at >= 0 && at <= limit - 16 && limit <= toI32(out.length)) {
1815
+ // "HTTP/1.1 000 ", and three lanes the head's next bytes overwrite.
1816
+ const line: u8x16 = u8x16(72, 84, 84, 80, 47, 49, 46, 49, 32, 48, 48, 48, 32, 32, 32, 32)
1817
+ store(
1818
+ replace(replace(replace(line, 9, toU8(48 + hundreds)), 10, toU8(48 + tens)), 11, toU8(48 + ones)),
1819
+ out,
1820
+ at
1821
+ )
1822
+ return at + 13
1823
+ }
1824
+ const end: i32 = http1PutText(out, at, "HTTP/1.1 ")
1825
+ if (end >= 0 && end < toI32(out.length) - 3) {
1826
+ out[end] = toU8(48 + hundreds)
1827
+ out[end + 1] = toU8(48 + tens)
1828
+ out[end + 2] = toU8(48 + ones)
1829
+ out[end + 3] = 32
1830
+ }
1831
+ return end + 4
1832
+ }
1833
+
1672
1834
  /** Writes the decimal digits of `n`, which is not negative, at `out[at ..)`, likewise. */
1673
1835
  const http1PutDecimal = (out: u8[], at: i32, n: i32): i32 => {
1674
1836
  const digits: i32 = http1DecimalDigits(n)
@@ -1725,7 +1887,7 @@ export const http1WriteResponseHead = (
1725
1887
  // is written, in 64 bits so that no caller's lengths can wrap the sum.
1726
1888
  let need: i64 = toI64(17) + toI64(reason.length)
1727
1889
  let sendDate: boolean = status >= 200 && toI32(date.length) > 0
1728
- for (let i: i32 = 0; i < count && i < toI32(values.length); i += 1) {
1890
+ for (let i: i32 = 0; i < toI32(names.length) && i < toI32(values.length); i += 1) {
1729
1891
  const name: u8[] = names[i]
1730
1892
  const value: u8[] = values[i]
1731
1893
  if (!http1BytesAreToken(name) || !http1BytesAreFieldText(value)) {
@@ -1757,41 +1919,49 @@ export const http1WriteResponseHead = (
1757
1919
  if (at < 0 || at > toI32(out.length) || need > toI64(toI32(out.length) - at)) {
1758
1920
  return HTTP1_NO_ROOM
1759
1921
  }
1760
- let end: i32 = http1PutText(out, at, "HTTP/1.1 ")
1761
1922
  // A status is three digits, checked above: no division loop for them.
1762
- if (end >= 0 && end < toI32(out.length) - 3) {
1763
- const hundreds: i32 = status / 100
1764
- const tens: i32 = status / 10
1765
- const tensDigit: i32 = tens % 10
1766
- const ones: i32 = status % 10
1767
- out[end] = toU8(48 + hundreds)
1768
- out[end + 1] = toU8(48 + tensDigit)
1769
- out[end + 2] = toU8(48 + ones)
1770
- out[end + 3] = 32
1771
- }
1772
- end = end + 4
1923
+ const limit: i32 = at + toI32(need)
1924
+ let end: i32 = http1PutStatusLine(out, at, limit, status)
1773
1925
  end = http1PutText(out, end, reason)
1774
1926
  end = http1PutCrlf(out, end)
1775
- for (let i: i32 = 0; i < count && i < toI32(values.length); i += 1) {
1927
+ for (let i: i32 = 0; i < toI32(names.length) && i < toI32(values.length); i += 1) {
1776
1928
  end = http1PutBytes(out, end, names[i])
1777
1929
  end = http1PutColonSpace(out, end)
1778
1930
  end = http1PutBytes(out, end, values[i])
1779
1931
  end = http1PutCrlf(out, end)
1780
1932
  }
1781
1933
  if (sendDate) {
1782
- end = http1PutText(out, end, "Date: ")
1934
+ end = http1PutFixed(
1935
+ out,
1936
+ end,
1937
+ limit,
1938
+ u8x16(68, 97, 116, 101, 58, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32),
1939
+ "Date: "
1940
+ )
1783
1941
  end = http1PutBytes(out, end, date)
1784
1942
  end = http1PutCrlf(out, end)
1785
1943
  }
1786
1944
  if (bodyLength >= 0) {
1787
- end = http1PutText(out, end, "Content-Length: ")
1945
+ end = http1PutFixed(
1946
+ out,
1947
+ end,
1948
+ limit,
1949
+ u8x16(67, 111, 110, 116, 101, 110, 116, 45, 76, 101, 110, 103, 116, 104, 58, 32),
1950
+ "Content-Length: "
1951
+ )
1788
1952
  end = http1PutDecimal(out, end, bodyLength)
1789
1953
  end = http1PutCrlf(out, end)
1790
1954
  } else if (bodyLength === HTTP1_CHUNKED) {
1791
1955
  end = http1PutText(out, end, "Transfer-Encoding: chunked\r\n")
1792
1956
  }
1793
1957
  if (toI32(connection.length) > 0) {
1794
- end = http1PutText(out, end, "Connection: ")
1958
+ end = http1PutFixed(
1959
+ out,
1960
+ end,
1961
+ limit,
1962
+ u8x16(67, 111, 110, 110, 101, 99, 116, 105, 111, 110, 58, 32, 32, 32, 32, 32),
1963
+ "Connection: "
1964
+ )
1795
1965
  end = http1PutText(out, end, connection)
1796
1966
  end = http1PutCrlf(out, end)
1797
1967
  }
@@ -51,7 +51,9 @@
51
51
  * connection answers `H1_NEED_MORE` until the socket has drained half the
52
52
  * output, then `H1_WRITE`. Until then it reads nothing, so the window the
53
53
  * program is writing from stays valid: back-pressure on the way out. Nothing
54
- * buffers a whole body.
54
+ * buffers a whole body. On an `Http1Server` slot `sendBody` sends a body with
55
+ * a length from the program's own array, the queued output with it, and
56
+ * copies only what the socket did not take, under the same rules.
55
57
  *
56
58
  * **What the server decides.** The framing field (`Content-Length` or
57
59
  * `Transfer-Encoding: chunked`) and the `Connection` field are the server's;
@@ -127,7 +129,7 @@ import {
127
129
  HttpCompressor,
128
130
  httpAcceptEncoding,
129
131
  } from "nish/net/http-compress"
130
- import { netClose, netMss, netRead, netWrite, tcpAccept } from "nish:net"
132
+ import { netClose, netMss, netRead, netWrite, netWrite2, tcpAccept } from "nish:net"
131
133
  import {
132
134
  HTTP1_BODY,
133
135
  HTTP1_CHUNKED,
@@ -247,7 +249,7 @@ const http1ServerCheckCap = (name: string, value: i32, low: i32, high: i32): voi
247
249
  }
248
250
 
249
251
  /** Panics unless `buf[off .. off + len)` is inside `buf`: a window past its buffer is the caller's mistake. */
250
- const http1ServerCheckWindow = (what: string, buf: u8[], off: i32, len: i32): void => {
252
+ const http1ServerCheckWindow = (what: string, buf: readonly u8[], off: i32, len: i32): void => {
251
253
  const size: i32 = toI32(buf.length)
252
254
  if (off < 0 || len < 0 || off > size || len > size - off) {
253
255
  panic(`${what}: the window is outside the buffer`)
@@ -255,7 +257,7 @@ const http1ServerCheckWindow = (what: string, buf: u8[], off: i32, len: i32): vo
255
257
  }
256
258
 
257
259
  /** Copies `src[off .. off + n)` to `out` at `at`, which the caller has made sure holds it, and answers where it ends. */
258
- const http1ServerCopy = (out: u8[], at: i32, src: u8[], off: i32, n: i32): i32 => {
260
+ const http1ServerCopy = (out: u8[], at: i32, src: readonly u8[], off: i32, n: i32): i32 => {
259
261
  if (n > 0 && at >= 0 && off >= 0 && at <= toI32(out.length) - n && off <= toI32(src.length) - n) {
260
262
  // Both windows fit, as they do for every caller: one move, not a byte loop.
261
263
  copyBytes(out, at, src, off, n)
@@ -615,6 +617,14 @@ export class Http1Connection {
615
617
  mss: i32 = 0
616
618
  /** The MSS `Http1Server.accept` read from this connection's socket (`netMss`), or 0 when it reports none. */
617
619
  socketMss: i32 = 0
620
+ /**
621
+ * The plain TCP socket the carrier sends `output` on, which `sendBody`
622
+ * writes to directly: `Http1Server.accept` sets it, and `restart` and
623
+ * `abort` put it back to -1. -1 for a connection with no such socket (a
624
+ * sans-IO carrier, `Http1TlsServer`'s TLS records), where `sendBody` copies
625
+ * as `write` does.
626
+ */
627
+ fd: i32 = -1
618
628
  config: Http1Config
619
629
  /**
620
630
  * The frame decoder: made when the slot first switches to WebSocket, so a
@@ -656,8 +666,10 @@ export class Http1Connection {
656
666
  big - H1_LINE_OVERHEAD
657
667
  )
658
668
  this.config = config
659
- this.date = new HttpDate()
669
+ // The parser is made first: the arena places each block after the last,
670
+ // so its front fields sit on the lines just behind the connection's own.
660
671
  this.parser = new Http1Parser(config.maxTarget, config.maxHeaderBytes, config.maxHeaders, config.maxBody)
672
+ this.date = new HttpDate()
661
673
  this.parser.keepText = false
662
674
  this.parser.maxChunk = config.chunkSize
663
675
  this.ws = null
@@ -713,6 +725,7 @@ export class Http1Connection {
713
725
  this.headSince = 0
714
726
  this.mss = 0
715
727
  this.socketMss = 0
728
+ this.fd = -1
716
729
  this.release()
717
730
  this.park()
718
731
  }
@@ -745,16 +758,22 @@ export class Http1Connection {
745
758
  }
746
759
  }
747
760
 
748
- /** Takes back the buffers `park` gave away, before bytes are fed. */
761
+ /**
762
+ * Takes back the buffers `park` gave away, before bytes are fed. A parked
763
+ * buffer is `noOutput` itself, which a pointer compare finds without
764
+ * loading the empty array's header from a line the request touches nowhere
765
+ * else; any other empty buffer is still swapped for a lent one.
766
+ */
749
767
  unpark(): void {
750
768
  const inputs: Http1OutputPool | null = this.inputs
751
769
  const heads: Http1OutputPool | null = this.heads
752
770
  const p: Http1Parser = this.parser
753
- if (inputs !== null && toI32(p.buf.length) === 0) {
771
+ const none: u8[] = this.noOutput
772
+ if (inputs !== null && (p.buf === none || toI32(p.buf.length) === 0)) {
754
773
  p.buf = inputs.take()
755
774
  p.body = p.buf
756
775
  }
757
- if (heads !== null && toI32(p.head.length) === 0) {
776
+ if (heads !== null && (p.head === none || toI32(p.head.length) === 0)) {
758
777
  p.head = heads.take()
759
778
  }
760
779
  }
@@ -816,6 +835,7 @@ export class Http1Connection {
816
835
  this.outputEnd = 0
817
836
  this.pongPending = false
818
837
  this.writeHeld = false
838
+ this.fd = -1
819
839
  this.release()
820
840
  }
821
841
 
@@ -1213,7 +1233,7 @@ export class Http1Connection {
1213
1233
  * nothing. `H1_CLOSED` with no response under way. A window outside `buf`
1214
1234
  * panics.
1215
1235
  */
1216
- write(buf: u8[], off: i32, len: i32): i32 {
1236
+ write(buf: readonly u8[], off: i32, len: i32): i32 {
1217
1237
  http1ServerCheckWindow("Http1Connection.write", buf, off, len)
1218
1238
  if (this.response !== H1_R_BODY || this.state !== H1_S_HTTP) {
1219
1239
  return H1_CLOSED
@@ -1252,6 +1272,63 @@ export class Http1Connection {
1252
1272
  return take
1253
1273
  }
1254
1274
 
1275
+ /**
1276
+ * `write` of `buf[off .. off + len)`, sent from `buf` itself where it can
1277
+ * be: under a `Content-Length` response on a connection whose carrier
1278
+ * named its socket (`fd`, set by `Http1Server.accept`) and with no write
1279
+ * held back, the queued output and the body leave in one `netWrite2`, and
1280
+ * only what the socket did not take is copied into the output, the way
1281
+ * `write` copies it (what does not fit is answered short, and `H1_WRITE`
1282
+ * says when to send the rest). Once it returns the connection holds no
1283
+ * reference to `buf`, so the caller may reuse or give back its bytes at
1284
+ * once. A chunked or empty response, a write held back (`H1_AGAIN` or a
1285
+ * short answer not yet followed by `H1_WRITE`), and a connection with no
1286
+ * socket (`Http1TlsServer`, a sans-IO carrier) copy all of it: it is
1287
+ * `write`, with the same bytes on the wire. Answers what `write` answers,
1288
+ * `H1_INVALID` for more than the response still owes; `H1_CLOSED` also
1289
+ * when the socket failed during the send, which aborts the connection. A
1290
+ * window outside `buf` panics.
1291
+ */
1292
+ sendBody(buf: readonly u8[], off: i32, len: i32): i32 {
1293
+ http1ServerCheckWindow("Http1Connection.sendBody", buf, off, len)
1294
+ if (
1295
+ this.fd < 0 ||
1296
+ this.writeHeld ||
1297
+ this.response !== H1_R_BODY ||
1298
+ this.state !== H1_S_HTTP ||
1299
+ this.responseEmpty ||
1300
+ this.responseFraming < 0 ||
1301
+ len === 0 ||
1302
+ len > this.responseLeft
1303
+ ) {
1304
+ return this.write(buf, off, len)
1305
+ }
1306
+ const pending: i32 = this.outputEnd - this.outputStart
1307
+ const n: i32 = netWrite2(this.fd, this.output, this.outputStart, pending, buf, off, len)
1308
+ if (n < 0 && n !== H1_AGAIN) {
1309
+ this.abort()
1310
+ return H1_CLOSED
1311
+ }
1312
+ let sent: i32 = 0
1313
+ // pending + len > 0 here (len > 0 above), so netWrite2 never answers 0: it is a count, H1_AGAIN or a failure.
1314
+ if (n > 0) {
1315
+ this.lastActive = monotonicNanos()
1316
+ this.consume(n)
1317
+ sent = n > pending ? n - pending : 0
1318
+ this.responseLeft = this.responseLeft - sent
1319
+ }
1320
+ if (sent < len) {
1321
+ const copied: i32 = this.write(buf, off + sent, len - sent)
1322
+ if (copied > 0) {
1323
+ sent = sent + copied
1324
+ } else if (sent === 0) {
1325
+ return copied
1326
+ }
1327
+ }
1328
+ this.release()
1329
+ return sent
1330
+ }
1331
+
1255
1332
  /**
1256
1333
  * Ends the response: the last chunk of a chunked body. Answers 0;
1257
1334
  * `H1_INVALID` for a response with a length that still owes bytes;
@@ -1777,6 +1854,7 @@ export class Http1Server {
1777
1854
  this.fds[k] = fd
1778
1855
  this.armed[k] = H1_WANT_READ
1779
1856
  conn.restart()
1857
+ conn.fd = fd
1780
1858
  // Once a connection, not a request, so a keep-alive request costs no
1781
1859
  // syscall: a path whose MSS moves after the handshake is not followed.
1782
1860
  const mss: i32 = netMss(fd)