Scoop API

scoop:scoop.http:0.1.0

src/multipart/boundary.scoop

Selected production source · src/multipart/boundary.scoop

1package scoop.http
3import scoop.crypto.secureRandomBytes
4import scoop.text.toHexString
6/**
7 * A validated multipart boundary of 1..70 permitted ASCII characters with no trailing space.
8 */
9public class MultipartBoundary private constructor(
10 /**
11 * The validated ASCII boundary text without delimiter prefixes.
12 */
13 public val value: String, internal val bytes: Array<Byte>)
14 : Equals<MultipartBoundary>, Hash, ToString {
15 public constructor(value: String) : this(value, checkedBoundary(value.toByteArray())) {}
16 /**
17 * Compares boundary text exactly.
18 */
19 public override operator fun equals(other: MultipartBoundary): Boolean = value == other.value
20 /**
21 * Hashes the boundary text consistently with equality.
22 */
23 public override fun hash(): Long = value.hash()
24 /**
25 * Returns the raw boundary text.
26 */
27 public override fun toString(): String = value
28 /**
29 * Builds a multipart media type with this boundary and the selected subtype.
30 */
31 public fun toMediaType(subtype: String = "form-data"): HttpMediaType =
32 HttpMediaType("multipart", subtype, [HttpParameter("boundary", bytes)])
34 /**
35 * Boundary generation and extraction from Content-Type.
36 */
37 public companion object {
38 /**
39 * Creates a boundary from 24 cryptographically random bytes with a scoop- prefix.
40 */
41 public fun generate(): MultipartBoundary = MultipartBoundary("scoop-" + secureRandomBytes(24L).toHexString())
42 /**
43 * Extracts and validates the boundary parameter from a multipart media type.
44 */
45 public fun fromMediaType(mediaType: HttpMediaType): MultipartBoundary {
46 if (mediaType.type != "multipart") throw IllegalArgumentException(Some("expected a multipart media type"))
47 val parameter = mediaType.parameter("boundary") ?: throw IllegalArgumentException(Some("missing multipart boundary"))
48 val bytes = checkedBoundary(parameter.value)
49 return MultipartBoundary(String.fromUtf8(bytes), bytes)
50 }
51 }
54private fun checkedBoundary(value: List<Byte>): Array<Byte> {
55 if (value.size < 1L || value.size > 70L || value[value.size - 1L] == 32.toByte())
56 throw IllegalArgumentException(Some("multipart boundary must contain 1 to 70 ASCII characters without trailing space"))
57 for (byte in value) {
58 val c = byte.toUByte().toInt()
59 val alpha = (c >= 65 && c <= 90) || (c >= 97 && c <= 122)
60 val digit = c >= 48 && c <= 57
61 if (!alpha && !digit && c != 39 && c != 40 && c != 41 && c != 43 && c != 95 && c != 44 &&
62 c != 45 && c != 46 && c != 47 && c != 58 && c != 61 && c != 63 && c != 32)
63 throw IllegalArgumentException(Some("invalid multipart boundary character"))
64 }
65 return value.toArray()