Sane C++ Libraries
C++ Platform Abstraction Libraries
Loading...
Searching...
No Matches
HttpMultipartParser.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4#include "../Foundation/Result.h"
5#include "../Foundation/Span.h"
6#include "../Foundation/StringSpan.h"
7
8namespace SC
9{
12
14struct SC_COMPILER_EXPORT HttpMultipartParser
15{
18
20 void reset();
21
23 enum class State
24 {
25 Parsing,
26 Result,
27 Finished,
28 };
29
31 enum class Token
32 {
33 HeaderName,
34 HeaderValue,
35 PartBody,
36 Boundary,
37 PartHeaderEnd,
38 Finished,
39 };
40
41 Token token = Token::Boundary;
42 State state = State::Parsing;
43
49 Result parse(Span<const char> data, size_t& readBytes, Span<const char>& parsedData);
50
51 private:
52 char boundaryStorage[71] = {0}; // MAX = 70 + NUL
53 char boundaryBuffer[128] = {0};
54
55 size_t tokenStart = 0;
56 size_t tokenLength = 0;
57 size_t globalStart = 0;
58 size_t globalLength = 0;
59 size_t matchIndex = 0; // For matching boundary and other fixed strings
60
61 int topLevelCoroutine = 0;
62 int nestedParserCoroutine = 0;
63
64 uint8_t boundaryMatchIndex = 0;
65
66 StringSpan boundary;
67
68 // Helper functions for parsing
69 [[nodiscard]] bool parseBoundary(char currentChar);
70 [[nodiscard]] bool parseHeaders(char currentChar);
71 [[nodiscard]] bool parseBody(char currentChar);
72
73 // Specific parsers
74 [[nodiscard]] bool parsePreamble(char currentChar);
75 [[nodiscard]] bool parseBoundaryLine(char currentChar);
76 [[nodiscard]] bool parseHeaderName(char currentChar);
77 [[nodiscard]] bool parseHeaderValue(char currentChar);
78 [[nodiscard]] bool parseBodyUntilBoundary(char currentChar);
79
80 template <bool (HttpMultipartParser::*Func)(char), Token currentResult>
81 Result process(Span<const char>& data, size_t& readBytes, Span<const char>& parsedData);
82};
83
85} // namespace SC
Incremental HTTP multipart/form-data parser.
Definition HttpMultipartParser.h:15
void reset()
Resets the parser state.
Result parse(Span< const char > data, size_t &readBytes, Span< const char > &parsedData)
Parse an incoming chunk of bytes, returning actually parsed span.
Result initWithBoundary(StringSpan boundary)
Initializes the parser with the given boundary (that excludes the leading '–')
State
State of the parser.
Definition HttpMultipartParser.h:24
Token
One possible Token reported by the parser.
Definition HttpMultipartParser.h:32
An ascii string used as boolean result. SC_TRY macro forwards errors to caller.
Definition Result.h:13
View over a contiguous sequence of items (pointer + size in elements).
Definition Span.h:29
An read-only view over a string (to avoid including Strings library when parsing is not needed).
Definition StringSpan.h:37