scoop:scoop.http:0.1.0
src/cookie/header.scoop
Selected production source · src/cookie/header.scoop
1
package scoop.http3
import scoop.bytes.ByteArrayBuilder5
/**6
* An ordered sequence of cookie name/value pairs for the Cookie field.7
*/8
public class HttpCookieHeader private constructor(9
/**10
* Cookie pairs in their original order.11
*/12
public val pairs: Array<HttpCookiePair>) {13
public constructor(pairs: List<HttpCookiePair>) : this(pairs.toArray()) {}15
/**16
* Serializes the structured value into HTTP field-value bytes.17
*/18
public fun toByteArray(): Array<Byte> {19
val output = ByteArrayBuilder()20
var first = true21
for (pair in pairs) {22
if (!first) output.append("; ".toByteArray())23
output.append(pair.toByteArray())24
first = false25
}26
return output.toByteArray()27
}28
/**29
* Builds a Cookie field with never-index enabled.30
*/31
public fun toHttpField(): HttpField = HttpField("Cookie".toByteArray(), toByteArray(), neverIndex = true)33
/**34
* Construction and parsing of this structured HTTP field.35
*/36
public companion object {37
/**38
* Parses the complete field value, throwing HttpFieldParseException for malformed syntax.39
*/40
public fun parse(value: List<Byte>): HttpCookieHeader {41
val reader = cookieFieldReader("Cookie", value)42
val pairs = ArrayList<HttpCookiePair>()43
while (!reader.ended) {44
val pair = HttpCookiePair.read(reader)45
if (pair.name.size > 0L || pair.value.size > 0L) pairs.add(pair)46
if (!reader.ended) reader.expect(59)47
}48
return HttpCookieHeader(pairs.toArray())49
}50
/**51
* Parses the complete field value, throwing HttpFieldParseException for malformed syntax.52
*/53
public fun parse(value: String): HttpCookieHeader = parse(value.toByteArray())54
/**55
* Parses the complete value, returning None for HttpFieldParseException while propagating56
* unrelated failures.57
*/58
public fun parseOrNone(value: List<Byte>): HttpCookieHeader? {59
try { return Some(parse(value)) }60
catch (_: HttpFieldParseException) { return None }61
}62
/**63
* Parses the complete value, returning None for HttpFieldParseException while propagating64
* unrelated failures.65
*/66
public fun parseOrNone(value: String): HttpCookieHeader? = parseOrNone(value.toByteArray())67
/**68
* Combines Cookie fields as ordered pairs without losing duplicates.69
*/70
public fun parseFields(fields: List<HttpField>): HttpCookieHeader {71
val pairs = ArrayList<HttpCookiePair>()72
for (field in fields.findAll("cookie".toByteArray())) for (pair in parse(field.value).pairs) pairs.add(pair)73
return HttpCookieHeader(pairs.toArray())74
}75
}76
}