2 * Copyright 2015 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 #include <folly/wangle/codec/LengthFieldPrepender.h>
18 namespace folly { namespace wangle {
20 LengthFieldPrepender::LengthFieldPrepender(
21 int lengthFieldLength,
23 bool lengthIncludesLengthField,
24 bool networkByteOrder)
25 : lengthFieldLength_(lengthFieldLength)
26 , lengthAdjustment_(lengthAdjustment)
27 , lengthIncludesLengthField_(lengthIncludesLengthField)
28 , networkByteOrder_(networkByteOrder) {
29 CHECK(lengthFieldLength == 1 ||
30 lengthFieldLength == 2 ||
31 lengthFieldLength == 4 ||
32 lengthFieldLength == 8 );
35 Future<Unit> LengthFieldPrepender::write(
36 Context* ctx, std::unique_ptr<IOBuf> buf) {
37 int length = lengthAdjustment_ + buf->computeChainDataLength();
38 if (lengthIncludesLengthField_) {
39 length += lengthFieldLength_;
43 throw std::runtime_error("Length field < 0");
46 auto len = IOBuf::create(lengthFieldLength_);
47 len->append(lengthFieldLength_);
48 folly::io::RWPrivateCursor c(len.get());
50 switch (lengthFieldLength_) {
53 throw std::runtime_error("length does not fit byte");
55 if (networkByteOrder_) {
56 c.writeBE((uint8_t)length);
58 c.writeLE((uint8_t)length);
63 if (length >= 65536) {
64 throw std::runtime_error("length does not fit byte");
66 if (networkByteOrder_) {
67 c.writeBE((uint16_t)length);
69 c.writeLE((uint16_t)length);
74 if (networkByteOrder_) {
75 c.writeBE((uint32_t)length);
77 c.writeLE((uint32_t)length);
82 if (networkByteOrder_) {
83 c.writeBE((uint64_t)length);
85 c.writeLE((uint64_t)length);
90 throw std::runtime_error("Invalid lengthFieldLength");
94 len->prependChain(std::move(buf));
95 return ctx->fireWrite(std::move(len));