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#include "HttpExport.h"
8
9namespace SC
10{
13
15struct SC_HTTP_EXPORT HttpMultipartParser
16{
19
21 void reset();
22
24 enum class State
25 {
26 Parsing,
27 Result,
28 Finished,
29 };
30
32 enum class Token
33 {
34 HeaderName,
35 HeaderValue,
36 PartBody,
37 Boundary,
38 PartHeaderEnd,
39 Finished,
40 };
41
42 Token token = Token::Boundary;
43 State state = State::Parsing;
44
50 Result parse(Span<const char> data, size_t& readBytes, Span<const char>& parsedData);
51
52 private:
53 char boundaryStorage[71] = {0}; // MAX = 70 + NUL
54 char boundaryBuffer[128] = {0};
55
56 size_t tokenStart = 0;
57 size_t tokenLength = 0;
58 size_t globalStart = 0;
59 size_t globalLength = 0;
60 size_t matchIndex = 0; // For matching boundary and other fixed strings
61
62 int topLevelCoroutine = 0;
63 int nestedParserCoroutine = 0;
64
65 uint8_t boundaryMatchIndex = 0;
66
67 StringSpan boundary;
68
69 // Helper functions for parsing
70 [[nodiscard]] bool parseBoundary(char currentChar);
71 [[nodiscard]] bool parseHeaders(char currentChar);
72 [[nodiscard]] bool parseBody(char currentChar);
73
74 // Specific parsers
75 [[nodiscard]] bool parsePreamble(char currentChar);
76 [[nodiscard]] bool parseBoundaryLine(char currentChar);
77 [[nodiscard]] bool parseHeaderName(char currentChar);
78 [[nodiscard]] bool parseHeaderValue(char currentChar);
79 [[nodiscard]] bool parseBodyUntilBoundary(char currentChar);
80
81 template <bool (HttpMultipartParser::*Func)(char), Token currentResult>
82 Result process(Span<const char>& data, size_t& readBytes, Span<const char>& parsedData);
83};
84
86} // namespace SC
Incremental HTTP multipart/form-data parser.
Definition HttpMultipartParser.h:16
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:25
Token
One possible Token reported by the parser.
Definition HttpMultipartParser.h:33
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