这本书(或者技术博客)记录了我在开发我自己感兴趣的应用的过程中的一些笔记,一方面也是督促自己把笔记写的更清晰、通俗易懂。

另外,单纯阅读大量文字很容易犯困,所以我会尽可能用代码或图表来传达。

如果你碰巧遇到了与我相同的问题,能帮到你再好不过,也非常欢迎你通过邮箱 1342347481@qq.com 联系我。

这本电子书是使用 mdBook 生成的,mdBook 是一个由 Rust 语言驱动的工具,能够根据 Markdown 文件制作出现代化的在线图书。 如果你感兴趣,可以去查看 用户指南

我的 GitHub 主页:github-mark Kymdon13

祝阅读愉快!

许可协议

本文采用 CC BY-NC 4.0 许可协议授权。

你可以:

  • 在非商业目的下,自由传播、修改、改编、或基于本作品进行创作,并可采用任何媒介与形式。

但你必须:

  • 给出适当署名,注明作品来源。

This book is about my experience building applications I'm interested in (Web APP, CLI APP, etc.). There are problems I ran into and solved and those I didn't, and I like taking notes out of it.

In the mean while, watching a whole bunch of words is quite frustrating, so I will try to use code or diagram to explain the idea if possible.

If you happen to encounter the same problem as I did, I'm glad that I can help. You are very welcome to disturb me at 1342347481@qq.com.

This e-book is generated by mdBook, which is powered by Rust. The mdBook is a utility to create modern online books from Markdown files (taken from its official GitHub repository). If you are interested in it, go check the User Guide.

My GitHub Homepage: github-mark Kymdon13.

Have a good time reading.

License

This work is licensed under the CC BY-NC 4.0.

You are free to:

  • Distribute, remix, adapt, and build upon the material in any medium or format for noncommercial purposes only.

You have to:

  • Give credit to the creator.

ace.js

If you want to add a new language in the backend and get the auto completion feature for this language, you just have to copy the mode-<language>.js file from ace/src-min-nonconflict (download it yourself on GitHub for the build version, I'm using ace-builds-1.5.0) to js/ and add it to the book.toml:

additional-js = [
    "js/mode-<language>.js",
]

and index.hbs:

<script src="{{ resource "js/mode-<language>.js" }}"></script>

Note that you must remove the original code in index.hbs because we are adding them all by hand:

{{#each additional_js}}
<script src="{{ resource this }}"></script>
{{/each}}

highlight.js

For language support add the all-languages.min.js to the js/, book.toml and index.hbs.

Tht all-languages.min.js is obtained by concat all js in https://github.com/highlightjs/cdn-release/tree/11.11.1/build/languages:

cat $(find ./languages -maxdepth 1 -type f ! -name 'all-languages.min.js') > all-languages.min.js

Some examples

bash:

some=hhh
if [ -n dir ]; do
    echo ${some}
fi

python:

for i in range(1,20):
    while i < 10:
        print(123)

mdBook features

classList of code block

If you create a code block like:

```cpp
int main() {}
```

then in the HTML mdBook generates, there will be a code element:

<code class="language-cpp ...">...</code>

Grammar

We can write like:

[link1](#link)

it will be rendered as: link1.

or we could write like:

[link2](#editable-code)

rendered as: link2.

As you can see, the H3 header as Editable Code is given the link editable-code after mdBook rendered it to HTML.

Actually, the rules are:

  • keep the -;
  • convert uppercase letters to lowercase;
  • convert single or multi "space" to -;
  • delete all & , . ? ! : ; * ^ % ( ).

Let's say we have a header like:

&,.?!:;*^%()Complex Header

and the actual link is:

[link3](#complex-header)

rendered as: link3

中文 标题
[中文链接](#中文-标题)

rendered as: 中文链接

Format

The format features of mdBook you can use.

Code

For code format, go check this chapter: CPP Playground.

Mermaid

graph TD;
    A-->B;
    A-->C;
    B-->D;
    C-->D;

Including Files

This is src/SUMMARY.md in my mdBook project, and I just use:

{{#include ./SUMMARY.md}}

in this md file to include it, it will be rendered as:

# Summary

[README](./readme.md)

[Tips](./tips.md)

---

# My MarkDown

- [RabbitMQ 交换机类型](./rabbitmq.md)

- [CMake](./cmake/cmake.md)
    - [CMake 模块和包](./cmake/cmake-module.md)
    - [如何创建一个可安装的 CMake 包](./cmake/how-to-create-installable-cmake-project.md)

- [gRPC](./grpc/grpc.md)
    - [gRPC 中的 CompletionQueue 模型](./grpc/cq-model.md)

- [CPP Playground](./cpp-playground.md)

- [Custom Playground](./custom-playground.md)

---

[© CC BY-NC 4.0](./license)

Math

Inline

Inline equations must use \\( and \\):

\\( \int x dx = \frac{x^2}{2} + C \\)

and this will be rendered as: \( \int x dx = \frac{x^2}{2} + C \).

Block

Block equations must use \\[ and \\]:

\\[ \mu = \frac{1}{N} \sum_{i=0} x_i \\]

and this will be rendered as:

\[ \mu = \frac{1}{N} \sum_{i=0} x_i \]

RabbitMQ 有几种常用的交换机类型:

  • fanout 交换机(广播)
  • direct 交换机(单播)
  • topic 交换机(多播)

下面我们用几张流程图展示这几种类型。

fanout 交换机(广播)

fanout 模式的交换机:将消息复制成 n 份(n 为队列数量),然后分发给所有队列。

graph TD
    P((P)) --> fanout{fanout}

    fanout --> Q1
    fanout --> Q2
    fanout --> ...
    fanout --> Qn

direct 交换机(单播)

direct 模式的交换机:发布消息时根据 routing_key 转发给对应的队列。

graph TD
    P((P)) --> direct{direct}

    direct -- info --> Q1[Q1]
    Q1 --> C1((C1))

    direct -- info --> Q2[Q2]
    direct -- warn --> Q2
    Q2 --> C2((C2))

这里如果 P 发送一个 routing_key=info 的消息:

  • direct 交换机会把消息复制为 2 份发给 Q1Q2

如果 P 发送一个 routing_key=warn 的消息:

  • direct 交换机只会发给 Q2

如果 P 发送一个 routing_key=error 的消息:

  • direct 交换机没找到匹配的队列,丢弃该消息。

注意一个队列只能绑定一个同名的 routing_key,例如假设 Q1 绑定了两次 info,第二次绑定是无效的。也就是说,复制操作只发生在队列之间,不会对同一个队列复制消息

topic 交换机(多播)

topic 模式的交换机:在 direct 模式的 routing_key 中加入了通配符,会复制并转发给匹配的所有队列。

其中,* 匹配 1 个单词,# 匹配 0 个或多个单词,. 用于分隔不同单词。

graph TD
    P((P)) --> topic{topic}

    topic -- lazy.# --> Q1[Q1]
    Q1 --> C1((C1))

    topic -- \*.big.\* --> Q2[Q2]
    topic -- \*.\*.dog --> Q2
    Q2 --> C2((C2))

如果 P 发送 lazylazy.

  • 只有 Q1 会收到消息。

如果 P 发送 lazy.big.cat

  • Q1Q2 都会收到消息。

如果 P 发送 normal.big.dog

  • 只有 Q2 会收到,而且只会收到一次。

混合模式

你可以混合上述 3 种模式形成自定义的消息转发网络。

graph TD
    P((P)) --> fanout{fanout}
    P((P)) --> direct{direct}

    P((P)) --> topic{topic}

    fanout --> Q1
    fanout --> Q2

    direct -- orange --> Q1[Q1]
    Q1 --> C1((C1))

    direct -- black --> Q2[Q2]
    direct -- green --> Q2
    Q2 --> C2((C2))

    topic -- lazy.# --> Q2
    topic -- \*.big.\* --> Q3[Q3]
    topic -- \*.\*.dog --> Q3
    Q3 --> C3((C3))

负载均衡

负载均衡一般发生在消费者端:

graph TD
    P((P)) --> direct{direct}

    direct -- info --> Q1[Q1]
    Q1 -- busy --> C1((C1))
    Q1 -- busy --> C2((C1))
    Q1 -- idle --> C3((C3))

    direct -- info --> Q2[Q2]
    direct -- warn --> Q2
    Q2 -- idle --> C4((C4))

上图中,队列 Q1 有 3 个消费者分摊任务负载。

CMake 使用手册(部分)。

include()

在 cmake 中引入模块就相当于在 C++ 的引入头文件,通常用于引入一些工具模块

例如,我们在工作目录下创建一个 cmake 目录,里面专门放一些辅助我们编写 CMakeLists.txt 的工具宏:

.
├── build/
├── cmake/
├── CMakeLists.txt
└── src/

然后我们创建一个 utils.cmake,里面定义了一个宏:

# utils.cmake
function(my_custom_function)
    message(STATUS "This is a custom function!")
endfunction()

include() 引入这个模块后,我们就可以在 CMakeLists.txt 中使用这个宏:

include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/utils.cmake)
my_custom_function() # 输出:This is a custom function!

作用域

上面提到,include() 引入模块就像 C++ 引入头文件,cmake 在运行时遇到 include() 就直接加载对应文件,相当于在调用处直接插入代码,所以模块不会有自己的作用域。

例如,我们定义一个 cmake/set.cmake

set(VAR 123)

然后我们在主 CMakeLists.txt 引入这个包:

include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/set.cmake)
message(${VAR}) # 输出:123,这个变量是set.cmake新建的

include() 的搜索路径

include() 的搜索顺序是:

  • 首先搜索 CMAKE_MODULE_PATH
  • 再搜索 cmake 的默认模块路径,一般是 cmake 安装目录下的 Modules 目录(我的是 /usr/share/cmake-3.16/Modules)。
自定义搜索路径

如果你想设置 include() 的搜索路径,可以这样写:

set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "/path/to/modules1")
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "/path/to/modules2")

每个路径会自动以 ; 分隔:CMAKE_MODULE_PATH = /path/to/modules1;/path/to/modules2

注意:如果你用上面的方法设置了 CMAKE_MODULE_PATH,那么引入时不要加后缀 .cmakeinclude(module_name),不然会找不到。

find_package()

find_package() 有两种主要工作模式:Module Mode 和 Config Mode。

Module Mode(模块模式)

该模式下 find_package() 会匹配名为 Find<PackageName>.cmake 的文件。

搜索路径

搜索路径和 include() 一样:

  • 首先搜索 CMAKE_MODULE_PATH
  • 再搜索 cmake 的默认模块路径,一般是 cmake 安装目录下的 Modules 目录(我的是 /usr/share/cmake-3.16/Modules)。

但是注意,这里要匹配的是 Find<PackageName>.cmake,例如:

find_package(set REQUIRED) # 只能匹配 "Findset.cmake"
主要用途

Find<PackageName>.cmake 文件通常是由 CMake 官方或者社区编写的脚本,用来猜测探测系统上可能安装了哪些版本的库、库文件在哪里、头文件在哪里等等

这种模式是为那些没有提供自己 CMake 配置文件的库准备的,所以要靠 cmake 自己去猜它们在哪里。

Config Mode(配置模式)

该模式下会匹配 <PackageName>Config.cmake<packagename>-config.cmake

例如我们找一个不存在的包:

find_package(set CONFIG REQUIRED)
# 报错:
# Could not find a package configuration file provided by "set" with any of
# the following names:
# setConfig.cmake
# set-config.cmake
搜索路径

一般的搜索路径有:

  • /usr/lib/cmake/<PackageName>
  • /usr/share/cmake/<PackageName>
  • /usr/local/lib/cmake/<PackageName>
  • /usr/local/share/cmake/<PackageName>

你也可以通过设置 CMAKE_PREFIX_PATH 变量告诉 CMake 应该去哪找:

cmake -DCMAKE_INSTALL_PREFIX=/path/to/<PackageName>Config.cmake <path/to/CMakeLists.txt>
主要用途

<PackageName>Config.cmake 通常是库项目自身在安装时生成的,它们会告诉 cmake 库在哪里、头文件在哪里、依赖哪些其他库、提供了哪些 CMake 目标 (targets) 等等。

find_dependency()

find_package() 功能上相似,但是:

  • find_dependency() 是一个宏,好像主要用于主项目;
  • find_package() 是内置命令,好像主要用在模块的配置文件中。

为什么推荐使用 CONFIG 模式(如果库支持的话)?

  • 更准确和健壮: Config 文件是由库项目自身提供的,相比于 Find 模块的“猜测”,Config 模式更不容易出错。
  • 提供现代 CMake 目标: 使用 Config 模式找到的包通常会定义并导出 CMake 目标(比如 protobuf::libprotobuf, grpc::grpc++)。在 target_link_libraries() 中使用这些目标是链接库的现代、推荐方式。CMake 会自动处理链接所需的头文件路径、库文件路径以及其他依赖关系。

INTERFACE 和 IMPORTED 标志

在 CMake 中,add_library()add_executable() 命令用于定义构建目标。除了 STATIC (静态库)、SHARED (动态库)、MODULE (模块库) 和可执行文件这些类型外,还有一些特殊的标志或概念来描述目标的性质和使用方式。IMPORTEDINTERFACE 就是其中非常重要的两个。

INTERFACE(接口)

INTERFACE 可以用来描述两种情况:

INTERFACE 库目标(INTERFACE Library Target)

库目标定义

使用 add_library(<target_name> INTERFACE) 命令创建的库目标。

特点
  • 不生成任何构建输出文件,比如 .a, .so, .dll,只存在于构建系统中。
主要用途

用来分组和封装一组供其他目标使用的使用要求(Usage Requirements),其中使用要求包含:

  • 要包含的目录;
  • 要链接的其他库;
  • 要添加的编译定义(例如添加 #define)和编译选项。

如何使用:

target_include_directories(<target_name> INTERFACE ...)
target_link_libraries(<target_name> INTERFACE ...)
target_compile_definitions(<target_name> INTERFACE ...)
target_compile_options(<target_name> INTERFACE ...)

上面的命令可以为这个 INTERFACE 目标设置使用要求。

如何依赖:

其他目标(无论是静态库、动态库还是可执行文件)可以通过下面的命令来“链接”到这个 INTERFACE 目标。

target_link_libraries(<another_target> PUBLIC|PRIVATE|INTERFACE <target_name>)

这里的“链接”不是传统的二进制链接,而是表示 <another_target> 将继承 <target_name> 定义的所有 INTERFACE 使用要求。

应用示例

纯头文件库 (Header-Only Libraries):

比如很多现代 C++ 模板库。它们只有头文件,不需要编译成 .o 文件或库文件。你可以

# 定义目标
add_library(MyHeaderOnlyLib INTERFACE)

# 指定头文件路径
target_include_directories(MyHeaderOnlyLib INTERFACE ${MyHeaderOnlyLib_SOURCE_DIR}/include)

### 其他库只要写下面这个命令,它们的包含目录就会自动加上 MyHeaderOnlyLib 的头文件路径
target_link_libraries(<another_target> PUBLIC MyHeaderOnlyLib)

打包一组编译器标志或定义:

创建一个 INTERFACE 目标,为其设置一组特定的编译定义或选项,然后让需要这些选项的其他目标链接到它。

分组外部依赖:

创建一个 INTERFACE 目标来代表一个概念上的功能模块,然后用 target_link_libraries(<target_name> INTERFACE <dependency1> <dependency2> ...) 将其链接到多个实际的库目标。其他目标只需链接这个 INTERFACE 目标,就会自动链接到其所有依赖的库。

INTERFACE 属性(INTERFACE Properties)

除了用于定义 INTERFACE 库目标外,INTERFACE 关键字还用在:

  • target_include_directories
  • target_compile_definitions
  • target_link_libraries

例如:

target_include_directories(MyLib PUBLIC include PRIVATE src INTERFACE include/public_api)

表示:

  • PUBLIC includeMyLib 自身需要编译 include 目录下的文件,并且任何链接到 MyLib 的目标也需要这个包含路径。
  • PRIVATE srcMyLib 自身需要编译 src 目录下的文件,但这个路径不会传递给链接它的目标。
  • INTERFACE include/public_apiMyLib 自身不需要这个包含路径,但任何链接到 MyLib 的目标都需要这个包含路径。

IMPORTED(导入)

IMPORTED 标志用于描述那些不是由当前 CMake 项目构建,而是预先存在于系统上或由其他构建过程生成的目标。

定义

通常用下面的命令来定义一个导入目标。这里的 <type> 可以是 STATIC, SHARED, MODULE

add_library(<target_name> <type> IMPORTED)
add_executable(<target_name> IMPORTED)
主要用途

在当前 CMake 项目中创建一个对外部已存在二进制文件(库或可执行文件)的引用代理。这样当前项目就可以使用 CMake 的目标管理机制来链接和依赖这些外部二进制文件,就像它们是在当前项目中构建的一样。

应用示例

导入外部库时,通过 find_package(<PackageName> CONFIG ...) 命令加载的 <PackageName>Config.cmake 文件,会自动定义一个或多个 IMPORTED 目标。

这些由 find_package 创建的导入目标通常带有双冒号 :: (例如 Protobuf::libprotobuf, grpc::grpc++),表示这是一个别名或导入目标

在定义了导入目标后,需要设置它的位置以及使用要求。例如:

# 定义目标
add_library(<target_name> STATIC IMPORTED)

# 设置导入库的实际文件路径
SET_TARGET_PROPERTY(<target_name> IMPORTED_LOCATION /path/to/the/library/file)

# 设置链接该导入目标时需要添加的包含目录
SET_TARGET_PROPERTY(<target_name> INTERFACE_INCLUDE_DIRECTORIES /path/to/its/include/dir)

# 设置该导入目标本身依赖的其他库
SET_TARGET_PROPERTY(<target_name> IMPORTED_LINK_INTERFACE_LIBRARIES "dependency1;dependency2")

如何使用: 其他目标可以通过下面的命令,来链接这个 IMPORTED 目标。

# CMake 会根据导入目标的属性,自动添加正确的链接器标志、库路径和包含路径。
target_link_libraries(<another_target> PUBLIC|PRIVATE|INTERFACE <target_name>)

本文使用的 CMake 版本为:3.16.3;C/C++ 编译器为 clang-17


在我们需要使用第三方包时,我们需要:

当我们需要编写 CMake 可安装库时,我们需要:

  • install() 命令 配置安装流程,以及生成 *Config.cmake 文件供消费者(引用包的人)搜索包文件。

整体流程大概是:

graph TD
	cmake -- 生成 --> conf[配置文件] -- 读入配置 --> make
	make -- 生成 --> exe[可执行文件、库文件]
	conf -- 读入配置 --> install[cmake --install]
	exe -- 读取 --> install
	install -- 安装 --> targetdir[指定目录]
	targetdir -- 读取目录中的*Config.cmake --> consumer[消费者]
	consumer -- 通过*Config.cmake找到 --> exe

CMAKE_INSTALL_PREFIX 标志

CMAKE_INSTALL_PREFIX 是一个 CMake 变量,它定义了项目在执行安装(install)操作时,文件将被复制到的根目录。

什么时候设置和使用?

在命令行中设置

通常在 CMake 配置阶段(运行 cmake ... 命令时)通过命令行参数 -DCMAKE_INSTALL_PREFIX=<路径> 来设置。消费者可以指定他们希望软件安装到哪个目录下。 例如:

cmake -DCMAKE_INSTALL_PREFIX=/opt/myproject <path/to/CMakeLists.txt>

如果在配置时没有显式指定,CMake 会有一个默认值(通常是 /usr/local/usr,取决于系统和 CMake 版本)。

CMake 自动使用

在 CMakeLists.txt 中,用 install() 命令来定义哪些文件和目标需要安装,以及它们相对于 CMAKE_INSTALL_PREFIX 应该放在哪个子目录下。

在执行 make installcmake --install 命令时,CMake 会读取这些 install() 定义,并将相应的文件复制到 CMAKE_INSTALL_PREFIX 指定的路径下的正确位置。

CMAKE_PREFIX_PATH 标志

消费者在自己的 CMakeLists.txt 中加入:

list(APPEND CMAKE_PREFIX_PATH absolute/path/to/<Package>Config.cmake)

然后调用 find_package(<Package> REQUIRED) 就会在上述路径中搜索 <Package>Config.cmake 文件,该文件会收集包的必要信息。

install() 命令

install() 命令: 这是在 CMakeLists.txt 中定义安装规则的核心命令。它告诉 CMake 需要安装哪些文件、哪些目标,以及它们相对于 CMAKE_INSTALL_PREFIX 应该放在哪个目录下。

常用的 install() 用法包括:

# 安装 myexecutable 到 ${CMAKE_INSTALL_PREFIX}/bin
install(TARGETS myexecutable DESTINATION bin)
# 安装 mylibrary (动态或静态) 到 ${CMAKE_INSTALL_PREFIX}/lib
install(TARGETS mylibrary DESTINATION lib)

# 安装 myheader.h 到 ${CMAKE_INSTALL_PREFIX}/include
install(FILES include/myheader.h DESTINATION include)

# 安装 conf 目录下的所有内容到 ${CMAKE_INSTALL_PREFIX}/share/myproject/conf
install(DIRECTORY conf/ DESTINATION share/myproject/conf)

导出项目安装信息

我们还可以导出项目安装信息:

install(EXPORT <export-name> DESTINATION <相对路径> ...)

这个用于导出 CMake 目标信息,生成 .cmake 文件(如 *Config.cmake),使得其他 CMake 项目可以通过 find_package() 来找到并使用该项目。

这些导出的文件通常安装在:

${CMAKE_INSTALL_PREFIX}/lib/cmake/<ProjectName>
${CMAKE_INSTALL_PREFIX}/share/cmake/<ProjectName>

安装命令

在编译完成后,执行以下命令,会触发 CMake 的安装过程,根据 CMakeLists.txt 中定义的所有 install() 规则,将文件从构建目录复制或移动到 CMAKE_INSTALL_PREFIX 指定的安装目录下:

  • make install:如果用的是 Makefile 生成器。
  • cmake --install <构建目录>:这是更通用的方法,适用于所有 CMake 生成器。

应用示例

现在我们创建一个目录结构如下:

Apple/
├── CMakeLists.txt
├── install
├── src
│   ├── Apple.cc
│   ├── Apple.h
│   └── CMakeLists.txt
└── test
    ├── CMakeLists.txt
    └── main.cc

在这个项目中,我们定义了一个 Apple 类,这个类依赖于 ZLIB

C++ 文件

// src/Apple.h
#include <iostream>
#include <string>
#include <vector>

class Apple {
public:
    Apple(std::string data);
    ~Apple();
    std::string data();
    std::vector<unsigned char> zippedString();

private:
    std::string data_;
};
// src/Apple.cc
#include "Apple.h"

#include <zlib.h>

#include <iostream>
#include <string>
#include <vector>

Apple::Apple(std::string data) : data_(data) {
    std::cout << "Apple constructor called" << std::endl;
}

Apple::~Apple() {
    std::cout << "Apple destructor called" << std::endl;
}

std::string Apple::data() {
    return data_;
}

std::vector<unsigned char> Apple::zippedString() {
    uLong srcLen = data_.size();
    uLong destLen = compressBound(srcLen);
    std::vector<unsigned char> out;
    out.resize(destLen);

    // Compress the string
    int res = compress(out.data(), &destLen, reinterpret_cast<const Bytef *>(data_.data()), srcLen);
    if (res != Z_OK)
    {
        std::cerr << "compress() failed with code " << res << std::endl;
    }

    out.resize(destLen); // trim unused space
    return out;
}
// test/main.cc
#include "Apple.h"

#include <iostream>
#include <vector>

int main() {
    Apple apple("Hello, World!");
    std::cout << "Apple data: " << apple.data() << std::endl;

    for (auto byte : apple.zippedString()) {
        std::cout << byte;
    }
    std::cout << std::endl;
}

CMakeLists.txt

然后是主目录、test 目录、src 目录下的 CMakeLists.txt

# ./CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(Apple VERSION 0.1.0)

set(CMAKE_C_COMPILER clang) # set C compiler
set(CMAKE_CXX_COMPILER clang++) # set C++ compiler
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) # set runtime output dir

add_compile_options(-stdlib=libc++) # set compile options
add_link_options(-stdlib=libc++ -lc++ -lc++abi -fuse-ld=lld) # set link options

add_subdirectory(test)
add_subdirectory(src)
# test/CMakeLists.txt
add_executable(main main.cc)
target_link_libraries(main PRIVATE Apple)
# src/CMakeLists.txt

# 定义一个库目标
file(GLOB LIB_SRC *.cc)
add_library(Apple SHARED ${LIB_SRC})
set(Apple_INSTALL_CMAKEDIR cmake/mylib)

# 定义库的公共包含目录(接口属性 INSTALL_INTERFACE 会被导出)
target_include_directories(Apple
    PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
        $<INSTALL_INTERFACE:include>
    PRIVATE
        src
)

# 定义库的接口链接依赖(例如依赖第三方库)
find_package(ZLIB REQUIRED)
target_link_libraries(Apple PUBLIC ZLIB::ZLIB)

# --- 安装实际的目标文件 ---
install(DIRECTORY include/
    DESTINATION include
    FILES_MATCHING PATTERN "*.h"
    PATTERN ".svn" EXCLUDE
)

# 安装库文件到 ${CMAKE_INSTALL_PREFIX}/lib
set(TARGETS_EXPORT_NAME AppleTargets)
install(TARGETS Apple
    DESTINATION lib
    EXPORT ${TARGETS_EXPORT_NAME}
)

# --- 生成并安装导出文件 ---
install(EXPORT ${TARGETS_EXPORT_NAME}
    DESTINATION ${Apple_INSTALL_CMAKEDIR}
    NAMESPACE mylib::
)

# 生成并安装 Package Configuration 文件
include(CMakePackageConfigHelpers)
# 生成 AppleConfig.cmake 到构建目录
configure_package_config_file(
    ${PROJECT_SOURCE_DIR}/cmake/${PROJECT_NAME}Config.cmake.in
    ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake
    INSTALL_DESTINATION ${Apple_INSTALL_CMAKEDIR}
)
# 生成 *ConfigVersion.cmake 到构建目录
write_basic_package_version_file(
    ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake
    VERSION ${PROJECT_VERSION}
    COMPATIBILITY AnyNewerVersion
)
# 将构建目录中的 *Config.cmake 等文件安装到指定路径
install(FILES
    ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake
    ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake
    DESTINATION ${Apple_INSTALL_CMAKEDIR}
)

CMake 模板文件

此外,我们还需要为 AppleConfig.cmake 写一个模板文件 AppleConfig.cmake.in

@PACKAGE_INIT@

# 查找依赖
include(CMakeFindDependencyMacro) # find_dependency() 宏需要这个模块
find_dependency(ZLIB REQUIRED)

# 包含版本文件
include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@ConfigVersion.cmake")

# 包含由 install(EXPORT ...) 生成的目标文件
include("${CMAKE_CURRENT_LIST_DIR}/@TARGETS_EXPORT_NAME@.cmake")

# 标记 Package 已找到
set(@PROJECT_NAME@_FOUND TRUE)

接下来就可以进行构建了。

有几点注意事项:

  • 模板文件中的占位符 @TARGETS_EXPORT_NAME@ 是我们自定义的,在 src/CMakeLists.txt 中创建;
  • 对于库的每一个依赖(本库只用了 ZLIB 一个依赖)需要在模板文件中用 find_dependency() 收集包的信息。

另外,AppleConfig.cmake 其实就是 configure_package_config_file()AppleConfig.cmake.in 中的 @@ 占位符全部展开后生成的。

构建

Apple 目录下执行(这里路径替换为你的 install 目录绝对路径):

rm -rf build/
mkdir build && cd build
cmake .. -DCMAKE_INSTALL_PREFIX=/path/to/Apple/install

安装

Apple/build 目录下执行:

cmake --install .

安装完成后,我们应该能看到:

Apple/install/
├── cmake
│   └── mylib
│       ├── AppleConfig.cmake
│       ├── AppleConfigVersion.cmake
│       ├── AppleTargets.cmake
│       └── AppleTargets-noconfig.cmake
├── include
│   └── Apple.h
└── lib
    └── libApple.so

其中:

  • Apple.h 暴露类声明给消费者,用于编译;
  • libApple.so 为类的实际实现,用于链接;
  • cmake 目录下是用于搜索包的 CMake 脚本。

消费者怎么使用 Apple 库

我们创建一个 Peach 目录,并写入以下文件:

Peach/
├── CMakeLists.txt
└── test
    ├── CMakeLists.txt
    └── main.cc

其中 main.cc 和 Apple 中的 main.cc 完全一样。

主目录、test 目录下的 CMakeLists.txt

# ./CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(Peach VERSION 0.1.0)

set(CMAKE_C_COMPILER clang) # set C compiler
set(CMAKE_CXX_COMPILER clang++) # set C++ compiler
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) # set runtime output dir

add_compile_options(-stdlib=libc++) # set compile options
add_link_options(-stdlib=libc++ -lc++ -lc++abi -fuse-ld=lld) # set link options

list(APPEND CMAKE_PREFIX_PATH "~/Apple/install/cmake/mylib")
find_package(Apple REQUIRED)

add_subdirectory(test)
# test/CMakeLists.txt
add_executable(main main.cc)
target_link_libraries(main PRIVATE mylib::Apple)

OK,现在我们创建并进入 Peach/build 目录然后执行:

cmake ..
make # 成功输出可执行文件 main

总结

至此,我们已经实现了 Apple 的安装:

  • 创建一个名为 Apple 的库(add_library());
  • 利用 install(...) 将头文件目录、库文件安装(其实就是复制)到自定义目录下(Apple/install);
  • 通过 target_include_directories($<INSTALL_INTERFACE:include>) 导出头文件目录的相对路径(相对于 CMAKE_INSTALL_PREFIX)到 *Targets.cmake
  • 利用 install(EXPORT ...) 导出 *Targets.cmake 到 CMake 的安装路径,并设置命名空间为 mylib::
  • 利用 CMake 宏生成 *Config.cmake*ConfigVersion.cmake 等收集包信息并验证包可用性的 CMake 脚本;

以及消费者的使用:

  • 安装完成后,消费者通过 find_package() 引入 Apple 库;
  • 并通过 target_link_libraries()mylib::Apple 链接到可执行文件。

你可以动手尝试一下(这个仓库里有更详细的 CMake 注释):如何创建一个可安装 CMake 包

gRPC 从入门到放弃。

本文使用的是 gRPC v1.71.0。使用的是官方的 grpc/examples/cpp/helloworld 中的示例。

gRPC 有 2 种异步模型,一个是 Callback API,还有一个就是 CompletionQueue API。

CompletionQueue 是什么

我们可以将 CompletionQueue 等效为一个由 gRPC 管理的消息队列,一个基本的服务端模型如下图所示(简略版):

sequenceDiagram
	ServerImpl.HandleRpcs()->>cd1: new CallData()
	cd1->>cd1.Proceed(): cd1.status_ = CREATE
	cd1.Proceed()->>service_.RequestSayHello(): register cd1 to service_
	loop Forever
		ServerImpl.HandleRpcs()->>cq_.Next(): block here and waiting for request
		cq_.Next()->>ServerImpl.HandleRpcs(): a request coming in, return it
		ServerImpl.HandleRpcs()->>cd1.Proceed(): process the request, cd1.status_ = PROCESS
		cd1.Proceed()->>cd2: create a new CallData cd2
        cd2->>cd2.Proceed(): cd2.status_ = CREATE
        cd2.Proceed()->>service_.RequestSayHello(): register cd2 to service_
		cd1.Proceed()->>responder_.Finish(): prepare the reply and call the Async Finish()
		responder_.Finish()->>cd1.Proceed(): status = FINISH
        cd1.Proceed()->>cd1: delete cd1
        ServerImpl.HandleRpcs()->>cq_.Next(): block here and waiting for request
		cq_.Next()->>ServerImpl.HandleRpcs(): a request coming in, return it
		ServerImpl.HandleRpcs()->>cd2.Proceed(): process the request, cd2.status_ = PROCESS
		cd2.Proceed()->>cd3: create a new CallData cd3...
	end

在服务器启动后(ServerImpl.Run() 调用 ServerImpl.HandleRpcs() 进入循环),通过不断生成 CallData 实例来处理数据。

service_ 指的是 AsyncService 实例。

这里的 cd1cd2 等仅用于指代不同的 CallData 实例,实际上我们并不会在 HandleRpcs() 中保存 new 出来的 CallData 实例,而是直接将其注册到 AsyncService 由 gRPC 来接管。

对应的客户端模型:

sequenceDiagram
	SayHello()->>stub_.AsyncSayHello(): send Async request
	SayHello()->>rpc.Finish(): regi
	cd1->>cd1.Proceed(): cd1.status_ = CREATE
	cd1.Proceed()->>service_.RequestSayHello(): register cd1 to service_
    ServerImpl.HandleRpcs()->>cq_.Next(): block here and waiting for request
    cq_.Next()->>ServerImpl.HandleRpcs(): a request coming in, return it

如何实现线程池

在 gRPC 中,我们将多个 CQ(CompletionQueue)注册到 service_ 之后,当有新的请求到达时,gRPC 会自行决定将这个请求投递到哪一个 CQ。

知道了这一点,我们只需要创建 N 个 CQ 和 N 个线程,每个线程负责一个 CQ,当有新的请求到达一个线程自己的 CQ 时,处理这个请求的资源(CallData 实例)都在这个线程的栈上,不会造成数据竞争。

这里我们以一个拥有 2 个线程的线程池为例,并且分别创建 2 个 CQ:cq1_cq2_

sequenceDiagram
	par thread1
        ServerImpl.HandleRpcs()->>cd1_q1: new CallData()
        cd1_q1->>cd1_q1.Proceed(): cd1_q1.status_ = CREATE
        cd1_q1.Proceed()->>service_.RequestSayHello(): register cd1_q1 to service_
	loop Forever
		ServerImpl.HandleRpcs()->>cq1_.Next(): block here and waiting for request
		cq1_.Next()->>ServerImpl.HandleRpcs(): a request coming in, return it
		ServerImpl.HandleRpcs()->>cd1_q1.Proceed(): process the request, cd1_q1.status_ = PROCESS
		cd1_q1.Proceed()->>cd2_q1: create a new CallData cd2_q1
        cd2_q1->>cd2_q1.Proceed(): cd2_q1.status_ = CREATE
        cd2_q1.Proceed()->>service_.RequestSayHello(): register cd2_q1 to service_
		cd1_q1.Proceed()->>responder_.Finish(): prepare the reply and call the Async Finish()
		responder_.Finish()->>cd1_q1.Proceed(): status = FINISH
        cd1_q1.Proceed()->>cd1_q1: delete cd1_q1
	end
	and thread2
        ServerImpl.HandleRpcs()->>cd1_q2: new CallData()
        cd1_q2->>cd1_q2.Proceed(): cd1_q2.status_ = CREATE
        cd1_q2.Proceed()->>service_.RequestSayHello(): register cd1_q2 to service_
    end
    loop Forever
		ServerImpl.HandleRpcs()->>cq2_.Next(): block here and waiting for request
		cq2_.Next()->>ServerImpl.HandleRpcs(): a request coming in, return it
		ServerImpl.HandleRpcs()->>cd1_q2.Proceed(): process the request, cd1_q2.status_ = PROCESS
		cd1_q2.Proceed()->>cd2_q2: create a new CallData cd2_q2
        cd2_q2->>cd2_q2.Proceed(): cd2_q2.status_ = CREATE
        cd2_q2.Proceed()->>service_.RequestSayHello(): register cd2_q2 to service_
		cd1_q2.Proceed()->>responder_.Finish(): prepare the reply and call the Async Finish()
		responder_.Finish()->>cd1_q2.Proceed(): status = FINISH
        cd1_q2.Proceed()->>cd1_q2: delete cd1_q2
	end

可以看到,2 个线程分别调用 cq1_.Next()cq2_.Next() 来获取请求,并分别进入各自的工作流程,互不干扰。

Runnable code block

Add run tag to the language declaration of the code block to enable running:

```cpp, run
#include <iostream>
int main() {
    std::cout << "good" << std::endl;
    std::cout << "hello from cpp!" << std::endl;
    return 0;
}
```

rendered as:

#include <iostream>
int main() {
    std::cout << "good" << std::endl;
    std::cout << "hello from cpp!" << std::endl;
    return 0;
}

Editable code

Add editable to enable editing:

```cpp, editable, run
#include <iostream>
int main() {
    std::cout << "hello from cpp!" << std::endl;
    return 0;
}
```

rendered as:

#include <iostream>
int main() {
    std::cout << "hello from cpp!" << std::endl;
    return 0;
}

or you prefer rust:

fn main() {
    let number = 5;
    print!("{}", number);
}

Hide lines in code block

Sometimes we just want the reader to focus on the important part of the code.

Note:

  • Editable code blocks can not use this feature.

Rust

In rust, we can use # at the beginning of the line to automatically ignore that line:

```rust
# #![allow(unused)]
# fn main() {
println!("Hello, World!");
# }
```

rendered as:

#![allow(unused)]
fn main() {
println!("Hello, World!");
}

C++

In C++, we use ~ (note that there is a space after ~) at the beginning of the line to automatically ignore that line:

```cpp
~ #include <iostream>
~ int main() {
std::cout << "hello from cpp with hidden lines!" << std::endl;
~ return 0;
~ }
```
#include <iostream>
int main() {
std::cout << "hello from cpp with hidden lines!" << std::endl;
return 0;
}

Edition

Edition in the language identifier is used to specify which C++ standard you want to use for the compiler (default is C++11).

You can use:

```cpp, run, edition17
#include <iostream>
#include <string>
#include <optional>
int main() {
    std::optional<std::string> maybeName;
    maybeName = "Tom";
    if (maybeName) {
        std::cout << "Optional has value: " << *maybeName << "\n";
    }
    return 0;
}
```

to specify the standard as C++17, and it will be rendered as:

#include <iostream>
#include <string>
#include <optional>
int main() {
    std::optional<std::string> maybeName;
    maybeName = "Tom";
    if (maybeName) {
        std::cout << "Optional has value: " << *maybeName << "\n";
    }
    return 0;
}

and if you use C++11, it is expected that you see some compile error:

#include <iostream>
#include <string>
#include <optional>
int main() {
    std::optional<std::string> maybeName;
    maybeName = "Tom";
    if (maybeName) {
        std::cout << "Optional has value: " << *maybeName << "\n";
    }
    return 0;
}

Exception

There are some exceptions you might run into:

Timeout

The time limit is set to 2 seconds of each process.

So this is ok:

#include <unistd.h>
int main() {
    sleep(1);
    return 0;
}

while this is not:

#include <unistd.h>
int main() {
    sleep(2);
    return 0;
}

Out of memory

The heap memory limit is set to 20 MiB.

So this is not ok:

#include <vector>
int main() {
    // int is 4 bytes on the server
    std::vector<int> vec = std::vector<int>(5 * 1024 * 1024);
    return 0;
}

Actually, std::vector<int>(4 * 1024 * 1024); also not working, though I don't know why. I use the setrlimit in the <sys/resource.h> to set the limit, maybe there is some soft limit & hard limit thing?

Privilege violation

There is a limit to restrict you from directly manipulating the OS.

This is not ok:

#include <cstdlib>
int main() {
    system("ls");
    return 0;
}

This tutorial is at GitHub, I just copied it, and it works for me.

Custom Playground

By default, mdBook supports playground for Rust only. If you want to add playground for another language, you can do it by overriding script through theme customization.

In this section, we will try to add a playground for the imaginary example language.

Add playground option to code blocks in the book

playground option is not officially supported. It is used to mark the code block should be translated to playground code block by JavaScript.

```example,playground
Example Language Code
```

editable option can be used like below:

```example,playground,editable
Example Language Code
```

Modify book.js

book.js can be modified through theme customization.

Remove the access to play.rust-lang.org

If there are playgrounds in the page, book.js will try to fetch crates list from play.rust-lang.org. So you shoud remove the following codes.

var playgrounds = Array.from(document.querySelectorAll(".playground"));
if (playgrounds.length > 0) {
    fetch_with_timeout("https://play.rust-lang.org/meta/crates", {
        headers: {
            'Content-Type': "application/json",
        },
        method: 'POST',
        mode: 'cors',
    })
    .then(response => response.json())
    .then(response => {
        // get list of crates available in the rust playground
        let playground_crates = response.crates.map(item => item["id"]);
        playgrounds.forEach(block => handle_crate_list_update(block, playground_crates));
    });
}

Modify run_rust_code function

If a play button is pushed, run_rust_code function will be called to get the result of the playground. So you should modify the function for your language.

function run_rust_code(code_block) {
    var result_block = code_block.querySelector(".result");
    if (!result_block) {
        result_block = document.createElement('code');
        // If the result should be syntax highlighted,
        // `language-bash` should be modified to the appropriate language.
        result_block.className = 'result hljs language-bash';

        code_block.append(result_block);
    }

    let text = playground_text(code_block);

    // Add function to get result of the playground
    result_block.innerText = example_language_run(text);

    // If the result should be syntax highlighted, enable the following code.
    //hljs.highlightBlock(result_block);
}

Add code for code block transformation

The following code transforms code blocks which have playground option to playground code blocks.

// Add <pre class="playground"> to playground codeblock
Array.from(document.querySelectorAll(".playground")).forEach((element) => {
    let parent = element.parentNode;
    let wrapper = document.createElement('pre');
    wrapper.className = 'playground';
    element.classList.remove('playground');
    // set the wrapper as child (instead of the element)
    parent.replaceChild(wrapper, element);
    // set element as child of wrapper
    wrapper.appendChild(element);
});

This should be executed before other processes of codeSnippets function. For example, the code should be inserted to the following point.

// Insert the above code

// Syntax highlighting Configuration
hljs.configure({
    tabReplace: '    ', // 4 spaces
    languages: [],      // Languages used for auto-detection
});

let code_nodes = Array
    .from(document.querySelectorAll('code'))
    // Don't highlight `inline code` blocks in headers.
    .filter(function (node) {return !node.parentElement.classList.contains("header"); });

Tweak for editable code blocks

If the code block is editable, the syntax highlight is executed by editor. So the normal highlight mechanism should be disabled to avoid conflict.

This is achieved by the following code.

// language-rust class needs to be removed for editable
// blocks or highlightjs will capture events
code_nodes
    .filter(function (node) {return node.classList.contains("editable"); })
    .forEach(function (block) { block.classList.remove('language-rust'); });

The language name shoud be changed to language-example.

// language-rust class needs to be removed for editable
// blocks or highlightjs will capture events
code_nodes
    .filter(function (node) {return node.classList.contains("editable"); })
    .forEach(function (block) { block.classList.remove('language-example'); });

Prepare syntax highlighting

highlight.js and Ace are used for syntax highlighting. If the code block is editable, Ace is used, and if not highlight.js is used. So a syntax definition of example language should be prepared for each library.

You can get the following JavaScript codes by following each library's document.

  • highlight.js: build/highlight.min.js
  • Ace: build/src-min-noconflict/mode-example.js

highlight.js can be overridden by theme. So the build/highlight.min.js should be moved to theme/highlight.js in the project. mode-example.js shoud be moved to the project root because it is not overridable.

Modify editor.js

The language configuration of Ace editor is set at editor.js. This script can't be customized through theme. So you should copy editor.js from the generated book directory to the project root. The copied file should be modified like below:

//editor.getSession().setMode("ace/mode/rust");
editor.getSession().setMode("ace/mode/example");

Set additional-js

You should add editor.js and mode-example.js to additional-js field of book.toml.

[output.html]
additional-js = [
    "mode-example.js",
    "editor.js",
]

Directory structure

The final directory structure becomes below:

.
|-- book.toml
|-- editor.js
|-- mode-example.js
|-- src
`-- theme
    |-- book.js
    `-- highlight.js

Attribution-NonCommercial 4.0 International

=======================================================================

Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.

Using Creative Commons Public Licenses

Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.

 Considerations for licensors: Our public licenses are
 intended for use by those authorized to give the public
 permission to use material in ways otherwise restricted by
 copyright and certain other rights. Our licenses are
 irrevocable. Licensors should read and understand the terms
 and conditions of the license they choose before applying it.
 Licensors should also secure all rights necessary before
 applying our licenses so that the public can reuse the
 material as expected. Licensors should clearly mark any
 material not subject to the license. This includes other CC-
 licensed material, or material used under an exception or
 limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors

 Considerations for the public: By using one of our public
 licenses, a licensor grants the public permission to use the
 licensed material under specified terms and conditions. If
 the licensor's permission is not necessary for any reason--for
 example, because of any applicable exception or limitation to
 copyright--then that use is not regulated by the license. Our
 licenses grant only permissions under copyright and certain
 other rights that a licensor has authority to grant. Use of
 the licensed material may still be restricted for other
 reasons, including because others have copyright or other
 rights in the material. A licensor may make special requests,
 such as asking that all changes be marked or described.
 Although not required by our licenses, you are encouraged to
 respect those requests where reasonable. More considerations
 for the public:
wiki.creativecommons.org/Considerations_for_licensees

=======================================================================

Creative Commons Attribution-NonCommercial 4.0 International Public License

By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.

Section 1 -- Definitions.

a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.

b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.

c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.

e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.

f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.

g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.

h. Licensor means the individual(s) or entity(ies) granting rights under this Public License.

i. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.

j. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.

k. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.

l. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.

Section 2 -- Scope.

a. License grant.

   1. Subject to the terms and conditions of this Public License,
      the Licensor hereby grants You a worldwide, royalty-free,
      non-sublicensable, non-exclusive, irrevocable license to
      exercise the Licensed Rights in the Licensed Material to:

        a. reproduce and Share the Licensed Material, in whole or
           in part, for NonCommercial purposes only; and

        b. produce, reproduce, and Share Adapted Material for
           NonCommercial purposes only.

   2. Exceptions and Limitations. For the avoidance of doubt, where
      Exceptions and Limitations apply to Your use, this Public
      License does not apply, and You do not need to comply with
      its terms and conditions.

   3. Term. The term of this Public License is specified in Section
      6(a).

   4. Media and formats; technical modifications allowed. The
      Licensor authorizes You to exercise the Licensed Rights in
      all media and formats whether now known or hereafter created,
      and to make technical modifications necessary to do so. The
      Licensor waives and/or agrees not to assert any right or
      authority to forbid You from making technical modifications
      necessary to exercise the Licensed Rights, including
      technical modifications necessary to circumvent Effective
      Technological Measures. For purposes of this Public License,
      simply making modifications authorized by this Section 2(a)
      (4) never produces Adapted Material.

   5. Downstream recipients.

        a. Offer from the Licensor -- Licensed Material. Every
           recipient of the Licensed Material automatically
           receives an offer from the Licensor to exercise the
           Licensed Rights under the terms and conditions of this
           Public License.

        b. No downstream restrictions. You may not offer or impose
           any additional or different terms or conditions on, or
           apply any Effective Technological Measures to, the
           Licensed Material if doing so restricts exercise of the
           Licensed Rights by any recipient of the Licensed
           Material.

   6. No endorsement. Nothing in this Public License constitutes or
      may be construed as permission to assert or imply that You
      are, or that Your use of the Licensed Material is, connected
      with, or sponsored, endorsed, or granted official status by,
      the Licensor or others designated to receive attribution as
      provided in Section 3(a)(1)(A)(i).

b. Other rights.

   1. Moral rights, such as the right of integrity, are not
      licensed under this Public License, nor are publicity,
      privacy, and/or other similar personality rights; however, to
      the extent possible, the Licensor waives and/or agrees not to
      assert any such rights held by the Licensor to the limited
      extent necessary to allow You to exercise the Licensed
      Rights, but not otherwise.

   2. Patent and trademark rights are not licensed under this
      Public License.

   3. To the extent possible, the Licensor waives any right to
      collect royalties from You for the exercise of the Licensed
      Rights, whether directly or through a collecting society
      under any voluntary or waivable statutory or compulsory
      licensing scheme. In all other cases the Licensor expressly
      reserves any right to collect such royalties, including when
      the Licensed Material is used other than for NonCommercial
      purposes.

Section 3 -- License Conditions.

Your exercise of the Licensed Rights is expressly made subject to the following conditions.

a. Attribution.

   1. If You Share the Licensed Material (including in modified
      form), You must:

        a. retain the following if it is supplied by the Licensor
           with the Licensed Material:

             i. identification of the creator(s) of the Licensed
                Material and any others designated to receive
                attribution, in any reasonable manner requested by
                the Licensor (including by pseudonym if
                designated);

            ii. a copyright notice;

           iii. a notice that refers to this Public License;

            iv. a notice that refers to the disclaimer of
                warranties;

             v. a URI or hyperlink to the Licensed Material to the
                extent reasonably practicable;

        b. indicate if You modified the Licensed Material and
           retain an indication of any previous modifications; and

        c. indicate the Licensed Material is licensed under this
           Public License, and include the text of, or the URI or
           hyperlink to, this Public License.

   2. You may satisfy the conditions in Section 3(a)(1) in any
      reasonable manner based on the medium, means, and context in
      which You Share the Licensed Material. For example, it may be
      reasonable to satisfy the conditions by providing a URI or
      hyperlink to a resource that includes the required
      information.

   3. If requested by the Licensor, You must remove any of the
      information required by Section 3(a)(1)(A) to the extent
      reasonably practicable.

   4. If You Share Adapted Material You produce, the Adapter's
      License You apply must not prevent recipients of the Adapted
      Material from complying with this Public License.

Section 4 -- Sui Generis Database Rights.

Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:

a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;

b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and

c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.

For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.

Section 5 -- Disclaimer of Warranties and Limitation of Liability.

a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.

b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.

c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.

Section 6 -- Term and Termination.

a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.

b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:

   1. automatically as of the date the violation is cured, provided
      it is cured within 30 days of Your discovery of the
      violation; or

   2. upon express reinstatement by the Licensor.

 For the avoidance of doubt, this Section 6(b) does not affect any
 right the Licensor may have to seek remedies for Your violations
 of this Public License.

c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.

d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.

Section 7 -- Other Terms and Conditions.

a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.

b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.

Section 8 -- Interpretation.

a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.

b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.

c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.

d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.

=======================================================================

Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.

Creative Commons may be contacted at creativecommons.org.