copy wangle back into folly
[folly.git] / folly / wangle / codec / ByteToMessageCodec.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/channel/Handler.h>
19
20 namespace folly { namespace wangle {
21
22 /**
23  * A Handler which decodes bytes in a stream-like fashion from
24  * IOBufQueue to a  Message type.
25  *
26  * Frame detection
27  *
28  * Generally frame detection should be handled earlier in the pipeline
29  * by adding a DelimiterBasedFrameDecoder, FixedLengthFrameDecoder,
30  * LengthFieldBasedFrameDecoder, LineBasedFrameDecoder.
31  *
32  * If a custom frame decoder is required, then one needs to be careful
33  * when implementing one with {@link ByteToMessageDecoder}. Ensure
34  * there are enough bytes in the buffer for a complete frame by
35  * checking {@link ByteBuf#readableBytes()}. If there are not enough
36  * bytes for a complete frame, return without modify the reader index
37  * to allow more bytes to arrive.
38  *
39  * To check for complete frames without modify the reader index, use
40  * IOBufQueue.front(), without split() or pop_front().
41  */
42 class ByteToMessageCodec
43     : public InboundBytesToBytesHandler {
44  public:
45
46   virtual std::unique_ptr<IOBuf> decode(
47     Context* ctx, IOBufQueue& buf, size_t&) = 0;
48
49   void read(Context* ctx, IOBufQueue& q);
50 };
51
52 }}