xref: /haiku/src/kits/network/libnetservices2/HttpSerializer.h (revision 52c4471a3024d2eb81fe88e2c3982b9f8daa5e56)
1 /*
2  * Copyright 2022 Haiku Inc. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 #ifndef _B_HTTP_SERIALIZER_H_
7 #define _B_HTTP_SERIALIZER_H_
8 
9 
10 #include <functional>
11 #include <optional>
12 
13 class BDataIO;
14 
15 namespace BPrivate {
16 
17 namespace Network {
18 
19 class BHttpRequest;
20 class HttpBuffer;
21 
22 using HttpTransferFunction = std::function<size_t(const std::byte*, size_t)>;
23 
24 
25 enum class HttpSerializerState { Uninitialized, Header, ChunkHeader, Body, Done };
26 
27 
28 class HttpSerializer
29 {
30 public:
31 								HttpSerializer(){};
32 
33 			void				SetTo(HttpBuffer& buffer, const BHttpRequest& request);
34 			bool				IsInitialized() const noexcept;
35 
36 			size_t				Serialize(HttpBuffer& buffer, BDataIO* target);
37 
38 			std::optional<off_t> BodyBytesTotal() const noexcept;
39 			off_t				BodyBytesTransferred() const noexcept;
40 			bool				Complete() const noexcept;
41 
42 private:
43 			bool				_IsChunked() const noexcept;
44 			size_t				_WriteToTarget(HttpBuffer& buffer, BDataIO* target) const;
45 
46 private:
47 			HttpSerializerState	fState = HttpSerializerState::Uninitialized;
48 			BDataIO*			fBody = nullptr;
49 			off_t				fTransferredBodySize = 0;
50 			std::optional<off_t> fBodySize;
51 };
52 
53 
54 inline bool
55 HttpSerializer::IsInitialized() const noexcept
56 {
57 	return fState != HttpSerializerState::Uninitialized;
58 }
59 
60 
61 inline std::optional<off_t>
62 HttpSerializer::BodyBytesTotal() const noexcept
63 {
64 	return fBodySize;
65 }
66 
67 
68 inline off_t
69 HttpSerializer::BodyBytesTransferred() const noexcept
70 {
71 	return fTransferredBodySize;
72 }
73 
74 
75 inline bool
76 HttpSerializer::Complete() const noexcept
77 {
78 	return fState == HttpSerializerState::Done;
79 }
80 
81 
82 } // namespace Network
83 
84 } // namespace BPrivate
85 
86 #endif // _B_HTTP_SERIALIZER_H_
87