This repository has been archived on 2020-05-25. You can view files and clone it, but cannot push or open issues or pull requests.
tdlib-fork/td/telegram/net/NetQueryCreator.cpp
levlam b8848a2ab4 Simplify NetQuery creation.
GitOrigin-RevId: a01e72f8e196b405dd28dfd75d16cadc7127ec4a
2020-03-16 00:17:11 +03:00

56 lines
2.1 KiB
C++

//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2020
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "td/telegram/net/NetQueryCreator.h"
#include "td/utils/format.h"
#include "td/utils/Gzip.h"
#include "td/utils/logging.h"
#include "td/utils/Slice.h"
namespace td {
NetQueryPtr NetQueryCreator::create_regular(const Storer &storer) {
return create(UniqueId::next(), storer, DcId::main(), NetQuery::Type::Common, NetQuery::AuthFlag::On);
}
NetQueryPtr NetQueryCreator::create(uint64 id, const Storer &storer, DcId dc_id, NetQuery::Type type,
NetQuery::AuthFlag auth_flag) {
BufferSlice slice(storer.size());
auto real_size = storer.store(slice.as_slice().ubegin());
LOG_CHECK(real_size == slice.size()) << real_size << " " << slice.size() << " "
<< format::as_hex_dump<4>(Slice(slice.as_slice()));
int32 tl_constructor = NetQuery::tl_magic(slice);
size_t MIN_GZIPPED_SIZE = 128;
auto gzip_flag = slice.size() < MIN_GZIPPED_SIZE ? NetQuery::GzipFlag::Off : NetQuery::GzipFlag::On;
if (slice.size() >= 16384) {
// test compression ratio for the middle part
// if it is less than 0.9, then try to compress the whole request
size_t TESTED_SIZE = 1024;
BufferSlice compressed_part = gzencode(slice.as_slice().substr((slice.size() - TESTED_SIZE) / 2, TESTED_SIZE), 0.9);
if (compressed_part.empty()) {
gzip_flag = NetQuery::GzipFlag::Off;
}
}
if (gzip_flag == NetQuery::GzipFlag::On) {
BufferSlice compressed = gzencode(slice.as_slice(), 0.9);
if (compressed.empty()) {
gzip_flag = NetQuery::GzipFlag::Off;
} else {
slice = std::move(compressed);
}
}
auto query = object_pool_.create(NetQuery::State::Query, id, std::move(slice), BufferSlice(), dc_id, type, auth_flag,
gzip_flag, tl_constructor);
query->set_cancellation_token(query.generation());
return query;
}
} // namespace td