Skip to content

Commit 219ba9c

Browse files
committed
Optimize is_reserved_ipv4.
1 parent 027780b commit 219ba9c

1 file changed

Lines changed: 23 additions & 11 deletions

File tree

‎tdutils/td/utils/port/IPAddress.cpp‎

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -224,19 +224,30 @@ static bool is_reserved_ipv4(uint32 ip) {
224224
const char *ip;
225225
int mask;
226226
};
227-
auto is_in_block = [ip](const IpBlock &block) {
228-
IPAddress block_ip_address;
229-
block_ip_address.init_ipv4_port(CSlice(block.ip), 80).ensure();
230-
uint32 range = block_ip_address.get_ipv4();
231-
CHECK(block.mask != 0);
232-
uint32 mask = std::numeric_limits<uint32>::max() >> (32 - block.mask) << (32 - block.mask);
233-
return (ip & mask) == (range & mask);
227+
struct IpRange {
228+
uint32 range;
229+
uint32 mask;
230+
};
231+
auto get_ranges = [](const auto &blocks) {
232+
vector<IpRange> ranges;
233+
for (auto &block : blocks) {
234+
IPAddress block_ip_address;
235+
block_ip_address.init_ipv4_port(CSlice(block.ip), 80).ensure();
236+
CHECK(block.mask != 0);
237+
uint32 mask = std::numeric_limits<uint32>::max() >> (32 - block.mask) << (32 - block.mask);
238+
ranges.push_back(IpRange{block_ip_address.get_ipv4() & mask, mask});
239+
}
240+
return ranges;
241+
};
242+
auto is_in_range = [ip](const IpRange &range) {
243+
return (ip & range.mask) == range.range;
234244
};
235245

236246
// globally reachable addresses from reserved blocks
237247
static const IpBlock global_blocks[] = {{"192.0.0.9", 32}, {"192.0.0.10", 32}};
238-
for (auto &block : global_blocks) {
239-
if (is_in_block(block)) {
248+
static const vector<IpRange> global_ranges = get_ranges(global_blocks);
249+
for (auto &range : global_ranges) {
250+
if (is_in_range(range)) {
240251
return false;
241252
}
242253
}
@@ -245,8 +256,9 @@ static bool is_reserved_ipv4(uint32 ip) {
245256
{"169.254.0.0", 16}, {"172.16.0.0", 12}, {"192.0.0.0", 24}, {"192.0.2.0", 24},
246257
{"192.88.99.0", 24}, {"192.168.0.0", 16}, {"198.18.0.0", 15}, {"198.51.100.0", 24},
247258
{"203.0.113.0", 24}, {"224.0.0.0", 3}};
248-
for (auto &block : blocks) {
249-
if (is_in_block(block)) {
259+
static const vector<IpRange> ranges = get_ranges(blocks);
260+
for (auto &range : ranges) {
261+
if (is_in_range(range)) {
250262
return true;
251263
}
252264
}

0 commit comments

Comments
 (0)