Scoop API

scoop:scoop.http:0.1.0

src/multipart/headers.scoop

Selected production source · src/multipart/headers.scoop

1package scoop.http
3import scoop.bytes.ByteArrayBuilder
5internal class MultipartHeaders(val limits: MultipartLimits) {
6 private var fields: ArrayList<HttpField> = ArrayList<HttpField>()
7 private var line: ByteArrayBuilder = ByteArrayBuilder()
8 private var value: ByteArrayBuilder = ByteArrayBuilder()
9 private var name: Array<Byte>? = None
10 private var size: Long = 0L
11 private var start: Long = 0L
12 private var cr: Boolean = false
14 fun accept(byte: Byte, offset: Long): MultipartPartHead? {
15 if (size == limits.maxHeaderBytes) throw MultipartLimitException(MultipartLimitKind.HeaderBytes, limits.maxHeaderBytes)
16 size += 1L
17 if (cr) {
18 if (byte != 10.toByte()) throw MultipartParseException(offset, "field CR must be followed by LF")
19 cr = false
20 val bytes = line.toByteArray()
21 line = ByteArrayBuilder()
22 if (bytes.size == 0L) {
23 commit()
24 val head = MultipartPartHead.parsed(fields.toArray())
25 clear()
26 return Some(head)
27 }
28 acceptLine(bytes)
29 return None
30 }
31 if (line.size == 0L) start = offset
32 val c = byte.toUByte().toInt()
33 if (c == 13) cr = true
34 else {
35 if ((c < 32 && c != 9) || c == 127) throw MultipartParseException(offset, "invalid field control byte")
36 line.append(byte)
37 }
38 return None
39 }
41 private fun acceptLine(bytes: Array<Byte>) {
42 if (bytes[0L] == 32.toByte() || bytes[0L] == 9.toByte()) {
43 if (!hasName) throw MultipartParseException(start, "field continuation has no preceding field")
44 value.append(32.toByte()).append(httpTrim(bytes, 0L, bytes.size))
45 return
46 }
47 commit()
48 if (fields.size == limits.maxFields) throw MultipartLimitException(MultipartLimitKind.Fields, limits.maxFields)
49 var colon = 0L
50 while (colon < bytes.size && bytes[colon] != 58.toByte()) {
51 if (!httpTokenByte(bytes[colon].toUByte().toInt())) throw MultipartParseException(start + colon, "invalid field name")
52 colon += 1L
53 }
54 if (colon == 0L || colon == bytes.size) throw MultipartParseException(start + colon, "field requires a name and colon")
55 val length = colon
56 name = Some(Array<Byte>(length) { index -> bytes[index] })
57 value.append(httpTrim(bytes, colon + 1L, bytes.size))
58 }
60 private val hasName: Boolean get() = when (name) { case Some(_) -> true; case None -> false }
61 private fun commit() {
62 when (name) {
63 case Some(val bytes) -> {
64 val raw = value.toByteArray()
65 fields.add(HttpField(bytes, httpTrim(raw, 0L, raw.size)))
66 }
67 case None -> {}
68 }
69 name = None
70 value = ByteArrayBuilder()
71 }
73 fun clear() {
74 fields = ArrayList<HttpField>()
75 line = ByteArrayBuilder()
76 value = ByteArrayBuilder()
77 name = None
78 cr = false
79 size = 0L
80 }