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 13class BDataIO; 14 15namespace BPrivate { 16 17namespace Network { 18 19class BHttpRequest; 20class HttpBuffer; 21 22using HttpTransferFunction = std::function<size_t(const std::byte*, size_t)>; 23 24 25enum class HttpSerializerState { Uninitialized, Header, ChunkHeader, Body, Done }; 26 27 28class HttpSerializer 29{ 30public: 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 42private: 43 bool _IsChunked() const noexcept; 44 size_t _WriteToTarget(HttpBuffer& buffer, BDataIO* target) const; 45 46private: 47 HttpSerializerState fState = HttpSerializerState::Uninitialized; 48 BDataIO* fBody = nullptr; 49 off_t fTransferredBodySize = 0; 50 std::optional<off_t> fBodySize; 51}; 52 53 54inline bool 55HttpSerializer::IsInitialized() const noexcept 56{ 57 return fState != HttpSerializerState::Uninitialized; 58} 59 60 61inline std::optional<off_t> 62HttpSerializer::BodyBytesTotal() const noexcept 63{ 64 return fBodySize; 65} 66 67 68inline off_t 69HttpSerializer::BodyBytesTransferred() const noexcept 70{ 71 return fTransferredBodySize; 72} 73 74 75inline bool 76HttpSerializer::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