Future<Unit> wangle fixup
[folly.git] / folly / wangle / codec / LengthFieldPrepender.h
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #pragma once
17
18 #include <folly/wangle/codec/ByteToMessageCodec.h>
19 #include <folly/io/Cursor.h>
20
21 namespace folly { namespace wangle {
22
23 /**
24  * An encoder that prepends the length of the message.  The length value is
25  * prepended as a binary form.
26  *
27  * For example, LengthFieldPrepender(2)will encode the
28  * following 12-bytes string:
29  *
30  * +----------------+
31  * | "HELLO, WORLD" |
32  * +----------------+
33  *
34  * into the following:
35  *
36  * +--------+----------------+
37  * + 0x000C | "HELLO, WORLD" |
38  * +--------+----------------+
39  *
40  * If you turned on the lengthIncludesLengthFieldLength flag in the
41  * constructor, the encoded data would look like the following
42  * (12 (original data) + 2 (prepended data) = 14 (0xE)):
43  *
44  * +--------+----------------+
45  * + 0x000E | "HELLO, WORLD" |
46  * +--------+----------------+
47  *
48  */
49 class LengthFieldPrepender
50 : public OutboundBytesToBytesHandler {
51  public:
52   LengthFieldPrepender(
53     int lengthFieldLength = 4,
54     int lengthAdjustment = 0,
55     bool lengthIncludesLengthField = false,
56     bool networkByteOrder = true);
57
58   Future<Unit> write(Context* ctx, std::unique_ptr<IOBuf> buf);
59
60  private:
61   int lengthFieldLength_;
62   int lengthAdjustment_;
63   bool lengthIncludesLengthField_;
64   bool networkByteOrder_;
65 };
66
67 }} // namespace