Scoop API

scoop:scoop.http:0.1.0

src/multipart/encoder.scoop

Selected production source · src/multipart/encoder.scoop

1package scoop.http
3import scoop.bytes.ByteArrayBuilder
4import scoop.platform.memory.NativeByteBuffer
6/**
7 * An in-memory multipart writer with explicit beginPart, body, endPart, and final finish. It
8 * performs no transport I/O and close does not emit a closing boundary.
9 */
10public class MultipartEncoder public constructor(
11 /**
12 * The validated delimiter boundary used by this codec.
13 */
14 public val boundary: MultipartBoundary) : Closeable {
15 private val guard: MultipartGuard = MultipartGuard()
16 private var part: MultipartPartHead? = None
17 private var written: Long = 0L
18 private var closed: Boolean = false
19 private var finished: Boolean = false
20 /**
21 * Whether this codec has been closed.
22 */
23 public val isClosed: Boolean get() = closed
24 /**
25 * Whether the codec has completed its terminal operation and, for a decoder, drained pending
26 * events.
27 */
28 public val isFinished: Boolean get() = finished
29 /**
30 * Whether a part is waiting for endPart.
31 */
32 public val isPartOpen: Boolean get() = when (part) { case Some(_) -> true; case None -> false }
34 /**
35 * Emits the boundary and validated part headers; the previous part must already be ended.
36 */
37 public fun beginPart(head: MultipartPartHead): Array<Byte> = guard.withUse {
38 requireOpen()
39 if (isPartOpen) throw IllegalStateException(Some("multipart part is still open"))
40 val output = ByteArrayBuilder().append("--".toByteArray()).append(boundary.bytes).append("\r\n".toByteArray())
41 .append(head.encoded).toByteArray()
42 part = Some(head)
43 written = 0L
44 output
45 }
47 /**
48 * Consumes and returns part-body bytes, rejecting writes beyond a declared body length.
49 */
50 public fun writeBody(buffer: NativeByteBuffer, count: Long = buffer.readableBytes): Array<Byte> = guard.withUse {
51 requireOpen()
52 val head = part ?: throw IllegalStateException(Some("multipart part is not open"))
53 if (count < 0L) throw IllegalArgumentException(Some("negative multipart input count"))
54 if (count > buffer.readableBytes) throw IndexOutOfBoundsException()
55 val total = multipartAdd(written, count)
56 if (head.bodyLength != None && total > head.bodyLength!!)
57 throw IllegalArgumentException(Some("multipart body exceeds its declared length"))
58 val bytes = buffer.readBytes(count)
59 written = total
60 bytes
61 }
63 /**
64 * Emits the part terminator after checking its declared body length is complete.
65 */
66 public fun endPart(): Array<Byte> = guard.withUse {
67 requireOpen()
68 val head = part ?: throw IllegalStateException(Some("multipart part is not open"))
69 if (head.bodyLength != None && written != head.bodyLength!!)
70 throw IllegalStateException(Some("multipart body has not reached its declared length"))
71 val output = "\r\n".toByteArray()
72 part = None
73 output
74 }
76 /**
77 * Emits the final closing boundary; no part may remain open.
78 */
79 public fun finish(): Array<Byte> = guard.withUse {
80 requireOpen()
81 if (isPartOpen) throw IllegalStateException(Some("multipart part is still open"))
82 val output = ByteArrayBuilder().append("--".toByteArray()).append(boundary.bytes).append("--\r\n".toByteArray()).toByteArray()
83 finished = true
84 output
85 }
87 /**
88 * Releases local state without emitting bytes or finishing an incomplete message.
89 */
90 public override fun close() {
91 guard.withUse { closed = true; part = None; Unit }
92 }
94 private fun requireOpen() {
95 if (closed || finished) throw IllegalStateException(Some("multipart encoder is closed or finished"))
96 }
98 /**
99 * Helpers for determining total encoded multipart length.
100 */
101 public companion object {
102 /**
103 * Computes exact framing plus body length with checked overflow, or None if any part
104 * length is unknown.
105 */
106 public fun contentLength(boundary: MultipartBoundary, parts: List<MultipartPartHead>): Long? {
107 var total = boundary.bytes.size + 6L
108 var known = true
109 for (part in parts) {
110 total = multipartAdd(total, multipartAdd(boundary.bytes.size + 6L, part.encoded.size))
111 when (part.bodyLength) { case Some(val length) -> total = multipartAdd(total, length); case None -> known = false }
112 }
113 return if (known) Some(total) else None
114 }
115 }