http_parser

    Incremental HTTP/1.1 request parsing in pure MoonBit, adapted from uWebSockets HttpParser

    http
    parser
    streaming
    chunked
    simd
    Download zip
    Author
    Version
    0.1.0
    License
    MIT
    Last updated
    58 minutes ago
    Downloads
    2

    No dependencies

    #Checked HTTP parser examples

    See README.md for streaming, ownership, limits, and upstream differences.

    ///|
    test "retain a parsed request and decode its query" {
    let parser = @http_parser.Parser::new()
    let requests : Array[@http_parser.Request] = []
    ignore(
    parser.feed(
    b"GET /?hello=a%20b+c&debug HTTP/1.1\r\nHost: h\r\n\r\n",
    on_request=request => {
    requests.push(request)
    @http_parser.Continue
    },
    on_body=(_, _) => @http_parser.Continue,
    ),
    )
    parser.finish()
    assert_eq(requests[0].get_header(b"host"), Some(b"h"[:]))
    assert_eq(
    requests[0].get_query_value(b"hello"),
    Some(@http_parser.Value(b"a b c")),
    )
    assert_eq(requests[0].get_query_value(b"debug"), Some(@http_parser.Valueless))
    }

    ///|
    test "a request callback can hand off the untouched suffix" {
    let parser = @http_parser.Parser::new()
    let input : Bytes = b"GET / HTTP/1.1\r\nHost: h\r\n\r\nnext protocol"
    let result = parser.feed(input, on_request=_ => @http_parser.Stop, on_body=(
    _,
    _,
    ) => @http_parser.Continue)
    assert_eq(input[result.consumed():], b"next protocol"[:])
    }

    ParseError

    pub(all) suberror ParseError {
    InvalidRequestLine
    InvalidHeaderName
    InvalidHeaderValue
    MissingHost
    DuplicateHost
    InvalidHost
    ConflictingBodyFraming
    InvalidContentLength
    InvalidTransferEncoding
    HeaderTooLarge
    TooManyHeaders
    InvalidChunkedEncoding
    UnexpectedEof
    InvalidLimits
    ReentrantCall
    } derive(Eq,
    Debug
    )

    Reports invalid wire input, incomplete EOF, or an invalid parser operation.

    Wire errors correspond to upstream 400 Bad Request, including header limits. UnexpectedEof rejects an unfinished head, body, chunk, or trailer section. InvalidLimits rejects nonpositive limits at construction; ReentrantCall rejects feeding, copying, resetting, or finishing the same parser inside a callback. Wire/EOF errors remain sticky until reset, and no later feed emits callbacks. Callbacks cannot raise errors through this API.

    Algorithm

    pub(all) enum Algorithm {
    Auto
    Scalar
    Simd
    } derive(Eq,
    Debug
    )

    Selects bounded byte scanning, without changing the accepted grammar.

    Simd requests V128 scans on native and linear-memory Wasm. Inputs shorter than sixteen bytes and the Wasm GC/JavaScript backends use scalar scans. Auto uses scalar scans until a complete CI snapshot establishes dispatch.

    Control

    pub(all) enum Control {
    Continue
    Stop
    } derive(Eq,
    Debug
    )

    Controls whether a callback lets the parser continue consuming this input.

    Stop leaves the parser resumable and returns an exact consumed byte count. After a request callback it also supports protocol handoff: body framing has not been interpreted, and the unconsumed suffix belongs to the caller.

    FeedResult

    pub(all) enum FeedResult {
    Consumed(Int)
    Stopped(Int)
    } derive(Eq,
    Debug
    )

    Describes how much of the supplied view a feed call consumed.

    Consumed includes bytes buffered for an incomplete header, and does not imply a complete request or body. Stopped means a callback returned Stop. In both cases the count is relative to the supplied view, in bytes.

    FeedResult::consumed

    fn FeedResult::consumed(self : FeedResult) -> Int

    Returns the consumed byte count for advancing the caller's input view. This operation does not change the result or parser state.

    Parser

    pub struct Parser {
    // private fields
    }

    An incremental HTTP/1.1 request parser with bounded header storage.

    The parser buffers only incomplete request heads, streams body views through callbacks, skips chunked trailers, and parses pipelined requests in order. Default limits are 4096 head bytes and 98 fields, matching upstream defaults. State has reference semantics: assignment aliases it; copy creates an independent cursor and buffer. Use reset after a wire error or to reuse it. Callbacks may inspect requests but must not reenter this parser.

    Parser::buffered_bytes

    fn Parser::buffered_bytes(self : Parser) -> Int

    Returns the number of buffered incomplete-head bytes, excluding all body bytes. The value is at most max_header_bytes, including bytes retained on error.

    Parser::copy

    fn Parser::copy(self : Parser) -> Parser raise ParseError

    Creates an independent parser at the same framing and buffered-head position. Limits, algorithm, pending request metadata, and sticky errors are copied. Immutable wire bytes are safely shared; all mutable cursor/buffer state is independent. Raises ReentrantCall when called from this parser's callback.

    Parser::feed

    fn Parser::feed(self : Parser, input : BytesView, on_request~ : (Request) -> Control, on_body~ : (BytesView, UInt64) -> Control) -> FeedResult raise ParseError

    Consumes unpadded immutable input, emitting requests and streaming body views.

    Request callbacks run after head/Host/TE+CL validation and before detailed body-framing validation. Returning Stop permits protocol handoff; resume by feeding the unconsumed suffix, possibly empty, to the same parser. Fixed-body events report exact remaining bytes; chunked payload reports 18446744073709551615UL, then an empty event with zero before trailers complete. No-body requests emit one empty event with zero. A fixed body whose head arrived alone initially emits an empty event with its full remaining length. Body storage is never accumulated. Views are immutable and may be retained. Malformed input raises a sticky ParseError; reset is required to recover. This parser must not be fed, copied, reset, or finished from its callbacks.

    Parser::finish

    fn Parser::finish(self : Parser) -> Unit raise ParseError

    Checks EOF without accepting an unfinished request, payload, or trailers. Healthy idle state succeeds without closing the parser. An unfinished state raises sticky UnexpectedEof; existing wire errors are raised unchanged. Call this only after any paused request callback has been resumed.

    Parser::is_idle

    fn Parser::is_idle(self : Parser) -> Bool

    Returns whether the parser is healthy and at an empty request boundary. A body-end event can precede chunked trailers, so it alone does not prove idle. A paused request callback leaves pending body validation and is not idle.

    Parser::new

    fn Parser::new(max_header_bytes? : Int, max_headers? : Int, algorithm? : Algorithm) -> Parser raise ParseError

    Creates an empty parser with independent state and explicit head limits.

    max_header_bytes counts the entire request line, fields, and final CRLF; max_headers counts actual fields, excluding the request line. Both must be positive or construction raises InvalidLimits. No body buffer is allocated. algorithm affects scans only; every backend implements the same grammar.

    Parser::reset

    fn Parser::reset(self : Parser) -> Unit raise ParseError

    Discards buffered input, framing state, and any sticky error for reuse. Limits and algorithm are retained; existing request/body views stay valid. Aliased parser references observe the reset; independent copies do not. Raises ReentrantCall if invoked on this parser inside a callback.

    QueryValue

    pub(all) enum QueryValue {
    Valueless
    Value(Bytes)
    } derive(Eq,
    Debug
    )

    Distinguishes a query flag from a query value, including an empty value.

    Valueless represents ?debug; Value(b"") represents ?debug=. Bytes can include NUL and invalid UTF-8. Keys are matched without decoding; values use the pinned upstream's permissive percent arithmetic and + rule.

    Request

    pub struct Request {
    // private fields
    }

    An owned, retainable request head with independently mutable routing metadata.

    Wire data is immutable and remains valid after callbacks and parser reset. Header names are lowercase, values are trimmed, and order/duplicates remain intact. Byte views preserve obs-text without requiring valid UTF-8. Assignment aliases the routing metadata; use copy for independent yield/parameters. The original method and query never change when using compatibility getters.

    Request::are_identical

    fn Request::are_identical(self : Request, lowercase_name : BytesView, expected_value : BytesView) -> Bool

    Checks every field named lowercase_name against an exact trimmed byte value. The caller supplies a lowercase name. The result is vacuously true when the field is absent; no case folding or numeric normalization applies to values.

    Request::copy

    fn Request::copy(self : Request) -> Request

    Copies mutable routing metadata while sharing immutable request bytes. Changing yield flags, parameter containers, or offsets in either copy cannot affect the other. Copying does not mutate or consume the original request.

    Request::get_case_sensitive_method

    fn Request::get_case_sensitive_method(self : Request) -> BytesView

    Returns the exact original method bytes, including their original case. Calling get_method first does not change this result. The view is retainable.

    Request::get_full_url

    fn Request::get_full_url(self : Request) -> BytesView

    Returns the complete original request target, including any query string. This immutable view remains valid after subsequent parser operations.

    Request::get_header

    fn Request::get_header(self : Request, lowercase_name : BytesView) -> BytesView?

    Finds the first field whose normalized name equals lowercase_name exactly. The caller supplies a lowercase byte key; a mixed-case key does not match. None means missing, while Some(b"") means present with an empty value. Duplicate fields are available through headers and are_identical.

    Request::get_method

    fn Request::get_method(self : Request) -> BytesView

    Returns the compatibility method with every original byte ORed with 32. The immutable result is cached; this does not mutate the original method. This reproduces upstream's getter for its permissively accepted methods.

    Request::get_named_parameter

    fn Request::get_named_parameter(self : Request, name : String) -> BytesView?

    Looks up a case-sensitive parameter name through externally supplied offsets. Missing names and invalid indices return None; no URL decoding is performed.

    Request::get_parameter

    fn Request::get_parameter(self : Request, index : Int) -> BytesView?

    Returns an indexed routing parameter or None for any out-of-range index. An explicitly empty parameter returns Some(b""); the byte view is retainable.

    Request::get_query

    fn Request::get_query(self : Request) -> BytesView?

    Returns the raw query after the first ?, without decoding or mutation. None means there was no ?; Some(b"") represents an explicitly empty query.

    Request::get_query_value

    fn Request::get_query_value(self : Request, key : BytesView) -> QueryValue?

    Returns the first query entry whose raw, undecoded key equals key exactly. Empty keys, missing entries, and truncated percent escapes return None. Valueless distinguishes flags from Value(b""). Values map + to SP and use upstream's permissive percent arithmetic, so invalid hex pairs are not rejected. Decoded NUL/obs-text is preserved. Repeated lookup is deterministic and never modifies the target or other entries, unlike upstream's in-place API.

    Request::get_url

    fn Request::get_url(self : Request) -> BytesView

    Returns the request target before its first ?, without percent decoding. Offsets count bytes; origin-form paths and the accepted OPTIONS * stay ASCII.

    Request::get_yield

    fn Request::get_yield(self : Request) -> Bool

    Returns the routing yield flag, initially false for each request. Assignment aliases this flag; copy creates independent routing metadata.

    Request::headers

    fn Request::headers(self : Request) -> Iter[(BytesView, BytesView)]

    Iterates normalized names and trimmed values in wire order, including duplicates. Values preserve every allowed byte, including invalid UTF-8 and DEL. Returned views share immutable request storage and may be retained.

    Request::is_ancient

    fn Request::is_ancient(_self : Request) -> Bool

    Returns false because the pinned parser accepts only HTTP/1.1 requests. This compatibility getter does not imply HTTP/1.0 or response support.

    Request::set_parameter_offsets

    fn Request::set_parameter_offsets(self : Request, offsets : Map[String, Int]) -> Unit

    Replaces name-to-index routing offsets with an independent copy of the map. Names are case sensitive; negative and out-of-range indices remain safe and return None during lookup. The request does not mutate the caller's map.

    Request::set_parameters

    fn Request::set_parameters(self : Request, parameters : ArrayView[Bytes]) -> Unit

    Replaces indexed routing parameters with a copy of the caller's container. Byte values are immutable. Existing name offsets are retained; out-of-range offsets simply return None. This operation does not infer routes from URLs.

    Request::set_yield

    fn Request::set_yield(self : Request, yielded : Bool) -> Unit

    Sets the routing yield flag without changing parser or wire state. Other references to this request observe the change; independent copies do not.