Passkey Idiom

如果出于某些目的希望将某个类的构造函数设置为 private,并提供工厂函数 Make() 创建最终对象;工厂函数中通常会使用 std::make_unique() 或者 std::make_shared() 来创建由对应智能指针托管的对象。

Read More

Golang's Options Pattern

可以将 Golang 的 Options Pattern 视作(有副作用)函数式版的 _Builder Pattern_,其核心是:特定的 option-function 调用会生成对应的类型为 Option 的闭包,执行闭包会修改内部的 Options 结构。

Golang 的函数支持同一类型的不定参数,因此上面的闭包类型一致。

Read More

保持 ASIO io_context 无任务时运行

ASIO 的 io_context::run() 如果发现没有 pending 的任务就会返回,对于 server 的监听线程来说这是符合常理的,因为无论如何至少有个 acceptor::async_accept() 在 pending。

Read More

atoi With Overflow Handled

leetcode 上有一题是让你实现一个 atoi(),但是因为函数类型是 32-bit int,所以可以直接内部转换到 64-bit int,避免需要直接处理溢出的情况。

如果要针对 int64 实现一个 atoi() 又该如何做?

Read More

Allow Connections From LAN for Trojan-qt5

因为众所周知的原因,机场的服务商把协议从 SS 切换到了 Trojan。但是之前的 SS windows 客户端只支持 SS 协议,所以切换后只能换 Trojan-qt5 作为客户端。

但是这个客户端做的实在不怎么样,作者似乎是在原来的 ss-qt5 的基础上做的修改,集成了 libtrojan;以至于之前 SS-Windows 用的好好的 Allow Connections From LAN 功能到这里没法用了。

Read More

Randomly Generate Base62 for URL Shortening

Last week I wrote a post about how to design an URL shortening service, like TinyURL, and came up with 2 strategies to encode an URL, and one of which is to randomly generate base64 sequence.

Read More

How To Design a URL Shortening Service

1. Encoding Actual URL

The path part, which we would call it key, of an encoded URL can consist of 6 ~ 8 digits in base62, up to desired uniqueness rate.

Randomly Generated

We can randomly generate those digits each within the range [0, 61].

Then we must check if the generated key is unique by consulting our key storage.

Aside: this checking process can be optimized with data structures like bloom-filter, provided we have to deal hundres of million records.

If we are unlucky, we may have a key collision; in this case, just re-generate another key until its unique.

To make encoding more efficient, we can have a standalone Key Generation Service(KGS) that generates those random key beforehand, and store them.

Read More